feat: plugin_antigravity_login v1.0.0 - Google Antigravity OAuth PKCE login and project manager
Clean-room C99 node plugin. Drives the SCORPIOX CODE login CLI machine mode (--status/--start/--finish/--cancel) and the token CLI, so the repo carries no OAuth client secret and no TLS code. Reports session state, token expiry and the companion project; never returns a token. 89 offline assertions, mock CLIs for both child processes, bot theme handoff, zero dependencies, POSIX + MinGW.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-12 13:53:10
Commit2260b881
Changed files
.gitignore+16−0■■■■■
LICENSE+21−0■■■■■
Makefile+80−0■■■■■
README.md+258−0■■■■■
build.ps1+51−0■■■■■
plugin.json+16−0■■■■■
release-dist.sh+365−0■■■■■
src/bot_theme_plugin.h+129−0■■■■■
src/plugin_antigravity_login.c+1327−0■■■■■
src/ui.html+330−0■■■■■
src/ui_html.h+338−0■■■■■
tests/mock_login.sh+68−0■■■■■
tests/mock_token.sh+14−0■■■■■
tests/run.sh+426−0■■■■■
tools/gen_ui.py+105−0■■■■■
15 files+3544−0
Diff
.gitignore+16−0■■■■■
11new file mode 100644
index 0000000..acf9bd5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,16 @@
1+# build artifacts
2+/plugin_antigravity_login
3+/plugin_antigravity_login.exe
4+/plugin_antigravity_login.musl
5+/plugin_antigravity_login.arm64
6+/plugin_antigravity_login.macos-arm64
7+/plugin_antigravity_login.macos-x86_64
8+bin/
9+
10+# test scratch
11+*.tmp
12+/tests/fixtures-out/
13+
14+# python tooling
15+__pycache__/
16+*.pyc
LICENSE+21−0■■■■■
11new file mode 100644
index 0000000..ef80120
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+80−0■■■■■
11new file mode 100644
index 0000000..7f204b4
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,80 @@
1+# plugin_antigravity_login - SCORPIOX BOT open-source Google Antigravity login for your node
2+#
3+# Targets:
4+# make native build -> ./plugin_antigravity_login
5+# make musl static musl x86_64 -> ./plugin_antigravity_login.musl
6+# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_antigravity_login.arm64
7+# make win64 MinGW-w64 static -> ./plugin_antigravity_login.exe
8+# make macos Apple clang -> ./plugin_antigravity_login (run this on macOS)
9+# make ui regenerate src/ui_html.h from src/ui.html
10+# make test build + run tests/run.sh
11+# make e2e build + run tests/e2e.py (Playwright)
12+# make clean
13+
14+CC ?= cc
15+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src
16+MUSL_CC ?= musl-gcc
17+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static
18+ARM_CC ?= aarch64-linux-gnu-gcc
19+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static
20+WIN_CC ?= x86_64-w64-mingw32-gcc
21+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static
22+SRC := src/plugin_antigravity_login.c
23+UI_SRC := src/ui.html
24+UI_HDR := src/ui_html.h
25+BIN := plugin_antigravity_login
26+EXE := plugin_antigravity_login.exe
27+
28+.PHONY: all native musl arm64 win64 macos ui test e2e clean help
29+
30+all: native
31+
32+$(UI_HDR): $(UI_SRC) tools/gen_ui.py
33+ @echo "==> regenerating $(UI_HDR)"
34+ python3 tools/gen_ui.py
35+
36+ui: $(UI_HDR)
37+
38+native: $(BIN)
39+
40+$(BIN): $(SRC) $(UI_HDR)
41+ @echo "==> native build ($(CC))"
42+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
43+
44+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
45+musl: $(SRC) $(UI_HDR)
46+ @echo "==> static musl build ($(MUSL_CC))"
47+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
48+
49+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
50+arm64: $(SRC) $(UI_HDR)
51+ @echo "==> static arm64 build ($(ARM_CC))"
52+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
53+
54+# Native Win64 static PE - runs on any Windows 10/11 x64 node
55+win64: $(SRC) $(UI_HDR)
56+ @echo "==> MinGW-w64 build ($(WIN_CC))"
57+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
58+
59+# Apple clang build (run this on macOS)
60+macos: $(SRC) $(UI_HDR)
61+ @echo "==> Apple clang build"
62+ clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o $(BIN) $(SRC)
63+
64+install: $(BIN)
65+ @dest="$${HOME}/.scorpiox/plugins"; [ -d /workspace ] && dest="/workspace/.scorpiox/plugins"; \
66+ mkdir -p "$$dest" && cp $(BIN) "$$dest/$(BIN)" && chmod 0755 "$$dest/$(BIN)" && \
67+ echo "==> installed $$dest/$(BIN)"
68+
69+test: $(BIN)
70+ sh tests/run.sh
71+
72+e2e: $(BIN)
73+ python3 tests/e2e.py
74+
75+clean:
76+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64
77+ rm -rf tests/__pycache__
78+
79+help:
80+ @sed -n '2,16p' $(MAKEFILE_LIST)
README.md+258−0■■■■■
11new file mode 100644
index 0000000..3c3161a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,258 @@
1+# plugin_antigravity_login — Google Antigravity login for SCORPIOX BOT
2+
3+`plugin_antigravity_login` is a **zero-dependency C99 node plugin** for
4+[SCORPIOX BOT](https://bot.scorpiox.net). It drives a Google **OAuth 2.0 PKCE**
5+login for **Google Antigravity** on the node it runs on: start the flow, paste
6+the authorization code, run the exchange and the Google Cloud companion‑project
7+discovery, then read the session state, token expiry and project — and refresh
8+the token on demand.
9+
10+* `--meta` → `{"name":"google","desc":"Google login"}`
11+* `--version` → `plugin_antigravity_login 1.0.0`
12+* Catalog slug `antigravity-login`, category `devtools`
13+* Public source: <https://plugingit.scorpiox.net/scorpiox-bot-plugin-antigravity-login.git>
14+* Prebuilt binaries: <https://dist.scorpiox.net/bot-plugins/antigravity-login/>
15+
16+Two ways to consume it, both first-class:
17+
18+| Track | What you get |
19+|---|---|
20+| **Source** | `git clone` the repo above, read one C file, compile it on your node in a second, install to `~/.scorpiox/plugins/`. No dependency, no build system beyond `cc`. |
21+| **Prebuilt** | a static binary per platform at `dist.scorpiox.net/bot-plugins/antigravity-login/1.0.0/`, with `manifest.json`, `SHA256SUMS` and the exact `source.tar.gz`. |
22+
23+---
24+
25+## Why this plugin has no TLS code and no client secret
26+
27+A PKCE code exchange is an HTTPS POST that carries an OAuth client identity. A
28+public, clean-room repository cannot ship a client secret, and a plugin that
29+re-implemented TLS would be a liability on every node.
30+
31+So this plugin does what SCORPIOX CODE already designed its login tools for: it
32+**drives the machine-mode CLI** that ships with the product.
33+
34+```
35+plugin_antigravity_login --popen--> scorpiox-antigravity-login --status
36+ --start
37+ --finish <code>
38+ --cancel
39+ --popen--> scorpiox-google-fetchtoken -local
40+```
41+
42+Machine mode is the contract documented in `sx_login_machine.h`: one JSON line
43+per call, human progress on stderr/stdout before it, no TTY required. The plugin
44+takes the **last** line that starts with `{`, so the parsers are exercised
45+against the production layout rather than an invented one.
46+
47+The plugin reads (and never writes):
48+
49+| Path | What it is used for |
50+|---|---|
51+| `~/.config/google-accounts/antigravity_accounts.json` | account list + `refresh_token` **presence** |
52+| `~/.config/google-accounts/selected_account.txt` | the active Google account |
53+| `~/.claude/scorpiox-env/antigravity.txt` | `GOOGLE_PROJECT_ID`, `GOOGLE_ACCOUNT` |
54+| `~/.claude/.login-pending/antigravity-default.json` | the pending-flow marker |
55+
56+**No token is ever printed, logged or returned.** `action=status` reports
57+`has_refresh` (a boolean), `expires_at` and `expires_in_sec`. `action=refresh`
58+reports `refreshed: true` and the expiry — the access token the CLI prints is
59+read for presence and discarded, so a browser, a proxy log or a screenshot can
60+never capture a bearer token from this route. The test suite asserts that: a mock
61+token CLI prints `ya29.MOCK-ACCESS-TOKEN-MUST-NOT-LEAK` and the suite fails if the
62+string appears in any response.
63+
64+---
65+
66+## Requirements on the node
67+
68+| Platform | Needs |
69+|---|---|
70+| Linux / macOS | `scorpiox-antigravity-login` and `scorpiox-google-fetchtoken` on `PATH` (both ship with SCORPIOX CODE) |
71+| Windows | the same two binaries in `%PATH%` |
72+| any | nothing else — the plugin has **zero** library dependencies |
73+
74+If the CLIs are absent the plugin still serves the UI and answers `action=status`
75+`cli_present:false` with a clear message, so a node without SCORPIOX CODE does not
76+show a broken panel.
77+
78+---
79+
80+## Environment overrides (all optional, all for testing or relocation)
81+
82+| Variable | Effect |
83+|---|---|
84+| `ANTIGRAVITY_CREDS_PATH` | the accounts JSON. Its directory also anchors `selected_account.txt` and the profile dir, so a relocated install stays self-consistent. |
85+| `ANTIGRAVITY_ENV_DIR` | the profile directory (default `~/.claude/scorpiox-env`) |
86+| `ANTIGRAVITY_PENDING_PATH` | the pending-flow marker |
87+| `ANTIGRAVITY_LOGIN_BIN` | the login CLI (default `scorpiox-antigravity-login`) |
88+| `ANTIGRAVITY_TOKEN_BIN` | the token CLI (default `scorpiox-google-fetchtoken`) |
89+| `BOT_PASSWORD` | when set, every route except `--meta` requires it |
90+
91+---
92+
93+## API
94+
95+All actions are `GET` (or `POST` for `finish`) against the plugin route, with the
96+node password supplied as `X-Bot-Password`, `Authorization: Bearer` or `?pwd=`.
97+
98+### `?action=status` (also `?format=json`)
99+
100+```json
101+{
102+ "ok": true,
103+ "plugin": "plugin_antigravity_login",
104+ "version": "1.0.0",
105+ "logged_in": true,
106+ "email": "someone@example.com",
107+ "account": "someone@example.com",
108+ "project_id": "proj-mock-42",
109+ "profile": "antigravity",
110+ "expires_at": 1790000000,
111+ "expires_in_sec": 3599,
112+ "expired": false,
113+ "has_refresh": true,
114+ "pending": false,
115+ "cli_present": true,
116+ "credentials_path": "/root/.config/google-accounts/antigravity_accounts.json"
117+}
118+```
119+
120+`expires_at` is unix **seconds** (the CLI's millisecond value is normalised).
121+`expired` is only ever true for a session that exists.
122+
123+### `?action=start`
124+
125+```json
126+{
127+ "ok": true,
128+ "flow": "paste_code",
129+ "auth_url": "https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=...&code_challenge=...&code_challenge_method=S256&...",
130+ "expires_in": 900,
131+ "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."
132+}
133+```
134+
135+The PKCE verifier lives in the CLI's pending file (mode 0600). The plugin never
136+sees it and never needs it.
137+
138+### `?action=finish&code=...` (or a POST body `{"code":"..."}`)
139+
140+Accepts a bare code **or** the whole `https://antigravity.google/oauth-callback?...`
141+address; the `code=` value is extracted before validation. On success the
142+response is the full status object with `"state":"done"`.
143+
144+Rejected before anything runs (the code is passed to a shell, so this is a real
145+guard, not a formality):
146+
147+```json
148+{"ok":false,"error":"invalid_code","detail":"the value is not an authorization code (empty, too long, or contains shell characters)"}
149+```
150+
151+Shell metacharacters, quotes, backticks, `$`, `;`, `|`, `&`, `<`, `>` and control
152+bytes are refused; the argument is also single-quoted with the `'\''` escape, and
153+the test suite proves a `$(touch /tmp/pwned)` payload creates no file.
154+
155+### `?action=cancel`
156+
157+```json
158+{"ok": true, "state": "cancelled", "pending": false}
159+```
160+
161+### `?action=refresh`
162+
163+Runs `scorpiox-google-fetchtoken -local`, reports success and the new expiry, and
164+**drops the token**:
165+
166+```json
167+{"ok": true, "refreshed": true, "logged_in": true, "email": "...", "project_id": "...", "expires_in_sec": 3599, ...}
168+```
169+
170+Failure is structured, never a stack trace:
171+
172+```json
173+{"ok": false, "error": "refresh_failed", "detail": "the token CLI could not refresh the session; sign in again"}
174+```
175+
176+### Errors
177+
178+| Error | HTTP | Meaning |
179+|---|---|---|
180+| `invalid node password` | 401 | `BOT_PASSWORD` is set and no credential matched |
181+| `missing_code` | 400 | `finish` without a code |
182+| `invalid_code` | 400 | the value cannot be an authorization code |
183+| `unknown_action` | 404 | unrecognised `action=` |
184+| `cli_unavailable` | 200 | the login/token CLI is not on this node |
185+| `exchange` / `finish_failed` | 200 | Google rejected the code, or the account needs verification |
186+
187+---
188+
189+## The UI
190+
191+One page, no framework, no CDN, no `<script src=>`, no external request of any
192+kind. It follows the bot's theme through the standard handoff:
193+
194+1. `?theme=light|dark` → `localStorage.bot_theme` → `prefers-color-scheme`,
195+ decided **before first paint** (no flash),
196+2. then it follows `{type:'sx-theme'}` posts from the bot and asks once with
197+ `{type:'sx-theme-request'}`,
198+3. every colour is a bot token from `src/bot_theme_plugin.h` — there is no
199+ plugin-private palette.
200+
201+Layout: a status pill (`Connected` / `Expired` / `Signing in` / `Not Connected`),
202+a session card, an OAuth card with the generated link and a paste box, and a
203+companion-project card. Fluid down to 390 px and inside the Chat floating window
204+(`?embed=1` hides the theme button).
205+
206+---
207+
208+## Build
209+
210+```sh
211+make # native
212+make musl # static x86_64 musl (the universal Linux artifact)
213+make arm64 # static aarch64 (Raspberry Pi 5, ARM servers)
214+make win64 # MinGW-w64 static PE
215+make macos # Apple clang (run on macOS)
216+make test # the offline suite
217+make install # ~/.scorpiox/plugins (or /workspace/.scorpiox/plugins)
218+```
219+
220+`src/ui_html.h` is generated from `src/ui.html` by `tools/gen_ui.py`; `make ui`
221+(or the `$(UI_HDR)` dependency) regenerates it, and `tools/gen_ui.py --check`
222+fails when the header is stale.
223+
224+Windows: `powershell -ExecutionPolicy Bypass -File build.ps1`.
225+
226+---
227+
228+## Release
229+
230+```sh
231+scorpiox-cli-botplugin publish . # preferred: scan, build, upload, mirror, reindex
232+./release-dist.sh --standalone # the same, self-contained
233+```
234+
235+Both refuse to publish a repo whose **full history** contains a credential, a
236+private address or an internal hostname. The standalone script needs
237+`DIST_HOST`/`DIST_PASS` (dist) and `SSHPASS` (macOS leg) in the environment and
238+reads the plugingit write token from `/etc/scorpiox-plugingit.token` — no secret
239+is ever stored in this repository.
240+
241+---
242+
243+## Layout
244+
245+```
246+src/plugin_antigravity_login.c the whole plugin (3 modes, ~1.2k lines)
247+src/ui.html the page, readable and diffable
248+src/ui_html.h generated by tools/gen_ui.py
249+src/bot_theme_plugin.h the bot's theme tokens, vendored
250+tests/run.sh the offline suite (mock CLIs, fixtures)
251+tests/mock_login.sh stand-in for scorpiox-antigravity-login machine mode
252+tests/mock_token.sh stand-in for scorpiox-google-fetchtoken -local
253+tools/gen_ui.py ui.html -> ui_html.h
254+```
255+
256+## License
257+
258+MIT. Copyright (c) 2026 SCORPIOX INC.
build.ps1+51−0■■■■■
11new file mode 100644
index 0000000..06453df
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,51 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_antigravity_login
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_antigravity_login.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+
9+$ErrorActionPreference = "Stop"
10+$ScriptDir = $PSScriptRoot
11+Push-Location $ScriptDir
12+try {
13+ $Src = Join-Path $ScriptDir "src\plugin_antigravity_login.c"
14+ $Out = Join-Path $ScriptDir "plugin_antigravity_login.exe"
15+ $Cc = "x86_64-w64-mingw32-gcc"
16+
17+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
18+
19+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
20+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
21+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
22+ $Cc = "C:\gcc16\bin\gcc.exe"
23+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
24+ $Cc = "gcc"
25+ } else {
26+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
27+ }
28+ }
29+
30+ # Regenerate the page header so the binary always matches src/ui.html.
31+ if (Get-Command python -ErrorAction SilentlyContinue) {
32+ python tools\gen_ui.py
33+ }
34+
35+ Write-Host "==> building plugin_antigravity_login.exe with $Cc"
36+ & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src
37+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
38+
39+ if (-not (Test-Path $Out)) { throw "build produced no output" }
40+
41+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
42+ $bytes = [System.IO.File]::ReadAllBytes($Out)
43+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
44+ throw "output is not a PE executable (missing MZ header)"
45+ }
46+
47+ Write-Host "==> ok: $Out ($($bytes.Length) bytes)"
48+ Write-Host " smoke test: .\plugin_antigravity_login.exe --meta"
49+} finally {
50+ Pop-Location
51+}
plugin.json+16−0■■■■■
11new file mode 100644
index 0000000..69f71d5
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,16 @@
1+{
2+ "slug": "antigravity-login",
3+ "id": "plugin_antigravity_login",
4+ "title": "Google Antigravity Login",
5+ "summary": "Zero-dependency Google Antigravity OAuth 2.0 PKCE login and companion-project manager for your node. Starts the PKCE flow, takes the pasted authorization code, runs the exchange and the Google Cloud project discovery through the node's own login CLI, then reports session state, token expiry and the companion project - and refreshes the token on demand. The plugin holds no OAuth client secret and never prints, logs or returns a token: it drives the CLI that ships with SCORPIOX CODE and reads only the credential and profile files that CLI writes.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "capabilities": [
9+ "spawn_login_cli",
10+ "read_credentials_metadata",
11+ "network_via_login_cli"
12+ ],
13+ "trust_notice": "Executes native C code on your node. It runs scorpiox-antigravity-login and scorpiox-google-fetchtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to Google over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only ~/.config/google-accounts/antigravity_accounts.json, selected_account.txt, ~/.claude/.login-pending/ and ~/.claude/scorpiox-env/antigravity.txt, and every response reports token presence and expiry only - never a token value.",
14+ "author": "SCORPIOX INC",
15+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-antigravity-login"
16+}
release-dist.sh+365−0■■■■■
11new file mode 100755
index 0000000..5c9b2fb
--- /dev/null
+++ b/release-dist.sh
@@ -0,0 +1,365 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_antigravity_login to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+# ./release-dist.sh --standalone # use this script even if the CLI is installed
27+# # (needed for plugins that link extra Win32 libs,
28+# # which the CLI's fixed link line cannot express)
29+
30+set -euo pipefail
31+
32+SLUG="antigravity-login"
33+ID="plugin_antigravity_login"
34+VERSION="1.0.0"
35+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --standalone) STANDALONE=1 ;;
47+ --dry-run) DRY_RUN=1 ;;
48+ --no-macos) DO_MACOS=0 ;;
49+ --no-mirror) DO_MIRROR=0 ;;
50+ -h|--help) sed -n '2,32p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition - otherwise this file's own detector patterns (and the
90+# test suite's identical checks) read as findings in every historical revision of
91+# them. A real secret on any other line still hits.
92+git log -p --all 2>/dev/null \
93+ | grep -v '^Author: ' \
94+ | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \
95+ > "$SCAN_TMP" || : > "$SCAN_TMP"
96+HITS=0
97+scan() { # scan <label> <regex>
98+ local out
99+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
100+ if [ -n "$out" ]; then
101+ printf ' \033[31mHIT\033[0m %s\n' "$1"
102+ printf '%s\n' "$out" | sed 's/^/ /'
103+ HITS=$((HITS + 1))
104+ else
105+ printf ' ok %s\n' "$1"
106+ fi
107+}
108+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
109+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
110+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
111+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
112+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
113+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
114+scan "hard-coded ssh password" 'sshpass -p [^"$]'
115+P_ROOT="/codebases"
116+P_PICOBOT="${P_ROOT}/pico""bot"
117+P_WT=".work""trees"
118+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
119+scan "run-token env assignment" 'RUNNER_'"PASS="
120+if [ "$HITS" -ne 0 ]; then
121+ die "secret scan found $HITS problem(s) - refusing to publish"
122+fi
123+echo " clean: 0 hits"
124+
125+# ---------------------------------------------------------------- 2. build
126+say "2/7 build targets"
127+
128+# linux-x86_64 (glibc, native)
129+if command -v cc >/dev/null 2>&1; then
130+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed"
131+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
132+else
133+ die "no native cc found"
134+fi
135+
136+# linux-x86_64-musl (fully static - the universal Linux artifact)
137+if command -v musl-gcc >/dev/null 2>&1; then
138+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \
139+ || die "musl build failed"
140+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
141+else
142+ echo " skip linux-x86_64-musl (no musl-gcc)"
143+fi
144+
145+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
146+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
147+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \
148+ || die "arm64 build failed"
149+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
150+else
151+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
152+fi
153+
154+# windows-x86_64 (static PE)
155+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
156+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \
157+ -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
158+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
159+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
160+else
161+ echo " skip windows-x86_64 (no MinGW cross compiler)"
162+fi
163+
164+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
165+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
166+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
167+ MAC_USER="${MAC_USER:-$(whoami)}"
168+ MAC_DIR="/tmp/${ID}-mac-$$"
169+ echo " building macOS legs on $MAC_HOST"
170+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
171+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
172+ if [ -n "${MAC_PASS:-}" ]; then
173+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
174+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
175+ fi
176+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
177+ tar -czf "$STAGE/src.tgz" src
178+ if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
179+ && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then
180+ # Build straight from the uploaded file - no src/ tree on the remote.
181+ for slice in arm64 x86_64; do
182+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
183+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \
184+ 2>/dev/null; then
185+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
186+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
187+ else
188+ echo " warn: macos-$slice build failed on $MAC_HOST"
189+ fi
190+ done
191+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
192+ else
193+ echo " warn: could not upload source to $MAC_HOST"
194+ fi
195+ else
196+ echo " warn: cannot reach macOS builder $MAC_HOST"
197+ fi
198+else
199+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
200+fi
201+
202+# ---------------------------------------------------------------- 3. manifest
203+say "3/7 manifest + checksums"
204+
205+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
206+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
207+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
208+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
209+
210+target_meta() { # target_meta <key> <file> <format> <relpath>
211+ local key="$1" file="$2" fmt="$3" rel="$4"
212+ [ -f "$file" ] || return 0
213+ local sha size
214+ sha=$(sha256sum "$file" | awk '{print $1}')
215+ size=$(wc -c < "$file" | tr -d ' ')
216+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
217+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
218+}
219+
220+{
221+ printf '{\n'
222+ printf ' "slug": "%s",\n' "$SLUG"
223+ printf ' "id": "%s",\n' "$ID"
224+ printf ' "name": "google",\n'
225+ printf ' "desc": "Google login",\n'
226+ printf ' "title": "Google Antigravity Login",\n'
227+ printf ' "summary": "Zero-dependency Google Antigravity OAuth 2.0 PKCE login and companion-project manager for your node. Starts the PKCE flow, takes the pasted authorization code, runs the exchange and the Google Cloud project discovery through the node own login CLI, then reports session state, token expiry and the companion project - and refreshes the token on demand. The plugin holds no OAuth client secret and never prints, logs or returns a token: it drives the CLI that ships with SCORPIOX CODE and reads only the credential and profile files that CLI writes.",\n'
228+ printf ' "category": "devtools",\n'
229+ printf ' "version": "%s",\n' "$VERSION"
230+ printf ' "license": "MIT",\n'
231+ printf ' "trust_notice": "Executes native C code on your node. It runs scorpiox-antigravity-login and scorpiox-google-fetchtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to Google over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only the Antigravity credential file, selected_account.txt, the login-pending marker and the antigravity profile, and every response reports token presence and expiry only - never a token value.",\n'
232+ printf ' "capabilities": ["spawn_login_cli", "read_credentials_metadata", "network_via_login_cli"],\n'
233+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
234+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
235+ printf ' "git_commit": "%s",\n' "$COMMIT"
236+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
237+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
238+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
239+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
240+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
241+ printf ' "targets": {\n'
242+ first=1
243+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
244+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
245+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
246+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
247+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
248+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
249+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
250+ printf '\n }\n}\n'
251+} > "$STAGE/manifest.json"
252+
253+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
254+ || die "generated manifest.json is not valid JSON"
255+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
256+
257+# SHA256SUMS - relative paths, exactly as published
258+( cd "$STAGE"
259+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
260+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
261+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
262+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
263+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
264+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
265+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
266+ true ) > "$STAGE/SHA256SUMS"
267+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
268+
269+# ---------------------------------------------------------------- 4. stage
270+say "4/7 stage tree"
271+PKG="$STAGE/pkg"
272+mkdir -p "$PKG"
273+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
274+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
275+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
276+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
277+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
278+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
279+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
280+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
281+
282+if [ "$DRY_RUN" -eq 1 ]; then
283+ say "dry run - leaving the staging tree in $PKG"
284+ trap - EXIT
285+ exit 0
286+fi
287+
288+# ---------------------------------------------------------------- 5. upload
289+say "5/7 upload to the dist server"
290+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
291+SSH=(ssh -o StrictHostKeyChecking=no)
292+SCP=(scp -o StrictHostKeyChecking=no)
293+if [ -n "$DIST_PASS" ]; then
294+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
295+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
296+fi
297+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
298+
299+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
300+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
301+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
302+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
303+# OpenSSH 9 refuses to scp a bare "." source.
304+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
305+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
306+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
307+ || die "remote extract failed"
308+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
309+
310+# latest.json = copy of this version's manifest
311+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
312+ || die "latest.json update failed"
313+echo " updated bot-plugins/$SLUG/latest.json"
314+
315+# index.json - merge, preserving every sibling <slug>/latest.json
316+say "index.json merge"
317+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
318+import json, os, sys, glob
319+slug = sys.argv[1]
320+entries = {}
321+for p in sorted(glob.glob('*/latest.json')):
322+ s = os.path.dirname(p)
323+ try:
324+ entries[s] = json.load(open(p))
325+ except Exception:
326+ pass
327+index = {
328+ 'ok': True,
329+ 'service': 'bot-plugins-dist',
330+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
331+ 'count': len(entries),
332+ 'slugs': sorted(entries),
333+ 'plugins': [entries[k] for k in sorted(entries)],
334+}
335+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
336+os.replace('index.json.tmp', 'index.json')
337+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
338+PY" || die "index.json merge failed"
339+
340+# ---------------------------------------------------------------- 6. mirror
341+say "6/7 plugingit mirror"
342+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
343+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
344+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
345+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
346+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
347+ echo " mirrored to $PLUGINGIT_REMOTE"
348+else
349+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
350+fi
351+
352+# ---------------------------------------------------------------- 7. verify
353+say "7/7 verify"
354+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
355+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
356+if [ "$CODE" = "200" ]; then
357+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
358+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
359+else
360+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
361+fi
362+
363+printf '\n\033[1mrelease complete\033[0m\n'
364+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
365+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/bot_theme_plugin.h+129−0■■■■■
11new file mode 100644
index 0000000..0dd243b
--- /dev/null
+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/plugin_antigravity_login.c+1327−0■■■■■
11new file mode 100644
index 0000000..d1ebea0
--- /dev/null
+++ b/src/plugin_antigravity_login.c
@@ -0,0 +1,1327 @@
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.0"
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+ int expires_in_sec; /* negative when expired, 0 when unknown */
732+} status_t;
733+
734+/* Pull email / refresh_token presence out of the accounts array.
735+ *
736+ * The file is a JSON array of {email, refresh_token}. The selected account
737+ * wins; otherwise the first entry that carries a refresh token. Presence of a
738+ * refresh token is the login signal, and only its presence is recorded - the
739+ * value is never copied. */
740+static void scan_accounts(const char *json, const char *selected, status_t *st)
741+{
742+ const char *p = json;
743+ char first_email[EMAIL_SZ] = {0};
744+ int first_has = 0;
745+ int found = 0;
746+
747+ while (p && *p) {
748+ const char *open = strchr(p, '{');
749+ const char *obj;
750+ const char *end;
751+ char email[EMAIL_SZ] = {0};
752+ char rt[8] = {0};
753+ int has_rt;
754+
755+ if (!open) break;
756+ end = json_skip_value(open);
757+ if (!end || end <= open) break;
758+ /* json_find_key tracks brace depth, so it must start INSIDE the
759+ * object: passing the opening '{' makes every top-level key look
760+ * nested and the whole scan silently returns nothing. */
761+ obj = open;
762+
763+ json_str_field(obj, end, "email", email, sizeof(email));
764+ has_rt = json_str_field(obj, end, "refresh_token", rt, sizeof(rt));
765+
766+ if (!first_email[0] && email[0]) {
767+ snprintf(first_email, sizeof(first_email), "%s", email);
768+ first_has = has_rt;
769+ }
770+ if (selected && selected[0] && email[0] && strcmp(email, selected) == 0) {
771+ snprintf(st->email, sizeof(st->email), "%s", email);
772+ st->has_refresh = has_rt;
773+ found = 1;
774+ p = end;
775+ break;
776+ }
777+ p = end;
778+ }
779+
780+ if (!found) {
781+ if (first_email[0]) snprintf(st->email, sizeof(st->email), "%s", first_email);
782+ st->has_refresh = first_has;
783+ }
784+ st->logged_in = st->has_refresh;
785+}
786+
787+/* Parse GOOGLE_PROJECT_ID / GOOGLE_ACCOUNT out of the profile file. */
788+static void scan_profile(const char *text, status_t *st)
789+{
790+ const char *p = text;
791+
792+ while (p && *p) {
793+ const char *nl = strchr(p, '\n');
794+ size_t len = nl ? (size_t)(nl - p) : strlen(p);
795+ char line[FIELD_SZ];
796+ size_t i;
797+
798+ if (len > 0 && len < sizeof(line)) {
799+ memcpy(line, p, len);
800+ line[len] = '\0';
801+ trim_tail(line);
802+ for (i = 0; line[i]; i++)
803+ if (line[i] == '\r') line[i] = ' ';
804+ if (strncmp(line, "GOOGLE_PROJECT_ID=", 18) == 0 && !st->project[0]) {
805+ snprintf(st->project, sizeof(st->project), "%.*s", (int)sizeof(st->project) - 1, line + 18);
806+ } else if (strncmp(line, "GOOGLE_ACCOUNT=", 15) == 0 && !st->account[0]) {
807+ snprintf(st->account, sizeof(st->account), "%.*s", (int)sizeof(st->account) - 1, line + 15);
808+ }
809+ }
810+ if (!nl) break;
811+ p = nl + 1;
812+ }
813+}
814+
815+static void collect_status(status_t *st)
816+{
817+ char acct[PATH_SZ], sel[PATH_SZ], prof[PATH_SZ], pend[PATH_SZ];
818+ char *text;
819+ char selected[EMAIL_SZ] = {0};
820+ long long now = (long long)time(NULL);
821+
822+ memset(st, 0, sizeof(*st));
823+ st->profile[0] = '\0';
824+
825+ creds_path(acct, sizeof(acct));
826+ snprintf(st->path, sizeof(st->path), "%s", acct);
827+
828+ creds_sibling("selected_account.txt", sel, sizeof(sel));
829+ text = read_file(sel);
830+ if (text) {
831+ trim_tail(text);
832+ snprintf(selected, sizeof(selected), "%s", text);
833+ free(text);
834+ }
835+
836+ text = read_file(acct);
837+ if (text) {
838+ scan_accounts(text, selected, st);
839+ free(text);
840+ }
841+
842+ /* The profile file carries the companion project and the account email. */
843+ env_dir(prof, sizeof(prof));
844+ {
845+ char pfile[PATH_SZ + 32];
846+ char *ptext;
847+ if (strlen(prof) + 16 < sizeof(pfile))
848+ snprintf(pfile, sizeof(pfile), "%s%cantigravity.txt", prof, PATH_SEP);
849+ else
850+ snprintf(pfile, sizeof(pfile), "antigravity.txt");
851+ ptext = read_file(pfile);
852+ if (ptext) {
853+ scan_profile(ptext, st);
854+ snprintf(st->profile, sizeof(st->profile), "antigravity");
855+ free(ptext);
856+ }
857+ }
858+
859+ if (!st->email[0] && st->account[0])
860+ snprintf(st->email, sizeof(st->email), "%s", st->account);
861+ if (!st->account[0] && st->email[0])
862+ snprintf(st->account, sizeof(st->account), "%s", st->email);
863+
864+ /* Pending flow marker (the CLI writes and removes this file). */
865+ pending_path(pend, sizeof(pend));
866+ st->pending = file_exists(pend);
867+
868+ /* Ask the CLI when it is on PATH: it knows the token expiry and the exact
869+ * pending state, and it is the authority on logged_in. The plugin never
870+ * becomes the source of truth about a Google session. */
871+ {
872+ buf_t out;
873+ buf_init(&out);
874+ if (run_capture(login_bin(), "--status", &out) > 0) {
875+ const char *j = last_json_line(&out);
876+ if (j) {
877+ const char *end = j + strlen(j);
878+ char identity[EMAIL_SZ] = {0};
879+ long long exp = 0;
880+
881+ st->cli_present = 1;
882+ json_str_field(j, end, "identity", identity, sizeof(identity));
883+ json_str_field(j, end, "path", st->path, sizeof(st->path));
884+ /* The CLI is authoritative, but never a downgrade: if the
885+ * credential file on disk carries a refresh token, the node IS
886+ * signed in and an older CLI build that answers logged_in:false
887+ * must not paint a green session grey. */
888+ if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1;
889+ if (json_bool_field(j, end, "has_refresh", 0)) { st->has_refresh = 1; st->logged_in = 1; }
890+ /* pending: the marker file is the authority (it is created by
891+ * --start and removed by --finish/--cancel), so a CLI answer is
892+ * only allowed to ADD a pending state, never to clear one. */
893+ if (json_bool_field(j, end, "pending", 0)) st->pending = 1;
894+ exp = json_num_field(j, end, "expires_at");
895+ if (exp > 0 && exp < 100000000000LL) exp *= 1000; /* seconds -> ms */
896+ if (exp > 0) st->expires_at = exp / 1000;
897+ if (identity[0] && !st->email[0])
898+ snprintf(st->email, sizeof(st->email), "%s", identity);
899+ if (identity[0] && !st->account[0])
900+ snprintf(st->account, sizeof(st->account), "%s", identity);
901+ }
902+ }
903+ buf_free(&out);
904+ }
905+
906+ if (st->expires_at > 0) {
907+ st->expires_in_sec = (int)(st->expires_at - now);
908+ st->expired = st->expires_at <= now;
909+ }
910+ if (!st->logged_in) {
911+ st->expired = 0;
912+ st->expires_in_sec = 0;
913+ }
914+}
915+
916+/* One status object. Shared by every action's response so the UI can always
917+ * re-render from the same shape. */
918+static void emit_status(buf_t *b, const status_t *st)
919+{
920+ buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false");
921+ buf_adds(b, "\"email\":");
922+ buf_json(b, st->email);
923+ buf_addf(b, ",\"account\":");
924+ buf_json(b, st->account);
925+ buf_addf(b, ",\"project_id\":");
926+ buf_json(b, st->project);
927+ buf_addf(b, ",\"profile\":");
928+ buf_json(b, st->profile);
929+ buf_addf(b, ",\"expires_at\":%lld", st->expires_at);
930+ buf_addf(b, ",\"expires_in_sec\":%d", st->expires_in_sec);
931+ buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
932+ buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
933+ buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
934+ buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false");
935+ buf_addf(b, ",\"credentials_path\":");
936+ buf_json(b, st->path);
937+}
938+
939+/* ------------------------------------------------------------------ */
940+/* Actions */
941+/* ------------------------------------------------------------------ */
942+
943+static void json_headers(void)
944+{
945+ fputs("Content-Type: application/json; charset=utf-8\r\n"
946+ "Cache-Control: no-store\r\n"
947+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
948+}
949+
950+static void emit_error(int code, const char *status, const char *err, const char *detail)
951+{
952+ buf_t b;
953+
954+ buf_init(&b);
955+ buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
956+ "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
957+ code, status);
958+ buf_addf(&b, "{\"ok\":false,\"error\":");
959+ buf_json(&b, err);
960+ if (detail && *detail) {
961+ buf_addf(&b, ",\"detail\":");
962+ buf_json(&b, detail);
963+ }
964+ buf_addf(&b, "}\n");
965+ fputs(buf_str(&b), stdout);
966+ buf_free(&b);
967+}
968+
969+static int action_status(void)
970+{
971+ status_t st;
972+ buf_t b;
973+
974+ collect_status(&st);
975+ buf_init(&b);
976+ buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",");
977+ emit_status(&b, &st);
978+ buf_adds(&b, "}\n");
979+ json_headers();
980+ fputs(buf_str(&b), stdout);
981+ buf_free(&b);
982+ return 0;
983+}
984+
985+static int action_start(void)
986+{
987+ buf_t out, b;
988+ const char *j;
989+ char auth_url[CMD_SZ] = {0};
990+ char flow[64] = {0};
991+ char hint[512] = {0};
992+ long long expires_in = 0;
993+
994+ buf_init(&out);
995+ if (run_capture(login_bin(), "--start", &out) <= 0) {
996+ buf_free(&out);
997+ emit_error(200, "OK", "cli_unavailable",
998+ "the login CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_LOGIN_BIN");
999+ return 1;
1000+ }
1001+ j = last_json_line(&out);
1002+ if (!j) {
1003+ buf_free(&out);
1004+ emit_error(200, "OK", "start_failed", buf_str(&out));
1005+ return 1;
1006+ }
1007+ {
1008+ const char *end = j + strlen(j);
1009+ json_str_field(j, end, "auth_url", auth_url, sizeof(auth_url));
1010+ json_str_field(j, end, "flow", flow, sizeof(flow));
1011+ json_str_field(j, end, "hint", hint, sizeof(hint));
1012+ expires_in = json_num_field(j, end, "expires_in");
1013+ if (!json_bool_field(j, end, "ok", 1) || !auth_url[0]) {
1014+ char detail[FIELD_SZ] = {0};
1015+ json_str_field(j, end, "error", detail, sizeof(detail));
1016+ buf_free(&out);
1017+ emit_error(200, "OK", detail[0] ? detail : "start_failed", "the login CLI did not return an authorization URL");
1018+ return 1;
1019+ }
1020+ }
1021+ buf_free(&out);
1022+
1023+ buf_init(&b);
1024+ buf_adds(&b, "{\"ok\":true,\"flow\":");
1025+ buf_json(&b, flow[0] ? flow : "paste_code");
1026+ buf_adds(&b, ",\"auth_url\":");
1027+ buf_json(&b, auth_url);
1028+ buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : 900);
1029+ buf_adds(&b, ",\"hint\":");
1030+ buf_json(&b, hint[0] ? hint
1031+ : "Sign in with Google and approve. The browser lands on antigravity.google - copy the whole address (or just the code) and paste it here.");
1032+ buf_adds(&b, "}\n");
1033+ json_headers();
1034+ fputs(buf_str(&b), stdout);
1035+ buf_free(&b);
1036+ return 0;
1037+}
1038+
1039+/* Reject anything that cannot be an authorization code. The value is passed
1040+ * to a shell, so this is the second line of defence behind shell_quote_into. */
1041+static int valid_code(const char *code)
1042+{
1043+ size_t n, i;
1044+ if (!code || !(n = strlen(code)) || n > CODE_MAX) return 0;
1045+ for (i = 0; i < n; i++) {
1046+ unsigned char c = (unsigned char)code[i];
1047+ if (c < 0x20 || c == 0x7f || c == '\'' || c == '"' || c == '\\' || c == ';' ||
1048+ c == '`' || c == '$' || c == '|' || c == '&' || c == '<' || c == '>' ||
1049+ c == '\n' || c == '\r')
1050+ return 0;
1051+ }
1052+ return 1;
1053+}
1054+
1055+static int action_finish(const char *raw_code)
1056+{
1057+ char code[CODE_MAX];
1058+ char qcode[CODE_MAX + 64];
1059+ buf_t out, b;
1060+ const char *j;
1061+
1062+ if (!raw_code) {
1063+ emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=...");
1064+ return 1;
1065+ }
1066+ snprintf(code, sizeof(code), "%s", raw_code);
1067+ url_decode(code);
1068+ trim_tail(code);
1069+
1070+ /* The user usually pastes the whole redirect address, which is what the
1071+ * login CLI expects too (its lm_clean_code does the same extraction). Pull
1072+ * out code= before validating, so a legitimate URL is not rejected for
1073+ * carrying a state= parameter alongside it. */
1074+ {
1075+ char *c = strstr(code, "code=");
1076+ if (c) {
1077+ char extracted[CODE_MAX];
1078+ size_t i = 0;
1079+ c += 5;
1080+ while (*c && *c != '&' && *c != '#' && i + 1 < sizeof(extracted))
1081+ extracted[i++] = *c++;
1082+ extracted[i] = '\0';
1083+ if (i > 0) snprintf(code, sizeof(code), "%s", extracted);
1084+ }
1085+ }
1086+ if (!valid_code(code)) {
1087+ emit_error(400, "Bad Request", "invalid_code",
1088+ "the value is not an authorization code (empty, too long, or contains shell characters)");
1089+ return 1;
1090+ }
1091+
1092+ shell_quote_into(code, qcode, sizeof(qcode));
1093+ {
1094+ char args[CODE_MAX + 128];
1095+ snprintf(args, sizeof(args), "--finish %s", qcode);
1096+ buf_init(&out);
1097+ if (run_capture(login_bin(), args, &out) <= 0) {
1098+ buf_free(&out);
1099+ emit_error(200, "OK", "cli_unavailable",
1100+ "the login CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_LOGIN_BIN");
1101+ return 1;
1102+ }
1103+ }
1104+
1105+ j = last_json_line(&out);
1106+ if (!j) {
1107+ buf_free(&out);
1108+ emit_error(200, "OK", "finish_failed", "the login CLI returned no JSON");
1109+ return 1;
1110+ }
1111+ if (!json_bool_field(j, (const char *)(j + strlen(j)), "ok", 0)) {
1112+ char detail[FIELD_SZ] = {0};
1113+ const char *end = j + strlen(j);
1114+ json_str_field(j, end, "error", detail, sizeof(detail));
1115+ buf_free(&out);
1116+ emit_error(200, "OK", detail[0] ? detail : "finish_failed",
1117+ "Google rejected the code, or the account needs verification in a browser");
1118+ return 1;
1119+ }
1120+ buf_free(&out);
1121+
1122+ /* Success: re-read everything so the caller gets the full new state. */
1123+ {
1124+ status_t st;
1125+ collect_status(&st);
1126+ buf_init(&b);
1127+ buf_adds(&b, "{\"ok\":true,\"state\":\"done\",");
1128+ emit_status(&b, &st);
1129+ buf_adds(&b, "}\n");
1130+ json_headers();
1131+ fputs(buf_str(&b), stdout);
1132+ buf_free(&b);
1133+ }
1134+ return 0;
1135+}
1136+
1137+static int action_cancel(void)
1138+{
1139+ buf_t out, b;
1140+
1141+ buf_init(&out);
1142+ run_capture(login_bin(), "--cancel", &out);
1143+ buf_free(&out);
1144+
1145+ buf_init(&b);
1146+ buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n");
1147+ json_headers();
1148+ fputs(buf_str(&b), stdout);
1149+ buf_free(&b);
1150+ return 0;
1151+}
1152+
1153+/* Refresh: the token CLI performs the refresh-token grant and prints the
1154+ * access token. We deliberately keep only ok/project and drop the token, so a
1155+ * browser (or a proxy log) can never capture a bearer token from this route. */
1156+static int action_refresh(void)
1157+{
1158+ buf_t out, b;
1159+ const char *j;
1160+ char project[PROJ_SZ] = {0};
1161+ char err[FIELD_SZ] = {0};
1162+ int ok = 0;
1163+
1164+ buf_init(&out);
1165+ if (run_capture(token_bin(), "-local", &out) <= 0) {
1166+ buf_free(&out);
1167+ emit_error(200, "OK", "cli_unavailable",
1168+ "the token CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_TOKEN_BIN");
1169+ return 1;
1170+ }
1171+ j = last_json_line(&out);
1172+ if (j) {
1173+ const char *end = j + strlen(j);
1174+ char tok[8] = {0};
1175+ ok = json_bool_field(j, end, "ok", 0);
1176+ json_str_field(j, end, "project_id", project, sizeof(project));
1177+ (void)json_str_field(j, end, "access_token", tok, sizeof(tok)); /* presence only */
1178+ if (!ok) json_str_field(j, end, "error", err, sizeof(err));
1179+ }
1180+ buf_free(&out);
1181+
1182+ if (!ok) {
1183+ buf_init(&b);
1184+ buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":");
1185+ buf_json(&b, err[0] ? err : "the token CLI could not refresh the session; sign in again");
1186+ buf_adds(&b, "}\n");
1187+ json_headers();
1188+ fputs(buf_str(&b), stdout);
1189+ buf_free(&b);
1190+ return 1;
1191+ }
1192+
1193+ {
1194+ status_t st;
1195+ collect_status(&st);
1196+ if (project[0]) snprintf(st.project, sizeof(st.project), "%s", project);
1197+ buf_init(&b);
1198+ buf_adds(&b, "{\"ok\":true,\"refreshed\":true,");
1199+ emit_status(&b, &st);
1200+ buf_adds(&b, "}\n");
1201+ json_headers();
1202+ fputs(buf_str(&b), stdout);
1203+ buf_free(&b);
1204+ }
1205+ return 0;
1206+}
1207+
1208+/* ------------------------------------------------------------------ */
1209+/* HTML emission */
1210+/* ------------------------------------------------------------------ */
1211+
1212+/* Expand the two placeholders gen_ui.py leaves in UI_HTML. Keeping this split
1213+ * means the palette lives in exactly one place (bot_theme_plugin.h) and the
1214+ * page can never drift away from the bot's own theme. */
1215+static void emit_ui(void)
1216+{
1217+ const char *p = UI_HTML;
1218+
1219+ while (*p) {
1220+ if (*p == '\001') {
1221+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1222+ p++;
1223+ } else if (*p == '\002') {
1224+ fputs(SX_BOT_THEME_HANDOFF, stdout);
1225+ p++;
1226+ } else {
1227+ putchar(*p++);
1228+ }
1229+ }
1230+}
1231+
1232+/* ------------------------------------------------------------------ */
1233+/* main */
1234+/* ------------------------------------------------------------------ */
1235+
1236+int main(int argc, char **argv)
1237+{
1238+ const char *qs;
1239+ char action[64] = {0};
1240+
1241+ /* 1. Discovery metadata. Must stay unauthenticated. */
1242+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1243+ puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1244+ return 0;
1245+ }
1246+ if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1247+ puts(PLUGIN_ID " " PLUGIN_VER);
1248+ return 0;
1249+ }
1250+
1251+ require_node_auth();
1252+
1253+ qs = getenv("QUERY_STRING");
1254+ if (!qs) qs = "";
1255+
1256+ /* 2. JSON API mode. `format=json` alone means "status", which is what a
1257+ * dashboard polls. */
1258+ if (query_has(qs, "action") || query_has(qs, "format")) {
1259+ char fmt[32] = {0};
1260+ char code[CODE_MAX] = {0};
1261+
1262+ get_query_val(qs, "action", action, sizeof(action));
1263+ get_query_val(qs, "format", fmt, sizeof(fmt));
1264+
1265+ if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status");
1266+
1267+ if (strcmp(action, "status") == 0 || !action[0]) return action_status();
1268+ if (strcmp(action, "start") == 0) return action_start();
1269+ if (strcmp(action, "cancel") == 0) return action_cancel();
1270+ if (strcmp(action, "refresh") == 0) return action_refresh();
1271+ if (strcmp(action, "finish") == 0) {
1272+ if (!get_query_val(qs, "code", code, sizeof(code))) {
1273+ char body[OUT_MAX];
1274+ size_t len = 0;
1275+
1276+ /* POST bodies carry the code too (a long code is easier to
1277+ * send as a body). Guard on CONTENT_LENGTH so an empty
1278+ * inherited stdin never blocks. */
1279+ {
1280+ const char *cl = getenv("CONTENT_LENGTH");
1281+ long n = (cl && *cl) ? atol(cl) : 0;
1282+ if (n > 0 && n < (long)sizeof(body)) {
1283+ len = fread(body, 1, (size_t)n, stdin);
1284+ body[len] = '\0';
1285+ {
1286+ char *p = strstr(body, "\"code\"");
1287+ if (p) {
1288+ p = strchr(p, ':');
1289+ if (p) {
1290+ p++;
1291+ while (*p == ' ' || *p == '\t' || *p == '"') p++;
1292+ {
1293+ size_t i = 0;
1294+ while (*p && *p != '"' && *p != ',' && *p != '}' &&
1295+ i + 1 < sizeof(code)) code[i++] = *p++;
1296+ code[i] = '\0';
1297+ }
1298+ }
1299+ }
1300+ }
1301+ }
1302+ }
1303+ if (!code[0]) {
1304+ emit_error(400, "Bad Request", "missing_code",
1305+ "pass the authorization code as &code=...");
1306+ return 1;
1307+ }
1308+ }
1309+ return action_finish(code);
1310+ }
1311+ emit_error(404, "Not Found", "unknown_action", action);
1312+ return 1;
1313+ }
1314+
1315+ /* 3. HTML UI. The page and its theme arrive from the generated header.
1316+ * UI_HTML carries two control bytes: 0x01 is the theme block (<style>
1317+ * with the bot tokens) and 0x02 is the handoff script before </body>. */
1318+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1319+ "Cache-Control: no-store\r\n"
1320+ "X-Content-Type-Options: nosniff\r\n"
1321+ "Referrer-Policy: no-referrer\r\n"
1322+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1323+ "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1324+ "base-uri 'none'; form-action 'none'; frame-ancestors *\r\n\r\n", stdout);
1325+ emit_ui();
1326+ return 0;
1327+}
src/ui.html+330−0■■■■■
11new file mode 100644
index 0000000..d310cf7
--- /dev/null
+++ b/src/ui.html
@@ -0,0 +1,330 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>google</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0;min-height:100%}
9+body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;
10+ line-height:1.5;-webkit-font-smoothing:antialiased}
11+#app{max-width:840px;margin:0 auto;padding:16px 16px 40px}
12+.hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}
13+.hd .grow{flex:1 1 auto;min-width:0}
14+.hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}
15+.hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;
16+ overflow:hidden;text-overflow:ellipsis}
17+.pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;
18+ padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);
19+ border:1px solid var(--line);white-space:nowrap}
20+.pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}
21+.pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}
22+.pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}
23+.pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}
24+.pill.warn .dot{background:var(--orange)}
25+.pill.off .dot{background:var(--gray)}
26+.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;
27+ padding:16px;margin-bottom:12px}
28+.card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;
29+ text-transform:uppercase;color:var(--text-2)}
30+.card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}
31+.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
32+.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;
33+ font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;
34+ transition:transform .12s var(--ease),opacity .12s}
35+.btn:active{transform:scale(.98)}
36+.btn:disabled{opacity:.5;cursor:default}
37+.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}
38+.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}
39+.btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}
40+a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}
41+.kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}
42+.kv .k{color:var(--text-2);font-size:12px}
43+.kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}
44+.kv .v.plain{font-family:var(--font);font-size:13px}
45+.hint{font-size:12px;color:var(--text-2);margin:10px 0 0}
46+.step{display:none}
47+.step.on{display:block}
48+.authurl{margin:10px 0;padding:10px 11px;border-radius:10px;background:var(--code-bg);
49+ border:1px solid var(--line);font-family:var(--mono);font-size:11.5px;
50+ word-break:break-all;max-height:120px;overflow:auto;color:var(--text)}
51+textarea{width:100%;min-height:82px;resize:vertical;border-radius:10px;padding:10px 11px;
52+ border:1px solid var(--line);background:var(--input-bg);color:var(--text);
53+ font-family:var(--mono);font-size:12px;line-height:1.45}
54+textarea:focus{outline:2px solid var(--blue);outline-offset:-1px}
55+.note{display:none;margin-top:10px;padding:9px 11px;border-radius:10px;font-size:12.5px;
56+ border:1px solid var(--line);background:var(--surface-2)}
57+.note.show{display:block}
58+.note.err{color:var(--red);border-color:rgba(255,69,58,.35)}
59+.note.ok{color:var(--green);border-color:rgba(48,209,88,.35)}
60+.empty{padding:10px 0;color:var(--text-2);font-size:12.5px}
61+.toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;
62+ pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);
63+ color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;
64+ box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);
65+ z-index:9;max-width:calc(100vw - 32px)}
66+.toast.show{opacity:1;transform:translate(-50%,0)}
67+#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);
68+ border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;
69+ font-family:inherit}
70+@media (max-width:520px){
71+ #app{padding:12px 12px 32px}
72+ .kv{grid-template-columns:1fr;gap:2px 0}
73+ .kv .k{margin-top:8px}
74+ .card{padding:13px;border-radius:12px}
75+}
76+</style>
77+</head>
78+<body>
79+<div id="app">
80+ <div class="hd">
81+ <div class="grow">
82+ <h1>Google Antigravity</h1>
83+ <div class="sub" id="sub">OAuth 2.0 PKCE login on this node</div>
84+ </div>
85+ <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span>
86+ <button id="themeToggle" class="embed-hide" type="button">Theme</button>
87+ </div>
88+
89+ <div class="card">
90+ <h2>Session</h2>
91+ <p class="lead" id="sessionLead">Reading the local Antigravity credentials.</p>
92+ <div class="kv" id="session"></div>
93+ <div class="row" style="margin-top:14px">
94+ <button class="btn ghost" id="btnRefresh" type="button">Refresh Token Now</button>
95+ <button class="btn ghost" id="btnReload" type="button">Reload</button>
96+ </div>
97+ <div class="note" id="refreshNote"></div>
98+ </div>
99+
100+ <div class="card">
101+ <h2>OAuth login</h2>
102+ <p class="lead">Sign in with Google. Nothing leaves this node: the login CLI performs the
103+ exchange and writes the credential file here.</p>
104+
105+ <div class="step on" id="step1">
106+ <button class="btn" id="btnStart" type="button">Start Google Login</button>
107+ <p class="hint">This generates a PKCE challenge and an authorization link. No token is
108+ created until you paste the code back.</p>
109+ </div>
110+
111+ <div class="step" id="step2">
112+ <div class="row">
113+ <a class="btn" id="linkOpen" href="#" target="_blank" rel="noopener noreferrer">Open Google Sign-in</a>
114+ <button class="btn ghost" id="btnCopy" type="button">Copy link</button>
115+ <button class="btn ghost" id="btnCancel" type="button">Cancel</button>
116+ </div>
117+ <div class="authurl" id="authUrl"></div>
118+ <p class="hint" id="flowHint">After approving, the browser lands on antigravity.google. Copy the
119+ whole address (or just the <span style="font-family:var(--mono)">code=</span> value) and paste it below.</p>
120+ <textarea id="codeInput" spellcheck="false" autocomplete="off"
121+ placeholder="Paste the authorization code or the full redirect URL"></textarea>
122+ <div class="row" style="margin-top:10px">
123+ <button class="btn" id="btnFinish" type="button">Authorize &amp; Discover Project</button>
124+ </div>
125+ <div class="note" id="loginNote"></div>
126+ </div>
127+ </div>
128+
129+ <div class="card">
130+ <h2>Companion project</h2>
131+ <p class="lead">The Google Cloud project the Antigravity session bills against.</p>
132+ <div class="kv" id="project"></div>
133+ </div>
134+</div>
135+
136+<div class="toast" id="toast"></div>
137+
138+<script>
139+var q=new URLSearchParams(location.search);
140+var node=q.get('node')||'';
141+var sid=q.get('id')||'';
142+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
143+ localStorage.getItem('bot_active_pwd')||'';
144+
145+/* Two call routes. Getting this wrong is the most common plugin bug:
146+ * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)
147+ * -> call the hub proxy back: /plugins?plugin=plugin_antigravity_login&action=..
148+ * opened directly on the node
149+ * -> the plugin itself is the route: /plugin_antigravity_login?action=..
150+ * Calling /plugins?plugin= on the node returns the discovery list, not us. */
151+var HUB=q.get('plugin')||'';
152+function url(action,extra){
153+ return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_antigravity_login')+
154+ '?action='+encodeURIComponent(action)+
155+ (extra?('&'+extra):'')+
156+ (node?'&node='+encodeURIComponent(node):'')+
157+ (sid?'&id='+encodeURIComponent(sid):'')+
158+ (pwd?'&pwd='+encodeURIComponent(pwd):'');
159+}
160+function hdr(){
161+ var h={};
162+ if(pwd)h['X-Bot-Password']=pwd;
163+ return h;
164+}
165+function api(action,extra){
166+ return fetch(url(action,extra),{headers:hdr()}).then(function(r){
167+ return r.json().catch(function(){return {ok:false,error:'bad response'};});
168+ });
169+}
170+
171+var $=function(id){return document.getElementById(id);};
172+function toast(msg){
173+ var t=$('toast');t.textContent=msg;t.classList.add('show');
174+ clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);
175+}
176+function note(el,msg,kind){
177+ el.textContent=msg||'';
178+ el.className='note'+(msg?' show '+(kind||''):'');
179+}
180+function kv(el,rows){
181+ el.innerHTML='';
182+ rows.forEach(function(r){
183+ var a=document.createElement('div');a.className='k';a.textContent=r[0];
184+ var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');
185+ b.textContent=r[1];el.appendChild(a);el.appendChild(b);
186+ });
187+}
188+function fmtExpiry(sec){
189+ if(!sec&&sec!==0)return '-';
190+ if(sec<=0)return 'expired';
191+ if(sec<90)return sec+'s';
192+ if(sec<5400)return Math.round(sec/60)+' min';
193+ if(sec<172800)return Math.round(sec/3600)+' h';
194+ return Math.round(sec/86400)+' d';
195+}
196+function setPill(st){
197+ var p=$('pill'),t=$('pillText');
198+ if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}
199+ else if(st.logged_in){p.className='pill ok';t.textContent='Connected';}
200+ else if(st.pending){p.className='pill warn';t.textContent='Signing in';}
201+ else {p.className='pill off';t.textContent='Not Connected';}
202+}
203+function render(st){
204+ setPill(st);
205+ $('sub').textContent=st.email?st.email:'OAuth 2.0 PKCE login on this node';
206+
207+ if(st.logged_in){
208+ $('sessionLead').textContent=st.expired
209+ ? 'The session is present but its access token has expired. Use Refresh Token Now.'
210+ : 'This node holds a Google Antigravity session.';
211+ }else{
212+ $('sessionLead').textContent='No Google session on this node yet. Start a login below.';
213+ }
214+ kv($('session'),[
215+ ['Account', st.email||'-', true],
216+ ['Logged in', st.logged_in?'yes':'no', true],
217+ ['Refresh token', st.has_refresh?'stored':'none', true],
218+ ['Token expires', st.logged_in?fmtExpiry(st.expires_in_sec):'-', true],
219+ ['Login pending', st.pending?'yes':'no', true],
220+ ['Login CLI', st.cli_present?'found':'not found', true],
221+ ['Credentials', st.credentials_path||'-']
222+ ]);
223+ kv($('project'),[
224+ ['Project ID', st.project_id||'(consumer shared project)', !st.project_id],
225+ ['Profile', st.profile||'-', true],
226+ ['Provider', 'google (Antigravity)', true]
227+ ]);
228+
229+ if(st.pending){$('step1').classList.remove('on');$('step2').classList.add('on');}
230+}
231+function load(){
232+ return api('status').then(function(d){
233+ if(d&&d.ok)render(d);
234+ else toast((d&&d.error)||'status failed');
235+ }).catch(function(e){toast('Status failed: '+e.message);});
236+}
237+
238+var authUrl='';
239+function start(){
240+ var b=$('btnStart');
241+ b.disabled=true;b.textContent='Starting...';
242+ api('start').then(function(d){
243+ b.disabled=false;b.textContent='Start Google Login';
244+ if(!d||!d.ok){toast((d&&(d.detail||d.error))||'start failed');return;}
245+ authUrl=d.auth_url||'';
246+ $('authUrl').textContent=authUrl;
247+ $('linkOpen').setAttribute('href',authUrl);
248+ if(d.hint)$('flowHint').textContent=d.hint;
249+ $('step1').classList.remove('on');
250+ $('step2').classList.add('on');
251+ $('codeInput').focus();
252+ }).catch(function(e){
253+ b.disabled=false;b.textContent='Start Google Login';
254+ toast('Start failed: '+e.message);
255+ });
256+}
257+
258+function finish(){
259+ var raw=$('codeInput').value.trim();
260+ if(!raw){note($('loginNote'),'Paste the code or the redirect address first.','err');return;}
261+ var b=$('btnFinish');
262+ b.disabled=true;b.textContent='Authorizing...';
263+ note($('loginNote'),'Exchange in progress. The Google project discovery can take a few seconds.');
264+ api('finish','code='+encodeURIComponent(raw)).then(function(d){
265+ b.disabled=false;b.textContent='Authorize & Discover Project';
266+ if(!d||!d.ok){
267+ note($('loginNote'),(d&&(d.detail||d.error))||'exchange failed','err');
268+ return;
269+ }
270+ note($('loginNote'),'');
271+ $('step2').classList.remove('on');
272+ $('step1').classList.add('on');
273+ $('codeInput').value='';
274+ render(d);
275+ toast('Signed in as '+(d.email||'Google account'));
276+ }).catch(function(e){
277+ b.disabled=false;b.textContent='Authorize & Discover Project';
278+ note($('loginNote'),'Exchange failed: '+e.message,'err');
279+ });
280+}
281+
282+function cancel(){
283+ api('cancel').then(function(){
284+ $('step2').classList.remove('on');
285+ $('step1').classList.add('on');
286+ $('codeInput').value='';
287+ note($('loginNote'),'');
288+ toast('Pending login cancelled');
289+ load();
290+ }).catch(function(e){toast('Cancel failed: '+e.message);});
291+}
292+
293+function refreshToken(){
294+ var b=$('btnRefresh');
295+ b.disabled=true;b.textContent='Refreshing...';
296+ note($('refreshNote'),'Asking Google for a new access token...');
297+ api('refresh').then(function(d){
298+ b.disabled=false;b.textContent='Refresh Token Now';
299+ if(!d||!d.ok){
300+ note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');
301+ return;
302+ }
303+ note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');
304+ render(d);
305+ }).catch(function(e){
306+ b.disabled=false;b.textContent='Refresh Token Now';
307+ note($('refreshNote'),'Refresh failed: '+e.message,'err');
308+ });
309+}
310+
311+function copyLink(){
312+ if(!authUrl)return;
313+ var done=function(){toast('Link copied');};
314+ if(navigator.clipboard&&navigator.clipboard.writeText){
315+ navigator.clipboard.writeText(authUrl).then(done).catch(function(){toast('Copy failed');});
316+ }else{toast('Copy not available');}
317+}
318+
319+$('btnStart').onclick=start;
320+$('btnFinish').onclick=finish;
321+$('btnCancel').onclick=cancel;
322+$('btnRefresh').onclick=refreshToken;
323+$('btnReload').onclick=load;
324+$('btnCopy').onclick=copyLink;
325+$('codeInput').addEventListener('keydown',function(e){
326+ if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)){e.preventDefault();finish();}
327+});
328+load();
329+</script>
330+</body></html>
src/ui_html.h+338−0■■■■■
11new file mode 100644
index 0000000..1b55812
--- /dev/null
+++ b/src/ui_html.h
@@ -0,0 +1,338 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_AGYLOGIN_UI_HTML_H
3+#define SX_AGYLOGIN_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
9+ "<title>google</title>\n"
10+ "\001\n"
11+ "<style>\n"
12+ "*{box-sizing:border-box}\n"
13+ "html,body{margin:0;min-height:100%}\n"
14+ "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n"
15+ " line-height:1.5;-webkit-font-smoothing:antialiased}\n"
16+ "#app{max-width:840px;margin:0 auto;padding:16px 16px 40px}\n"
17+ ".hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n"
18+ ".hd .grow{flex:1 1 auto;min-width:0}\n"
19+ ".hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}\n"
20+ ".hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;\n"
21+ " overflow:hidden;text-overflow:ellipsis}\n"
22+ ".pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;\n"
23+ " padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);\n"
24+ " border:1px solid var(--line);white-space:nowrap}\n"
25+ ".pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}\n"
26+ ".pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n"
27+ ".pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}\n"
28+ ".pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n"
29+ ".pill.warn .dot{background:var(--orange)}\n"
30+ ".pill.off .dot{background:var(--gray)}\n"
31+ ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n"
32+ " padding:16px;margin-bottom:12px}\n"
33+ ".card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;\n"
34+ " text-transform:uppercase;color:var(--text-2)}\n"
35+ ".card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}\n"
36+ ".row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n"
37+ ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;\n"
38+ " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;\n"
39+ " transition:transform .12s var(--ease),opacity .12s}\n"
40+ ".btn:active{transform:scale(.98)}\n"
41+ ".btn:disabled{opacity:.5;cursor:default}\n"
42+ ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n"
43+ ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n"
44+ ".btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}\n"
45+ "a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}\n"
46+ ".kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}\n"
47+ ".kv .k{color:var(--text-2);font-size:12px}\n"
48+ ".kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}\n"
49+ ".kv .v.plain{font-family:var(--font);font-size:13px}\n"
50+ ".hint{font-size:12px;color:var(--text-2);margin:10px 0 0}\n"
51+ ".step{display:none}\n"
52+ ".step.on{display:block}\n"
53+ ".authurl{margin:10px 0;padding:10px 11px;border-radius:10px;background:var(--code-bg);\n"
54+ " border:1px solid var(--line);font-family:var(--mono);font-size:11.5px;\n"
55+ " word-break:break-all;max-height:120px;overflow:auto;color:var(--text)}\n"
56+ "textarea{width:100%;min-height:82px;resize:vertical;border-radius:10px;padding:10px 11px;\n"
57+ " border:1px solid var(--line);background:var(--input-bg);color:var(--text);\n"
58+ " font-family:var(--mono);font-size:12px;line-height:1.45}\n"
59+ "textarea:focus{outline:2px solid var(--blue);outline-offset:-1px}\n"
60+ ".note{display:none;margin-top:10px;padding:9px 11px;border-radius:10px;font-size:12.5px;\n"
61+ " border:1px solid var(--line);background:var(--surface-2)}\n"
62+ ".note.show{display:block}\n"
63+ ".note.err{color:var(--red);border-color:rgba(255,69,58,.35)}\n"
64+ ".note.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n"
65+ ".empty{padding:10px 0;color:var(--text-2);font-size:12.5px}\n"
66+ ".toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;\n"
67+ " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n"
68+ " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n"
69+ " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n"
70+ " z-index:9;max-width:calc(100vw - 32px)}\n"
71+ ".toast.show{opacity:1;transform:translate(-50%,0)}\n"
72+ "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n"
73+ " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n"
74+ " font-family:inherit}\n"
75+ "@media (max-width:520px){\n"
76+ " #app{padding:12px 12px 32px}\n"
77+ " .kv{grid-template-columns:1fr;gap:2px 0}\n"
78+ " .kv .k{margin-top:8px}\n"
79+ " .card{padding:13px;border-radius:12px}\n"
80+ "}\n"
81+ "</style>\n"
82+ "</head>\n"
83+ "<body>\n"
84+ "<div id=\"app\">\n"
85+ " <div class=\"hd\">\n"
86+ " <div class=\"grow\">\n"
87+ " <h1>Google Antigravity</h1>\n"
88+ " <div class=\"sub\" id=\"sub\">OAuth 2.0 PKCE login on this node</div>\n"
89+ " </div>\n"
90+ " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n"
91+ " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n"
92+ " </div>\n"
93+ "\n"
94+ " <div class=\"card\">\n"
95+ " <h2>Session</h2>\n"
96+ " <p class=\"lead\" id=\"sessionLead\">Reading the local Antigravity credentials.</p>\n"
97+ " <div class=\"kv\" id=\"session\"></div>\n"
98+ " <div class=\"row\" style=\"margin-top:14px\">\n"
99+ " <button class=\"btn ghost\" id=\"btnRefresh\" type=\"button\">Refresh Token Now</button>\n"
100+ " <button class=\"btn ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n"
101+ " </div>\n"
102+ " <div class=\"note\" id=\"refreshNote\"></div>\n"
103+ " </div>\n"
104+ "\n"
105+ " <div class=\"card\">\n"
106+ " <h2>OAuth login</h2>\n"
107+ " <p class=\"lead\">Sign in with Google. Nothing leaves this node: the login CLI performs the\n"
108+ " exchange and writes the credential file here.</p>\n"
109+ "\n"
110+ " <div class=\"step on\" id=\"step1\">\n"
111+ " <button class=\"btn\" id=\"btnStart\" type=\"button\">Start Google Login</button>\n"
112+ " <p class=\"hint\">This generates a PKCE challenge and an authorization link. No token is\n"
113+ " created until you paste the code back.</p>\n"
114+ " </div>\n"
115+ "\n"
116+ " <div class=\"step\" id=\"step2\">\n"
117+ " <div class=\"row\">\n"
118+ " <a class=\"btn\" id=\"linkOpen\" href=\"#\" target=\"_blank\" rel=\"noopener noreferrer\">Open Google Sign-in</a>\n"
119+ " <button class=\"btn ghost\" id=\"btnCopy\" type=\"button\">Copy link</button>\n"
120+ " <button class=\"btn ghost\" id=\"btnCancel\" type=\"button\">Cancel</button>\n"
121+ " </div>\n"
122+ " <div class=\"authurl\" id=\"authUrl\"></div>\n"
123+ " <p class=\"hint\" id=\"flowHint\">After approving, the browser lands on antigravity.google. Copy the\n"
124+ " whole address (or just the <span style=\"font-family:var(--mono)\">code=</span> value) and paste it below.</p>\n"
125+ " <textarea id=\"codeInput\" spellcheck=\"false\" autocomplete=\"off\"\n"
126+ " placeholder=\"Paste the authorization code or the full redirect URL\"></textarea>\n"
127+ " <div class=\"row\" style=\"margin-top:10px\">\n"
128+ " <button class=\"btn\" id=\"btnFinish\" type=\"button\">Authorize &amp; Discover Project</button>\n"
129+ " </div>\n"
130+ " <div class=\"note\" id=\"loginNote\"></div>\n"
131+ " </div>\n"
132+ " </div>\n"
133+ "\n"
134+ " <div class=\"card\">\n"
135+ " <h2>Companion project</h2>\n"
136+ " <p class=\"lead\">The Google Cloud project the Antigravity session bills against.</p>\n"
137+ " <div class=\"kv\" id=\"project\"></div>\n"
138+ " </div>\n"
139+ "</div>\n"
140+ "\n"
141+ "<div class=\"toast\" id=\"toast\"></div>\n"
142+ "\n"
143+ "<script>\n"
144+ "var q=new URLSearchParams(location.search);\n"
145+ "var node=q.get('node')||'';\n"
146+ "var sid=q.get('id')||'';\n"
147+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n"
148+ " localStorage.getItem('bot_active_pwd')||'';\n"
149+ "\n"
150+ "/* Two call routes. Getting this wrong is the most common plugin bug:\n"
151+ " * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)\n"
152+ " * -> call the hub proxy back: /plugins?plugin=plugin_antigravity_login&action=..\n"
153+ " * opened directly on the node\n"
154+ " * -> the plugin itself is the route: /plugin_antigravity_login?action=..\n"
155+ " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n"
156+ "var HUB=q.get('plugin')||'';\n"
157+ "function url(action,extra){\n"
158+ " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_antigravity_login')+\n"
159+ " '?action='+encodeURIComponent(action)+\n"
160+ " (extra?('&'+extra):'')+\n"
161+ " (node?'&node='+encodeURIComponent(node):'')+\n"
162+ " (sid?'&id='+encodeURIComponent(sid):'')+\n"
163+ " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n"
164+ "}\n"
165+ "function hdr(){\n"
166+ " var h={};\n"
167+ " if(pwd)h['X-Bot-Password']=pwd;\n"
168+ " return h;\n"
169+ "}\n"
170+ "function api(action,extra){\n"
171+ " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n"
172+ " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n"
173+ " });\n"
174+ "}\n"
175+ "\n"
176+ "var $=function(id){return document.getElementById(id);};\n"
177+ "function toast(msg){\n"
178+ " var t=$('toast');t.textContent=msg;t.classList.add('show');\n"
179+ " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n"
180+ "}\n"
181+ "function note(el,msg,kind){\n"
182+ " el.textContent=msg||'';\n"
183+ " el.className='note'+(msg?' show '+(kind||''):'');\n"
184+ "}\n"
185+ "function kv(el,rows){\n"
186+ " el.innerHTML='';\n"
187+ " rows.forEach(function(r){\n"
188+ " var a=document.createElement('div');a.className='k';a.textContent=r[0];\n"
189+ " var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');\n"
190+ " b.textContent=r[1];el.appendChild(a);el.appendChild(b);\n"
191+ " });\n"
192+ "}\n"
193+ "function fmtExpiry(sec){\n"
194+ " if(!sec&&sec!==0)return '-';\n"
195+ " if(sec<=0)return 'expired';\n"
196+ " if(sec<90)return sec+'s';\n"
197+ " if(sec<5400)return Math.round(sec/60)+' min';\n"
198+ " if(sec<172800)return Math.round(sec/3600)+' h';\n"
199+ " return Math.round(sec/86400)+' d';\n"
200+ "}\n"
201+ "function setPill(st){\n"
202+ " var p=$('pill'),t=$('pillText');\n"
203+ " if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}\n"
204+ " else if(st.logged_in){p.className='pill ok';t.textContent='Connected';}\n"
205+ " else if(st.pending){p.className='pill warn';t.textContent='Signing in';}\n"
206+ " else {p.className='pill off';t.textContent='Not Connected';}\n"
207+ "}\n"
208+ "function render(st){\n"
209+ " setPill(st);\n"
210+ " $('sub').textContent=st.email?st.email:'OAuth 2.0 PKCE login on this node';\n"
211+ "\n"
212+ " if(st.logged_in){\n"
213+ " $('sessionLead').textContent=st.expired\n"
214+ " ? 'The session is present but its access token has expired. Use Refresh Token Now.'\n"
215+ " : 'This node holds a Google Antigravity session.';\n"
216+ " }else{\n"
217+ " $('sessionLead').textContent='No Google session on this node yet. Start a login below.';\n"
218+ " }\n"
219+ " kv($('session'),[\n"
220+ " ['Account', st.email||'-', true],\n"
221+ " ['Logged in', st.logged_in?'yes':'no', true],\n"
222+ " ['Refresh token', st.has_refresh?'stored':'none', true],\n"
223+ " ['Token expires', st.logged_in?fmtExpiry(st.expires_in_sec):'-', true],\n"
224+ " ['Login pending', st.pending?'yes':'no', true],\n"
225+ " ['Login CLI', st.cli_present?'found':'not found', true],\n"
226+ " ['Credentials', st.credentials_path||'-']\n"
227+ " ]);\n"
228+ " kv($('project'),[\n"
229+ " ['Project ID', st.project_id||'(consumer shared project)', !st.project_id],\n"
230+ " ['Profile', st.profile||'-', true],\n"
231+ " ['Provider', 'google (Antigravity)', true]\n"
232+ " ]);\n"
233+ "\n"
234+ " if(st.pending){$('step1').classList.remove('on');$('step2').classList.add('on');}\n"
235+ "}\n"
236+ "function load(){\n"
237+ " return api('status').then(function(d){\n"
238+ " if(d&&d.ok)render(d);\n"
239+ " else toast((d&&d.error)||'status failed');\n"
240+ " }).catch(function(e){toast('Status failed: '+e.message);});\n"
241+ "}\n"
242+ "\n"
243+ "var authUrl='';\n"
244+ "function start(){\n"
245+ " var b=$('btnStart');\n"
246+ " b.disabled=true;b.textContent='Starting...';\n"
247+ " api('start').then(function(d){\n"
248+ " b.disabled=false;b.textContent='Start Google Login';\n"
249+ " if(!d||!d.ok){toast((d&&(d.detail||d.error))||'start failed');return;}\n"
250+ " authUrl=d.auth_url||'';\n"
251+ " $('authUrl').textContent=authUrl;\n"
252+ " $('linkOpen').setAttribute('href',authUrl);\n"
253+ " if(d.hint)$('flowHint').textContent=d.hint;\n"
254+ " $('step1').classList.remove('on');\n"
255+ " $('step2').classList.add('on');\n"
256+ " $('codeInput').focus();\n"
257+ " }).catch(function(e){\n"
258+ " b.disabled=false;b.textContent='Start Google Login';\n"
259+ " toast('Start failed: '+e.message);\n"
260+ " });\n"
261+ "}\n"
262+ "\n"
263+ "function finish(){\n"
264+ " var raw=$('codeInput').value.trim();\n"
265+ " if(!raw){note($('loginNote'),'Paste the code or the redirect address first.','err');return;}\n"
266+ " var b=$('btnFinish');\n"
267+ " b.disabled=true;b.textContent='Authorizing...';\n"
268+ " note($('loginNote'),'Exchange in progress. The Google project discovery can take a few seconds.');\n"
269+ " api('finish','code='+encodeURIComponent(raw)).then(function(d){\n"
270+ " b.disabled=false;b.textContent='Authorize & Discover Project';\n"
271+ " if(!d||!d.ok){\n"
272+ " note($('loginNote'),(d&&(d.detail||d.error))||'exchange failed','err');\n"
273+ " return;\n"
274+ " }\n"
275+ " note($('loginNote'),'');\n"
276+ " $('step2').classList.remove('on');\n"
277+ " $('step1').classList.add('on');\n"
278+ " $('codeInput').value='';\n"
279+ " render(d);\n"
280+ " toast('Signed in as '+(d.email||'Google account'));\n"
281+ " }).catch(function(e){\n"
282+ " b.disabled=false;b.textContent='Authorize & Discover Project';\n"
283+ " note($('loginNote'),'Exchange failed: '+e.message,'err');\n"
284+ " });\n"
285+ "}\n"
286+ "\n"
287+ "function cancel(){\n"
288+ " api('cancel').then(function(){\n"
289+ " $('step2').classList.remove('on');\n"
290+ " $('step1').classList.add('on');\n"
291+ " $('codeInput').value='';\n"
292+ " note($('loginNote'),'');\n"
293+ " toast('Pending login cancelled');\n"
294+ " load();\n"
295+ " }).catch(function(e){toast('Cancel failed: '+e.message);});\n"
296+ "}\n"
297+ "\n"
298+ "function refreshToken(){\n"
299+ " var b=$('btnRefresh');\n"
300+ " b.disabled=true;b.textContent='Refreshing...';\n"
301+ " note($('refreshNote'),'Asking Google for a new access token...');\n"
302+ " api('refresh').then(function(d){\n"
303+ " b.disabled=false;b.textContent='Refresh Token Now';\n"
304+ " if(!d||!d.ok){\n"
305+ " note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');\n"
306+ " return;\n"
307+ " }\n"
308+ " note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');\n"
309+ " render(d);\n"
310+ " }).catch(function(e){\n"
311+ " b.disabled=false;b.textContent='Refresh Token Now';\n"
312+ " note($('refreshNote'),'Refresh failed: '+e.message,'err');\n"
313+ " });\n"
314+ "}\n"
315+ "\n"
316+ "function copyLink(){\n"
317+ " if(!authUrl)return;\n"
318+ " var done=function(){toast('Link copied');};\n"
319+ " if(navigator.clipboard&&navigator.clipboard.writeText){\n"
320+ " navigator.clipboard.writeText(authUrl).then(done).catch(function(){toast('Copy failed');});\n"
321+ " }else{toast('Copy not available');}\n"
322+ "}\n"
323+ "\n"
324+ "$('btnStart').onclick=start;\n"
325+ "$('btnFinish').onclick=finish;\n"
326+ "$('btnCancel').onclick=cancel;\n"
327+ "$('btnRefresh').onclick=refreshToken;\n"
328+ "$('btnReload').onclick=load;\n"
329+ "$('btnCopy').onclick=copyLink;\n"
330+ "$('codeInput').addEventListener('keydown',function(e){\n"
331+ " if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)){e.preventDefault();finish();}\n"
332+ "});\n"
333+ "load();\n"
334+ "</script>\n"
335+ "\002</body></html>\n"
336+ ;
337+
338+#endif /* SX_AGYLOGIN_UI_HTML_H */
tests/mock_login.sh+68−0■■■■■
11new file mode 100755
index 0000000..082dc05
--- /dev/null
+++ b/tests/mock_login.sh
@@ -0,0 +1,68 @@
1+#!/bin/sh
2+# tests/mock_login.sh - stand-in for scorpiox-antigravity-login machine mode.
3+#
4+# Emits exactly the contract shape the real CLI emits (one JSON line last, all
5+# human output before it), so the plugin's parsers are exercised against the
6+# production layout rather than an invented one. The exchange is simulated:
7+# --finish writes a credential file into $ANTIGRAVITY_CREDS_PATH's directory so
8+# the test can prove the plugin re-reads state after a successful login.
9+#
10+# Set MOCK_FAIL=1 to make --finish fail the way Google does when the account
11+# needs verification.
12+
13+case "$1" in
14+ --status)
15+ if [ -n "$MOCK_STATUS_JSON" ]; then
16+ printf '%s\n' "$MOCK_STATUS_JSON"
17+ else
18+ # Mirror the real CLI: logged_in / has_refresh / identity all come from
19+ # the credential file the exchange wrote, so a test that runs --finish
20+ # and then --status sees the same thing a real node would.
21+ _acct="${ANTIGRAVITY_CREDS_PATH:-/nonexistent}"
22+ _li=false; _hr=false; _id=""
23+ if [ -f "$_acct" ] && grep -q 'refresh_token' "$_acct" 2>/dev/null; then
24+ _li=true; _hr=true
25+ _id=$(sed -n 's/.*"email"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_acct" | head -1)
26+ fi
27+ printf 'scorpiox-antigravity-login 1.0.0 (SXLOGIN-MACHINE-V1)\n'
28+ printf '{"ok":true,"provider":"antigravity","name":"Antigravity (Google)","flow":"paste_code",'
29+ printf '"logged_in":%s,"path":"%s",' "$_li" "$_acct"
30+ if [ -n "$_id" ]; then printf '"identity":"%s",' "$_id"; fi
31+ printf '"expires_at":0,"expired":false,"has_refresh":%s,"pending":false,' "$_hr"
32+ printf '"profile":"antigravity","profile_exists":false}\n'
33+ fi
34+ ;;
35+ --start)
36+ printf 'generating PKCE challenge\n'
37+ printf '{"ok":true,"provider":"antigravity","flow":"paste_code",'
38+ printf '"auth_url":"https://accounts.google.com/o/oauth2/auth?client_id=test&code_challenge=abc123&code_challenge_method=S256&state=st4te",'
39+ printf '"expires_in":900,"hint":"Sign in with Google and approve, then paste the code."}\n'
40+ ;;
41+ --finish)
42+ if [ "$MOCK_FAIL" = "1" ]; then
43+ printf '{"ok":false,"provider":"antigravity","error":"exchange","detail":"validation required"}\n'
44+ exit 1
45+ fi
46+ [ -z "$2" ] && { printf '{"ok":false,"error":"no_code"}\n'; exit 1; }
47+ # simulate the CLI writing the credential + profile
48+ if [ -n "$MOCK_WRITE_DIR" ]; then
49+ mkdir -p "$MOCK_WRITE_DIR" "$MOCK_WRITE_DIR/scorpiox-env"
50+ printf '[{"email":"pico@example.com","refresh_token":"1//mock-refresh-token-value"}]\n' \
51+ > "$MOCK_WRITE_DIR/antigravity_accounts.json"
52+ printf 'pico@example.com\n' > "$MOCK_WRITE_DIR/selected_account.txt"
53+ printf 'PROVIDER=google_gemini\nGOOGLE_ACCOUNT=pico@example.com\nGOOGLE_PROJECT_ID=proj-mock-42\n' \
54+ > "$MOCK_WRITE_DIR/scorpiox-env/antigravity.txt"
55+ fi
56+ printf 'Login Successful!\n'
57+ printf '{"ok":true,"provider":"antigravity","state":"done","logged_in":true,'
58+ printf '"path":"%s","identity":"pico@example.com","profile":"antigravity","profile_created":true}\n' \
59+ "${ANTIGRAVITY_CREDS_PATH:-/nonexistent}"
60+ ;;
61+ --cancel)
62+ printf '{"ok":true,"provider":"antigravity","state":"cancelled"}\n'
63+ ;;
64+ *)
65+ printf '{"ok":false,"error":"usage"}\n'
66+ exit 1
67+ ;;
68+esac
tests/mock_token.sh+14−0■■■■■
11new file mode 100755
index 0000000..9f7839e
--- /dev/null
+++ b/tests/mock_token.sh
@@ -0,0 +1,14 @@
1+#!/bin/sh
2+# tests/mock_token.sh - stand-in for scorpiox-google-fetchtoken -local.
3+#
4+# Prints the real payload shape, including a fake bearer token, so the suite can
5+# prove the plugin never forwards that token to a browser or a proxy log.
6+#
7+# Set MOCK_TOKEN_FAIL=1 to exercise the refresh failure path.
8+if [ "$MOCK_TOKEN_FAIL" = "1" ]; then
9+ printf '{"ok":false,"error":"no refresh_token for account"}\n'
10+ exit 1
11+fi
12+printf 'fetching token (local)\n'
13+printf '{"ok":true,"email":"pico@example.com","access_token":"ya29.MOCK-ACCESS-TOKEN-MUST-NOT-LEAK",'
14+printf '"project_id":"proj-mock-42","expires_in":3599}\n'
tests/run.sh+426−0■■■■■
11new file mode 100755
index 0000000..e31a831
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,426 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_antigravity_login across all 3 modes.
3+#
4+# Every check runs against ./plugin_antigravity_login with the credential paths
5+# and both CLIs redirected at throwaway fixtures, so the suite proves the public
6+# contract without touching a real Google session and without a network.
7+#
8+# What it proves:
9+# - --meta is exactly {"name":"google","desc":"Google login"} and is reachable
10+# with no password (discovery must never be gated)
11+# - every action 401s without the node password, and 401 is a real CGI Status
12+# - status parses the accounts array + sibling files + the CLI JSON and never
13+# emits a token
14+# - start returns the CLI's auth_url, finish rejects garbage codes locally and
15+# re-reads state after a successful exchange
16+# - refresh performs the grant, drops the access token, and surfaces failure
17+# - the HTML page carries the bot theme handoff, no CDN and no <script src=>
18+# - the source has no hard-coded secret, no internal address and no emoji
19+#
20+# Exit code 0 = everything passed.
21+
22+set -u
23+
24+ROOT=$(cd "$(dirname "$0")/.." && pwd)
25+cd "$ROOT" || exit 1
26+
27+BIN=./plugin_antigravity_login
28+ID=plugin_antigravity_login
29+PASS=0
30+FAIL=0
31+
32+if [ -t 1 ]; then
33+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
34+else
35+ C_OK=; C_BAD=; C_B=; C_0=
36+fi
37+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
38+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
39+
40+check() { # check <desc> <expected-substring> <actual>
41+ if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
42+ fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
43+ fi
44+}
45+
46+check_not() { # check_not <desc> <forbidden-substring> <actual>
47+ if printf '%s' "$3" | grep -F -q -- "$2"; then
48+ fail "$1 (must NOT contain: $2)"; else pass "$1"
49+ fi
50+}
51+
52+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
53+
54+# strip CGI headers if present, drop CRs, keep the payload
55+body() {
56+ printf '%s\n' "$1" | tr -d '\r' | awk '
57+ BEGIN { inhdr = 0 }
58+ NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next }
59+ inhdr && $0 == "" { inhdr = 0; next }
60+ inhdr { next }
61+ { print }
62+ '
63+}
64+
65+json_ok() { # json_ok <desc> <json> [python-expression]
66+ expr=${3:-True}
67+ if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
68+ pass "$1"
69+ else
70+ fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
71+ fi
72+}
73+
74+api() { body "$(QUERY_STRING="$1" $BIN)"; }
75+apiraw() { QUERY_STRING="$1" $BIN; }
76+
77+# ---------------------------------------------------------------- build
78+section "build"
79+if [ ! -x "$BIN" ]; then
80+ echo " building native binary..."
81+ gcc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_antigravity_login.c || {
82+ fail "native build"; exit 1; }
83+fi
84+pass "native binary present"
85+
86+# generated page header must match src/ui.html
87+if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
88+ pass "src/ui_html.h is in sync with src/ui.html"
89+else
90+ fail "src/ui_html.h is stale - run tools/gen_ui.py"
91+fi
92+
93+# the page header must not be hand-edited: it is generated from ui.html
94+check "ui header is marked generated" \
95+ "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
96+
97+# ---------------------------------------------------------------- fixtures
98+FIX=$(mktemp -d 2>/dev/null || mktemp -d -t agyfix)
99+trap 'rm -rf "$FIX"' EXIT
100+
101+mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" "$FIX/full/scorpiox-env" "$FIX/pending"
102+export ANTIGRAVITY_LOGIN_BIN="$ROOT/tests/mock_login.sh"
103+export ANTIGRAVITY_TOKEN_BIN="$ROOT/tests/mock_token.sh"
104+export ANTIGRAVITY_PENDING_PATH="$FIX/pending/antigravity-default.json"
105+
106+# empty credentials file (exists but has no accounts)
107+: > "$FIX/empty/antigravity_accounts.json"
108+
109+# a realistic signed-in fixture: the accounts array + selected account + profile
110+cat > "$FIX/full/antigravity_accounts.json" <<'JSON'
111+[
112+ {"email":"other@example.com","refresh_token":"1//other-refresh"},
113+ {"email":"pico@example.com","refresh_token":"1//pico-refresh-value"}
114+]
115+JSON
116+printf 'pico@example.com\n' > "$FIX/full/selected_account.txt"
117+printf 'PROVIDER=google_gemini\nGOOGLE_TOKEN_SOURCE=local\nGOOGLE_ACCOUNT=pico@example.com\nGOOGLE_PROJECT_ID=proj-mock-42\nMODEL=gemini-3.7-flash-tiered\n' \
118+ > "$FIX/full/scorpiox-env/antigravity.txt"
119+
120+# ---------------------------------------------------------------- metadata
121+section "mode 1: discovery metadata"
122+META=$("$BIN" --meta)
123+if [ "$META" = '{"name":"google","desc":"Google login"}' ]; then
124+ pass "--meta is exactly the contract line"
125+else
126+ fail "--meta mismatch"; printf ' got: %s\n' "$META"
127+fi
128+json_ok "--meta is valid JSON with name+desc" "$META" \
129+ "d['name']=='google' and d['desc']=='Google login'"
130+check "--meta desc is within 15 chars" "Google login" "$META"
131+
132+ENVMETA=$(SX_PLUGIN_META=1 "$BIN")
133+check "SX_PLUGIN_META=1 works like --meta" '"name":"google"' "$ENVMETA"
134+
135+# --meta must not be gated by the node password
136+META_PW=$(BOT_PASSWORD=testpw "$BIN" --meta)
137+check "--meta ignores BOT_PASSWORD" '"name":"google"' "$META_PW"
138+
139+check "--version prints the plugin id and version" "$ID" "$("$BIN" --version)"
140+
141+# ---------------------------------------------------------------- auth
142+section "node auth"
143+export BOT_PASSWORD=testpw
144+RAW=$(apiraw "action=status")
145+check "unauthenticated action returns a 401 Status line" "Status: 401 Unauthorized" "$RAW"
146+check "unauthenticated action body is JSON" '"error":"invalid node password"' "$RAW"
147+
148+RAW=$(apiraw "")
149+check "unauthenticated HTML also 401s" "Status: 401 Unauthorized" "$RAW"
150+
151+HDR=$(api "action=status&pwd=testpw")
152+check "?pwd= authenticates" '"ok":true' "$HDR"
153+
154+HDR=$(QUERY_STRING="action=status" HTTP_X_BOT_PASSWORD=testpw $BIN)
155+check "X-Bot-Password authenticates" '"ok":true' "$(body "$HDR")"
156+
157+HDR=$(QUERY_STRING="action=status" HTTP_AUTHORIZATION="Bearer testpw" $BIN)
158+check "Authorization: Bearer authenticates" '"ok":true' "$(body "$HDR")"
159+
160+WRONG=$(apiraw "action=status&pwd=nope")
161+check "a wrong password still 401s" "Status: 401 Unauthorized" "$WRONG"
162+unset BOT_PASSWORD
163+
164+# ---------------------------------------------------------------- status
165+section "action=status"
166+NOFIX=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \
167+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":false,"expires_at":0,"expired":false,"has_refresh":false,"pending":false}' \
168+ api "action=status")
169+json_ok "status with no credentials is valid JSON" "$NOFIX" \
170+ "d['ok'] is True and d['logged_in'] is False and d['has_refresh'] is False"
171+check_not "status with no credentials emits no token field" "refresh_token" "$NOFIX"
172+
173+EMPTYJ=$(ANTIGRAVITY_CREDS_PATH="$FIX/empty/antigravity_accounts.json" api "action=status")
174+json_ok "empty accounts file yields logged_in false" "$EMPTYJ" \
175+ "d['ok'] is True and d['logged_in'] is False"
176+
177+FULL=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
178+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":4102444800000,"expired":false,"has_refresh":true,"pending":false,"identity":"pico@example.com"}' \
179+ api "action=status")
180+json_ok "signed-in status reports logged_in + has_refresh" "$FULL" \
181+ "d['ok'] is True and d['logged_in'] is True and d['has_refresh'] is True"
182+check_not "signed-in status never returns the refresh token" "1//pico-refresh-value" "$FULL"
183+check_not "signed-in status never returns any token literal" "refresh_token\":" "$FULL"
184+
185+check "status reports the selected account email" "pico@example.com" "$FULL"
186+check "status reads the companion project from the profile" "proj-mock-42" "$FULL"
187+check "status reports the credentials path" "$FIX/full/antigravity_accounts.json" "$FULL"
188+json_ok "status has the full contract field set" "$FULL" \
189+ "all(k in d for k in ('logged_in','email','project_id','expires_at','expires_in_sec','expired','has_refresh','account','pending','profile'))"
190+
191+# expired session: the CLI says the expiry is in the past
192+EXPIRED=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
193+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":1000000000000,"expired":true,"has_refresh":true,"pending":false}' \
194+ api "action=status")
195+json_ok "an expired session reports expired true and a negative remaining time" "$EXPIRED" \
196+ "d['expired'] is True and d['expires_in_sec'] < 0"
197+
198+# pending marker file present -> pending true even without CLI help
199+: > "$FIX/pending/antigravity-default.json"
200+PEND=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \
201+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":false,"pending":false}' \
202+ api "action=status")
203+json_ok "the pending marker file makes status pending" "$PEND" "d['pending'] is True"
204+rm -f "$FIX/pending/antigravity-default.json"
205+
206+# no CLI on PATH: status must still answer from the files alone
207+NOCLI=$(ANTIGRAVITY_LOGIN_BIN="/nonexistent/login-cli" \
208+ ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" api "action=status")
209+json_ok "status answers without the login CLI" "$NOCLI" \
210+ "d['ok'] is True and d['logged_in'] is True"
211+json_ok "cli_present is false when the CLI is missing" "$NOCLI" "d['cli_present'] is False"
212+
213+# format=json with no action means status
214+FMT=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
215+ MOCK_STATUS_JSON='{"ok":true,"logged_in":true,"has_refresh":true}' api "format=json")
216+json_ok "format=json alone answers status" "$FMT" "d['ok'] is True and 'logged_in' in d"
217+
218+# ---------------------------------------------------------------- start
219+section "action=start"
220+START=$(api "action=start")
221+json_ok "start returns ok + an auth_url" "$START" \
222+ "d['ok'] is True and d['auth_url'].startswith('https://accounts.google.com/')"
223+check "start reports the paste_code flow" '"flow":"paste_code"' "$START"
224+check "start carries the PKCE challenge in the URL" "code_challenge=" "$START"
225+check "start carries the S256 method" "code_challenge_method=S256" "$START"
226+check "start reports an expiry window" "expires_in" "$START"
227+
228+# the plugin must not invent a client secret of its own
229+check_not "start never echoes a client secret" "GOCSPX" "$START"
230+
231+NOCLISTART=$(ANTIGRAVITY_LOGIN_BIN="/nonexistent/login-cli" api "action=start")
232+json_ok "start without the CLI returns a structured error" "$NOCLISTART" \
233+ "d['ok'] is False and d['error']=='cli_unavailable'"
234+
235+# ---------------------------------------------------------------- finish
236+section "action=finish"
237+MISSING=$(api "action=finish")
238+json_ok "finish without a code is a 400-style error object" "$MISSING" \
239+ "d['ok'] is False and d['error']=='missing_code'"
240+
241+SHELLY=$(api "action=finish&code=\$(touch_/tmp/pwned)")
242+json_ok "finish rejects shell metacharacters before running anything" "$SHELLY" \
243+ "d['ok'] is False and d['error']=='invalid_code'"
244+if [ -e /tmp/pwned ]; then fail "shell injection created /tmp/pwned"; rm -f /tmp/pwned; else pass "shell injection did not execute"; fi
245+
246+QUOTED=$(api "action=finish&code=abc%27def")
247+json_ok "finish rejects a quote in the code" "$QUOTED" \
248+ "d['ok'] is False and d['error']=='invalid_code'"
249+
250+FAILED=$(MOCK_FAIL=1 api "action=finish&code=4/0AX4XfWh-test-code")
251+json_ok "a rejected exchange surfaces the CLI error" "$FAILED" \
252+ "d['ok'] is False and d['error'] in ('exchange','finish_failed')"
253+
254+# successful exchange: the mock writes the credential files into $MOCK_WRITE_DIR
255+mkdir -p "$FIX/finishdir"
256+OKF=$(MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
257+ api "action=finish&code=4/0AX4XfWh-test-code")
258+json_ok "a successful exchange reports done + logged_in" "$OKF" \
259+ "d['ok'] is True and d['state']=='done' and d['logged_in'] is True"
260+check "the exchange result re-reads the new account" "pico@example.com" "$OKF"
261+check_not "the exchange result never carries the token" "1//mock-refresh-token-value" "$OKF"
262+
263+# a full redirect URL is accepted (the CLI extracts code= itself)
264+FULLURL=$(MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
265+ api "action=finish&code=https%3A%2F%2Fantigravity.google%2Foauth-callback%3Fcode%3D4%2F0AX-test%26state%3Dxyz")
266+json_ok "a whole redirect URL is accepted" "$FULLURL" "d['ok'] is True and d['state']=='done'"
267+
268+# POST body carrying the code
269+POSTB=$(printf '{"code":"4/0AX4XfWh-post-code"}' | \
270+ REQUEST_METHOD=POST CONTENT_LENGTH=32 \
271+ MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
272+ QUERY_STRING="action=finish" $BIN)
273+json_ok "the code can arrive in a POST body" "$(body "$POSTB")" "d['ok'] is True"
274+
275+# ---------------------------------------------------------------- cancel
276+section "action=cancel"
277+CANCEL=$(api "action=cancel")
278+json_ok "cancel reports a cancelled state" "$CANCEL" \
279+ "d['ok'] is True and d['state']=='cancelled' and d['pending'] is False"
280+
281+# ---------------------------------------------------------------- refresh
282+section "action=refresh"
283+REFR=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" api "action=refresh")
284+json_ok "refresh succeeds and reports refreshed" "$REFR" \
285+ "d['ok'] is True and d['refreshed'] is True"
286+check_not "refresh NEVER returns the access token" "ya29.MOCK-ACCESS-TOKEN-MUST-NOT-LEAK" "$REFR"
287+check_not "refresh has no access_token key at all" "access_token" "$REFR"
288+check "refresh reports the project from the token CLI" "proj-mock-42" "$REFR"
289+
290+REFRFAIL=$(MOCK_TOKEN_FAIL=1 api "action=refresh")
291+json_ok "a failed refresh returns a structured error" "$REFRFAIL" \
292+ "d['ok'] is False and d['error']=='refresh_failed'"
293+
294+REFRNOCLI=$(ANTIGRAVITY_TOKEN_BIN="/nonexistent/token-cli" api "action=refresh")
295+json_ok "refresh without the token CLI says cli_unavailable" "$REFRNOCLI" \
296+ "d['ok'] is False and d['error']=='cli_unavailable'"
297+
298+# ---------------------------------------------------------------- errors
299+section "unknown routes and actions"
300+UNK=$(api "action=teleport")
301+json_ok "an unknown action is a structured error" "$UNK" \
302+ "d['ok'] is False and d['error']=='unknown_action'"
303+RAWUNK=$(apiraw "action=teleport")
304+check "an unknown action returns a 404 Status" "Status: 404 Not Found" "$RAWUNK"
305+check "the error carries the plugin contract headers" "Content-Type: application/json" "$RAWUNK"
306+check_not "no response emits Content-Length" "Content-Length" "$RAWUNK"
307+
308+BADS=$(api "action=status")
309+check_not "JSON responses carry Cache-Control: no-store" "Cache-Control: no-store" "$BADS"
310+
311+# ---------------------------------------------------------------- HTML
312+section "mode 3: HTML UI"
313+HTMLRAW=$(apiraw "")
314+HTML=$(body "$HTMLRAW")
315+check "HTML is served as text/html" "Content-Type: text/html; charset=utf-8" "$HTMLRAW"
316+check "HTML declares a viewport" "name=\"viewport\"" "$HTML"
317+check "HTML carries the CSP header" "Content-Security-Policy" "$HTMLRAW"
318+check "HTML declares color-scheme via the theme tokens" "color-scheme" "$HTML"
319+check "HTML includes the bot prepaint script" "bot_theme" "$HTML"
320+check "HTML includes the theme handoff listener" "sx-theme" "$HTML"
321+check "HTML has the status pill" 'id="pill"' "$HTML"
322+check "HTML has the start button" 'id="btnStart"' "$HTML"
323+check "HTML has the paste input" 'id="codeInput"' "$HTML"
324+check "HTML has the finish button" 'id="btnFinish"' "$HTML"
325+check "HTML has the cancel button" 'id="btnCancel"' "$HTML"
326+check "HTML has the refresh button" 'id="btnRefresh"' "$HTML"
327+check "HTML has the companion project card" "Companion project" "$HTML"
328+check "HTML uses the two-route API helper" "plugin_antigravity_login" "$HTML"
329+check "HTML hides the back link in embed mode" "embed-hide" "$HTML"
330+check_not "HTML loads no CDN script" "<script src=" "$HTML"
331+check_not "HTML references no external host script" "cdnjs" "$HTML"
332+check_not "HTML makes no outbound fetch to a third party" "googleapis.com" "$HTML"
333+check_not "HTML carries no emoji" "🚀" "$HTML"
334+
335+if command -v python3 >/dev/null 2>&1; then
336+ printf '%s' "$HTML" > "$FIX/page.html"
337+ if python3 - "$FIX/page.html" <<'PY'
338+import re, sys
339+html = open(sys.argv[1], encoding='utf-8').read()
340+# every id referenced by getElementById must exist in the markup
341+ids = set(re.findall(r'id="([^"]+)"', html))
342+missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids]
343+sys.exit(1 if missing else 0)
344+PY
345+ then pass "every JS element id exists in the markup"
346+ else fail "the page JS references an element id that is not in the HTML"; fi
347+fi
348+
349+# ---------------------------------------------------------------- source hygiene
350+section "source hygiene"
351+check_not "source has no OAuth client secret" "GOCSPX" "$(cat src/plugin_antigravity_login.c)"
352+check_not "source has no Google API key" "AIza" "$(cat src/plugin_antigravity_login.c)"
353+check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_antigravity_login.c)"
354+check_not "source has no internal address" "192.168." "$(cat src/plugin_antigravity_login.c src/ui.html)"
355+check_not "source has no 10.x internal address" "10.0." "$(cat src/plugin_antigravity_login.c src/ui.html)"
356+check_not "the page has no internal address either" "172.16" "$(cat src/ui.html)"
357+
358+# no emoji anywhere in the shipped sources (byte-level check, not a regex guess)
359+if python3 - src/plugin_antigravity_login.c src/ui.html src/bot_theme_plugin.h <<'PY'
360+import sys, unicodedata
361+bad = []
362+for path in sys.argv[1:]:
363+ for n, line in enumerate(open(path, encoding='utf-8'), 1):
364+ for ch in line:
365+ o = ord(ch)
366+ if o < 0x2000:
367+ continue
368+ if 0x2190 <= o <= 0x21FF: # arrows are typography, not emoji
369+ continue
370+ if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF:
371+ bad.append('%s:%d %r' % (path, n, ch))
372+if bad:
373+ print('\n'.join(bad[:10]))
374+ sys.exit(1)
375+PY
376+then pass "no emoji in source, page or theme header"
377+else fail "emoji found in the shipped sources"; fi
378+
379+# ---------------------------------------------------------------- extra builds
380+section "cross-target builds"
381+if command -v musl-gcc >/dev/null 2>&1; then
382+ if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_antigravity_login.c 2>/dev/null; then
383+ pass "static musl build"
384+ MUSLMETA=$("$FIX/musl-bin" --meta)
385+ check "the musl binary reports the same metadata" '"name":"google"' "$MUSLMETA"
386+ else fail "static musl build"; fi
387+else
388+ echo " skip musl-gcc not installed"
389+fi
390+
391+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
392+ if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_antigravity_login.c 2>/dev/null; then
393+ pass "MinGW-w64 build"
394+ if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then
395+ pass "the Windows build has a real PE header"
396+ else fail "the Windows build is not a PE (missing MZ)"; fi
397+ else fail "MinGW-w64 build"; fi
398+else
399+ echo " skip x86_64-w64-mingw32-gcc not installed"
400+fi
401+
402+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
403+ if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_antigravity_login.c 2>/dev/null; then
404+ pass "static arm64 build"
405+ else fail "static arm64 build"; fi
406+else
407+ echo " skip aarch64-linux-gnu-gcc not installed"
408+fi
409+
410+# _FORTIFY_SOURCE=2: the sqlite plugin lost a whole build to this, so it is
411+# part of every suite now.
412+if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_antigravity_login.c 2>/dev/null; then
413+ FORTMETA=$("$FIX/fortify-bin" --meta)
414+ check "a _FORTIFY_SOURCE=2 build runs --meta clean" '"name":"google"' "$FORTMETA"
415+ FORTSTAT=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
416+ QUERY_STRING="action=status" "$FIX/fortify-bin")
417+ json_ok "a fortify build answers status without aborting" "$(body "$FORTSTAT")" "d['ok'] is True"
418+else
419+ fail "_FORTIFY_SOURCE=2 build"
420+fi
421+
422+# ---------------------------------------------------------------- summary
423+printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
424+printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
425+[ "$FAIL" -eq 0 ] || exit 1
426+exit 0
tools/gen_ui.py+105−0■■■■■
11new file mode 100644
index 0000000..55470a4
--- /dev/null
+++ b/tools/gen_ui.py
@@ -0,0 +1,105 @@
1+#!/usr/bin/env python3
2+"""tools/gen_ui.py - compile src/ui.html into src/ui.html.h.
3+
4+The page lives in one readable file (src/ui.html) so it can be diffed and
5+reviewed like any other source. This script turns it into a single C string
6+constant with two control-character placeholders:
7+
8+ 0x01 -> the bot theme prepaint script + <style> + theme tokens
9+ 0x02 -> the bot theme handoff script (just before </body>)
10+
11+main() splits the constant on those bytes and emits the macros from
12+src/bot_theme_plugin.h in their place, so the theme can never drift out of
13+sync with the rest of the bot.
14+
15+ python3 tools/gen_ui.py # write src/ui.html.h
16+ python3 tools/gen_ui.py --check # exit 1 when the header is stale
17+"""
18+
19+import os
20+import sys
21+
22+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23+SRC = os.path.join(ROOT, "src", "ui.html")
24+OUT = os.path.join(ROOT, "src", "ui_html.h")
25+
26+TOKENS = "<!--TOKENS-->"
27+MARK_TOKENS = "\u0001"
28+MARK_HANDOFF = "\u0002"
29+
30+
31+def c_literal(text):
32+ """Escape text for a C string literal, one line per source line."""
33+ out = []
34+ for line in text.splitlines(True):
35+ piece = []
36+ for ch in line:
37+ if ch == "\\":
38+ piece.append("\\\\")
39+ elif ch == '"':
40+ piece.append('\\"')
41+ elif ch == "\n":
42+ piece.append("\\n")
43+ elif ch == "\r":
44+ piece.append("\\r")
45+ elif ch == "\t":
46+ piece.append("\\t")
47+ elif ch == MARK_TOKENS:
48+ piece.append("\\001")
49+ elif ch == MARK_HANDOFF:
50+ piece.append("\\002")
51+ elif ord(ch) < 0x20:
52+ piece.append("\\%03o" % ord(ch))
53+ else:
54+ piece.append(ch)
55+ out.append(' "%s"\n' % "".join(piece))
56+ return "".join(out)
57+
58+
59+def render():
60+ with open(SRC, "r", encoding="utf-8") as f:
61+ html = f.read()
62+
63+ if TOKENS not in html:
64+ raise SystemExit("src/ui.html has no %s placeholder" % TOKENS)
65+ html = html.replace(TOKENS, MARK_TOKENS)
66+
67+ # Handoff script goes right before the closing body tag.
68+ if "</body>" not in html:
69+ raise SystemExit("src/ui.html has no </body>")
70+ html = html.replace("</body>", MARK_HANDOFF + "</body>", 1)
71+
72+ header = (
73+ "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n"
74+ "#ifndef SX_AGYLOGIN_UI_HTML_H\n"
75+ "#define SX_AGYLOGIN_UI_HTML_H\n"
76+ "\n"
77+ "static const char *UI_HTML =\n" + c_literal(html) + " ;\n"
78+ "\n"
79+ "#endif /* SX_AGYLOGIN_UI_HTML_H */\n"
80+ )
81+ return header
82+
83+
84+def main():
85+ header = render()
86+ check = "--check" in sys.argv[1:]
87+ if check:
88+ try:
89+ with open(OUT, "r", encoding="utf-8") as f:
90+ cur = f.read()
91+ except OSError:
92+ cur = ""
93+ if cur != header:
94+ sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n")
95+ return 1
96+ print("src/ui.html.h is up to date")
97+ return 0
98+ with open(OUT, "w", encoding="utf-8") as f:
99+ f.write(header)
100+ print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header)))
101+ return 0
102+
103+
104+if __name__ == "__main__":
105+ sys.exit(main())
0106
.gitignore+16−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..acf9bd5index 0000000..acf9bd5
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,16 @@@@ -0,0 +1,16 @@
1+# build artifacts
2+/plugin_antigravity_login
3+/plugin_antigravity_login.exe
4+/plugin_antigravity_login.musl
5+/plugin_antigravity_login.arm64
6+/plugin_antigravity_login.macos-arm64
7+/plugin_antigravity_login.macos-x86_64
8+bin/
9+
10+# test scratch
11+*.tmp
12+/tests/fixtures-out/
13+
14+# python tooling
15+__pycache__/
16+*.pyc
LICENSE+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ef80120index 0000000..ef80120
--- /dev/null--- /dev/null
+++ b/LICENSE+++ b/LICENSE
@@ -0,0 +1,21 @@@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+80−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..7f204b4index 0000000..7f204b4
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,80 @@@@ -0,0 +1,80 @@
1+# plugin_antigravity_login - SCORPIOX BOT open-source Google Antigravity login for your node
2+#
3+# Targets:
4+# make native build -> ./plugin_antigravity_login
5+# make musl static musl x86_64 -> ./plugin_antigravity_login.musl
6+# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_antigravity_login.arm64
7+# make win64 MinGW-w64 static -> ./plugin_antigravity_login.exe
8+# make macos Apple clang -> ./plugin_antigravity_login (run this on macOS)
9+# make ui regenerate src/ui_html.h from src/ui.html
10+# make test build + run tests/run.sh
11+# make e2e build + run tests/e2e.py (Playwright)
12+# make clean
13+
14+CC ?= cc
15+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src
16+MUSL_CC ?= musl-gcc
17+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static
18+ARM_CC ?= aarch64-linux-gnu-gcc
19+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static
20+WIN_CC ?= x86_64-w64-mingw32-gcc
21+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static
22+SRC := src/plugin_antigravity_login.c
23+UI_SRC := src/ui.html
24+UI_HDR := src/ui_html.h
25+BIN := plugin_antigravity_login
26+EXE := plugin_antigravity_login.exe
27+
28+.PHONY: all native musl arm64 win64 macos ui test e2e clean help
29+
30+all: native
31+
32+$(UI_HDR): $(UI_SRC) tools/gen_ui.py
33+ @echo "==> regenerating $(UI_HDR)"
34+ python3 tools/gen_ui.py
35+
36+ui: $(UI_HDR)
37+
38+native: $(BIN)
39+
40+$(BIN): $(SRC) $(UI_HDR)
41+ @echo "==> native build ($(CC))"
42+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
43+
44+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
45+musl: $(SRC) $(UI_HDR)
46+ @echo "==> static musl build ($(MUSL_CC))"
47+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
48+
49+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
50+arm64: $(SRC) $(UI_HDR)
51+ @echo "==> static arm64 build ($(ARM_CC))"
52+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
53+
54+# Native Win64 static PE - runs on any Windows 10/11 x64 node
55+win64: $(SRC) $(UI_HDR)
56+ @echo "==> MinGW-w64 build ($(WIN_CC))"
57+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
58+
59+# Apple clang build (run this on macOS)
60+macos: $(SRC) $(UI_HDR)
61+ @echo "==> Apple clang build"
62+ clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o $(BIN) $(SRC)
63+
64+install: $(BIN)
65+ @dest="$${HOME}/.scorpiox/plugins"; [ -d /workspace ] && dest="/workspace/.scorpiox/plugins"; \
66+ mkdir -p "$$dest" && cp $(BIN) "$$dest/$(BIN)" && chmod 0755 "$$dest/$(BIN)" && \
67+ echo "==> installed $$dest/$(BIN)"
68+
69+test: $(BIN)
70+ sh tests/run.sh
71+
72+e2e: $(BIN)
73+ python3 tests/e2e.py
74+
75+clean:
76+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64
77+ rm -rf tests/__pycache__
78+
79+help:
80+ @sed -n '2,16p' $(MAKEFILE_LIST)
README.md+258−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..3c3161aindex 0000000..3c3161a
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,258 @@@@ -0,0 +1,258 @@
1+# plugin_antigravity_login — Google Antigravity login for SCORPIOX BOT
2+
3+`plugin_antigravity_login` is a **zero-dependency C99 node plugin** for
4+[SCORPIOX BOT](https://bot.scorpiox.net). It drives a Google **OAuth 2.0 PKCE**
5+login for **Google Antigravity** on the node it runs on: start the flow, paste
6+the authorization code, run the exchange and the Google Cloud companion‑project
7+discovery, then read the session state, token expiry and project — and refresh
8+the token on demand.
9+
10+* `--meta` → `{"name":"google","desc":"Google login"}`
11+* `--version` → `plugin_antigravity_login 1.0.0`
12+* Catalog slug `antigravity-login`, category `devtools`
13+* Public source: <https://plugingit.scorpiox.net/scorpiox-bot-plugin-antigravity-login.git>
14+* Prebuilt binaries: <https://dist.scorpiox.net/bot-plugins/antigravity-login/>
15+
16+Two ways to consume it, both first-class:
17+
18+| Track | What you get |
19+|---|---|
20+| **Source** | `git clone` the repo above, read one C file, compile it on your node in a second, install to `~/.scorpiox/plugins/`. No dependency, no build system beyond `cc`. |
21+| **Prebuilt** | a static binary per platform at `dist.scorpiox.net/bot-plugins/antigravity-login/1.0.0/`, with `manifest.json`, `SHA256SUMS` and the exact `source.tar.gz`. |
22+
23+---
24+
25+## Why this plugin has no TLS code and no client secret
26+
27+A PKCE code exchange is an HTTPS POST that carries an OAuth client identity. A
28+public, clean-room repository cannot ship a client secret, and a plugin that
29+re-implemented TLS would be a liability on every node.
30+
31+So this plugin does what SCORPIOX CODE already designed its login tools for: it
32+**drives the machine-mode CLI** that ships with the product.
33+
34+```
35+plugin_antigravity_login --popen--> scorpiox-antigravity-login --status
36+ --start
37+ --finish <code>
38+ --cancel
39+ --popen--> scorpiox-google-fetchtoken -local
40+```
41+
42+Machine mode is the contract documented in `sx_login_machine.h`: one JSON line
43+per call, human progress on stderr/stdout before it, no TTY required. The plugin
44+takes the **last** line that starts with `{`, so the parsers are exercised
45+against the production layout rather than an invented one.
46+
47+The plugin reads (and never writes):
48+
49+| Path | What it is used for |
50+|---|---|
51+| `~/.config/google-accounts/antigravity_accounts.json` | account list + `refresh_token` **presence** |
52+| `~/.config/google-accounts/selected_account.txt` | the active Google account |
53+| `~/.claude/scorpiox-env/antigravity.txt` | `GOOGLE_PROJECT_ID`, `GOOGLE_ACCOUNT` |
54+| `~/.claude/.login-pending/antigravity-default.json` | the pending-flow marker |
55+
56+**No token is ever printed, logged or returned.** `action=status` reports
57+`has_refresh` (a boolean), `expires_at` and `expires_in_sec`. `action=refresh`
58+reports `refreshed: true` and the expiry — the access token the CLI prints is
59+read for presence and discarded, so a browser, a proxy log or a screenshot can
60+never capture a bearer token from this route. The test suite asserts that: a mock
61+token CLI prints `ya29.MOCK-ACCESS-TOKEN-MUST-NOT-LEAK` and the suite fails if the
62+string appears in any response.
63+
64+---
65+
66+## Requirements on the node
67+
68+| Platform | Needs |
69+|---|---|
70+| Linux / macOS | `scorpiox-antigravity-login` and `scorpiox-google-fetchtoken` on `PATH` (both ship with SCORPIOX CODE) |
71+| Windows | the same two binaries in `%PATH%` |
72+| any | nothing else — the plugin has **zero** library dependencies |
73+
74+If the CLIs are absent the plugin still serves the UI and answers `action=status`
75+`cli_present:false` with a clear message, so a node without SCORPIOX CODE does not
76+show a broken panel.
77+
78+---
79+
80+## Environment overrides (all optional, all for testing or relocation)
81+
82+| Variable | Effect |
83+|---|---|
84+| `ANTIGRAVITY_CREDS_PATH` | the accounts JSON. Its directory also anchors `selected_account.txt` and the profile dir, so a relocated install stays self-consistent. |
85+| `ANTIGRAVITY_ENV_DIR` | the profile directory (default `~/.claude/scorpiox-env`) |
86+| `ANTIGRAVITY_PENDING_PATH` | the pending-flow marker |
87+| `ANTIGRAVITY_LOGIN_BIN` | the login CLI (default `scorpiox-antigravity-login`) |
88+| `ANTIGRAVITY_TOKEN_BIN` | the token CLI (default `scorpiox-google-fetchtoken`) |
89+| `BOT_PASSWORD` | when set, every route except `--meta` requires it |
90+
91+---
92+
93+## API
94+
95+All actions are `GET` (or `POST` for `finish`) against the plugin route, with the
96+node password supplied as `X-Bot-Password`, `Authorization: Bearer` or `?pwd=`.
97+
98+### `?action=status` (also `?format=json`)
99+
100+```json
101+{
102+ "ok": true,
103+ "plugin": "plugin_antigravity_login",
104+ "version": "1.0.0",
105+ "logged_in": true,
106+ "email": "someone@example.com",
107+ "account": "someone@example.com",
108+ "project_id": "proj-mock-42",
109+ "profile": "antigravity",
110+ "expires_at": 1790000000,
111+ "expires_in_sec": 3599,
112+ "expired": false,
113+ "has_refresh": true,
114+ "pending": false,
115+ "cli_present": true,
116+ "credentials_path": "/root/.config/google-accounts/antigravity_accounts.json"
117+}
118+```
119+
120+`expires_at` is unix **seconds** (the CLI's millisecond value is normalised).
121+`expired` is only ever true for a session that exists.
122+
123+### `?action=start`
124+
125+```json
126+{
127+ "ok": true,
128+ "flow": "paste_code",
129+ "auth_url": "https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=...&code_challenge=...&code_challenge_method=S256&...",
130+ "expires_in": 900,
131+ "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."
132+}
133+```
134+
135+The PKCE verifier lives in the CLI's pending file (mode 0600). The plugin never
136+sees it and never needs it.
137+
138+### `?action=finish&code=...` (or a POST body `{"code":"..."}`)
139+
140+Accepts a bare code **or** the whole `https://antigravity.google/oauth-callback?...`
141+address; the `code=` value is extracted before validation. On success the
142+response is the full status object with `"state":"done"`.
143+
144+Rejected before anything runs (the code is passed to a shell, so this is a real
145+guard, not a formality):
146+
147+```json
148+{"ok":false,"error":"invalid_code","detail":"the value is not an authorization code (empty, too long, or contains shell characters)"}
149+```
150+
151+Shell metacharacters, quotes, backticks, `$`, `;`, `|`, `&`, `<`, `>` and control
152+bytes are refused; the argument is also single-quoted with the `'\''` escape, and
153+the test suite proves a `$(touch /tmp/pwned)` payload creates no file.
154+
155+### `?action=cancel`
156+
157+```json
158+{"ok": true, "state": "cancelled", "pending": false}
159+```
160+
161+### `?action=refresh`
162+
163+Runs `scorpiox-google-fetchtoken -local`, reports success and the new expiry, and
164+**drops the token**:
165+
166+```json
167+{"ok": true, "refreshed": true, "logged_in": true, "email": "...", "project_id": "...", "expires_in_sec": 3599, ...}
168+```
169+
170+Failure is structured, never a stack trace:
171+
172+```json
173+{"ok": false, "error": "refresh_failed", "detail": "the token CLI could not refresh the session; sign in again"}
174+```
175+
176+### Errors
177+
178+| Error | HTTP | Meaning |
179+|---|---|---|
180+| `invalid node password` | 401 | `BOT_PASSWORD` is set and no credential matched |
181+| `missing_code` | 400 | `finish` without a code |
182+| `invalid_code` | 400 | the value cannot be an authorization code |
183+| `unknown_action` | 404 | unrecognised `action=` |
184+| `cli_unavailable` | 200 | the login/token CLI is not on this node |
185+| `exchange` / `finish_failed` | 200 | Google rejected the code, or the account needs verification |
186+
187+---
188+
189+## The UI
190+
191+One page, no framework, no CDN, no `<script src=>`, no external request of any
192+kind. It follows the bot's theme through the standard handoff:
193+
194+1. `?theme=light|dark` → `localStorage.bot_theme` → `prefers-color-scheme`,
195+ decided **before first paint** (no flash),
196+2. then it follows `{type:'sx-theme'}` posts from the bot and asks once with
197+ `{type:'sx-theme-request'}`,
198+3. every colour is a bot token from `src/bot_theme_plugin.h` — there is no
199+ plugin-private palette.
200+
201+Layout: a status pill (`Connected` / `Expired` / `Signing in` / `Not Connected`),
202+a session card, an OAuth card with the generated link and a paste box, and a
203+companion-project card. Fluid down to 390 px and inside the Chat floating window
204+(`?embed=1` hides the theme button).
205+
206+---
207+
208+## Build
209+
210+```sh
211+make # native
212+make musl # static x86_64 musl (the universal Linux artifact)
213+make arm64 # static aarch64 (Raspberry Pi 5, ARM servers)
214+make win64 # MinGW-w64 static PE
215+make macos # Apple clang (run on macOS)
216+make test # the offline suite
217+make install # ~/.scorpiox/plugins (or /workspace/.scorpiox/plugins)
218+```
219+
220+`src/ui_html.h` is generated from `src/ui.html` by `tools/gen_ui.py`; `make ui`
221+(or the `$(UI_HDR)` dependency) regenerates it, and `tools/gen_ui.py --check`
222+fails when the header is stale.
223+
224+Windows: `powershell -ExecutionPolicy Bypass -File build.ps1`.
225+
226+---
227+
228+## Release
229+
230+```sh
231+scorpiox-cli-botplugin publish . # preferred: scan, build, upload, mirror, reindex
232+./release-dist.sh --standalone # the same, self-contained
233+```
234+
235+Both refuse to publish a repo whose **full history** contains a credential, a
236+private address or an internal hostname. The standalone script needs
237+`DIST_HOST`/`DIST_PASS` (dist) and `SSHPASS` (macOS leg) in the environment and
238+reads the plugingit write token from `/etc/scorpiox-plugingit.token` — no secret
239+is ever stored in this repository.
240+
241+---
242+
243+## Layout
244+
245+```
246+src/plugin_antigravity_login.c the whole plugin (3 modes, ~1.2k lines)
247+src/ui.html the page, readable and diffable
248+src/ui_html.h generated by tools/gen_ui.py
249+src/bot_theme_plugin.h the bot's theme tokens, vendored
250+tests/run.sh the offline suite (mock CLIs, fixtures)
251+tests/mock_login.sh stand-in for scorpiox-antigravity-login machine mode
252+tests/mock_token.sh stand-in for scorpiox-google-fetchtoken -local
253+tools/gen_ui.py ui.html -> ui_html.h
254+```
255+
256+## License
257+
258+MIT. Copyright (c) 2026 SCORPIOX INC.
build.ps1+51−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..06453dfindex 0000000..06453df
--- /dev/null--- /dev/null
+++ b/build.ps1+++ b/build.ps1
@@ -0,0 +1,51 @@@@ -0,0 +1,51 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_antigravity_login
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_antigravity_login.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+
9+$ErrorActionPreference = "Stop"
10+$ScriptDir = $PSScriptRoot
11+Push-Location $ScriptDir
12+try {
13+ $Src = Join-Path $ScriptDir "src\plugin_antigravity_login.c"
14+ $Out = Join-Path $ScriptDir "plugin_antigravity_login.exe"
15+ $Cc = "x86_64-w64-mingw32-gcc"
16+
17+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
18+
19+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
20+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
21+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
22+ $Cc = "C:\gcc16\bin\gcc.exe"
23+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
24+ $Cc = "gcc"
25+ } else {
26+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
27+ }
28+ }
29+
30+ # Regenerate the page header so the binary always matches src/ui.html.
31+ if (Get-Command python -ErrorAction SilentlyContinue) {
32+ python tools\gen_ui.py
33+ }
34+
35+ Write-Host "==> building plugin_antigravity_login.exe with $Cc"
36+ & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src
37+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
38+
39+ if (-not (Test-Path $Out)) { throw "build produced no output" }
40+
41+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
42+ $bytes = [System.IO.File]::ReadAllBytes($Out)
43+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
44+ throw "output is not a PE executable (missing MZ header)"
45+ }
46+
47+ Write-Host "==> ok: $Out ($($bytes.Length) bytes)"
48+ Write-Host " smoke test: .\plugin_antigravity_login.exe --meta"
49+} finally {
50+ Pop-Location
51+}
plugin.json+16−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..69f71d5index 0000000..69f71d5
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,16 @@@@ -0,0 +1,16 @@
1+{
2+ "slug": "antigravity-login",
3+ "id": "plugin_antigravity_login",
4+ "title": "Google Antigravity Login",
5+ "summary": "Zero-dependency Google Antigravity OAuth 2.0 PKCE login and companion-project manager for your node. Starts the PKCE flow, takes the pasted authorization code, runs the exchange and the Google Cloud project discovery through the node's own login CLI, then reports session state, token expiry and the companion project - and refreshes the token on demand. The plugin holds no OAuth client secret and never prints, logs or returns a token: it drives the CLI that ships with SCORPIOX CODE and reads only the credential and profile files that CLI writes.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "capabilities": [
9+ "spawn_login_cli",
10+ "read_credentials_metadata",
11+ "network_via_login_cli"
12+ ],
13+ "trust_notice": "Executes native C code on your node. It runs scorpiox-antigravity-login and scorpiox-google-fetchtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to Google over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only ~/.config/google-accounts/antigravity_accounts.json, selected_account.txt, ~/.claude/.login-pending/ and ~/.claude/scorpiox-env/antigravity.txt, and every response reports token presence and expiry only - never a token value.",
14+ "author": "SCORPIOX INC",
15+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-antigravity-login"
16+}
release-dist.sh+365−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..5c9b2fbindex 0000000..5c9b2fb
--- /dev/null--- /dev/null
+++ b/release-dist.sh+++ b/release-dist.sh
@@ -0,0 +1,365 @@@@ -0,0 +1,365 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_antigravity_login to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+# ./release-dist.sh --standalone # use this script even if the CLI is installed
27+# # (needed for plugins that link extra Win32 libs,
28+# # which the CLI's fixed link line cannot express)
29+
30+set -euo pipefail
31+
32+SLUG="antigravity-login"
33+ID="plugin_antigravity_login"
34+VERSION="1.0.0"
35+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --standalone) STANDALONE=1 ;;
47+ --dry-run) DRY_RUN=1 ;;
48+ --no-macos) DO_MACOS=0 ;;
49+ --no-mirror) DO_MIRROR=0 ;;
50+ -h|--help) sed -n '2,32p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition - otherwise this file's own detector patterns (and the
90+# test suite's identical checks) read as findings in every historical revision of
91+# them. A real secret on any other line still hits.
92+git log -p --all 2>/dev/null \
93+ | grep -v '^Author: ' \
94+ | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \
95+ > "$SCAN_TMP" || : > "$SCAN_TMP"
96+HITS=0
97+scan() { # scan <label> <regex>
98+ local out
99+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
100+ if [ -n "$out" ]; then
101+ printf ' \033[31mHIT\033[0m %s\n' "$1"
102+ printf '%s\n' "$out" | sed 's/^/ /'
103+ HITS=$((HITS + 1))
104+ else
105+ printf ' ok %s\n' "$1"
106+ fi
107+}
108+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
109+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
110+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
111+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
112+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
113+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
114+scan "hard-coded ssh password" 'sshpass -p [^"$]'
115+P_ROOT="/codebases"
116+P_PICOBOT="${P_ROOT}/pico""bot"
117+P_WT=".work""trees"
118+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
119+scan "run-token env assignment" 'RUNNER_'"PASS="
120+if [ "$HITS" -ne 0 ]; then
121+ die "secret scan found $HITS problem(s) - refusing to publish"
122+fi
123+echo " clean: 0 hits"
124+
125+# ---------------------------------------------------------------- 2. build
126+say "2/7 build targets"
127+
128+# linux-x86_64 (glibc, native)
129+if command -v cc >/dev/null 2>&1; then
130+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed"
131+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
132+else
133+ die "no native cc found"
134+fi
135+
136+# linux-x86_64-musl (fully static - the universal Linux artifact)
137+if command -v musl-gcc >/dev/null 2>&1; then
138+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \
139+ || die "musl build failed"
140+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
141+else
142+ echo " skip linux-x86_64-musl (no musl-gcc)"
143+fi
144+
145+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
146+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
147+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \
148+ || die "arm64 build failed"
149+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
150+else
151+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
152+fi
153+
154+# windows-x86_64 (static PE)
155+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
156+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \
157+ -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
158+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
159+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
160+else
161+ echo " skip windows-x86_64 (no MinGW cross compiler)"
162+fi
163+
164+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
165+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
166+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
167+ MAC_USER="${MAC_USER:-$(whoami)}"
168+ MAC_DIR="/tmp/${ID}-mac-$$"
169+ echo " building macOS legs on $MAC_HOST"
170+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
171+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
172+ if [ -n "${MAC_PASS:-}" ]; then
173+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
174+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
175+ fi
176+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
177+ tar -czf "$STAGE/src.tgz" src
178+ if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
179+ && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then
180+ # Build straight from the uploaded file - no src/ tree on the remote.
181+ for slice in arm64 x86_64; do
182+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
183+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \
184+ 2>/dev/null; then
185+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
186+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
187+ else
188+ echo " warn: macos-$slice build failed on $MAC_HOST"
189+ fi
190+ done
191+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
192+ else
193+ echo " warn: could not upload source to $MAC_HOST"
194+ fi
195+ else
196+ echo " warn: cannot reach macOS builder $MAC_HOST"
197+ fi
198+else
199+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
200+fi
201+
202+# ---------------------------------------------------------------- 3. manifest
203+say "3/7 manifest + checksums"
204+
205+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
206+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
207+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
208+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
209+
210+target_meta() { # target_meta <key> <file> <format> <relpath>
211+ local key="$1" file="$2" fmt="$3" rel="$4"
212+ [ -f "$file" ] || return 0
213+ local sha size
214+ sha=$(sha256sum "$file" | awk '{print $1}')
215+ size=$(wc -c < "$file" | tr -d ' ')
216+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
217+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
218+}
219+
220+{
221+ printf '{\n'
222+ printf ' "slug": "%s",\n' "$SLUG"
223+ printf ' "id": "%s",\n' "$ID"
224+ printf ' "name": "google",\n'
225+ printf ' "desc": "Google login",\n'
226+ printf ' "title": "Google Antigravity Login",\n'
227+ printf ' "summary": "Zero-dependency Google Antigravity OAuth 2.0 PKCE login and companion-project manager for your node. Starts the PKCE flow, takes the pasted authorization code, runs the exchange and the Google Cloud project discovery through the node own login CLI, then reports session state, token expiry and the companion project - and refreshes the token on demand. The plugin holds no OAuth client secret and never prints, logs or returns a token: it drives the CLI that ships with SCORPIOX CODE and reads only the credential and profile files that CLI writes.",\n'
228+ printf ' "category": "devtools",\n'
229+ printf ' "version": "%s",\n' "$VERSION"
230+ printf ' "license": "MIT",\n'
231+ printf ' "trust_notice": "Executes native C code on your node. It runs scorpiox-antigravity-login and scorpiox-google-fetchtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to Google over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only the Antigravity credential file, selected_account.txt, the login-pending marker and the antigravity profile, and every response reports token presence and expiry only - never a token value.",\n'
232+ printf ' "capabilities": ["spawn_login_cli", "read_credentials_metadata", "network_via_login_cli"],\n'
233+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
234+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
235+ printf ' "git_commit": "%s",\n' "$COMMIT"
236+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
237+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
238+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
239+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
240+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
241+ printf ' "targets": {\n'
242+ first=1
243+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
244+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
245+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
246+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
247+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
248+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
249+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
250+ printf '\n }\n}\n'
251+} > "$STAGE/manifest.json"
252+
253+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
254+ || die "generated manifest.json is not valid JSON"
255+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
256+
257+# SHA256SUMS - relative paths, exactly as published
258+( cd "$STAGE"
259+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
260+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
261+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
262+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
263+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
264+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
265+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
266+ true ) > "$STAGE/SHA256SUMS"
267+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
268+
269+# ---------------------------------------------------------------- 4. stage
270+say "4/7 stage tree"
271+PKG="$STAGE/pkg"
272+mkdir -p "$PKG"
273+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
274+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
275+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
276+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
277+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
278+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
279+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
280+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
281+
282+if [ "$DRY_RUN" -eq 1 ]; then
283+ say "dry run - leaving the staging tree in $PKG"
284+ trap - EXIT
285+ exit 0
286+fi
287+
288+# ---------------------------------------------------------------- 5. upload
289+say "5/7 upload to the dist server"
290+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
291+SSH=(ssh -o StrictHostKeyChecking=no)
292+SCP=(scp -o StrictHostKeyChecking=no)
293+if [ -n "$DIST_PASS" ]; then
294+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
295+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
296+fi
297+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
298+
299+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
300+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
301+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
302+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
303+# OpenSSH 9 refuses to scp a bare "." source.
304+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
305+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
306+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
307+ || die "remote extract failed"
308+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
309+
310+# latest.json = copy of this version's manifest
311+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
312+ || die "latest.json update failed"
313+echo " updated bot-plugins/$SLUG/latest.json"
314+
315+# index.json - merge, preserving every sibling <slug>/latest.json
316+say "index.json merge"
317+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
318+import json, os, sys, glob
319+slug = sys.argv[1]
320+entries = {}
321+for p in sorted(glob.glob('*/latest.json')):
322+ s = os.path.dirname(p)
323+ try:
324+ entries[s] = json.load(open(p))
325+ except Exception:
326+ pass
327+index = {
328+ 'ok': True,
329+ 'service': 'bot-plugins-dist',
330+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
331+ 'count': len(entries),
332+ 'slugs': sorted(entries),
333+ 'plugins': [entries[k] for k in sorted(entries)],
334+}
335+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
336+os.replace('index.json.tmp', 'index.json')
337+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
338+PY" || die "index.json merge failed"
339+
340+# ---------------------------------------------------------------- 6. mirror
341+say "6/7 plugingit mirror"
342+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
343+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
344+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
345+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
346+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
347+ echo " mirrored to $PLUGINGIT_REMOTE"
348+else
349+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
350+fi
351+
352+# ---------------------------------------------------------------- 7. verify
353+say "7/7 verify"
354+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
355+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
356+if [ "$CODE" = "200" ]; then
357+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
358+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
359+else
360+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
361+fi
362+
363+printf '\n\033[1mrelease complete\033[0m\n'
364+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
365+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/bot_theme_plugin.h+129−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0dd243bindex 0000000..0dd243b
--- /dev/null--- /dev/null
+++ b/src/bot_theme_plugin.h+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/plugin_antigravity_login.c+1327−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..d1ebea0index 0000000..d1ebea0
--- /dev/null--- /dev/null
+++ b/src/plugin_antigravity_login.c+++ b/src/plugin_antigravity_login.c
@@ -0,0 +1,1327 @@@@ -0,0 +1,1327 @@
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.0"
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+ int expires_in_sec; /* negative when expired, 0 when unknown */
732+} status_t;
733+
734+/* Pull email / refresh_token presence out of the accounts array.
735+ *
736+ * The file is a JSON array of {email, refresh_token}. The selected account
737+ * wins; otherwise the first entry that carries a refresh token. Presence of a
738+ * refresh token is the login signal, and only its presence is recorded - the
739+ * value is never copied. */
740+static void scan_accounts(const char *json, const char *selected, status_t *st)
741+{
742+ const char *p = json;
743+ char first_email[EMAIL_SZ] = {0};
744+ int first_has = 0;
745+ int found = 0;
746+
747+ while (p && *p) {
748+ const char *open = strchr(p, '{');
749+ const char *obj;
750+ const char *end;
751+ char email[EMAIL_SZ] = {0};
752+ char rt[8] = {0};
753+ int has_rt;
754+
755+ if (!open) break;
756+ end = json_skip_value(open);
757+ if (!end || end <= open) break;
758+ /* json_find_key tracks brace depth, so it must start INSIDE the
759+ * object: passing the opening '{' makes every top-level key look
760+ * nested and the whole scan silently returns nothing. */
761+ obj = open;
762+
763+ json_str_field(obj, end, "email", email, sizeof(email));
764+ has_rt = json_str_field(obj, end, "refresh_token", rt, sizeof(rt));
765+
766+ if (!first_email[0] && email[0]) {
767+ snprintf(first_email, sizeof(first_email), "%s", email);
768+ first_has = has_rt;
769+ }
770+ if (selected && selected[0] && email[0] && strcmp(email, selected) == 0) {
771+ snprintf(st->email, sizeof(st->email), "%s", email);
772+ st->has_refresh = has_rt;
773+ found = 1;
774+ p = end;
775+ break;
776+ }
777+ p = end;
778+ }
779+
780+ if (!found) {
781+ if (first_email[0]) snprintf(st->email, sizeof(st->email), "%s", first_email);
782+ st->has_refresh = first_has;
783+ }
784+ st->logged_in = st->has_refresh;
785+}
786+
787+/* Parse GOOGLE_PROJECT_ID / GOOGLE_ACCOUNT out of the profile file. */
788+static void scan_profile(const char *text, status_t *st)
789+{
790+ const char *p = text;
791+
792+ while (p && *p) {
793+ const char *nl = strchr(p, '\n');
794+ size_t len = nl ? (size_t)(nl - p) : strlen(p);
795+ char line[FIELD_SZ];
796+ size_t i;
797+
798+ if (len > 0 && len < sizeof(line)) {
799+ memcpy(line, p, len);
800+ line[len] = '\0';
801+ trim_tail(line);
802+ for (i = 0; line[i]; i++)
803+ if (line[i] == '\r') line[i] = ' ';
804+ if (strncmp(line, "GOOGLE_PROJECT_ID=", 18) == 0 && !st->project[0]) {
805+ snprintf(st->project, sizeof(st->project), "%.*s", (int)sizeof(st->project) - 1, line + 18);
806+ } else if (strncmp(line, "GOOGLE_ACCOUNT=", 15) == 0 && !st->account[0]) {
807+ snprintf(st->account, sizeof(st->account), "%.*s", (int)sizeof(st->account) - 1, line + 15);
808+ }
809+ }
810+ if (!nl) break;
811+ p = nl + 1;
812+ }
813+}
814+
815+static void collect_status(status_t *st)
816+{
817+ char acct[PATH_SZ], sel[PATH_SZ], prof[PATH_SZ], pend[PATH_SZ];
818+ char *text;
819+ char selected[EMAIL_SZ] = {0};
820+ long long now = (long long)time(NULL);
821+
822+ memset(st, 0, sizeof(*st));
823+ st->profile[0] = '\0';
824+
825+ creds_path(acct, sizeof(acct));
826+ snprintf(st->path, sizeof(st->path), "%s", acct);
827+
828+ creds_sibling("selected_account.txt", sel, sizeof(sel));
829+ text = read_file(sel);
830+ if (text) {
831+ trim_tail(text);
832+ snprintf(selected, sizeof(selected), "%s", text);
833+ free(text);
834+ }
835+
836+ text = read_file(acct);
837+ if (text) {
838+ scan_accounts(text, selected, st);
839+ free(text);
840+ }
841+
842+ /* The profile file carries the companion project and the account email. */
843+ env_dir(prof, sizeof(prof));
844+ {
845+ char pfile[PATH_SZ + 32];
846+ char *ptext;
847+ if (strlen(prof) + 16 < sizeof(pfile))
848+ snprintf(pfile, sizeof(pfile), "%s%cantigravity.txt", prof, PATH_SEP);
849+ else
850+ snprintf(pfile, sizeof(pfile), "antigravity.txt");
851+ ptext = read_file(pfile);
852+ if (ptext) {
853+ scan_profile(ptext, st);
854+ snprintf(st->profile, sizeof(st->profile), "antigravity");
855+ free(ptext);
856+ }
857+ }
858+
859+ if (!st->email[0] && st->account[0])
860+ snprintf(st->email, sizeof(st->email), "%s", st->account);
861+ if (!st->account[0] && st->email[0])
862+ snprintf(st->account, sizeof(st->account), "%s", st->email);
863+
864+ /* Pending flow marker (the CLI writes and removes this file). */
865+ pending_path(pend, sizeof(pend));
866+ st->pending = file_exists(pend);
867+
868+ /* Ask the CLI when it is on PATH: it knows the token expiry and the exact
869+ * pending state, and it is the authority on logged_in. The plugin never
870+ * becomes the source of truth about a Google session. */
871+ {
872+ buf_t out;
873+ buf_init(&out);
874+ if (run_capture(login_bin(), "--status", &out) > 0) {
875+ const char *j = last_json_line(&out);
876+ if (j) {
877+ const char *end = j + strlen(j);
878+ char identity[EMAIL_SZ] = {0};
879+ long long exp = 0;
880+
881+ st->cli_present = 1;
882+ json_str_field(j, end, "identity", identity, sizeof(identity));
883+ json_str_field(j, end, "path", st->path, sizeof(st->path));
884+ /* The CLI is authoritative, but never a downgrade: if the
885+ * credential file on disk carries a refresh token, the node IS
886+ * signed in and an older CLI build that answers logged_in:false
887+ * must not paint a green session grey. */
888+ if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1;
889+ if (json_bool_field(j, end, "has_refresh", 0)) { st->has_refresh = 1; st->logged_in = 1; }
890+ /* pending: the marker file is the authority (it is created by
891+ * --start and removed by --finish/--cancel), so a CLI answer is
892+ * only allowed to ADD a pending state, never to clear one. */
893+ if (json_bool_field(j, end, "pending", 0)) st->pending = 1;
894+ exp = json_num_field(j, end, "expires_at");
895+ if (exp > 0 && exp < 100000000000LL) exp *= 1000; /* seconds -> ms */
896+ if (exp > 0) st->expires_at = exp / 1000;
897+ if (identity[0] && !st->email[0])
898+ snprintf(st->email, sizeof(st->email), "%s", identity);
899+ if (identity[0] && !st->account[0])
900+ snprintf(st->account, sizeof(st->account), "%s", identity);
901+ }
902+ }
903+ buf_free(&out);
904+ }
905+
906+ if (st->expires_at > 0) {
907+ st->expires_in_sec = (int)(st->expires_at - now);
908+ st->expired = st->expires_at <= now;
909+ }
910+ if (!st->logged_in) {
911+ st->expired = 0;
912+ st->expires_in_sec = 0;
913+ }
914+}
915+
916+/* One status object. Shared by every action's response so the UI can always
917+ * re-render from the same shape. */
918+static void emit_status(buf_t *b, const status_t *st)
919+{
920+ buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false");
921+ buf_adds(b, "\"email\":");
922+ buf_json(b, st->email);
923+ buf_addf(b, ",\"account\":");
924+ buf_json(b, st->account);
925+ buf_addf(b, ",\"project_id\":");
926+ buf_json(b, st->project);
927+ buf_addf(b, ",\"profile\":");
928+ buf_json(b, st->profile);
929+ buf_addf(b, ",\"expires_at\":%lld", st->expires_at);
930+ buf_addf(b, ",\"expires_in_sec\":%d", st->expires_in_sec);
931+ buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
932+ buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
933+ buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
934+ buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false");
935+ buf_addf(b, ",\"credentials_path\":");
936+ buf_json(b, st->path);
937+}
938+
939+/* ------------------------------------------------------------------ */
940+/* Actions */
941+/* ------------------------------------------------------------------ */
942+
943+static void json_headers(void)
944+{
945+ fputs("Content-Type: application/json; charset=utf-8\r\n"
946+ "Cache-Control: no-store\r\n"
947+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
948+}
949+
950+static void emit_error(int code, const char *status, const char *err, const char *detail)
951+{
952+ buf_t b;
953+
954+ buf_init(&b);
955+ buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
956+ "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
957+ code, status);
958+ buf_addf(&b, "{\"ok\":false,\"error\":");
959+ buf_json(&b, err);
960+ if (detail && *detail) {
961+ buf_addf(&b, ",\"detail\":");
962+ buf_json(&b, detail);
963+ }
964+ buf_addf(&b, "}\n");
965+ fputs(buf_str(&b), stdout);
966+ buf_free(&b);
967+}
968+
969+static int action_status(void)
970+{
971+ status_t st;
972+ buf_t b;
973+
974+ collect_status(&st);
975+ buf_init(&b);
976+ buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",");
977+ emit_status(&b, &st);
978+ buf_adds(&b, "}\n");
979+ json_headers();
980+ fputs(buf_str(&b), stdout);
981+ buf_free(&b);
982+ return 0;
983+}
984+
985+static int action_start(void)
986+{
987+ buf_t out, b;
988+ const char *j;
989+ char auth_url[CMD_SZ] = {0};
990+ char flow[64] = {0};
991+ char hint[512] = {0};
992+ long long expires_in = 0;
993+
994+ buf_init(&out);
995+ if (run_capture(login_bin(), "--start", &out) <= 0) {
996+ buf_free(&out);
997+ emit_error(200, "OK", "cli_unavailable",
998+ "the login CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_LOGIN_BIN");
999+ return 1;
1000+ }
1001+ j = last_json_line(&out);
1002+ if (!j) {
1003+ buf_free(&out);
1004+ emit_error(200, "OK", "start_failed", buf_str(&out));
1005+ return 1;
1006+ }
1007+ {
1008+ const char *end = j + strlen(j);
1009+ json_str_field(j, end, "auth_url", auth_url, sizeof(auth_url));
1010+ json_str_field(j, end, "flow", flow, sizeof(flow));
1011+ json_str_field(j, end, "hint", hint, sizeof(hint));
1012+ expires_in = json_num_field(j, end, "expires_in");
1013+ if (!json_bool_field(j, end, "ok", 1) || !auth_url[0]) {
1014+ char detail[FIELD_SZ] = {0};
1015+ json_str_field(j, end, "error", detail, sizeof(detail));
1016+ buf_free(&out);
1017+ emit_error(200, "OK", detail[0] ? detail : "start_failed", "the login CLI did not return an authorization URL");
1018+ return 1;
1019+ }
1020+ }
1021+ buf_free(&out);
1022+
1023+ buf_init(&b);
1024+ buf_adds(&b, "{\"ok\":true,\"flow\":");
1025+ buf_json(&b, flow[0] ? flow : "paste_code");
1026+ buf_adds(&b, ",\"auth_url\":");
1027+ buf_json(&b, auth_url);
1028+ buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : 900);
1029+ buf_adds(&b, ",\"hint\":");
1030+ buf_json(&b, hint[0] ? hint
1031+ : "Sign in with Google and approve. The browser lands on antigravity.google - copy the whole address (or just the code) and paste it here.");
1032+ buf_adds(&b, "}\n");
1033+ json_headers();
1034+ fputs(buf_str(&b), stdout);
1035+ buf_free(&b);
1036+ return 0;
1037+}
1038+
1039+/* Reject anything that cannot be an authorization code. The value is passed
1040+ * to a shell, so this is the second line of defence behind shell_quote_into. */
1041+static int valid_code(const char *code)
1042+{
1043+ size_t n, i;
1044+ if (!code || !(n = strlen(code)) || n > CODE_MAX) return 0;
1045+ for (i = 0; i < n; i++) {
1046+ unsigned char c = (unsigned char)code[i];
1047+ if (c < 0x20 || c == 0x7f || c == '\'' || c == '"' || c == '\\' || c == ';' ||
1048+ c == '`' || c == '$' || c == '|' || c == '&' || c == '<' || c == '>' ||
1049+ c == '\n' || c == '\r')
1050+ return 0;
1051+ }
1052+ return 1;
1053+}
1054+
1055+static int action_finish(const char *raw_code)
1056+{
1057+ char code[CODE_MAX];
1058+ char qcode[CODE_MAX + 64];
1059+ buf_t out, b;
1060+ const char *j;
1061+
1062+ if (!raw_code) {
1063+ emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=...");
1064+ return 1;
1065+ }
1066+ snprintf(code, sizeof(code), "%s", raw_code);
1067+ url_decode(code);
1068+ trim_tail(code);
1069+
1070+ /* The user usually pastes the whole redirect address, which is what the
1071+ * login CLI expects too (its lm_clean_code does the same extraction). Pull
1072+ * out code= before validating, so a legitimate URL is not rejected for
1073+ * carrying a state= parameter alongside it. */
1074+ {
1075+ char *c = strstr(code, "code=");
1076+ if (c) {
1077+ char extracted[CODE_MAX];
1078+ size_t i = 0;
1079+ c += 5;
1080+ while (*c && *c != '&' && *c != '#' && i + 1 < sizeof(extracted))
1081+ extracted[i++] = *c++;
1082+ extracted[i] = '\0';
1083+ if (i > 0) snprintf(code, sizeof(code), "%s", extracted);
1084+ }
1085+ }
1086+ if (!valid_code(code)) {
1087+ emit_error(400, "Bad Request", "invalid_code",
1088+ "the value is not an authorization code (empty, too long, or contains shell characters)");
1089+ return 1;
1090+ }
1091+
1092+ shell_quote_into(code, qcode, sizeof(qcode));
1093+ {
1094+ char args[CODE_MAX + 128];
1095+ snprintf(args, sizeof(args), "--finish %s", qcode);
1096+ buf_init(&out);
1097+ if (run_capture(login_bin(), args, &out) <= 0) {
1098+ buf_free(&out);
1099+ emit_error(200, "OK", "cli_unavailable",
1100+ "the login CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_LOGIN_BIN");
1101+ return 1;
1102+ }
1103+ }
1104+
1105+ j = last_json_line(&out);
1106+ if (!j) {
1107+ buf_free(&out);
1108+ emit_error(200, "OK", "finish_failed", "the login CLI returned no JSON");
1109+ return 1;
1110+ }
1111+ if (!json_bool_field(j, (const char *)(j + strlen(j)), "ok", 0)) {
1112+ char detail[FIELD_SZ] = {0};
1113+ const char *end = j + strlen(j);
1114+ json_str_field(j, end, "error", detail, sizeof(detail));
1115+ buf_free(&out);
1116+ emit_error(200, "OK", detail[0] ? detail : "finish_failed",
1117+ "Google rejected the code, or the account needs verification in a browser");
1118+ return 1;
1119+ }
1120+ buf_free(&out);
1121+
1122+ /* Success: re-read everything so the caller gets the full new state. */
1123+ {
1124+ status_t st;
1125+ collect_status(&st);
1126+ buf_init(&b);
1127+ buf_adds(&b, "{\"ok\":true,\"state\":\"done\",");
1128+ emit_status(&b, &st);
1129+ buf_adds(&b, "}\n");
1130+ json_headers();
1131+ fputs(buf_str(&b), stdout);
1132+ buf_free(&b);
1133+ }
1134+ return 0;
1135+}
1136+
1137+static int action_cancel(void)
1138+{
1139+ buf_t out, b;
1140+
1141+ buf_init(&out);
1142+ run_capture(login_bin(), "--cancel", &out);
1143+ buf_free(&out);
1144+
1145+ buf_init(&b);
1146+ buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n");
1147+ json_headers();
1148+ fputs(buf_str(&b), stdout);
1149+ buf_free(&b);
1150+ return 0;
1151+}
1152+
1153+/* Refresh: the token CLI performs the refresh-token grant and prints the
1154+ * access token. We deliberately keep only ok/project and drop the token, so a
1155+ * browser (or a proxy log) can never capture a bearer token from this route. */
1156+static int action_refresh(void)
1157+{
1158+ buf_t out, b;
1159+ const char *j;
1160+ char project[PROJ_SZ] = {0};
1161+ char err[FIELD_SZ] = {0};
1162+ int ok = 0;
1163+
1164+ buf_init(&out);
1165+ if (run_capture(token_bin(), "-local", &out) <= 0) {
1166+ buf_free(&out);
1167+ emit_error(200, "OK", "cli_unavailable",
1168+ "the token CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_TOKEN_BIN");
1169+ return 1;
1170+ }
1171+ j = last_json_line(&out);
1172+ if (j) {
1173+ const char *end = j + strlen(j);
1174+ char tok[8] = {0};
1175+ ok = json_bool_field(j, end, "ok", 0);
1176+ json_str_field(j, end, "project_id", project, sizeof(project));
1177+ (void)json_str_field(j, end, "access_token", tok, sizeof(tok)); /* presence only */
1178+ if (!ok) json_str_field(j, end, "error", err, sizeof(err));
1179+ }
1180+ buf_free(&out);
1181+
1182+ if (!ok) {
1183+ buf_init(&b);
1184+ buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":");
1185+ buf_json(&b, err[0] ? err : "the token CLI could not refresh the session; sign in again");
1186+ buf_adds(&b, "}\n");
1187+ json_headers();
1188+ fputs(buf_str(&b), stdout);
1189+ buf_free(&b);
1190+ return 1;
1191+ }
1192+
1193+ {
1194+ status_t st;
1195+ collect_status(&st);
1196+ if (project[0]) snprintf(st.project, sizeof(st.project), "%s", project);
1197+ buf_init(&b);
1198+ buf_adds(&b, "{\"ok\":true,\"refreshed\":true,");
1199+ emit_status(&b, &st);
1200+ buf_adds(&b, "}\n");
1201+ json_headers();
1202+ fputs(buf_str(&b), stdout);
1203+ buf_free(&b);
1204+ }
1205+ return 0;
1206+}
1207+
1208+/* ------------------------------------------------------------------ */
1209+/* HTML emission */
1210+/* ------------------------------------------------------------------ */
1211+
1212+/* Expand the two placeholders gen_ui.py leaves in UI_HTML. Keeping this split
1213+ * means the palette lives in exactly one place (bot_theme_plugin.h) and the
1214+ * page can never drift away from the bot's own theme. */
1215+static void emit_ui(void)
1216+{
1217+ const char *p = UI_HTML;
1218+
1219+ while (*p) {
1220+ if (*p == '\001') {
1221+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1222+ p++;
1223+ } else if (*p == '\002') {
1224+ fputs(SX_BOT_THEME_HANDOFF, stdout);
1225+ p++;
1226+ } else {
1227+ putchar(*p++);
1228+ }
1229+ }
1230+}
1231+
1232+/* ------------------------------------------------------------------ */
1233+/* main */
1234+/* ------------------------------------------------------------------ */
1235+
1236+int main(int argc, char **argv)
1237+{
1238+ const char *qs;
1239+ char action[64] = {0};
1240+
1241+ /* 1. Discovery metadata. Must stay unauthenticated. */
1242+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1243+ puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1244+ return 0;
1245+ }
1246+ if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1247+ puts(PLUGIN_ID " " PLUGIN_VER);
1248+ return 0;
1249+ }
1250+
1251+ require_node_auth();
1252+
1253+ qs = getenv("QUERY_STRING");
1254+ if (!qs) qs = "";
1255+
1256+ /* 2. JSON API mode. `format=json` alone means "status", which is what a
1257+ * dashboard polls. */
1258+ if (query_has(qs, "action") || query_has(qs, "format")) {
1259+ char fmt[32] = {0};
1260+ char code[CODE_MAX] = {0};
1261+
1262+ get_query_val(qs, "action", action, sizeof(action));
1263+ get_query_val(qs, "format", fmt, sizeof(fmt));
1264+
1265+ if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status");
1266+
1267+ if (strcmp(action, "status") == 0 || !action[0]) return action_status();
1268+ if (strcmp(action, "start") == 0) return action_start();
1269+ if (strcmp(action, "cancel") == 0) return action_cancel();
1270+ if (strcmp(action, "refresh") == 0) return action_refresh();
1271+ if (strcmp(action, "finish") == 0) {
1272+ if (!get_query_val(qs, "code", code, sizeof(code))) {
1273+ char body[OUT_MAX];
1274+ size_t len = 0;
1275+
1276+ /* POST bodies carry the code too (a long code is easier to
1277+ * send as a body). Guard on CONTENT_LENGTH so an empty
1278+ * inherited stdin never blocks. */
1279+ {
1280+ const char *cl = getenv("CONTENT_LENGTH");
1281+ long n = (cl && *cl) ? atol(cl) : 0;
1282+ if (n > 0 && n < (long)sizeof(body)) {
1283+ len = fread(body, 1, (size_t)n, stdin);
1284+ body[len] = '\0';
1285+ {
1286+ char *p = strstr(body, "\"code\"");
1287+ if (p) {
1288+ p = strchr(p, ':');
1289+ if (p) {
1290+ p++;
1291+ while (*p == ' ' || *p == '\t' || *p == '"') p++;
1292+ {
1293+ size_t i = 0;
1294+ while (*p && *p != '"' && *p != ',' && *p != '}' &&
1295+ i + 1 < sizeof(code)) code[i++] = *p++;
1296+ code[i] = '\0';
1297+ }
1298+ }
1299+ }
1300+ }
1301+ }
1302+ }
1303+ if (!code[0]) {
1304+ emit_error(400, "Bad Request", "missing_code",
1305+ "pass the authorization code as &code=...");
1306+ return 1;
1307+ }
1308+ }
1309+ return action_finish(code);
1310+ }
1311+ emit_error(404, "Not Found", "unknown_action", action);
1312+ return 1;
1313+ }
1314+
1315+ /* 3. HTML UI. The page and its theme arrive from the generated header.
1316+ * UI_HTML carries two control bytes: 0x01 is the theme block (<style>
1317+ * with the bot tokens) and 0x02 is the handoff script before </body>. */
1318+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1319+ "Cache-Control: no-store\r\n"
1320+ "X-Content-Type-Options: nosniff\r\n"
1321+ "Referrer-Policy: no-referrer\r\n"
1322+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1323+ "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1324+ "base-uri 'none'; form-action 'none'; frame-ancestors *\r\n\r\n", stdout);
1325+ emit_ui();
1326+ return 0;
1327+}
src/ui.html+330−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..d310cf7index 0000000..d310cf7
--- /dev/null--- /dev/null
+++ b/src/ui.html+++ b/src/ui.html
@@ -0,0 +1,330 @@@@ -0,0 +1,330 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>google</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0;min-height:100%}
9+body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;
10+ line-height:1.5;-webkit-font-smoothing:antialiased}
11+#app{max-width:840px;margin:0 auto;padding:16px 16px 40px}
12+.hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}
13+.hd .grow{flex:1 1 auto;min-width:0}
14+.hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}
15+.hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;
16+ overflow:hidden;text-overflow:ellipsis}
17+.pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;
18+ padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);
19+ border:1px solid var(--line);white-space:nowrap}
20+.pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}
21+.pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}
22+.pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}
23+.pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}
24+.pill.warn .dot{background:var(--orange)}
25+.pill.off .dot{background:var(--gray)}
26+.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;
27+ padding:16px;margin-bottom:12px}
28+.card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;
29+ text-transform:uppercase;color:var(--text-2)}
30+.card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}
31+.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
32+.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;
33+ font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;
34+ transition:transform .12s var(--ease),opacity .12s}
35+.btn:active{transform:scale(.98)}
36+.btn:disabled{opacity:.5;cursor:default}
37+.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}
38+.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}
39+.btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}
40+a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}
41+.kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}
42+.kv .k{color:var(--text-2);font-size:12px}
43+.kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}
44+.kv .v.plain{font-family:var(--font);font-size:13px}
45+.hint{font-size:12px;color:var(--text-2);margin:10px 0 0}
46+.step{display:none}
47+.step.on{display:block}
48+.authurl{margin:10px 0;padding:10px 11px;border-radius:10px;background:var(--code-bg);
49+ border:1px solid var(--line);font-family:var(--mono);font-size:11.5px;
50+ word-break:break-all;max-height:120px;overflow:auto;color:var(--text)}
51+textarea{width:100%;min-height:82px;resize:vertical;border-radius:10px;padding:10px 11px;
52+ border:1px solid var(--line);background:var(--input-bg);color:var(--text);
53+ font-family:var(--mono);font-size:12px;line-height:1.45}
54+textarea:focus{outline:2px solid var(--blue);outline-offset:-1px}
55+.note{display:none;margin-top:10px;padding:9px 11px;border-radius:10px;font-size:12.5px;
56+ border:1px solid var(--line);background:var(--surface-2)}
57+.note.show{display:block}
58+.note.err{color:var(--red);border-color:rgba(255,69,58,.35)}
59+.note.ok{color:var(--green);border-color:rgba(48,209,88,.35)}
60+.empty{padding:10px 0;color:var(--text-2);font-size:12.5px}
61+.toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;
62+ pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);
63+ color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;
64+ box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);
65+ z-index:9;max-width:calc(100vw - 32px)}
66+.toast.show{opacity:1;transform:translate(-50%,0)}
67+#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);
68+ border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;
69+ font-family:inherit}
70+@media (max-width:520px){
71+ #app{padding:12px 12px 32px}
72+ .kv{grid-template-columns:1fr;gap:2px 0}
73+ .kv .k{margin-top:8px}
74+ .card{padding:13px;border-radius:12px}
75+}
76+</style>
77+</head>
78+<body>
79+<div id="app">
80+ <div class="hd">
81+ <div class="grow">
82+ <h1>Google Antigravity</h1>
83+ <div class="sub" id="sub">OAuth 2.0 PKCE login on this node</div>
84+ </div>
85+ <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span>
86+ <button id="themeToggle" class="embed-hide" type="button">Theme</button>
87+ </div>
88+
89+ <div class="card">
90+ <h2>Session</h2>
91+ <p class="lead" id="sessionLead">Reading the local Antigravity credentials.</p>
92+ <div class="kv" id="session"></div>
93+ <div class="row" style="margin-top:14px">
94+ <button class="btn ghost" id="btnRefresh" type="button">Refresh Token Now</button>
95+ <button class="btn ghost" id="btnReload" type="button">Reload</button>
96+ </div>
97+ <div class="note" id="refreshNote"></div>
98+ </div>
99+
100+ <div class="card">
101+ <h2>OAuth login</h2>
102+ <p class="lead">Sign in with Google. Nothing leaves this node: the login CLI performs the
103+ exchange and writes the credential file here.</p>
104+
105+ <div class="step on" id="step1">
106+ <button class="btn" id="btnStart" type="button">Start Google Login</button>
107+ <p class="hint">This generates a PKCE challenge and an authorization link. No token is
108+ created until you paste the code back.</p>
109+ </div>
110+
111+ <div class="step" id="step2">
112+ <div class="row">
113+ <a class="btn" id="linkOpen" href="#" target="_blank" rel="noopener noreferrer">Open Google Sign-in</a>
114+ <button class="btn ghost" id="btnCopy" type="button">Copy link</button>
115+ <button class="btn ghost" id="btnCancel" type="button">Cancel</button>
116+ </div>
117+ <div class="authurl" id="authUrl"></div>
118+ <p class="hint" id="flowHint">After approving, the browser lands on antigravity.google. Copy the
119+ whole address (or just the <span style="font-family:var(--mono)">code=</span> value) and paste it below.</p>
120+ <textarea id="codeInput" spellcheck="false" autocomplete="off"
121+ placeholder="Paste the authorization code or the full redirect URL"></textarea>
122+ <div class="row" style="margin-top:10px">
123+ <button class="btn" id="btnFinish" type="button">Authorize &amp; Discover Project</button>
124+ </div>
125+ <div class="note" id="loginNote"></div>
126+ </div>
127+ </div>
128+
129+ <div class="card">
130+ <h2>Companion project</h2>
131+ <p class="lead">The Google Cloud project the Antigravity session bills against.</p>
132+ <div class="kv" id="project"></div>
133+ </div>
134+</div>
135+
136+<div class="toast" id="toast"></div>
137+
138+<script>
139+var q=new URLSearchParams(location.search);
140+var node=q.get('node')||'';
141+var sid=q.get('id')||'';
142+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
143+ localStorage.getItem('bot_active_pwd')||'';
144+
145+/* Two call routes. Getting this wrong is the most common plugin bug:
146+ * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)
147+ * -> call the hub proxy back: /plugins?plugin=plugin_antigravity_login&action=..
148+ * opened directly on the node
149+ * -> the plugin itself is the route: /plugin_antigravity_login?action=..
150+ * Calling /plugins?plugin= on the node returns the discovery list, not us. */
151+var HUB=q.get('plugin')||'';
152+function url(action,extra){
153+ return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_antigravity_login')+
154+ '?action='+encodeURIComponent(action)+
155+ (extra?('&'+extra):'')+
156+ (node?'&node='+encodeURIComponent(node):'')+
157+ (sid?'&id='+encodeURIComponent(sid):'')+
158+ (pwd?'&pwd='+encodeURIComponent(pwd):'');
159+}
160+function hdr(){
161+ var h={};
162+ if(pwd)h['X-Bot-Password']=pwd;
163+ return h;
164+}
165+function api(action,extra){
166+ return fetch(url(action,extra),{headers:hdr()}).then(function(r){
167+ return r.json().catch(function(){return {ok:false,error:'bad response'};});
168+ });
169+}
170+
171+var $=function(id){return document.getElementById(id);};
172+function toast(msg){
173+ var t=$('toast');t.textContent=msg;t.classList.add('show');
174+ clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);
175+}
176+function note(el,msg,kind){
177+ el.textContent=msg||'';
178+ el.className='note'+(msg?' show '+(kind||''):'');
179+}
180+function kv(el,rows){
181+ el.innerHTML='';
182+ rows.forEach(function(r){
183+ var a=document.createElement('div');a.className='k';a.textContent=r[0];
184+ var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');
185+ b.textContent=r[1];el.appendChild(a);el.appendChild(b);
186+ });
187+}
188+function fmtExpiry(sec){
189+ if(!sec&&sec!==0)return '-';
190+ if(sec<=0)return 'expired';
191+ if(sec<90)return sec+'s';
192+ if(sec<5400)return Math.round(sec/60)+' min';
193+ if(sec<172800)return Math.round(sec/3600)+' h';
194+ return Math.round(sec/86400)+' d';
195+}
196+function setPill(st){
197+ var p=$('pill'),t=$('pillText');
198+ if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}
199+ else if(st.logged_in){p.className='pill ok';t.textContent='Connected';}
200+ else if(st.pending){p.className='pill warn';t.textContent='Signing in';}
201+ else {p.className='pill off';t.textContent='Not Connected';}
202+}
203+function render(st){
204+ setPill(st);
205+ $('sub').textContent=st.email?st.email:'OAuth 2.0 PKCE login on this node';
206+
207+ if(st.logged_in){
208+ $('sessionLead').textContent=st.expired
209+ ? 'The session is present but its access token has expired. Use Refresh Token Now.'
210+ : 'This node holds a Google Antigravity session.';
211+ }else{
212+ $('sessionLead').textContent='No Google session on this node yet. Start a login below.';
213+ }
214+ kv($('session'),[
215+ ['Account', st.email||'-', true],
216+ ['Logged in', st.logged_in?'yes':'no', true],
217+ ['Refresh token', st.has_refresh?'stored':'none', true],
218+ ['Token expires', st.logged_in?fmtExpiry(st.expires_in_sec):'-', true],
219+ ['Login pending', st.pending?'yes':'no', true],
220+ ['Login CLI', st.cli_present?'found':'not found', true],
221+ ['Credentials', st.credentials_path||'-']
222+ ]);
223+ kv($('project'),[
224+ ['Project ID', st.project_id||'(consumer shared project)', !st.project_id],
225+ ['Profile', st.profile||'-', true],
226+ ['Provider', 'google (Antigravity)', true]
227+ ]);
228+
229+ if(st.pending){$('step1').classList.remove('on');$('step2').classList.add('on');}
230+}
231+function load(){
232+ return api('status').then(function(d){
233+ if(d&&d.ok)render(d);
234+ else toast((d&&d.error)||'status failed');
235+ }).catch(function(e){toast('Status failed: '+e.message);});
236+}
237+
238+var authUrl='';
239+function start(){
240+ var b=$('btnStart');
241+ b.disabled=true;b.textContent='Starting...';
242+ api('start').then(function(d){
243+ b.disabled=false;b.textContent='Start Google Login';
244+ if(!d||!d.ok){toast((d&&(d.detail||d.error))||'start failed');return;}
245+ authUrl=d.auth_url||'';
246+ $('authUrl').textContent=authUrl;
247+ $('linkOpen').setAttribute('href',authUrl);
248+ if(d.hint)$('flowHint').textContent=d.hint;
249+ $('step1').classList.remove('on');
250+ $('step2').classList.add('on');
251+ $('codeInput').focus();
252+ }).catch(function(e){
253+ b.disabled=false;b.textContent='Start Google Login';
254+ toast('Start failed: '+e.message);
255+ });
256+}
257+
258+function finish(){
259+ var raw=$('codeInput').value.trim();
260+ if(!raw){note($('loginNote'),'Paste the code or the redirect address first.','err');return;}
261+ var b=$('btnFinish');
262+ b.disabled=true;b.textContent='Authorizing...';
263+ note($('loginNote'),'Exchange in progress. The Google project discovery can take a few seconds.');
264+ api('finish','code='+encodeURIComponent(raw)).then(function(d){
265+ b.disabled=false;b.textContent='Authorize & Discover Project';
266+ if(!d||!d.ok){
267+ note($('loginNote'),(d&&(d.detail||d.error))||'exchange failed','err');
268+ return;
269+ }
270+ note($('loginNote'),'');
271+ $('step2').classList.remove('on');
272+ $('step1').classList.add('on');
273+ $('codeInput').value='';
274+ render(d);
275+ toast('Signed in as '+(d.email||'Google account'));
276+ }).catch(function(e){
277+ b.disabled=false;b.textContent='Authorize & Discover Project';
278+ note($('loginNote'),'Exchange failed: '+e.message,'err');
279+ });
280+}
281+
282+function cancel(){
283+ api('cancel').then(function(){
284+ $('step2').classList.remove('on');
285+ $('step1').classList.add('on');
286+ $('codeInput').value='';
287+ note($('loginNote'),'');
288+ toast('Pending login cancelled');
289+ load();
290+ }).catch(function(e){toast('Cancel failed: '+e.message);});
291+}
292+
293+function refreshToken(){
294+ var b=$('btnRefresh');
295+ b.disabled=true;b.textContent='Refreshing...';
296+ note($('refreshNote'),'Asking Google for a new access token...');
297+ api('refresh').then(function(d){
298+ b.disabled=false;b.textContent='Refresh Token Now';
299+ if(!d||!d.ok){
300+ note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');
301+ return;
302+ }
303+ note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');
304+ render(d);
305+ }).catch(function(e){
306+ b.disabled=false;b.textContent='Refresh Token Now';
307+ note($('refreshNote'),'Refresh failed: '+e.message,'err');
308+ });
309+}
310+
311+function copyLink(){
312+ if(!authUrl)return;
313+ var done=function(){toast('Link copied');};
314+ if(navigator.clipboard&&navigator.clipboard.writeText){
315+ navigator.clipboard.writeText(authUrl).then(done).catch(function(){toast('Copy failed');});
316+ }else{toast('Copy not available');}
317+}
318+
319+$('btnStart').onclick=start;
320+$('btnFinish').onclick=finish;
321+$('btnCancel').onclick=cancel;
322+$('btnRefresh').onclick=refreshToken;
323+$('btnReload').onclick=load;
324+$('btnCopy').onclick=copyLink;
325+$('codeInput').addEventListener('keydown',function(e){
326+ if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)){e.preventDefault();finish();}
327+});
328+load();
329+</script>
330+</body></html>
src/ui_html.h+338−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..1b55812index 0000000..1b55812
--- /dev/null--- /dev/null
+++ b/src/ui_html.h+++ b/src/ui_html.h
@@ -0,0 +1,338 @@@@ -0,0 +1,338 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_AGYLOGIN_UI_HTML_H
3+#define SX_AGYLOGIN_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
9+ "<title>google</title>\n"
10+ "\001\n"
11+ "<style>\n"
12+ "*{box-sizing:border-box}\n"
13+ "html,body{margin:0;min-height:100%}\n"
14+ "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n"
15+ " line-height:1.5;-webkit-font-smoothing:antialiased}\n"
16+ "#app{max-width:840px;margin:0 auto;padding:16px 16px 40px}\n"
17+ ".hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n"
18+ ".hd .grow{flex:1 1 auto;min-width:0}\n"
19+ ".hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}\n"
20+ ".hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;\n"
21+ " overflow:hidden;text-overflow:ellipsis}\n"
22+ ".pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;\n"
23+ " padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);\n"
24+ " border:1px solid var(--line);white-space:nowrap}\n"
25+ ".pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}\n"
26+ ".pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n"
27+ ".pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}\n"
28+ ".pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n"
29+ ".pill.warn .dot{background:var(--orange)}\n"
30+ ".pill.off .dot{background:var(--gray)}\n"
31+ ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n"
32+ " padding:16px;margin-bottom:12px}\n"
33+ ".card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;\n"
34+ " text-transform:uppercase;color:var(--text-2)}\n"
35+ ".card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}\n"
36+ ".row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n"
37+ ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;\n"
38+ " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;\n"
39+ " transition:transform .12s var(--ease),opacity .12s}\n"
40+ ".btn:active{transform:scale(.98)}\n"
41+ ".btn:disabled{opacity:.5;cursor:default}\n"
42+ ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n"
43+ ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n"
44+ ".btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}\n"
45+ "a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}\n"
46+ ".kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}\n"
47+ ".kv .k{color:var(--text-2);font-size:12px}\n"
48+ ".kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}\n"
49+ ".kv .v.plain{font-family:var(--font);font-size:13px}\n"
50+ ".hint{font-size:12px;color:var(--text-2);margin:10px 0 0}\n"
51+ ".step{display:none}\n"
52+ ".step.on{display:block}\n"
53+ ".authurl{margin:10px 0;padding:10px 11px;border-radius:10px;background:var(--code-bg);\n"
54+ " border:1px solid var(--line);font-family:var(--mono);font-size:11.5px;\n"
55+ " word-break:break-all;max-height:120px;overflow:auto;color:var(--text)}\n"
56+ "textarea{width:100%;min-height:82px;resize:vertical;border-radius:10px;padding:10px 11px;\n"
57+ " border:1px solid var(--line);background:var(--input-bg);color:var(--text);\n"
58+ " font-family:var(--mono);font-size:12px;line-height:1.45}\n"
59+ "textarea:focus{outline:2px solid var(--blue);outline-offset:-1px}\n"
60+ ".note{display:none;margin-top:10px;padding:9px 11px;border-radius:10px;font-size:12.5px;\n"
61+ " border:1px solid var(--line);background:var(--surface-2)}\n"
62+ ".note.show{display:block}\n"
63+ ".note.err{color:var(--red);border-color:rgba(255,69,58,.35)}\n"
64+ ".note.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n"
65+ ".empty{padding:10px 0;color:var(--text-2);font-size:12.5px}\n"
66+ ".toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;\n"
67+ " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n"
68+ " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n"
69+ " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n"
70+ " z-index:9;max-width:calc(100vw - 32px)}\n"
71+ ".toast.show{opacity:1;transform:translate(-50%,0)}\n"
72+ "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n"
73+ " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n"
74+ " font-family:inherit}\n"
75+ "@media (max-width:520px){\n"
76+ " #app{padding:12px 12px 32px}\n"
77+ " .kv{grid-template-columns:1fr;gap:2px 0}\n"
78+ " .kv .k{margin-top:8px}\n"
79+ " .card{padding:13px;border-radius:12px}\n"
80+ "}\n"
81+ "</style>\n"
82+ "</head>\n"
83+ "<body>\n"
84+ "<div id=\"app\">\n"
85+ " <div class=\"hd\">\n"
86+ " <div class=\"grow\">\n"
87+ " <h1>Google Antigravity</h1>\n"
88+ " <div class=\"sub\" id=\"sub\">OAuth 2.0 PKCE login on this node</div>\n"
89+ " </div>\n"
90+ " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n"
91+ " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n"
92+ " </div>\n"
93+ "\n"
94+ " <div class=\"card\">\n"
95+ " <h2>Session</h2>\n"
96+ " <p class=\"lead\" id=\"sessionLead\">Reading the local Antigravity credentials.</p>\n"
97+ " <div class=\"kv\" id=\"session\"></div>\n"
98+ " <div class=\"row\" style=\"margin-top:14px\">\n"
99+ " <button class=\"btn ghost\" id=\"btnRefresh\" type=\"button\">Refresh Token Now</button>\n"
100+ " <button class=\"btn ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n"
101+ " </div>\n"
102+ " <div class=\"note\" id=\"refreshNote\"></div>\n"
103+ " </div>\n"
104+ "\n"
105+ " <div class=\"card\">\n"
106+ " <h2>OAuth login</h2>\n"
107+ " <p class=\"lead\">Sign in with Google. Nothing leaves this node: the login CLI performs the\n"
108+ " exchange and writes the credential file here.</p>\n"
109+ "\n"
110+ " <div class=\"step on\" id=\"step1\">\n"
111+ " <button class=\"btn\" id=\"btnStart\" type=\"button\">Start Google Login</button>\n"
112+ " <p class=\"hint\">This generates a PKCE challenge and an authorization link. No token is\n"
113+ " created until you paste the code back.</p>\n"
114+ " </div>\n"
115+ "\n"
116+ " <div class=\"step\" id=\"step2\">\n"
117+ " <div class=\"row\">\n"
118+ " <a class=\"btn\" id=\"linkOpen\" href=\"#\" target=\"_blank\" rel=\"noopener noreferrer\">Open Google Sign-in</a>\n"
119+ " <button class=\"btn ghost\" id=\"btnCopy\" type=\"button\">Copy link</button>\n"
120+ " <button class=\"btn ghost\" id=\"btnCancel\" type=\"button\">Cancel</button>\n"
121+ " </div>\n"
122+ " <div class=\"authurl\" id=\"authUrl\"></div>\n"
123+ " <p class=\"hint\" id=\"flowHint\">After approving, the browser lands on antigravity.google. Copy the\n"
124+ " whole address (or just the <span style=\"font-family:var(--mono)\">code=</span> value) and paste it below.</p>\n"
125+ " <textarea id=\"codeInput\" spellcheck=\"false\" autocomplete=\"off\"\n"
126+ " placeholder=\"Paste the authorization code or the full redirect URL\"></textarea>\n"
127+ " <div class=\"row\" style=\"margin-top:10px\">\n"
128+ " <button class=\"btn\" id=\"btnFinish\" type=\"button\">Authorize &amp; Discover Project</button>\n"
129+ " </div>\n"
130+ " <div class=\"note\" id=\"loginNote\"></div>\n"
131+ " </div>\n"
132+ " </div>\n"
133+ "\n"
134+ " <div class=\"card\">\n"
135+ " <h2>Companion project</h2>\n"
136+ " <p class=\"lead\">The Google Cloud project the Antigravity session bills against.</p>\n"
137+ " <div class=\"kv\" id=\"project\"></div>\n"
138+ " </div>\n"
139+ "</div>\n"
140+ "\n"
141+ "<div class=\"toast\" id=\"toast\"></div>\n"
142+ "\n"
143+ "<script>\n"
144+ "var q=new URLSearchParams(location.search);\n"
145+ "var node=q.get('node')||'';\n"
146+ "var sid=q.get('id')||'';\n"
147+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n"
148+ " localStorage.getItem('bot_active_pwd')||'';\n"
149+ "\n"
150+ "/* Two call routes. Getting this wrong is the most common plugin bug:\n"
151+ " * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)\n"
152+ " * -> call the hub proxy back: /plugins?plugin=plugin_antigravity_login&action=..\n"
153+ " * opened directly on the node\n"
154+ " * -> the plugin itself is the route: /plugin_antigravity_login?action=..\n"
155+ " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n"
156+ "var HUB=q.get('plugin')||'';\n"
157+ "function url(action,extra){\n"
158+ " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_antigravity_login')+\n"
159+ " '?action='+encodeURIComponent(action)+\n"
160+ " (extra?('&'+extra):'')+\n"
161+ " (node?'&node='+encodeURIComponent(node):'')+\n"
162+ " (sid?'&id='+encodeURIComponent(sid):'')+\n"
163+ " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n"
164+ "}\n"
165+ "function hdr(){\n"
166+ " var h={};\n"
167+ " if(pwd)h['X-Bot-Password']=pwd;\n"
168+ " return h;\n"
169+ "}\n"
170+ "function api(action,extra){\n"
171+ " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n"
172+ " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n"
173+ " });\n"
174+ "}\n"
175+ "\n"
176+ "var $=function(id){return document.getElementById(id);};\n"
177+ "function toast(msg){\n"
178+ " var t=$('toast');t.textContent=msg;t.classList.add('show');\n"
179+ " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n"
180+ "}\n"
181+ "function note(el,msg,kind){\n"
182+ " el.textContent=msg||'';\n"
183+ " el.className='note'+(msg?' show '+(kind||''):'');\n"
184+ "}\n"
185+ "function kv(el,rows){\n"
186+ " el.innerHTML='';\n"
187+ " rows.forEach(function(r){\n"
188+ " var a=document.createElement('div');a.className='k';a.textContent=r[0];\n"
189+ " var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');\n"
190+ " b.textContent=r[1];el.appendChild(a);el.appendChild(b);\n"
191+ " });\n"
192+ "}\n"
193+ "function fmtExpiry(sec){\n"
194+ " if(!sec&&sec!==0)return '-';\n"
195+ " if(sec<=0)return 'expired';\n"
196+ " if(sec<90)return sec+'s';\n"
197+ " if(sec<5400)return Math.round(sec/60)+' min';\n"
198+ " if(sec<172800)return Math.round(sec/3600)+' h';\n"
199+ " return Math.round(sec/86400)+' d';\n"
200+ "}\n"
201+ "function setPill(st){\n"
202+ " var p=$('pill'),t=$('pillText');\n"
203+ " if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}\n"
204+ " else if(st.logged_in){p.className='pill ok';t.textContent='Connected';}\n"
205+ " else if(st.pending){p.className='pill warn';t.textContent='Signing in';}\n"
206+ " else {p.className='pill off';t.textContent='Not Connected';}\n"
207+ "}\n"
208+ "function render(st){\n"
209+ " setPill(st);\n"
210+ " $('sub').textContent=st.email?st.email:'OAuth 2.0 PKCE login on this node';\n"
211+ "\n"
212+ " if(st.logged_in){\n"
213+ " $('sessionLead').textContent=st.expired\n"
214+ " ? 'The session is present but its access token has expired. Use Refresh Token Now.'\n"
215+ " : 'This node holds a Google Antigravity session.';\n"
216+ " }else{\n"
217+ " $('sessionLead').textContent='No Google session on this node yet. Start a login below.';\n"
218+ " }\n"
219+ " kv($('session'),[\n"
220+ " ['Account', st.email||'-', true],\n"
221+ " ['Logged in', st.logged_in?'yes':'no', true],\n"
222+ " ['Refresh token', st.has_refresh?'stored':'none', true],\n"
223+ " ['Token expires', st.logged_in?fmtExpiry(st.expires_in_sec):'-', true],\n"
224+ " ['Login pending', st.pending?'yes':'no', true],\n"
225+ " ['Login CLI', st.cli_present?'found':'not found', true],\n"
226+ " ['Credentials', st.credentials_path||'-']\n"
227+ " ]);\n"
228+ " kv($('project'),[\n"
229+ " ['Project ID', st.project_id||'(consumer shared project)', !st.project_id],\n"
230+ " ['Profile', st.profile||'-', true],\n"
231+ " ['Provider', 'google (Antigravity)', true]\n"
232+ " ]);\n"
233+ "\n"
234+ " if(st.pending){$('step1').classList.remove('on');$('step2').classList.add('on');}\n"
235+ "}\n"
236+ "function load(){\n"
237+ " return api('status').then(function(d){\n"
238+ " if(d&&d.ok)render(d);\n"
239+ " else toast((d&&d.error)||'status failed');\n"
240+ " }).catch(function(e){toast('Status failed: '+e.message);});\n"
241+ "}\n"
242+ "\n"
243+ "var authUrl='';\n"
244+ "function start(){\n"
245+ " var b=$('btnStart');\n"
246+ " b.disabled=true;b.textContent='Starting...';\n"
247+ " api('start').then(function(d){\n"
248+ " b.disabled=false;b.textContent='Start Google Login';\n"
249+ " if(!d||!d.ok){toast((d&&(d.detail||d.error))||'start failed');return;}\n"
250+ " authUrl=d.auth_url||'';\n"
251+ " $('authUrl').textContent=authUrl;\n"
252+ " $('linkOpen').setAttribute('href',authUrl);\n"
253+ " if(d.hint)$('flowHint').textContent=d.hint;\n"
254+ " $('step1').classList.remove('on');\n"
255+ " $('step2').classList.add('on');\n"
256+ " $('codeInput').focus();\n"
257+ " }).catch(function(e){\n"
258+ " b.disabled=false;b.textContent='Start Google Login';\n"
259+ " toast('Start failed: '+e.message);\n"
260+ " });\n"
261+ "}\n"
262+ "\n"
263+ "function finish(){\n"
264+ " var raw=$('codeInput').value.trim();\n"
265+ " if(!raw){note($('loginNote'),'Paste the code or the redirect address first.','err');return;}\n"
266+ " var b=$('btnFinish');\n"
267+ " b.disabled=true;b.textContent='Authorizing...';\n"
268+ " note($('loginNote'),'Exchange in progress. The Google project discovery can take a few seconds.');\n"
269+ " api('finish','code='+encodeURIComponent(raw)).then(function(d){\n"
270+ " b.disabled=false;b.textContent='Authorize & Discover Project';\n"
271+ " if(!d||!d.ok){\n"
272+ " note($('loginNote'),(d&&(d.detail||d.error))||'exchange failed','err');\n"
273+ " return;\n"
274+ " }\n"
275+ " note($('loginNote'),'');\n"
276+ " $('step2').classList.remove('on');\n"
277+ " $('step1').classList.add('on');\n"
278+ " $('codeInput').value='';\n"
279+ " render(d);\n"
280+ " toast('Signed in as '+(d.email||'Google account'));\n"
281+ " }).catch(function(e){\n"
282+ " b.disabled=false;b.textContent='Authorize & Discover Project';\n"
283+ " note($('loginNote'),'Exchange failed: '+e.message,'err');\n"
284+ " });\n"
285+ "}\n"
286+ "\n"
287+ "function cancel(){\n"
288+ " api('cancel').then(function(){\n"
289+ " $('step2').classList.remove('on');\n"
290+ " $('step1').classList.add('on');\n"
291+ " $('codeInput').value='';\n"
292+ " note($('loginNote'),'');\n"
293+ " toast('Pending login cancelled');\n"
294+ " load();\n"
295+ " }).catch(function(e){toast('Cancel failed: '+e.message);});\n"
296+ "}\n"
297+ "\n"
298+ "function refreshToken(){\n"
299+ " var b=$('btnRefresh');\n"
300+ " b.disabled=true;b.textContent='Refreshing...';\n"
301+ " note($('refreshNote'),'Asking Google for a new access token...');\n"
302+ " api('refresh').then(function(d){\n"
303+ " b.disabled=false;b.textContent='Refresh Token Now';\n"
304+ " if(!d||!d.ok){\n"
305+ " note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');\n"
306+ " return;\n"
307+ " }\n"
308+ " note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');\n"
309+ " render(d);\n"
310+ " }).catch(function(e){\n"
311+ " b.disabled=false;b.textContent='Refresh Token Now';\n"
312+ " note($('refreshNote'),'Refresh failed: '+e.message,'err');\n"
313+ " });\n"
314+ "}\n"
315+ "\n"
316+ "function copyLink(){\n"
317+ " if(!authUrl)return;\n"
318+ " var done=function(){toast('Link copied');};\n"
319+ " if(navigator.clipboard&&navigator.clipboard.writeText){\n"
320+ " navigator.clipboard.writeText(authUrl).then(done).catch(function(){toast('Copy failed');});\n"
321+ " }else{toast('Copy not available');}\n"
322+ "}\n"
323+ "\n"
324+ "$('btnStart').onclick=start;\n"
325+ "$('btnFinish').onclick=finish;\n"
326+ "$('btnCancel').onclick=cancel;\n"
327+ "$('btnRefresh').onclick=refreshToken;\n"
328+ "$('btnReload').onclick=load;\n"
329+ "$('btnCopy').onclick=copyLink;\n"
330+ "$('codeInput').addEventListener('keydown',function(e){\n"
331+ " if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)){e.preventDefault();finish();}\n"
332+ "});\n"
333+ "load();\n"
334+ "</script>\n"
335+ "\002</body></html>\n"
336+ ;
337+
338+#endif /* SX_AGYLOGIN_UI_HTML_H */
tests/mock_login.sh+68−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..082dc05index 0000000..082dc05
--- /dev/null--- /dev/null
+++ b/tests/mock_login.sh+++ b/tests/mock_login.sh
@@ -0,0 +1,68 @@@@ -0,0 +1,68 @@
1+#!/bin/sh
2+# tests/mock_login.sh - stand-in for scorpiox-antigravity-login machine mode.
3+#
4+# Emits exactly the contract shape the real CLI emits (one JSON line last, all
5+# human output before it), so the plugin's parsers are exercised against the
6+# production layout rather than an invented one. The exchange is simulated:
7+# --finish writes a credential file into $ANTIGRAVITY_CREDS_PATH's directory so
8+# the test can prove the plugin re-reads state after a successful login.
9+#
10+# Set MOCK_FAIL=1 to make --finish fail the way Google does when the account
11+# needs verification.
12+
13+case "$1" in
14+ --status)
15+ if [ -n "$MOCK_STATUS_JSON" ]; then
16+ printf '%s\n' "$MOCK_STATUS_JSON"
17+ else
18+ # Mirror the real CLI: logged_in / has_refresh / identity all come from
19+ # the credential file the exchange wrote, so a test that runs --finish
20+ # and then --status sees the same thing a real node would.
21+ _acct="${ANTIGRAVITY_CREDS_PATH:-/nonexistent}"
22+ _li=false; _hr=false; _id=""
23+ if [ -f "$_acct" ] && grep -q 'refresh_token' "$_acct" 2>/dev/null; then
24+ _li=true; _hr=true
25+ _id=$(sed -n 's/.*"email"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_acct" | head -1)
26+ fi
27+ printf 'scorpiox-antigravity-login 1.0.0 (SXLOGIN-MACHINE-V1)\n'
28+ printf '{"ok":true,"provider":"antigravity","name":"Antigravity (Google)","flow":"paste_code",'
29+ printf '"logged_in":%s,"path":"%s",' "$_li" "$_acct"
30+ if [ -n "$_id" ]; then printf '"identity":"%s",' "$_id"; fi
31+ printf '"expires_at":0,"expired":false,"has_refresh":%s,"pending":false,' "$_hr"
32+ printf '"profile":"antigravity","profile_exists":false}\n'
33+ fi
34+ ;;
35+ --start)
36+ printf 'generating PKCE challenge\n'
37+ printf '{"ok":true,"provider":"antigravity","flow":"paste_code",'
38+ printf '"auth_url":"https://accounts.google.com/o/oauth2/auth?client_id=test&code_challenge=abc123&code_challenge_method=S256&state=st4te",'
39+ printf '"expires_in":900,"hint":"Sign in with Google and approve, then paste the code."}\n'
40+ ;;
41+ --finish)
42+ if [ "$MOCK_FAIL" = "1" ]; then
43+ printf '{"ok":false,"provider":"antigravity","error":"exchange","detail":"validation required"}\n'
44+ exit 1
45+ fi
46+ [ -z "$2" ] && { printf '{"ok":false,"error":"no_code"}\n'; exit 1; }
47+ # simulate the CLI writing the credential + profile
48+ if [ -n "$MOCK_WRITE_DIR" ]; then
49+ mkdir -p "$MOCK_WRITE_DIR" "$MOCK_WRITE_DIR/scorpiox-env"
50+ printf '[{"email":"pico@example.com","refresh_token":"1//mock-refresh-token-value"}]\n' \
51+ > "$MOCK_WRITE_DIR/antigravity_accounts.json"
52+ printf 'pico@example.com\n' > "$MOCK_WRITE_DIR/selected_account.txt"
53+ printf 'PROVIDER=google_gemini\nGOOGLE_ACCOUNT=pico@example.com\nGOOGLE_PROJECT_ID=proj-mock-42\n' \
54+ > "$MOCK_WRITE_DIR/scorpiox-env/antigravity.txt"
55+ fi
56+ printf 'Login Successful!\n'
57+ printf '{"ok":true,"provider":"antigravity","state":"done","logged_in":true,'
58+ printf '"path":"%s","identity":"pico@example.com","profile":"antigravity","profile_created":true}\n' \
59+ "${ANTIGRAVITY_CREDS_PATH:-/nonexistent}"
60+ ;;
61+ --cancel)
62+ printf '{"ok":true,"provider":"antigravity","state":"cancelled"}\n'
63+ ;;
64+ *)
65+ printf '{"ok":false,"error":"usage"}\n'
66+ exit 1
67+ ;;
68+esac
tests/mock_token.sh+14−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..9f7839eindex 0000000..9f7839e
--- /dev/null--- /dev/null
+++ b/tests/mock_token.sh+++ b/tests/mock_token.sh
@@ -0,0 +1,14 @@@@ -0,0 +1,14 @@
1+#!/bin/sh
2+# tests/mock_token.sh - stand-in for scorpiox-google-fetchtoken -local.
3+#
4+# Prints the real payload shape, including a fake bearer token, so the suite can
5+# prove the plugin never forwards that token to a browser or a proxy log.
6+#
7+# Set MOCK_TOKEN_FAIL=1 to exercise the refresh failure path.
8+if [ "$MOCK_TOKEN_FAIL" = "1" ]; then
9+ printf '{"ok":false,"error":"no refresh_token for account"}\n'
10+ exit 1
11+fi
12+printf 'fetching token (local)\n'
13+printf '{"ok":true,"email":"pico@example.com","access_token":"ya29.MOCK-ACCESS-TOKEN-MUST-NOT-LEAK",'
14+printf '"project_id":"proj-mock-42","expires_in":3599}\n'
tests/run.sh+426−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..e31a831index 0000000..e31a831
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,426 @@@@ -0,0 +1,426 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_antigravity_login across all 3 modes.
3+#
4+# Every check runs against ./plugin_antigravity_login with the credential paths
5+# and both CLIs redirected at throwaway fixtures, so the suite proves the public
6+# contract without touching a real Google session and without a network.
7+#
8+# What it proves:
9+# - --meta is exactly {"name":"google","desc":"Google login"} and is reachable
10+# with no password (discovery must never be gated)
11+# - every action 401s without the node password, and 401 is a real CGI Status
12+# - status parses the accounts array + sibling files + the CLI JSON and never
13+# emits a token
14+# - start returns the CLI's auth_url, finish rejects garbage codes locally and
15+# re-reads state after a successful exchange
16+# - refresh performs the grant, drops the access token, and surfaces failure
17+# - the HTML page carries the bot theme handoff, no CDN and no <script src=>
18+# - the source has no hard-coded secret, no internal address and no emoji
19+#
20+# Exit code 0 = everything passed.
21+
22+set -u
23+
24+ROOT=$(cd "$(dirname "$0")/.." && pwd)
25+cd "$ROOT" || exit 1
26+
27+BIN=./plugin_antigravity_login
28+ID=plugin_antigravity_login
29+PASS=0
30+FAIL=0
31+
32+if [ -t 1 ]; then
33+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
34+else
35+ C_OK=; C_BAD=; C_B=; C_0=
36+fi
37+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
38+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
39+
40+check() { # check <desc> <expected-substring> <actual>
41+ if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
42+ fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
43+ fi
44+}
45+
46+check_not() { # check_not <desc> <forbidden-substring> <actual>
47+ if printf '%s' "$3" | grep -F -q -- "$2"; then
48+ fail "$1 (must NOT contain: $2)"; else pass "$1"
49+ fi
50+}
51+
52+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
53+
54+# strip CGI headers if present, drop CRs, keep the payload
55+body() {
56+ printf '%s\n' "$1" | tr -d '\r' | awk '
57+ BEGIN { inhdr = 0 }
58+ NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next }
59+ inhdr && $0 == "" { inhdr = 0; next }
60+ inhdr { next }
61+ { print }
62+ '
63+}
64+
65+json_ok() { # json_ok <desc> <json> [python-expression]
66+ expr=${3:-True}
67+ if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
68+ pass "$1"
69+ else
70+ fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
71+ fi
72+}
73+
74+api() { body "$(QUERY_STRING="$1" $BIN)"; }
75+apiraw() { QUERY_STRING="$1" $BIN; }
76+
77+# ---------------------------------------------------------------- build
78+section "build"
79+if [ ! -x "$BIN" ]; then
80+ echo " building native binary..."
81+ gcc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_antigravity_login.c || {
82+ fail "native build"; exit 1; }
83+fi
84+pass "native binary present"
85+
86+# generated page header must match src/ui.html
87+if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
88+ pass "src/ui_html.h is in sync with src/ui.html"
89+else
90+ fail "src/ui_html.h is stale - run tools/gen_ui.py"
91+fi
92+
93+# the page header must not be hand-edited: it is generated from ui.html
94+check "ui header is marked generated" \
95+ "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
96+
97+# ---------------------------------------------------------------- fixtures
98+FIX=$(mktemp -d 2>/dev/null || mktemp -d -t agyfix)
99+trap 'rm -rf "$FIX"' EXIT
100+
101+mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" "$FIX/full/scorpiox-env" "$FIX/pending"
102+export ANTIGRAVITY_LOGIN_BIN="$ROOT/tests/mock_login.sh"
103+export ANTIGRAVITY_TOKEN_BIN="$ROOT/tests/mock_token.sh"
104+export ANTIGRAVITY_PENDING_PATH="$FIX/pending/antigravity-default.json"
105+
106+# empty credentials file (exists but has no accounts)
107+: > "$FIX/empty/antigravity_accounts.json"
108+
109+# a realistic signed-in fixture: the accounts array + selected account + profile
110+cat > "$FIX/full/antigravity_accounts.json" <<'JSON'
111+[
112+ {"email":"other@example.com","refresh_token":"1//other-refresh"},
113+ {"email":"pico@example.com","refresh_token":"1//pico-refresh-value"}
114+]
115+JSON
116+printf 'pico@example.com\n' > "$FIX/full/selected_account.txt"
117+printf 'PROVIDER=google_gemini\nGOOGLE_TOKEN_SOURCE=local\nGOOGLE_ACCOUNT=pico@example.com\nGOOGLE_PROJECT_ID=proj-mock-42\nMODEL=gemini-3.7-flash-tiered\n' \
118+ > "$FIX/full/scorpiox-env/antigravity.txt"
119+
120+# ---------------------------------------------------------------- metadata
121+section "mode 1: discovery metadata"
122+META=$("$BIN" --meta)
123+if [ "$META" = '{"name":"google","desc":"Google login"}' ]; then
124+ pass "--meta is exactly the contract line"
125+else
126+ fail "--meta mismatch"; printf ' got: %s\n' "$META"
127+fi
128+json_ok "--meta is valid JSON with name+desc" "$META" \
129+ "d['name']=='google' and d['desc']=='Google login'"
130+check "--meta desc is within 15 chars" "Google login" "$META"
131+
132+ENVMETA=$(SX_PLUGIN_META=1 "$BIN")
133+check "SX_PLUGIN_META=1 works like --meta" '"name":"google"' "$ENVMETA"
134+
135+# --meta must not be gated by the node password
136+META_PW=$(BOT_PASSWORD=testpw "$BIN" --meta)
137+check "--meta ignores BOT_PASSWORD" '"name":"google"' "$META_PW"
138+
139+check "--version prints the plugin id and version" "$ID" "$("$BIN" --version)"
140+
141+# ---------------------------------------------------------------- auth
142+section "node auth"
143+export BOT_PASSWORD=testpw
144+RAW=$(apiraw "action=status")
145+check "unauthenticated action returns a 401 Status line" "Status: 401 Unauthorized" "$RAW"
146+check "unauthenticated action body is JSON" '"error":"invalid node password"' "$RAW"
147+
148+RAW=$(apiraw "")
149+check "unauthenticated HTML also 401s" "Status: 401 Unauthorized" "$RAW"
150+
151+HDR=$(api "action=status&pwd=testpw")
152+check "?pwd= authenticates" '"ok":true' "$HDR"
153+
154+HDR=$(QUERY_STRING="action=status" HTTP_X_BOT_PASSWORD=testpw $BIN)
155+check "X-Bot-Password authenticates" '"ok":true' "$(body "$HDR")"
156+
157+HDR=$(QUERY_STRING="action=status" HTTP_AUTHORIZATION="Bearer testpw" $BIN)
158+check "Authorization: Bearer authenticates" '"ok":true' "$(body "$HDR")"
159+
160+WRONG=$(apiraw "action=status&pwd=nope")
161+check "a wrong password still 401s" "Status: 401 Unauthorized" "$WRONG"
162+unset BOT_PASSWORD
163+
164+# ---------------------------------------------------------------- status
165+section "action=status"
166+NOFIX=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \
167+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":false,"expires_at":0,"expired":false,"has_refresh":false,"pending":false}' \
168+ api "action=status")
169+json_ok "status with no credentials is valid JSON" "$NOFIX" \
170+ "d['ok'] is True and d['logged_in'] is False and d['has_refresh'] is False"
171+check_not "status with no credentials emits no token field" "refresh_token" "$NOFIX"
172+
173+EMPTYJ=$(ANTIGRAVITY_CREDS_PATH="$FIX/empty/antigravity_accounts.json" api "action=status")
174+json_ok "empty accounts file yields logged_in false" "$EMPTYJ" \
175+ "d['ok'] is True and d['logged_in'] is False"
176+
177+FULL=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
178+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":4102444800000,"expired":false,"has_refresh":true,"pending":false,"identity":"pico@example.com"}' \
179+ api "action=status")
180+json_ok "signed-in status reports logged_in + has_refresh" "$FULL" \
181+ "d['ok'] is True and d['logged_in'] is True and d['has_refresh'] is True"
182+check_not "signed-in status never returns the refresh token" "1//pico-refresh-value" "$FULL"
183+check_not "signed-in status never returns any token literal" "refresh_token\":" "$FULL"
184+
185+check "status reports the selected account email" "pico@example.com" "$FULL"
186+check "status reads the companion project from the profile" "proj-mock-42" "$FULL"
187+check "status reports the credentials path" "$FIX/full/antigravity_accounts.json" "$FULL"
188+json_ok "status has the full contract field set" "$FULL" \
189+ "all(k in d for k in ('logged_in','email','project_id','expires_at','expires_in_sec','expired','has_refresh','account','pending','profile'))"
190+
191+# expired session: the CLI says the expiry is in the past
192+EXPIRED=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
193+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":1000000000000,"expired":true,"has_refresh":true,"pending":false}' \
194+ api "action=status")
195+json_ok "an expired session reports expired true and a negative remaining time" "$EXPIRED" \
196+ "d['expired'] is True and d['expires_in_sec'] < 0"
197+
198+# pending marker file present -> pending true even without CLI help
199+: > "$FIX/pending/antigravity-default.json"
200+PEND=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \
201+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":false,"pending":false}' \
202+ api "action=status")
203+json_ok "the pending marker file makes status pending" "$PEND" "d['pending'] is True"
204+rm -f "$FIX/pending/antigravity-default.json"
205+
206+# no CLI on PATH: status must still answer from the files alone
207+NOCLI=$(ANTIGRAVITY_LOGIN_BIN="/nonexistent/login-cli" \
208+ ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" api "action=status")
209+json_ok "status answers without the login CLI" "$NOCLI" \
210+ "d['ok'] is True and d['logged_in'] is True"
211+json_ok "cli_present is false when the CLI is missing" "$NOCLI" "d['cli_present'] is False"
212+
213+# format=json with no action means status
214+FMT=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
215+ MOCK_STATUS_JSON='{"ok":true,"logged_in":true,"has_refresh":true}' api "format=json")
216+json_ok "format=json alone answers status" "$FMT" "d['ok'] is True and 'logged_in' in d"
217+
218+# ---------------------------------------------------------------- start
219+section "action=start"
220+START=$(api "action=start")
221+json_ok "start returns ok + an auth_url" "$START" \
222+ "d['ok'] is True and d['auth_url'].startswith('https://accounts.google.com/')"
223+check "start reports the paste_code flow" '"flow":"paste_code"' "$START"
224+check "start carries the PKCE challenge in the URL" "code_challenge=" "$START"
225+check "start carries the S256 method" "code_challenge_method=S256" "$START"
226+check "start reports an expiry window" "expires_in" "$START"
227+
228+# the plugin must not invent a client secret of its own
229+check_not "start never echoes a client secret" "GOCSPX" "$START"
230+
231+NOCLISTART=$(ANTIGRAVITY_LOGIN_BIN="/nonexistent/login-cli" api "action=start")
232+json_ok "start without the CLI returns a structured error" "$NOCLISTART" \
233+ "d['ok'] is False and d['error']=='cli_unavailable'"
234+
235+# ---------------------------------------------------------------- finish
236+section "action=finish"
237+MISSING=$(api "action=finish")
238+json_ok "finish without a code is a 400-style error object" "$MISSING" \
239+ "d['ok'] is False and d['error']=='missing_code'"
240+
241+SHELLY=$(api "action=finish&code=\$(touch_/tmp/pwned)")
242+json_ok "finish rejects shell metacharacters before running anything" "$SHELLY" \
243+ "d['ok'] is False and d['error']=='invalid_code'"
244+if [ -e /tmp/pwned ]; then fail "shell injection created /tmp/pwned"; rm -f /tmp/pwned; else pass "shell injection did not execute"; fi
245+
246+QUOTED=$(api "action=finish&code=abc%27def")
247+json_ok "finish rejects a quote in the code" "$QUOTED" \
248+ "d['ok'] is False and d['error']=='invalid_code'"
249+
250+FAILED=$(MOCK_FAIL=1 api "action=finish&code=4/0AX4XfWh-test-code")
251+json_ok "a rejected exchange surfaces the CLI error" "$FAILED" \
252+ "d['ok'] is False and d['error'] in ('exchange','finish_failed')"
253+
254+# successful exchange: the mock writes the credential files into $MOCK_WRITE_DIR
255+mkdir -p "$FIX/finishdir"
256+OKF=$(MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
257+ api "action=finish&code=4/0AX4XfWh-test-code")
258+json_ok "a successful exchange reports done + logged_in" "$OKF" \
259+ "d['ok'] is True and d['state']=='done' and d['logged_in'] is True"
260+check "the exchange result re-reads the new account" "pico@example.com" "$OKF"
261+check_not "the exchange result never carries the token" "1//mock-refresh-token-value" "$OKF"
262+
263+# a full redirect URL is accepted (the CLI extracts code= itself)
264+FULLURL=$(MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
265+ api "action=finish&code=https%3A%2F%2Fantigravity.google%2Foauth-callback%3Fcode%3D4%2F0AX-test%26state%3Dxyz")
266+json_ok "a whole redirect URL is accepted" "$FULLURL" "d['ok'] is True and d['state']=='done'"
267+
268+# POST body carrying the code
269+POSTB=$(printf '{"code":"4/0AX4XfWh-post-code"}' | \
270+ REQUEST_METHOD=POST CONTENT_LENGTH=32 \
271+ MOCK_WRITE_DIR="$FIX/finishdir" ANTIGRAVITY_CREDS_PATH="$FIX/finishdir/antigravity_accounts.json" \
272+ QUERY_STRING="action=finish" $BIN)
273+json_ok "the code can arrive in a POST body" "$(body "$POSTB")" "d['ok'] is True"
274+
275+# ---------------------------------------------------------------- cancel
276+section "action=cancel"
277+CANCEL=$(api "action=cancel")
278+json_ok "cancel reports a cancelled state" "$CANCEL" \
279+ "d['ok'] is True and d['state']=='cancelled' and d['pending'] is False"
280+
281+# ---------------------------------------------------------------- refresh
282+section "action=refresh"
283+REFR=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" api "action=refresh")
284+json_ok "refresh succeeds and reports refreshed" "$REFR" \
285+ "d['ok'] is True and d['refreshed'] is True"
286+check_not "refresh NEVER returns the access token" "ya29.MOCK-ACCESS-TOKEN-MUST-NOT-LEAK" "$REFR"
287+check_not "refresh has no access_token key at all" "access_token" "$REFR"
288+check "refresh reports the project from the token CLI" "proj-mock-42" "$REFR"
289+
290+REFRFAIL=$(MOCK_TOKEN_FAIL=1 api "action=refresh")
291+json_ok "a failed refresh returns a structured error" "$REFRFAIL" \
292+ "d['ok'] is False and d['error']=='refresh_failed'"
293+
294+REFRNOCLI=$(ANTIGRAVITY_TOKEN_BIN="/nonexistent/token-cli" api "action=refresh")
295+json_ok "refresh without the token CLI says cli_unavailable" "$REFRNOCLI" \
296+ "d['ok'] is False and d['error']=='cli_unavailable'"
297+
298+# ---------------------------------------------------------------- errors
299+section "unknown routes and actions"
300+UNK=$(api "action=teleport")
301+json_ok "an unknown action is a structured error" "$UNK" \
302+ "d['ok'] is False and d['error']=='unknown_action'"
303+RAWUNK=$(apiraw "action=teleport")
304+check "an unknown action returns a 404 Status" "Status: 404 Not Found" "$RAWUNK"
305+check "the error carries the plugin contract headers" "Content-Type: application/json" "$RAWUNK"
306+check_not "no response emits Content-Length" "Content-Length" "$RAWUNK"
307+
308+BADS=$(api "action=status")
309+check_not "JSON responses carry Cache-Control: no-store" "Cache-Control: no-store" "$BADS"
310+
311+# ---------------------------------------------------------------- HTML
312+section "mode 3: HTML UI"
313+HTMLRAW=$(apiraw "")
314+HTML=$(body "$HTMLRAW")
315+check "HTML is served as text/html" "Content-Type: text/html; charset=utf-8" "$HTMLRAW"
316+check "HTML declares a viewport" "name=\"viewport\"" "$HTML"
317+check "HTML carries the CSP header" "Content-Security-Policy" "$HTMLRAW"
318+check "HTML declares color-scheme via the theme tokens" "color-scheme" "$HTML"
319+check "HTML includes the bot prepaint script" "bot_theme" "$HTML"
320+check "HTML includes the theme handoff listener" "sx-theme" "$HTML"
321+check "HTML has the status pill" 'id="pill"' "$HTML"
322+check "HTML has the start button" 'id="btnStart"' "$HTML"
323+check "HTML has the paste input" 'id="codeInput"' "$HTML"
324+check "HTML has the finish button" 'id="btnFinish"' "$HTML"
325+check "HTML has the cancel button" 'id="btnCancel"' "$HTML"
326+check "HTML has the refresh button" 'id="btnRefresh"' "$HTML"
327+check "HTML has the companion project card" "Companion project" "$HTML"
328+check "HTML uses the two-route API helper" "plugin_antigravity_login" "$HTML"
329+check "HTML hides the back link in embed mode" "embed-hide" "$HTML"
330+check_not "HTML loads no CDN script" "<script src=" "$HTML"
331+check_not "HTML references no external host script" "cdnjs" "$HTML"
332+check_not "HTML makes no outbound fetch to a third party" "googleapis.com" "$HTML"
333+check_not "HTML carries no emoji" "🚀" "$HTML"
334+
335+if command -v python3 >/dev/null 2>&1; then
336+ printf '%s' "$HTML" > "$FIX/page.html"
337+ if python3 - "$FIX/page.html" <<'PY'
338+import re, sys
339+html = open(sys.argv[1], encoding='utf-8').read()
340+# every id referenced by getElementById must exist in the markup
341+ids = set(re.findall(r'id="([^"]+)"', html))
342+missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids]
343+sys.exit(1 if missing else 0)
344+PY
345+ then pass "every JS element id exists in the markup"
346+ else fail "the page JS references an element id that is not in the HTML"; fi
347+fi
348+
349+# ---------------------------------------------------------------- source hygiene
350+section "source hygiene"
351+check_not "source has no OAuth client secret" "GOCSPX" "$(cat src/plugin_antigravity_login.c)"
352+check_not "source has no Google API key" "AIza" "$(cat src/plugin_antigravity_login.c)"
353+check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_antigravity_login.c)"
354+check_not "source has no internal address" "192.168." "$(cat src/plugin_antigravity_login.c src/ui.html)"
355+check_not "source has no 10.x internal address" "10.0." "$(cat src/plugin_antigravity_login.c src/ui.html)"
356+check_not "the page has no internal address either" "172.16" "$(cat src/ui.html)"
357+
358+# no emoji anywhere in the shipped sources (byte-level check, not a regex guess)
359+if python3 - src/plugin_antigravity_login.c src/ui.html src/bot_theme_plugin.h <<'PY'
360+import sys, unicodedata
361+bad = []
362+for path in sys.argv[1:]:
363+ for n, line in enumerate(open(path, encoding='utf-8'), 1):
364+ for ch in line:
365+ o = ord(ch)
366+ if o < 0x2000:
367+ continue
368+ if 0x2190 <= o <= 0x21FF: # arrows are typography, not emoji
369+ continue
370+ if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF:
371+ bad.append('%s:%d %r' % (path, n, ch))
372+if bad:
373+ print('\n'.join(bad[:10]))
374+ sys.exit(1)
375+PY
376+then pass "no emoji in source, page or theme header"
377+else fail "emoji found in the shipped sources"; fi
378+
379+# ---------------------------------------------------------------- extra builds
380+section "cross-target builds"
381+if command -v musl-gcc >/dev/null 2>&1; then
382+ if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_antigravity_login.c 2>/dev/null; then
383+ pass "static musl build"
384+ MUSLMETA=$("$FIX/musl-bin" --meta)
385+ check "the musl binary reports the same metadata" '"name":"google"' "$MUSLMETA"
386+ else fail "static musl build"; fi
387+else
388+ echo " skip musl-gcc not installed"
389+fi
390+
391+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
392+ if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_antigravity_login.c 2>/dev/null; then
393+ pass "MinGW-w64 build"
394+ if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then
395+ pass "the Windows build has a real PE header"
396+ else fail "the Windows build is not a PE (missing MZ)"; fi
397+ else fail "MinGW-w64 build"; fi
398+else
399+ echo " skip x86_64-w64-mingw32-gcc not installed"
400+fi
401+
402+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
403+ if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_antigravity_login.c 2>/dev/null; then
404+ pass "static arm64 build"
405+ else fail "static arm64 build"; fi
406+else
407+ echo " skip aarch64-linux-gnu-gcc not installed"
408+fi
409+
410+# _FORTIFY_SOURCE=2: the sqlite plugin lost a whole build to this, so it is
411+# part of every suite now.
412+if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_antigravity_login.c 2>/dev/null; then
413+ FORTMETA=$("$FIX/fortify-bin" --meta)
414+ check "a _FORTIFY_SOURCE=2 build runs --meta clean" '"name":"google"' "$FORTMETA"
415+ FORTSTAT=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
416+ QUERY_STRING="action=status" "$FIX/fortify-bin")
417+ json_ok "a fortify build answers status without aborting" "$(body "$FORTSTAT")" "d['ok'] is True"
418+else
419+ fail "_FORTIFY_SOURCE=2 build"
420+fi
421+
422+# ---------------------------------------------------------------- summary
423+printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
424+printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
425+[ "$FAIL" -eq 0 ] || exit 1
426+exit 0
tools/gen_ui.py+105−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..55470a4index 0000000..55470a4
--- /dev/null--- /dev/null
+++ b/tools/gen_ui.py+++ b/tools/gen_ui.py
@@ -0,0 +1,105 @@@@ -0,0 +1,105 @@
1+#!/usr/bin/env python3
2+"""tools/gen_ui.py - compile src/ui.html into src/ui.html.h.
3+
4+The page lives in one readable file (src/ui.html) so it can be diffed and
5+reviewed like any other source. This script turns it into a single C string
6+constant with two control-character placeholders:
7+
8+ 0x01 -> the bot theme prepaint script + <style> + theme tokens
9+ 0x02 -> the bot theme handoff script (just before </body>)
10+
11+main() splits the constant on those bytes and emits the macros from
12+src/bot_theme_plugin.h in their place, so the theme can never drift out of
13+sync with the rest of the bot.
14+
15+ python3 tools/gen_ui.py # write src/ui.html.h
16+ python3 tools/gen_ui.py --check # exit 1 when the header is stale
17+"""
18+
19+import os
20+import sys
21+
22+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23+SRC = os.path.join(ROOT, "src", "ui.html")
24+OUT = os.path.join(ROOT, "src", "ui_html.h")
25+
26+TOKENS = "<!--TOKENS-->"
27+MARK_TOKENS = "\u0001"
28+MARK_HANDOFF = "\u0002"
29+
30+
31+def c_literal(text):
32+ """Escape text for a C string literal, one line per source line."""
33+ out = []
34+ for line in text.splitlines(True):
35+ piece = []
36+ for ch in line:
37+ if ch == "\\":
38+ piece.append("\\\\")
39+ elif ch == '"':
40+ piece.append('\\"')
41+ elif ch == "\n":
42+ piece.append("\\n")
43+ elif ch == "\r":
44+ piece.append("\\r")
45+ elif ch == "\t":
46+ piece.append("\\t")
47+ elif ch == MARK_TOKENS:
48+ piece.append("\\001")
49+ elif ch == MARK_HANDOFF:
50+ piece.append("\\002")
51+ elif ord(ch) < 0x20:
52+ piece.append("\\%03o" % ord(ch))
53+ else:
54+ piece.append(ch)
55+ out.append(' "%s"\n' % "".join(piece))
56+ return "".join(out)
57+
58+
59+def render():
60+ with open(SRC, "r", encoding="utf-8") as f:
61+ html = f.read()
62+
63+ if TOKENS not in html:
64+ raise SystemExit("src/ui.html has no %s placeholder" % TOKENS)
65+ html = html.replace(TOKENS, MARK_TOKENS)
66+
67+ # Handoff script goes right before the closing body tag.
68+ if "</body>" not in html:
69+ raise SystemExit("src/ui.html has no </body>")
70+ html = html.replace("</body>", MARK_HANDOFF + "</body>", 1)
71+
72+ header = (
73+ "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n"
74+ "#ifndef SX_AGYLOGIN_UI_HTML_H\n"
75+ "#define SX_AGYLOGIN_UI_HTML_H\n"
76+ "\n"
77+ "static const char *UI_HTML =\n" + c_literal(html) + " ;\n"
78+ "\n"
79+ "#endif /* SX_AGYLOGIN_UI_HTML_H */\n"
80+ )
81+ return header
82+
83+
84+def main():
85+ header = render()
86+ check = "--check" in sys.argv[1:]
87+ if check:
88+ try:
89+ with open(OUT, "r", encoding="utf-8") as f:
90+ cur = f.read()
91+ except OSError:
92+ cur = ""
93+ if cur != header:
94+ sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n")
95+ return 1
96+ print("src/ui.html.h is up to date")
97+ return 0
98+ with open(OUT, "w", encoding="utf-8") as f:
99+ f.write(header)
100+ print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header)))
101+ return 0
102+
103+
104+if __name__ == "__main__":
105+ sys.exit(main())
0106