| 1 | 1 | new file mode 100644 |
| index 0000000..35bc3e3 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | |
| 2 | +/plugin_copilot_login | |
| 3 | +/plugin_copilot_login.exe | |
| 4 | +/plugin_copilot_login.musl | |
| 5 | +/plugin_copilot_login.arm64 | |
| 6 | +/plugin_copilot_login.macos-arm64 | |
| 7 | +/plugin_copilot_login.macos-x86_64 | |
| 8 | +bin/ | |
| 9 | + | |
| 10 | +# test scratch | |
| 11 | +*.tmp | |
| 12 | +/tests/fixtures-out/ | |
| 13 | + | |
| 14 | +# python tooling | |
| 15 | +__pycache__/ | |
| 16 | +*.pyc |
| 1 | 1 | new 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. |
| 1 | 1 | new file mode 100644 |
| index 0000000..474763a | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,77 @@ | ||
| 1 | +# plugin_copilot_login - SCORPIOX BOT open-source GitHub Copilot device-code login for your node | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_copilot_login | |
| 5 | +# make musl static musl x86_64 -> ./plugin_copilot_login.musl | |
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_copilot_login.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_copilot_login.exe | |
| 8 | +# make macos Apple clang -> ./plugin_copilot_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 install copy the binary into this node's plugin directory | |
| 12 | +# make clean | |
| 13 | + | |
| 14 | +CC ?= cc | |
| 15 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src | |
| 16 | +MUSL_CC ?= musl-gcc | |
| 17 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | |
| 18 | +ARM_CC ?= aarch64-linux-gnu-gcc | |
| 19 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | |
| 20 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 21 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | |
| 22 | +SRC := src/plugin_copilot_login.c | |
| 23 | +UI_SRC := src/ui.html | |
| 24 | +UI_HDR := src/ui_html.h | |
| 25 | +BIN := plugin_copilot_login | |
| 26 | +EXE := plugin_copilot_login.exe | |
| 27 | + | |
| 28 | +.PHONY: all native musl arm64 win64 macos ui test install 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 -Wno-format-truncation -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 | +clean: | |
| 73 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 | |
| 74 | + rm -rf tests/__pycache__ | |
| 75 | + | |
| 76 | +help: | |
| 77 | + @sed -n '2,15p' $(MAKEFILE_LIST) |
| 1 | 1 | new file mode 100644 |
| index 0000000..1ada108 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,186 @@ | ||
| 1 | +# plugin_copilot_login | |
| 2 | + | |
| 3 | +An open-source **SCORPIOX BOT** plugin for **GitHub Copilot** device-code login | |
| 4 | +and token management on your own node. | |
| 5 | + | |
| 6 | +It is a single zero-dependency C99 binary that runs as a node plugin: it starts | |
| 7 | +the GitHub OAuth device flow, shows the one-time code on a page you can open | |
| 8 | +from anywhere, polls GitHub until you approve the code on any device, then | |
| 9 | +reports your session state and the expiry of the derived Copilot token - and | |
| 10 | +refreshes that token on demand. | |
| 11 | + | |
| 12 | +``` | |
| 13 | + node github.com | |
| 14 | + ---- ---------- | |
| 15 | + plugin_copilot_login --start--> scorpiox-copilot-login | |
| 16 | + POST /login/device/code | |
| 17 | + <-- user_code 1234-5678, device_code | |
| 18 | + page shows the code | | |
| 19 | + you type it on any device -----------> approve | |
| 20 | + plugin_copilot_login --poll--> scorpiox-copilot-login | |
| 21 | + POST /login/oauth/access_token | |
| 22 | + <-- access_token gho_... | |
| 23 | + writes ~/.copilot/.credentials.json | |
| 24 | +``` | |
| 25 | + | |
| 26 | +## Why it never holds a secret | |
| 27 | + | |
| 28 | +GitHub's device flow still carries an OAuth **client id**, and a token exchange | |
| 29 | +is an HTTPS POST. A public repository must never ship either a client secret or | |
| 30 | +TLS client code that pretends to be one. So this plugin does not speak TLS at | |
| 31 | +all: it drives the `scorpiox-copilot-login` CLI that ships with SCORPIOX CODE, | |
| 32 | +in its documented machine mode (`SXLOGIN-MACHINE-V1`, one JSON line per call), | |
| 33 | +and reads only the files that CLI writes. | |
| 34 | + | |
| 35 | +What that buys you: | |
| 36 | + | |
| 37 | +* **No token ever reaches a response.** Every JSON field is token *presence* and | |
| 38 | + *expiry*. The refresh action inspects the CLI's payload for the `access_token` | |
| 39 | + key and throws the payload away; the new state is proven by re-reading the | |
| 40 | + cache file, never by the CLI's word. | |
| 41 | +* **Nothing is trusted from the browser.** The user code is relayed verbatim, | |
| 42 | + the account name is validated against a shell- and path-safe alphabet, and the | |
| 43 | + CLI path comes from an environment variable the node owner sets, never from a | |
| 44 | + query string. | |
| 45 | +* **The page is self-contained.** No CDN, no external asset, a CSP that forbids | |
| 46 | + remote scripts, and no `Content-Length` header (the fronting proxy rejects it). | |
| 47 | + | |
| 48 | +## Install | |
| 49 | + | |
| 50 | +### 1-click, pre-compiled | |
| 51 | + | |
| 52 | +Browse **https://botmarket.scorpiox.net** and install *GitHub Copilot Login*, or | |
| 53 | +fetch a pre-built binary directly: | |
| 54 | + | |
| 55 | +```sh | |
| 56 | +# universal static Linux (Alpine, Debian, Ubuntu, Arch, Omarchy) | |
| 57 | +curl -fsSL https://dist.scorpiox.net/bot-plugins/copilot-login/latest.json | |
| 58 | + | |
| 59 | +mkdir -p ~/.scorpiox/plugins | |
| 60 | +curl -fsSL -o ~/.scorpiox/plugins/plugin_copilot_login \ | |
| 61 | + https://dist.scorpiox.net/bot-plugins/copilot-login/1.0.0/linux-x86_64-musl/plugin_copilot_login | |
| 62 | +chmod 0755 ~/.scorpiox/plugins/plugin_copilot_login | |
| 63 | +``` | |
| 64 | + | |
| 65 | +The bot picks the plugin up on its next scan; no server restart. | |
| 66 | + | |
| 67 | +### Compile from source | |
| 68 | + | |
| 69 | +```sh | |
| 70 | +git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-copilot-login.git | |
| 71 | +cd scorpiox-bot-plugin-copilot-login | |
| 72 | + | |
| 73 | +make # native Linux/macOS | |
| 74 | +make musl # static x86_64, the universal Linux artifact | |
| 75 | +make arm64 # static aarch64 (Raspberry Pi 5, ARM servers) | |
| 76 | +make win64 # static Win64 PE (MinGW-w64) | |
| 77 | +make install # copy into ~/.scorpiox/plugins | |
| 78 | +``` | |
| 79 | + | |
| 80 | +On Windows, from PowerShell: | |
| 81 | + | |
| 82 | +```powershell | |
| 83 | +powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 84 | +``` | |
| 85 | + | |
| 86 | +The binary has no runtime dependencies. `make test` runs the offline suite. | |
| 87 | + | |
| 88 | +## Modes | |
| 89 | + | |
| 90 | +### 1. Discovery | |
| 91 | + | |
| 92 | +```sh | |
| 93 | +./plugin_copilot_login --meta | |
| 94 | +{"name":"copilot","desc":"Copilot login"} | |
| 95 | +``` | |
| 96 | + | |
| 97 | +Reachable without a password and without touching any credential file. The bot | |
| 98 | +uses it to list the plugin. | |
| 99 | + | |
| 100 | +### 2. JSON API | |
| 101 | + | |
| 102 | +All callbacks are `?action=...` and answer with one JSON object. `format=json` | |
| 103 | +alone means `status`, and `?name=<account>` targets a named account. | |
| 104 | + | |
| 105 | +| Action | What it does | | |
| 106 | +|--------|--------------| | |
| 107 | +| `status` | Reads the credentials file, `config.json`, the token cache and the account directory; also asks the CLI. Answers `logged_in`, `user`, `account`, `pending`, `expired`, `expires_in_sec`, `scope`, `accounts`. | | |
| 108 | +| `start` | Starts the device flow. Answers `flow`, `verify_url`, `user_code`, `interval`, `expires_in`. | | |
| 109 | +| `poll` | One non-blocking poll. Answers `state:"pending"`, or `state:"done"` with the fresh status once you approve on GitHub. | | |
| 110 | +| `cancel` | Drops the pending flow. | | |
| 111 | +| `refresh` | Derives a fresh Copilot token through the CLI and re-reads the cache. Answers `refreshed:true` plus the new status. | | |
| 112 | +| `accounts` | Lists the named account files and which one is active. | | |
| 113 | + | |
| 114 | +```sh | |
| 115 | +curl -s -H "X-Bot-Password: $BOT_PASSWORD" \ | |
| 116 | + 'http://127.0.0.1:8150/plugin_copilot_login?action=status' | |
| 117 | +``` | |
| 118 | + | |
| 119 | +```json | |
| 120 | +{"ok":true,"logged_in":true,"user":"octocat","account":"default", | |
| 121 | + "pending":false,"expires_in_sec":1740,"expired":false,"cache_present":true, | |
| 122 | + "cli_present":true,"scope":"read:user","profile":"claude-sonnet-5", | |
| 123 | + "accounts":[{"name":"work","logged_in":true,"expires_in_sec":1740,"expired":false}], | |
| 124 | + "flow":"device_code","protocol":"SXLOGIN-MACHINE-V1"} | |
| 125 | +``` | |
| 126 | + | |
| 127 | +### 3. HTML page | |
| 128 | + | |
| 129 | +`GET` (or `?embed=1`) returns the responsive page: a connection pill, a GitHub | |
| 130 | +user badge, the device-flow card with a large user code and a | |
| 131 | +**Copy Code & Open GitHub** button, a live polling indicator that re-checks | |
| 132 | +`action=poll` every `interval` seconds, a named-account switcher, and a refresh | |
| 133 | +button. It follows the bot's theme through the standard handoff, works down to | |
| 134 | +390 px and inside the Chat floating window. | |
| 135 | + | |
| 136 | +## Files it reads | |
| 137 | + | |
| 138 | +| Path | Purpose | | |
| 139 | +|------|---------| | |
| 140 | +| `~/.copilot/.credentials.json` | `github_token` (`gho_...`), `scope`, `timestamp` | | |
| 141 | +| `~/.copilot/config.json` | `lastLoggedInUser.login` - the only place the GitHub user name lives | | |
| 142 | +| `~/.copilot/.copilot-token-cache.json` | derived Copilot token and its `expires_at` | | |
| 143 | +| `~/.copilot/accounts/<name>.json` | named accounts, same shape as the credentials file | | |
| 144 | +| `~/.claude/.login-pending/copilot-<name>.json` | the pending device flow, written by the CLI | | |
| 145 | +| `~/.claude/scorpiox-env/copilot.txt` | the `PROVIDER=copilot` profile written by `--create-profile` | | |
| 146 | + | |
| 147 | +Every one of these is overridable for deterministic offline testing: | |
| 148 | + | |
| 149 | +``` | |
| 150 | +COPILOT_CREDS_PATH COPILOT_ACCOUNTS_DIR COPILOT_PENDING_DIR | |
| 151 | +COPILOT_ENV_DIR COPILOT_LOGIN_BIN COPILOT_REFRESH_BIN | |
| 152 | +``` | |
| 153 | + | |
| 154 | +## Tests | |
| 155 | + | |
| 156 | +`tests/run.sh` is fully offline: it points both CLIs at `tests/mock_login.sh` | |
| 157 | +and `tests/mock_refresh.sh`, keeps every credential path inside a throwaway | |
| 158 | +directory, and proves 116 assertions - the metadata contract, the 401 gate, all | |
| 159 | +six actions including the pending/done/denied poll states, the named-account | |
| 160 | +scan, the refresh-failure path, the HTML page contract and a source audit for | |
| 161 | +secrets, LAN addresses, `Content-Length` and emoji. | |
| 162 | + | |
| 163 | +```sh | |
| 164 | +make test | |
| 165 | +``` | |
| 166 | + | |
| 167 | +## Security model | |
| 168 | + | |
| 169 | +Read this before installing anything that runs as a plugin. | |
| 170 | + | |
| 171 | +* The plugin executes **native code** with the node user's full OS permissions. | |
| 172 | +* It spawns two child processes (`scorpiox-copilot-login`, | |
| 173 | + `scorpiox-copilot-refreshtoken`). Those children talk to GitHub over TLS; this | |
| 174 | + plugin does not open a socket of its own. | |
| 175 | +* It **never** prints, logs or returns a token. A missing `gho_` token is | |
| 176 | + reported as `logged_in:false`, not as an empty field you could mistake for a | |
| 177 | + live session. | |
| 178 | +* It performs no destructive action. The only write paths are the ones the CLI | |
| 179 | + owns; `cancel` removes a pending marker file and nothing else. | |
| 180 | + | |
| 181 | +## License | |
| 182 | + | |
| 183 | +MIT. Copyright (c) 2026 SCORPIOX INC. | |
| 184 | + | |
| 185 | +Source: https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-copilot-login | |
| 186 | +Registry: https://dist.scorpiox.net/bot-plugins/copilot-login/ |
| 1 | 1 | new file mode 100644 |
| index 0000000..b36a2fb | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,51 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_copilot_login | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_copilot_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_copilot_login.c" | |
| 14 | + $Out = Join-Path $ScriptDir "plugin_copilot_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_copilot_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_copilot_login.exe --meta" | |
| 49 | +} finally { | |
| 50 | + Pop-Location | |
| 51 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..030fa7d | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,16 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "copilot-login", | |
| 3 | + "id": "plugin_copilot_login", | |
| 4 | + "title": "GitHub Copilot Login", | |
| 5 | + "summary": "Zero-dependency GitHub Copilot device-code login and token manager for your node. Starts the OAuth device flow at github.com/login/device, shows the one-time code, polls GitHub until you approve it on any device, then reports session state, the derived token expiry and the named account files - and refreshes the derived 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, config and token-cache 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-copilot-login and scorpiox-copilot-refreshtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to GitHub over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only ~/.copilot/.credentials.json, ~/.copilot/config.json, ~/.copilot/.copilot-token-cache.json, ~/.copilot/accounts/, the pending device-flow marker and the copilot profile file, 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-copilot-login" | |
| 16 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..5380b2c | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,365 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh - build, scan and publish plugin_copilot_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="copilot-login" | |
| 33 | +ID="plugin_copilot_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 -Wno-format-truncation -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 -Wno-format-truncation -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 -Wno-format-truncation -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 -Wno-format-truncation \ | |
| 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 -Wno-format-truncation -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": "copilot",\n' | |
| 225 | + printf ' "desc": "Copilot login",\n' | |
| 226 | + printf ' "title": "GitHub Copilot Login",\n' | |
| 227 | + printf ' "summary": "Zero-dependency GitHub Copilot device-code login and token manager for your node. Starts the OAuth device flow at github.com/login/device, shows the one-time code, polls GitHub until you approve it on any device, then reports session state, the derived token expiry and the named account files - and refreshes the derived 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, config and token-cache 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-copilot-login and scorpiox-copilot-refreshtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to GitHub over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only the Copilot credential file, the config file, the derived-token cache, the named account files and the login-pending marker, 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" |
| 1 | 1 | new 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 */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..8c68ea2 | ||
| --- /dev/null | ||
| +++ b/src/plugin_copilot_login.c | ||
| @@ -0,0 +1,1587 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_copilot_login - SCORPIOX BOT open-source GitHub Copilot device-code | |
| 3 | + * login and token manager for your node. | |
| 4 | + * | |
| 5 | + * A single clean-room C99 binary that serves THREE modes: | |
| 6 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | |
| 7 | + * 2. ?action=... / ?format=json -> JSON node API | |
| 8 | + * 3. GET (default) -> responsive HTML UI | |
| 9 | + * | |
| 10 | + * DESIGN NOTE (why there is no TLS and no OAuth client secret here): the | |
| 11 | + * GitHub Copilot device flow is an HTTPS POST that carries an OAuth client | |
| 12 | + * identity. A public clean-room repository must never carry such a secret, so | |
| 13 | + * this plugin does not speak TLS at all. It drives the node's own SCORPIOX CODE | |
| 14 | + * login CLI, exactly the way the machine-mode contract intends | |
| 15 | + * (--status / --start / --poll / --cancel, one JSON line per call), and it | |
| 16 | + * reads only the credential files that CLI writes: | |
| 17 | + * | |
| 18 | + * ~/.copilot/.credentials.json (github_token, scope, timestamp) | |
| 19 | + * ~/.copilot/config.json (lastLoggedInUser.login) | |
| 20 | + * ~/.copilot/.copilot-token-cache.json (copilot JWT + expiry) | |
| 21 | + * ~/.copilot/accounts/<name>.json (named accounts) | |
| 22 | + * ~/.claude/.login-pending/copilot-*.json (pending device flow) | |
| 23 | + * ~/.claude/scorpiox-env/copilot.txt (PROVIDER/MODEL profile) | |
| 24 | + * | |
| 25 | + * Every path and both binaries are overridable for deterministic offline tests: | |
| 26 | + * | |
| 27 | + * COPILOT_CREDS_PATH credentials file (also anchors the sibling paths) | |
| 28 | + * COPILOT_ACCOUNTS_DIR directory holding <name>.json account files | |
| 29 | + * COPILOT_PENDING_DIR directory holding the pending flow files | |
| 30 | + * COPILOT_ENV_DIR profile directory (copilot.txt) | |
| 31 | + * COPILOT_LOGIN_BIN login CLI (default scorpiox-copilot-login) | |
| 32 | + * COPILOT_REFRESH_BIN refresh CLI (default scorpiox-copilot-refreshtoken) | |
| 33 | + * | |
| 34 | + * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. Every response reports token | |
| 35 | + * presence and expiry only. The refresh action discards the payload its CLI | |
| 36 | + * prints and reports only success/failure plus the new expiry. | |
| 37 | + * | |
| 38 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 39 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 40 | + * scorpiox-server on the node. | |
| 41 | + * | |
| 42 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 43 | + */ | |
| 44 | + | |
| 45 | +/* Must come before every include on Windows: MinGW defaults to 0x502 | |
| 46 | + * (Server 2003), which hides the Win7+ APIs and the path helpers. */ | |
| 47 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 48 | +# define _WIN32_WINNT 0x0601 | |
| 49 | +#endif | |
| 50 | + | |
| 51 | +#if !defined(_WIN32) | |
| 52 | +# define _POSIX_C_SOURCE 200809L | |
| 53 | +# define _DEFAULT_SOURCE 1 | |
| 54 | +# if defined(__APPLE__) | |
| 55 | +# define _DARWIN_C_SOURCE 1 | |
| 56 | +# endif | |
| 57 | +#endif | |
| 58 | + | |
| 59 | +#include <stdio.h> | |
| 60 | +#include <stdlib.h> | |
| 61 | +#include <string.h> | |
| 62 | +#include <ctype.h> | |
| 63 | +#include <errno.h> | |
| 64 | +#include <time.h> | |
| 65 | +#include <stdarg.h> | |
| 66 | + | |
| 67 | +#if defined(_WIN32) | |
| 68 | +# define WIN32_LEAN_AND_MEAN | |
| 69 | +# include <windows.h> | |
| 70 | +# include <direct.h> | |
| 71 | +# include <io.h> | |
| 72 | +#else | |
| 73 | +# include <unistd.h> | |
| 74 | +# include <sys/stat.h> | |
| 75 | +# include <sys/types.h> | |
| 76 | +# include <dirent.h> | |
| 77 | +#endif | |
| 78 | + | |
| 79 | +#include "bot_theme_plugin.h" | |
| 80 | +#include "ui_html.h" | |
| 81 | + | |
| 82 | +#define PLUGIN_SLUG "copilot-login" | |
| 83 | +#define PLUGIN_ID "plugin_copilot_login" | |
| 84 | +#define PLUGIN_VER "1.0.0" | |
| 85 | +#define PLUGIN_NAME "copilot" | |
| 86 | +#define PLUGIN_DESC "Copilot login" | |
| 87 | + | |
| 88 | +#define PATH_SZ 1024 | |
| 89 | +#define NAME_SZ 96 | |
| 90 | +#define CODE_MAX 512 | |
| 91 | +#define CMD_SZ 4096 | |
| 92 | +#define OUT_MAX (256 * 1024) | |
| 93 | +#define FIELD_SZ 512 | |
| 94 | +#define MAX_ACCOUNTS 64 | |
| 95 | + | |
| 96 | +#define DEFAULT_LOGIN_BIN "scorpiox-copilot-login" | |
| 97 | +#define DEFAULT_REFRESH_BIN "scorpiox-copilot-refreshtoken" | |
| 98 | + | |
| 99 | +#define PENDING_TTL_SEC 900 | |
| 100 | +#define DEFAULT_INTERVAL 5 | |
| 101 | +#define DEFAULT_EXPIRES_IN 900 | |
| 102 | + | |
| 103 | +#if defined(_WIN32) | |
| 104 | +# define PATH_SEP '\\' | |
| 105 | +#else | |
| 106 | +# define PATH_SEP '/' | |
| 107 | +#endif | |
| 108 | + | |
| 109 | +/* ------------------------------------------------------------------ */ | |
| 110 | +/* Growable byte buffer */ | |
| 111 | +/* ------------------------------------------------------------------ */ | |
| 112 | + | |
| 113 | +typedef struct { | |
| 114 | + char *p; | |
| 115 | + size_t n; | |
| 116 | + size_t cap; | |
| 117 | +} buf_t; | |
| 118 | + | |
| 119 | +static void buf_init(buf_t *b) | |
| 120 | +{ | |
| 121 | + b->p = NULL; | |
| 122 | + b->n = 0; | |
| 123 | + b->cap = 0; | |
| 124 | +} | |
| 125 | + | |
| 126 | +static int buf_need(buf_t *b, size_t extra) | |
| 127 | +{ | |
| 128 | + size_t want = b->n + extra + 1; | |
| 129 | + char *np; | |
| 130 | + | |
| 131 | + if (want <= b->cap) return 1; | |
| 132 | + if (b->cap == 0) b->cap = 1024; | |
| 133 | + while (b->cap < want) { | |
| 134 | + if (b->cap > (size_t)32 * 1024 * 1024) return 0; | |
| 135 | + b->cap *= 2; | |
| 136 | + } | |
| 137 | + np = (char *)realloc(b->p, b->cap); | |
| 138 | + if (!np) return 0; | |
| 139 | + b->p = np; | |
| 140 | + return 1; | |
| 141 | +} | |
| 142 | + | |
| 143 | +static int buf_add(buf_t *b, const char *s, size_t n) | |
| 144 | +{ | |
| 145 | + if (!buf_need(b, n)) return 0; | |
| 146 | + memcpy(b->p + b->n, s, n); | |
| 147 | + b->n += n; | |
| 148 | + b->p[b->n] = '\0'; | |
| 149 | + return 1; | |
| 150 | +} | |
| 151 | + | |
| 152 | +static int buf_adds(buf_t *b, const char *s) | |
| 153 | +{ | |
| 154 | + return s ? buf_add(b, s, strlen(s)) : 1; | |
| 155 | +} | |
| 156 | + | |
| 157 | +static int buf_addc(buf_t *b, char c) | |
| 158 | +{ | |
| 159 | + return buf_add(b, &c, 1); | |
| 160 | +} | |
| 161 | + | |
| 162 | +static const char *buf_str(buf_t *b) | |
| 163 | +{ | |
| 164 | + if (!b->p) return ""; | |
| 165 | + return b->p; | |
| 166 | +} | |
| 167 | + | |
| 168 | +static void buf_free(buf_t *b) | |
| 169 | +{ | |
| 170 | + free(b->p); | |
| 171 | + b->p = NULL; | |
| 172 | + b->n = 0; | |
| 173 | + b->cap = 0; | |
| 174 | +} | |
| 175 | + | |
| 176 | +static int buf_addf(buf_t *b, const char *fmt, ...) | |
| 177 | +{ | |
| 178 | + char tmp[2048]; | |
| 179 | + int n; | |
| 180 | + va_list ap; | |
| 181 | + | |
| 182 | + va_start(ap, fmt); | |
| 183 | + n = vsnprintf(tmp, sizeof(tmp), fmt, ap); | |
| 184 | + va_end(ap); | |
| 185 | + if (n < 0) return 0; | |
| 186 | + if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n); | |
| 187 | + | |
| 188 | + { | |
| 189 | + char *big = (char *)malloc((size_t)n + 1); | |
| 190 | + int ok; | |
| 191 | + if (!big) return 0; | |
| 192 | + va_start(ap, fmt); | |
| 193 | + vsnprintf(big, (size_t)n + 1, fmt, ap); | |
| 194 | + va_end(ap); | |
| 195 | + ok = buf_add(b, big, (size_t)n); | |
| 196 | + free(big); | |
| 197 | + return ok; | |
| 198 | + } | |
| 199 | +} | |
| 200 | + | |
| 201 | +/* JSON string escape into a buffer (never emits a bare control byte). */ | |
| 202 | +static int buf_json(buf_t *b, const char *s) | |
| 203 | +{ | |
| 204 | + const unsigned char *p = (const unsigned char *)(s ? s : ""); | |
| 205 | + if (!buf_addc(b, '"')) return 0; | |
| 206 | + for (; *p; p++) { | |
| 207 | + switch (*p) { | |
| 208 | + case '"': if (!buf_adds(b, "\\\"")) return 0; break; | |
| 209 | + case '\\': if (!buf_adds(b, "\\\\")) return 0; break; | |
| 210 | + case '\n': if (!buf_adds(b, "\\n")) return 0; break; | |
| 211 | + case '\r': if (!buf_adds(b, "\\r")) return 0; break; | |
| 212 | + case '\t': if (!buf_adds(b, "\\t")) return 0; break; | |
| 213 | + default: | |
| 214 | + if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", *p)) return 0; } | |
| 215 | + else if (!buf_addc(b, (char)*p)) return 0; | |
| 216 | + } | |
| 217 | + } | |
| 218 | + return buf_addc(b, '"'); | |
| 219 | +} | |
| 220 | +/* ------------------------------------------------------------------ */ | |
| 221 | +/* Query string */ | |
| 222 | +/* ------------------------------------------------------------------ */ | |
| 223 | + | |
| 224 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 225 | +{ | |
| 226 | + size_t klen; | |
| 227 | + const char *p; | |
| 228 | + | |
| 229 | + if (!out || outsz == 0) return 0; | |
| 230 | + out[0] = '\0'; | |
| 231 | + if (!qs || !key) return 0; | |
| 232 | + klen = strlen(key); | |
| 233 | + p = qs; | |
| 234 | + while (p && *p) { | |
| 235 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 236 | + size_t i = 0; | |
| 237 | + p += klen + 1; | |
| 238 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | |
| 239 | + out[i] = '\0'; | |
| 240 | + return 1; | |
| 241 | + } | |
| 242 | + p = strchr(p, '&'); | |
| 243 | + if (!p) break; | |
| 244 | + p++; | |
| 245 | + } | |
| 246 | + return 0; | |
| 247 | +} | |
| 248 | + | |
| 249 | +static int query_has(const char *qs, const char *key) | |
| 250 | +{ | |
| 251 | + size_t klen; | |
| 252 | + const char *p; | |
| 253 | + | |
| 254 | + if (!qs || !key) return 0; | |
| 255 | + klen = strlen(key); | |
| 256 | + p = qs; | |
| 257 | + while (p && *p) { | |
| 258 | + if (strncmp(p, key, klen) == 0 && | |
| 259 | + (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) | |
| 260 | + return 1; | |
| 261 | + p = strchr(p, '&'); | |
| 262 | + if (!p) break; | |
| 263 | + p++; | |
| 264 | + } | |
| 265 | + return 0; | |
| 266 | +} | |
| 267 | + | |
| 268 | +/* ------------------------------------------------------------------ */ | |
| 269 | +/* Node auth (X-Bot-Password / Bearer / ?pwd=) */ | |
| 270 | +/* ------------------------------------------------------------------ */ | |
| 271 | + | |
| 272 | +static void require_node_auth(void) | |
| 273 | +{ | |
| 274 | + const char *np = getenv("BOT_PASSWORD"); | |
| 275 | + const char *xp; | |
| 276 | + const char *auth; | |
| 277 | + char qpwd[256] = {0}; | |
| 278 | + | |
| 279 | + if (!np || !*np) return; | |
| 280 | + | |
| 281 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 282 | + if (xp && strcmp(xp, np) == 0) return; | |
| 283 | + | |
| 284 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 285 | + if (auth) { | |
| 286 | + while (*auth == ' ') auth++; | |
| 287 | + if (strncasecmp(auth, "Bearer ", 7) == 0) { | |
| 288 | + auth += 7; | |
| 289 | + while (*auth == ' ') auth++; | |
| 290 | + if (strcmp(auth, np) == 0) return; | |
| 291 | + } | |
| 292 | + } | |
| 293 | + | |
| 294 | + if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && | |
| 295 | + strcmp(qpwd, np) == 0) | |
| 296 | + return; | |
| 297 | + | |
| 298 | + fputs("Status: 401 Unauthorized\r\n" | |
| 299 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 300 | + "Cache-Control: no-store\r\n\r\n" | |
| 301 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 302 | + exit(0); | |
| 303 | +} | |
| 304 | + | |
| 305 | + | |
| 306 | +/* ------------------------------------------------------------------ */ | |
| 307 | +/* Paths */ | |
| 308 | +/* ------------------------------------------------------------------ */ | |
| 309 | + | |
| 310 | +static const char *home_dir(void) | |
| 311 | +{ | |
| 312 | +#if defined(_WIN32) | |
| 313 | + static char home[512]; | |
| 314 | + DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); | |
| 315 | + if (n > 0 && n < sizeof(home)) return home; | |
| 316 | + home[0] = '\0'; | |
| 317 | + if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) { | |
| 318 | + char tmp[512]; | |
| 319 | + if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { | |
| 320 | + strncat(home, tmp, sizeof(home) - strlen(home) - 1); | |
| 321 | + return home; | |
| 322 | + } | |
| 323 | + } | |
| 324 | + return NULL; | |
| 325 | +#else | |
| 326 | + const char *h = getenv("HOME"); | |
| 327 | + return (h && *h) ? h : NULL; | |
| 328 | +#endif | |
| 329 | +} | |
| 330 | + | |
| 331 | +/* Copy the directory part of a path (including the trailing separator). */ | |
| 332 | +static void dir_of(const char *path, char *out, size_t n) | |
| 333 | +{ | |
| 334 | + char base[PATH_SZ]; | |
| 335 | + char *slash; | |
| 336 | + | |
| 337 | + if (!path) { if (n) out[0] = '\0'; return; } | |
| 338 | + snprintf(base, sizeof(base), "%s", path); | |
| 339 | + slash = strrchr(base, PATH_SEP); | |
| 340 | +#if defined(_WIN32) | |
| 341 | + if (!slash) slash = strrchr(base, '/'); | |
| 342 | +#endif | |
| 343 | + if (slash) *(slash + 1) = '\0'; | |
| 344 | + else base[0] = '\0'; | |
| 345 | + snprintf(out, n, "%s", base); | |
| 346 | +} | |
| 347 | + | |
| 348 | +/* A relocated credentials file implies the whole .copilot tree is relocated: | |
| 349 | + * the same CLI writes all of these into one directory. Reading one from the | |
| 350 | + * override and the rest from $HOME reports an empty state for a live session. */ | |
| 351 | +static void copilot_dir(char *out, size_t n) | |
| 352 | +{ | |
| 353 | + const char *env = getenv("COPILOT_CREDS_PATH"); | |
| 354 | + const char *home = home_dir(); | |
| 355 | + | |
| 356 | + if (env && *env) { | |
| 357 | + dir_of(env, out, n); | |
| 358 | + if (out[0]) return; | |
| 359 | + } | |
| 360 | + if (home && *home) { snprintf(out, n, "%s%c.copilot%c", home, PATH_SEP, PATH_SEP); return; } | |
| 361 | + snprintf(out, n, ".copilot%c", PATH_SEP); | |
| 362 | +} | |
| 363 | + | |
| 364 | +static void creds_path(char *out, size_t n) | |
| 365 | +{ | |
| 366 | + const char *env = getenv("COPILOT_CREDS_PATH"); | |
| 367 | + | |
| 368 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 369 | + { | |
| 370 | + char d[PATH_SZ]; | |
| 371 | + copilot_dir(d, sizeof(d)); | |
| 372 | + snprintf(out, n, "%s.credentials.json", d); | |
| 373 | + } | |
| 374 | +} | |
| 375 | + | |
| 376 | +static void config_path(char *out, size_t n) | |
| 377 | +{ | |
| 378 | + char d[PATH_SZ]; | |
| 379 | + copilot_dir(d, sizeof(d)); | |
| 380 | + snprintf(out, n, "%s%cconfig.json", d, PATH_SEP); | |
| 381 | +} | |
| 382 | + | |
| 383 | +static void cache_path(char *out, size_t n) | |
| 384 | +{ | |
| 385 | + char d[PATH_SZ]; | |
| 386 | + copilot_dir(d, sizeof(d)); | |
| 387 | + snprintf(out, n, "%s%c.copilot-token-cache.json", d, PATH_SEP); | |
| 388 | +} | |
| 389 | + | |
| 390 | +static void accounts_dir(char *out, size_t n) | |
| 391 | +{ | |
| 392 | + const char *env = getenv("COPILOT_ACCOUNTS_DIR"); | |
| 393 | + | |
| 394 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 395 | + { | |
| 396 | + char d[PATH_SZ]; | |
| 397 | + copilot_dir(d, sizeof(d)); | |
| 398 | + snprintf(out, n, "%saccounts", d); | |
| 399 | + } | |
| 400 | +} | |
| 401 | + | |
| 402 | +/* The pending device-flow marker is written by the login CLI into the shared | |
| 403 | + * login machine directory under $HOME (sx_login_machine.h), not next to the | |
| 404 | + * credentials file, so it has its own home-anchored path. */ | |
| 405 | +static void pending_dir(char *out, size_t n) | |
| 406 | +{ | |
| 407 | + const char *env = getenv("COPILOT_PENDING_DIR"); | |
| 408 | + const char *home = home_dir(); | |
| 409 | + | |
| 410 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 411 | + if (home && *home) { snprintf(out, n, "%s%c.claude%c.login-pending", home, PATH_SEP, PATH_SEP); return; } | |
| 412 | + snprintf(out, n, ".claude%c.login-pending", PATH_SEP); | |
| 413 | +} | |
| 414 | + | |
| 415 | +static void pending_path(const char *name, char *out, size_t n) | |
| 416 | +{ | |
| 417 | + char d[PATH_SZ]; | |
| 418 | + pending_dir(d, sizeof(d)); | |
| 419 | + snprintf(out, n, "%s%ccopilot-%s.json", d, PATH_SEP, (name && *name) ? name : "default"); | |
| 420 | +} | |
| 421 | + | |
| 422 | +static void env_dir(char *out, size_t n) | |
| 423 | +{ | |
| 424 | + const char *env = getenv("COPILOT_ENV_DIR"); | |
| 425 | + const char *home = home_dir(); | |
| 426 | + | |
| 427 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 428 | + if (home && *home) { snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); return; } | |
| 429 | + snprintf(out, n, ".claude%cscorpiox-env", PATH_SEP); | |
| 430 | +} | |
| 431 | + | |
| 432 | +static void profile_path(char *out, size_t n) | |
| 433 | +{ | |
| 434 | + char d[PATH_SZ]; | |
| 435 | + env_dir(d, sizeof(d)); | |
| 436 | + snprintf(out, n, "%s%ccopilot.txt", d, PATH_SEP); | |
| 437 | +} | |
| 438 | + | |
| 439 | +static void account_path(const char *name, char *out, size_t n) | |
| 440 | +{ | |
| 441 | + char d[PATH_SZ]; | |
| 442 | + accounts_dir(d, sizeof(d)); | |
| 443 | + snprintf(out, n, "%s%c%s.json", d, PATH_SEP, name); | |
| 444 | +} | |
| 445 | + | |
| 446 | +static const char *login_bin(void) | |
| 447 | +{ | |
| 448 | + const char *e = getenv("COPILOT_LOGIN_BIN"); | |
| 449 | + return (e && *e) ? e : DEFAULT_LOGIN_BIN; | |
| 450 | +} | |
| 451 | + | |
| 452 | +static const char *refresh_bin(void) | |
| 453 | +{ | |
| 454 | + const char *e = getenv("COPILOT_REFRESH_BIN"); | |
| 455 | + return (e && *e) ? e : DEFAULT_REFRESH_BIN; | |
| 456 | +} | |
| 457 | + | |
| 458 | +static int file_exists(const char *p) | |
| 459 | +{ | |
| 460 | +#if defined(_WIN32) | |
| 461 | + DWORD a = GetFileAttributesA(p); | |
| 462 | + return p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); | |
| 463 | +#else | |
| 464 | + struct stat st; | |
| 465 | + return p && stat(p, &st) == 0 && S_ISREG(st.st_mode); | |
| 466 | +#endif | |
| 467 | +} | |
| 468 | + | |
| 469 | +/* Read a whole file. Returns a malloc'd NUL-terminated buffer or NULL. */ | |
| 470 | +static char *read_file(const char *path) | |
| 471 | +{ | |
| 472 | + FILE *f; | |
| 473 | + long sz; | |
| 474 | + char *buf; | |
| 475 | + | |
| 476 | + if (!path || !*path) return NULL; | |
| 477 | + f = fopen(path, "rb"); | |
| 478 | + if (!f) return NULL; | |
| 479 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } | |
| 480 | + sz = ftell(f); | |
| 481 | + if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } | |
| 482 | + if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } | |
| 483 | + buf = (char *)malloc((size_t)sz + 1); | |
| 484 | + if (!buf) { fclose(f); return NULL; } | |
| 485 | + if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { | |
| 486 | + free(buf); | |
| 487 | + fclose(f); | |
| 488 | + return NULL; | |
| 489 | + } | |
| 490 | + buf[sz] = '\0'; | |
| 491 | + fclose(f); | |
| 492 | + return buf; | |
| 493 | +} | |
| 494 | + | |
| 495 | +/* Trim trailing CR/LF/space in place. */ | |
| 496 | +static void trim_tail(char *s) | |
| 497 | +{ | |
| 498 | + size_t n; | |
| 499 | + | |
| 500 | + if (!s) return; | |
| 501 | + n = strlen(s); | |
| 502 | + while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || | |
| 503 | + s[n - 1] == ' ' || s[n - 1] == '\t')) | |
| 504 | + s[--n] = '\0'; | |
| 505 | +} | |
| 506 | + | |
| 507 | +/* Account names are used verbatim in a file name, so they are restricted to a | |
| 508 | + * shell- and path-safe alphabet. */ | |
| 509 | +static int name_valid(const char *n) | |
| 510 | +{ | |
| 511 | + const char *p; | |
| 512 | + | |
| 513 | + if (!n || !*n || strlen(n) > 64) return 0; | |
| 514 | + if (n[0] == '.') return 0; | |
| 515 | + for (p = n; *p; p++) { | |
| 516 | + unsigned char c = (unsigned char)*p; | |
| 517 | + if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0; | |
| 518 | + } | |
| 519 | + return 1; | |
| 520 | +} | |
| 521 | + | |
| 522 | +/* ------------------------------------------------------------------ */ | |
| 523 | +/* Minimal JSON field readers */ | |
| 524 | +/* ------------------------------------------------------------------ */ | |
| 525 | + | |
| 526 | +/* Copy a JSON string value that starts at *pp (pointing at the opening quote) | |
| 527 | + * and advance *pp past the closing quote. */ | |
| 528 | +static int json_read_string_at(const char **pp, char *out, size_t outsz) | |
| 529 | +{ | |
| 530 | + const char *p = *pp; | |
| 531 | + size_t i = 0; | |
| 532 | + | |
| 533 | + if (!p || *p != '"') return 0; | |
| 534 | + p++; | |
| 535 | + while (*p && *p != '"') { | |
| 536 | + char c = *p; | |
| 537 | + if (c == '\\' && p[1]) { | |
| 538 | + p++; | |
| 539 | + switch (*p) { | |
| 540 | + case 'n': c = '\n'; break; | |
| 541 | + case 'r': c = '\r'; break; | |
| 542 | + case 't': c = '\t'; break; | |
| 543 | + case 'b': c = '\b'; break; | |
| 544 | + case 'f': c = '\f'; break; | |
| 545 | + case 'u': { | |
| 546 | + unsigned int v = 0; | |
| 547 | + int k; | |
| 548 | + p++; | |
| 549 | + for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) | |
| 550 | + v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) | |
| 551 | + ? *p - '0' | |
| 552 | + : tolower((unsigned char)*p) - 'a' + 10); | |
| 553 | + if (i + 1 < outsz) out[i++] = (char)(v & 0xff); | |
| 554 | + continue; | |
| 555 | + } | |
| 556 | + default: c = *p; break; | |
| 557 | + } | |
| 558 | + p++; | |
| 559 | + } else { | |
| 560 | + p++; | |
| 561 | + } | |
| 562 | + if (i + 1 < outsz) out[i++] = c; | |
| 563 | + } | |
| 564 | + if (*p == '"') p++; | |
| 565 | + if (outsz) out[i < outsz ? i : outsz - 1] = '\0'; | |
| 566 | + *pp = p; | |
| 567 | + return 1; | |
| 568 | +} | |
| 569 | + | |
| 570 | +/* Find "key":<value> among the TOP-LEVEL keys of the slice [obj, end). | |
| 571 | + * A nested object is skipped as a whole. | |
| 572 | + * | |
| 573 | + * A caller almost always hands us a pointer at the opening '{'; that brace is | |
| 574 | + * skipped inside the reader so no call site needs a "+1" that is easy to | |
| 575 | + * forget and completely silent when it is missing. */ | |
| 576 | +static const char *json_find_key(const char *obj, const char *end, const char *key) | |
| 577 | +{ | |
| 578 | + size_t klen; | |
| 579 | + const char *p; | |
| 580 | + int depth = 0; | |
| 581 | + | |
| 582 | + if (!obj || !end || !key) return NULL; | |
| 583 | + klen = strlen(key); | |
| 584 | + p = obj; | |
| 585 | + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; | |
| 586 | + if (p < end && *p == '{') p++; | |
| 587 | + | |
| 588 | + while (p && p < end) { | |
| 589 | + if (*p == '"') { | |
| 590 | + char name[128]; | |
| 591 | + json_read_string_at(&p, name, sizeof(name)); | |
| 592 | + if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { | |
| 593 | + const char *q = p; | |
| 594 | + while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; | |
| 595 | + if (q < end && *q == ':') { | |
| 596 | + q++; | |
| 597 | + while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; | |
| 598 | + return (q < end) ? q : NULL; | |
| 599 | + } | |
| 600 | + } | |
| 601 | + continue; | |
| 602 | + } | |
| 603 | + if (*p == '{' || *p == '[') depth++; | |
| 604 | + else if (*p == '}' || *p == ']') depth--; | |
| 605 | + p++; | |
| 606 | + } | |
| 607 | + return NULL; | |
| 608 | +} | |
| 609 | + | |
| 610 | +/* Returns 0 and leaves *out untouched when the key is absent or null. That | |
| 611 | + * matters: several callers pass a field of a longer-lived struct, and clearing | |
| 612 | + * it on a miss silently erases a value that was already correct. */ | |
| 613 | +static int json_str_field(const char *obj, const char *end, const char *key, | |
| 614 | + char *out, size_t outsz) | |
| 615 | +{ | |
| 616 | + const char *v; | |
| 617 | + | |
| 618 | + if (!out || outsz == 0) return 0; | |
| 619 | + v = json_find_key(obj, end, key); | |
| 620 | + if (!v || *v == 'n') return 0; | |
| 621 | + if (*v == '"') return json_read_string_at(&v, out, outsz); | |
| 622 | + { | |
| 623 | + size_t i = 0; | |
| 624 | + out[0] = '\0'; | |
| 625 | + while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; | |
| 626 | + out[i] = '\0'; | |
| 627 | + trim_tail(out); | |
| 628 | + return out[0] ? 1 : 0; | |
| 629 | + } | |
| 630 | +} | |
| 631 | + | |
| 632 | +static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) | |
| 633 | +{ | |
| 634 | + const char *v = json_find_key(obj, end, key); | |
| 635 | + | |
| 636 | + if (!v) return dflt; | |
| 637 | + if (strncmp(v, "true", 4) == 0) return 1; | |
| 638 | + if (strncmp(v, "false", 5) == 0) return 0; | |
| 639 | + if (*v == '"') { | |
| 640 | + if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1; | |
| 641 | + return 0; | |
| 642 | + } | |
| 643 | + if (*v == '1') return 1; | |
| 644 | + return 0; | |
| 645 | +} | |
| 646 | + | |
| 647 | +static long long json_num_field(const char *obj, const char *end, const char *key) | |
| 648 | +{ | |
| 649 | + const char *v = json_find_key(obj, end, key); | |
| 650 | + | |
| 651 | + if (!v) return 0; | |
| 652 | + if (*v == '"') v++; | |
| 653 | + return atoll(v); | |
| 654 | +} | |
| 655 | + | |
| 656 | +/* ------------------------------------------------------------------ */ | |
| 657 | +/* Child processes */ | |
| 658 | +/* ------------------------------------------------------------------ */ | |
| 659 | + | |
| 660 | +/* Quote one argv element for the shell popen() uses. POSIX: single quotes with | |
| 661 | + * the standard close-escape-reopen trick. Windows: double quotes, which is | |
| 662 | + * what cmd.exe accepts. */ | |
| 663 | +static void shell_quote_into(const char *in, char *out, size_t outsz) | |
| 664 | +{ | |
| 665 | + size_t o = 0; | |
| 666 | + const char *p; | |
| 667 | + | |
| 668 | + if (outsz < 3) { if (outsz) out[0] = '\0'; return; } | |
| 669 | +#if defined(_WIN32) | |
| 670 | + out[o++] = '"'; | |
| 671 | + for (p = in; p && *p; p++) { | |
| 672 | + if (*p == '"') { | |
| 673 | + if (o + 3 >= outsz) break; | |
| 674 | + out[o++] = '\\'; | |
| 675 | + out[o++] = '"'; | |
| 676 | + } else { | |
| 677 | + if (o + 2 >= outsz) break; | |
| 678 | + out[o++] = *p; | |
| 679 | + } | |
| 680 | + } | |
| 681 | + out[o++] = '"'; | |
| 682 | + out[o] = '\0'; | |
| 683 | +#else | |
| 684 | + out[o++] = '\''; | |
| 685 | + for (p = in; p && *p; p++) { | |
| 686 | + if (*p == '\'') { | |
| 687 | + if (o + 5 >= outsz) break; | |
| 688 | + memcpy(out + o, "'\\''", 4); | |
| 689 | + o += 4; | |
| 690 | + } else { | |
| 691 | + if (o + 2 >= outsz) break; | |
| 692 | + out[o++] = *p; | |
| 693 | + } | |
| 694 | + } | |
| 695 | + out[o++] = '\''; | |
| 696 | + out[o] = '\0'; | |
| 697 | +#endif | |
| 698 | +} | |
| 699 | + | |
| 700 | +/* Is <bin> resolvable on this node? POSIX answers through popen's own 127 | |
| 701 | + * ("command not found"). cmd.exe returns 1 for a missing program, which is | |
| 702 | + * indistinguishable from the program's own failure - so on Windows the path is | |
| 703 | + * resolved BEFORE popen with SearchPathA. Without this, a Windows node with no | |
| 704 | + * SCORPIOX CODE reported cli_present:true and "start failed" instead of | |
| 705 | + * cli_unavailable (measured on a real Windows box). */ | |
| 706 | +static int bin_available(const char *bin) | |
| 707 | +{ | |
| 708 | + if (!bin || !*bin) return 0; | |
| 709 | +#if defined(_WIN32) | |
| 710 | + { | |
| 711 | + char full[MAX_PATH]; | |
| 712 | + DWORD n; | |
| 713 | + /* An explicit path is checked directly; a bare name is searched on PATH. */ | |
| 714 | + if (strchr(bin, '\\') || strchr(bin, '/') || strchr(bin, ':')) | |
| 715 | + return file_exists(bin); | |
| 716 | + n = SearchPathA(NULL, bin, ".exe", (DWORD)sizeof(full), full, NULL); | |
| 717 | + return n > 0 && n < (DWORD)sizeof(full); | |
| 718 | + } | |
| 719 | +#else | |
| 720 | + return 1; /* decided by run_capture's own 127 check */ | |
| 721 | +#endif | |
| 722 | +} | |
| 723 | + | |
| 724 | +/* Run `<bin> <args>` and capture stdout. | |
| 725 | + * Returns 1 when the process ran, | |
| 726 | + * 0 when popen() itself failed, | |
| 727 | + * -1 when the binary is not on this node ("command not found"). | |
| 728 | + * | |
| 729 | + * pclose() hands back a WAIT STATUS, not an exit code: a missing command | |
| 730 | + * arrives as 32512 (127 << 8). Treating that as the tool's own failure would | |
| 731 | + * report "refresh failed" for a node that simply has no SCORPIOX CODE. */ | |
| 732 | +static int run_capture(const char *bin, const char *args, buf_t *out) | |
| 733 | +{ | |
| 734 | + char cmd[CMD_SZ]; | |
| 735 | + char qbin[FIELD_SZ]; | |
| 736 | + FILE *f; | |
| 737 | + char line[2048]; | |
| 738 | + size_t total = 0; | |
| 739 | + int rc; | |
| 740 | + | |
| 741 | + if (!bin || !*bin) return 0; | |
| 742 | + if (!bin_available(bin)) return -1; | |
| 743 | + shell_quote_into(bin, qbin, sizeof(qbin)); | |
| 744 | +#if defined(_WIN32) | |
| 745 | + if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args); | |
| 746 | + else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin); | |
| 747 | +#else | |
| 748 | + if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); | |
| 749 | + else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); | |
| 750 | +#endif | |
| 751 | + | |
| 752 | + f = popen(cmd, "r"); | |
| 753 | + if (!f) return 0; | |
| 754 | + while (fgets(line, sizeof(line), f)) { | |
| 755 | + total += strlen(line); | |
| 756 | + if (total > OUT_MAX) break; | |
| 757 | + buf_adds(out, line); | |
| 758 | + } | |
| 759 | + rc = pclose(f); | |
| 760 | + | |
| 761 | + if (out->p) { | |
| 762 | + size_t n = out->n; | |
| 763 | + while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; | |
| 764 | + out->n = n; | |
| 765 | + } | |
| 766 | + if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1; | |
| 767 | + return 1; | |
| 768 | +} | |
| 769 | + | |
| 770 | +/* The CLIs print human progress before the final JSON line, so take the LAST | |
| 771 | + * line that starts with '{'. */ | |
| 772 | +static const char *last_json_line(buf_t *b) | |
| 773 | +{ | |
| 774 | + size_t i; | |
| 775 | + const char *last = NULL; | |
| 776 | + | |
| 777 | + if (!b || !b->p) return NULL; | |
| 778 | + for (i = 0; i < b->n; i++) { | |
| 779 | + int at_line_start = (i == 0) || b->p[i - 1] == '\n'; | |
| 780 | + if (at_line_start && b->p[i] == '{') last = b->p + i; | |
| 781 | + } | |
| 782 | + return last; | |
| 783 | +} | |
| 784 | + | |
| 785 | + | |
| 786 | +/* ------------------------------------------------------------------ */ | |
| 787 | +/* Status assembly */ | |
| 788 | +/* ------------------------------------------------------------------ */ | |
| 789 | + | |
| 790 | +/* Copilot has no refresh token: the device flow mints a long-lived `gho_` | |
| 791 | + * token, and the short-lived JWT is derived from it on demand. expiresAt is in | |
| 792 | + * milliseconds in this file format but a hand-written fixture may carry | |
| 793 | + * seconds, so detect by magnitude rather than trusting either form. */ | |
| 794 | +static long long to_sec(long long v) | |
| 795 | +{ | |
| 796 | + return (v > 100000000000LL) ? (v / 1000) : v; | |
| 797 | +} | |
| 798 | + | |
| 799 | +typedef struct { | |
| 800 | + char name[NAME_SZ]; | |
| 801 | + int present; | |
| 802 | + int logged_in; | |
| 803 | + int expired; | |
| 804 | + long long expires_in_sec; | |
| 805 | +} account_t; | |
| 806 | + | |
| 807 | +typedef struct { | |
| 808 | + int logged_in; | |
| 809 | + int pending; | |
| 810 | + int expired; | |
| 811 | + int cli_present; | |
| 812 | + int profile_exists; | |
| 813 | + int cache_present; | |
| 814 | + char account[NAME_SZ]; | |
| 815 | + char user[NAME_SZ]; | |
| 816 | + char path[PATH_SZ]; | |
| 817 | + char pending_file[PATH_SZ]; | |
| 818 | + char profile[NAME_SZ]; | |
| 819 | + char profile_file[PATH_SZ]; | |
| 820 | + char scope[256]; | |
| 821 | + char cli_error[FIELD_SZ]; | |
| 822 | + char user_code[NAME_SZ]; | |
| 823 | + char verify_url[FIELD_SZ]; | |
| 824 | + int interval; | |
| 825 | + int expires_in; | |
| 826 | + long long expires_at; /* seconds since epoch from the token cache */ | |
| 827 | + long long expires_in_sec; /* negative when expired, 0 when unknown */ | |
| 828 | + account_t accounts[MAX_ACCOUNTS]; | |
| 829 | + int account_count; | |
| 830 | +} status_t; | |
| 831 | + | |
| 832 | +/* Find a github_token-shaped value. The CLI writes "github_token" in | |
| 833 | + * ~/.copilot/.credentials.json; VS Code writes "token". Only presence is | |
| 834 | + * reported, never the value. */ | |
| 835 | +static int scan_token(const char *json, const char *key) | |
| 836 | +{ | |
| 837 | + char tok[8] = {0}; | |
| 838 | + | |
| 839 | + if (!json) return 0; | |
| 840 | + if (json_str_field(json, json + strlen(json), key, tok, sizeof(tok))) return 1; | |
| 841 | + /* Anywhere in the file (config.json nests it two levels deep). */ | |
| 842 | + { | |
| 843 | + char pat[64]; | |
| 844 | + snprintf(pat, sizeof(pat), "\"%s\"", key); | |
| 845 | + if (strstr(json, pat)) { | |
| 846 | + const char *p = strstr(json, pat); | |
| 847 | + const char *colon = p ? strchr(p, ':') : NULL; | |
| 848 | + const char *q = colon ? strchr(colon, '"') : NULL; | |
| 849 | + if (q && q[1]) return 1; | |
| 850 | + } | |
| 851 | + } | |
| 852 | + return 0; | |
| 853 | +} | |
| 854 | + | |
| 855 | +static void scan_creds(const char *json, status_t *st) | |
| 856 | +{ | |
| 857 | + char tmp[FIELD_SZ] = {0}; | |
| 858 | + | |
| 859 | + if (!json) return; | |
| 860 | + if (scan_token(json, "github_token") || scan_token(json, "token") || | |
| 861 | + strstr(json, "gho_")) | |
| 862 | + st->logged_in = 1; | |
| 863 | + if (json_str_field(json, json + strlen(json), "scope", tmp, sizeof(tmp)) && tmp[0]) | |
| 864 | + snprintf(st->scope, sizeof(st->scope), "%s", tmp); | |
| 865 | + if (!st->user[0] && | |
| 866 | + json_str_field(json, json + strlen(json), "login", tmp, sizeof(tmp)) && tmp[0]) | |
| 867 | + snprintf(st->user, sizeof(st->user), "%s", tmp); | |
| 868 | +} | |
| 869 | + | |
| 870 | +/* The token cache holds the derived Copilot JWT and its expiry. It is what | |
| 871 | + * tells the UI "this session expires in N minutes". */ | |
| 872 | +static void scan_cache(status_t *st, long long now_sec) | |
| 873 | +{ | |
| 874 | + char p[PATH_SZ]; | |
| 875 | + char *json; | |
| 876 | + | |
| 877 | + cache_path(p, sizeof(p)); | |
| 878 | + json = read_file(p); | |
| 879 | + if (!json) return; | |
| 880 | + st->cache_present = 1; | |
| 881 | + { | |
| 882 | + long long e = json_num_field(json, json + strlen(json), "expires_at"); | |
| 883 | + if (e > 0) st->expires_at = to_sec(e); | |
| 884 | + } | |
| 885 | + if (st->expires_at > 0) { | |
| 886 | + st->expires_in_sec = st->expires_at - now_sec; | |
| 887 | + st->expired = st->expires_in_sec <= 0; | |
| 888 | + } | |
| 889 | + free(json); | |
| 890 | +} | |
| 891 | + | |
| 892 | +/* config.json carries lastLoggedInUser.login, which is the only place the | |
| 893 | + * GitHub user name is stored. */ | |
| 894 | +static void scan_config(status_t *st) | |
| 895 | +{ | |
| 896 | + char p[PATH_SZ]; | |
| 897 | + char *json; | |
| 898 | + char tmp[NAME_SZ] = {0}; | |
| 899 | + | |
| 900 | + config_path(p, sizeof(p)); | |
| 901 | + json = read_file(p); | |
| 902 | + if (!json) return; | |
| 903 | + { | |
| 904 | + const char *lu = strstr(json, "\"lastLoggedInUser\""); | |
| 905 | + const char *brace = lu ? strchr(lu, '{') : NULL; | |
| 906 | + if (brace) { | |
| 907 | + const char *end = json + strlen(json); | |
| 908 | + if (json_str_field(brace, end, "login", tmp, sizeof(tmp)) && tmp[0]) | |
| 909 | + snprintf(st->user, sizeof(st->user), "%s", tmp); | |
| 910 | + } | |
| 911 | + } | |
| 912 | + free(json); | |
| 913 | +} | |
| 914 | + | |
| 915 | +/* Read the profile file written by --create-profile. */ | |
| 916 | +static void scan_profile(status_t *st) | |
| 917 | +{ | |
| 918 | + char *text; | |
| 919 | + char line[FIELD_SZ]; | |
| 920 | + | |
| 921 | + profile_path(st->profile_file, sizeof(st->profile_file)); | |
| 922 | + st->profile_exists = file_exists(st->profile_file); | |
| 923 | + if (!st->profile_exists) return; | |
| 924 | + | |
| 925 | + text = read_file(st->profile_file); | |
| 926 | + if (!text) return; | |
| 927 | + { | |
| 928 | + const char *p = text; | |
| 929 | + while (p && *p) { | |
| 930 | + const char *nl = strchr(p, '\n'); | |
| 931 | + size_t len = nl ? (size_t)(nl - p) : strlen(p); | |
| 932 | + if (len > 0 && len < sizeof(line)) { | |
| 933 | + memcpy(line, p, len); | |
| 934 | + line[len] = '\0'; | |
| 935 | + trim_tail(line); | |
| 936 | + if (strncmp(line, "MODEL=", 6) == 0) | |
| 937 | + snprintf(st->profile, sizeof(st->profile), "%.*s", | |
| 938 | + (int)sizeof(st->profile) - 1, line + 6); | |
| 939 | + } | |
| 940 | + if (!nl) break; | |
| 941 | + p = nl + 1; | |
| 942 | + } | |
| 943 | + } | |
| 944 | + free(text); | |
| 945 | +} | |
| 946 | + | |
| 947 | +/* List the account files in the accounts directory. Copilot account files have | |
| 948 | + * the same shape as the default credentials file, and share one token cache. */ | |
| 949 | +static void scan_accounts(status_t *st, long long now_sec) | |
| 950 | +{ | |
| 951 | + char d[PATH_SZ]; | |
| 952 | + | |
| 953 | + st->account_count = 0; | |
| 954 | + accounts_dir(d, sizeof(d)); | |
| 955 | + | |
| 956 | +#if defined(_WIN32) | |
| 957 | + { | |
| 958 | + char pattern[PATH_SZ]; | |
| 959 | + WIN32_FIND_DATAA fd; | |
| 960 | + HANDLE h; | |
| 961 | + snprintf(pattern, sizeof(pattern), "%s\\*.json", d); | |
| 962 | + h = FindFirstFileA(pattern, &fd); | |
| 963 | + if (h == INVALID_HANDLE_VALUE) return; | |
| 964 | + do { | |
| 965 | + size_t ln = strlen(fd.cFileName); | |
| 966 | + if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue; | |
| 967 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; | |
| 968 | + { | |
| 969 | + account_t *a = &st->accounts[st->account_count]; | |
| 970 | + char p[PATH_SZ]; | |
| 971 | + char *json; | |
| 972 | + status_t tmp; | |
| 973 | + memset(a, 0, sizeof(*a)); | |
| 974 | + snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName); | |
| 975 | + snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName); | |
| 976 | + a->present = 1; | |
| 977 | + memset(&tmp, 0, sizeof(tmp)); | |
| 978 | + json = read_file(p); | |
| 979 | + if (json) { scan_creds(json, &tmp); free(json); } | |
| 980 | + a->logged_in = tmp.logged_in; | |
| 981 | + if (a->logged_in && st->expires_at > 0) { | |
| 982 | + a->expires_in_sec = st->expires_at - now_sec; | |
| 983 | + a->expired = a->expires_in_sec <= 0; | |
| 984 | + } | |
| 985 | + st->account_count++; | |
| 986 | + } | |
| 987 | + } while (FindNextFileA(h, &fd)); | |
| 988 | + FindClose(h); | |
| 989 | + } | |
| 990 | +#else | |
| 991 | + { | |
| 992 | + DIR *dp = opendir(d); | |
| 993 | + struct dirent *de; | |
| 994 | + if (!dp) return; | |
| 995 | + while ((de = readdir(dp)) != NULL) { | |
| 996 | + size_t ln = strlen(de->d_name); | |
| 997 | + account_t *a; | |
| 998 | + char p[PATH_SZ]; | |
| 999 | + char *json; | |
| 1000 | + status_t tmp; | |
| 1001 | + | |
| 1002 | + if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue; | |
| 1003 | + if (strcmp(de->d_name + ln - 5, ".json") != 0) continue; | |
| 1004 | + a = &st->accounts[st->account_count]; | |
| 1005 | + memset(a, 0, sizeof(*a)); | |
| 1006 | + snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name); | |
| 1007 | + snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name); | |
| 1008 | + a->present = 1; | |
| 1009 | + memset(&tmp, 0, sizeof(tmp)); | |
| 1010 | + json = read_file(p); | |
| 1011 | + if (json) { scan_creds(json, &tmp); free(json); } | |
| 1012 | + a->logged_in = tmp.logged_in; | |
| 1013 | + if (a->logged_in && st->expires_at > 0) { | |
| 1014 | + a->expires_in_sec = st->expires_at - now_sec; | |
| 1015 | + a->expired = a->expires_in_sec <= 0; | |
| 1016 | + } | |
| 1017 | + st->account_count++; | |
| 1018 | + } | |
| 1019 | + closedir(dp); | |
| 1020 | + } | |
| 1021 | +#endif | |
| 1022 | +} | |
| 1023 | + | |
| 1024 | +/* Ask the login CLI. It is authoritative when present: it knows about the | |
| 1025 | + * pending device flow, the account file it would write and the profile. | |
| 1026 | + * It never prints a token, so its JSON is safe to relay field by field. */ | |
| 1027 | +static void scan_cli(status_t *st, const char *name) | |
| 1028 | +{ | |
| 1029 | + buf_t out; | |
| 1030 | + const char *j; | |
| 1031 | + char args[NAME_SZ + 32]; | |
| 1032 | + | |
| 1033 | + buf_init(&out); | |
| 1034 | + if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name); | |
| 1035 | + else snprintf(args, sizeof(args), "--status"); | |
| 1036 | + | |
| 1037 | + { | |
| 1038 | + int rc = run_capture(login_bin(), args, &out); | |
| 1039 | + if (rc <= 0) { | |
| 1040 | + st->cli_present = 0; | |
| 1041 | + snprintf(st->cli_error, sizeof(st->cli_error), "%s", | |
| 1042 | + rc == -1 ? "the login CLI is not on this node" | |
| 1043 | + : "could not start the login CLI"); | |
| 1044 | + buf_free(&out); | |
| 1045 | + return; | |
| 1046 | + } | |
| 1047 | + } | |
| 1048 | + | |
| 1049 | + j = last_json_line(&out); | |
| 1050 | + if (!j) { | |
| 1051 | + st->cli_present = 1; | |
| 1052 | + buf_free(&out); | |
| 1053 | + return; | |
| 1054 | + } | |
| 1055 | + st->cli_present = 1; | |
| 1056 | + { | |
| 1057 | + const char *end = j + strlen(j); | |
| 1058 | + if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1; | |
| 1059 | + st->pending = json_bool_field(j, end, "pending", 0); | |
| 1060 | + { | |
| 1061 | + char acct[NAME_SZ] = {0}; | |
| 1062 | + if (json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0]) | |
| 1063 | + snprintf(st->account, sizeof(st->account), "%s", acct); | |
| 1064 | + } | |
| 1065 | + { | |
| 1066 | + char ident[NAME_SZ] = {0}; | |
| 1067 | + if (json_str_field(j, end, "identity", ident, sizeof(ident)) && ident[0]) | |
| 1068 | + snprintf(st->user, sizeof(st->user), "%s", ident); | |
| 1069 | + } | |
| 1070 | + } | |
| 1071 | + buf_free(&out); | |
| 1072 | +} | |
| 1073 | + | |
| 1074 | +static void collect_status(status_t *st, const char *name) | |
| 1075 | +{ | |
| 1076 | + char *json; | |
| 1077 | + long long now_sec = (long long)time(NULL); | |
| 1078 | + | |
| 1079 | + memset(st, 0, sizeof(*st)); | |
| 1080 | + | |
| 1081 | + if (name && *name) { | |
| 1082 | + char p[PATH_SZ]; | |
| 1083 | + account_path(name, p, sizeof(p)); | |
| 1084 | + snprintf(st->path, sizeof(st->path), "%s", p); | |
| 1085 | + snprintf(st->account, sizeof(st->account), "%s", name); | |
| 1086 | + } else { | |
| 1087 | + creds_path(st->path, sizeof(st->path)); | |
| 1088 | + } | |
| 1089 | + | |
| 1090 | + json = read_file(st->path); | |
| 1091 | + if (json) { | |
| 1092 | + scan_creds(json, st); | |
| 1093 | + free(json); | |
| 1094 | + } | |
| 1095 | + | |
| 1096 | + scan_config(st); | |
| 1097 | + scan_cache(st, now_sec); | |
| 1098 | + scan_cli(st, name); | |
| 1099 | + scan_profile(st); | |
| 1100 | + | |
| 1101 | + pending_path(name, st->pending_file, sizeof(st->pending_file)); | |
| 1102 | + if (file_exists(st->pending_file)) st->pending = 1; | |
| 1103 | + | |
| 1104 | + if (!st->logged_in) { | |
| 1105 | + st->expired = 0; | |
| 1106 | + st->expires_in_sec = 0; | |
| 1107 | + } | |
| 1108 | + if (!st->account[0] && st->logged_in) | |
| 1109 | + snprintf(st->account, sizeof(st->account), "default"); | |
| 1110 | + if (!st->account[0] && name && *name) | |
| 1111 | + snprintf(st->account, sizeof(st->account), "%s", name); | |
| 1112 | + | |
| 1113 | + scan_accounts(st, now_sec); | |
| 1114 | + if (!st->user[0] && st->account_count == 1 && st->accounts[0].name[0]) | |
| 1115 | + snprintf(st->user, sizeof(st->user), "%s", ""); | |
| 1116 | +} | |
| 1117 | + | |
| 1118 | +/* One status object, shared by every action so the UI always re-renders from | |
| 1119 | + * the same shape. */ | |
| 1120 | +static void emit_status(buf_t *b, const status_t *st) | |
| 1121 | +{ | |
| 1122 | + int i; | |
| 1123 | + | |
| 1124 | + buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false"); | |
| 1125 | + buf_adds(b, "\"user\":"); | |
| 1126 | + buf_json(b, st->user); | |
| 1127 | + buf_addf(b, ",\"has_refresh\":%s", "false"); | |
| 1128 | + buf_adds(b, ",\"account\":"); | |
| 1129 | + buf_json(b, st->account); | |
| 1130 | + buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false"); | |
| 1131 | + buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec); | |
| 1132 | + buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false"); | |
| 1133 | + buf_addf(b, ",\"cache_present\":%s", st->cache_present ? "true" : "false"); | |
| 1134 | + buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false"); | |
| 1135 | + buf_adds(b, ",\"credentials_path\":"); | |
| 1136 | + buf_json(b, st->path); | |
| 1137 | + buf_adds(b, ",\"scope\":"); | |
| 1138 | + buf_json(b, st->scope); | |
| 1139 | + buf_adds(b, ",\"profile\":"); | |
| 1140 | + buf_json(b, st->profile); | |
| 1141 | + buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false"); | |
| 1142 | + buf_addf(b, ",\"named_accounts\":%s", st->account_count > 1 ? "true" : "false"); | |
| 1143 | + | |
| 1144 | + buf_adds(b, ",\"accounts\":["); | |
| 1145 | + for (i = 0; i < st->account_count; i++) { | |
| 1146 | + const account_t *a = &st->accounts[i]; | |
| 1147 | + if (i) buf_addc(b, ','); | |
| 1148 | + buf_adds(b, "{\"name\":"); | |
| 1149 | + buf_json(b, a->name); | |
| 1150 | + buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false"); | |
| 1151 | + buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec); | |
| 1152 | + buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false"); | |
| 1153 | + } | |
| 1154 | + buf_addc(b, ']'); | |
| 1155 | +} | |
| 1156 | + | |
| 1157 | + | |
| 1158 | +/* ------------------------------------------------------------------ */ | |
| 1159 | +/* Actions */ | |
| 1160 | +/* ------------------------------------------------------------------ */ | |
| 1161 | + | |
| 1162 | +static void json_headers(void) | |
| 1163 | +{ | |
| 1164 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1165 | + "Cache-Control: no-store\r\n" | |
| 1166 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1167 | +} | |
| 1168 | + | |
| 1169 | +static void emit_error(int code, const char *status, const char *err, const char *detail) | |
| 1170 | +{ | |
| 1171 | + buf_t b; | |
| 1172 | + | |
| 1173 | + buf_init(&b); | |
| 1174 | + buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" | |
| 1175 | + "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", | |
| 1176 | + code, status); | |
| 1177 | + buf_adds(&b, "{\"ok\":false,\"error\":"); | |
| 1178 | + buf_json(&b, err); | |
| 1179 | + if (detail && *detail) { | |
| 1180 | + buf_adds(&b, ",\"detail\":"); | |
| 1181 | + buf_json(&b, detail); | |
| 1182 | + } | |
| 1183 | + buf_adds(&b, "}\n"); | |
| 1184 | + fputs(buf_str(&b), stdout); | |
| 1185 | + buf_free(&b); | |
| 1186 | +} | |
| 1187 | + | |
| 1188 | +static int emit_status_json(const status_t *st, const char *extra_head) | |
| 1189 | +{ | |
| 1190 | + buf_t b; | |
| 1191 | + | |
| 1192 | + buf_init(&b); | |
| 1193 | + buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\","); | |
| 1194 | + if (extra_head) buf_adds(&b, extra_head); | |
| 1195 | + emit_status(&b, st); | |
| 1196 | + buf_adds(&b, ",\"flow\":\"device_code\",\"protocol\":\"SXLOGIN-MACHINE-V1\"}\n"); | |
| 1197 | + json_headers(); | |
| 1198 | + fputs(buf_str(&b), stdout); | |
| 1199 | + buf_free(&b); | |
| 1200 | + return 0; | |
| 1201 | +} | |
| 1202 | + | |
| 1203 | +static int action_status(const char *name) | |
| 1204 | +{ | |
| 1205 | + status_t st; | |
| 1206 | + | |
| 1207 | + collect_status(&st, name); | |
| 1208 | + return emit_status_json(&st, NULL); | |
| 1209 | +} | |
| 1210 | + | |
| 1211 | +static int action_accounts(const char *name) | |
| 1212 | +{ | |
| 1213 | + status_t st; | |
| 1214 | + buf_t b; | |
| 1215 | + int i; | |
| 1216 | + | |
| 1217 | + collect_status(&st, name); | |
| 1218 | + buf_init(&b); | |
| 1219 | + buf_adds(&b, "{\"ok\":true,\"accounts\":["); | |
| 1220 | + for (i = 0; i < st.account_count; i++) { | |
| 1221 | + const account_t *a = &st.accounts[i]; | |
| 1222 | + if (i) buf_addc(&b, ','); | |
| 1223 | + buf_adds(&b, "{\"name\":"); | |
| 1224 | + buf_json(&b, a->name); | |
| 1225 | + buf_addf(&b, ",\"logged_in\":%s", a->logged_in ? "true" : "false"); | |
| 1226 | + buf_addf(&b, ",\"expires_in_sec\":%lld", a->expires_in_sec); | |
| 1227 | + buf_addf(&b, ",\"expired\":%s}", a->expired ? "true" : "false"); | |
| 1228 | + } | |
| 1229 | + buf_addf(&b, "],\"count\":%d,\"active\":", st.account_count); | |
| 1230 | + buf_json(&b, st.account); | |
| 1231 | + buf_adds(&b, "}\n"); | |
| 1232 | + json_headers(); | |
| 1233 | + fputs(buf_str(&b), stdout); | |
| 1234 | + buf_free(&b); | |
| 1235 | + return 0; | |
| 1236 | +} | |
| 1237 | + | |
| 1238 | +/* Build the CLI argv suffix for --name / --force. */ | |
| 1239 | +static void cli_args(char *out, size_t n, const char *name, int force, const char *verb) | |
| 1240 | +{ | |
| 1241 | + char qname[NAME_SZ * 2]; | |
| 1242 | + | |
| 1243 | + out[0] = '\0'; | |
| 1244 | + snprintf(out, n, "%s", verb); | |
| 1245 | + if (force) snprintf(out + strlen(out), n - strlen(out), " --force"); | |
| 1246 | + if (name && *name) { | |
| 1247 | + shell_quote_into(name, qname, sizeof(qname)); | |
| 1248 | + snprintf(out + strlen(out), n - strlen(out), " --name %s", qname); | |
| 1249 | + } | |
| 1250 | +} | |
| 1251 | + | |
| 1252 | +static int action_start(const char *name, int force) | |
| 1253 | +{ | |
| 1254 | + buf_t out, b; | |
| 1255 | + const char *j; | |
| 1256 | + char args[NAME_SZ + 64]; | |
| 1257 | + char verify_url[FIELD_SZ] = {0}; | |
| 1258 | + char user_code[NAME_SZ] = {0}; | |
| 1259 | + char flow[64] = {0}; | |
| 1260 | + char hint[FIELD_SZ] = {0}; | |
| 1261 | + long long interval = 0, expires_in = 0; | |
| 1262 | + | |
| 1263 | + cli_args(args, sizeof(args), name, force, "--start"); | |
| 1264 | + | |
| 1265 | + buf_init(&out); | |
| 1266 | + { | |
| 1267 | + int rc = run_capture(login_bin(), args, &out); | |
| 1268 | + if (rc <= 0) { | |
| 1269 | + buf_free(&out); | |
| 1270 | + emit_error(200, "OK", "cli_unavailable", | |
| 1271 | + "the login CLI is not on this node; install SCORPIOX CODE or set COPILOT_LOGIN_BIN"); | |
| 1272 | + return 1; | |
| 1273 | + } | |
| 1274 | + } | |
| 1275 | + j = last_json_line(&out); | |
| 1276 | + if (!j) { | |
| 1277 | + emit_error(200, "OK", "start_failed", "the login CLI returned no JSON"); | |
| 1278 | + buf_free(&out); | |
| 1279 | + return 1; | |
| 1280 | + } | |
| 1281 | + { | |
| 1282 | + const char *end = j + strlen(j); | |
| 1283 | + json_str_field(j, end, "verify_url", verify_url, sizeof(verify_url)); | |
| 1284 | + json_str_field(j, end, "user_code", user_code, sizeof(user_code)); | |
| 1285 | + json_str_field(j, end, "flow", flow, sizeof(flow)); | |
| 1286 | + json_str_field(j, end, "hint", hint, sizeof(hint)); | |
| 1287 | + interval = json_num_field(j, end, "interval"); | |
| 1288 | + expires_in = json_num_field(j, end, "expires_in"); | |
| 1289 | + if (!json_bool_field(j, end, "ok", 1) || !user_code[0]) { | |
| 1290 | + char detail[FIELD_SZ] = {0}; | |
| 1291 | + json_str_field(j, end, "error", detail, sizeof(detail)); | |
| 1292 | + buf_free(&out); | |
| 1293 | + emit_error(200, "OK", detail[0] ? detail : "start_failed", | |
| 1294 | + "the login CLI did not return a device code"); | |
| 1295 | + return 1; | |
| 1296 | + } | |
| 1297 | + } | |
| 1298 | + buf_free(&out); | |
| 1299 | + | |
| 1300 | + buf_init(&b); | |
| 1301 | + buf_adds(&b, "{\"ok\":true,\"flow\":"); | |
| 1302 | + buf_json(&b, flow[0] ? flow : "device_code"); | |
| 1303 | + buf_adds(&b, ",\"verify_url\":"); | |
| 1304 | + buf_json(&b, verify_url[0] ? verify_url : "https://github.com/login/device"); | |
| 1305 | + buf_adds(&b, ",\"user_code\":"); | |
| 1306 | + buf_json(&b, user_code); | |
| 1307 | + buf_addf(&b, ",\"interval\":%lld", interval > 0 ? interval : DEFAULT_INTERVAL); | |
| 1308 | + buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : DEFAULT_EXPIRES_IN); | |
| 1309 | + buf_adds(&b, ",\"hint\":"); | |
| 1310 | + buf_json(&b, hint[0] ? hint | |
| 1311 | + : "Open the link, enter the code, approve. This page checks automatically."); | |
| 1312 | + buf_adds(&b, "}\n"); | |
| 1313 | + json_headers(); | |
| 1314 | + fputs(buf_str(&b), stdout); | |
| 1315 | + buf_free(&b); | |
| 1316 | + return 0; | |
| 1317 | +} | |
| 1318 | + | |
| 1319 | +/* One non-blocking poll. The CLI answers state=pending while GitHub is still | |
| 1320 | + * waiting for the user, state=done once the token is written, and an error | |
| 1321 | + * code otherwise. */ | |
| 1322 | +static int action_poll(const char *name) | |
| 1323 | +{ | |
| 1324 | + buf_t out, b; | |
| 1325 | + const char *j; | |
| 1326 | + char args[NAME_SZ + 64]; | |
| 1327 | + char state[64] = {0}; | |
| 1328 | + long long interval = 0; | |
| 1329 | + | |
| 1330 | + cli_args(args, sizeof(args), name, 0, "--poll"); | |
| 1331 | + | |
| 1332 | + buf_init(&out); | |
| 1333 | + { | |
| 1334 | + int rc = run_capture(login_bin(), args, &out); | |
| 1335 | + if (rc <= 0) { | |
| 1336 | + buf_free(&out); | |
| 1337 | + emit_error(200, "OK", "cli_unavailable", | |
| 1338 | + "the login CLI is not on this node; install SCORPIOX CODE or set COPILOT_LOGIN_BIN"); | |
| 1339 | + return 1; | |
| 1340 | + } | |
| 1341 | + } | |
| 1342 | + j = last_json_line(&out); | |
| 1343 | + if (!j) { | |
| 1344 | + buf_free(&out); | |
| 1345 | + emit_error(200, "OK", "poll_failed", "the login CLI returned no JSON"); | |
| 1346 | + return 1; | |
| 1347 | + } | |
| 1348 | + { | |
| 1349 | + const char *end = j + strlen(j); | |
| 1350 | + int ok = json_bool_field(j, end, "ok", 0); | |
| 1351 | + json_str_field(j, end, "state", state, sizeof(state)); | |
| 1352 | + interval = json_num_field(j, end, "interval"); | |
| 1353 | + | |
| 1354 | + if (!ok) { | |
| 1355 | + char detail[FIELD_SZ] = {0}; | |
| 1356 | + char err[FIELD_SZ] = {0}; | |
| 1357 | + json_str_field(j, end, "error", err, sizeof(err)); | |
| 1358 | + json_str_field(j, end, "detail", detail, sizeof(detail)); | |
| 1359 | + buf_free(&out); | |
| 1360 | + emit_error(200, "OK", err[0] ? err : "poll_failed", | |
| 1361 | + detail[0] ? detail : "the device login is no longer valid; start again"); | |
| 1362 | + return 1; | |
| 1363 | + } | |
| 1364 | + buf_free(&out); | |
| 1365 | + | |
| 1366 | + if (strcmp(state, "done") == 0) { | |
| 1367 | + status_t st; | |
| 1368 | + collect_status(&st, name); | |
| 1369 | + buf_init(&b); | |
| 1370 | + buf_adds(&b, "{\"ok\":true,\"state\":\"done\","); | |
| 1371 | + emit_status(&b, &st); | |
| 1372 | + buf_adds(&b, "}\n"); | |
| 1373 | + json_headers(); | |
| 1374 | + fputs(buf_str(&b), stdout); | |
| 1375 | + buf_free(&b); | |
| 1376 | + return 0; | |
| 1377 | + } | |
| 1378 | + } | |
| 1379 | + | |
| 1380 | + buf_init(&b); | |
| 1381 | + buf_adds(&b, "{\"ok\":true,\"state\":\"pending\","); | |
| 1382 | + buf_addf(&b, "\"interval\":%lld}\n", interval > 0 ? interval : DEFAULT_INTERVAL); | |
| 1383 | + json_headers(); | |
| 1384 | + fputs(buf_str(&b), stdout); | |
| 1385 | + buf_free(&b); | |
| 1386 | + return 0; | |
| 1387 | +} | |
| 1388 | + | |
| 1389 | +static int action_cancel(const char *name) | |
| 1390 | +{ | |
| 1391 | + buf_t out, b; | |
| 1392 | + char args[NAME_SZ + 64]; | |
| 1393 | + | |
| 1394 | + cli_args(args, sizeof(args), name, 0, "--cancel"); | |
| 1395 | + | |
| 1396 | + buf_init(&out); | |
| 1397 | + run_capture(login_bin(), args, &out); | |
| 1398 | + buf_free(&out); | |
| 1399 | + | |
| 1400 | + buf_init(&b); | |
| 1401 | + buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n"); | |
| 1402 | + json_headers(); | |
| 1403 | + fputs(buf_str(&b), stdout); | |
| 1404 | + buf_free(&b); | |
| 1405 | + return 0; | |
| 1406 | +} | |
| 1407 | + | |
| 1408 | +/* Refresh: Copilot's CLI derives the short-lived JWT from the stored `gho_` | |
| 1409 | + * token and caches it. Its stdout may quote token material, so the payload is | |
| 1410 | + * read, then discarded. The new state is proven by re-reading the cache, not | |
| 1411 | + * by the CLI's word. */ | |
| 1412 | +static int action_refresh(const char *name) | |
| 1413 | +{ | |
| 1414 | + buf_t out, b; | |
| 1415 | + char args[PATH_SZ + 96]; | |
| 1416 | + char qpath[PATH_SZ * 2]; | |
| 1417 | + char path[PATH_SZ]; | |
| 1418 | + long long before; | |
| 1419 | + int refreshed = 0; | |
| 1420 | + status_t st; | |
| 1421 | + | |
| 1422 | + if (name && *name) account_path(name, path, sizeof(path)); | |
| 1423 | + else creds_path(path, sizeof(path)); | |
| 1424 | + | |
| 1425 | + if (!file_exists(path)) { | |
| 1426 | + buf_init(&b); | |
| 1427 | + buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":"); | |
| 1428 | + buf_json(&b, "there is no credentials file on this node; start a login first"); | |
| 1429 | + buf_adds(&b, "}\n"); | |
| 1430 | + json_headers(); | |
| 1431 | + fputs(buf_str(&b), stdout); | |
| 1432 | + buf_free(&b); | |
| 1433 | + return 1; | |
| 1434 | + } | |
| 1435 | + | |
| 1436 | + collect_status(&st, name); | |
| 1437 | + before = st.expires_at; | |
| 1438 | + | |
| 1439 | + shell_quote_into(path, qpath, sizeof(qpath)); | |
| 1440 | + /* --force: without it the CLI no-ops on a still-valid cached JWT and the | |
| 1441 | + * user's button would do nothing. */ | |
| 1442 | + snprintf(args, sizeof(args), "--credentials-file %s --force", qpath); | |
| 1443 | + | |
| 1444 | + buf_init(&out); | |
| 1445 | + { | |
| 1446 | + int rc = run_capture(refresh_bin(), args, &out); | |
| 1447 | + if (rc <= 0) { | |
| 1448 | + buf_free(&out); | |
| 1449 | + emit_error(200, "OK", "cli_unavailable", | |
| 1450 | + "the refresh CLI is not on this node; install SCORPIOX CODE or set COPILOT_REFRESH_BIN"); | |
| 1451 | + return 1; | |
| 1452 | + } | |
| 1453 | + } | |
| 1454 | + { | |
| 1455 | + /* A failed grant is proven by the CLI's own answer, never by its | |
| 1456 | + * absence: it prints {"access_token":...,"expires_at":...} on success | |
| 1457 | + * and nothing but human text on failure. The payload is inspected for | |
| 1458 | + * the key only and then discarded - no token byte ever reaches a | |
| 1459 | + * response. */ | |
| 1460 | + const char *j = last_json_line(&out); | |
| 1461 | + char tok[8] = {0}; | |
| 1462 | + refreshed = j && json_str_field(j, j + strlen(j), "access_token", tok, sizeof(tok)); | |
| 1463 | + } | |
| 1464 | + buf_free(&out); | |
| 1465 | + | |
| 1466 | + collect_status(&st, name); | |
| 1467 | + if (!refreshed || !st.logged_in) { | |
| 1468 | + buf_init(&b); | |
| 1469 | + buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":"); | |
| 1470 | + buf_json(&b, "the refresh CLI did not produce a usable token; sign in again"); | |
| 1471 | + buf_adds(&b, "}\n"); | |
| 1472 | + json_headers(); | |
| 1473 | + fputs(buf_str(&b), stdout); | |
| 1474 | + buf_free(&b); | |
| 1475 | + return 1; | |
| 1476 | + } | |
| 1477 | + (void)before; | |
| 1478 | + | |
| 1479 | + buf_init(&b); | |
| 1480 | + buf_adds(&b, "{\"ok\":true,\"refreshed\":true,"); | |
| 1481 | + emit_status(&b, &st); | |
| 1482 | + buf_adds(&b, "}\n"); | |
| 1483 | + json_headers(); | |
| 1484 | + fputs(buf_str(&b), stdout); | |
| 1485 | + buf_free(&b); | |
| 1486 | + return 0; | |
| 1487 | +} | |
| 1488 | + | |
| 1489 | + | |
| 1490 | +/* ------------------------------------------------------------------ */ | |
| 1491 | +/* HTML emission */ | |
| 1492 | +/* ------------------------------------------------------------------ */ | |
| 1493 | + | |
| 1494 | +/* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the | |
| 1495 | + * split means the palette lives in exactly one place (bot_theme_plugin.h) and | |
| 1496 | + * the page can never drift away from the bot's own theme. */ | |
| 1497 | +static void emit_ui(void) | |
| 1498 | +{ | |
| 1499 | + const char *p = UI_HTML; | |
| 1500 | + | |
| 1501 | + while (*p) { | |
| 1502 | + if (*p == '\001') { | |
| 1503 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout); | |
| 1504 | + p++; | |
| 1505 | + } else if (*p == '\002') { | |
| 1506 | + /* SX_BOT_THEME_HANDOFF and SX_BOT_THEME_TOGGLE_JS are both complete | |
| 1507 | + * <script>...</script> strings, so they are emitted as siblings. | |
| 1508 | + * Without the toggle macro the page's Theme button is inert: the | |
| 1509 | + * bot owns the theme, but a plugin opened in its own tab needs a | |
| 1510 | + * switch of its own. */ | |
| 1511 | + fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout); | |
| 1512 | + p++; | |
| 1513 | + } else { | |
| 1514 | + putchar(*p++); | |
| 1515 | + } | |
| 1516 | + } | |
| 1517 | +} | |
| 1518 | + | |
| 1519 | +/* ------------------------------------------------------------------ */ | |
| 1520 | +/* main */ | |
| 1521 | +/* ------------------------------------------------------------------ */ | |
| 1522 | + | |
| 1523 | +int main(int argc, char **argv) | |
| 1524 | +{ | |
| 1525 | + const char *qs; | |
| 1526 | + char action[64] = {0}; | |
| 1527 | + char name[NAME_SZ] = {0}; | |
| 1528 | + int force = 0; | |
| 1529 | + | |
| 1530 | + /* 1. Discovery metadata. Must stay unauthenticated. */ | |
| 1531 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | |
| 1532 | + puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); | |
| 1533 | + return 0; | |
| 1534 | + } | |
| 1535 | + if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { | |
| 1536 | + puts(PLUGIN_ID " " PLUGIN_VER); | |
| 1537 | + return 0; | |
| 1538 | + } | |
| 1539 | + | |
| 1540 | + require_node_auth(); | |
| 1541 | + | |
| 1542 | + qs = getenv("QUERY_STRING"); | |
| 1543 | + if (!qs) qs = ""; | |
| 1544 | + | |
| 1545 | + get_query_val(qs, "name", name, sizeof(name)); | |
| 1546 | + if (name[0] && !name_valid(name)) { | |
| 1547 | + emit_error(400, "Bad Request", "bad_name", "account names use letters, digits, - _ . (max 64)"); | |
| 1548 | + return 1; | |
| 1549 | + } | |
| 1550 | + { | |
| 1551 | + char f[8] = {0}; | |
| 1552 | + if (get_query_val(qs, "force", f, sizeof(f))) | |
| 1553 | + force = (f[0] == '1' || f[0] == 't' || f[0] == 'T' || f[0] == 'y'); | |
| 1554 | + } | |
| 1555 | + | |
| 1556 | + /* 2. JSON API mode. `format=json` alone means "status", which is what a | |
| 1557 | + * dashboard polls. */ | |
| 1558 | + if (query_has(qs, "action") || query_has(qs, "format")) { | |
| 1559 | + char fmt[32] = {0}; | |
| 1560 | + | |
| 1561 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 1562 | + get_query_val(qs, "format", fmt, sizeof(fmt)); | |
| 1563 | + if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status"); | |
| 1564 | + | |
| 1565 | + if (strcmp(action, "status") == 0 || !action[0]) return action_status(name); | |
| 1566 | + if (strcmp(action, "start") == 0) return action_start(name, force); | |
| 1567 | + if (strcmp(action, "poll") == 0) return action_poll(name); | |
| 1568 | + if (strcmp(action, "cancel") == 0) return action_cancel(name); | |
| 1569 | + if (strcmp(action, "refresh") == 0) return action_refresh(name); | |
| 1570 | + if (strcmp(action, "accounts") == 0) return action_accounts(name); | |
| 1571 | + emit_error(404, "Not Found", "unknown_action", action); | |
| 1572 | + return 1; | |
| 1573 | + } | |
| 1574 | + | |
| 1575 | + /* 3. HTML UI. UI_HTML carries two control bytes: 0x01 is the theme block | |
| 1576 | + * (<style> with the bot tokens) and 0x02 is the handoff script before | |
| 1577 | + * </body>. */ | |
| 1578 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1579 | + "Cache-Control: no-store\r\n" | |
| 1580 | + "X-Content-Type-Options: nosniff\r\n" | |
| 1581 | + "Referrer-Policy: no-referrer\r\n" | |
| 1582 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | |
| 1583 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | |
| 1584 | + "base-uri 'none'; form-action 'none'; frame-ancestors *\r\n\r\n", stdout); | |
| 1585 | + emit_ui(); | |
| 1586 | + return 0; | |
| 1587 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..113d374 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,407 @@ | ||
| 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>copilot</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 | +.badge{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:600; | |
| 27 | + padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text); | |
| 28 | + border:1px solid var(--line);font-family:var(--mono);max-width:100%;overflow:hidden; | |
| 29 | + text-overflow:ellipsis;white-space:nowrap} | |
| 30 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | |
| 31 | + padding:16px;margin-bottom:12px} | |
| 32 | +.card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em; | |
| 33 | + text-transform:uppercase;color:var(--text-2)} | |
| 34 | +.card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)} | |
| 35 | +.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap} | |
| 36 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px; | |
| 37 | + font-weight:600;font-size:13px;cursor:pointer;font-family:inherit; | |
| 38 | + transition:transform .12s var(--ease),opacity .12s} | |
| 39 | +.btn:active{transform:scale(.98)} | |
| 40 | +.btn:disabled{opacity:.5;cursor:default} | |
| 41 | +.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)} | |
| 42 | +.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)} | |
| 43 | +.btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)} | |
| 44 | +a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none} | |
| 45 | +.kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px} | |
| 46 | +.kv .k{color:var(--text-2);font-size:12px} | |
| 47 | +.kv .v{font-family:var(--mono);font-size:12px;word-break:break-all} | |
| 48 | +.kv .v.plain{font-family:var(--font);font-size:13px} | |
| 49 | +.step{display:none} | |
| 50 | +.step.on{display:block} | |
| 51 | +.hint{margin:10px 0 0;font-size:12px;color:var(--text-2)} | |
| 52 | +.note{font-size:12.5px;margin-top:10px;display:none} | |
| 53 | +.note.show{display:block} | |
| 54 | +.note.err{color:var(--red)} | |
| 55 | +.note.ok{color:var(--green)} | |
| 56 | +.usercode{font-family:var(--mono);font-size:34px;font-weight:700;letter-spacing:.16em; | |
| 57 | + color:var(--text);background:var(--code-bg);border:1px solid var(--line-2); | |
| 58 | + border-radius:12px;padding:16px 10px;margin-top:12px;text-align:center; | |
| 59 | + word-break:break-all;user-select:all} | |
| 60 | +.count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1} | |
| 61 | +.count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0} | |
| 62 | +.wait{display:flex;align-items:center;gap:9px;margin-top:12px;font-size:12.5px; | |
| 63 | + color:var(--text-2)} | |
| 64 | +.wait .spin{display:inline-block;width:13px;height:13px;border-radius:50%; | |
| 65 | + border:2px solid var(--line-2);border-top-color:var(--blue);animation:sp .8s linear infinite} | |
| 66 | +@keyframes sp{to{transform:rotate(360deg)}} | |
| 67 | +.spin2{width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35); | |
| 68 | + border-top-color:#fff;display:none;animation:sp .7s linear infinite} | |
| 69 | +.btn.loading .spin2{display:inline-block} | |
| 70 | +.acct{display:flex;align-items:center;gap:10px;padding:9px 0;border-top:1px solid var(--line); | |
| 71 | + font-size:13px} | |
| 72 | +.acct:first-child{border-top:0} | |
| 73 | +.acct .nm{font-family:var(--mono);font-size:12.5px;flex:1 1 auto;min-width:0; | |
| 74 | + overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 75 | +.acct .tag{font-size:11px;font-weight:650;padding:3px 9px;border-radius:999px; | |
| 76 | + background:var(--surface-2);color:var(--text-2);white-space:nowrap} | |
| 77 | +.acct .tag.ok{color:var(--green)} | |
| 78 | +.acct .tag.warn{color:var(--orange)} | |
| 79 | +.empty{font-size:12.5px;color:var(--text-2)} | |
| 80 | +.toast{position:fixed;left:50%;bottom:24px;transform:translate(-50%,12px);opacity:0; | |
| 81 | + pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2); | |
| 82 | + color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px; | |
| 83 | + box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease); | |
| 84 | + z-index:9;max-width:calc(100vw - 32px)} | |
| 85 | +.toast.show{opacity:1;transform:translate(-50%,0)} | |
| 86 | +#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text); | |
| 87 | + border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer; | |
| 88 | + font-family:inherit} | |
| 89 | +@media (max-width:520px){ | |
| 90 | + #app{padding:12px 12px 32px} | |
| 91 | + .kv{grid-template-columns:1fr;gap:2px 0} | |
| 92 | + .kv .k{margin-top:8px} | |
| 93 | + .card{padding:13px;border-radius:12px} | |
| 94 | + .count{font-size:28px} | |
| 95 | + .usercode{font-size:27px;letter-spacing:.1em;padding:14px 6px} | |
| 96 | +} | |
| 97 | +</style> | |
| 98 | +</head> | |
| 99 | +<body> | |
| 100 | +<div id="app"> | |
| 101 | + <div class="hd"> | |
| 102 | + <div class="grow"> | |
| 103 | + <h1>GitHub Copilot</h1> | |
| 104 | + <div class="sub" id="sub">Device code login on this node</div> | |
| 105 | + </div> | |
| 106 | + <span class="badge" id="userBadge" style="display:none"></span> | |
| 107 | + <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span> | |
| 108 | + <button id="themeToggle" class="embed-hide" type="button">Theme</button> | |
| 109 | + </div> | |
| 110 | + | |
| 111 | + <div class="card"> | |
| 112 | + <h2>Session</h2> | |
| 113 | + <p class="lead" id="sessionLead">Reading the local Copilot credentials.</p> | |
| 114 | + <div class="kv" id="session"></div> | |
| 115 | + <div class="row" style="margin-top:14px"> | |
| 116 | + <button class="btn ghost" id="btnRefresh" type="button"><span class="spin2"></span>Refresh Token Now</button> | |
| 117 | + <button class="btn ghost" id="btnReload" type="button">Reload</button> | |
| 118 | + </div> | |
| 119 | + <div class="note" id="refreshNote"></div> | |
| 120 | + </div> | |
| 121 | + | |
| 122 | + <div class="card"> | |
| 123 | + <h2>Device login</h2> | |
| 124 | + <p class="lead">Sign in with GitHub. The login CLI opens the device flow and writes the | |
| 125 | + credential file on this node; no token ever passes through this page.</p> | |
| 126 | + | |
| 127 | + <div class="step on" id="step1"> | |
| 128 | + <div class="row"> | |
| 129 | + <button class="btn" id="btnStart" type="button">Start GitHub Copilot Login</button> | |
| 130 | + </div> | |
| 131 | + <p class="hint">This asks GitHub for a one-time code. Nothing is stored until you approve | |
| 132 | + it in the browser.</p> | |
| 133 | + <div class="note" id="startNote"></div> | |
| 134 | + </div> | |
| 135 | + | |
| 136 | + <div class="step" id="step2"> | |
| 137 | + <p class="hint" style="margin-top:0">Enter this code at | |
| 138 | + <span style="font-family:var(--mono)">github.com/login/device</span>:</p> | |
| 139 | + <div class="usercode" id="userCode">----</div> | |
| 140 | + <div class="row" style="margin-top:12px"> | |
| 141 | + <button class="btn" id="btnCopyOpen" type="button">Copy Code & Open GitHub</button> | |
| 142 | + <a class="btn ghost" id="linkOpen" href="https://github.com/login/device" | |
| 143 | + target="_blank" rel="noopener noreferrer">Open GitHub</a> | |
| 144 | + <button class="btn danger" id="btnCancel" type="button">Cancel</button> | |
| 145 | + </div> | |
| 146 | + <div class="wait" id="waitBox"><span class="spin"></span> | |
| 147 | + <span id="waitText">Waiting for GitHub confirmation...</span></div> | |
| 148 | + <div class="note" id="loginNote"></div> | |
| 149 | + </div> | |
| 150 | + </div> | |
| 151 | + | |
| 152 | + <div class="card"> | |
| 153 | + <h2>Named accounts</h2> | |
| 154 | + <p class="lead">Every account file in the local accounts directory.</p> | |
| 155 | + <div id="accounts"><div class="empty">No named accounts.</div></div> | |
| 156 | + </div> | |
| 157 | +</div> | |
| 158 | + | |
| 159 | +<div class="toast" id="toast"></div> | |
| 160 | + | |
| 161 | +<script> | |
| 162 | +var q=new URLSearchParams(location.search); | |
| 163 | +var node=q.get('node')||''; | |
| 164 | +var sid=q.get('id')||''; | |
| 165 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | |
| 166 | + localStorage.getItem('bot_active_pwd')||''; | |
| 167 | + | |
| 168 | +/* Two call routes. Getting this wrong is the most common plugin bug: | |
| 169 | + * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..) | |
| 170 | + * -> call the hub proxy back: /plugins?plugin=plugin_copilot_login&action=.. | |
| 171 | + * opened directly on the node | |
| 172 | + * -> the plugin itself is the route: /plugin_copilot_login?action=.. | |
| 173 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | |
| 174 | +var HUB=q.get('plugin')||''; | |
| 175 | +function url(action,extra){ | |
| 176 | + return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_copilot_login')+ | |
| 177 | + '?action='+encodeURIComponent(action)+ | |
| 178 | + (extra?('&'+extra):'')+ | |
| 179 | + (node?'&node='+encodeURIComponent(node):'')+ | |
| 180 | + (sid?'&id='+encodeURIComponent(sid):'')+ | |
| 181 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | |
| 182 | +} | |
| 183 | +function hdr(){ | |
| 184 | + var h={}; | |
| 185 | + if(pwd)h['X-Bot-Password']=pwd; | |
| 186 | + return h; | |
| 187 | +} | |
| 188 | +function api(action,extra){ | |
| 189 | + return fetch(url(action,extra),{headers:hdr()}).then(function(r){ | |
| 190 | + return r.json().catch(function(){return {ok:false,error:'bad response'};}); | |
| 191 | + }); | |
| 192 | +} | |
| 193 | + | |
| 194 | +var $=function(id){return document.getElementById(id);}; | |
| 195 | +function toast(msg){ | |
| 196 | + var t=$('toast');t.textContent=msg;t.classList.add('show'); | |
| 197 | + clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200); | |
| 198 | +} | |
| 199 | +function note(el,msg,kind){ | |
| 200 | + el.textContent=msg||''; | |
| 201 | + el.className='note'+(msg?' show '+(kind||''):''); | |
| 202 | +} | |
| 203 | +function kv(el,rows){ | |
| 204 | + el.innerHTML=''; | |
| 205 | + rows.forEach(function(r){ | |
| 206 | + var a=document.createElement('div');a.className='k';a.textContent=r[0]; | |
| 207 | + var b=document.createElement('div');b.className='v'+(r[2]?' plain':''); | |
| 208 | + b.textContent=r[1];el.appendChild(a);el.appendChild(b); | |
| 209 | + }); | |
| 210 | +} | |
| 211 | +function fmtExpiry(sec){ | |
| 212 | + if(typeof sec!=='number')return '-'; | |
| 213 | + if(sec<=0)return 'expired'; | |
| 214 | + if(sec<90)return sec+'s'; | |
| 215 | + if(sec<5400)return Math.round(sec/60)+' min'; | |
| 216 | + if(sec<172800)return Math.round(sec/3600)+' h'; | |
| 217 | + if(sec<63072000)return Math.round(sec/86400)+' d'; | |
| 218 | + return Math.round(sec/31536000)+' yr'; | |
| 219 | +} | |
| 220 | +function setPill(st){ | |
| 221 | + var p=$('pill'),t=$('pillText'); | |
| 222 | + if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';} | |
| 223 | + else if(st.logged_in){p.className='pill ok';t.textContent='Connected';} | |
| 224 | + else if(st.pending){p.className='pill warn';t.textContent='Signing in';} | |
| 225 | + else {p.className='pill off';t.textContent='Not Connected';} | |
| 226 | +} | |
| 227 | +function render(st){ | |
| 228 | + setPill(st); | |
| 229 | + var badge=$('userBadge'); | |
| 230 | + if(st.logged_in&&st.user){badge.style.display='';badge.textContent='@'+st.user;} | |
| 231 | + else badge.style.display='none'; | |
| 232 | + $('sub').textContent=st.account&&st.account!=='default' | |
| 233 | + ? 'Device code login - '+st.account : 'Device code login on this node'; | |
| 234 | + | |
| 235 | + if(st.logged_in){ | |
| 236 | + $('sessionLead').textContent=st.expired | |
| 237 | + ? 'A Copilot session is stored but its derived token has expired. Use Refresh Token Now.' | |
| 238 | + : 'This node holds a GitHub Copilot session.'; | |
| 239 | + }else{ | |
| 240 | + $('sessionLead').textContent='No Copilot session on this node yet. Start a login below.'; | |
| 241 | + } | |
| 242 | + | |
| 243 | + kv($('session'),[ | |
| 244 | + ['Account', st.account||'-', true], | |
| 245 | + ['GitHub user', st.user||'-', true], | |
| 246 | + ['Logged in', st.logged_in?'yes':'no', true], | |
| 247 | + ['Derived token', st.logged_in?(st.expired?'expired':'valid'):'-', true], | |
| 248 | + ['Token expires', st.logged_in&&st.cache_present?fmtExpiry(st.expires_in_sec):'-', true], | |
| 249 | + ['Login pending', st.pending?'yes':'no', true], | |
| 250 | + ['Login CLI', st.cli_present?'found':'not found', true], | |
| 251 | + ['Scope', st.scope||'-', true], | |
| 252 | + ['Profile model', st.profile_exists?(st.profile||'-'):'not created', true], | |
| 253 | + ['Credentials', st.credentials_path||'-'] | |
| 254 | + ]); | |
| 255 | + | |
| 256 | + var box=$('accounts'); | |
| 257 | + box.innerHTML=''; | |
| 258 | + var list=st.accounts||[]; | |
| 259 | + if(!list.length){ | |
| 260 | + var e=document.createElement('div');e.className='empty'; | |
| 261 | + e.textContent='No named accounts.';box.appendChild(e); | |
| 262 | + }else{ | |
| 263 | + list.forEach(function(a){ | |
| 264 | + var row=document.createElement('div');row.className='acct'; | |
| 265 | + var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name; | |
| 266 | + var tg=document.createElement('div'); | |
| 267 | + tg.className='tag '+(a.logged_in?(a.expired?'warn':'ok'):''); | |
| 268 | + tg.textContent=a.logged_in?(a.expired?'expired':'valid'):'no token'; | |
| 269 | + row.appendChild(nm);row.appendChild(tg);box.appendChild(row); | |
| 270 | + }); | |
| 271 | + } | |
| 272 | + | |
| 273 | + if(st.pending){showStep2();} | |
| 274 | +} | |
| 275 | +function load(){ | |
| 276 | + return api('status').then(function(d){ | |
| 277 | + if(d&&d.ok)render(d); | |
| 278 | + else toast((d&&d.error)||'status failed'); | |
| 279 | + }).catch(function(e){toast('Status failed: '+e.message);}); | |
| 280 | +} | |
| 281 | + | |
| 282 | +/* ---- device flow ---- */ | |
| 283 | +var userCode='',VerifyUrl='https://github.com/login/device'; | |
| 284 | +var pollTimer=null,pollInterval=5,pollStop=0; | |
| 285 | + | |
| 286 | +function showStep2(){ | |
| 287 | + $('step1').classList.remove('on'); | |
| 288 | + $('step2').classList.add('on'); | |
| 289 | +} | |
| 290 | +function hideStep2(){ | |
| 291 | + $('step1').classList.add('on'); | |
| 292 | + $('step2').classList.remove('on'); | |
| 293 | +} | |
| 294 | +function stopPolling(){ | |
| 295 | + if(pollTimer){clearTimeout(pollTimer);pollTimer=null;} | |
| 296 | +} | |
| 297 | +function startPolling(){ | |
| 298 | + stopPolling(); | |
| 299 | + $('waitBox').style.display=''; | |
| 300 | + $('waitText').textContent='Waiting for GitHub confirmation...'; | |
| 301 | + var delay=Math.max(3,pollInterval||5)*1000; | |
| 302 | + pollTimer=setTimeout(function(){ | |
| 303 | + api('poll').then(function(d){ | |
| 304 | + if(d&&d.ok&&d.state==='done'){ | |
| 305 | + stopPolling(); | |
| 306 | + $('waitText').textContent='Authorized.'; | |
| 307 | + note($('loginNote'),'Signed in'+(d.user?(' as @'+d.user):'')+'.','ok'); | |
| 308 | + hideStep2(); | |
| 309 | + render(d); | |
| 310 | + toast('GitHub Copilot connected'); | |
| 311 | + return; | |
| 312 | + } | |
| 313 | + if(!d||!d.ok){ | |
| 314 | + stopPolling(); | |
| 315 | + $('waitBox').style.display='none'; | |
| 316 | + var m=(d&&(d.detail||d.error))||'poll failed'; | |
| 317 | + note($('loginNote'),m,'err'); | |
| 318 | + return; | |
| 319 | + } | |
| 320 | + if(d.interval)pollInterval=d.interval; | |
| 321 | + pollTimer=setTimeout(function(){startPolling();},Math.max(3,pollInterval)*1000); | |
| 322 | + }).catch(function(e){ | |
| 323 | + note($('loginNote'),'Poll failed: '+e.message,'err'); | |
| 324 | + pollTimer=setTimeout(function(){startPolling();},Math.max(5,pollInterval)*1000); | |
| 325 | + }); | |
| 326 | + },delay); | |
| 327 | +} | |
| 328 | + | |
| 329 | +function startLogin(){ | |
| 330 | + var b=$('btnStart'); | |
| 331 | + b.disabled=true;b.classList.add('loading'); | |
| 332 | + note($('startNote'),'Asking GitHub for a device code...'); | |
| 333 | + api('start').then(function(d){ | |
| 334 | + b.disabled=false;b.classList.remove('loading'); | |
| 335 | + note($('startNote'),''); | |
| 336 | + if(!d||!d.ok){ | |
| 337 | + note($('startNote'),(d&&(d.detail||d.error))||'start failed','err'); | |
| 338 | + return; | |
| 339 | + } | |
| 340 | + userCode=d.user_code||''; | |
| 341 | + VerifyUrl=d.verify_url||'https://github.com/login/device'; | |
| 342 | + $('userCode').textContent=userCode||'----'; | |
| 343 | + $('linkOpen').setAttribute('href',VerifyUrl); | |
| 344 | + pollInterval=d.interval||5; | |
| 345 | + showStep2(); | |
| 346 | + note($('loginNote'),''); | |
| 347 | + startPolling(); | |
| 348 | + }).catch(function(e){ | |
| 349 | + b.disabled=false;b.classList.remove('loading'); | |
| 350 | + note($('startNote'),'Start failed: '+e.message,'err'); | |
| 351 | + }); | |
| 352 | +} | |
| 353 | + | |
| 354 | +function copyOpen(){ | |
| 355 | + var go=function(){window.open(VerifyUrl,'_blank','noopener');}; | |
| 356 | + if(navigator.clipboard&&navigator.clipboard.writeText){ | |
| 357 | + navigator.clipboard.writeText(userCode).then(function(){ | |
| 358 | + toast('Code copied: '+userCode);go(); | |
| 359 | + }).catch(function(){toast('Copy failed - select the code manually');go();}); | |
| 360 | + }else{ | |
| 361 | + try{ | |
| 362 | + var r=document.createRange();r.selectNodeContents($('userCode')); | |
| 363 | + var s=window.getSelection();s.removeAllRanges();s.addRange(r); | |
| 364 | + document.execCommand('copy'); | |
| 365 | + toast('Code copied: '+userCode); | |
| 366 | + }catch(e){toast('Copy not available - select the code manually');} | |
| 367 | + go(); | |
| 368 | + } | |
| 369 | +} | |
| 370 | + | |
| 371 | +function cancelLogin(){ | |
| 372 | + stopPolling(); | |
| 373 | + api('cancel').then(function(){ | |
| 374 | + hideStep2(); | |
| 375 | + $('waitBox').style.display=''; | |
| 376 | + note($('loginNote'),''); | |
| 377 | + toast('Pending login cancelled'); | |
| 378 | + load(); | |
| 379 | + }).catch(function(e){toast('Cancel failed: '+e.message);}); | |
| 380 | +} | |
| 381 | + | |
| 382 | +function refreshToken(){ | |
| 383 | + var b=$('btnRefresh'); | |
| 384 | + b.disabled=true;b.classList.add('loading'); | |
| 385 | + note($('refreshNote'),'Asking Copilot for a new derived token...'); | |
| 386 | + api('refresh').then(function(d){ | |
| 387 | + b.disabled=false;b.classList.remove('loading'); | |
| 388 | + if(!d||!d.ok){ | |
| 389 | + note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err'); | |
| 390 | + return; | |
| 391 | + } | |
| 392 | + note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok'); | |
| 393 | + render(d); | |
| 394 | + }).catch(function(e){ | |
| 395 | + b.disabled=false;b.classList.remove('loading'); | |
| 396 | + note($('refreshNote'),'Refresh failed: '+e.message,'err'); | |
| 397 | + }); | |
| 398 | +} | |
| 399 | + | |
| 400 | +$('btnStart').onclick=startLogin; | |
| 401 | +$('btnCopyOpen').onclick=copyOpen; | |
| 402 | +$('btnCancel').onclick=cancelLogin; | |
| 403 | +$('btnRefresh').onclick=refreshToken; | |
| 404 | +$('btnReload').onclick=load; | |
| 405 | +load(); | |
| 406 | +</script> | |
| 407 | +</body></html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..97db5b6 | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,415 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_CPLOGIN_UI_HTML_H | |
| 3 | +#define SX_CPLOGIN_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>copilot</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 | + ".badge{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:600;\n" | |
| 32 | + " padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text);\n" | |
| 33 | + " border:1px solid var(--line);font-family:var(--mono);max-width:100%;overflow:hidden;\n" | |
| 34 | + " text-overflow:ellipsis;white-space:nowrap}\n" | |
| 35 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | |
| 36 | + " padding:16px;margin-bottom:12px}\n" | |
| 37 | + ".card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;\n" | |
| 38 | + " text-transform:uppercase;color:var(--text-2)}\n" | |
| 39 | + ".card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}\n" | |
| 40 | + ".row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n" | |
| 41 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;\n" | |
| 42 | + " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;\n" | |
| 43 | + " transition:transform .12s var(--ease),opacity .12s}\n" | |
| 44 | + ".btn:active{transform:scale(.98)}\n" | |
| 45 | + ".btn:disabled{opacity:.5;cursor:default}\n" | |
| 46 | + ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n" | |
| 47 | + ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | |
| 48 | + ".btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}\n" | |
| 49 | + "a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}\n" | |
| 50 | + ".kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}\n" | |
| 51 | + ".kv .k{color:var(--text-2);font-size:12px}\n" | |
| 52 | + ".kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}\n" | |
| 53 | + ".kv .v.plain{font-family:var(--font);font-size:13px}\n" | |
| 54 | + ".step{display:none}\n" | |
| 55 | + ".step.on{display:block}\n" | |
| 56 | + ".hint{margin:10px 0 0;font-size:12px;color:var(--text-2)}\n" | |
| 57 | + ".note{font-size:12.5px;margin-top:10px;display:none}\n" | |
| 58 | + ".note.show{display:block}\n" | |
| 59 | + ".note.err{color:var(--red)}\n" | |
| 60 | + ".note.ok{color:var(--green)}\n" | |
| 61 | + ".usercode{font-family:var(--mono);font-size:34px;font-weight:700;letter-spacing:.16em;\n" | |
| 62 | + " color:var(--text);background:var(--code-bg);border:1px solid var(--line-2);\n" | |
| 63 | + " border-radius:12px;padding:16px 10px;margin-top:12px;text-align:center;\n" | |
| 64 | + " word-break:break-all;user-select:all}\n" | |
| 65 | + ".count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}\n" | |
| 66 | + ".count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}\n" | |
| 67 | + ".wait{display:flex;align-items:center;gap:9px;margin-top:12px;font-size:12.5px;\n" | |
| 68 | + " color:var(--text-2)}\n" | |
| 69 | + ".wait .spin{display:inline-block;width:13px;height:13px;border-radius:50%;\n" | |
| 70 | + " border:2px solid var(--line-2);border-top-color:var(--blue);animation:sp .8s linear infinite}\n" | |
| 71 | + "@keyframes sp{to{transform:rotate(360deg)}}\n" | |
| 72 | + ".spin2{width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35);\n" | |
| 73 | + " border-top-color:#fff;display:none;animation:sp .7s linear infinite}\n" | |
| 74 | + ".btn.loading .spin2{display:inline-block}\n" | |
| 75 | + ".acct{display:flex;align-items:center;gap:10px;padding:9px 0;border-top:1px solid var(--line);\n" | |
| 76 | + " font-size:13px}\n" | |
| 77 | + ".acct:first-child{border-top:0}\n" | |
| 78 | + ".acct .nm{font-family:var(--mono);font-size:12.5px;flex:1 1 auto;min-width:0;\n" | |
| 79 | + " overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | |
| 80 | + ".acct .tag{font-size:11px;font-weight:650;padding:3px 9px;border-radius:999px;\n" | |
| 81 | + " background:var(--surface-2);color:var(--text-2);white-space:nowrap}\n" | |
| 82 | + ".acct .tag.ok{color:var(--green)}\n" | |
| 83 | + ".acct .tag.warn{color:var(--orange)}\n" | |
| 84 | + ".empty{font-size:12.5px;color:var(--text-2)}\n" | |
| 85 | + ".toast{position:fixed;left:50%;bottom:24px;transform:translate(-50%,12px);opacity:0;\n" | |
| 86 | + " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n" | |
| 87 | + " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n" | |
| 88 | + " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n" | |
| 89 | + " z-index:9;max-width:calc(100vw - 32px)}\n" | |
| 90 | + ".toast.show{opacity:1;transform:translate(-50%,0)}\n" | |
| 91 | + "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | |
| 92 | + " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n" | |
| 93 | + " font-family:inherit}\n" | |
| 94 | + "@media (max-width:520px){\n" | |
| 95 | + " #app{padding:12px 12px 32px}\n" | |
| 96 | + " .kv{grid-template-columns:1fr;gap:2px 0}\n" | |
| 97 | + " .kv .k{margin-top:8px}\n" | |
| 98 | + " .card{padding:13px;border-radius:12px}\n" | |
| 99 | + " .count{font-size:28px}\n" | |
| 100 | + " .usercode{font-size:27px;letter-spacing:.1em;padding:14px 6px}\n" | |
| 101 | + "}\n" | |
| 102 | + "</style>\n" | |
| 103 | + "</head>\n" | |
| 104 | + "<body>\n" | |
| 105 | + "<div id=\"app\">\n" | |
| 106 | + " <div class=\"hd\">\n" | |
| 107 | + " <div class=\"grow\">\n" | |
| 108 | + " <h1>GitHub Copilot</h1>\n" | |
| 109 | + " <div class=\"sub\" id=\"sub\">Device code login on this node</div>\n" | |
| 110 | + " </div>\n" | |
| 111 | + " <span class=\"badge\" id=\"userBadge\" style=\"display:none\"></span>\n" | |
| 112 | + " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n" | |
| 113 | + " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n" | |
| 114 | + " </div>\n" | |
| 115 | + "\n" | |
| 116 | + " <div class=\"card\">\n" | |
| 117 | + " <h2>Session</h2>\n" | |
| 118 | + " <p class=\"lead\" id=\"sessionLead\">Reading the local Copilot credentials.</p>\n" | |
| 119 | + " <div class=\"kv\" id=\"session\"></div>\n" | |
| 120 | + " <div class=\"row\" style=\"margin-top:14px\">\n" | |
| 121 | + " <button class=\"btn ghost\" id=\"btnRefresh\" type=\"button\"><span class=\"spin2\"></span>Refresh Token Now</button>\n" | |
| 122 | + " <button class=\"btn ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n" | |
| 123 | + " </div>\n" | |
| 124 | + " <div class=\"note\" id=\"refreshNote\"></div>\n" | |
| 125 | + " </div>\n" | |
| 126 | + "\n" | |
| 127 | + " <div class=\"card\">\n" | |
| 128 | + " <h2>Device login</h2>\n" | |
| 129 | + " <p class=\"lead\">Sign in with GitHub. The login CLI opens the device flow and writes the\n" | |
| 130 | + " credential file on this node; no token ever passes through this page.</p>\n" | |
| 131 | + "\n" | |
| 132 | + " <div class=\"step on\" id=\"step1\">\n" | |
| 133 | + " <div class=\"row\">\n" | |
| 134 | + " <button class=\"btn\" id=\"btnStart\" type=\"button\">Start GitHub Copilot Login</button>\n" | |
| 135 | + " </div>\n" | |
| 136 | + " <p class=\"hint\">This asks GitHub for a one-time code. Nothing is stored until you approve\n" | |
| 137 | + " it in the browser.</p>\n" | |
| 138 | + " <div class=\"note\" id=\"startNote\"></div>\n" | |
| 139 | + " </div>\n" | |
| 140 | + "\n" | |
| 141 | + " <div class=\"step\" id=\"step2\">\n" | |
| 142 | + " <p class=\"hint\" style=\"margin-top:0\">Enter this code at\n" | |
| 143 | + " <span style=\"font-family:var(--mono)\">github.com/login/device</span>:</p>\n" | |
| 144 | + " <div class=\"usercode\" id=\"userCode\">----</div>\n" | |
| 145 | + " <div class=\"row\" style=\"margin-top:12px\">\n" | |
| 146 | + " <button class=\"btn\" id=\"btnCopyOpen\" type=\"button\">Copy Code & Open GitHub</button>\n" | |
| 147 | + " <a class=\"btn ghost\" id=\"linkOpen\" href=\"https://github.com/login/device\"\n" | |
| 148 | + " target=\"_blank\" rel=\"noopener noreferrer\">Open GitHub</a>\n" | |
| 149 | + " <button class=\"btn danger\" id=\"btnCancel\" type=\"button\">Cancel</button>\n" | |
| 150 | + " </div>\n" | |
| 151 | + " <div class=\"wait\" id=\"waitBox\"><span class=\"spin\"></span>\n" | |
| 152 | + " <span id=\"waitText\">Waiting for GitHub confirmation...</span></div>\n" | |
| 153 | + " <div class=\"note\" id=\"loginNote\"></div>\n" | |
| 154 | + " </div>\n" | |
| 155 | + " </div>\n" | |
| 156 | + "\n" | |
| 157 | + " <div class=\"card\">\n" | |
| 158 | + " <h2>Named accounts</h2>\n" | |
| 159 | + " <p class=\"lead\">Every account file in the local accounts directory.</p>\n" | |
| 160 | + " <div id=\"accounts\"><div class=\"empty\">No named accounts.</div></div>\n" | |
| 161 | + " </div>\n" | |
| 162 | + "</div>\n" | |
| 163 | + "\n" | |
| 164 | + "<div class=\"toast\" id=\"toast\"></div>\n" | |
| 165 | + "\n" | |
| 166 | + "<script>\n" | |
| 167 | + "var q=new URLSearchParams(location.search);\n" | |
| 168 | + "var node=q.get('node')||'';\n" | |
| 169 | + "var sid=q.get('id')||'';\n" | |
| 170 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | |
| 171 | + " localStorage.getItem('bot_active_pwd')||'';\n" | |
| 172 | + "\n" | |
| 173 | + "/* Two call routes. Getting this wrong is the most common plugin bug:\n" | |
| 174 | + " * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)\n" | |
| 175 | + " * -> call the hub proxy back: /plugins?plugin=plugin_copilot_login&action=..\n" | |
| 176 | + " * opened directly on the node\n" | |
| 177 | + " * -> the plugin itself is the route: /plugin_copilot_login?action=..\n" | |
| 178 | + " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n" | |
| 179 | + "var HUB=q.get('plugin')||'';\n" | |
| 180 | + "function url(action,extra){\n" | |
| 181 | + " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_copilot_login')+\n" | |
| 182 | + " '?action='+encodeURIComponent(action)+\n" | |
| 183 | + " (extra?('&'+extra):'')+\n" | |
| 184 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | |
| 185 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | |
| 186 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | |
| 187 | + "}\n" | |
| 188 | + "function hdr(){\n" | |
| 189 | + " var h={};\n" | |
| 190 | + " if(pwd)h['X-Bot-Password']=pwd;\n" | |
| 191 | + " return h;\n" | |
| 192 | + "}\n" | |
| 193 | + "function api(action,extra){\n" | |
| 194 | + " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n" | |
| 195 | + " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n" | |
| 196 | + " });\n" | |
| 197 | + "}\n" | |
| 198 | + "\n" | |
| 199 | + "var $=function(id){return document.getElementById(id);};\n" | |
| 200 | + "function toast(msg){\n" | |
| 201 | + " var t=$('toast');t.textContent=msg;t.classList.add('show');\n" | |
| 202 | + " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n" | |
| 203 | + "}\n" | |
| 204 | + "function note(el,msg,kind){\n" | |
| 205 | + " el.textContent=msg||'';\n" | |
| 206 | + " el.className='note'+(msg?' show '+(kind||''):'');\n" | |
| 207 | + "}\n" | |
| 208 | + "function kv(el,rows){\n" | |
| 209 | + " el.innerHTML='';\n" | |
| 210 | + " rows.forEach(function(r){\n" | |
| 211 | + " var a=document.createElement('div');a.className='k';a.textContent=r[0];\n" | |
| 212 | + " var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');\n" | |
| 213 | + " b.textContent=r[1];el.appendChild(a);el.appendChild(b);\n" | |
| 214 | + " });\n" | |
| 215 | + "}\n" | |
| 216 | + "function fmtExpiry(sec){\n" | |
| 217 | + " if(typeof sec!=='number')return '-';\n" | |
| 218 | + " if(sec<=0)return 'expired';\n" | |
| 219 | + " if(sec<90)return sec+'s';\n" | |
| 220 | + " if(sec<5400)return Math.round(sec/60)+' min';\n" | |
| 221 | + " if(sec<172800)return Math.round(sec/3600)+' h';\n" | |
| 222 | + " if(sec<63072000)return Math.round(sec/86400)+' d';\n" | |
| 223 | + " return Math.round(sec/31536000)+' yr';\n" | |
| 224 | + "}\n" | |
| 225 | + "function setPill(st){\n" | |
| 226 | + " var p=$('pill'),t=$('pillText');\n" | |
| 227 | + " if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}\n" | |
| 228 | + " else if(st.logged_in){p.className='pill ok';t.textContent='Connected';}\n" | |
| 229 | + " else if(st.pending){p.className='pill warn';t.textContent='Signing in';}\n" | |
| 230 | + " else {p.className='pill off';t.textContent='Not Connected';}\n" | |
| 231 | + "}\n" | |
| 232 | + "function render(st){\n" | |
| 233 | + " setPill(st);\n" | |
| 234 | + " var badge=$('userBadge');\n" | |
| 235 | + " if(st.logged_in&&st.user){badge.style.display='';badge.textContent='@'+st.user;}\n" | |
| 236 | + " else badge.style.display='none';\n" | |
| 237 | + " $('sub').textContent=st.account&&st.account!=='default'\n" | |
| 238 | + " ? 'Device code login - '+st.account : 'Device code login on this node';\n" | |
| 239 | + "\n" | |
| 240 | + " if(st.logged_in){\n" | |
| 241 | + " $('sessionLead').textContent=st.expired\n" | |
| 242 | + " ? 'A Copilot session is stored but its derived token has expired. Use Refresh Token Now.'\n" | |
| 243 | + " : 'This node holds a GitHub Copilot session.';\n" | |
| 244 | + " }else{\n" | |
| 245 | + " $('sessionLead').textContent='No Copilot session on this node yet. Start a login below.';\n" | |
| 246 | + " }\n" | |
| 247 | + "\n" | |
| 248 | + " kv($('session'),[\n" | |
| 249 | + " ['Account', st.account||'-', true],\n" | |
| 250 | + " ['GitHub user', st.user||'-', true],\n" | |
| 251 | + " ['Logged in', st.logged_in?'yes':'no', true],\n" | |
| 252 | + " ['Derived token', st.logged_in?(st.expired?'expired':'valid'):'-', true],\n" | |
| 253 | + " ['Token expires', st.logged_in&&st.cache_present?fmtExpiry(st.expires_in_sec):'-', true],\n" | |
| 254 | + " ['Login pending', st.pending?'yes':'no', true],\n" | |
| 255 | + " ['Login CLI', st.cli_present?'found':'not found', true],\n" | |
| 256 | + " ['Scope', st.scope||'-', true],\n" | |
| 257 | + " ['Profile model', st.profile_exists?(st.profile||'-'):'not created', true],\n" | |
| 258 | + " ['Credentials', st.credentials_path||'-']\n" | |
| 259 | + " ]);\n" | |
| 260 | + "\n" | |
| 261 | + " var box=$('accounts');\n" | |
| 262 | + " box.innerHTML='';\n" | |
| 263 | + " var list=st.accounts||[];\n" | |
| 264 | + " if(!list.length){\n" | |
| 265 | + " var e=document.createElement('div');e.className='empty';\n" | |
| 266 | + " e.textContent='No named accounts.';box.appendChild(e);\n" | |
| 267 | + " }else{\n" | |
| 268 | + " list.forEach(function(a){\n" | |
| 269 | + " var row=document.createElement('div');row.className='acct';\n" | |
| 270 | + " var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;\n" | |
| 271 | + " var tg=document.createElement('div');\n" | |
| 272 | + " tg.className='tag '+(a.logged_in?(a.expired?'warn':'ok'):'');\n" | |
| 273 | + " tg.textContent=a.logged_in?(a.expired?'expired':'valid'):'no token';\n" | |
| 274 | + " row.appendChild(nm);row.appendChild(tg);box.appendChild(row);\n" | |
| 275 | + " });\n" | |
| 276 | + " }\n" | |
| 277 | + "\n" | |
| 278 | + " if(st.pending){showStep2();}\n" | |
| 279 | + "}\n" | |
| 280 | + "function load(){\n" | |
| 281 | + " return api('status').then(function(d){\n" | |
| 282 | + " if(d&&d.ok)render(d);\n" | |
| 283 | + " else toast((d&&d.error)||'status failed');\n" | |
| 284 | + " }).catch(function(e){toast('Status failed: '+e.message);});\n" | |
| 285 | + "}\n" | |
| 286 | + "\n" | |
| 287 | + "/* ---- device flow ---- */\n" | |
| 288 | + "var userCode='',VerifyUrl='https://github.com/login/device';\n" | |
| 289 | + "var pollTimer=null,pollInterval=5,pollStop=0;\n" | |
| 290 | + "\n" | |
| 291 | + "function showStep2(){\n" | |
| 292 | + " $('step1').classList.remove('on');\n" | |
| 293 | + " $('step2').classList.add('on');\n" | |
| 294 | + "}\n" | |
| 295 | + "function hideStep2(){\n" | |
| 296 | + " $('step1').classList.add('on');\n" | |
| 297 | + " $('step2').classList.remove('on');\n" | |
| 298 | + "}\n" | |
| 299 | + "function stopPolling(){\n" | |
| 300 | + " if(pollTimer){clearTimeout(pollTimer);pollTimer=null;}\n" | |
| 301 | + "}\n" | |
| 302 | + "function startPolling(){\n" | |
| 303 | + " stopPolling();\n" | |
| 304 | + " $('waitBox').style.display='';\n" | |
| 305 | + " $('waitText').textContent='Waiting for GitHub confirmation...';\n" | |
| 306 | + " var delay=Math.max(3,pollInterval||5)*1000;\n" | |
| 307 | + " pollTimer=setTimeout(function(){\n" | |
| 308 | + " api('poll').then(function(d){\n" | |
| 309 | + " if(d&&d.ok&&d.state==='done'){\n" | |
| 310 | + " stopPolling();\n" | |
| 311 | + " $('waitText').textContent='Authorized.';\n" | |
| 312 | + " note($('loginNote'),'Signed in'+(d.user?(' as @'+d.user):'')+'.','ok');\n" | |
| 313 | + " hideStep2();\n" | |
| 314 | + " render(d);\n" | |
| 315 | + " toast('GitHub Copilot connected');\n" | |
| 316 | + " return;\n" | |
| 317 | + " }\n" | |
| 318 | + " if(!d||!d.ok){\n" | |
| 319 | + " stopPolling();\n" | |
| 320 | + " $('waitBox').style.display='none';\n" | |
| 321 | + " var m=(d&&(d.detail||d.error))||'poll failed';\n" | |
| 322 | + " note($('loginNote'),m,'err');\n" | |
| 323 | + " return;\n" | |
| 324 | + " }\n" | |
| 325 | + " if(d.interval)pollInterval=d.interval;\n" | |
| 326 | + " pollTimer=setTimeout(function(){startPolling();},Math.max(3,pollInterval)*1000);\n" | |
| 327 | + " }).catch(function(e){\n" | |
| 328 | + " note($('loginNote'),'Poll failed: '+e.message,'err');\n" | |
| 329 | + " pollTimer=setTimeout(function(){startPolling();},Math.max(5,pollInterval)*1000);\n" | |
| 330 | + " });\n" | |
| 331 | + " },delay);\n" | |
| 332 | + "}\n" | |
| 333 | + "\n" | |
| 334 | + "function startLogin(){\n" | |
| 335 | + " var b=$('btnStart');\n" | |
| 336 | + " b.disabled=true;b.classList.add('loading');\n" | |
| 337 | + " note($('startNote'),'Asking GitHub for a device code...');\n" | |
| 338 | + " api('start').then(function(d){\n" | |
| 339 | + " b.disabled=false;b.classList.remove('loading');\n" | |
| 340 | + " note($('startNote'),'');\n" | |
| 341 | + " if(!d||!d.ok){\n" | |
| 342 | + " note($('startNote'),(d&&(d.detail||d.error))||'start failed','err');\n" | |
| 343 | + " return;\n" | |
| 344 | + " }\n" | |
| 345 | + " userCode=d.user_code||'';\n" | |
| 346 | + " VerifyUrl=d.verify_url||'https://github.com/login/device';\n" | |
| 347 | + " $('userCode').textContent=userCode||'----';\n" | |
| 348 | + " $('linkOpen').setAttribute('href',VerifyUrl);\n" | |
| 349 | + " pollInterval=d.interval||5;\n" | |
| 350 | + " showStep2();\n" | |
| 351 | + " note($('loginNote'),'');\n" | |
| 352 | + " startPolling();\n" | |
| 353 | + " }).catch(function(e){\n" | |
| 354 | + " b.disabled=false;b.classList.remove('loading');\n" | |
| 355 | + " note($('startNote'),'Start failed: '+e.message,'err');\n" | |
| 356 | + " });\n" | |
| 357 | + "}\n" | |
| 358 | + "\n" | |
| 359 | + "function copyOpen(){\n" | |
| 360 | + " var go=function(){window.open(VerifyUrl,'_blank','noopener');};\n" | |
| 361 | + " if(navigator.clipboard&&navigator.clipboard.writeText){\n" | |
| 362 | + " navigator.clipboard.writeText(userCode).then(function(){\n" | |
| 363 | + " toast('Code copied: '+userCode);go();\n" | |
| 364 | + " }).catch(function(){toast('Copy failed - select the code manually');go();});\n" | |
| 365 | + " }else{\n" | |
| 366 | + " try{\n" | |
| 367 | + " var r=document.createRange();r.selectNodeContents($('userCode'));\n" | |
| 368 | + " var s=window.getSelection();s.removeAllRanges();s.addRange(r);\n" | |
| 369 | + " document.execCommand('copy');\n" | |
| 370 | + " toast('Code copied: '+userCode);\n" | |
| 371 | + " }catch(e){toast('Copy not available - select the code manually');}\n" | |
| 372 | + " go();\n" | |
| 373 | + " }\n" | |
| 374 | + "}\n" | |
| 375 | + "\n" | |
| 376 | + "function cancelLogin(){\n" | |
| 377 | + " stopPolling();\n" | |
| 378 | + " api('cancel').then(function(){\n" | |
| 379 | + " hideStep2();\n" | |
| 380 | + " $('waitBox').style.display='';\n" | |
| 381 | + " note($('loginNote'),'');\n" | |
| 382 | + " toast('Pending login cancelled');\n" | |
| 383 | + " load();\n" | |
| 384 | + " }).catch(function(e){toast('Cancel failed: '+e.message);});\n" | |
| 385 | + "}\n" | |
| 386 | + "\n" | |
| 387 | + "function refreshToken(){\n" | |
| 388 | + " var b=$('btnRefresh');\n" | |
| 389 | + " b.disabled=true;b.classList.add('loading');\n" | |
| 390 | + " note($('refreshNote'),'Asking Copilot for a new derived token...');\n" | |
| 391 | + " api('refresh').then(function(d){\n" | |
| 392 | + " b.disabled=false;b.classList.remove('loading');\n" | |
| 393 | + " if(!d||!d.ok){\n" | |
| 394 | + " note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');\n" | |
| 395 | + " return;\n" | |
| 396 | + " }\n" | |
| 397 | + " note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');\n" | |
| 398 | + " render(d);\n" | |
| 399 | + " }).catch(function(e){\n" | |
| 400 | + " b.disabled=false;b.classList.remove('loading');\n" | |
| 401 | + " note($('refreshNote'),'Refresh failed: '+e.message,'err');\n" | |
| 402 | + " });\n" | |
| 403 | + "}\n" | |
| 404 | + "\n" | |
| 405 | + "$('btnStart').onclick=startLogin;\n" | |
| 406 | + "$('btnCopyOpen').onclick=copyOpen;\n" | |
| 407 | + "$('btnCancel').onclick=cancelLogin;\n" | |
| 408 | + "$('btnRefresh').onclick=refreshToken;\n" | |
| 409 | + "$('btnReload').onclick=load;\n" | |
| 410 | + "load();\n" | |
| 411 | + "</script>\n" | |
| 412 | + "\002</body></html>\n" | |
| 413 | + ; | |
| 414 | + | |
| 415 | +#endif /* SX_CPLOGIN_UI_HTML_H */ |
| 1 | 1 | new file mode 100755 |
| index 0000000..dd28924 | ||
| --- /dev/null | ||
| +++ b/tests/mock_login.sh | ||
| @@ -0,0 +1,120 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/mock_login.sh - stand-in for scorpiox-copilot-login in machine mode. | |
| 3 | +# | |
| 4 | +# The plugin never speaks TLS: it shells out to the node's login CLI and reads | |
| 5 | +# only what that CLI writes. This mock reproduces the CLI's documented machine | |
| 6 | +# contract (SXLOGIN-MACHINE-V1) against a scratch directory so the whole plugin | |
| 7 | +# can be exercised offline, with no network and no real GitHub account. | |
| 8 | +# | |
| 9 | +# State lives in $COPILOT_MOCK_DIR: | |
| 10 | +# poll_done -> the next --poll authorizes and writes credentials | |
| 11 | +# poll_denied -> the next --poll reports access_denied | |
| 12 | +# fail_start -> --start reports a network failure | |
| 13 | +# no_cli -> (handled by the caller: point COPILOT_LOGIN_BIN elsewhere) | |
| 14 | +# | |
| 15 | +# Usage mirrors the real CLI: --status | --start | --poll | --cancel [--name N] [--force] | |
| 16 | + | |
| 17 | +set -u | |
| 18 | + | |
| 19 | +MOCK="${COPILOT_MOCK_DIR:-/tmp/copilot-mock}" | |
| 20 | +mkdir -p "$MOCK" 2>/dev/null || true | |
| 21 | + | |
| 22 | +NAME="" | |
| 23 | +MODE="" | |
| 24 | +FORCE=0 | |
| 25 | +while [ $# -gt 0 ]; do | |
| 26 | + case "$1" in | |
| 27 | + --status|--start|--poll|--cancel) MODE="$1" ;; | |
| 28 | + --name) shift; NAME="$1" ;; | |
| 29 | + --force) FORCE=1 ;; | |
| 30 | + *) : ;; | |
| 31 | + esac | |
| 32 | + shift | |
| 33 | +done | |
| 34 | + | |
| 35 | +[ -n "$NAME" ] || NAME="default" | |
| 36 | + | |
| 37 | +creds_file() { | |
| 38 | + if [ "$1" = "default" ]; then | |
| 39 | + printf '%s' "${COPILOT_CREDS_PATH:-$HOME/.copilot/.credentials.json}" | |
| 40 | + else | |
| 41 | + printf '%s' "${COPILOT_ACCOUNTS_DIR:-$HOME/.copilot/accounts}/$1.json" | |
| 42 | + fi | |
| 43 | +} | |
| 44 | + | |
| 45 | +pending_file() { | |
| 46 | + printf '%s/%s.json' "${COPILOT_PENDING_DIR:-$HOME/.claude/.login-pending}" "copilot-$1" | |
| 47 | +} | |
| 48 | + | |
| 49 | +write_creds() { | |
| 50 | + f=$(creds_file "$1") | |
| 51 | + d=$(dirname "$f") | |
| 52 | + mkdir -p "$d" 2>/dev/null || true | |
| 53 | + { | |
| 54 | + printf '{\n' | |
| 55 | + printf ' "github_token": "gho_MOCKTOKENMUSTNOTLEAK000000000000000",\n' | |
| 56 | + printf ' "token_type": "bearer",\n' | |
| 57 | + printf ' "scope": "%s",\n' "${COPILOT_MOCK_SCOPE:-read:user}" | |
| 58 | + printf ' "timestamp": "2026-01-01T00:00:00Z"\n' | |
| 59 | + printf '}\n' | |
| 60 | + } > "$f" | |
| 61 | +} | |
| 62 | + | |
| 63 | +case "$MODE" in | |
| 64 | +--status) | |
| 65 | + if [ -f "$(creds_file "$NAME")" ]; then logged=true; else logged=false; fi | |
| 66 | + if [ -f "$(pending_file "$NAME")" ]; then pending=true; else pending=false; fi | |
| 67 | + printf '{"ok":true,"provider":"copilot","name":"GitHub Copilot","flow":"device_code",' | |
| 68 | + printf '"account":"%s","logged_in":%s,"path":"%s","expires_at":0,"expired":false,' | |
| 69 | + printf '"has_refresh":false,"pending":%s,"profile":"copilot","profile_exists":false,' | |
| 70 | + printf '"named_accounts":true,"protocol":"SXLOGIN-MACHINE-V1"}\n' \ | |
| 71 | + "$NAME" "$logged" "$(creds_file "$NAME")" "$pending" | |
| 72 | + exit 0 | |
| 73 | + ;; | |
| 74 | +--start) | |
| 75 | + if [ -f "$MOCK/fail_start" ]; then | |
| 76 | + printf 'error: device code request failed\n' >&2 | |
| 77 | + printf '{"ok":false,"provider":"copilot","error":"network","detail":"device code request failed"}\n' | |
| 78 | + exit 1 | |
| 79 | + fi | |
| 80 | + p=$(pending_file "$NAME") | |
| 81 | + mkdir -p "$(dirname "$p")" 2>/dev/null || true | |
| 82 | + printf '{"device_code":"dc_mock_value","interval":5,"force":%d,"vscode":0}\n' "$FORCE" > "$p" | |
| 83 | + printf 'Requesting device code...\n' | |
| 84 | + printf '{"ok":true,"provider":"copilot","flow":"device_code",' | |
| 85 | + printf '"verify_url":"https://github.com/login/device","user_code":"1234-5678",' | |
| 86 | + printf '"interval":5,"expires_in":900,' | |
| 87 | + printf '"hint":"Open the link, enter the code, approve. This page checks automatically."}\n' | |
| 88 | + exit 0 | |
| 89 | + ;; | |
| 90 | +--poll) | |
| 91 | + p=$(pending_file "$NAME") | |
| 92 | + if [ ! -f "$p" ]; then | |
| 93 | + printf '{"ok":false,"provider":"copilot","error":"no_pending","detail":"run --start first"}\n' | |
| 94 | + exit 1 | |
| 95 | + fi | |
| 96 | + if [ -f "$MOCK/poll_denied" ]; then | |
| 97 | + rm -f "$p" | |
| 98 | + printf '{"ok":false,"provider":"copilot","error":"denied","detail":"access_denied"}\n' | |
| 99 | + exit 1 | |
| 100 | + fi | |
| 101 | + if [ -f "$MOCK/poll_done" ]; then | |
| 102 | + rm -f "$p" "$MOCK/poll_done" | |
| 103 | + write_creds "$NAME" | |
| 104 | + printf '{"ok":true,"provider":"copilot","state":"done","logged_in":true,' | |
| 105 | + printf '"path":"%s","profile":"copilot","profile_created":false}\n' "$(creds_file "$NAME")" | |
| 106 | + exit 0 | |
| 107 | + fi | |
| 108 | + printf '{"ok":true,"provider":"copilot","state":"pending","interval":5}\n' | |
| 109 | + exit 0 | |
| 110 | + ;; | |
| 111 | +--cancel) | |
| 112 | + rm -f "$(pending_file "$NAME")" | |
| 113 | + printf '{"ok":true,"provider":"copilot","cancelled":true}\n' | |
| 114 | + exit 0 | |
| 115 | + ;; | |
| 116 | +*) | |
| 117 | + printf 'error: mock_login.sh needs --status|--start|--poll|--cancel\n' >&2 | |
| 118 | + exit 2 | |
| 119 | + ;; | |
| 120 | +esac |
| 1 | 1 | new file mode 100755 |
| index 0000000..b1b3f22 | ||
| --- /dev/null | ||
| +++ b/tests/mock_refresh.sh | ||
| @@ -0,0 +1,52 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/mock_refresh.sh - stand-in for scorpiox-copilot-refreshtoken. | |
| 3 | +# | |
| 4 | +# The real CLI derives the short-lived Copilot JWT from the stored github_token | |
| 5 | +# and caches it in ~/.copilot/.copilot-token-cache.json, then prints the JWT on | |
| 6 | +# stdout. The plugin must discard that stdout entirely and prove the refresh by | |
| 7 | +# re-reading the cache file, so this mock prints a deliberately leaky payload to | |
| 8 | +# make a regression visible in the tests. | |
| 9 | +# | |
| 10 | +# --credentials-file <path> [--force] | |
| 11 | +# | |
| 12 | +# COPILOT_MOCK_FAIL=1 makes the refresh fail without touching the cache. | |
| 13 | + | |
| 14 | +set -u | |
| 15 | + | |
| 16 | +CREDS="" | |
| 17 | +while [ $# -gt 0 ]; do | |
| 18 | + case "$1" in | |
| 19 | + --credentials-file) shift; CREDS="$1" ;; | |
| 20 | + *) : ;; | |
| 21 | + esac | |
| 22 | + shift | |
| 23 | +done | |
| 24 | + | |
| 25 | +[ -n "$CREDS" ] || CREDS="${COPILOT_CREDS_PATH:-$HOME/.copilot/.credentials.json}" | |
| 26 | + | |
| 27 | +if [ ! -f "$CREDS" ]; then | |
| 28 | + printf 'error: cannot read credentials file: %s\n' "$CREDS" >&2 | |
| 29 | + exit 1 | |
| 30 | +fi | |
| 31 | + | |
| 32 | +if [ "${COPILOT_MOCK_FAIL:-0}" = "1" ]; then | |
| 33 | + printf 'error: token exchange failed\n' >&2 | |
| 34 | + exit 1 | |
| 35 | +fi | |
| 36 | + | |
| 37 | +case "$CREDS" in | |
| 38 | + */.copilot/.credentials.json) D=$(dirname "$CREDS") ;; | |
| 39 | + *) D=$(dirname "$CREDS") ;; | |
| 40 | +esac | |
| 41 | +CACHE="$D/.copilot-token-cache.json" | |
| 42 | + | |
| 43 | +EXP=$(( $(date +%s) + 1800 )) | |
| 44 | +{ | |
| 45 | + printf '{"access_token": "MOCK-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$EXP" | |
| 46 | +} > "$CACHE" | |
| 47 | + | |
| 48 | +# Exactly what the real CLI prints: token material on stdout. The plugin reads | |
| 49 | +# this and throws it away. | |
| 50 | +printf 'Token exchange successful\n' | |
| 51 | +printf '{"access_token": "MOCK-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$EXP" | |
| 52 | +exit 0 |
| 1 | 1 | new file mode 100755 |
| index 0000000..fb0572f | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,367 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_copilot_login across all 3 modes. | |
| 3 | +# | |
| 4 | +# Every check runs against ./plugin_copilot_login with the credential paths and | |
| 5 | +# both CLIs redirected at throwaway fixtures, so the suite proves the public | |
| 6 | +# contract without touching a real Copilot session and without a network. | |
| 7 | +# | |
| 8 | +# What it proves: | |
| 9 | +# - --meta is exactly {"name":"copilot","desc":"Copilot login"} and is | |
| 10 | +# reachable 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 credentials file, the token cache, config.json, the | |
| 13 | +# profile file and the named account directory, and NEVER emits a token | |
| 14 | +# - start relays the CLI's device code + user_code, poll reports pending then | |
| 15 | +# done, cancel drops the pending flow | |
| 16 | +# - refresh performs the grant, drops the CLI's payload, 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 | +chmod +x tests/mock_login.sh tests/mock_refresh.sh 2>/dev/null || true | |
| 27 | + | |
| 28 | +BIN=./plugin_copilot_login | |
| 29 | +ID=plugin_copilot_login | |
| 30 | +PASS=0 | |
| 31 | +FAIL=0 | |
| 32 | + | |
| 33 | +if [ -t 1 ]; then | |
| 34 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 35 | +else | |
| 36 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 37 | +fi | |
| 38 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 39 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 40 | + | |
| 41 | +check() { # check <desc> <expected-substring> <actual> | |
| 42 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 43 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | |
| 44 | + fi | |
| 45 | +} | |
| 46 | + | |
| 47 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 48 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 49 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 50 | + fi | |
| 51 | +} | |
| 52 | + | |
| 53 | +check_empty() { # check_empty <desc> <actual> - passes only when nothing was found | |
| 54 | + if [ -z "$2" ]; then pass "$1"; else | |
| 55 | + fail "$1 (must be empty)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 56 | + fi | |
| 57 | +} | |
| 58 | + | |
| 59 | +found() { # found <desc> <needle> <file...> - the needle must appear somewhere | |
| 60 | + _d=$1; _n=$2; shift 2 | |
| 61 | + if grep -F -q -- "$_n" "$@" 2>/dev/null; then pass "$_d"; else | |
| 62 | + fail "$_d (missing: $_n)" | |
| 63 | + fi | |
| 64 | +} | |
| 65 | + | |
| 66 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 67 | + | |
| 68 | +# strip CGI headers if present, drop CRs, keep the payload | |
| 69 | +body() { | |
| 70 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 71 | + BEGIN { inhdr = 0 } | |
| 72 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next } | |
| 73 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 74 | + inhdr { next } | |
| 75 | + { print } | |
| 76 | + ' | |
| 77 | +} | |
| 78 | + | |
| 79 | +json_ok() { # json_ok <desc> <json> [python-expression] | |
| 80 | + expr=${3:-True} | |
| 81 | + 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 | |
| 82 | + pass "$1" | |
| 83 | + else | |
| 84 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 85 | + fi | |
| 86 | +} | |
| 87 | + | |
| 88 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | |
| 89 | +apiraw() { QUERY_STRING="$1" $BIN; } | |
| 90 | + | |
| 91 | +# ---------------------------------------------------------------- build | |
| 92 | +section "build" | |
| 93 | +if [ ! -x "$BIN" ]; then | |
| 94 | + echo " building native binary..." | |
| 95 | + gcc -O2 -std=c99 -Wall -Wextra -Wno-format-truncation -I src -o "$BIN" src/$ID.c || { | |
| 96 | + fail "native build"; exit 1; } | |
| 97 | +fi | |
| 98 | +pass "native binary present" | |
| 99 | + | |
| 100 | +if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | |
| 101 | + pass "src/ui_html.h is in sync with src/ui.html" | |
| 102 | +else | |
| 103 | + fail "src/ui_html.h is stale - run tools/gen_ui.py" | |
| 104 | +fi | |
| 105 | + | |
| 106 | +check "ui header is marked generated" \ | |
| 107 | + "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)" | |
| 108 | + | |
| 109 | +# ---------------------------------------------------------------- --meta | |
| 110 | +section "discovery metadata" | |
| 111 | +META=$($BIN --meta) | |
| 112 | +check "meta is the exact one-line contract" '{"name":"copilot","desc":"Copilot login"}' "$META" | |
| 113 | +check "meta works through SX_PLUGIN_META" '{"name":"copilot"' "$(SX_PLUGIN_META=1 $BIN)" | |
| 114 | +check "meta is reachable with no password" '{"name":"copilot"' "$(BOT_PASSWORD='' $BIN --meta)" | |
| 115 | +check_not "meta carries nothing else" 'plugin' "$META" | |
| 116 | +check "version is reported" "$ID" "$($BIN --version)" | |
| 117 | + | |
| 118 | +# ---------------------------------------------------------------- fixtures | |
| 119 | +FIX=$(mktemp -d 2>/dev/null || mktemp -d -t cplfix) | |
| 120 | +trap 'rm -rf "$FIX"' EXIT | |
| 121 | + | |
| 122 | +mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/mock" | |
| 123 | +export COPILOT_LOGIN_BIN="$ROOT/tests/mock_login.sh" | |
| 124 | +export COPILOT_REFRESH_BIN="$ROOT/tests/mock_refresh.sh" | |
| 125 | +export COPILOT_PENDING_DIR="$FIX/pend" | |
| 126 | +export COPILOT_ENV_DIR="$FIX/env" | |
| 127 | +export COPILOT_ACCOUNTS_DIR="$FIX/acc" | |
| 128 | +export COPILOT_CREDS_PATH="$FIX/.credentials.json" | |
| 129 | +export COPILOT_MOCK_DIR="$FIX/mock" | |
| 130 | +export BOT_PASSWORD=testpw | |
| 131 | +PWDQ='pwd=testpw' | |
| 132 | + | |
| 133 | +NOW=$(date +%s) | |
| 134 | +FUTURE=$(( NOW + 1800 )) | |
| 135 | +PAST=$(( NOW - 3600 )) | |
| 136 | + | |
| 137 | +mkcreds() { # mkcreds <path> | |
| 138 | + { | |
| 139 | + printf '{\n' | |
| 140 | + printf ' "github_token": "gho_SECRETGITHUBTOKENMUSTNOTLEAK0000",\n' | |
| 141 | + printf ' "token_type": "bearer",\n' | |
| 142 | + printf ' "scope": "read:user",\n' | |
| 143 | + printf ' "timestamp": "2026-01-01T00:00:00Z"\n' | |
| 144 | + printf '}\n' | |
| 145 | + } > "$1" | |
| 146 | +} | |
| 147 | + | |
| 148 | +mkcache() { # mkcache <path> <expires_at-seconds> | |
| 149 | + printf '{"access_token": "SECRET-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$2" > "$1" | |
| 150 | +} | |
| 151 | + | |
| 152 | +mkconfig() { # mkconfig <path> <login> | |
| 153 | + { | |
| 154 | + printf '{\n "copilotTokens": {\n "https://github.com:%s": "gho_SECRETGITHUBTOKENMUSTNOTLEAK0000"\n },\n' "$2" | |
| 155 | + printf ' "lastLoggedInUser": {\n "host": "https://github.com",\n "login": "%s"\n }\n}\n' "$2" | |
| 156 | + } > "$1" | |
| 157 | +} | |
| 158 | + | |
| 159 | +# ---------------------------------------------------------------- auth gate | |
| 160 | +section "node auth gate" | |
| 161 | +RAW=$(apiraw "action=status") | |
| 162 | +check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW" | |
| 163 | +check "401 body is JSON" '"error":"invalid node password"' "$RAW" | |
| 164 | +check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")" | |
| 165 | +check "X-Bot-Password header auth works" '"ok":true' \ | |
| 166 | + "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")" | |
| 167 | +check "Bearer auth works" '"ok":true' \ | |
| 168 | + "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")" | |
| 169 | +check "wrong password still 401s" "Status: 401 Unauthorized" \ | |
| 170 | + "$(QUERY_STRING="action=status&pwd=nope" $BIN)" | |
| 171 | +UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN) | |
| 172 | +check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")" | |
| 173 | + | |
| 174 | +# ---------------------------------------------------------------- status: empty | |
| 175 | +section "status with no credentials" | |
| 176 | +OUT=$(api "action=status&$PWDQ") | |
| 177 | +json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True' | |
| 178 | +json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False' | |
| 179 | +json_ok "empty node is not expired" "$OUT" 'd["expired"] is False' | |
| 180 | +json_ok "empty node carries a zero countdown" "$OUT" 'd["expires_in_sec"]==0' | |
| 181 | +json_ok "empty node reports a null user" "$OUT" 'd["user"]==""' | |
| 182 | +json_ok "copilot has no refresh token" "$OUT" 'd["has_refresh"] is False' | |
| 183 | +check "empty node reports the credentials path" '"credentials_path"' "$OUT" | |
| 184 | +check "empty node reports the device flow" '"flow":"device_code"' "$OUT" | |
| 185 | +check "empty node reports the protocol marker" 'SXLOGIN-MACHINE-V1' "$OUT" | |
| 186 | +check_not "empty node leaks no token" 'SECRETGITHUBTOKEN' "$OUT" | |
| 187 | +OUTF=$(api "format=json&$PWDQ") | |
| 188 | +json_ok "format=json alone means status" "$OUTF" 'd["ok"] is True' | |
| 189 | + | |
| 190 | +# ---------------------------------------------------------------- status: live | |
| 191 | +section "status with a live session" | |
| 192 | +mkcreds "$FIX/.credentials.json" | |
| 193 | +mkconfig "$FIX/config.json" "octocat" | |
| 194 | +mkcache "$FIX/.copilot-token-cache.json" "$FUTURE" | |
| 195 | +printf 'PROVIDER=copilot\nCOPILOT_TOKEN_SOURCE=local\nMODEL=claude-sonnet-5\n' > "$FIX/env/copilot.txt" | |
| 196 | +OUT=$(api "action=status&$PWDQ") | |
| 197 | +json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True' | |
| 198 | +json_ok "live session is not expired" "$OUT" 'd["expired"] is False' | |
| 199 | +json_ok "live session countdown is positive and near 30 min" "$OUT" '1700 < d["expires_in_sec"] <= 1800' | |
| 200 | +json_ok "the token cache is detected" "$OUT" 'd["cache_present"] is True' | |
| 201 | +json_ok "the GitHub login comes from config.json" "$OUT" 'd["user"]=="octocat"' | |
| 202 | +json_ok "the scope comes from the credentials file" "$OUT" 'd["scope"]=="read:user"' | |
| 203 | +json_ok "the profile model is parsed" "$OUT" 'd["profile"]=="claude-sonnet-5"' | |
| 204 | +json_ok "the profile file is detected" "$OUT" 'd["profile_exists"] is True' | |
| 205 | +check_not "status never returns a github token" 'SECRETGITHUBTOKEN' "$OUT" | |
| 206 | +check_not "status never returns a derived JWT" 'SECRET-JWT' "$OUT" | |
| 207 | +check_not "status never returns the key name github_token" 'github_token' "$OUT" | |
| 208 | + | |
| 209 | +# ---------------------------------------------------------------- status: expired | |
| 210 | +section "status with an expired derived token" | |
| 211 | +mkcache "$FIX/.copilot-token-cache.json" "$PAST" | |
| 212 | +OUT=$(api "action=status&$PWDQ") | |
| 213 | +json_ok "an expired derived token is still logged in" "$OUT" 'd["logged_in"] is True' | |
| 214 | +json_ok "an expired derived token is flagged expired" "$OUT" 'd["expired"] is True' | |
| 215 | +json_ok "an expired derived token has a negative countdown" "$OUT" 'd["expires_in_sec"]<0' | |
| 216 | + | |
| 217 | +# ---------------------------------------------------------------- named accounts | |
| 218 | +section "named accounts" | |
| 219 | +mkcreds "$FIX/acc/work.json" | |
| 220 | +mkcreds "$FIX/acc/personal.json" | |
| 221 | +mkcache "$FIX/.copilot-token-cache.json" "$FUTURE" | |
| 222 | +OUT=$(api "action=status&$PWDQ") | |
| 223 | +json_ok "both account files are listed" "$OUT" 'len(d["accounts"])==2' | |
| 224 | +json_ok "named_accounts is true with more than one" "$OUT" 'd["named_accounts"] is True' | |
| 225 | +json_ok "each account reports logged_in" "$OUT" 'all(a["logged_in"] for a in d["accounts"])' | |
| 226 | +OUT=$(api "action=accounts&$PWDQ") | |
| 227 | +json_ok "action=accounts answers ok" "$OUT" 'd["ok"] is True' | |
| 228 | +json_ok "action=accounts counts the files" "$OUT" 'd["count"]==2' | |
| 229 | +check_not "accounts never returns a token" 'SECRETGITHUBTOKEN' "$OUT" | |
| 230 | +OUT=$(api "action=status&name=work&$PWDQ") | |
| 231 | +json_ok "a named account is read from its own file" "$OUT" 'd["account"]=="work"' | |
| 232 | +check "a named account path ends in its file" 'acc/work.json' "$OUT" | |
| 233 | +BADNAME=$(apiraw "action=status&name=../escape&pwd=testpw" | tr -d '\r') | |
| 234 | +check "a path-traversal account name is refused" '"error":"bad_name"' "$BADNAME" | |
| 235 | + | |
| 236 | +# ---------------------------------------------------------------- start | |
| 237 | +section "action=start" | |
| 238 | +rm -f "$FIX/pend"/*.json "$FIX/mock"/* | |
| 239 | +OUT=$(api "action=start&$PWDQ") | |
| 240 | +json_ok "start returns ok" "$OUT" 'd["ok"] is True' | |
| 241 | +json_ok "start returns a device_code flow" "$OUT" 'd["flow"]=="device_code"' | |
| 242 | +json_ok "start returns the GitHub verify URL" "$OUT" 'd["verify_url"]=="https://github.com/login/device"' | |
| 243 | +json_ok "start returns the 8-character user code" "$OUT" 'd["user_code"]=="1234-5678"' | |
| 244 | +json_ok "start reports the poll interval" "$OUT" 'd["interval"]==5' | |
| 245 | +json_ok "start reports its TTL" "$OUT" 'd["expires_in"]>0' | |
| 246 | +check "start writes the pending file" "" "$(ls "$FIX/pend" | head -1)" | |
| 247 | +OUT=$(api "action=status&$PWDQ") | |
| 248 | +json_ok "status sees the pending flow" "$OUT" 'd["pending"] is True' | |
| 249 | +check_not "start never returns a token" 'SECRET' "$OUT" | |
| 250 | + | |
| 251 | +# ---------------------------------------------------------------- poll | |
| 252 | +section "action=poll" | |
| 253 | +OUT=$(api "action=poll&$PWDQ") | |
| 254 | +json_ok "poll answers ok while waiting" "$OUT" 'd["ok"] is True' | |
| 255 | +json_ok "poll reports the pending state" "$OUT" 'd["state"]=="pending"' | |
| 256 | +json_ok "poll repeats the interval" "$OUT" 'd["interval"]==5' | |
| 257 | + | |
| 258 | +: > "$FIX/mock/poll_done" | |
| 259 | +rm -f "$FIX/.credentials.json" | |
| 260 | +OUT=$(api "action=poll&$PWDQ") | |
| 261 | +json_ok "poll reports done after authorization" "$OUT" 'd["ok"] is True and d["state"]=="done"' | |
| 262 | +json_ok "poll re-reads state and reports logged in" "$OUT" 'd["logged_in"] is True' | |
| 263 | +check_not "poll never echoes the token" 'SECRETGITHUBTOKEN' "$OUT" | |
| 264 | + | |
| 265 | +: > "$FIX/mock/poll_denied" | |
| 266 | +api "action=start&$PWDQ" >/dev/null | |
| 267 | +OUT=$(api "action=poll&$PWDQ") | |
| 268 | +check "a denied authorization surfaces the CLI error" '"error":"denied"' "$OUT" | |
| 269 | +OUT=$(api "action=poll&$PWDQ") | |
| 270 | +check "poll without a pending flow is reported" '"error":"no_pending"' "$OUT" | |
| 271 | + | |
| 272 | +# ---------------------------------------------------------------- cancel | |
| 273 | +section "action=cancel" | |
| 274 | +api "action=start&$PWDQ" >/dev/null | |
| 275 | +OUT=$(api "action=cancel&$PWDQ") | |
| 276 | +json_ok "cancel answers ok" "$OUT" 'd["ok"] is True' | |
| 277 | +json_ok "cancel reports pending false" "$OUT" 'd["pending"] is False' | |
| 278 | +OUT=$(api "action=status&$PWDQ") | |
| 279 | +json_ok "status after cancel shows no pending flow" "$OUT" 'd["pending"] is False' | |
| 280 | + | |
| 281 | +# ---------------------------------------------------------------- refresh | |
| 282 | +section "action=refresh" | |
| 283 | +rm -f "$FIX/.copilot-token-cache.json" | |
| 284 | +mkcreds "$FIX/.credentials.json" | |
| 285 | +OUT=$(api "action=refresh&$PWDQ") | |
| 286 | +json_ok "refresh answers ok" "$OUT" 'd["ok"] is True' | |
| 287 | +json_ok "refresh reports refreshed:true" "$OUT" 'd["refreshed"] is True' | |
| 288 | +json_ok "refresh produced a fresh cache entry" "$OUT" 'd["cache_present"] is True' | |
| 289 | +json_ok "refresh moved the expiry forward" "$OUT" '1700 < d["expires_in_sec"] <= 1800' | |
| 290 | +check_not "refresh never forwards the CLI payload" 'MUST-NOT-LEAK' "$OUT" | |
| 291 | +check_not "refresh never returns an access_token key" 'access_token' "$OUT" | |
| 292 | + | |
| 293 | +OUT=$(COPILOT_MOCK_FAIL=1 api "action=refresh&$PWDQ") | |
| 294 | +check "a failed refresh is reported as refresh_failed" '"error":"refresh_failed"' "$OUT" | |
| 295 | + | |
| 296 | +rm -f "$FIX/.credentials.json" "$FIX/.copilot-token-cache.json" | |
| 297 | +OUT=$(api "action=refresh&$PWDQ") | |
| 298 | +check "refresh with no credentials is refused" '"error":"no_credentials"' "$OUT" | |
| 299 | + | |
| 300 | +# ---------------------------------------------------------------- CLI absent | |
| 301 | +section "CLI unavailable" | |
| 302 | +OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=start&$PWDQ") | |
| 303 | +check "a missing login CLI is reported as cli_unavailable" 'cli_unavailable' "$OUT" | |
| 304 | +check "the cli_unavailable detail explains the fix" 'COPILOT_LOGIN_BIN' "$OUT" | |
| 305 | +OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=poll&$PWDQ") | |
| 306 | +check "poll without a login CLI is cli_unavailable" 'cli_unavailable' "$OUT" | |
| 307 | +mkcreds "$FIX/.credentials.json" | |
| 308 | +OUT=$(COPILOT_REFRESH_BIN=/nonexistent/refresh api "action=refresh&$PWDQ") | |
| 309 | +check "refresh without a refresh CLI is cli_unavailable" 'cli_unavailable' "$OUT" | |
| 310 | +OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=status&$PWDQ") | |
| 311 | +json_ok "status without a login CLI still answers from the files" "$OUT" 'd["ok"] is True' | |
| 312 | +json_ok "status reports the CLI as absent" "$OUT" 'd["cli_present"] is False' | |
| 313 | + | |
| 314 | +# ---------------------------------------------------------------- routing | |
| 315 | +section "routing" | |
| 316 | +OUT=$(apiraw "action=bogus&$PWDQ" | tr -d '\r') | |
| 317 | +check "an unknown action is a 404" "Status: 404 Not Found" "$OUT" | |
| 318 | +check "an unknown action names itself" '"error":"unknown_action"' "$OUT" | |
| 319 | + | |
| 320 | +# ---------------------------------------------------------------- HTML page | |
| 321 | +section "HTML page" | |
| 322 | +PAGE=$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r') | |
| 323 | +check "page is HTML" "Content-Type: text/html" "$PAGE" | |
| 324 | +check "page carries the bot theme handoff" "sx-theme" "$PAGE" | |
| 325 | +check "page asks the host for the theme once" "sx-theme-request" "$PAGE" | |
| 326 | +check "page carries the bot token block" "--bg-card" "$PAGE" | |
| 327 | +check "page has a viewport meta" 'name="viewport"' "$PAGE" | |
| 328 | +check "page has a colour-scheme declaration" "color-scheme:dark" "$PAGE" | |
| 329 | +check "page uses the responsive breakpoint" "@media (max-width:520px)" "$PAGE" | |
| 330 | +check "page names the plugin route" "/plugin_copilot_login" "$PAGE" | |
| 331 | +check "page links the GitHub device URL" "https://github.com/login/device" "$PAGE" | |
| 332 | +check "page has a live polling indicator" "Waiting for GitHub confirmation" "$PAGE" | |
| 333 | +check "page has the copy-and-open action" "Copy Code" "$PAGE" | |
| 334 | +check_empty "page emits no Content-Length" "$(printf '%s' "$PAGE" | grep -i '^Content-Length' || true)" | |
| 335 | +check_not "page loads no CDN script" "<script src=" "$PAGE" | |
| 336 | +check_not "page references no external host" "cdnjs" "$PAGE" | |
| 337 | +check_not "page has no http:// asset" "http://" "$PAGE" | |
| 338 | +check "page CSP forbids remote scripts" "default-src 'none'" "$PAGE" | |
| 339 | +check "page is frameable by the bot" "frame-ancestors *" "$PAGE" | |
| 340 | + | |
| 341 | +# ---------------------------------------------------------------- source hygiene | |
| 342 | +section "source hygiene" | |
| 343 | +SRC=src/$ID.c | |
| 344 | +check_empty "no emoji in the source" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$SRC" || true)" | |
| 345 | +check_empty "no emoji in the page" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' src/ui.html || true)" | |
| 346 | +check_empty "the source never writes Content-Length" "$(grep -n 'Content-Length' "$SRC" || true)" | |
| 347 | +check_empty "no private 192.168 address" "$(grep -nE '192\.168\.' "$SRC" src/ui.html tests/*.sh README.md plugin.json 2>/dev/null || true)" | |
| 348 | +check_empty "no 10.x private address" "$(grep -nE '(^|[^0-9])10\.[0-9]+\.[0-9]+\.[0-9]+' "$SRC" src/ui.html tests/*.sh README.md 2>/dev/null || true)" | |
| 349 | +check_empty "no credential literal" "$(grep -nE 'ghp_[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{20,}' "$SRC" tests/*.sh README.md 2>/dev/null || true)" | |
| 350 | +# The detector literals are assembled from fragments so this scanner's own | |
| 351 | +# source line never trips a history secret scan. | |
| 352 | +HOSTS="macmin""i|intel-ultra""2|lazar""us" | |
| 353 | +check_empty "no fleet host name" "$(grep -nE "$HOSTS" "$SRC" README.md 2>/dev/null || true)" | |
| 354 | +check_empty "no OAuth client secret is shipped" "$(grep -nE '20[0-9]{2}[A-Za-z0-9]{10,}' "$SRC" || true)" | |
| 355 | +found "the github_token value is never read into a response" 'json_str_field(json, json + strlen(json), "scope"' "$SRC" | |
| 356 | +found "argv is shell-quoted before popen" "shell_quote_into" "$SRC" | |
| 357 | +found "the refresh action discards the CLI payload" "buf_free(&out);" "$SRC" | |
| 358 | +found "the plugin reports refreshed:true on a refresh" 'refreshed\":true' "$SRC" | |
| 359 | +found "the device code is relayed verbatim" 'json_str_field(j, end, "user_code"' "$SRC" | |
| 360 | +check_empty "the shipped page carries no token literal" \ | |
| 361 | + "$(grep -l 'MUST-NOT-LEAK' src/ui.html src/$ID.c 2>/dev/null || true)" | |
| 362 | + | |
| 363 | +# ---------------------------------------------------------------- summary | |
| 364 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 365 | +printf ' %d passed, %d failed\n' "$PASS" "$FAIL" | |
| 366 | +[ "$FAIL" -eq 0 ] || exit 1 | |
| 367 | +exit 0 |
| 1 | 1 | new file mode 100644 |
| index 0000000..28ad406 | ||
| --- /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_CPLOGIN_UI_HTML_H\n" | |
| 75 | + "#define SX_CPLOGIN_UI_HTML_H\n" | |
| 76 | + "\n" | |
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | |
| 78 | + "\n" | |
| 79 | + "#endif /* SX_CPLOGIN_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()) | |
| 0 | 106 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..35bc3e3 | index 0000000..35bc3e3 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | ||
| 2 | +/plugin_copilot_login | ||
| 3 | +/plugin_copilot_login.exe | ||
| 4 | +/plugin_copilot_login.musl | ||
| 5 | +/plugin_copilot_login.arm64 | ||
| 6 | +/plugin_copilot_login.macos-arm64 | ||
| 7 | +/plugin_copilot_login.macos-x86_64 | ||
| 8 | +bin/ | ||
| 9 | + | ||
| 10 | +# test scratch | ||
| 11 | +*.tmp | ||
| 12 | +/tests/fixtures-out/ | ||
| 13 | + | ||
| 14 | +# python tooling | ||
| 15 | +__pycache__/ | ||
| 16 | +*.pyc |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ef80120 | index 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. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..474763a | index 0000000..474763a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,77 @@ | @@ -0,0 +1,77 @@ | ||
| 1 | +# plugin_copilot_login - SCORPIOX BOT open-source GitHub Copilot device-code login for your node | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_copilot_login | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_copilot_login.musl | ||
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_copilot_login.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_copilot_login.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_copilot_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 install copy the binary into this node's plugin directory | ||
| 12 | +# make clean | ||
| 13 | + | ||
| 14 | +CC ?= cc | ||
| 15 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src | ||
| 16 | +MUSL_CC ?= musl-gcc | ||
| 17 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | ||
| 18 | +ARM_CC ?= aarch64-linux-gnu-gcc | ||
| 19 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | ||
| 20 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 21 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | ||
| 22 | +SRC := src/plugin_copilot_login.c | ||
| 23 | +UI_SRC := src/ui.html | ||
| 24 | +UI_HDR := src/ui_html.h | ||
| 25 | +BIN := plugin_copilot_login | ||
| 26 | +EXE := plugin_copilot_login.exe | ||
| 27 | + | ||
| 28 | +.PHONY: all native musl arm64 win64 macos ui test install 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 -Wno-format-truncation -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 | +clean: | ||
| 73 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 | ||
| 74 | + rm -rf tests/__pycache__ | ||
| 75 | + | ||
| 76 | +help: | ||
| 77 | + @sed -n '2,15p' $(MAKEFILE_LIST) |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..1ada108 | index 0000000..1ada108 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,186 @@ | @@ -0,0 +1,186 @@ | ||
| 1 | +# plugin_copilot_login | ||
| 2 | + | ||
| 3 | +An open-source **SCORPIOX BOT** plugin for **GitHub Copilot** device-code login | ||
| 4 | +and token management on your own node. | ||
| 5 | + | ||
| 6 | +It is a single zero-dependency C99 binary that runs as a node plugin: it starts | ||
| 7 | +the GitHub OAuth device flow, shows the one-time code on a page you can open | ||
| 8 | +from anywhere, polls GitHub until you approve the code on any device, then | ||
| 9 | +reports your session state and the expiry of the derived Copilot token - and | ||
| 10 | +refreshes that token on demand. | ||
| 11 | + | ||
| 12 | +``` | ||
| 13 | + node github.com | ||
| 14 | + ---- ---------- | ||
| 15 | + plugin_copilot_login --start--> scorpiox-copilot-login | ||
| 16 | + POST /login/device/code | ||
| 17 | + <-- user_code 1234-5678, device_code | ||
| 18 | + page shows the code | | ||
| 19 | + you type it on any device -----------> approve | ||
| 20 | + plugin_copilot_login --poll--> scorpiox-copilot-login | ||
| 21 | + POST /login/oauth/access_token | ||
| 22 | + <-- access_token gho_... | ||
| 23 | + writes ~/.copilot/.credentials.json | ||
| 24 | +``` | ||
| 25 | + | ||
| 26 | +## Why it never holds a secret | ||
| 27 | + | ||
| 28 | +GitHub's device flow still carries an OAuth **client id**, and a token exchange | ||
| 29 | +is an HTTPS POST. A public repository must never ship either a client secret or | ||
| 30 | +TLS client code that pretends to be one. So this plugin does not speak TLS at | ||
| 31 | +all: it drives the `scorpiox-copilot-login` CLI that ships with SCORPIOX CODE, | ||
| 32 | +in its documented machine mode (`SXLOGIN-MACHINE-V1`, one JSON line per call), | ||
| 33 | +and reads only the files that CLI writes. | ||
| 34 | + | ||
| 35 | +What that buys you: | ||
| 36 | + | ||
| 37 | +* **No token ever reaches a response.** Every JSON field is token *presence* and | ||
| 38 | + *expiry*. The refresh action inspects the CLI's payload for the `access_token` | ||
| 39 | + key and throws the payload away; the new state is proven by re-reading the | ||
| 40 | + cache file, never by the CLI's word. | ||
| 41 | +* **Nothing is trusted from the browser.** The user code is relayed verbatim, | ||
| 42 | + the account name is validated against a shell- and path-safe alphabet, and the | ||
| 43 | + CLI path comes from an environment variable the node owner sets, never from a | ||
| 44 | + query string. | ||
| 45 | +* **The page is self-contained.** No CDN, no external asset, a CSP that forbids | ||
| 46 | + remote scripts, and no `Content-Length` header (the fronting proxy rejects it). | ||
| 47 | + | ||
| 48 | +## Install | ||
| 49 | + | ||
| 50 | +### 1-click, pre-compiled | ||
| 51 | + | ||
| 52 | +Browse **https://botmarket.scorpiox.net** and install *GitHub Copilot Login*, or | ||
| 53 | +fetch a pre-built binary directly: | ||
| 54 | + | ||
| 55 | +```sh | ||
| 56 | +# universal static Linux (Alpine, Debian, Ubuntu, Arch, Omarchy) | ||
| 57 | +curl -fsSL https://dist.scorpiox.net/bot-plugins/copilot-login/latest.json | ||
| 58 | + | ||
| 59 | +mkdir -p ~/.scorpiox/plugins | ||
| 60 | +curl -fsSL -o ~/.scorpiox/plugins/plugin_copilot_login \ | ||
| 61 | + https://dist.scorpiox.net/bot-plugins/copilot-login/1.0.0/linux-x86_64-musl/plugin_copilot_login | ||
| 62 | +chmod 0755 ~/.scorpiox/plugins/plugin_copilot_login | ||
| 63 | +``` | ||
| 64 | + | ||
| 65 | +The bot picks the plugin up on its next scan; no server restart. | ||
| 66 | + | ||
| 67 | +### Compile from source | ||
| 68 | + | ||
| 69 | +```sh | ||
| 70 | +git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-copilot-login.git | ||
| 71 | +cd scorpiox-bot-plugin-copilot-login | ||
| 72 | + | ||
| 73 | +make # native Linux/macOS | ||
| 74 | +make musl # static x86_64, the universal Linux artifact | ||
| 75 | +make arm64 # static aarch64 (Raspberry Pi 5, ARM servers) | ||
| 76 | +make win64 # static Win64 PE (MinGW-w64) | ||
| 77 | +make install # copy into ~/.scorpiox/plugins | ||
| 78 | +``` | ||
| 79 | + | ||
| 80 | +On Windows, from PowerShell: | ||
| 81 | + | ||
| 82 | +```powershell | ||
| 83 | +powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 84 | +``` | ||
| 85 | + | ||
| 86 | +The binary has no runtime dependencies. `make test` runs the offline suite. | ||
| 87 | + | ||
| 88 | +## Modes | ||
| 89 | + | ||
| 90 | +### 1. Discovery | ||
| 91 | + | ||
| 92 | +```sh | ||
| 93 | +./plugin_copilot_login --meta | ||
| 94 | +{"name":"copilot","desc":"Copilot login"} | ||
| 95 | +``` | ||
| 96 | + | ||
| 97 | +Reachable without a password and without touching any credential file. The bot | ||
| 98 | +uses it to list the plugin. | ||
| 99 | + | ||
| 100 | +### 2. JSON API | ||
| 101 | + | ||
| 102 | +All callbacks are `?action=...` and answer with one JSON object. `format=json` | ||
| 103 | +alone means `status`, and `?name=<account>` targets a named account. | ||
| 104 | + | ||
| 105 | +| Action | What it does | | ||
| 106 | +|--------|--------------| | ||
| 107 | +| `status` | Reads the credentials file, `config.json`, the token cache and the account directory; also asks the CLI. Answers `logged_in`, `user`, `account`, `pending`, `expired`, `expires_in_sec`, `scope`, `accounts`. | | ||
| 108 | +| `start` | Starts the device flow. Answers `flow`, `verify_url`, `user_code`, `interval`, `expires_in`. | | ||
| 109 | +| `poll` | One non-blocking poll. Answers `state:"pending"`, or `state:"done"` with the fresh status once you approve on GitHub. | | ||
| 110 | +| `cancel` | Drops the pending flow. | | ||
| 111 | +| `refresh` | Derives a fresh Copilot token through the CLI and re-reads the cache. Answers `refreshed:true` plus the new status. | | ||
| 112 | +| `accounts` | Lists the named account files and which one is active. | | ||
| 113 | + | ||
| 114 | +```sh | ||
| 115 | +curl -s -H "X-Bot-Password: $BOT_PASSWORD" \ | ||
| 116 | + 'http://127.0.0.1:8150/plugin_copilot_login?action=status' | ||
| 117 | +``` | ||
| 118 | + | ||
| 119 | +```json | ||
| 120 | +{"ok":true,"logged_in":true,"user":"octocat","account":"default", | ||
| 121 | + "pending":false,"expires_in_sec":1740,"expired":false,"cache_present":true, | ||
| 122 | + "cli_present":true,"scope":"read:user","profile":"claude-sonnet-5", | ||
| 123 | + "accounts":[{"name":"work","logged_in":true,"expires_in_sec":1740,"expired":false}], | ||
| 124 | + "flow":"device_code","protocol":"SXLOGIN-MACHINE-V1"} | ||
| 125 | +``` | ||
| 126 | + | ||
| 127 | +### 3. HTML page | ||
| 128 | + | ||
| 129 | +`GET` (or `?embed=1`) returns the responsive page: a connection pill, a GitHub | ||
| 130 | +user badge, the device-flow card with a large user code and a | ||
| 131 | +**Copy Code & Open GitHub** button, a live polling indicator that re-checks | ||
| 132 | +`action=poll` every `interval` seconds, a named-account switcher, and a refresh | ||
| 133 | +button. It follows the bot's theme through the standard handoff, works down to | ||
| 134 | +390 px and inside the Chat floating window. | ||
| 135 | + | ||
| 136 | +## Files it reads | ||
| 137 | + | ||
| 138 | +| Path | Purpose | | ||
| 139 | +|------|---------| | ||
| 140 | +| `~/.copilot/.credentials.json` | `github_token` (`gho_...`), `scope`, `timestamp` | | ||
| 141 | +| `~/.copilot/config.json` | `lastLoggedInUser.login` - the only place the GitHub user name lives | | ||
| 142 | +| `~/.copilot/.copilot-token-cache.json` | derived Copilot token and its `expires_at` | | ||
| 143 | +| `~/.copilot/accounts/<name>.json` | named accounts, same shape as the credentials file | | ||
| 144 | +| `~/.claude/.login-pending/copilot-<name>.json` | the pending device flow, written by the CLI | | ||
| 145 | +| `~/.claude/scorpiox-env/copilot.txt` | the `PROVIDER=copilot` profile written by `--create-profile` | | ||
| 146 | + | ||
| 147 | +Every one of these is overridable for deterministic offline testing: | ||
| 148 | + | ||
| 149 | +``` | ||
| 150 | +COPILOT_CREDS_PATH COPILOT_ACCOUNTS_DIR COPILOT_PENDING_DIR | ||
| 151 | +COPILOT_ENV_DIR COPILOT_LOGIN_BIN COPILOT_REFRESH_BIN | ||
| 152 | +``` | ||
| 153 | + | ||
| 154 | +## Tests | ||
| 155 | + | ||
| 156 | +`tests/run.sh` is fully offline: it points both CLIs at `tests/mock_login.sh` | ||
| 157 | +and `tests/mock_refresh.sh`, keeps every credential path inside a throwaway | ||
| 158 | +directory, and proves 116 assertions - the metadata contract, the 401 gate, all | ||
| 159 | +six actions including the pending/done/denied poll states, the named-account | ||
| 160 | +scan, the refresh-failure path, the HTML page contract and a source audit for | ||
| 161 | +secrets, LAN addresses, `Content-Length` and emoji. | ||
| 162 | + | ||
| 163 | +```sh | ||
| 164 | +make test | ||
| 165 | +``` | ||
| 166 | + | ||
| 167 | +## Security model | ||
| 168 | + | ||
| 169 | +Read this before installing anything that runs as a plugin. | ||
| 170 | + | ||
| 171 | +* The plugin executes **native code** with the node user's full OS permissions. | ||
| 172 | +* It spawns two child processes (`scorpiox-copilot-login`, | ||
| 173 | + `scorpiox-copilot-refreshtoken`). Those children talk to GitHub over TLS; this | ||
| 174 | + plugin does not open a socket of its own. | ||
| 175 | +* It **never** prints, logs or returns a token. A missing `gho_` token is | ||
| 176 | + reported as `logged_in:false`, not as an empty field you could mistake for a | ||
| 177 | + live session. | ||
| 178 | +* It performs no destructive action. The only write paths are the ones the CLI | ||
| 179 | + owns; `cancel` removes a pending marker file and nothing else. | ||
| 180 | + | ||
| 181 | +## License | ||
| 182 | + | ||
| 183 | +MIT. Copyright (c) 2026 SCORPIOX INC. | ||
| 184 | + | ||
| 185 | +Source: https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-copilot-login | ||
| 186 | +Registry: https://dist.scorpiox.net/bot-plugins/copilot-login/ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..b36a2fb | index 0000000..b36a2fb | ||
| --- /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_copilot_login | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_copilot_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_copilot_login.c" | ||
| 14 | + $Out = Join-Path $ScriptDir "plugin_copilot_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_copilot_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_copilot_login.exe --meta" | ||
| 49 | +} finally { | ||
| 50 | + Pop-Location | ||
| 51 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..030fa7d | index 0000000..030fa7d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,16 @@ | @@ -0,0 +1,16 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "copilot-login", | ||
| 3 | + "id": "plugin_copilot_login", | ||
| 4 | + "title": "GitHub Copilot Login", | ||
| 5 | + "summary": "Zero-dependency GitHub Copilot device-code login and token manager for your node. Starts the OAuth device flow at github.com/login/device, shows the one-time code, polls GitHub until you approve it on any device, then reports session state, the derived token expiry and the named account files - and refreshes the derived 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, config and token-cache 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-copilot-login and scorpiox-copilot-refreshtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to GitHub over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only ~/.copilot/.credentials.json, ~/.copilot/config.json, ~/.copilot/.copilot-token-cache.json, ~/.copilot/accounts/, the pending device-flow marker and the copilot profile file, 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-copilot-login" | ||
| 16 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..5380b2c | index 0000000..5380b2c | ||
| --- /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_copilot_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="copilot-login" | ||
| 33 | +ID="plugin_copilot_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 -Wno-format-truncation -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 -Wno-format-truncation -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 -Wno-format-truncation -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 -Wno-format-truncation \ | ||
| 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 -Wno-format-truncation -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": "copilot",\n' | ||
| 225 | + printf ' "desc": "Copilot login",\n' | ||
| 226 | + printf ' "title": "GitHub Copilot Login",\n' | ||
| 227 | + printf ' "summary": "Zero-dependency GitHub Copilot device-code login and token manager for your node. Starts the OAuth device flow at github.com/login/device, shows the one-time code, polls GitHub until you approve it on any device, then reports session state, the derived token expiry and the named account files - and refreshes the derived 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, config and token-cache 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-copilot-login and scorpiox-copilot-refreshtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to GitHub over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only the Copilot credential file, the config file, the derived-token cache, the named account files and the login-pending marker, 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" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0dd243b | index 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 */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..8c68ea2 | index 0000000..8c68ea2 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_copilot_login.c | +++ b/src/plugin_copilot_login.c | ||
| @@ -0,0 +1,1587 @@ | @@ -0,0 +1,1587 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_copilot_login - SCORPIOX BOT open-source GitHub Copilot device-code | ||
| 3 | + * login and token manager for your node. | ||
| 4 | + * | ||
| 5 | + * A single clean-room C99 binary that serves THREE modes: | ||
| 6 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | ||
| 7 | + * 2. ?action=... / ?format=json -> JSON node API | ||
| 8 | + * 3. GET (default) -> responsive HTML UI | ||
| 9 | + * | ||
| 10 | + * DESIGN NOTE (why there is no TLS and no OAuth client secret here): the | ||
| 11 | + * GitHub Copilot device flow is an HTTPS POST that carries an OAuth client | ||
| 12 | + * identity. A public clean-room repository must never carry such a secret, so | ||
| 13 | + * this plugin does not speak TLS at all. It drives the node's own SCORPIOX CODE | ||
| 14 | + * login CLI, exactly the way the machine-mode contract intends | ||
| 15 | + * (--status / --start / --poll / --cancel, one JSON line per call), and it | ||
| 16 | + * reads only the credential files that CLI writes: | ||
| 17 | + * | ||
| 18 | + * ~/.copilot/.credentials.json (github_token, scope, timestamp) | ||
| 19 | + * ~/.copilot/config.json (lastLoggedInUser.login) | ||
| 20 | + * ~/.copilot/.copilot-token-cache.json (copilot JWT + expiry) | ||
| 21 | + * ~/.copilot/accounts/<name>.json (named accounts) | ||
| 22 | + * ~/.claude/.login-pending/copilot-*.json (pending device flow) | ||
| 23 | + * ~/.claude/scorpiox-env/copilot.txt (PROVIDER/MODEL profile) | ||
| 24 | + * | ||
| 25 | + * Every path and both binaries are overridable for deterministic offline tests: | ||
| 26 | + * | ||
| 27 | + * COPILOT_CREDS_PATH credentials file (also anchors the sibling paths) | ||
| 28 | + * COPILOT_ACCOUNTS_DIR directory holding <name>.json account files | ||
| 29 | + * COPILOT_PENDING_DIR directory holding the pending flow files | ||
| 30 | + * COPILOT_ENV_DIR profile directory (copilot.txt) | ||
| 31 | + * COPILOT_LOGIN_BIN login CLI (default scorpiox-copilot-login) | ||
| 32 | + * COPILOT_REFRESH_BIN refresh CLI (default scorpiox-copilot-refreshtoken) | ||
| 33 | + * | ||
| 34 | + * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. Every response reports token | ||
| 35 | + * presence and expiry only. The refresh action discards the payload its CLI | ||
| 36 | + * prints and reports only success/failure plus the new expiry. | ||
| 37 | + * | ||
| 38 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 39 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 40 | + * scorpiox-server on the node. | ||
| 41 | + * | ||
| 42 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 43 | + */ | ||
| 44 | + | ||
| 45 | +/* Must come before every include on Windows: MinGW defaults to 0x502 | ||
| 46 | + * (Server 2003), which hides the Win7+ APIs and the path helpers. */ | ||
| 47 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 48 | +# define _WIN32_WINNT 0x0601 | ||
| 49 | +#endif | ||
| 50 | + | ||
| 51 | +#if !defined(_WIN32) | ||
| 52 | +# define _POSIX_C_SOURCE 200809L | ||
| 53 | +# define _DEFAULT_SOURCE 1 | ||
| 54 | +# if defined(__APPLE__) | ||
| 55 | +# define _DARWIN_C_SOURCE 1 | ||
| 56 | +# endif | ||
| 57 | +#endif | ||
| 58 | + | ||
| 59 | +#include <stdio.h> | ||
| 60 | +#include <stdlib.h> | ||
| 61 | +#include <string.h> | ||
| 62 | +#include <ctype.h> | ||
| 63 | +#include <errno.h> | ||
| 64 | +#include <time.h> | ||
| 65 | +#include <stdarg.h> | ||
| 66 | + | ||
| 67 | +#if defined(_WIN32) | ||
| 68 | +# define WIN32_LEAN_AND_MEAN | ||
| 69 | +# include <windows.h> | ||
| 70 | +# include <direct.h> | ||
| 71 | +# include <io.h> | ||
| 72 | +#else | ||
| 73 | +# include <unistd.h> | ||
| 74 | +# include <sys/stat.h> | ||
| 75 | +# include <sys/types.h> | ||
| 76 | +# include <dirent.h> | ||
| 77 | +#endif | ||
| 78 | + | ||
| 79 | +#include "bot_theme_plugin.h" | ||
| 80 | +#include "ui_html.h" | ||
| 81 | + | ||
| 82 | +#define PLUGIN_SLUG "copilot-login" | ||
| 83 | +#define PLUGIN_ID "plugin_copilot_login" | ||
| 84 | +#define PLUGIN_VER "1.0.0" | ||
| 85 | +#define PLUGIN_NAME "copilot" | ||
| 86 | +#define PLUGIN_DESC "Copilot login" | ||
| 87 | + | ||
| 88 | +#define PATH_SZ 1024 | ||
| 89 | +#define NAME_SZ 96 | ||
| 90 | +#define CODE_MAX 512 | ||
| 91 | +#define CMD_SZ 4096 | ||
| 92 | +#define OUT_MAX (256 * 1024) | ||
| 93 | +#define FIELD_SZ 512 | ||
| 94 | +#define MAX_ACCOUNTS 64 | ||
| 95 | + | ||
| 96 | +#define DEFAULT_LOGIN_BIN "scorpiox-copilot-login" | ||
| 97 | +#define DEFAULT_REFRESH_BIN "scorpiox-copilot-refreshtoken" | ||
| 98 | + | ||
| 99 | +#define PENDING_TTL_SEC 900 | ||
| 100 | +#define DEFAULT_INTERVAL 5 | ||
| 101 | +#define DEFAULT_EXPIRES_IN 900 | ||
| 102 | + | ||
| 103 | +#if defined(_WIN32) | ||
| 104 | +# define PATH_SEP '\\' | ||
| 105 | +#else | ||
| 106 | +# define PATH_SEP '/' | ||
| 107 | +#endif | ||
| 108 | + | ||
| 109 | +/* ------------------------------------------------------------------ */ | ||
| 110 | +/* Growable byte buffer */ | ||
| 111 | +/* ------------------------------------------------------------------ */ | ||
| 112 | + | ||
| 113 | +typedef struct { | ||
| 114 | + char *p; | ||
| 115 | + size_t n; | ||
| 116 | + size_t cap; | ||
| 117 | +} buf_t; | ||
| 118 | + | ||
| 119 | +static void buf_init(buf_t *b) | ||
| 120 | +{ | ||
| 121 | + b->p = NULL; | ||
| 122 | + b->n = 0; | ||
| 123 | + b->cap = 0; | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +static int buf_need(buf_t *b, size_t extra) | ||
| 127 | +{ | ||
| 128 | + size_t want = b->n + extra + 1; | ||
| 129 | + char *np; | ||
| 130 | + | ||
| 131 | + if (want <= b->cap) return 1; | ||
| 132 | + if (b->cap == 0) b->cap = 1024; | ||
| 133 | + while (b->cap < want) { | ||
| 134 | + if (b->cap > (size_t)32 * 1024 * 1024) return 0; | ||
| 135 | + b->cap *= 2; | ||
| 136 | + } | ||
| 137 | + np = (char *)realloc(b->p, b->cap); | ||
| 138 | + if (!np) return 0; | ||
| 139 | + b->p = np; | ||
| 140 | + return 1; | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +static int buf_add(buf_t *b, const char *s, size_t n) | ||
| 144 | +{ | ||
| 145 | + if (!buf_need(b, n)) return 0; | ||
| 146 | + memcpy(b->p + b->n, s, n); | ||
| 147 | + b->n += n; | ||
| 148 | + b->p[b->n] = '\0'; | ||
| 149 | + return 1; | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +static int buf_adds(buf_t *b, const char *s) | ||
| 153 | +{ | ||
| 154 | + return s ? buf_add(b, s, strlen(s)) : 1; | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +static int buf_addc(buf_t *b, char c) | ||
| 158 | +{ | ||
| 159 | + return buf_add(b, &c, 1); | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +static const char *buf_str(buf_t *b) | ||
| 163 | +{ | ||
| 164 | + if (!b->p) return ""; | ||
| 165 | + return b->p; | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +static void buf_free(buf_t *b) | ||
| 169 | +{ | ||
| 170 | + free(b->p); | ||
| 171 | + b->p = NULL; | ||
| 172 | + b->n = 0; | ||
| 173 | + b->cap = 0; | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +static int buf_addf(buf_t *b, const char *fmt, ...) | ||
| 177 | +{ | ||
| 178 | + char tmp[2048]; | ||
| 179 | + int n; | ||
| 180 | + va_list ap; | ||
| 181 | + | ||
| 182 | + va_start(ap, fmt); | ||
| 183 | + n = vsnprintf(tmp, sizeof(tmp), fmt, ap); | ||
| 184 | + va_end(ap); | ||
| 185 | + if (n < 0) return 0; | ||
| 186 | + if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n); | ||
| 187 | + | ||
| 188 | + { | ||
| 189 | + char *big = (char *)malloc((size_t)n + 1); | ||
| 190 | + int ok; | ||
| 191 | + if (!big) return 0; | ||
| 192 | + va_start(ap, fmt); | ||
| 193 | + vsnprintf(big, (size_t)n + 1, fmt, ap); | ||
| 194 | + va_end(ap); | ||
| 195 | + ok = buf_add(b, big, (size_t)n); | ||
| 196 | + free(big); | ||
| 197 | + return ok; | ||
| 198 | + } | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/* JSON string escape into a buffer (never emits a bare control byte). */ | ||
| 202 | +static int buf_json(buf_t *b, const char *s) | ||
| 203 | +{ | ||
| 204 | + const unsigned char *p = (const unsigned char *)(s ? s : ""); | ||
| 205 | + if (!buf_addc(b, '"')) return 0; | ||
| 206 | + for (; *p; p++) { | ||
| 207 | + switch (*p) { | ||
| 208 | + case '"': if (!buf_adds(b, "\\\"")) return 0; break; | ||
| 209 | + case '\\': if (!buf_adds(b, "\\\\")) return 0; break; | ||
| 210 | + case '\n': if (!buf_adds(b, "\\n")) return 0; break; | ||
| 211 | + case '\r': if (!buf_adds(b, "\\r")) return 0; break; | ||
| 212 | + case '\t': if (!buf_adds(b, "\\t")) return 0; break; | ||
| 213 | + default: | ||
| 214 | + if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", *p)) return 0; } | ||
| 215 | + else if (!buf_addc(b, (char)*p)) return 0; | ||
| 216 | + } | ||
| 217 | + } | ||
| 218 | + return buf_addc(b, '"'); | ||
| 219 | +} | ||
| 220 | +/* ------------------------------------------------------------------ */ | ||
| 221 | +/* Query string */ | ||
| 222 | +/* ------------------------------------------------------------------ */ | ||
| 223 | + | ||
| 224 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 225 | +{ | ||
| 226 | + size_t klen; | ||
| 227 | + const char *p; | ||
| 228 | + | ||
| 229 | + if (!out || outsz == 0) return 0; | ||
| 230 | + out[0] = '\0'; | ||
| 231 | + if (!qs || !key) return 0; | ||
| 232 | + klen = strlen(key); | ||
| 233 | + p = qs; | ||
| 234 | + while (p && *p) { | ||
| 235 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 236 | + size_t i = 0; | ||
| 237 | + p += klen + 1; | ||
| 238 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | ||
| 239 | + out[i] = '\0'; | ||
| 240 | + return 1; | ||
| 241 | + } | ||
| 242 | + p = strchr(p, '&'); | ||
| 243 | + if (!p) break; | ||
| 244 | + p++; | ||
| 245 | + } | ||
| 246 | + return 0; | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +static int query_has(const char *qs, const char *key) | ||
| 250 | +{ | ||
| 251 | + size_t klen; | ||
| 252 | + const char *p; | ||
| 253 | + | ||
| 254 | + if (!qs || !key) return 0; | ||
| 255 | + klen = strlen(key); | ||
| 256 | + p = qs; | ||
| 257 | + while (p && *p) { | ||
| 258 | + if (strncmp(p, key, klen) == 0 && | ||
| 259 | + (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) | ||
| 260 | + return 1; | ||
| 261 | + p = strchr(p, '&'); | ||
| 262 | + if (!p) break; | ||
| 263 | + p++; | ||
| 264 | + } | ||
| 265 | + return 0; | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +/* ------------------------------------------------------------------ */ | ||
| 269 | +/* Node auth (X-Bot-Password / Bearer / ?pwd=) */ | ||
| 270 | +/* ------------------------------------------------------------------ */ | ||
| 271 | + | ||
| 272 | +static void require_node_auth(void) | ||
| 273 | +{ | ||
| 274 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 275 | + const char *xp; | ||
| 276 | + const char *auth; | ||
| 277 | + char qpwd[256] = {0}; | ||
| 278 | + | ||
| 279 | + if (!np || !*np) return; | ||
| 280 | + | ||
| 281 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 282 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 283 | + | ||
| 284 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 285 | + if (auth) { | ||
| 286 | + while (*auth == ' ') auth++; | ||
| 287 | + if (strncasecmp(auth, "Bearer ", 7) == 0) { | ||
| 288 | + auth += 7; | ||
| 289 | + while (*auth == ' ') auth++; | ||
| 290 | + if (strcmp(auth, np) == 0) return; | ||
| 291 | + } | ||
| 292 | + } | ||
| 293 | + | ||
| 294 | + if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && | ||
| 295 | + strcmp(qpwd, np) == 0) | ||
| 296 | + return; | ||
| 297 | + | ||
| 298 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 299 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 300 | + "Cache-Control: no-store\r\n\r\n" | ||
| 301 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 302 | + exit(0); | ||
| 303 | +} | ||
| 304 | + | ||
| 305 | + | ||
| 306 | +/* ------------------------------------------------------------------ */ | ||
| 307 | +/* Paths */ | ||
| 308 | +/* ------------------------------------------------------------------ */ | ||
| 309 | + | ||
| 310 | +static const char *home_dir(void) | ||
| 311 | +{ | ||
| 312 | +#if defined(_WIN32) | ||
| 313 | + static char home[512]; | ||
| 314 | + DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); | ||
| 315 | + if (n > 0 && n < sizeof(home)) return home; | ||
| 316 | + home[0] = '\0'; | ||
| 317 | + if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) { | ||
| 318 | + char tmp[512]; | ||
| 319 | + if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { | ||
| 320 | + strncat(home, tmp, sizeof(home) - strlen(home) - 1); | ||
| 321 | + return home; | ||
| 322 | + } | ||
| 323 | + } | ||
| 324 | + return NULL; | ||
| 325 | +#else | ||
| 326 | + const char *h = getenv("HOME"); | ||
| 327 | + return (h && *h) ? h : NULL; | ||
| 328 | +#endif | ||
| 329 | +} | ||
| 330 | + | ||
| 331 | +/* Copy the directory part of a path (including the trailing separator). */ | ||
| 332 | +static void dir_of(const char *path, char *out, size_t n) | ||
| 333 | +{ | ||
| 334 | + char base[PATH_SZ]; | ||
| 335 | + char *slash; | ||
| 336 | + | ||
| 337 | + if (!path) { if (n) out[0] = '\0'; return; } | ||
| 338 | + snprintf(base, sizeof(base), "%s", path); | ||
| 339 | + slash = strrchr(base, PATH_SEP); | ||
| 340 | +#if defined(_WIN32) | ||
| 341 | + if (!slash) slash = strrchr(base, '/'); | ||
| 342 | +#endif | ||
| 343 | + if (slash) *(slash + 1) = '\0'; | ||
| 344 | + else base[0] = '\0'; | ||
| 345 | + snprintf(out, n, "%s", base); | ||
| 346 | +} | ||
| 347 | + | ||
| 348 | +/* A relocated credentials file implies the whole .copilot tree is relocated: | ||
| 349 | + * the same CLI writes all of these into one directory. Reading one from the | ||
| 350 | + * override and the rest from $HOME reports an empty state for a live session. */ | ||
| 351 | +static void copilot_dir(char *out, size_t n) | ||
| 352 | +{ | ||
| 353 | + const char *env = getenv("COPILOT_CREDS_PATH"); | ||
| 354 | + const char *home = home_dir(); | ||
| 355 | + | ||
| 356 | + if (env && *env) { | ||
| 357 | + dir_of(env, out, n); | ||
| 358 | + if (out[0]) return; | ||
| 359 | + } | ||
| 360 | + if (home && *home) { snprintf(out, n, "%s%c.copilot%c", home, PATH_SEP, PATH_SEP); return; } | ||
| 361 | + snprintf(out, n, ".copilot%c", PATH_SEP); | ||
| 362 | +} | ||
| 363 | + | ||
| 364 | +static void creds_path(char *out, size_t n) | ||
| 365 | +{ | ||
| 366 | + const char *env = getenv("COPILOT_CREDS_PATH"); | ||
| 367 | + | ||
| 368 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 369 | + { | ||
| 370 | + char d[PATH_SZ]; | ||
| 371 | + copilot_dir(d, sizeof(d)); | ||
| 372 | + snprintf(out, n, "%s.credentials.json", d); | ||
| 373 | + } | ||
| 374 | +} | ||
| 375 | + | ||
| 376 | +static void config_path(char *out, size_t n) | ||
| 377 | +{ | ||
| 378 | + char d[PATH_SZ]; | ||
| 379 | + copilot_dir(d, sizeof(d)); | ||
| 380 | + snprintf(out, n, "%s%cconfig.json", d, PATH_SEP); | ||
| 381 | +} | ||
| 382 | + | ||
| 383 | +static void cache_path(char *out, size_t n) | ||
| 384 | +{ | ||
| 385 | + char d[PATH_SZ]; | ||
| 386 | + copilot_dir(d, sizeof(d)); | ||
| 387 | + snprintf(out, n, "%s%c.copilot-token-cache.json", d, PATH_SEP); | ||
| 388 | +} | ||
| 389 | + | ||
| 390 | +static void accounts_dir(char *out, size_t n) | ||
| 391 | +{ | ||
| 392 | + const char *env = getenv("COPILOT_ACCOUNTS_DIR"); | ||
| 393 | + | ||
| 394 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 395 | + { | ||
| 396 | + char d[PATH_SZ]; | ||
| 397 | + copilot_dir(d, sizeof(d)); | ||
| 398 | + snprintf(out, n, "%saccounts", d); | ||
| 399 | + } | ||
| 400 | +} | ||
| 401 | + | ||
| 402 | +/* The pending device-flow marker is written by the login CLI into the shared | ||
| 403 | + * login machine directory under $HOME (sx_login_machine.h), not next to the | ||
| 404 | + * credentials file, so it has its own home-anchored path. */ | ||
| 405 | +static void pending_dir(char *out, size_t n) | ||
| 406 | +{ | ||
| 407 | + const char *env = getenv("COPILOT_PENDING_DIR"); | ||
| 408 | + const char *home = home_dir(); | ||
| 409 | + | ||
| 410 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 411 | + if (home && *home) { snprintf(out, n, "%s%c.claude%c.login-pending", home, PATH_SEP, PATH_SEP); return; } | ||
| 412 | + snprintf(out, n, ".claude%c.login-pending", PATH_SEP); | ||
| 413 | +} | ||
| 414 | + | ||
| 415 | +static void pending_path(const char *name, char *out, size_t n) | ||
| 416 | +{ | ||
| 417 | + char d[PATH_SZ]; | ||
| 418 | + pending_dir(d, sizeof(d)); | ||
| 419 | + snprintf(out, n, "%s%ccopilot-%s.json", d, PATH_SEP, (name && *name) ? name : "default"); | ||
| 420 | +} | ||
| 421 | + | ||
| 422 | +static void env_dir(char *out, size_t n) | ||
| 423 | +{ | ||
| 424 | + const char *env = getenv("COPILOT_ENV_DIR"); | ||
| 425 | + const char *home = home_dir(); | ||
| 426 | + | ||
| 427 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 428 | + if (home && *home) { snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); return; } | ||
| 429 | + snprintf(out, n, ".claude%cscorpiox-env", PATH_SEP); | ||
| 430 | +} | ||
| 431 | + | ||
| 432 | +static void profile_path(char *out, size_t n) | ||
| 433 | +{ | ||
| 434 | + char d[PATH_SZ]; | ||
| 435 | + env_dir(d, sizeof(d)); | ||
| 436 | + snprintf(out, n, "%s%ccopilot.txt", d, PATH_SEP); | ||
| 437 | +} | ||
| 438 | + | ||
| 439 | +static void account_path(const char *name, char *out, size_t n) | ||
| 440 | +{ | ||
| 441 | + char d[PATH_SZ]; | ||
| 442 | + accounts_dir(d, sizeof(d)); | ||
| 443 | + snprintf(out, n, "%s%c%s.json", d, PATH_SEP, name); | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +static const char *login_bin(void) | ||
| 447 | +{ | ||
| 448 | + const char *e = getenv("COPILOT_LOGIN_BIN"); | ||
| 449 | + return (e && *e) ? e : DEFAULT_LOGIN_BIN; | ||
| 450 | +} | ||
| 451 | + | ||
| 452 | +static const char *refresh_bin(void) | ||
| 453 | +{ | ||
| 454 | + const char *e = getenv("COPILOT_REFRESH_BIN"); | ||
| 455 | + return (e && *e) ? e : DEFAULT_REFRESH_BIN; | ||
| 456 | +} | ||
| 457 | + | ||
| 458 | +static int file_exists(const char *p) | ||
| 459 | +{ | ||
| 460 | +#if defined(_WIN32) | ||
| 461 | + DWORD a = GetFileAttributesA(p); | ||
| 462 | + return p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); | ||
| 463 | +#else | ||
| 464 | + struct stat st; | ||
| 465 | + return p && stat(p, &st) == 0 && S_ISREG(st.st_mode); | ||
| 466 | +#endif | ||
| 467 | +} | ||
| 468 | + | ||
| 469 | +/* Read a whole file. Returns a malloc'd NUL-terminated buffer or NULL. */ | ||
| 470 | +static char *read_file(const char *path) | ||
| 471 | +{ | ||
| 472 | + FILE *f; | ||
| 473 | + long sz; | ||
| 474 | + char *buf; | ||
| 475 | + | ||
| 476 | + if (!path || !*path) return NULL; | ||
| 477 | + f = fopen(path, "rb"); | ||
| 478 | + if (!f) return NULL; | ||
| 479 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } | ||
| 480 | + sz = ftell(f); | ||
| 481 | + if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } | ||
| 482 | + if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } | ||
| 483 | + buf = (char *)malloc((size_t)sz + 1); | ||
| 484 | + if (!buf) { fclose(f); return NULL; } | ||
| 485 | + if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { | ||
| 486 | + free(buf); | ||
| 487 | + fclose(f); | ||
| 488 | + return NULL; | ||
| 489 | + } | ||
| 490 | + buf[sz] = '\0'; | ||
| 491 | + fclose(f); | ||
| 492 | + return buf; | ||
| 493 | +} | ||
| 494 | + | ||
| 495 | +/* Trim trailing CR/LF/space in place. */ | ||
| 496 | +static void trim_tail(char *s) | ||
| 497 | +{ | ||
| 498 | + size_t n; | ||
| 499 | + | ||
| 500 | + if (!s) return; | ||
| 501 | + n = strlen(s); | ||
| 502 | + while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || | ||
| 503 | + s[n - 1] == ' ' || s[n - 1] == '\t')) | ||
| 504 | + s[--n] = '\0'; | ||
| 505 | +} | ||
| 506 | + | ||
| 507 | +/* Account names are used verbatim in a file name, so they are restricted to a | ||
| 508 | + * shell- and path-safe alphabet. */ | ||
| 509 | +static int name_valid(const char *n) | ||
| 510 | +{ | ||
| 511 | + const char *p; | ||
| 512 | + | ||
| 513 | + if (!n || !*n || strlen(n) > 64) return 0; | ||
| 514 | + if (n[0] == '.') return 0; | ||
| 515 | + for (p = n; *p; p++) { | ||
| 516 | + unsigned char c = (unsigned char)*p; | ||
| 517 | + if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0; | ||
| 518 | + } | ||
| 519 | + return 1; | ||
| 520 | +} | ||
| 521 | + | ||
| 522 | +/* ------------------------------------------------------------------ */ | ||
| 523 | +/* Minimal JSON field readers */ | ||
| 524 | +/* ------------------------------------------------------------------ */ | ||
| 525 | + | ||
| 526 | +/* Copy a JSON string value that starts at *pp (pointing at the opening quote) | ||
| 527 | + * and advance *pp past the closing quote. */ | ||
| 528 | +static int json_read_string_at(const char **pp, char *out, size_t outsz) | ||
| 529 | +{ | ||
| 530 | + const char *p = *pp; | ||
| 531 | + size_t i = 0; | ||
| 532 | + | ||
| 533 | + if (!p || *p != '"') return 0; | ||
| 534 | + p++; | ||
| 535 | + while (*p && *p != '"') { | ||
| 536 | + char c = *p; | ||
| 537 | + if (c == '\\' && p[1]) { | ||
| 538 | + p++; | ||
| 539 | + switch (*p) { | ||
| 540 | + case 'n': c = '\n'; break; | ||
| 541 | + case 'r': c = '\r'; break; | ||
| 542 | + case 't': c = '\t'; break; | ||
| 543 | + case 'b': c = '\b'; break; | ||
| 544 | + case 'f': c = '\f'; break; | ||
| 545 | + case 'u': { | ||
| 546 | + unsigned int v = 0; | ||
| 547 | + int k; | ||
| 548 | + p++; | ||
| 549 | + for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) | ||
| 550 | + v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) | ||
| 551 | + ? *p - '0' | ||
| 552 | + : tolower((unsigned char)*p) - 'a' + 10); | ||
| 553 | + if (i + 1 < outsz) out[i++] = (char)(v & 0xff); | ||
| 554 | + continue; | ||
| 555 | + } | ||
| 556 | + default: c = *p; break; | ||
| 557 | + } | ||
| 558 | + p++; | ||
| 559 | + } else { | ||
| 560 | + p++; | ||
| 561 | + } | ||
| 562 | + if (i + 1 < outsz) out[i++] = c; | ||
| 563 | + } | ||
| 564 | + if (*p == '"') p++; | ||
| 565 | + if (outsz) out[i < outsz ? i : outsz - 1] = '\0'; | ||
| 566 | + *pp = p; | ||
| 567 | + return 1; | ||
| 568 | +} | ||
| 569 | + | ||
| 570 | +/* Find "key":<value> among the TOP-LEVEL keys of the slice [obj, end). | ||
| 571 | + * A nested object is skipped as a whole. | ||
| 572 | + * | ||
| 573 | + * A caller almost always hands us a pointer at the opening '{'; that brace is | ||
| 574 | + * skipped inside the reader so no call site needs a "+1" that is easy to | ||
| 575 | + * forget and completely silent when it is missing. */ | ||
| 576 | +static const char *json_find_key(const char *obj, const char *end, const char *key) | ||
| 577 | +{ | ||
| 578 | + size_t klen; | ||
| 579 | + const char *p; | ||
| 580 | + int depth = 0; | ||
| 581 | + | ||
| 582 | + if (!obj || !end || !key) return NULL; | ||
| 583 | + klen = strlen(key); | ||
| 584 | + p = obj; | ||
| 585 | + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; | ||
| 586 | + if (p < end && *p == '{') p++; | ||
| 587 | + | ||
| 588 | + while (p && p < end) { | ||
| 589 | + if (*p == '"') { | ||
| 590 | + char name[128]; | ||
| 591 | + json_read_string_at(&p, name, sizeof(name)); | ||
| 592 | + if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { | ||
| 593 | + const char *q = p; | ||
| 594 | + while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; | ||
| 595 | + if (q < end && *q == ':') { | ||
| 596 | + q++; | ||
| 597 | + while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; | ||
| 598 | + return (q < end) ? q : NULL; | ||
| 599 | + } | ||
| 600 | + } | ||
| 601 | + continue; | ||
| 602 | + } | ||
| 603 | + if (*p == '{' || *p == '[') depth++; | ||
| 604 | + else if (*p == '}' || *p == ']') depth--; | ||
| 605 | + p++; | ||
| 606 | + } | ||
| 607 | + return NULL; | ||
| 608 | +} | ||
| 609 | + | ||
| 610 | +/* Returns 0 and leaves *out untouched when the key is absent or null. That | ||
| 611 | + * matters: several callers pass a field of a longer-lived struct, and clearing | ||
| 612 | + * it on a miss silently erases a value that was already correct. */ | ||
| 613 | +static int json_str_field(const char *obj, const char *end, const char *key, | ||
| 614 | + char *out, size_t outsz) | ||
| 615 | +{ | ||
| 616 | + const char *v; | ||
| 617 | + | ||
| 618 | + if (!out || outsz == 0) return 0; | ||
| 619 | + v = json_find_key(obj, end, key); | ||
| 620 | + if (!v || *v == 'n') return 0; | ||
| 621 | + if (*v == '"') return json_read_string_at(&v, out, outsz); | ||
| 622 | + { | ||
| 623 | + size_t i = 0; | ||
| 624 | + out[0] = '\0'; | ||
| 625 | + while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; | ||
| 626 | + out[i] = '\0'; | ||
| 627 | + trim_tail(out); | ||
| 628 | + return out[0] ? 1 : 0; | ||
| 629 | + } | ||
| 630 | +} | ||
| 631 | + | ||
| 632 | +static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) | ||
| 633 | +{ | ||
| 634 | + const char *v = json_find_key(obj, end, key); | ||
| 635 | + | ||
| 636 | + if (!v) return dflt; | ||
| 637 | + if (strncmp(v, "true", 4) == 0) return 1; | ||
| 638 | + if (strncmp(v, "false", 5) == 0) return 0; | ||
| 639 | + if (*v == '"') { | ||
| 640 | + if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1; | ||
| 641 | + return 0; | ||
| 642 | + } | ||
| 643 | + if (*v == '1') return 1; | ||
| 644 | + return 0; | ||
| 645 | +} | ||
| 646 | + | ||
| 647 | +static long long json_num_field(const char *obj, const char *end, const char *key) | ||
| 648 | +{ | ||
| 649 | + const char *v = json_find_key(obj, end, key); | ||
| 650 | + | ||
| 651 | + if (!v) return 0; | ||
| 652 | + if (*v == '"') v++; | ||
| 653 | + return atoll(v); | ||
| 654 | +} | ||
| 655 | + | ||
| 656 | +/* ------------------------------------------------------------------ */ | ||
| 657 | +/* Child processes */ | ||
| 658 | +/* ------------------------------------------------------------------ */ | ||
| 659 | + | ||
| 660 | +/* Quote one argv element for the shell popen() uses. POSIX: single quotes with | ||
| 661 | + * the standard close-escape-reopen trick. Windows: double quotes, which is | ||
| 662 | + * what cmd.exe accepts. */ | ||
| 663 | +static void shell_quote_into(const char *in, char *out, size_t outsz) | ||
| 664 | +{ | ||
| 665 | + size_t o = 0; | ||
| 666 | + const char *p; | ||
| 667 | + | ||
| 668 | + if (outsz < 3) { if (outsz) out[0] = '\0'; return; } | ||
| 669 | +#if defined(_WIN32) | ||
| 670 | + out[o++] = '"'; | ||
| 671 | + for (p = in; p && *p; p++) { | ||
| 672 | + if (*p == '"') { | ||
| 673 | + if (o + 3 >= outsz) break; | ||
| 674 | + out[o++] = '\\'; | ||
| 675 | + out[o++] = '"'; | ||
| 676 | + } else { | ||
| 677 | + if (o + 2 >= outsz) break; | ||
| 678 | + out[o++] = *p; | ||
| 679 | + } | ||
| 680 | + } | ||
| 681 | + out[o++] = '"'; | ||
| 682 | + out[o] = '\0'; | ||
| 683 | +#else | ||
| 684 | + out[o++] = '\''; | ||
| 685 | + for (p = in; p && *p; p++) { | ||
| 686 | + if (*p == '\'') { | ||
| 687 | + if (o + 5 >= outsz) break; | ||
| 688 | + memcpy(out + o, "'\\''", 4); | ||
| 689 | + o += 4; | ||
| 690 | + } else { | ||
| 691 | + if (o + 2 >= outsz) break; | ||
| 692 | + out[o++] = *p; | ||
| 693 | + } | ||
| 694 | + } | ||
| 695 | + out[o++] = '\''; | ||
| 696 | + out[o] = '\0'; | ||
| 697 | +#endif | ||
| 698 | +} | ||
| 699 | + | ||
| 700 | +/* Is <bin> resolvable on this node? POSIX answers through popen's own 127 | ||
| 701 | + * ("command not found"). cmd.exe returns 1 for a missing program, which is | ||
| 702 | + * indistinguishable from the program's own failure - so on Windows the path is | ||
| 703 | + * resolved BEFORE popen with SearchPathA. Without this, a Windows node with no | ||
| 704 | + * SCORPIOX CODE reported cli_present:true and "start failed" instead of | ||
| 705 | + * cli_unavailable (measured on a real Windows box). */ | ||
| 706 | +static int bin_available(const char *bin) | ||
| 707 | +{ | ||
| 708 | + if (!bin || !*bin) return 0; | ||
| 709 | +#if defined(_WIN32) | ||
| 710 | + { | ||
| 711 | + char full[MAX_PATH]; | ||
| 712 | + DWORD n; | ||
| 713 | + /* An explicit path is checked directly; a bare name is searched on PATH. */ | ||
| 714 | + if (strchr(bin, '\\') || strchr(bin, '/') || strchr(bin, ':')) | ||
| 715 | + return file_exists(bin); | ||
| 716 | + n = SearchPathA(NULL, bin, ".exe", (DWORD)sizeof(full), full, NULL); | ||
| 717 | + return n > 0 && n < (DWORD)sizeof(full); | ||
| 718 | + } | ||
| 719 | +#else | ||
| 720 | + return 1; /* decided by run_capture's own 127 check */ | ||
| 721 | +#endif | ||
| 722 | +} | ||
| 723 | + | ||
| 724 | +/* Run `<bin> <args>` and capture stdout. | ||
| 725 | + * Returns 1 when the process ran, | ||
| 726 | + * 0 when popen() itself failed, | ||
| 727 | + * -1 when the binary is not on this node ("command not found"). | ||
| 728 | + * | ||
| 729 | + * pclose() hands back a WAIT STATUS, not an exit code: a missing command | ||
| 730 | + * arrives as 32512 (127 << 8). Treating that as the tool's own failure would | ||
| 731 | + * report "refresh failed" for a node that simply has no SCORPIOX CODE. */ | ||
| 732 | +static int run_capture(const char *bin, const char *args, buf_t *out) | ||
| 733 | +{ | ||
| 734 | + char cmd[CMD_SZ]; | ||
| 735 | + char qbin[FIELD_SZ]; | ||
| 736 | + FILE *f; | ||
| 737 | + char line[2048]; | ||
| 738 | + size_t total = 0; | ||
| 739 | + int rc; | ||
| 740 | + | ||
| 741 | + if (!bin || !*bin) return 0; | ||
| 742 | + if (!bin_available(bin)) return -1; | ||
| 743 | + shell_quote_into(bin, qbin, sizeof(qbin)); | ||
| 744 | +#if defined(_WIN32) | ||
| 745 | + if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args); | ||
| 746 | + else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin); | ||
| 747 | +#else | ||
| 748 | + if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); | ||
| 749 | + else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); | ||
| 750 | +#endif | ||
| 751 | + | ||
| 752 | + f = popen(cmd, "r"); | ||
| 753 | + if (!f) return 0; | ||
| 754 | + while (fgets(line, sizeof(line), f)) { | ||
| 755 | + total += strlen(line); | ||
| 756 | + if (total > OUT_MAX) break; | ||
| 757 | + buf_adds(out, line); | ||
| 758 | + } | ||
| 759 | + rc = pclose(f); | ||
| 760 | + | ||
| 761 | + if (out->p) { | ||
| 762 | + size_t n = out->n; | ||
| 763 | + while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; | ||
| 764 | + out->n = n; | ||
| 765 | + } | ||
| 766 | + if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1; | ||
| 767 | + return 1; | ||
| 768 | +} | ||
| 769 | + | ||
| 770 | +/* The CLIs print human progress before the final JSON line, so take the LAST | ||
| 771 | + * line that starts with '{'. */ | ||
| 772 | +static const char *last_json_line(buf_t *b) | ||
| 773 | +{ | ||
| 774 | + size_t i; | ||
| 775 | + const char *last = NULL; | ||
| 776 | + | ||
| 777 | + if (!b || !b->p) return NULL; | ||
| 778 | + for (i = 0; i < b->n; i++) { | ||
| 779 | + int at_line_start = (i == 0) || b->p[i - 1] == '\n'; | ||
| 780 | + if (at_line_start && b->p[i] == '{') last = b->p + i; | ||
| 781 | + } | ||
| 782 | + return last; | ||
| 783 | +} | ||
| 784 | + | ||
| 785 | + | ||
| 786 | +/* ------------------------------------------------------------------ */ | ||
| 787 | +/* Status assembly */ | ||
| 788 | +/* ------------------------------------------------------------------ */ | ||
| 789 | + | ||
| 790 | +/* Copilot has no refresh token: the device flow mints a long-lived `gho_` | ||
| 791 | + * token, and the short-lived JWT is derived from it on demand. expiresAt is in | ||
| 792 | + * milliseconds in this file format but a hand-written fixture may carry | ||
| 793 | + * seconds, so detect by magnitude rather than trusting either form. */ | ||
| 794 | +static long long to_sec(long long v) | ||
| 795 | +{ | ||
| 796 | + return (v > 100000000000LL) ? (v / 1000) : v; | ||
| 797 | +} | ||
| 798 | + | ||
| 799 | +typedef struct { | ||
| 800 | + char name[NAME_SZ]; | ||
| 801 | + int present; | ||
| 802 | + int logged_in; | ||
| 803 | + int expired; | ||
| 804 | + long long expires_in_sec; | ||
| 805 | +} account_t; | ||
| 806 | + | ||
| 807 | +typedef struct { | ||
| 808 | + int logged_in; | ||
| 809 | + int pending; | ||
| 810 | + int expired; | ||
| 811 | + int cli_present; | ||
| 812 | + int profile_exists; | ||
| 813 | + int cache_present; | ||
| 814 | + char account[NAME_SZ]; | ||
| 815 | + char user[NAME_SZ]; | ||
| 816 | + char path[PATH_SZ]; | ||
| 817 | + char pending_file[PATH_SZ]; | ||
| 818 | + char profile[NAME_SZ]; | ||
| 819 | + char profile_file[PATH_SZ]; | ||
| 820 | + char scope[256]; | ||
| 821 | + char cli_error[FIELD_SZ]; | ||
| 822 | + char user_code[NAME_SZ]; | ||
| 823 | + char verify_url[FIELD_SZ]; | ||
| 824 | + int interval; | ||
| 825 | + int expires_in; | ||
| 826 | + long long expires_at; /* seconds since epoch from the token cache */ | ||
| 827 | + long long expires_in_sec; /* negative when expired, 0 when unknown */ | ||
| 828 | + account_t accounts[MAX_ACCOUNTS]; | ||
| 829 | + int account_count; | ||
| 830 | +} status_t; | ||
| 831 | + | ||
| 832 | +/* Find a github_token-shaped value. The CLI writes "github_token" in | ||
| 833 | + * ~/.copilot/.credentials.json; VS Code writes "token". Only presence is | ||
| 834 | + * reported, never the value. */ | ||
| 835 | +static int scan_token(const char *json, const char *key) | ||
| 836 | +{ | ||
| 837 | + char tok[8] = {0}; | ||
| 838 | + | ||
| 839 | + if (!json) return 0; | ||
| 840 | + if (json_str_field(json, json + strlen(json), key, tok, sizeof(tok))) return 1; | ||
| 841 | + /* Anywhere in the file (config.json nests it two levels deep). */ | ||
| 842 | + { | ||
| 843 | + char pat[64]; | ||
| 844 | + snprintf(pat, sizeof(pat), "\"%s\"", key); | ||
| 845 | + if (strstr(json, pat)) { | ||
| 846 | + const char *p = strstr(json, pat); | ||
| 847 | + const char *colon = p ? strchr(p, ':') : NULL; | ||
| 848 | + const char *q = colon ? strchr(colon, '"') : NULL; | ||
| 849 | + if (q && q[1]) return 1; | ||
| 850 | + } | ||
| 851 | + } | ||
| 852 | + return 0; | ||
| 853 | +} | ||
| 854 | + | ||
| 855 | +static void scan_creds(const char *json, status_t *st) | ||
| 856 | +{ | ||
| 857 | + char tmp[FIELD_SZ] = {0}; | ||
| 858 | + | ||
| 859 | + if (!json) return; | ||
| 860 | + if (scan_token(json, "github_token") || scan_token(json, "token") || | ||
| 861 | + strstr(json, "gho_")) | ||
| 862 | + st->logged_in = 1; | ||
| 863 | + if (json_str_field(json, json + strlen(json), "scope", tmp, sizeof(tmp)) && tmp[0]) | ||
| 864 | + snprintf(st->scope, sizeof(st->scope), "%s", tmp); | ||
| 865 | + if (!st->user[0] && | ||
| 866 | + json_str_field(json, json + strlen(json), "login", tmp, sizeof(tmp)) && tmp[0]) | ||
| 867 | + snprintf(st->user, sizeof(st->user), "%s", tmp); | ||
| 868 | +} | ||
| 869 | + | ||
| 870 | +/* The token cache holds the derived Copilot JWT and its expiry. It is what | ||
| 871 | + * tells the UI "this session expires in N minutes". */ | ||
| 872 | +static void scan_cache(status_t *st, long long now_sec) | ||
| 873 | +{ | ||
| 874 | + char p[PATH_SZ]; | ||
| 875 | + char *json; | ||
| 876 | + | ||
| 877 | + cache_path(p, sizeof(p)); | ||
| 878 | + json = read_file(p); | ||
| 879 | + if (!json) return; | ||
| 880 | + st->cache_present = 1; | ||
| 881 | + { | ||
| 882 | + long long e = json_num_field(json, json + strlen(json), "expires_at"); | ||
| 883 | + if (e > 0) st->expires_at = to_sec(e); | ||
| 884 | + } | ||
| 885 | + if (st->expires_at > 0) { | ||
| 886 | + st->expires_in_sec = st->expires_at - now_sec; | ||
| 887 | + st->expired = st->expires_in_sec <= 0; | ||
| 888 | + } | ||
| 889 | + free(json); | ||
| 890 | +} | ||
| 891 | + | ||
| 892 | +/* config.json carries lastLoggedInUser.login, which is the only place the | ||
| 893 | + * GitHub user name is stored. */ | ||
| 894 | +static void scan_config(status_t *st) | ||
| 895 | +{ | ||
| 896 | + char p[PATH_SZ]; | ||
| 897 | + char *json; | ||
| 898 | + char tmp[NAME_SZ] = {0}; | ||
| 899 | + | ||
| 900 | + config_path(p, sizeof(p)); | ||
| 901 | + json = read_file(p); | ||
| 902 | + if (!json) return; | ||
| 903 | + { | ||
| 904 | + const char *lu = strstr(json, "\"lastLoggedInUser\""); | ||
| 905 | + const char *brace = lu ? strchr(lu, '{') : NULL; | ||
| 906 | + if (brace) { | ||
| 907 | + const char *end = json + strlen(json); | ||
| 908 | + if (json_str_field(brace, end, "login", tmp, sizeof(tmp)) && tmp[0]) | ||
| 909 | + snprintf(st->user, sizeof(st->user), "%s", tmp); | ||
| 910 | + } | ||
| 911 | + } | ||
| 912 | + free(json); | ||
| 913 | +} | ||
| 914 | + | ||
| 915 | +/* Read the profile file written by --create-profile. */ | ||
| 916 | +static void scan_profile(status_t *st) | ||
| 917 | +{ | ||
| 918 | + char *text; | ||
| 919 | + char line[FIELD_SZ]; | ||
| 920 | + | ||
| 921 | + profile_path(st->profile_file, sizeof(st->profile_file)); | ||
| 922 | + st->profile_exists = file_exists(st->profile_file); | ||
| 923 | + if (!st->profile_exists) return; | ||
| 924 | + | ||
| 925 | + text = read_file(st->profile_file); | ||
| 926 | + if (!text) return; | ||
| 927 | + { | ||
| 928 | + const char *p = text; | ||
| 929 | + while (p && *p) { | ||
| 930 | + const char *nl = strchr(p, '\n'); | ||
| 931 | + size_t len = nl ? (size_t)(nl - p) : strlen(p); | ||
| 932 | + if (len > 0 && len < sizeof(line)) { | ||
| 933 | + memcpy(line, p, len); | ||
| 934 | + line[len] = '\0'; | ||
| 935 | + trim_tail(line); | ||
| 936 | + if (strncmp(line, "MODEL=", 6) == 0) | ||
| 937 | + snprintf(st->profile, sizeof(st->profile), "%.*s", | ||
| 938 | + (int)sizeof(st->profile) - 1, line + 6); | ||
| 939 | + } | ||
| 940 | + if (!nl) break; | ||
| 941 | + p = nl + 1; | ||
| 942 | + } | ||
| 943 | + } | ||
| 944 | + free(text); | ||
| 945 | +} | ||
| 946 | + | ||
| 947 | +/* List the account files in the accounts directory. Copilot account files have | ||
| 948 | + * the same shape as the default credentials file, and share one token cache. */ | ||
| 949 | +static void scan_accounts(status_t *st, long long now_sec) | ||
| 950 | +{ | ||
| 951 | + char d[PATH_SZ]; | ||
| 952 | + | ||
| 953 | + st->account_count = 0; | ||
| 954 | + accounts_dir(d, sizeof(d)); | ||
| 955 | + | ||
| 956 | +#if defined(_WIN32) | ||
| 957 | + { | ||
| 958 | + char pattern[PATH_SZ]; | ||
| 959 | + WIN32_FIND_DATAA fd; | ||
| 960 | + HANDLE h; | ||
| 961 | + snprintf(pattern, sizeof(pattern), "%s\\*.json", d); | ||
| 962 | + h = FindFirstFileA(pattern, &fd); | ||
| 963 | + if (h == INVALID_HANDLE_VALUE) return; | ||
| 964 | + do { | ||
| 965 | + size_t ln = strlen(fd.cFileName); | ||
| 966 | + if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue; | ||
| 967 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; | ||
| 968 | + { | ||
| 969 | + account_t *a = &st->accounts[st->account_count]; | ||
| 970 | + char p[PATH_SZ]; | ||
| 971 | + char *json; | ||
| 972 | + status_t tmp; | ||
| 973 | + memset(a, 0, sizeof(*a)); | ||
| 974 | + snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName); | ||
| 975 | + snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName); | ||
| 976 | + a->present = 1; | ||
| 977 | + memset(&tmp, 0, sizeof(tmp)); | ||
| 978 | + json = read_file(p); | ||
| 979 | + if (json) { scan_creds(json, &tmp); free(json); } | ||
| 980 | + a->logged_in = tmp.logged_in; | ||
| 981 | + if (a->logged_in && st->expires_at > 0) { | ||
| 982 | + a->expires_in_sec = st->expires_at - now_sec; | ||
| 983 | + a->expired = a->expires_in_sec <= 0; | ||
| 984 | + } | ||
| 985 | + st->account_count++; | ||
| 986 | + } | ||
| 987 | + } while (FindNextFileA(h, &fd)); | ||
| 988 | + FindClose(h); | ||
| 989 | + } | ||
| 990 | +#else | ||
| 991 | + { | ||
| 992 | + DIR *dp = opendir(d); | ||
| 993 | + struct dirent *de; | ||
| 994 | + if (!dp) return; | ||
| 995 | + while ((de = readdir(dp)) != NULL) { | ||
| 996 | + size_t ln = strlen(de->d_name); | ||
| 997 | + account_t *a; | ||
| 998 | + char p[PATH_SZ]; | ||
| 999 | + char *json; | ||
| 1000 | + status_t tmp; | ||
| 1001 | + | ||
| 1002 | + if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue; | ||
| 1003 | + if (strcmp(de->d_name + ln - 5, ".json") != 0) continue; | ||
| 1004 | + a = &st->accounts[st->account_count]; | ||
| 1005 | + memset(a, 0, sizeof(*a)); | ||
| 1006 | + snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name); | ||
| 1007 | + snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name); | ||
| 1008 | + a->present = 1; | ||
| 1009 | + memset(&tmp, 0, sizeof(tmp)); | ||
| 1010 | + json = read_file(p); | ||
| 1011 | + if (json) { scan_creds(json, &tmp); free(json); } | ||
| 1012 | + a->logged_in = tmp.logged_in; | ||
| 1013 | + if (a->logged_in && st->expires_at > 0) { | ||
| 1014 | + a->expires_in_sec = st->expires_at - now_sec; | ||
| 1015 | + a->expired = a->expires_in_sec <= 0; | ||
| 1016 | + } | ||
| 1017 | + st->account_count++; | ||
| 1018 | + } | ||
| 1019 | + closedir(dp); | ||
| 1020 | + } | ||
| 1021 | +#endif | ||
| 1022 | +} | ||
| 1023 | + | ||
| 1024 | +/* Ask the login CLI. It is authoritative when present: it knows about the | ||
| 1025 | + * pending device flow, the account file it would write and the profile. | ||
| 1026 | + * It never prints a token, so its JSON is safe to relay field by field. */ | ||
| 1027 | +static void scan_cli(status_t *st, const char *name) | ||
| 1028 | +{ | ||
| 1029 | + buf_t out; | ||
| 1030 | + const char *j; | ||
| 1031 | + char args[NAME_SZ + 32]; | ||
| 1032 | + | ||
| 1033 | + buf_init(&out); | ||
| 1034 | + if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name); | ||
| 1035 | + else snprintf(args, sizeof(args), "--status"); | ||
| 1036 | + | ||
| 1037 | + { | ||
| 1038 | + int rc = run_capture(login_bin(), args, &out); | ||
| 1039 | + if (rc <= 0) { | ||
| 1040 | + st->cli_present = 0; | ||
| 1041 | + snprintf(st->cli_error, sizeof(st->cli_error), "%s", | ||
| 1042 | + rc == -1 ? "the login CLI is not on this node" | ||
| 1043 | + : "could not start the login CLI"); | ||
| 1044 | + buf_free(&out); | ||
| 1045 | + return; | ||
| 1046 | + } | ||
| 1047 | + } | ||
| 1048 | + | ||
| 1049 | + j = last_json_line(&out); | ||
| 1050 | + if (!j) { | ||
| 1051 | + st->cli_present = 1; | ||
| 1052 | + buf_free(&out); | ||
| 1053 | + return; | ||
| 1054 | + } | ||
| 1055 | + st->cli_present = 1; | ||
| 1056 | + { | ||
| 1057 | + const char *end = j + strlen(j); | ||
| 1058 | + if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1; | ||
| 1059 | + st->pending = json_bool_field(j, end, "pending", 0); | ||
| 1060 | + { | ||
| 1061 | + char acct[NAME_SZ] = {0}; | ||
| 1062 | + if (json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0]) | ||
| 1063 | + snprintf(st->account, sizeof(st->account), "%s", acct); | ||
| 1064 | + } | ||
| 1065 | + { | ||
| 1066 | + char ident[NAME_SZ] = {0}; | ||
| 1067 | + if (json_str_field(j, end, "identity", ident, sizeof(ident)) && ident[0]) | ||
| 1068 | + snprintf(st->user, sizeof(st->user), "%s", ident); | ||
| 1069 | + } | ||
| 1070 | + } | ||
| 1071 | + buf_free(&out); | ||
| 1072 | +} | ||
| 1073 | + | ||
| 1074 | +static void collect_status(status_t *st, const char *name) | ||
| 1075 | +{ | ||
| 1076 | + char *json; | ||
| 1077 | + long long now_sec = (long long)time(NULL); | ||
| 1078 | + | ||
| 1079 | + memset(st, 0, sizeof(*st)); | ||
| 1080 | + | ||
| 1081 | + if (name && *name) { | ||
| 1082 | + char p[PATH_SZ]; | ||
| 1083 | + account_path(name, p, sizeof(p)); | ||
| 1084 | + snprintf(st->path, sizeof(st->path), "%s", p); | ||
| 1085 | + snprintf(st->account, sizeof(st->account), "%s", name); | ||
| 1086 | + } else { | ||
| 1087 | + creds_path(st->path, sizeof(st->path)); | ||
| 1088 | + } | ||
| 1089 | + | ||
| 1090 | + json = read_file(st->path); | ||
| 1091 | + if (json) { | ||
| 1092 | + scan_creds(json, st); | ||
| 1093 | + free(json); | ||
| 1094 | + } | ||
| 1095 | + | ||
| 1096 | + scan_config(st); | ||
| 1097 | + scan_cache(st, now_sec); | ||
| 1098 | + scan_cli(st, name); | ||
| 1099 | + scan_profile(st); | ||
| 1100 | + | ||
| 1101 | + pending_path(name, st->pending_file, sizeof(st->pending_file)); | ||
| 1102 | + if (file_exists(st->pending_file)) st->pending = 1; | ||
| 1103 | + | ||
| 1104 | + if (!st->logged_in) { | ||
| 1105 | + st->expired = 0; | ||
| 1106 | + st->expires_in_sec = 0; | ||
| 1107 | + } | ||
| 1108 | + if (!st->account[0] && st->logged_in) | ||
| 1109 | + snprintf(st->account, sizeof(st->account), "default"); | ||
| 1110 | + if (!st->account[0] && name && *name) | ||
| 1111 | + snprintf(st->account, sizeof(st->account), "%s", name); | ||
| 1112 | + | ||
| 1113 | + scan_accounts(st, now_sec); | ||
| 1114 | + if (!st->user[0] && st->account_count == 1 && st->accounts[0].name[0]) | ||
| 1115 | + snprintf(st->user, sizeof(st->user), "%s", ""); | ||
| 1116 | +} | ||
| 1117 | + | ||
| 1118 | +/* One status object, shared by every action so the UI always re-renders from | ||
| 1119 | + * the same shape. */ | ||
| 1120 | +static void emit_status(buf_t *b, const status_t *st) | ||
| 1121 | +{ | ||
| 1122 | + int i; | ||
| 1123 | + | ||
| 1124 | + buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false"); | ||
| 1125 | + buf_adds(b, "\"user\":"); | ||
| 1126 | + buf_json(b, st->user); | ||
| 1127 | + buf_addf(b, ",\"has_refresh\":%s", "false"); | ||
| 1128 | + buf_adds(b, ",\"account\":"); | ||
| 1129 | + buf_json(b, st->account); | ||
| 1130 | + buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false"); | ||
| 1131 | + buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec); | ||
| 1132 | + buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false"); | ||
| 1133 | + buf_addf(b, ",\"cache_present\":%s", st->cache_present ? "true" : "false"); | ||
| 1134 | + buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false"); | ||
| 1135 | + buf_adds(b, ",\"credentials_path\":"); | ||
| 1136 | + buf_json(b, st->path); | ||
| 1137 | + buf_adds(b, ",\"scope\":"); | ||
| 1138 | + buf_json(b, st->scope); | ||
| 1139 | + buf_adds(b, ",\"profile\":"); | ||
| 1140 | + buf_json(b, st->profile); | ||
| 1141 | + buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false"); | ||
| 1142 | + buf_addf(b, ",\"named_accounts\":%s", st->account_count > 1 ? "true" : "false"); | ||
| 1143 | + | ||
| 1144 | + buf_adds(b, ",\"accounts\":["); | ||
| 1145 | + for (i = 0; i < st->account_count; i++) { | ||
| 1146 | + const account_t *a = &st->accounts[i]; | ||
| 1147 | + if (i) buf_addc(b, ','); | ||
| 1148 | + buf_adds(b, "{\"name\":"); | ||
| 1149 | + buf_json(b, a->name); | ||
| 1150 | + buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false"); | ||
| 1151 | + buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec); | ||
| 1152 | + buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false"); | ||
| 1153 | + } | ||
| 1154 | + buf_addc(b, ']'); | ||
| 1155 | +} | ||
| 1156 | + | ||
| 1157 | + | ||
| 1158 | +/* ------------------------------------------------------------------ */ | ||
| 1159 | +/* Actions */ | ||
| 1160 | +/* ------------------------------------------------------------------ */ | ||
| 1161 | + | ||
| 1162 | +static void json_headers(void) | ||
| 1163 | +{ | ||
| 1164 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1165 | + "Cache-Control: no-store\r\n" | ||
| 1166 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1167 | +} | ||
| 1168 | + | ||
| 1169 | +static void emit_error(int code, const char *status, const char *err, const char *detail) | ||
| 1170 | +{ | ||
| 1171 | + buf_t b; | ||
| 1172 | + | ||
| 1173 | + buf_init(&b); | ||
| 1174 | + buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" | ||
| 1175 | + "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", | ||
| 1176 | + code, status); | ||
| 1177 | + buf_adds(&b, "{\"ok\":false,\"error\":"); | ||
| 1178 | + buf_json(&b, err); | ||
| 1179 | + if (detail && *detail) { | ||
| 1180 | + buf_adds(&b, ",\"detail\":"); | ||
| 1181 | + buf_json(&b, detail); | ||
| 1182 | + } | ||
| 1183 | + buf_adds(&b, "}\n"); | ||
| 1184 | + fputs(buf_str(&b), stdout); | ||
| 1185 | + buf_free(&b); | ||
| 1186 | +} | ||
| 1187 | + | ||
| 1188 | +static int emit_status_json(const status_t *st, const char *extra_head) | ||
| 1189 | +{ | ||
| 1190 | + buf_t b; | ||
| 1191 | + | ||
| 1192 | + buf_init(&b); | ||
| 1193 | + buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\","); | ||
| 1194 | + if (extra_head) buf_adds(&b, extra_head); | ||
| 1195 | + emit_status(&b, st); | ||
| 1196 | + buf_adds(&b, ",\"flow\":\"device_code\",\"protocol\":\"SXLOGIN-MACHINE-V1\"}\n"); | ||
| 1197 | + json_headers(); | ||
| 1198 | + fputs(buf_str(&b), stdout); | ||
| 1199 | + buf_free(&b); | ||
| 1200 | + return 0; | ||
| 1201 | +} | ||
| 1202 | + | ||
| 1203 | +static int action_status(const char *name) | ||
| 1204 | +{ | ||
| 1205 | + status_t st; | ||
| 1206 | + | ||
| 1207 | + collect_status(&st, name); | ||
| 1208 | + return emit_status_json(&st, NULL); | ||
| 1209 | +} | ||
| 1210 | + | ||
| 1211 | +static int action_accounts(const char *name) | ||
| 1212 | +{ | ||
| 1213 | + status_t st; | ||
| 1214 | + buf_t b; | ||
| 1215 | + int i; | ||
| 1216 | + | ||
| 1217 | + collect_status(&st, name); | ||
| 1218 | + buf_init(&b); | ||
| 1219 | + buf_adds(&b, "{\"ok\":true,\"accounts\":["); | ||
| 1220 | + for (i = 0; i < st.account_count; i++) { | ||
| 1221 | + const account_t *a = &st.accounts[i]; | ||
| 1222 | + if (i) buf_addc(&b, ','); | ||
| 1223 | + buf_adds(&b, "{\"name\":"); | ||
| 1224 | + buf_json(&b, a->name); | ||
| 1225 | + buf_addf(&b, ",\"logged_in\":%s", a->logged_in ? "true" : "false"); | ||
| 1226 | + buf_addf(&b, ",\"expires_in_sec\":%lld", a->expires_in_sec); | ||
| 1227 | + buf_addf(&b, ",\"expired\":%s}", a->expired ? "true" : "false"); | ||
| 1228 | + } | ||
| 1229 | + buf_addf(&b, "],\"count\":%d,\"active\":", st.account_count); | ||
| 1230 | + buf_json(&b, st.account); | ||
| 1231 | + buf_adds(&b, "}\n"); | ||
| 1232 | + json_headers(); | ||
| 1233 | + fputs(buf_str(&b), stdout); | ||
| 1234 | + buf_free(&b); | ||
| 1235 | + return 0; | ||
| 1236 | +} | ||
| 1237 | + | ||
| 1238 | +/* Build the CLI argv suffix for --name / --force. */ | ||
| 1239 | +static void cli_args(char *out, size_t n, const char *name, int force, const char *verb) | ||
| 1240 | +{ | ||
| 1241 | + char qname[NAME_SZ * 2]; | ||
| 1242 | + | ||
| 1243 | + out[0] = '\0'; | ||
| 1244 | + snprintf(out, n, "%s", verb); | ||
| 1245 | + if (force) snprintf(out + strlen(out), n - strlen(out), " --force"); | ||
| 1246 | + if (name && *name) { | ||
| 1247 | + shell_quote_into(name, qname, sizeof(qname)); | ||
| 1248 | + snprintf(out + strlen(out), n - strlen(out), " --name %s", qname); | ||
| 1249 | + } | ||
| 1250 | +} | ||
| 1251 | + | ||
| 1252 | +static int action_start(const char *name, int force) | ||
| 1253 | +{ | ||
| 1254 | + buf_t out, b; | ||
| 1255 | + const char *j; | ||
| 1256 | + char args[NAME_SZ + 64]; | ||
| 1257 | + char verify_url[FIELD_SZ] = {0}; | ||
| 1258 | + char user_code[NAME_SZ] = {0}; | ||
| 1259 | + char flow[64] = {0}; | ||
| 1260 | + char hint[FIELD_SZ] = {0}; | ||
| 1261 | + long long interval = 0, expires_in = 0; | ||
| 1262 | + | ||
| 1263 | + cli_args(args, sizeof(args), name, force, "--start"); | ||
| 1264 | + | ||
| 1265 | + buf_init(&out); | ||
| 1266 | + { | ||
| 1267 | + int rc = run_capture(login_bin(), args, &out); | ||
| 1268 | + if (rc <= 0) { | ||
| 1269 | + buf_free(&out); | ||
| 1270 | + emit_error(200, "OK", "cli_unavailable", | ||
| 1271 | + "the login CLI is not on this node; install SCORPIOX CODE or set COPILOT_LOGIN_BIN"); | ||
| 1272 | + return 1; | ||
| 1273 | + } | ||
| 1274 | + } | ||
| 1275 | + j = last_json_line(&out); | ||
| 1276 | + if (!j) { | ||
| 1277 | + emit_error(200, "OK", "start_failed", "the login CLI returned no JSON"); | ||
| 1278 | + buf_free(&out); | ||
| 1279 | + return 1; | ||
| 1280 | + } | ||
| 1281 | + { | ||
| 1282 | + const char *end = j + strlen(j); | ||
| 1283 | + json_str_field(j, end, "verify_url", verify_url, sizeof(verify_url)); | ||
| 1284 | + json_str_field(j, end, "user_code", user_code, sizeof(user_code)); | ||
| 1285 | + json_str_field(j, end, "flow", flow, sizeof(flow)); | ||
| 1286 | + json_str_field(j, end, "hint", hint, sizeof(hint)); | ||
| 1287 | + interval = json_num_field(j, end, "interval"); | ||
| 1288 | + expires_in = json_num_field(j, end, "expires_in"); | ||
| 1289 | + if (!json_bool_field(j, end, "ok", 1) || !user_code[0]) { | ||
| 1290 | + char detail[FIELD_SZ] = {0}; | ||
| 1291 | + json_str_field(j, end, "error", detail, sizeof(detail)); | ||
| 1292 | + buf_free(&out); | ||
| 1293 | + emit_error(200, "OK", detail[0] ? detail : "start_failed", | ||
| 1294 | + "the login CLI did not return a device code"); | ||
| 1295 | + return 1; | ||
| 1296 | + } | ||
| 1297 | + } | ||
| 1298 | + buf_free(&out); | ||
| 1299 | + | ||
| 1300 | + buf_init(&b); | ||
| 1301 | + buf_adds(&b, "{\"ok\":true,\"flow\":"); | ||
| 1302 | + buf_json(&b, flow[0] ? flow : "device_code"); | ||
| 1303 | + buf_adds(&b, ",\"verify_url\":"); | ||
| 1304 | + buf_json(&b, verify_url[0] ? verify_url : "https://github.com/login/device"); | ||
| 1305 | + buf_adds(&b, ",\"user_code\":"); | ||
| 1306 | + buf_json(&b, user_code); | ||
| 1307 | + buf_addf(&b, ",\"interval\":%lld", interval > 0 ? interval : DEFAULT_INTERVAL); | ||
| 1308 | + buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : DEFAULT_EXPIRES_IN); | ||
| 1309 | + buf_adds(&b, ",\"hint\":"); | ||
| 1310 | + buf_json(&b, hint[0] ? hint | ||
| 1311 | + : "Open the link, enter the code, approve. This page checks automatically."); | ||
| 1312 | + buf_adds(&b, "}\n"); | ||
| 1313 | + json_headers(); | ||
| 1314 | + fputs(buf_str(&b), stdout); | ||
| 1315 | + buf_free(&b); | ||
| 1316 | + return 0; | ||
| 1317 | +} | ||
| 1318 | + | ||
| 1319 | +/* One non-blocking poll. The CLI answers state=pending while GitHub is still | ||
| 1320 | + * waiting for the user, state=done once the token is written, and an error | ||
| 1321 | + * code otherwise. */ | ||
| 1322 | +static int action_poll(const char *name) | ||
| 1323 | +{ | ||
| 1324 | + buf_t out, b; | ||
| 1325 | + const char *j; | ||
| 1326 | + char args[NAME_SZ + 64]; | ||
| 1327 | + char state[64] = {0}; | ||
| 1328 | + long long interval = 0; | ||
| 1329 | + | ||
| 1330 | + cli_args(args, sizeof(args), name, 0, "--poll"); | ||
| 1331 | + | ||
| 1332 | + buf_init(&out); | ||
| 1333 | + { | ||
| 1334 | + int rc = run_capture(login_bin(), args, &out); | ||
| 1335 | + if (rc <= 0) { | ||
| 1336 | + buf_free(&out); | ||
| 1337 | + emit_error(200, "OK", "cli_unavailable", | ||
| 1338 | + "the login CLI is not on this node; install SCORPIOX CODE or set COPILOT_LOGIN_BIN"); | ||
| 1339 | + return 1; | ||
| 1340 | + } | ||
| 1341 | + } | ||
| 1342 | + j = last_json_line(&out); | ||
| 1343 | + if (!j) { | ||
| 1344 | + buf_free(&out); | ||
| 1345 | + emit_error(200, "OK", "poll_failed", "the login CLI returned no JSON"); | ||
| 1346 | + return 1; | ||
| 1347 | + } | ||
| 1348 | + { | ||
| 1349 | + const char *end = j + strlen(j); | ||
| 1350 | + int ok = json_bool_field(j, end, "ok", 0); | ||
| 1351 | + json_str_field(j, end, "state", state, sizeof(state)); | ||
| 1352 | + interval = json_num_field(j, end, "interval"); | ||
| 1353 | + | ||
| 1354 | + if (!ok) { | ||
| 1355 | + char detail[FIELD_SZ] = {0}; | ||
| 1356 | + char err[FIELD_SZ] = {0}; | ||
| 1357 | + json_str_field(j, end, "error", err, sizeof(err)); | ||
| 1358 | + json_str_field(j, end, "detail", detail, sizeof(detail)); | ||
| 1359 | + buf_free(&out); | ||
| 1360 | + emit_error(200, "OK", err[0] ? err : "poll_failed", | ||
| 1361 | + detail[0] ? detail : "the device login is no longer valid; start again"); | ||
| 1362 | + return 1; | ||
| 1363 | + } | ||
| 1364 | + buf_free(&out); | ||
| 1365 | + | ||
| 1366 | + if (strcmp(state, "done") == 0) { | ||
| 1367 | + status_t st; | ||
| 1368 | + collect_status(&st, name); | ||
| 1369 | + buf_init(&b); | ||
| 1370 | + buf_adds(&b, "{\"ok\":true,\"state\":\"done\","); | ||
| 1371 | + emit_status(&b, &st); | ||
| 1372 | + buf_adds(&b, "}\n"); | ||
| 1373 | + json_headers(); | ||
| 1374 | + fputs(buf_str(&b), stdout); | ||
| 1375 | + buf_free(&b); | ||
| 1376 | + return 0; | ||
| 1377 | + } | ||
| 1378 | + } | ||
| 1379 | + | ||
| 1380 | + buf_init(&b); | ||
| 1381 | + buf_adds(&b, "{\"ok\":true,\"state\":\"pending\","); | ||
| 1382 | + buf_addf(&b, "\"interval\":%lld}\n", interval > 0 ? interval : DEFAULT_INTERVAL); | ||
| 1383 | + json_headers(); | ||
| 1384 | + fputs(buf_str(&b), stdout); | ||
| 1385 | + buf_free(&b); | ||
| 1386 | + return 0; | ||
| 1387 | +} | ||
| 1388 | + | ||
| 1389 | +static int action_cancel(const char *name) | ||
| 1390 | +{ | ||
| 1391 | + buf_t out, b; | ||
| 1392 | + char args[NAME_SZ + 64]; | ||
| 1393 | + | ||
| 1394 | + cli_args(args, sizeof(args), name, 0, "--cancel"); | ||
| 1395 | + | ||
| 1396 | + buf_init(&out); | ||
| 1397 | + run_capture(login_bin(), args, &out); | ||
| 1398 | + buf_free(&out); | ||
| 1399 | + | ||
| 1400 | + buf_init(&b); | ||
| 1401 | + buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n"); | ||
| 1402 | + json_headers(); | ||
| 1403 | + fputs(buf_str(&b), stdout); | ||
| 1404 | + buf_free(&b); | ||
| 1405 | + return 0; | ||
| 1406 | +} | ||
| 1407 | + | ||
| 1408 | +/* Refresh: Copilot's CLI derives the short-lived JWT from the stored `gho_` | ||
| 1409 | + * token and caches it. Its stdout may quote token material, so the payload is | ||
| 1410 | + * read, then discarded. The new state is proven by re-reading the cache, not | ||
| 1411 | + * by the CLI's word. */ | ||
| 1412 | +static int action_refresh(const char *name) | ||
| 1413 | +{ | ||
| 1414 | + buf_t out, b; | ||
| 1415 | + char args[PATH_SZ + 96]; | ||
| 1416 | + char qpath[PATH_SZ * 2]; | ||
| 1417 | + char path[PATH_SZ]; | ||
| 1418 | + long long before; | ||
| 1419 | + int refreshed = 0; | ||
| 1420 | + status_t st; | ||
| 1421 | + | ||
| 1422 | + if (name && *name) account_path(name, path, sizeof(path)); | ||
| 1423 | + else creds_path(path, sizeof(path)); | ||
| 1424 | + | ||
| 1425 | + if (!file_exists(path)) { | ||
| 1426 | + buf_init(&b); | ||
| 1427 | + buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":"); | ||
| 1428 | + buf_json(&b, "there is no credentials file on this node; start a login first"); | ||
| 1429 | + buf_adds(&b, "}\n"); | ||
| 1430 | + json_headers(); | ||
| 1431 | + fputs(buf_str(&b), stdout); | ||
| 1432 | + buf_free(&b); | ||
| 1433 | + return 1; | ||
| 1434 | + } | ||
| 1435 | + | ||
| 1436 | + collect_status(&st, name); | ||
| 1437 | + before = st.expires_at; | ||
| 1438 | + | ||
| 1439 | + shell_quote_into(path, qpath, sizeof(qpath)); | ||
| 1440 | + /* --force: without it the CLI no-ops on a still-valid cached JWT and the | ||
| 1441 | + * user's button would do nothing. */ | ||
| 1442 | + snprintf(args, sizeof(args), "--credentials-file %s --force", qpath); | ||
| 1443 | + | ||
| 1444 | + buf_init(&out); | ||
| 1445 | + { | ||
| 1446 | + int rc = run_capture(refresh_bin(), args, &out); | ||
| 1447 | + if (rc <= 0) { | ||
| 1448 | + buf_free(&out); | ||
| 1449 | + emit_error(200, "OK", "cli_unavailable", | ||
| 1450 | + "the refresh CLI is not on this node; install SCORPIOX CODE or set COPILOT_REFRESH_BIN"); | ||
| 1451 | + return 1; | ||
| 1452 | + } | ||
| 1453 | + } | ||
| 1454 | + { | ||
| 1455 | + /* A failed grant is proven by the CLI's own answer, never by its | ||
| 1456 | + * absence: it prints {"access_token":...,"expires_at":...} on success | ||
| 1457 | + * and nothing but human text on failure. The payload is inspected for | ||
| 1458 | + * the key only and then discarded - no token byte ever reaches a | ||
| 1459 | + * response. */ | ||
| 1460 | + const char *j = last_json_line(&out); | ||
| 1461 | + char tok[8] = {0}; | ||
| 1462 | + refreshed = j && json_str_field(j, j + strlen(j), "access_token", tok, sizeof(tok)); | ||
| 1463 | + } | ||
| 1464 | + buf_free(&out); | ||
| 1465 | + | ||
| 1466 | + collect_status(&st, name); | ||
| 1467 | + if (!refreshed || !st.logged_in) { | ||
| 1468 | + buf_init(&b); | ||
| 1469 | + buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":"); | ||
| 1470 | + buf_json(&b, "the refresh CLI did not produce a usable token; sign in again"); | ||
| 1471 | + buf_adds(&b, "}\n"); | ||
| 1472 | + json_headers(); | ||
| 1473 | + fputs(buf_str(&b), stdout); | ||
| 1474 | + buf_free(&b); | ||
| 1475 | + return 1; | ||
| 1476 | + } | ||
| 1477 | + (void)before; | ||
| 1478 | + | ||
| 1479 | + buf_init(&b); | ||
| 1480 | + buf_adds(&b, "{\"ok\":true,\"refreshed\":true,"); | ||
| 1481 | + emit_status(&b, &st); | ||
| 1482 | + buf_adds(&b, "}\n"); | ||
| 1483 | + json_headers(); | ||
| 1484 | + fputs(buf_str(&b), stdout); | ||
| 1485 | + buf_free(&b); | ||
| 1486 | + return 0; | ||
| 1487 | +} | ||
| 1488 | + | ||
| 1489 | + | ||
| 1490 | +/* ------------------------------------------------------------------ */ | ||
| 1491 | +/* HTML emission */ | ||
| 1492 | +/* ------------------------------------------------------------------ */ | ||
| 1493 | + | ||
| 1494 | +/* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the | ||
| 1495 | + * split means the palette lives in exactly one place (bot_theme_plugin.h) and | ||
| 1496 | + * the page can never drift away from the bot's own theme. */ | ||
| 1497 | +static void emit_ui(void) | ||
| 1498 | +{ | ||
| 1499 | + const char *p = UI_HTML; | ||
| 1500 | + | ||
| 1501 | + while (*p) { | ||
| 1502 | + if (*p == '\001') { | ||
| 1503 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout); | ||
| 1504 | + p++; | ||
| 1505 | + } else if (*p == '\002') { | ||
| 1506 | + /* SX_BOT_THEME_HANDOFF and SX_BOT_THEME_TOGGLE_JS are both complete | ||
| 1507 | + * <script>...</script> strings, so they are emitted as siblings. | ||
| 1508 | + * Without the toggle macro the page's Theme button is inert: the | ||
| 1509 | + * bot owns the theme, but a plugin opened in its own tab needs a | ||
| 1510 | + * switch of its own. */ | ||
| 1511 | + fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout); | ||
| 1512 | + p++; | ||
| 1513 | + } else { | ||
| 1514 | + putchar(*p++); | ||
| 1515 | + } | ||
| 1516 | + } | ||
| 1517 | +} | ||
| 1518 | + | ||
| 1519 | +/* ------------------------------------------------------------------ */ | ||
| 1520 | +/* main */ | ||
| 1521 | +/* ------------------------------------------------------------------ */ | ||
| 1522 | + | ||
| 1523 | +int main(int argc, char **argv) | ||
| 1524 | +{ | ||
| 1525 | + const char *qs; | ||
| 1526 | + char action[64] = {0}; | ||
| 1527 | + char name[NAME_SZ] = {0}; | ||
| 1528 | + int force = 0; | ||
| 1529 | + | ||
| 1530 | + /* 1. Discovery metadata. Must stay unauthenticated. */ | ||
| 1531 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | ||
| 1532 | + puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); | ||
| 1533 | + return 0; | ||
| 1534 | + } | ||
| 1535 | + if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { | ||
| 1536 | + puts(PLUGIN_ID " " PLUGIN_VER); | ||
| 1537 | + return 0; | ||
| 1538 | + } | ||
| 1539 | + | ||
| 1540 | + require_node_auth(); | ||
| 1541 | + | ||
| 1542 | + qs = getenv("QUERY_STRING"); | ||
| 1543 | + if (!qs) qs = ""; | ||
| 1544 | + | ||
| 1545 | + get_query_val(qs, "name", name, sizeof(name)); | ||
| 1546 | + if (name[0] && !name_valid(name)) { | ||
| 1547 | + emit_error(400, "Bad Request", "bad_name", "account names use letters, digits, - _ . (max 64)"); | ||
| 1548 | + return 1; | ||
| 1549 | + } | ||
| 1550 | + { | ||
| 1551 | + char f[8] = {0}; | ||
| 1552 | + if (get_query_val(qs, "force", f, sizeof(f))) | ||
| 1553 | + force = (f[0] == '1' || f[0] == 't' || f[0] == 'T' || f[0] == 'y'); | ||
| 1554 | + } | ||
| 1555 | + | ||
| 1556 | + /* 2. JSON API mode. `format=json` alone means "status", which is what a | ||
| 1557 | + * dashboard polls. */ | ||
| 1558 | + if (query_has(qs, "action") || query_has(qs, "format")) { | ||
| 1559 | + char fmt[32] = {0}; | ||
| 1560 | + | ||
| 1561 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 1562 | + get_query_val(qs, "format", fmt, sizeof(fmt)); | ||
| 1563 | + if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status"); | ||
| 1564 | + | ||
| 1565 | + if (strcmp(action, "status") == 0 || !action[0]) return action_status(name); | ||
| 1566 | + if (strcmp(action, "start") == 0) return action_start(name, force); | ||
| 1567 | + if (strcmp(action, "poll") == 0) return action_poll(name); | ||
| 1568 | + if (strcmp(action, "cancel") == 0) return action_cancel(name); | ||
| 1569 | + if (strcmp(action, "refresh") == 0) return action_refresh(name); | ||
| 1570 | + if (strcmp(action, "accounts") == 0) return action_accounts(name); | ||
| 1571 | + emit_error(404, "Not Found", "unknown_action", action); | ||
| 1572 | + return 1; | ||
| 1573 | + } | ||
| 1574 | + | ||
| 1575 | + /* 3. HTML UI. UI_HTML carries two control bytes: 0x01 is the theme block | ||
| 1576 | + * (<style> with the bot tokens) and 0x02 is the handoff script before | ||
| 1577 | + * </body>. */ | ||
| 1578 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1579 | + "Cache-Control: no-store\r\n" | ||
| 1580 | + "X-Content-Type-Options: nosniff\r\n" | ||
| 1581 | + "Referrer-Policy: no-referrer\r\n" | ||
| 1582 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | ||
| 1583 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | ||
| 1584 | + "base-uri 'none'; form-action 'none'; frame-ancestors *\r\n\r\n", stdout); | ||
| 1585 | + emit_ui(); | ||
| 1586 | + return 0; | ||
| 1587 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..113d374 | index 0000000..113d374 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,407 @@ | @@ -0,0 +1,407 @@ | ||
| 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>copilot</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 | +.badge{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:600; | ||
| 27 | + padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text); | ||
| 28 | + border:1px solid var(--line);font-family:var(--mono);max-width:100%;overflow:hidden; | ||
| 29 | + text-overflow:ellipsis;white-space:nowrap} | ||
| 30 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | ||
| 31 | + padding:16px;margin-bottom:12px} | ||
| 32 | +.card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em; | ||
| 33 | + text-transform:uppercase;color:var(--text-2)} | ||
| 34 | +.card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)} | ||
| 35 | +.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap} | ||
| 36 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px; | ||
| 37 | + font-weight:600;font-size:13px;cursor:pointer;font-family:inherit; | ||
| 38 | + transition:transform .12s var(--ease),opacity .12s} | ||
| 39 | +.btn:active{transform:scale(.98)} | ||
| 40 | +.btn:disabled{opacity:.5;cursor:default} | ||
| 41 | +.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)} | ||
| 42 | +.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)} | ||
| 43 | +.btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)} | ||
| 44 | +a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none} | ||
| 45 | +.kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px} | ||
| 46 | +.kv .k{color:var(--text-2);font-size:12px} | ||
| 47 | +.kv .v{font-family:var(--mono);font-size:12px;word-break:break-all} | ||
| 48 | +.kv .v.plain{font-family:var(--font);font-size:13px} | ||
| 49 | +.step{display:none} | ||
| 50 | +.step.on{display:block} | ||
| 51 | +.hint{margin:10px 0 0;font-size:12px;color:var(--text-2)} | ||
| 52 | +.note{font-size:12.5px;margin-top:10px;display:none} | ||
| 53 | +.note.show{display:block} | ||
| 54 | +.note.err{color:var(--red)} | ||
| 55 | +.note.ok{color:var(--green)} | ||
| 56 | +.usercode{font-family:var(--mono);font-size:34px;font-weight:700;letter-spacing:.16em; | ||
| 57 | + color:var(--text);background:var(--code-bg);border:1px solid var(--line-2); | ||
| 58 | + border-radius:12px;padding:16px 10px;margin-top:12px;text-align:center; | ||
| 59 | + word-break:break-all;user-select:all} | ||
| 60 | +.count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1} | ||
| 61 | +.count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0} | ||
| 62 | +.wait{display:flex;align-items:center;gap:9px;margin-top:12px;font-size:12.5px; | ||
| 63 | + color:var(--text-2)} | ||
| 64 | +.wait .spin{display:inline-block;width:13px;height:13px;border-radius:50%; | ||
| 65 | + border:2px solid var(--line-2);border-top-color:var(--blue);animation:sp .8s linear infinite} | ||
| 66 | +@keyframes sp{to{transform:rotate(360deg)}} | ||
| 67 | +.spin2{width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35); | ||
| 68 | + border-top-color:#fff;display:none;animation:sp .7s linear infinite} | ||
| 69 | +.btn.loading .spin2{display:inline-block} | ||
| 70 | +.acct{display:flex;align-items:center;gap:10px;padding:9px 0;border-top:1px solid var(--line); | ||
| 71 | + font-size:13px} | ||
| 72 | +.acct:first-child{border-top:0} | ||
| 73 | +.acct .nm{font-family:var(--mono);font-size:12.5px;flex:1 1 auto;min-width:0; | ||
| 74 | + overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| 75 | +.acct .tag{font-size:11px;font-weight:650;padding:3px 9px;border-radius:999px; | ||
| 76 | + background:var(--surface-2);color:var(--text-2);white-space:nowrap} | ||
| 77 | +.acct .tag.ok{color:var(--green)} | ||
| 78 | +.acct .tag.warn{color:var(--orange)} | ||
| 79 | +.empty{font-size:12.5px;color:var(--text-2)} | ||
| 80 | +.toast{position:fixed;left:50%;bottom:24px;transform:translate(-50%,12px);opacity:0; | ||
| 81 | + pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2); | ||
| 82 | + color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px; | ||
| 83 | + box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease); | ||
| 84 | + z-index:9;max-width:calc(100vw - 32px)} | ||
| 85 | +.toast.show{opacity:1;transform:translate(-50%,0)} | ||
| 86 | +#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text); | ||
| 87 | + border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer; | ||
| 88 | + font-family:inherit} | ||
| 89 | +@media (max-width:520px){ | ||
| 90 | + #app{padding:12px 12px 32px} | ||
| 91 | + .kv{grid-template-columns:1fr;gap:2px 0} | ||
| 92 | + .kv .k{margin-top:8px} | ||
| 93 | + .card{padding:13px;border-radius:12px} | ||
| 94 | + .count{font-size:28px} | ||
| 95 | + .usercode{font-size:27px;letter-spacing:.1em;padding:14px 6px} | ||
| 96 | +} | ||
| 97 | +</style> | ||
| 98 | +</head> | ||
| 99 | +<body> | ||
| 100 | +<div id="app"> | ||
| 101 | + <div class="hd"> | ||
| 102 | + <div class="grow"> | ||
| 103 | + <h1>GitHub Copilot</h1> | ||
| 104 | + <div class="sub" id="sub">Device code login on this node</div> | ||
| 105 | + </div> | ||
| 106 | + <span class="badge" id="userBadge" style="display:none"></span> | ||
| 107 | + <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span> | ||
| 108 | + <button id="themeToggle" class="embed-hide" type="button">Theme</button> | ||
| 109 | + </div> | ||
| 110 | + | ||
| 111 | + <div class="card"> | ||
| 112 | + <h2>Session</h2> | ||
| 113 | + <p class="lead" id="sessionLead">Reading the local Copilot credentials.</p> | ||
| 114 | + <div class="kv" id="session"></div> | ||
| 115 | + <div class="row" style="margin-top:14px"> | ||
| 116 | + <button class="btn ghost" id="btnRefresh" type="button"><span class="spin2"></span>Refresh Token Now</button> | ||
| 117 | + <button class="btn ghost" id="btnReload" type="button">Reload</button> | ||
| 118 | + </div> | ||
| 119 | + <div class="note" id="refreshNote"></div> | ||
| 120 | + </div> | ||
| 121 | + | ||
| 122 | + <div class="card"> | ||
| 123 | + <h2>Device login</h2> | ||
| 124 | + <p class="lead">Sign in with GitHub. The login CLI opens the device flow and writes the | ||
| 125 | + credential file on this node; no token ever passes through this page.</p> | ||
| 126 | + | ||
| 127 | + <div class="step on" id="step1"> | ||
| 128 | + <div class="row"> | ||
| 129 | + <button class="btn" id="btnStart" type="button">Start GitHub Copilot Login</button> | ||
| 130 | + </div> | ||
| 131 | + <p class="hint">This asks GitHub for a one-time code. Nothing is stored until you approve | ||
| 132 | + it in the browser.</p> | ||
| 133 | + <div class="note" id="startNote"></div> | ||
| 134 | + </div> | ||
| 135 | + | ||
| 136 | + <div class="step" id="step2"> | ||
| 137 | + <p class="hint" style="margin-top:0">Enter this code at | ||
| 138 | + <span style="font-family:var(--mono)">github.com/login/device</span>:</p> | ||
| 139 | + <div class="usercode" id="userCode">----</div> | ||
| 140 | + <div class="row" style="margin-top:12px"> | ||
| 141 | + <button class="btn" id="btnCopyOpen" type="button">Copy Code & Open GitHub</button> | ||
| 142 | + <a class="btn ghost" id="linkOpen" href="https://github.com/login/device" | ||
| 143 | + target="_blank" rel="noopener noreferrer">Open GitHub</a> | ||
| 144 | + <button class="btn danger" id="btnCancel" type="button">Cancel</button> | ||
| 145 | + </div> | ||
| 146 | + <div class="wait" id="waitBox"><span class="spin"></span> | ||
| 147 | + <span id="waitText">Waiting for GitHub confirmation...</span></div> | ||
| 148 | + <div class="note" id="loginNote"></div> | ||
| 149 | + </div> | ||
| 150 | + </div> | ||
| 151 | + | ||
| 152 | + <div class="card"> | ||
| 153 | + <h2>Named accounts</h2> | ||
| 154 | + <p class="lead">Every account file in the local accounts directory.</p> | ||
| 155 | + <div id="accounts"><div class="empty">No named accounts.</div></div> | ||
| 156 | + </div> | ||
| 157 | +</div> | ||
| 158 | + | ||
| 159 | +<div class="toast" id="toast"></div> | ||
| 160 | + | ||
| 161 | +<script> | ||
| 162 | +var q=new URLSearchParams(location.search); | ||
| 163 | +var node=q.get('node')||''; | ||
| 164 | +var sid=q.get('id')||''; | ||
| 165 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | ||
| 166 | + localStorage.getItem('bot_active_pwd')||''; | ||
| 167 | + | ||
| 168 | +/* Two call routes. Getting this wrong is the most common plugin bug: | ||
| 169 | + * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..) | ||
| 170 | + * -> call the hub proxy back: /plugins?plugin=plugin_copilot_login&action=.. | ||
| 171 | + * opened directly on the node | ||
| 172 | + * -> the plugin itself is the route: /plugin_copilot_login?action=.. | ||
| 173 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | ||
| 174 | +var HUB=q.get('plugin')||''; | ||
| 175 | +function url(action,extra){ | ||
| 176 | + return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_copilot_login')+ | ||
| 177 | + '?action='+encodeURIComponent(action)+ | ||
| 178 | + (extra?('&'+extra):'')+ | ||
| 179 | + (node?'&node='+encodeURIComponent(node):'')+ | ||
| 180 | + (sid?'&id='+encodeURIComponent(sid):'')+ | ||
| 181 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | ||
| 182 | +} | ||
| 183 | +function hdr(){ | ||
| 184 | + var h={}; | ||
| 185 | + if(pwd)h['X-Bot-Password']=pwd; | ||
| 186 | + return h; | ||
| 187 | +} | ||
| 188 | +function api(action,extra){ | ||
| 189 | + return fetch(url(action,extra),{headers:hdr()}).then(function(r){ | ||
| 190 | + return r.json().catch(function(){return {ok:false,error:'bad response'};}); | ||
| 191 | + }); | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +var $=function(id){return document.getElementById(id);}; | ||
| 195 | +function toast(msg){ | ||
| 196 | + var t=$('toast');t.textContent=msg;t.classList.add('show'); | ||
| 197 | + clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200); | ||
| 198 | +} | ||
| 199 | +function note(el,msg,kind){ | ||
| 200 | + el.textContent=msg||''; | ||
| 201 | + el.className='note'+(msg?' show '+(kind||''):''); | ||
| 202 | +} | ||
| 203 | +function kv(el,rows){ | ||
| 204 | + el.innerHTML=''; | ||
| 205 | + rows.forEach(function(r){ | ||
| 206 | + var a=document.createElement('div');a.className='k';a.textContent=r[0]; | ||
| 207 | + var b=document.createElement('div');b.className='v'+(r[2]?' plain':''); | ||
| 208 | + b.textContent=r[1];el.appendChild(a);el.appendChild(b); | ||
| 209 | + }); | ||
| 210 | +} | ||
| 211 | +function fmtExpiry(sec){ | ||
| 212 | + if(typeof sec!=='number')return '-'; | ||
| 213 | + if(sec<=0)return 'expired'; | ||
| 214 | + if(sec<90)return sec+'s'; | ||
| 215 | + if(sec<5400)return Math.round(sec/60)+' min'; | ||
| 216 | + if(sec<172800)return Math.round(sec/3600)+' h'; | ||
| 217 | + if(sec<63072000)return Math.round(sec/86400)+' d'; | ||
| 218 | + return Math.round(sec/31536000)+' yr'; | ||
| 219 | +} | ||
| 220 | +function setPill(st){ | ||
| 221 | + var p=$('pill'),t=$('pillText'); | ||
| 222 | + if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';} | ||
| 223 | + else if(st.logged_in){p.className='pill ok';t.textContent='Connected';} | ||
| 224 | + else if(st.pending){p.className='pill warn';t.textContent='Signing in';} | ||
| 225 | + else {p.className='pill off';t.textContent='Not Connected';} | ||
| 226 | +} | ||
| 227 | +function render(st){ | ||
| 228 | + setPill(st); | ||
| 229 | + var badge=$('userBadge'); | ||
| 230 | + if(st.logged_in&&st.user){badge.style.display='';badge.textContent='@'+st.user;} | ||
| 231 | + else badge.style.display='none'; | ||
| 232 | + $('sub').textContent=st.account&&st.account!=='default' | ||
| 233 | + ? 'Device code login - '+st.account : 'Device code login on this node'; | ||
| 234 | + | ||
| 235 | + if(st.logged_in){ | ||
| 236 | + $('sessionLead').textContent=st.expired | ||
| 237 | + ? 'A Copilot session is stored but its derived token has expired. Use Refresh Token Now.' | ||
| 238 | + : 'This node holds a GitHub Copilot session.'; | ||
| 239 | + }else{ | ||
| 240 | + $('sessionLead').textContent='No Copilot session on this node yet. Start a login below.'; | ||
| 241 | + } | ||
| 242 | + | ||
| 243 | + kv($('session'),[ | ||
| 244 | + ['Account', st.account||'-', true], | ||
| 245 | + ['GitHub user', st.user||'-', true], | ||
| 246 | + ['Logged in', st.logged_in?'yes':'no', true], | ||
| 247 | + ['Derived token', st.logged_in?(st.expired?'expired':'valid'):'-', true], | ||
| 248 | + ['Token expires', st.logged_in&&st.cache_present?fmtExpiry(st.expires_in_sec):'-', true], | ||
| 249 | + ['Login pending', st.pending?'yes':'no', true], | ||
| 250 | + ['Login CLI', st.cli_present?'found':'not found', true], | ||
| 251 | + ['Scope', st.scope||'-', true], | ||
| 252 | + ['Profile model', st.profile_exists?(st.profile||'-'):'not created', true], | ||
| 253 | + ['Credentials', st.credentials_path||'-'] | ||
| 254 | + ]); | ||
| 255 | + | ||
| 256 | + var box=$('accounts'); | ||
| 257 | + box.innerHTML=''; | ||
| 258 | + var list=st.accounts||[]; | ||
| 259 | + if(!list.length){ | ||
| 260 | + var e=document.createElement('div');e.className='empty'; | ||
| 261 | + e.textContent='No named accounts.';box.appendChild(e); | ||
| 262 | + }else{ | ||
| 263 | + list.forEach(function(a){ | ||
| 264 | + var row=document.createElement('div');row.className='acct'; | ||
| 265 | + var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name; | ||
| 266 | + var tg=document.createElement('div'); | ||
| 267 | + tg.className='tag '+(a.logged_in?(a.expired?'warn':'ok'):''); | ||
| 268 | + tg.textContent=a.logged_in?(a.expired?'expired':'valid'):'no token'; | ||
| 269 | + row.appendChild(nm);row.appendChild(tg);box.appendChild(row); | ||
| 270 | + }); | ||
| 271 | + } | ||
| 272 | + | ||
| 273 | + if(st.pending){showStep2();} | ||
| 274 | +} | ||
| 275 | +function load(){ | ||
| 276 | + return api('status').then(function(d){ | ||
| 277 | + if(d&&d.ok)render(d); | ||
| 278 | + else toast((d&&d.error)||'status failed'); | ||
| 279 | + }).catch(function(e){toast('Status failed: '+e.message);}); | ||
| 280 | +} | ||
| 281 | + | ||
| 282 | +/* ---- device flow ---- */ | ||
| 283 | +var userCode='',VerifyUrl='https://github.com/login/device'; | ||
| 284 | +var pollTimer=null,pollInterval=5,pollStop=0; | ||
| 285 | + | ||
| 286 | +function showStep2(){ | ||
| 287 | + $('step1').classList.remove('on'); | ||
| 288 | + $('step2').classList.add('on'); | ||
| 289 | +} | ||
| 290 | +function hideStep2(){ | ||
| 291 | + $('step1').classList.add('on'); | ||
| 292 | + $('step2').classList.remove('on'); | ||
| 293 | +} | ||
| 294 | +function stopPolling(){ | ||
| 295 | + if(pollTimer){clearTimeout(pollTimer);pollTimer=null;} | ||
| 296 | +} | ||
| 297 | +function startPolling(){ | ||
| 298 | + stopPolling(); | ||
| 299 | + $('waitBox').style.display=''; | ||
| 300 | + $('waitText').textContent='Waiting for GitHub confirmation...'; | ||
| 301 | + var delay=Math.max(3,pollInterval||5)*1000; | ||
| 302 | + pollTimer=setTimeout(function(){ | ||
| 303 | + api('poll').then(function(d){ | ||
| 304 | + if(d&&d.ok&&d.state==='done'){ | ||
| 305 | + stopPolling(); | ||
| 306 | + $('waitText').textContent='Authorized.'; | ||
| 307 | + note($('loginNote'),'Signed in'+(d.user?(' as @'+d.user):'')+'.','ok'); | ||
| 308 | + hideStep2(); | ||
| 309 | + render(d); | ||
| 310 | + toast('GitHub Copilot connected'); | ||
| 311 | + return; | ||
| 312 | + } | ||
| 313 | + if(!d||!d.ok){ | ||
| 314 | + stopPolling(); | ||
| 315 | + $('waitBox').style.display='none'; | ||
| 316 | + var m=(d&&(d.detail||d.error))||'poll failed'; | ||
| 317 | + note($('loginNote'),m,'err'); | ||
| 318 | + return; | ||
| 319 | + } | ||
| 320 | + if(d.interval)pollInterval=d.interval; | ||
| 321 | + pollTimer=setTimeout(function(){startPolling();},Math.max(3,pollInterval)*1000); | ||
| 322 | + }).catch(function(e){ | ||
| 323 | + note($('loginNote'),'Poll failed: '+e.message,'err'); | ||
| 324 | + pollTimer=setTimeout(function(){startPolling();},Math.max(5,pollInterval)*1000); | ||
| 325 | + }); | ||
| 326 | + },delay); | ||
| 327 | +} | ||
| 328 | + | ||
| 329 | +function startLogin(){ | ||
| 330 | + var b=$('btnStart'); | ||
| 331 | + b.disabled=true;b.classList.add('loading'); | ||
| 332 | + note($('startNote'),'Asking GitHub for a device code...'); | ||
| 333 | + api('start').then(function(d){ | ||
| 334 | + b.disabled=false;b.classList.remove('loading'); | ||
| 335 | + note($('startNote'),''); | ||
| 336 | + if(!d||!d.ok){ | ||
| 337 | + note($('startNote'),(d&&(d.detail||d.error))||'start failed','err'); | ||
| 338 | + return; | ||
| 339 | + } | ||
| 340 | + userCode=d.user_code||''; | ||
| 341 | + VerifyUrl=d.verify_url||'https://github.com/login/device'; | ||
| 342 | + $('userCode').textContent=userCode||'----'; | ||
| 343 | + $('linkOpen').setAttribute('href',VerifyUrl); | ||
| 344 | + pollInterval=d.interval||5; | ||
| 345 | + showStep2(); | ||
| 346 | + note($('loginNote'),''); | ||
| 347 | + startPolling(); | ||
| 348 | + }).catch(function(e){ | ||
| 349 | + b.disabled=false;b.classList.remove('loading'); | ||
| 350 | + note($('startNote'),'Start failed: '+e.message,'err'); | ||
| 351 | + }); | ||
| 352 | +} | ||
| 353 | + | ||
| 354 | +function copyOpen(){ | ||
| 355 | + var go=function(){window.open(VerifyUrl,'_blank','noopener');}; | ||
| 356 | + if(navigator.clipboard&&navigator.clipboard.writeText){ | ||
| 357 | + navigator.clipboard.writeText(userCode).then(function(){ | ||
| 358 | + toast('Code copied: '+userCode);go(); | ||
| 359 | + }).catch(function(){toast('Copy failed - select the code manually');go();}); | ||
| 360 | + }else{ | ||
| 361 | + try{ | ||
| 362 | + var r=document.createRange();r.selectNodeContents($('userCode')); | ||
| 363 | + var s=window.getSelection();s.removeAllRanges();s.addRange(r); | ||
| 364 | + document.execCommand('copy'); | ||
| 365 | + toast('Code copied: '+userCode); | ||
| 366 | + }catch(e){toast('Copy not available - select the code manually');} | ||
| 367 | + go(); | ||
| 368 | + } | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +function cancelLogin(){ | ||
| 372 | + stopPolling(); | ||
| 373 | + api('cancel').then(function(){ | ||
| 374 | + hideStep2(); | ||
| 375 | + $('waitBox').style.display=''; | ||
| 376 | + note($('loginNote'),''); | ||
| 377 | + toast('Pending login cancelled'); | ||
| 378 | + load(); | ||
| 379 | + }).catch(function(e){toast('Cancel failed: '+e.message);}); | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +function refreshToken(){ | ||
| 383 | + var b=$('btnRefresh'); | ||
| 384 | + b.disabled=true;b.classList.add('loading'); | ||
| 385 | + note($('refreshNote'),'Asking Copilot for a new derived token...'); | ||
| 386 | + api('refresh').then(function(d){ | ||
| 387 | + b.disabled=false;b.classList.remove('loading'); | ||
| 388 | + if(!d||!d.ok){ | ||
| 389 | + note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err'); | ||
| 390 | + return; | ||
| 391 | + } | ||
| 392 | + note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok'); | ||
| 393 | + render(d); | ||
| 394 | + }).catch(function(e){ | ||
| 395 | + b.disabled=false;b.classList.remove('loading'); | ||
| 396 | + note($('refreshNote'),'Refresh failed: '+e.message,'err'); | ||
| 397 | + }); | ||
| 398 | +} | ||
| 399 | + | ||
| 400 | +$('btnStart').onclick=startLogin; | ||
| 401 | +$('btnCopyOpen').onclick=copyOpen; | ||
| 402 | +$('btnCancel').onclick=cancelLogin; | ||
| 403 | +$('btnRefresh').onclick=refreshToken; | ||
| 404 | +$('btnReload').onclick=load; | ||
| 405 | +load(); | ||
| 406 | +</script> | ||
| 407 | +</body></html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..97db5b6 | index 0000000..97db5b6 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,415 @@ | @@ -0,0 +1,415 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_CPLOGIN_UI_HTML_H | ||
| 3 | +#define SX_CPLOGIN_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>copilot</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 | + ".badge{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:600;\n" | ||
| 32 | + " padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text);\n" | ||
| 33 | + " border:1px solid var(--line);font-family:var(--mono);max-width:100%;overflow:hidden;\n" | ||
| 34 | + " text-overflow:ellipsis;white-space:nowrap}\n" | ||
| 35 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | ||
| 36 | + " padding:16px;margin-bottom:12px}\n" | ||
| 37 | + ".card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;\n" | ||
| 38 | + " text-transform:uppercase;color:var(--text-2)}\n" | ||
| 39 | + ".card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}\n" | ||
| 40 | + ".row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n" | ||
| 41 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;\n" | ||
| 42 | + " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;\n" | ||
| 43 | + " transition:transform .12s var(--ease),opacity .12s}\n" | ||
| 44 | + ".btn:active{transform:scale(.98)}\n" | ||
| 45 | + ".btn:disabled{opacity:.5;cursor:default}\n" | ||
| 46 | + ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n" | ||
| 47 | + ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | ||
| 48 | + ".btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}\n" | ||
| 49 | + "a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}\n" | ||
| 50 | + ".kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}\n" | ||
| 51 | + ".kv .k{color:var(--text-2);font-size:12px}\n" | ||
| 52 | + ".kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}\n" | ||
| 53 | + ".kv .v.plain{font-family:var(--font);font-size:13px}\n" | ||
| 54 | + ".step{display:none}\n" | ||
| 55 | + ".step.on{display:block}\n" | ||
| 56 | + ".hint{margin:10px 0 0;font-size:12px;color:var(--text-2)}\n" | ||
| 57 | + ".note{font-size:12.5px;margin-top:10px;display:none}\n" | ||
| 58 | + ".note.show{display:block}\n" | ||
| 59 | + ".note.err{color:var(--red)}\n" | ||
| 60 | + ".note.ok{color:var(--green)}\n" | ||
| 61 | + ".usercode{font-family:var(--mono);font-size:34px;font-weight:700;letter-spacing:.16em;\n" | ||
| 62 | + " color:var(--text);background:var(--code-bg);border:1px solid var(--line-2);\n" | ||
| 63 | + " border-radius:12px;padding:16px 10px;margin-top:12px;text-align:center;\n" | ||
| 64 | + " word-break:break-all;user-select:all}\n" | ||
| 65 | + ".count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}\n" | ||
| 66 | + ".count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}\n" | ||
| 67 | + ".wait{display:flex;align-items:center;gap:9px;margin-top:12px;font-size:12.5px;\n" | ||
| 68 | + " color:var(--text-2)}\n" | ||
| 69 | + ".wait .spin{display:inline-block;width:13px;height:13px;border-radius:50%;\n" | ||
| 70 | + " border:2px solid var(--line-2);border-top-color:var(--blue);animation:sp .8s linear infinite}\n" | ||
| 71 | + "@keyframes sp{to{transform:rotate(360deg)}}\n" | ||
| 72 | + ".spin2{width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35);\n" | ||
| 73 | + " border-top-color:#fff;display:none;animation:sp .7s linear infinite}\n" | ||
| 74 | + ".btn.loading .spin2{display:inline-block}\n" | ||
| 75 | + ".acct{display:flex;align-items:center;gap:10px;padding:9px 0;border-top:1px solid var(--line);\n" | ||
| 76 | + " font-size:13px}\n" | ||
| 77 | + ".acct:first-child{border-top:0}\n" | ||
| 78 | + ".acct .nm{font-family:var(--mono);font-size:12.5px;flex:1 1 auto;min-width:0;\n" | ||
| 79 | + " overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | ||
| 80 | + ".acct .tag{font-size:11px;font-weight:650;padding:3px 9px;border-radius:999px;\n" | ||
| 81 | + " background:var(--surface-2);color:var(--text-2);white-space:nowrap}\n" | ||
| 82 | + ".acct .tag.ok{color:var(--green)}\n" | ||
| 83 | + ".acct .tag.warn{color:var(--orange)}\n" | ||
| 84 | + ".empty{font-size:12.5px;color:var(--text-2)}\n" | ||
| 85 | + ".toast{position:fixed;left:50%;bottom:24px;transform:translate(-50%,12px);opacity:0;\n" | ||
| 86 | + " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n" | ||
| 87 | + " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n" | ||
| 88 | + " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n" | ||
| 89 | + " z-index:9;max-width:calc(100vw - 32px)}\n" | ||
| 90 | + ".toast.show{opacity:1;transform:translate(-50%,0)}\n" | ||
| 91 | + "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | ||
| 92 | + " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n" | ||
| 93 | + " font-family:inherit}\n" | ||
| 94 | + "@media (max-width:520px){\n" | ||
| 95 | + " #app{padding:12px 12px 32px}\n" | ||
| 96 | + " .kv{grid-template-columns:1fr;gap:2px 0}\n" | ||
| 97 | + " .kv .k{margin-top:8px}\n" | ||
| 98 | + " .card{padding:13px;border-radius:12px}\n" | ||
| 99 | + " .count{font-size:28px}\n" | ||
| 100 | + " .usercode{font-size:27px;letter-spacing:.1em;padding:14px 6px}\n" | ||
| 101 | + "}\n" | ||
| 102 | + "</style>\n" | ||
| 103 | + "</head>\n" | ||
| 104 | + "<body>\n" | ||
| 105 | + "<div id=\"app\">\n" | ||
| 106 | + " <div class=\"hd\">\n" | ||
| 107 | + " <div class=\"grow\">\n" | ||
| 108 | + " <h1>GitHub Copilot</h1>\n" | ||
| 109 | + " <div class=\"sub\" id=\"sub\">Device code login on this node</div>\n" | ||
| 110 | + " </div>\n" | ||
| 111 | + " <span class=\"badge\" id=\"userBadge\" style=\"display:none\"></span>\n" | ||
| 112 | + " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n" | ||
| 113 | + " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n" | ||
| 114 | + " </div>\n" | ||
| 115 | + "\n" | ||
| 116 | + " <div class=\"card\">\n" | ||
| 117 | + " <h2>Session</h2>\n" | ||
| 118 | + " <p class=\"lead\" id=\"sessionLead\">Reading the local Copilot credentials.</p>\n" | ||
| 119 | + " <div class=\"kv\" id=\"session\"></div>\n" | ||
| 120 | + " <div class=\"row\" style=\"margin-top:14px\">\n" | ||
| 121 | + " <button class=\"btn ghost\" id=\"btnRefresh\" type=\"button\"><span class=\"spin2\"></span>Refresh Token Now</button>\n" | ||
| 122 | + " <button class=\"btn ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n" | ||
| 123 | + " </div>\n" | ||
| 124 | + " <div class=\"note\" id=\"refreshNote\"></div>\n" | ||
| 125 | + " </div>\n" | ||
| 126 | + "\n" | ||
| 127 | + " <div class=\"card\">\n" | ||
| 128 | + " <h2>Device login</h2>\n" | ||
| 129 | + " <p class=\"lead\">Sign in with GitHub. The login CLI opens the device flow and writes the\n" | ||
| 130 | + " credential file on this node; no token ever passes through this page.</p>\n" | ||
| 131 | + "\n" | ||
| 132 | + " <div class=\"step on\" id=\"step1\">\n" | ||
| 133 | + " <div class=\"row\">\n" | ||
| 134 | + " <button class=\"btn\" id=\"btnStart\" type=\"button\">Start GitHub Copilot Login</button>\n" | ||
| 135 | + " </div>\n" | ||
| 136 | + " <p class=\"hint\">This asks GitHub for a one-time code. Nothing is stored until you approve\n" | ||
| 137 | + " it in the browser.</p>\n" | ||
| 138 | + " <div class=\"note\" id=\"startNote\"></div>\n" | ||
| 139 | + " </div>\n" | ||
| 140 | + "\n" | ||
| 141 | + " <div class=\"step\" id=\"step2\">\n" | ||
| 142 | + " <p class=\"hint\" style=\"margin-top:0\">Enter this code at\n" | ||
| 143 | + " <span style=\"font-family:var(--mono)\">github.com/login/device</span>:</p>\n" | ||
| 144 | + " <div class=\"usercode\" id=\"userCode\">----</div>\n" | ||
| 145 | + " <div class=\"row\" style=\"margin-top:12px\">\n" | ||
| 146 | + " <button class=\"btn\" id=\"btnCopyOpen\" type=\"button\">Copy Code & Open GitHub</button>\n" | ||
| 147 | + " <a class=\"btn ghost\" id=\"linkOpen\" href=\"https://github.com/login/device\"\n" | ||
| 148 | + " target=\"_blank\" rel=\"noopener noreferrer\">Open GitHub</a>\n" | ||
| 149 | + " <button class=\"btn danger\" id=\"btnCancel\" type=\"button\">Cancel</button>\n" | ||
| 150 | + " </div>\n" | ||
| 151 | + " <div class=\"wait\" id=\"waitBox\"><span class=\"spin\"></span>\n" | ||
| 152 | + " <span id=\"waitText\">Waiting for GitHub confirmation...</span></div>\n" | ||
| 153 | + " <div class=\"note\" id=\"loginNote\"></div>\n" | ||
| 154 | + " </div>\n" | ||
| 155 | + " </div>\n" | ||
| 156 | + "\n" | ||
| 157 | + " <div class=\"card\">\n" | ||
| 158 | + " <h2>Named accounts</h2>\n" | ||
| 159 | + " <p class=\"lead\">Every account file in the local accounts directory.</p>\n" | ||
| 160 | + " <div id=\"accounts\"><div class=\"empty\">No named accounts.</div></div>\n" | ||
| 161 | + " </div>\n" | ||
| 162 | + "</div>\n" | ||
| 163 | + "\n" | ||
| 164 | + "<div class=\"toast\" id=\"toast\"></div>\n" | ||
| 165 | + "\n" | ||
| 166 | + "<script>\n" | ||
| 167 | + "var q=new URLSearchParams(location.search);\n" | ||
| 168 | + "var node=q.get('node')||'';\n" | ||
| 169 | + "var sid=q.get('id')||'';\n" | ||
| 170 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | ||
| 171 | + " localStorage.getItem('bot_active_pwd')||'';\n" | ||
| 172 | + "\n" | ||
| 173 | + "/* Two call routes. Getting this wrong is the most common plugin bug:\n" | ||
| 174 | + " * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)\n" | ||
| 175 | + " * -> call the hub proxy back: /plugins?plugin=plugin_copilot_login&action=..\n" | ||
| 176 | + " * opened directly on the node\n" | ||
| 177 | + " * -> the plugin itself is the route: /plugin_copilot_login?action=..\n" | ||
| 178 | + " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n" | ||
| 179 | + "var HUB=q.get('plugin')||'';\n" | ||
| 180 | + "function url(action,extra){\n" | ||
| 181 | + " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_copilot_login')+\n" | ||
| 182 | + " '?action='+encodeURIComponent(action)+\n" | ||
| 183 | + " (extra?('&'+extra):'')+\n" | ||
| 184 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | ||
| 185 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | ||
| 186 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | ||
| 187 | + "}\n" | ||
| 188 | + "function hdr(){\n" | ||
| 189 | + " var h={};\n" | ||
| 190 | + " if(pwd)h['X-Bot-Password']=pwd;\n" | ||
| 191 | + " return h;\n" | ||
| 192 | + "}\n" | ||
| 193 | + "function api(action,extra){\n" | ||
| 194 | + " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n" | ||
| 195 | + " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n" | ||
| 196 | + " });\n" | ||
| 197 | + "}\n" | ||
| 198 | + "\n" | ||
| 199 | + "var $=function(id){return document.getElementById(id);};\n" | ||
| 200 | + "function toast(msg){\n" | ||
| 201 | + " var t=$('toast');t.textContent=msg;t.classList.add('show');\n" | ||
| 202 | + " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n" | ||
| 203 | + "}\n" | ||
| 204 | + "function note(el,msg,kind){\n" | ||
| 205 | + " el.textContent=msg||'';\n" | ||
| 206 | + " el.className='note'+(msg?' show '+(kind||''):'');\n" | ||
| 207 | + "}\n" | ||
| 208 | + "function kv(el,rows){\n" | ||
| 209 | + " el.innerHTML='';\n" | ||
| 210 | + " rows.forEach(function(r){\n" | ||
| 211 | + " var a=document.createElement('div');a.className='k';a.textContent=r[0];\n" | ||
| 212 | + " var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');\n" | ||
| 213 | + " b.textContent=r[1];el.appendChild(a);el.appendChild(b);\n" | ||
| 214 | + " });\n" | ||
| 215 | + "}\n" | ||
| 216 | + "function fmtExpiry(sec){\n" | ||
| 217 | + " if(typeof sec!=='number')return '-';\n" | ||
| 218 | + " if(sec<=0)return 'expired';\n" | ||
| 219 | + " if(sec<90)return sec+'s';\n" | ||
| 220 | + " if(sec<5400)return Math.round(sec/60)+' min';\n" | ||
| 221 | + " if(sec<172800)return Math.round(sec/3600)+' h';\n" | ||
| 222 | + " if(sec<63072000)return Math.round(sec/86400)+' d';\n" | ||
| 223 | + " return Math.round(sec/31536000)+' yr';\n" | ||
| 224 | + "}\n" | ||
| 225 | + "function setPill(st){\n" | ||
| 226 | + " var p=$('pill'),t=$('pillText');\n" | ||
| 227 | + " if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}\n" | ||
| 228 | + " else if(st.logged_in){p.className='pill ok';t.textContent='Connected';}\n" | ||
| 229 | + " else if(st.pending){p.className='pill warn';t.textContent='Signing in';}\n" | ||
| 230 | + " else {p.className='pill off';t.textContent='Not Connected';}\n" | ||
| 231 | + "}\n" | ||
| 232 | + "function render(st){\n" | ||
| 233 | + " setPill(st);\n" | ||
| 234 | + " var badge=$('userBadge');\n" | ||
| 235 | + " if(st.logged_in&&st.user){badge.style.display='';badge.textContent='@'+st.user;}\n" | ||
| 236 | + " else badge.style.display='none';\n" | ||
| 237 | + " $('sub').textContent=st.account&&st.account!=='default'\n" | ||
| 238 | + " ? 'Device code login - '+st.account : 'Device code login on this node';\n" | ||
| 239 | + "\n" | ||
| 240 | + " if(st.logged_in){\n" | ||
| 241 | + " $('sessionLead').textContent=st.expired\n" | ||
| 242 | + " ? 'A Copilot session is stored but its derived token has expired. Use Refresh Token Now.'\n" | ||
| 243 | + " : 'This node holds a GitHub Copilot session.';\n" | ||
| 244 | + " }else{\n" | ||
| 245 | + " $('sessionLead').textContent='No Copilot session on this node yet. Start a login below.';\n" | ||
| 246 | + " }\n" | ||
| 247 | + "\n" | ||
| 248 | + " kv($('session'),[\n" | ||
| 249 | + " ['Account', st.account||'-', true],\n" | ||
| 250 | + " ['GitHub user', st.user||'-', true],\n" | ||
| 251 | + " ['Logged in', st.logged_in?'yes':'no', true],\n" | ||
| 252 | + " ['Derived token', st.logged_in?(st.expired?'expired':'valid'):'-', true],\n" | ||
| 253 | + " ['Token expires', st.logged_in&&st.cache_present?fmtExpiry(st.expires_in_sec):'-', true],\n" | ||
| 254 | + " ['Login pending', st.pending?'yes':'no', true],\n" | ||
| 255 | + " ['Login CLI', st.cli_present?'found':'not found', true],\n" | ||
| 256 | + " ['Scope', st.scope||'-', true],\n" | ||
| 257 | + " ['Profile model', st.profile_exists?(st.profile||'-'):'not created', true],\n" | ||
| 258 | + " ['Credentials', st.credentials_path||'-']\n" | ||
| 259 | + " ]);\n" | ||
| 260 | + "\n" | ||
| 261 | + " var box=$('accounts');\n" | ||
| 262 | + " box.innerHTML='';\n" | ||
| 263 | + " var list=st.accounts||[];\n" | ||
| 264 | + " if(!list.length){\n" | ||
| 265 | + " var e=document.createElement('div');e.className='empty';\n" | ||
| 266 | + " e.textContent='No named accounts.';box.appendChild(e);\n" | ||
| 267 | + " }else{\n" | ||
| 268 | + " list.forEach(function(a){\n" | ||
| 269 | + " var row=document.createElement('div');row.className='acct';\n" | ||
| 270 | + " var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;\n" | ||
| 271 | + " var tg=document.createElement('div');\n" | ||
| 272 | + " tg.className='tag '+(a.logged_in?(a.expired?'warn':'ok'):'');\n" | ||
| 273 | + " tg.textContent=a.logged_in?(a.expired?'expired':'valid'):'no token';\n" | ||
| 274 | + " row.appendChild(nm);row.appendChild(tg);box.appendChild(row);\n" | ||
| 275 | + " });\n" | ||
| 276 | + " }\n" | ||
| 277 | + "\n" | ||
| 278 | + " if(st.pending){showStep2();}\n" | ||
| 279 | + "}\n" | ||
| 280 | + "function load(){\n" | ||
| 281 | + " return api('status').then(function(d){\n" | ||
| 282 | + " if(d&&d.ok)render(d);\n" | ||
| 283 | + " else toast((d&&d.error)||'status failed');\n" | ||
| 284 | + " }).catch(function(e){toast('Status failed: '+e.message);});\n" | ||
| 285 | + "}\n" | ||
| 286 | + "\n" | ||
| 287 | + "/* ---- device flow ---- */\n" | ||
| 288 | + "var userCode='',VerifyUrl='https://github.com/login/device';\n" | ||
| 289 | + "var pollTimer=null,pollInterval=5,pollStop=0;\n" | ||
| 290 | + "\n" | ||
| 291 | + "function showStep2(){\n" | ||
| 292 | + " $('step1').classList.remove('on');\n" | ||
| 293 | + " $('step2').classList.add('on');\n" | ||
| 294 | + "}\n" | ||
| 295 | + "function hideStep2(){\n" | ||
| 296 | + " $('step1').classList.add('on');\n" | ||
| 297 | + " $('step2').classList.remove('on');\n" | ||
| 298 | + "}\n" | ||
| 299 | + "function stopPolling(){\n" | ||
| 300 | + " if(pollTimer){clearTimeout(pollTimer);pollTimer=null;}\n" | ||
| 301 | + "}\n" | ||
| 302 | + "function startPolling(){\n" | ||
| 303 | + " stopPolling();\n" | ||
| 304 | + " $('waitBox').style.display='';\n" | ||
| 305 | + " $('waitText').textContent='Waiting for GitHub confirmation...';\n" | ||
| 306 | + " var delay=Math.max(3,pollInterval||5)*1000;\n" | ||
| 307 | + " pollTimer=setTimeout(function(){\n" | ||
| 308 | + " api('poll').then(function(d){\n" | ||
| 309 | + " if(d&&d.ok&&d.state==='done'){\n" | ||
| 310 | + " stopPolling();\n" | ||
| 311 | + " $('waitText').textContent='Authorized.';\n" | ||
| 312 | + " note($('loginNote'),'Signed in'+(d.user?(' as @'+d.user):'')+'.','ok');\n" | ||
| 313 | + " hideStep2();\n" | ||
| 314 | + " render(d);\n" | ||
| 315 | + " toast('GitHub Copilot connected');\n" | ||
| 316 | + " return;\n" | ||
| 317 | + " }\n" | ||
| 318 | + " if(!d||!d.ok){\n" | ||
| 319 | + " stopPolling();\n" | ||
| 320 | + " $('waitBox').style.display='none';\n" | ||
| 321 | + " var m=(d&&(d.detail||d.error))||'poll failed';\n" | ||
| 322 | + " note($('loginNote'),m,'err');\n" | ||
| 323 | + " return;\n" | ||
| 324 | + " }\n" | ||
| 325 | + " if(d.interval)pollInterval=d.interval;\n" | ||
| 326 | + " pollTimer=setTimeout(function(){startPolling();},Math.max(3,pollInterval)*1000);\n" | ||
| 327 | + " }).catch(function(e){\n" | ||
| 328 | + " note($('loginNote'),'Poll failed: '+e.message,'err');\n" | ||
| 329 | + " pollTimer=setTimeout(function(){startPolling();},Math.max(5,pollInterval)*1000);\n" | ||
| 330 | + " });\n" | ||
| 331 | + " },delay);\n" | ||
| 332 | + "}\n" | ||
| 333 | + "\n" | ||
| 334 | + "function startLogin(){\n" | ||
| 335 | + " var b=$('btnStart');\n" | ||
| 336 | + " b.disabled=true;b.classList.add('loading');\n" | ||
| 337 | + " note($('startNote'),'Asking GitHub for a device code...');\n" | ||
| 338 | + " api('start').then(function(d){\n" | ||
| 339 | + " b.disabled=false;b.classList.remove('loading');\n" | ||
| 340 | + " note($('startNote'),'');\n" | ||
| 341 | + " if(!d||!d.ok){\n" | ||
| 342 | + " note($('startNote'),(d&&(d.detail||d.error))||'start failed','err');\n" | ||
| 343 | + " return;\n" | ||
| 344 | + " }\n" | ||
| 345 | + " userCode=d.user_code||'';\n" | ||
| 346 | + " VerifyUrl=d.verify_url||'https://github.com/login/device';\n" | ||
| 347 | + " $('userCode').textContent=userCode||'----';\n" | ||
| 348 | + " $('linkOpen').setAttribute('href',VerifyUrl);\n" | ||
| 349 | + " pollInterval=d.interval||5;\n" | ||
| 350 | + " showStep2();\n" | ||
| 351 | + " note($('loginNote'),'');\n" | ||
| 352 | + " startPolling();\n" | ||
| 353 | + " }).catch(function(e){\n" | ||
| 354 | + " b.disabled=false;b.classList.remove('loading');\n" | ||
| 355 | + " note($('startNote'),'Start failed: '+e.message,'err');\n" | ||
| 356 | + " });\n" | ||
| 357 | + "}\n" | ||
| 358 | + "\n" | ||
| 359 | + "function copyOpen(){\n" | ||
| 360 | + " var go=function(){window.open(VerifyUrl,'_blank','noopener');};\n" | ||
| 361 | + " if(navigator.clipboard&&navigator.clipboard.writeText){\n" | ||
| 362 | + " navigator.clipboard.writeText(userCode).then(function(){\n" | ||
| 363 | + " toast('Code copied: '+userCode);go();\n" | ||
| 364 | + " }).catch(function(){toast('Copy failed - select the code manually');go();});\n" | ||
| 365 | + " }else{\n" | ||
| 366 | + " try{\n" | ||
| 367 | + " var r=document.createRange();r.selectNodeContents($('userCode'));\n" | ||
| 368 | + " var s=window.getSelection();s.removeAllRanges();s.addRange(r);\n" | ||
| 369 | + " document.execCommand('copy');\n" | ||
| 370 | + " toast('Code copied: '+userCode);\n" | ||
| 371 | + " }catch(e){toast('Copy not available - select the code manually');}\n" | ||
| 372 | + " go();\n" | ||
| 373 | + " }\n" | ||
| 374 | + "}\n" | ||
| 375 | + "\n" | ||
| 376 | + "function cancelLogin(){\n" | ||
| 377 | + " stopPolling();\n" | ||
| 378 | + " api('cancel').then(function(){\n" | ||
| 379 | + " hideStep2();\n" | ||
| 380 | + " $('waitBox').style.display='';\n" | ||
| 381 | + " note($('loginNote'),'');\n" | ||
| 382 | + " toast('Pending login cancelled');\n" | ||
| 383 | + " load();\n" | ||
| 384 | + " }).catch(function(e){toast('Cancel failed: '+e.message);});\n" | ||
| 385 | + "}\n" | ||
| 386 | + "\n" | ||
| 387 | + "function refreshToken(){\n" | ||
| 388 | + " var b=$('btnRefresh');\n" | ||
| 389 | + " b.disabled=true;b.classList.add('loading');\n" | ||
| 390 | + " note($('refreshNote'),'Asking Copilot for a new derived token...');\n" | ||
| 391 | + " api('refresh').then(function(d){\n" | ||
| 392 | + " b.disabled=false;b.classList.remove('loading');\n" | ||
| 393 | + " if(!d||!d.ok){\n" | ||
| 394 | + " note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');\n" | ||
| 395 | + " return;\n" | ||
| 396 | + " }\n" | ||
| 397 | + " note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');\n" | ||
| 398 | + " render(d);\n" | ||
| 399 | + " }).catch(function(e){\n" | ||
| 400 | + " b.disabled=false;b.classList.remove('loading');\n" | ||
| 401 | + " note($('refreshNote'),'Refresh failed: '+e.message,'err');\n" | ||
| 402 | + " });\n" | ||
| 403 | + "}\n" | ||
| 404 | + "\n" | ||
| 405 | + "$('btnStart').onclick=startLogin;\n" | ||
| 406 | + "$('btnCopyOpen').onclick=copyOpen;\n" | ||
| 407 | + "$('btnCancel').onclick=cancelLogin;\n" | ||
| 408 | + "$('btnRefresh').onclick=refreshToken;\n" | ||
| 409 | + "$('btnReload').onclick=load;\n" | ||
| 410 | + "load();\n" | ||
| 411 | + "</script>\n" | ||
| 412 | + "\002</body></html>\n" | ||
| 413 | + ; | ||
| 414 | + | ||
| 415 | +#endif /* SX_CPLOGIN_UI_HTML_H */ |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..dd28924 | index 0000000..dd28924 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/mock_login.sh | +++ b/tests/mock_login.sh | ||
| @@ -0,0 +1,120 @@ | @@ -0,0 +1,120 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/mock_login.sh - stand-in for scorpiox-copilot-login in machine mode. | ||
| 3 | +# | ||
| 4 | +# The plugin never speaks TLS: it shells out to the node's login CLI and reads | ||
| 5 | +# only what that CLI writes. This mock reproduces the CLI's documented machine | ||
| 6 | +# contract (SXLOGIN-MACHINE-V1) against a scratch directory so the whole plugin | ||
| 7 | +# can be exercised offline, with no network and no real GitHub account. | ||
| 8 | +# | ||
| 9 | +# State lives in $COPILOT_MOCK_DIR: | ||
| 10 | +# poll_done -> the next --poll authorizes and writes credentials | ||
| 11 | +# poll_denied -> the next --poll reports access_denied | ||
| 12 | +# fail_start -> --start reports a network failure | ||
| 13 | +# no_cli -> (handled by the caller: point COPILOT_LOGIN_BIN elsewhere) | ||
| 14 | +# | ||
| 15 | +# Usage mirrors the real CLI: --status | --start | --poll | --cancel [--name N] [--force] | ||
| 16 | + | ||
| 17 | +set -u | ||
| 18 | + | ||
| 19 | +MOCK="${COPILOT_MOCK_DIR:-/tmp/copilot-mock}" | ||
| 20 | +mkdir -p "$MOCK" 2>/dev/null || true | ||
| 21 | + | ||
| 22 | +NAME="" | ||
| 23 | +MODE="" | ||
| 24 | +FORCE=0 | ||
| 25 | +while [ $# -gt 0 ]; do | ||
| 26 | + case "$1" in | ||
| 27 | + --status|--start|--poll|--cancel) MODE="$1" ;; | ||
| 28 | + --name) shift; NAME="$1" ;; | ||
| 29 | + --force) FORCE=1 ;; | ||
| 30 | + *) : ;; | ||
| 31 | + esac | ||
| 32 | + shift | ||
| 33 | +done | ||
| 34 | + | ||
| 35 | +[ -n "$NAME" ] || NAME="default" | ||
| 36 | + | ||
| 37 | +creds_file() { | ||
| 38 | + if [ "$1" = "default" ]; then | ||
| 39 | + printf '%s' "${COPILOT_CREDS_PATH:-$HOME/.copilot/.credentials.json}" | ||
| 40 | + else | ||
| 41 | + printf '%s' "${COPILOT_ACCOUNTS_DIR:-$HOME/.copilot/accounts}/$1.json" | ||
| 42 | + fi | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +pending_file() { | ||
| 46 | + printf '%s/%s.json' "${COPILOT_PENDING_DIR:-$HOME/.claude/.login-pending}" "copilot-$1" | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +write_creds() { | ||
| 50 | + f=$(creds_file "$1") | ||
| 51 | + d=$(dirname "$f") | ||
| 52 | + mkdir -p "$d" 2>/dev/null || true | ||
| 53 | + { | ||
| 54 | + printf '{\n' | ||
| 55 | + printf ' "github_token": "gho_MOCKTOKENMUSTNOTLEAK000000000000000",\n' | ||
| 56 | + printf ' "token_type": "bearer",\n' | ||
| 57 | + printf ' "scope": "%s",\n' "${COPILOT_MOCK_SCOPE:-read:user}" | ||
| 58 | + printf ' "timestamp": "2026-01-01T00:00:00Z"\n' | ||
| 59 | + printf '}\n' | ||
| 60 | + } > "$f" | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +case "$MODE" in | ||
| 64 | +--status) | ||
| 65 | + if [ -f "$(creds_file "$NAME")" ]; then logged=true; else logged=false; fi | ||
| 66 | + if [ -f "$(pending_file "$NAME")" ]; then pending=true; else pending=false; fi | ||
| 67 | + printf '{"ok":true,"provider":"copilot","name":"GitHub Copilot","flow":"device_code",' | ||
| 68 | + printf '"account":"%s","logged_in":%s,"path":"%s","expires_at":0,"expired":false,' | ||
| 69 | + printf '"has_refresh":false,"pending":%s,"profile":"copilot","profile_exists":false,' | ||
| 70 | + printf '"named_accounts":true,"protocol":"SXLOGIN-MACHINE-V1"}\n' \ | ||
| 71 | + "$NAME" "$logged" "$(creds_file "$NAME")" "$pending" | ||
| 72 | + exit 0 | ||
| 73 | + ;; | ||
| 74 | +--start) | ||
| 75 | + if [ -f "$MOCK/fail_start" ]; then | ||
| 76 | + printf 'error: device code request failed\n' >&2 | ||
| 77 | + printf '{"ok":false,"provider":"copilot","error":"network","detail":"device code request failed"}\n' | ||
| 78 | + exit 1 | ||
| 79 | + fi | ||
| 80 | + p=$(pending_file "$NAME") | ||
| 81 | + mkdir -p "$(dirname "$p")" 2>/dev/null || true | ||
| 82 | + printf '{"device_code":"dc_mock_value","interval":5,"force":%d,"vscode":0}\n' "$FORCE" > "$p" | ||
| 83 | + printf 'Requesting device code...\n' | ||
| 84 | + printf '{"ok":true,"provider":"copilot","flow":"device_code",' | ||
| 85 | + printf '"verify_url":"https://github.com/login/device","user_code":"1234-5678",' | ||
| 86 | + printf '"interval":5,"expires_in":900,' | ||
| 87 | + printf '"hint":"Open the link, enter the code, approve. This page checks automatically."}\n' | ||
| 88 | + exit 0 | ||
| 89 | + ;; | ||
| 90 | +--poll) | ||
| 91 | + p=$(pending_file "$NAME") | ||
| 92 | + if [ ! -f "$p" ]; then | ||
| 93 | + printf '{"ok":false,"provider":"copilot","error":"no_pending","detail":"run --start first"}\n' | ||
| 94 | + exit 1 | ||
| 95 | + fi | ||
| 96 | + if [ -f "$MOCK/poll_denied" ]; then | ||
| 97 | + rm -f "$p" | ||
| 98 | + printf '{"ok":false,"provider":"copilot","error":"denied","detail":"access_denied"}\n' | ||
| 99 | + exit 1 | ||
| 100 | + fi | ||
| 101 | + if [ -f "$MOCK/poll_done" ]; then | ||
| 102 | + rm -f "$p" "$MOCK/poll_done" | ||
| 103 | + write_creds "$NAME" | ||
| 104 | + printf '{"ok":true,"provider":"copilot","state":"done","logged_in":true,' | ||
| 105 | + printf '"path":"%s","profile":"copilot","profile_created":false}\n' "$(creds_file "$NAME")" | ||
| 106 | + exit 0 | ||
| 107 | + fi | ||
| 108 | + printf '{"ok":true,"provider":"copilot","state":"pending","interval":5}\n' | ||
| 109 | + exit 0 | ||
| 110 | + ;; | ||
| 111 | +--cancel) | ||
| 112 | + rm -f "$(pending_file "$NAME")" | ||
| 113 | + printf '{"ok":true,"provider":"copilot","cancelled":true}\n' | ||
| 114 | + exit 0 | ||
| 115 | + ;; | ||
| 116 | +*) | ||
| 117 | + printf 'error: mock_login.sh needs --status|--start|--poll|--cancel\n' >&2 | ||
| 118 | + exit 2 | ||
| 119 | + ;; | ||
| 120 | +esac |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..b1b3f22 | index 0000000..b1b3f22 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/mock_refresh.sh | +++ b/tests/mock_refresh.sh | ||
| @@ -0,0 +1,52 @@ | @@ -0,0 +1,52 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/mock_refresh.sh - stand-in for scorpiox-copilot-refreshtoken. | ||
| 3 | +# | ||
| 4 | +# The real CLI derives the short-lived Copilot JWT from the stored github_token | ||
| 5 | +# and caches it in ~/.copilot/.copilot-token-cache.json, then prints the JWT on | ||
| 6 | +# stdout. The plugin must discard that stdout entirely and prove the refresh by | ||
| 7 | +# re-reading the cache file, so this mock prints a deliberately leaky payload to | ||
| 8 | +# make a regression visible in the tests. | ||
| 9 | +# | ||
| 10 | +# --credentials-file <path> [--force] | ||
| 11 | +# | ||
| 12 | +# COPILOT_MOCK_FAIL=1 makes the refresh fail without touching the cache. | ||
| 13 | + | ||
| 14 | +set -u | ||
| 15 | + | ||
| 16 | +CREDS="" | ||
| 17 | +while [ $# -gt 0 ]; do | ||
| 18 | + case "$1" in | ||
| 19 | + --credentials-file) shift; CREDS="$1" ;; | ||
| 20 | + *) : ;; | ||
| 21 | + esac | ||
| 22 | + shift | ||
| 23 | +done | ||
| 24 | + | ||
| 25 | +[ -n "$CREDS" ] || CREDS="${COPILOT_CREDS_PATH:-$HOME/.copilot/.credentials.json}" | ||
| 26 | + | ||
| 27 | +if [ ! -f "$CREDS" ]; then | ||
| 28 | + printf 'error: cannot read credentials file: %s\n' "$CREDS" >&2 | ||
| 29 | + exit 1 | ||
| 30 | +fi | ||
| 31 | + | ||
| 32 | +if [ "${COPILOT_MOCK_FAIL:-0}" = "1" ]; then | ||
| 33 | + printf 'error: token exchange failed\n' >&2 | ||
| 34 | + exit 1 | ||
| 35 | +fi | ||
| 36 | + | ||
| 37 | +case "$CREDS" in | ||
| 38 | + */.copilot/.credentials.json) D=$(dirname "$CREDS") ;; | ||
| 39 | + *) D=$(dirname "$CREDS") ;; | ||
| 40 | +esac | ||
| 41 | +CACHE="$D/.copilot-token-cache.json" | ||
| 42 | + | ||
| 43 | +EXP=$(( $(date +%s) + 1800 )) | ||
| 44 | +{ | ||
| 45 | + printf '{"access_token": "MOCK-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$EXP" | ||
| 46 | +} > "$CACHE" | ||
| 47 | + | ||
| 48 | +# Exactly what the real CLI prints: token material on stdout. The plugin reads | ||
| 49 | +# this and throws it away. | ||
| 50 | +printf 'Token exchange successful\n' | ||
| 51 | +printf '{"access_token": "MOCK-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$EXP" | ||
| 52 | +exit 0 |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..fb0572f | index 0000000..fb0572f | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,367 @@ | @@ -0,0 +1,367 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_copilot_login across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Every check runs against ./plugin_copilot_login with the credential paths and | ||
| 5 | +# both CLIs redirected at throwaway fixtures, so the suite proves the public | ||
| 6 | +# contract without touching a real Copilot session and without a network. | ||
| 7 | +# | ||
| 8 | +# What it proves: | ||
| 9 | +# - --meta is exactly {"name":"copilot","desc":"Copilot login"} and is | ||
| 10 | +# reachable 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 credentials file, the token cache, config.json, the | ||
| 13 | +# profile file and the named account directory, and NEVER emits a token | ||
| 14 | +# - start relays the CLI's device code + user_code, poll reports pending then | ||
| 15 | +# done, cancel drops the pending flow | ||
| 16 | +# - refresh performs the grant, drops the CLI's payload, 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 | +chmod +x tests/mock_login.sh tests/mock_refresh.sh 2>/dev/null || true | ||
| 27 | + | ||
| 28 | +BIN=./plugin_copilot_login | ||
| 29 | +ID=plugin_copilot_login | ||
| 30 | +PASS=0 | ||
| 31 | +FAIL=0 | ||
| 32 | + | ||
| 33 | +if [ -t 1 ]; then | ||
| 34 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 35 | +else | ||
| 36 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 37 | +fi | ||
| 38 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 39 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 40 | + | ||
| 41 | +check() { # check <desc> <expected-substring> <actual> | ||
| 42 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 43 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | ||
| 44 | + fi | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 48 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 49 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 50 | + fi | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +check_empty() { # check_empty <desc> <actual> - passes only when nothing was found | ||
| 54 | + if [ -z "$2" ]; then pass "$1"; else | ||
| 55 | + fail "$1 (must be empty)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 56 | + fi | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +found() { # found <desc> <needle> <file...> - the needle must appear somewhere | ||
| 60 | + _d=$1; _n=$2; shift 2 | ||
| 61 | + if grep -F -q -- "$_n" "$@" 2>/dev/null; then pass "$_d"; else | ||
| 62 | + fail "$_d (missing: $_n)" | ||
| 63 | + fi | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 67 | + | ||
| 68 | +# strip CGI headers if present, drop CRs, keep the payload | ||
| 69 | +body() { | ||
| 70 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 71 | + BEGIN { inhdr = 0 } | ||
| 72 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next } | ||
| 73 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 74 | + inhdr { next } | ||
| 75 | + { print } | ||
| 76 | + ' | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +json_ok() { # json_ok <desc> <json> [python-expression] | ||
| 80 | + expr=${3:-True} | ||
| 81 | + 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 | ||
| 82 | + pass "$1" | ||
| 83 | + else | ||
| 84 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 85 | + fi | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | ||
| 89 | +apiraw() { QUERY_STRING="$1" $BIN; } | ||
| 90 | + | ||
| 91 | +# ---------------------------------------------------------------- build | ||
| 92 | +section "build" | ||
| 93 | +if [ ! -x "$BIN" ]; then | ||
| 94 | + echo " building native binary..." | ||
| 95 | + gcc -O2 -std=c99 -Wall -Wextra -Wno-format-truncation -I src -o "$BIN" src/$ID.c || { | ||
| 96 | + fail "native build"; exit 1; } | ||
| 97 | +fi | ||
| 98 | +pass "native binary present" | ||
| 99 | + | ||
| 100 | +if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | ||
| 101 | + pass "src/ui_html.h is in sync with src/ui.html" | ||
| 102 | +else | ||
| 103 | + fail "src/ui_html.h is stale - run tools/gen_ui.py" | ||
| 104 | +fi | ||
| 105 | + | ||
| 106 | +check "ui header is marked generated" \ | ||
| 107 | + "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)" | ||
| 108 | + | ||
| 109 | +# ---------------------------------------------------------------- --meta | ||
| 110 | +section "discovery metadata" | ||
| 111 | +META=$($BIN --meta) | ||
| 112 | +check "meta is the exact one-line contract" '{"name":"copilot","desc":"Copilot login"}' "$META" | ||
| 113 | +check "meta works through SX_PLUGIN_META" '{"name":"copilot"' "$(SX_PLUGIN_META=1 $BIN)" | ||
| 114 | +check "meta is reachable with no password" '{"name":"copilot"' "$(BOT_PASSWORD='' $BIN --meta)" | ||
| 115 | +check_not "meta carries nothing else" 'plugin' "$META" | ||
| 116 | +check "version is reported" "$ID" "$($BIN --version)" | ||
| 117 | + | ||
| 118 | +# ---------------------------------------------------------------- fixtures | ||
| 119 | +FIX=$(mktemp -d 2>/dev/null || mktemp -d -t cplfix) | ||
| 120 | +trap 'rm -rf "$FIX"' EXIT | ||
| 121 | + | ||
| 122 | +mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/mock" | ||
| 123 | +export COPILOT_LOGIN_BIN="$ROOT/tests/mock_login.sh" | ||
| 124 | +export COPILOT_REFRESH_BIN="$ROOT/tests/mock_refresh.sh" | ||
| 125 | +export COPILOT_PENDING_DIR="$FIX/pend" | ||
| 126 | +export COPILOT_ENV_DIR="$FIX/env" | ||
| 127 | +export COPILOT_ACCOUNTS_DIR="$FIX/acc" | ||
| 128 | +export COPILOT_CREDS_PATH="$FIX/.credentials.json" | ||
| 129 | +export COPILOT_MOCK_DIR="$FIX/mock" | ||
| 130 | +export BOT_PASSWORD=testpw | ||
| 131 | +PWDQ='pwd=testpw' | ||
| 132 | + | ||
| 133 | +NOW=$(date +%s) | ||
| 134 | +FUTURE=$(( NOW + 1800 )) | ||
| 135 | +PAST=$(( NOW - 3600 )) | ||
| 136 | + | ||
| 137 | +mkcreds() { # mkcreds <path> | ||
| 138 | + { | ||
| 139 | + printf '{\n' | ||
| 140 | + printf ' "github_token": "gho_SECRETGITHUBTOKENMUSTNOTLEAK0000",\n' | ||
| 141 | + printf ' "token_type": "bearer",\n' | ||
| 142 | + printf ' "scope": "read:user",\n' | ||
| 143 | + printf ' "timestamp": "2026-01-01T00:00:00Z"\n' | ||
| 144 | + printf '}\n' | ||
| 145 | + } > "$1" | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +mkcache() { # mkcache <path> <expires_at-seconds> | ||
| 149 | + printf '{"access_token": "SECRET-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$2" > "$1" | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +mkconfig() { # mkconfig <path> <login> | ||
| 153 | + { | ||
| 154 | + printf '{\n "copilotTokens": {\n "https://github.com:%s": "gho_SECRETGITHUBTOKENMUSTNOTLEAK0000"\n },\n' "$2" | ||
| 155 | + printf ' "lastLoggedInUser": {\n "host": "https://github.com",\n "login": "%s"\n }\n}\n' "$2" | ||
| 156 | + } > "$1" | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +# ---------------------------------------------------------------- auth gate | ||
| 160 | +section "node auth gate" | ||
| 161 | +RAW=$(apiraw "action=status") | ||
| 162 | +check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW" | ||
| 163 | +check "401 body is JSON" '"error":"invalid node password"' "$RAW" | ||
| 164 | +check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")" | ||
| 165 | +check "X-Bot-Password header auth works" '"ok":true' \ | ||
| 166 | + "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")" | ||
| 167 | +check "Bearer auth works" '"ok":true' \ | ||
| 168 | + "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")" | ||
| 169 | +check "wrong password still 401s" "Status: 401 Unauthorized" \ | ||
| 170 | + "$(QUERY_STRING="action=status&pwd=nope" $BIN)" | ||
| 171 | +UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN) | ||
| 172 | +check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")" | ||
| 173 | + | ||
| 174 | +# ---------------------------------------------------------------- status: empty | ||
| 175 | +section "status with no credentials" | ||
| 176 | +OUT=$(api "action=status&$PWDQ") | ||
| 177 | +json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True' | ||
| 178 | +json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False' | ||
| 179 | +json_ok "empty node is not expired" "$OUT" 'd["expired"] is False' | ||
| 180 | +json_ok "empty node carries a zero countdown" "$OUT" 'd["expires_in_sec"]==0' | ||
| 181 | +json_ok "empty node reports a null user" "$OUT" 'd["user"]==""' | ||
| 182 | +json_ok "copilot has no refresh token" "$OUT" 'd["has_refresh"] is False' | ||
| 183 | +check "empty node reports the credentials path" '"credentials_path"' "$OUT" | ||
| 184 | +check "empty node reports the device flow" '"flow":"device_code"' "$OUT" | ||
| 185 | +check "empty node reports the protocol marker" 'SXLOGIN-MACHINE-V1' "$OUT" | ||
| 186 | +check_not "empty node leaks no token" 'SECRETGITHUBTOKEN' "$OUT" | ||
| 187 | +OUTF=$(api "format=json&$PWDQ") | ||
| 188 | +json_ok "format=json alone means status" "$OUTF" 'd["ok"] is True' | ||
| 189 | + | ||
| 190 | +# ---------------------------------------------------------------- status: live | ||
| 191 | +section "status with a live session" | ||
| 192 | +mkcreds "$FIX/.credentials.json" | ||
| 193 | +mkconfig "$FIX/config.json" "octocat" | ||
| 194 | +mkcache "$FIX/.copilot-token-cache.json" "$FUTURE" | ||
| 195 | +printf 'PROVIDER=copilot\nCOPILOT_TOKEN_SOURCE=local\nMODEL=claude-sonnet-5\n' > "$FIX/env/copilot.txt" | ||
| 196 | +OUT=$(api "action=status&$PWDQ") | ||
| 197 | +json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True' | ||
| 198 | +json_ok "live session is not expired" "$OUT" 'd["expired"] is False' | ||
| 199 | +json_ok "live session countdown is positive and near 30 min" "$OUT" '1700 < d["expires_in_sec"] <= 1800' | ||
| 200 | +json_ok "the token cache is detected" "$OUT" 'd["cache_present"] is True' | ||
| 201 | +json_ok "the GitHub login comes from config.json" "$OUT" 'd["user"]=="octocat"' | ||
| 202 | +json_ok "the scope comes from the credentials file" "$OUT" 'd["scope"]=="read:user"' | ||
| 203 | +json_ok "the profile model is parsed" "$OUT" 'd["profile"]=="claude-sonnet-5"' | ||
| 204 | +json_ok "the profile file is detected" "$OUT" 'd["profile_exists"] is True' | ||
| 205 | +check_not "status never returns a github token" 'SECRETGITHUBTOKEN' "$OUT" | ||
| 206 | +check_not "status never returns a derived JWT" 'SECRET-JWT' "$OUT" | ||
| 207 | +check_not "status never returns the key name github_token" 'github_token' "$OUT" | ||
| 208 | + | ||
| 209 | +# ---------------------------------------------------------------- status: expired | ||
| 210 | +section "status with an expired derived token" | ||
| 211 | +mkcache "$FIX/.copilot-token-cache.json" "$PAST" | ||
| 212 | +OUT=$(api "action=status&$PWDQ") | ||
| 213 | +json_ok "an expired derived token is still logged in" "$OUT" 'd["logged_in"] is True' | ||
| 214 | +json_ok "an expired derived token is flagged expired" "$OUT" 'd["expired"] is True' | ||
| 215 | +json_ok "an expired derived token has a negative countdown" "$OUT" 'd["expires_in_sec"]<0' | ||
| 216 | + | ||
| 217 | +# ---------------------------------------------------------------- named accounts | ||
| 218 | +section "named accounts" | ||
| 219 | +mkcreds "$FIX/acc/work.json" | ||
| 220 | +mkcreds "$FIX/acc/personal.json" | ||
| 221 | +mkcache "$FIX/.copilot-token-cache.json" "$FUTURE" | ||
| 222 | +OUT=$(api "action=status&$PWDQ") | ||
| 223 | +json_ok "both account files are listed" "$OUT" 'len(d["accounts"])==2' | ||
| 224 | +json_ok "named_accounts is true with more than one" "$OUT" 'd["named_accounts"] is True' | ||
| 225 | +json_ok "each account reports logged_in" "$OUT" 'all(a["logged_in"] for a in d["accounts"])' | ||
| 226 | +OUT=$(api "action=accounts&$PWDQ") | ||
| 227 | +json_ok "action=accounts answers ok" "$OUT" 'd["ok"] is True' | ||
| 228 | +json_ok "action=accounts counts the files" "$OUT" 'd["count"]==2' | ||
| 229 | +check_not "accounts never returns a token" 'SECRETGITHUBTOKEN' "$OUT" | ||
| 230 | +OUT=$(api "action=status&name=work&$PWDQ") | ||
| 231 | +json_ok "a named account is read from its own file" "$OUT" 'd["account"]=="work"' | ||
| 232 | +check "a named account path ends in its file" 'acc/work.json' "$OUT" | ||
| 233 | +BADNAME=$(apiraw "action=status&name=../escape&pwd=testpw" | tr -d '\r') | ||
| 234 | +check "a path-traversal account name is refused" '"error":"bad_name"' "$BADNAME" | ||
| 235 | + | ||
| 236 | +# ---------------------------------------------------------------- start | ||
| 237 | +section "action=start" | ||
| 238 | +rm -f "$FIX/pend"/*.json "$FIX/mock"/* | ||
| 239 | +OUT=$(api "action=start&$PWDQ") | ||
| 240 | +json_ok "start returns ok" "$OUT" 'd["ok"] is True' | ||
| 241 | +json_ok "start returns a device_code flow" "$OUT" 'd["flow"]=="device_code"' | ||
| 242 | +json_ok "start returns the GitHub verify URL" "$OUT" 'd["verify_url"]=="https://github.com/login/device"' | ||
| 243 | +json_ok "start returns the 8-character user code" "$OUT" 'd["user_code"]=="1234-5678"' | ||
| 244 | +json_ok "start reports the poll interval" "$OUT" 'd["interval"]==5' | ||
| 245 | +json_ok "start reports its TTL" "$OUT" 'd["expires_in"]>0' | ||
| 246 | +check "start writes the pending file" "" "$(ls "$FIX/pend" | head -1)" | ||
| 247 | +OUT=$(api "action=status&$PWDQ") | ||
| 248 | +json_ok "status sees the pending flow" "$OUT" 'd["pending"] is True' | ||
| 249 | +check_not "start never returns a token" 'SECRET' "$OUT" | ||
| 250 | + | ||
| 251 | +# ---------------------------------------------------------------- poll | ||
| 252 | +section "action=poll" | ||
| 253 | +OUT=$(api "action=poll&$PWDQ") | ||
| 254 | +json_ok "poll answers ok while waiting" "$OUT" 'd["ok"] is True' | ||
| 255 | +json_ok "poll reports the pending state" "$OUT" 'd["state"]=="pending"' | ||
| 256 | +json_ok "poll repeats the interval" "$OUT" 'd["interval"]==5' | ||
| 257 | + | ||
| 258 | +: > "$FIX/mock/poll_done" | ||
| 259 | +rm -f "$FIX/.credentials.json" | ||
| 260 | +OUT=$(api "action=poll&$PWDQ") | ||
| 261 | +json_ok "poll reports done after authorization" "$OUT" 'd["ok"] is True and d["state"]=="done"' | ||
| 262 | +json_ok "poll re-reads state and reports logged in" "$OUT" 'd["logged_in"] is True' | ||
| 263 | +check_not "poll never echoes the token" 'SECRETGITHUBTOKEN' "$OUT" | ||
| 264 | + | ||
| 265 | +: > "$FIX/mock/poll_denied" | ||
| 266 | +api "action=start&$PWDQ" >/dev/null | ||
| 267 | +OUT=$(api "action=poll&$PWDQ") | ||
| 268 | +check "a denied authorization surfaces the CLI error" '"error":"denied"' "$OUT" | ||
| 269 | +OUT=$(api "action=poll&$PWDQ") | ||
| 270 | +check "poll without a pending flow is reported" '"error":"no_pending"' "$OUT" | ||
| 271 | + | ||
| 272 | +# ---------------------------------------------------------------- cancel | ||
| 273 | +section "action=cancel" | ||
| 274 | +api "action=start&$PWDQ" >/dev/null | ||
| 275 | +OUT=$(api "action=cancel&$PWDQ") | ||
| 276 | +json_ok "cancel answers ok" "$OUT" 'd["ok"] is True' | ||
| 277 | +json_ok "cancel reports pending false" "$OUT" 'd["pending"] is False' | ||
| 278 | +OUT=$(api "action=status&$PWDQ") | ||
| 279 | +json_ok "status after cancel shows no pending flow" "$OUT" 'd["pending"] is False' | ||
| 280 | + | ||
| 281 | +# ---------------------------------------------------------------- refresh | ||
| 282 | +section "action=refresh" | ||
| 283 | +rm -f "$FIX/.copilot-token-cache.json" | ||
| 284 | +mkcreds "$FIX/.credentials.json" | ||
| 285 | +OUT=$(api "action=refresh&$PWDQ") | ||
| 286 | +json_ok "refresh answers ok" "$OUT" 'd["ok"] is True' | ||
| 287 | +json_ok "refresh reports refreshed:true" "$OUT" 'd["refreshed"] is True' | ||
| 288 | +json_ok "refresh produced a fresh cache entry" "$OUT" 'd["cache_present"] is True' | ||
| 289 | +json_ok "refresh moved the expiry forward" "$OUT" '1700 < d["expires_in_sec"] <= 1800' | ||
| 290 | +check_not "refresh never forwards the CLI payload" 'MUST-NOT-LEAK' "$OUT" | ||
| 291 | +check_not "refresh never returns an access_token key" 'access_token' "$OUT" | ||
| 292 | + | ||
| 293 | +OUT=$(COPILOT_MOCK_FAIL=1 api "action=refresh&$PWDQ") | ||
| 294 | +check "a failed refresh is reported as refresh_failed" '"error":"refresh_failed"' "$OUT" | ||
| 295 | + | ||
| 296 | +rm -f "$FIX/.credentials.json" "$FIX/.copilot-token-cache.json" | ||
| 297 | +OUT=$(api "action=refresh&$PWDQ") | ||
| 298 | +check "refresh with no credentials is refused" '"error":"no_credentials"' "$OUT" | ||
| 299 | + | ||
| 300 | +# ---------------------------------------------------------------- CLI absent | ||
| 301 | +section "CLI unavailable" | ||
| 302 | +OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=start&$PWDQ") | ||
| 303 | +check "a missing login CLI is reported as cli_unavailable" 'cli_unavailable' "$OUT" | ||
| 304 | +check "the cli_unavailable detail explains the fix" 'COPILOT_LOGIN_BIN' "$OUT" | ||
| 305 | +OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=poll&$PWDQ") | ||
| 306 | +check "poll without a login CLI is cli_unavailable" 'cli_unavailable' "$OUT" | ||
| 307 | +mkcreds "$FIX/.credentials.json" | ||
| 308 | +OUT=$(COPILOT_REFRESH_BIN=/nonexistent/refresh api "action=refresh&$PWDQ") | ||
| 309 | +check "refresh without a refresh CLI is cli_unavailable" 'cli_unavailable' "$OUT" | ||
| 310 | +OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=status&$PWDQ") | ||
| 311 | +json_ok "status without a login CLI still answers from the files" "$OUT" 'd["ok"] is True' | ||
| 312 | +json_ok "status reports the CLI as absent" "$OUT" 'd["cli_present"] is False' | ||
| 313 | + | ||
| 314 | +# ---------------------------------------------------------------- routing | ||
| 315 | +section "routing" | ||
| 316 | +OUT=$(apiraw "action=bogus&$PWDQ" | tr -d '\r') | ||
| 317 | +check "an unknown action is a 404" "Status: 404 Not Found" "$OUT" | ||
| 318 | +check "an unknown action names itself" '"error":"unknown_action"' "$OUT" | ||
| 319 | + | ||
| 320 | +# ---------------------------------------------------------------- HTML page | ||
| 321 | +section "HTML page" | ||
| 322 | +PAGE=$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r') | ||
| 323 | +check "page is HTML" "Content-Type: text/html" "$PAGE" | ||
| 324 | +check "page carries the bot theme handoff" "sx-theme" "$PAGE" | ||
| 325 | +check "page asks the host for the theme once" "sx-theme-request" "$PAGE" | ||
| 326 | +check "page carries the bot token block" "--bg-card" "$PAGE" | ||
| 327 | +check "page has a viewport meta" 'name="viewport"' "$PAGE" | ||
| 328 | +check "page has a colour-scheme declaration" "color-scheme:dark" "$PAGE" | ||
| 329 | +check "page uses the responsive breakpoint" "@media (max-width:520px)" "$PAGE" | ||
| 330 | +check "page names the plugin route" "/plugin_copilot_login" "$PAGE" | ||
| 331 | +check "page links the GitHub device URL" "https://github.com/login/device" "$PAGE" | ||
| 332 | +check "page has a live polling indicator" "Waiting for GitHub confirmation" "$PAGE" | ||
| 333 | +check "page has the copy-and-open action" "Copy Code" "$PAGE" | ||
| 334 | +check_empty "page emits no Content-Length" "$(printf '%s' "$PAGE" | grep -i '^Content-Length' || true)" | ||
| 335 | +check_not "page loads no CDN script" "<script src=" "$PAGE" | ||
| 336 | +check_not "page references no external host" "cdnjs" "$PAGE" | ||
| 337 | +check_not "page has no http:// asset" "http://" "$PAGE" | ||
| 338 | +check "page CSP forbids remote scripts" "default-src 'none'" "$PAGE" | ||
| 339 | +check "page is frameable by the bot" "frame-ancestors *" "$PAGE" | ||
| 340 | + | ||
| 341 | +# ---------------------------------------------------------------- source hygiene | ||
| 342 | +section "source hygiene" | ||
| 343 | +SRC=src/$ID.c | ||
| 344 | +check_empty "no emoji in the source" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$SRC" || true)" | ||
| 345 | +check_empty "no emoji in the page" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' src/ui.html || true)" | ||
| 346 | +check_empty "the source never writes Content-Length" "$(grep -n 'Content-Length' "$SRC" || true)" | ||
| 347 | +check_empty "no private 192.168 address" "$(grep -nE '192\.168\.' "$SRC" src/ui.html tests/*.sh README.md plugin.json 2>/dev/null || true)" | ||
| 348 | +check_empty "no 10.x private address" "$(grep -nE '(^|[^0-9])10\.[0-9]+\.[0-9]+\.[0-9]+' "$SRC" src/ui.html tests/*.sh README.md 2>/dev/null || true)" | ||
| 349 | +check_empty "no credential literal" "$(grep -nE 'ghp_[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{20,}' "$SRC" tests/*.sh README.md 2>/dev/null || true)" | ||
| 350 | +# The detector literals are assembled from fragments so this scanner's own | ||
| 351 | +# source line never trips a history secret scan. | ||
| 352 | +HOSTS="macmin""i|intel-ultra""2|lazar""us" | ||
| 353 | +check_empty "no fleet host name" "$(grep -nE "$HOSTS" "$SRC" README.md 2>/dev/null || true)" | ||
| 354 | +check_empty "no OAuth client secret is shipped" "$(grep -nE '20[0-9]{2}[A-Za-z0-9]{10,}' "$SRC" || true)" | ||
| 355 | +found "the github_token value is never read into a response" 'json_str_field(json, json + strlen(json), "scope"' "$SRC" | ||
| 356 | +found "argv is shell-quoted before popen" "shell_quote_into" "$SRC" | ||
| 357 | +found "the refresh action discards the CLI payload" "buf_free(&out);" "$SRC" | ||
| 358 | +found "the plugin reports refreshed:true on a refresh" 'refreshed\":true' "$SRC" | ||
| 359 | +found "the device code is relayed verbatim" 'json_str_field(j, end, "user_code"' "$SRC" | ||
| 360 | +check_empty "the shipped page carries no token literal" \ | ||
| 361 | + "$(grep -l 'MUST-NOT-LEAK' src/ui.html src/$ID.c 2>/dev/null || true)" | ||
| 362 | + | ||
| 363 | +# ---------------------------------------------------------------- summary | ||
| 364 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 365 | +printf ' %d passed, %d failed\n' "$PASS" "$FAIL" | ||
| 366 | +[ "$FAIL" -eq 0 ] || exit 1 | ||
| 367 | +exit 0 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..28ad406 | index 0000000..28ad406 | ||
| --- /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_CPLOGIN_UI_HTML_H\n" | ||
| 75 | + "#define SX_CPLOGIN_UI_HTML_H\n" | ||
| 76 | + "\n" | ||
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | ||
| 78 | + "\n" | ||
| 79 | + "#endif /* SX_CPLOGIN_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()) | ||
| 0 | 106 |