| 1 | 1 | new file mode 100644 |
| index 0000000..b143622 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | |
| 2 | +/plugin_opencode_login | |
| 3 | +/plugin_opencode_login.exe | |
| 4 | +/plugin_opencode_login.musl | |
| 5 | +/plugin_opencode_login.arm64 | |
| 6 | +/plugin_opencode_login.macos-arm64 | |
| 7 | +/plugin_opencode_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..ff2f4a3 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,72 @@ | ||
| 1 | +# plugin_opencode_login - SCORPIOX BOT open-source OpenCode device-code login | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_opencode_login | |
| 5 | +# make musl static musl x86_64 -> ./plugin_opencode_login.musl | |
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_opencode_login.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_opencode_login.exe | |
| 8 | +# make macos Apple clang -> ./plugin_opencode_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 clean | |
| 12 | + | |
| 13 | +CC ?= cc | |
| 14 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src | |
| 15 | +MUSL_CC ?= musl-gcc | |
| 16 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 17 | +ARM_CC ?= aarch64-linux-gnu-gcc | |
| 18 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 19 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 20 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 21 | +SRC := src/plugin_opencode_login.c | |
| 22 | +UI_SRC := src/ui.html | |
| 23 | +UI_HDR := src/ui_html.h | |
| 24 | +BIN := plugin_opencode_login | |
| 25 | +EXE := plugin_opencode_login.exe | |
| 26 | + | |
| 27 | +.PHONY: all native musl arm64 win64 macos ui test clean help | |
| 28 | + | |
| 29 | +all: native | |
| 30 | + | |
| 31 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | |
| 32 | + @echo "==> regenerating $(UI_HDR)" | |
| 33 | + python3 tools/gen_ui.py | |
| 34 | + | |
| 35 | +ui: $(UI_HDR) | |
| 36 | + | |
| 37 | +native: $(BIN) | |
| 38 | + | |
| 39 | +$(BIN): $(SRC) $(UI_HDR) | |
| 40 | + @echo "==> native build ($(CC))" | |
| 41 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 42 | + | |
| 43 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 44 | +musl: $(SRC) $(UI_HDR) | |
| 45 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 46 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) | |
| 47 | + | |
| 48 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 49 | +arm64: $(SRC) $(UI_HDR) | |
| 50 | + @echo "==> static arm64 build ($(ARM_CC))" | |
| 51 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) | |
| 52 | + | |
| 53 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 54 | +win64: $(SRC) $(UI_HDR) | |
| 55 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 56 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | |
| 57 | + | |
| 58 | +# Apple clang build (run this on macOS) | |
| 59 | +macos: $(SRC) $(UI_HDR) | |
| 60 | + @echo "==> Apple clang build" | |
| 61 | + $(CC) -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o $(BIN) $(SRC) | |
| 62 | + | |
| 63 | +test: native | |
| 64 | + @echo "==> running tests" | |
| 65 | + sh tests/run.sh | |
| 66 | + | |
| 67 | +clean: | |
| 68 | + @rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 69 | + @echo "==> cleaned" | |
| 70 | + | |
| 71 | +help: | |
| 72 | + @sed -n '2,14p' Makefile |
| 1 | 1 | new file mode 100644 |
| index 0000000..1105138 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,139 @@ | ||
| 1 | +# scorpiox-bot-plugin-oss-opencode-login | |
| 2 | + | |
| 3 | +A clean-room, zero-dependency, cross-platform SCORPIOX BOT node plugin for | |
| 4 | +**OpenCode device-code login and account token management** on the node it runs | |
| 5 | +on. Binary: `plugin_opencode_login` (Windows: `plugin_opencode_login.exe`). | |
| 6 | +Marketplace slug: `opencode-login`. Category: `devtools`. License: MIT. | |
| 7 | + | |
| 8 | +``` | |
| 9 | +--meta {"name":"opencode","desc":"OpenCode login"} | |
| 10 | +?action= status | start | poll | cancel | refresh | |
| 11 | +GET responsive dark/light HTML UI (?embed=1 aware) | |
| 12 | +``` | |
| 13 | + | |
| 14 | +## Why it drives a CLI instead of speaking TLS | |
| 15 | + | |
| 16 | +An OAuth device flow is a sequence of HTTPS POSTs. A public clean-room | |
| 17 | +repository cannot ship a client secret, and vendoring a TLS stack into every | |
| 18 | +plugin would be a liability on each node. So this plugin opens **no socket of | |
| 19 | +its own**: it drives the machine-mode login CLI that already ships with | |
| 20 | +SCORPIOX CODE (`SXLOGIN-MACHINE-V1`: `--status`, `--start`, `--poll`, | |
| 21 | +`--cancel`, one JSON line per call) and reads the credential file that CLI | |
| 22 | +writes. The repo contains no secret, no internal address and no emoji. | |
| 23 | + | |
| 24 | +``` | |
| 25 | +plugin_opencode_login --popen--> scorpiox-opencode-login --status|--start|--poll|--cancel | |
| 26 | +plugin_opencode_login --popen--> scorpiox-opencode-fetchtoken -local | |
| 27 | +``` | |
| 28 | + | |
| 29 | +Files it reads (all on the local node, all overridable): | |
| 30 | + | |
| 31 | +| Path | Written by | Override | | |
| 32 | +|---|---|---| | |
| 33 | +| `~/.config/opencode/auth.json` | the login CLI | `OPENCODE_CREDS_PATH` | | |
| 34 | +| `~/.opencode/token.json` (fallback when the primary is absent) | hand-written installs | — | | |
| 35 | +| `~/.claude/.login-pending/opencode-default.json` | the login CLI | `OPENCODE_PENDING_PATH` | | |
| 36 | +| `~/.claude/scorpiox-env/superopencode.txt` | the login CLI | `OPENCODE_ENV_DIR` | | |
| 37 | +| the login binary | SCORPIOX CODE | `OPENCODE_LOGIN_BIN` | | |
| 38 | +| the token binary | SCORPIOX CODE | `OPENCODE_TOKEN_BIN` | | |
| 39 | + | |
| 40 | +**No token is ever printed, logged or returned.** `status` reports | |
| 41 | +`logged_in`, `has_refresh`, `expires_at`, `expires_in_sec`, `expired`; | |
| 42 | +`refresh` reports success and the new expiry and discards the payload. The | |
| 43 | +test suite fails if the mock token appears in any response, and if the words | |
| 44 | +`access_token` or `refresh_token` appear at all. | |
| 45 | + | |
| 46 | +## Actions | |
| 47 | + | |
| 48 | +| Action | Behaviour | | |
| 49 | +|---|---| | |
| 50 | +| `status` (also `format=json`) | credential file + pending marker + CLI JSON merged into one honest picture; `pending` is owned by the marker file and its TTL, the CLI may only add to it | | |
| 51 | +| `start` | returns the CLI's `verify_url`, `user_code`, `expires_in`, `interval`; `already_logged_in` when the node already has credentials (`force=1` replaces them) | | |
| 52 | +| `poll` | one non-blocking round trip: `{state:"pending"}` while waiting, `{state:"done",logged_in:true}` on approval, `{state:"failed",error:...}` on denial or a dead flow | | |
| 53 | +| `cancel` | aborts the pending flow and reports the cleared state | | |
| 54 | +| `refresh` | re-reads the stored token through the node's token CLI and reports the new expiry with the value discarded | | |
| 55 | +| `cli_unavailable` | structured, HTTP 200, when a CLI is missing, so a node without SCORPIOX CODE shows a message, not a broken panel | | |
| 56 | + | |
| 57 | +Auth: `X-Bot-Password`, `Authorization: Bearer` or `?pwd=`; a no-op when | |
| 58 | +`BOT_PASSWORD` is unset; `--meta` is always unauthenticated. | |
| 59 | + | |
| 60 | +## UI | |
| 61 | + | |
| 62 | +One page, no framework, no CDN, no `<script src=>`, no external request. Bot | |
| 63 | +theme handoff (`?theme=` then `localStorage.bot_theme` then | |
| 64 | +`prefers-color-scheme`, before first paint, then follows `{type:'sx-theme'}`), | |
| 65 | +every colour a token from the vendored `src/bot_theme_plugin.h`. A status pill | |
| 66 | +(`Connected` / `Expired` / `Signing in` / `Not Connected`), a user badge, a | |
| 67 | +session card, a device-flow card with a large user code and a one-click | |
| 68 | +**Copy Code & Open OpenCode** button, a live polling indicator, a cancel | |
| 69 | +button, and **Refresh Token Now**. Fluid down to 390 px and the Chat floating | |
| 70 | +window. | |
| 71 | + | |
| 72 | +## Build | |
| 73 | + | |
| 74 | +```bash | |
| 75 | +make # native -> ./plugin_opencode_login | |
| 76 | +make musl # static musl x86_64 (Alpine, Debian, Arch, Omarchy) | |
| 77 | +make arm64 # static aarch64 (Raspberry Pi 5, ARM servers) | |
| 78 | +make win64 # MinGW-w64 static PE -> plugin_opencode_login.exe | |
| 79 | +make macos # Apple clang, run on a Mac | |
| 80 | +make ui # regenerate src/ui_html.h from src/ui.html | |
| 81 | +make test # build + run tests/run.sh | |
| 82 | +``` | |
| 83 | + | |
| 84 | +On Windows: | |
| 85 | + | |
| 86 | +```powershell | |
| 87 | +powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 88 | +``` | |
| 89 | + | |
| 90 | +## Install | |
| 91 | + | |
| 92 | +Drop the binary into the node's plugin directory - no restart: | |
| 93 | + | |
| 94 | +```bash | |
| 95 | +mkdir -p ~/.scorpiox/plugins | |
| 96 | +cp plugin_opencode_login ~/.scorpiox/plugins/ | |
| 97 | +~/.scorpiox/plugins/plugin_opencode_login --meta | |
| 98 | +``` | |
| 99 | + | |
| 100 | +`scorpiox-bot-api` discovers it on the next `GET /plugins` and serves it at | |
| 101 | +`/plugin_opencode_login`. BotMarket installs the prebuilt artifact for your | |
| 102 | +platform in one click, or compiles it from the public mirror. | |
| 103 | + | |
| 104 | +## Tests | |
| 105 | + | |
| 106 | +`tests/run.sh` is fully offline: both CLIs are replaced by fixtures that emit | |
| 107 | +the exact production contract shape, and the credential and marker paths point | |
| 108 | +at throwaway files. It proves the metadata contract, the 401 gate, status | |
| 109 | +parsing (live, expired, empty, missing, secondary location, pending, stale | |
| 110 | +marker), the start/poll/cancel/refresh lifecycle, that no token ever surfaces, | |
| 111 | +that the page has no CDN and no emoji, and that the source history carries no | |
| 112 | +secret or internal address. Cross-target builds (musl, MinGW PE, aarch64) are | |
| 113 | +checked when the toolchains are installed. | |
| 114 | + | |
| 115 | +```bash | |
| 116 | +sh tests/run.sh | |
| 117 | +``` | |
| 118 | + | |
| 119 | +## Release | |
| 120 | + | |
| 121 | +`release-dist.sh` runs the whole publish pipeline: full-history secret scan, | |
| 122 | +multi-target build, `source.tar.gz`, `manifest.json` + `SHA256SUMS`, upload to | |
| 123 | +`dist.scorpiox.net/bot-plugins/opencode-login/<version>/`, `latest.json` and | |
| 124 | +the master `index.json` merge, and the one-way mirror push to | |
| 125 | +`plugingit.scorpiox.net/scorpiox-bot-plugin-opencode-login.git`. | |
| 126 | + | |
| 127 | +The mirror push has three hard requirements, all measured the hard way: | |
| 128 | +the push URL user must be the literal `token` | |
| 129 | +(`https://token:<PAT>@plugingit.scorpiox.net/...`); a first release needs | |
| 130 | +`POST /api?r=repos&name=<repo>` **with a request body** and the header | |
| 131 | +`Authorization: token <PAT>`; and the push must run over HTTP/1.1 | |
| 132 | +(`git -c http.version=HTTP/1.1 push`). | |
| 133 | + | |
| 134 | +## Never emit Content-Length | |
| 135 | + | |
| 136 | +The plugin writes `Content-Type`, `Cache-Control` and the security headers but | |
| 137 | +deliberately never a `Content-Length`. The reverse proxy in front of the bot | |
| 138 | +gets confused by a length that does not survive the CGI-to-HTTP rewrite and | |
| 139 | +answers 502. |
| 1 | 1 | new file mode 100644 |
| index 0000000..0573a29 | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,34 @@ | ||
| 1 | +# build.ps1 - build plugin_opencode_login.exe on a Windows box with MinGW-w64. | |
| 2 | +# | |
| 3 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 -Cc C:\gcc16\mingw64\bin\gcc.exe | |
| 5 | +# | |
| 6 | +# The generated page header (src/ui_html.h) is produced from src/ui.html by | |
| 7 | +# tools/gen_ui.py. If python3 is not on the box, the checked-in header is used | |
| 8 | +# as-is; the test suite is the place that proves the two agree. | |
| 9 | + | |
| 10 | +param( | |
| 11 | + [string]$Cc = "x86_64-w64-mingw32-gcc", | |
| 12 | + [string]$Out = "plugin_opencode_login.exe" | |
| 13 | +) | |
| 14 | + | |
| 15 | +$ErrorActionPreference = "Stop" | |
| 16 | +$Root = Split-Path -Parent $MyInvocation.MyCommand.Path | |
| 17 | +Set-Location $Root | |
| 18 | + | |
| 19 | +if (Get-Command python3 -ErrorAction SilentlyContinue) { | |
| 20 | + python3 tools/gen_ui.py | |
| 21 | +} elseif (Get-Command python -ErrorAction SilentlyContinue) { | |
| 22 | + python tools/gen_ui.py | |
| 23 | +} else { | |
| 24 | + Write-Host "no python on this box - using the checked-in src/ui_html.h" | |
| 25 | +} | |
| 26 | + | |
| 27 | +Write-Host "==> building $Out with $Cc" | |
| 28 | +& $Cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -static -I src ` | |
| 29 | + -o $Out src/plugin_opencode_login.c | |
| 30 | +if ($LASTEXITCODE -ne 0) { throw "build failed ($LASTEXITCODE)" } | |
| 31 | + | |
| 32 | +Write-Host "==> --meta" | |
| 33 | +& ".\$Out" --meta | |
| 34 | +Write-Host "==> done: $Out" |
| 1 | 1 | new file mode 100644 |
| index 0000000..7289e36 | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,17 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "opencode-login", | |
| 3 | + "id": "plugin_opencode_login", | |
| 4 | + "name": "opencode", | |
| 5 | + "desc": "OpenCode login", | |
| 6 | + "title": "OpenCode Login", | |
| 7 | + "summary": "Device code login and account token manager for OpenCode on this node. Starts the SXLOGIN-MACHINE-V1 device flow through the node's own login CLI, shows the one-time user code, polls for approval without blocking, cancels a half-finished flow, and re-reads the stored token on demand. It reports presence and expiry of credentials only and never prints, logs or returns a token value.", | |
| 8 | + "category": "devtools", | |
| 9 | + "license": "MIT", | |
| 10 | + "capabilities": [ | |
| 11 | + "credentials_read", | |
| 12 | + "oauth_device_flow" | |
| 13 | + ], | |
| 14 | + "trust_notice": "Executes native C code on your node. It runs scorpiox-opencode-login and scorpiox-opencode-fetchtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to the provider over TLS. This plugin itself opens no socket and carries no secret. It reads only ~/.config/opencode/auth.json, ~/.opencode/token.json, ~/.claude/.login-pending/opencode-default.json and ~/.claude/scorpiox-env/superopencode.txt, and every response reports token presence and expiry only - never a token value. Credentials are saved locally and never leave your node.", | |
| 15 | + "author": "SCORPIOX INC", | |
| 16 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-opencode-login" | |
| 17 | +} |
| 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..8dc72be | ||
| --- /dev/null | ||
| +++ b/src/plugin_opencode_login.c | ||
| @@ -0,0 +1,1340 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_opencode_login - SCORPIOX BOT open-source OpenCode device-code login | |
| 3 | + * and account 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 in this binary): the OpenCode device flow | |
| 11 | + * is a sequence of HTTPS POSTs to the provider, and a public clean-room | |
| 12 | + * repository must not carry a client secret or a vendored TLS stack. So this | |
| 13 | + * plugin does not speak TLS at all. It drives the node's own login CLI, exactly | |
| 14 | + * the way the SCORPIOX CODE login tools are meant to be driven (the machine | |
| 15 | + * mode contract: --status / --start / --poll / --cancel, one JSON line per | |
| 16 | + * call), and it reads the credential file that the CLI writes: | |
| 17 | + * | |
| 18 | + * ~/.config/opencode/auth.json (access + refresh token) | |
| 19 | + * ~/.claude/.login-pending/opencode-default.json (pending device flow) | |
| 20 | + * ~/.claude/scorpiox-env/superopencode.txt (the profile the CLI creates) | |
| 21 | + * | |
| 22 | + * Every one of those paths and both CLIs can be overridden for deterministic | |
| 23 | + * offline testing: | |
| 24 | + * | |
| 25 | + * OPENCODE_CREDS_PATH the credential json (default ~/.config/opencode/auth.json) | |
| 26 | + * OPENCODE_PENDING_PATH the pending-flow marker | |
| 27 | + * OPENCODE_LOGIN_BIN the login CLI (default scorpiox-opencode-login) | |
| 28 | + * OPENCODE_TOKEN_BIN the token CLI (default scorpiox-opencode-fetchtoken) | |
| 29 | + * OPENCODE_ENV_DIR the profile dir (default ~/.claude/scorpiox-env) | |
| 30 | + * | |
| 31 | + * No token is ever printed, logged or returned by this plugin: the API reports | |
| 32 | + * presence and expiry only, and the refresh action reports success or the | |
| 33 | + * failure reason from the token CLI with the payload discarded. | |
| 34 | + * | |
| 35 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 36 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 37 | + * scorpiox-server on the node. | |
| 38 | + * | |
| 39 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 40 | + */ | |
| 41 | + | |
| 42 | +/* Must come before every include on Windows: MinGW defaults to 0x502 | |
| 43 | + * (Server 2003), which hides the Win7+ APIs and the path helpers. */ | |
| 44 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 45 | +# define _WIN32_WINNT 0x0601 | |
| 46 | +#endif | |
| 47 | + | |
| 48 | +#if !defined(_WIN32) | |
| 49 | +# define _POSIX_C_SOURCE 200809L | |
| 50 | +# define _DEFAULT_SOURCE 1 | |
| 51 | +# if defined(__APPLE__) | |
| 52 | +# define _DARWIN_C_SOURCE 1 | |
| 53 | +# endif | |
| 54 | +#endif | |
| 55 | + | |
| 56 | +#include <stdio.h> | |
| 57 | +#include <stdlib.h> | |
| 58 | +#include <string.h> | |
| 59 | +#include <ctype.h> | |
| 60 | +#include <errno.h> | |
| 61 | +#include <time.h> | |
| 62 | +#include <stdarg.h> | |
| 63 | + | |
| 64 | +#if defined(_WIN32) | |
| 65 | +# define WIN32_LEAN_AND_MEAN | |
| 66 | +# include <windows.h> | |
| 67 | +# include <direct.h> | |
| 68 | +# include <io.h> | |
| 69 | +#else | |
| 70 | +# include <unistd.h> | |
| 71 | +# include <sys/stat.h> | |
| 72 | +# include <sys/types.h> | |
| 73 | +#endif | |
| 74 | + | |
| 75 | +#include "bot_theme_plugin.h" | |
| 76 | +#include "ui_html.h" | |
| 77 | + | |
| 78 | +#define PLUGIN_SLUG "opencode-login" | |
| 79 | +#define PLUGIN_ID "plugin_opencode_login" | |
| 80 | +#define PLUGIN_VER "1.0.0" | |
| 81 | +#define PLUGIN_NAME "opencode" | |
| 82 | +#define PLUGIN_DESC "OpenCode login" | |
| 83 | + | |
| 84 | +#define PATH_SZ 1024 | |
| 85 | +#define LABEL_SZ 256 | |
| 86 | +#define ORG_SZ 256 | |
| 87 | +#define CODE_SZ 64 | |
| 88 | +#define URL_SZ 1024 | |
| 89 | +#define CMD_SZ 4096 | |
| 90 | +#define OUT_MAX (256 * 1024) | |
| 91 | +#define FIELD_SZ 512 | |
| 92 | + | |
| 93 | +#define DEFAULT_LOGIN_BIN "scorpiox-opencode-login" | |
| 94 | +#define DEFAULT_TOKEN_BIN "scorpiox-opencode-fetchtoken" | |
| 95 | + | |
| 96 | +/* The device-flow marker the login CLI writes and removes. Its TTL matches the | |
| 97 | + * CLI's own (900 s); the plugin only uses it to decide whether the UI should | |
| 98 | + * show a live polling indicator, never to authorise anything. */ | |
| 99 | +#define PENDING_TTL_SEC 900 | |
| 100 | + | |
| 101 | +/* ------------------------------------------------------------------ */ | |
| 102 | +/* Growable byte buffer */ | |
| 103 | +/* ------------------------------------------------------------------ */ | |
| 104 | + | |
| 105 | +typedef struct { | |
| 106 | + char *p; | |
| 107 | + size_t n; | |
| 108 | + size_t cap; | |
| 109 | +} buf_t; | |
| 110 | + | |
| 111 | +static void buf_init(buf_t *b) | |
| 112 | +{ | |
| 113 | + b->p = NULL; | |
| 114 | + b->n = 0; | |
| 115 | + b->cap = 0; | |
| 116 | +} | |
| 117 | + | |
| 118 | +static int buf_need(buf_t *b, size_t extra) | |
| 119 | +{ | |
| 120 | + size_t want = b->n + extra + 1; | |
| 121 | + char *np; | |
| 122 | + | |
| 123 | + if (want <= b->cap) return 1; | |
| 124 | + if (b->cap == 0) b->cap = 1024; | |
| 125 | + while (b->cap < want) { | |
| 126 | + if (b->cap > (size_t)32 * 1024 * 1024) return 0; | |
| 127 | + b->cap *= 2; | |
| 128 | + } | |
| 129 | + np = (char *)realloc(b->p, b->cap); | |
| 130 | + if (!np) return 0; | |
| 131 | + b->p = np; | |
| 132 | + return 1; | |
| 133 | +} | |
| 134 | + | |
| 135 | +static int buf_addc(buf_t *b, char c) | |
| 136 | +{ | |
| 137 | + if (!buf_need(b, 1)) return 0; | |
| 138 | + b->p[b->n++] = c; | |
| 139 | + b->p[b->n] = '\0'; | |
| 140 | + return 1; | |
| 141 | +} | |
| 142 | + | |
| 143 | +static int buf_adds(buf_t *b, const char *s) | |
| 144 | +{ | |
| 145 | + size_t len; | |
| 146 | + if (!s) return 1; | |
| 147 | + len = strlen(s); | |
| 148 | + if (!buf_need(b, len)) return 0; | |
| 149 | + memcpy(b->p + b->n, s, len); | |
| 150 | + b->n += len; | |
| 151 | + b->p[b->n] = '\0'; | |
| 152 | + return 1; | |
| 153 | +} | |
| 154 | + | |
| 155 | +static int buf_addf(buf_t *b, const char *fmt, ...) | |
| 156 | +{ | |
| 157 | + char tmp[2048]; | |
| 158 | + va_list ap; | |
| 159 | + int n; | |
| 160 | + | |
| 161 | + va_start(ap, fmt); | |
| 162 | + n = vsnprintf(tmp, sizeof(tmp), fmt, ap); | |
| 163 | + va_end(ap); | |
| 164 | + if (n < 0) return 0; | |
| 165 | + if ((size_t)n >= sizeof(tmp)) n = (int)sizeof(tmp) - 1; | |
| 166 | + return buf_adds(b, tmp); | |
| 167 | +} | |
| 168 | + | |
| 169 | +/* Append s as a JSON string literal (escapes control characters). */ | |
| 170 | +static int buf_json(buf_t *b, const char *s) | |
| 171 | +{ | |
| 172 | + if (!buf_addc(b, '"')) return 0; | |
| 173 | + for (; s && *s; s++) { | |
| 174 | + unsigned char c = (unsigned char)*s; | |
| 175 | + switch (c) { | |
| 176 | + case '"': if (!buf_adds(b, "\\\"")) return 0; continue; | |
| 177 | + case '\\': if (!buf_adds(b, "\\\\")) return 0; continue; | |
| 178 | + case '\n': if (!buf_adds(b, "\\n")) return 0; continue; | |
| 179 | + case '\r': if (!buf_adds(b, "\\r")) return 0; continue; | |
| 180 | + case '\t': if (!buf_adds(b, "\\t")) return 0; continue; | |
| 181 | + default: break; | |
| 182 | + } | |
| 183 | + if (c < 0x20) { if (!buf_addf(b, "\\u%04x", c)) return 0; } | |
| 184 | + else if (!buf_addc(b, (char)c)) return 0; | |
| 185 | + } | |
| 186 | + return buf_addc(b, '"'); | |
| 187 | +} | |
| 188 | + | |
| 189 | +static const char *buf_str(buf_t *b) | |
| 190 | +{ | |
| 191 | + if (!b->p) return ""; | |
| 192 | + return b->p; | |
| 193 | +} | |
| 194 | + | |
| 195 | +static void buf_free(buf_t *b) | |
| 196 | +{ | |
| 197 | + free(b->p); | |
| 198 | + b->p = NULL; | |
| 199 | + b->n = 0; | |
| 200 | + b->cap = 0; | |
| 201 | +} | |
| 202 | + | |
| 203 | +/* ------------------------------------------------------------------ */ | |
| 204 | +/* Query string */ | |
| 205 | +/* ------------------------------------------------------------------ */ | |
| 206 | + | |
| 207 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 208 | +{ | |
| 209 | + size_t klen; | |
| 210 | + const char *p; | |
| 211 | + | |
| 212 | + if (!out || outsz == 0) return 0; | |
| 213 | + out[0] = '\0'; | |
| 214 | + if (!qs || !key) return 0; | |
| 215 | + klen = strlen(key); | |
| 216 | + p = qs; | |
| 217 | + while (*p) { | |
| 218 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 219 | + size_t i = 0; | |
| 220 | + p += klen + 1; | |
| 221 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | |
| 222 | + out[i] = '\0'; | |
| 223 | + return 1; | |
| 224 | + } | |
| 225 | + p = strchr(p, '&'); | |
| 226 | + if (!p) break; | |
| 227 | + p++; | |
| 228 | + } | |
| 229 | + return 0; | |
| 230 | +} | |
| 231 | + | |
| 232 | +static int query_has(const char *qs, const char *key) | |
| 233 | +{ | |
| 234 | + size_t klen = strlen(key); | |
| 235 | + const char *p = qs; | |
| 236 | + | |
| 237 | + while (p && *p) { | |
| 238 | + if (strncmp(p, key, klen) == 0 && | |
| 239 | + (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) | |
| 240 | + return 1; | |
| 241 | + p = strchr(p, '&'); | |
| 242 | + if (!p) break; | |
| 243 | + p++; | |
| 244 | + } | |
| 245 | + return 0; | |
| 246 | +} | |
| 247 | + | |
| 248 | + | |
| 249 | +/* ------------------------------------------------------------------ */ | |
| 250 | +/* Node auth (X-Bot-Password / Bearer / ?pwd=) */ | |
| 251 | +/* ------------------------------------------------------------------ */ | |
| 252 | + | |
| 253 | +static void require_node_auth(void) | |
| 254 | +{ | |
| 255 | + const char *np = getenv("BOT_PASSWORD"); | |
| 256 | + const char *xp; | |
| 257 | + const char *auth; | |
| 258 | + char qpwd[256] = {0}; | |
| 259 | + | |
| 260 | + if (!np || !*np) return; | |
| 261 | + | |
| 262 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 263 | + if (xp && strcmp(xp, np) == 0) return; | |
| 264 | + | |
| 265 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 266 | + if (auth) { | |
| 267 | + while (*auth == ' ') auth++; | |
| 268 | + if (strncasecmp(auth, "Bearer ", 7) == 0) { | |
| 269 | + auth += 7; | |
| 270 | + while (*auth == ' ') auth++; | |
| 271 | + if (strcmp(auth, np) == 0) return; | |
| 272 | + } | |
| 273 | + } | |
| 274 | + | |
| 275 | + if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && | |
| 276 | + strcmp(qpwd, np) == 0) return; | |
| 277 | + | |
| 278 | + fputs("Status: 401 Unauthorized\r\n" | |
| 279 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 280 | + "Cache-Control: no-store\r\n\r\n" | |
| 281 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 282 | + exit(0); | |
| 283 | +} | |
| 284 | + | |
| 285 | +/* ------------------------------------------------------------------ */ | |
| 286 | +/* Paths */ | |
| 287 | +/* ------------------------------------------------------------------ */ | |
| 288 | + | |
| 289 | +static const char *home_dir(void) | |
| 290 | +{ | |
| 291 | +#ifdef _WIN32 | |
| 292 | + static char home[512]; | |
| 293 | + DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); | |
| 294 | + if (n > 0 && n < sizeof(home)) return home; | |
| 295 | + home[0] = '\0'; | |
| 296 | + if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) { | |
| 297 | + char tmp[512]; | |
| 298 | + if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { | |
| 299 | + strncat(home, tmp, sizeof(home) - strlen(home) - 1); | |
| 300 | + return home; | |
| 301 | + } | |
| 302 | + } | |
| 303 | + return NULL; | |
| 304 | +#else | |
| 305 | + const char *h = getenv("HOME"); | |
| 306 | + return (h && *h) ? h : NULL; | |
| 307 | +#endif | |
| 308 | +} | |
| 309 | + | |
| 310 | +#if defined(_WIN32) | |
| 311 | +# define PATH_SEP '\\' | |
| 312 | +#else | |
| 313 | +# define PATH_SEP '/' | |
| 314 | +#endif | |
| 315 | + | |
| 316 | +/* Credential json: OPENCODE_CREDS_PATH, else ~/.config/opencode/auth.json - | |
| 317 | + * the file the login CLI actually writes. ~/.opencode/token.json is probed as a | |
| 318 | + * secondary location so a relocated or hand-written install is still seen. */ | |
| 319 | +static void creds_path(char *out, size_t n) | |
| 320 | +{ | |
| 321 | + const char *env = getenv("OPENCODE_CREDS_PATH"); | |
| 322 | + const char *home = home_dir(); | |
| 323 | + | |
| 324 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 325 | + if (!home) { snprintf(out, n, "auth.json"); return; } | |
| 326 | + snprintf(out, n, "%s%c.config%copencode%cauth.json", | |
| 327 | + home, PATH_SEP, PATH_SEP, PATH_SEP); | |
| 328 | +} | |
| 329 | + | |
| 330 | +/* The secondary, spec-named location (only consulted when the primary is | |
| 331 | + * absent, so a normal install never pays for it). */ | |
| 332 | +static int creds_path_alt(char *out, size_t n) | |
| 333 | +{ | |
| 334 | + const char *home = home_dir(); | |
| 335 | + | |
| 336 | + if (getenv("OPENCODE_CREDS_PATH")) return 0; /* override wins outright */ | |
| 337 | + if (!home) return 0; | |
| 338 | + snprintf(out, n, "%s%c.opencode%ctoken.json", home, PATH_SEP, PATH_SEP); | |
| 339 | + return 1; | |
| 340 | +} | |
| 341 | + | |
| 342 | +/* The pending device-flow marker written by the login CLI. */ | |
| 343 | +static void pending_path(char *out, size_t n) | |
| 344 | +{ | |
| 345 | + const char *env = getenv("OPENCODE_PENDING_PATH"); | |
| 346 | + const char *home = home_dir(); | |
| 347 | + | |
| 348 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 349 | + if (!home) { snprintf(out, n, "opencode-default.json"); return; } | |
| 350 | + snprintf(out, n, "%s%c.claude%c.login-pending%copencode-default.json", | |
| 351 | + home, PATH_SEP, PATH_SEP, PATH_SEP); | |
| 352 | +} | |
| 353 | + | |
| 354 | +static void env_dir(char *out, size_t n) | |
| 355 | +{ | |
| 356 | + const char *env = getenv("OPENCODE_ENV_DIR"); | |
| 357 | + const char *creds = getenv("OPENCODE_CREDS_PATH"); | |
| 358 | + const char *home = home_dir(); | |
| 359 | + | |
| 360 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 361 | + | |
| 362 | + /* A relocated credential file implies a relocated profile: they are written | |
| 363 | + * by the same CLI into the same tree, and reading one from the default home | |
| 364 | + * while the other is overridden makes status report a missing profile for a | |
| 365 | + * session that has one. */ | |
| 366 | + if (creds && *creds) { | |
| 367 | + char base[PATH_SZ]; | |
| 368 | + char *slash; | |
| 369 | + snprintf(base, sizeof(base), "%s", creds); | |
| 370 | + slash = strrchr(base, PATH_SEP); | |
| 371 | + if (!slash) slash = strrchr(base, '/'); | |
| 372 | + if (slash) { | |
| 373 | + *(slash + 1) = '\0'; | |
| 374 | + if (strlen(base) + 16 < n) { snprintf(out, n, "%sscorpiox-env", base); return; } | |
| 375 | + } | |
| 376 | + } | |
| 377 | + | |
| 378 | + if (!home) { snprintf(out, n, "."); return; } | |
| 379 | + snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); | |
| 380 | +} | |
| 381 | + | |
| 382 | +static void profile_path(char *out, size_t n) | |
| 383 | +{ | |
| 384 | + char d[PATH_SZ]; | |
| 385 | + | |
| 386 | + env_dir(d, sizeof(d)); | |
| 387 | + /* Copy with explicit bounds so a long directory cannot have its tail | |
| 388 | + * replaced by the filename (snprintf would silently truncate). */ | |
| 389 | + { | |
| 390 | + const char *name = "superopencode.txt"; | |
| 391 | + size_t dl = strlen(d); | |
| 392 | + if (dl + 1 + strlen(name) >= n) { snprintf(out, n, "%s", name); return; } | |
| 393 | + memcpy(out, d, dl); | |
| 394 | + out[dl] = PATH_SEP; | |
| 395 | + memcpy(out + dl + 1, name, strlen(name) + 1); | |
| 396 | + } | |
| 397 | +} | |
| 398 | + | |
| 399 | +static const char *login_bin(void) | |
| 400 | +{ | |
| 401 | + const char *b = getenv("OPENCODE_LOGIN_BIN"); | |
| 402 | + return (b && *b) ? b : DEFAULT_LOGIN_BIN; | |
| 403 | +} | |
| 404 | + | |
| 405 | +static const char *token_bin(void) | |
| 406 | +{ | |
| 407 | + const char *b = getenv("OPENCODE_TOKEN_BIN"); | |
| 408 | + return (b && *b) ? b : DEFAULT_TOKEN_BIN; | |
| 409 | +} | |
| 410 | + | |
| 411 | +static int file_exists(const char *p) | |
| 412 | +{ | |
| 413 | +#if defined(_WIN32) | |
| 414 | + DWORD a = GetFileAttributesA(p); | |
| 415 | + return (a != (DWORD)-1); | |
| 416 | +#else | |
| 417 | + struct stat st; | |
| 418 | + return p && *p && stat(p, &st) == 0; | |
| 419 | +#endif | |
| 420 | +} | |
| 421 | + | |
| 422 | +/* Whole-file read; NULL on any failure. Caller frees. */ | |
| 423 | +static char *read_file(const char *path) | |
| 424 | +{ | |
| 425 | + FILE *f; | |
| 426 | + long sz; | |
| 427 | + char *buf; | |
| 428 | + | |
| 429 | + if (!path || !*path) return NULL; | |
| 430 | + f = fopen(path, "rb"); | |
| 431 | + if (!f) return NULL; | |
| 432 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } | |
| 433 | + sz = ftell(f); | |
| 434 | + if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } | |
| 435 | + if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } | |
| 436 | + buf = (char *)malloc((size_t)sz + 1); | |
| 437 | + if (!buf) { fclose(f); return NULL; } | |
| 438 | + if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { | |
| 439 | + free(buf); | |
| 440 | + fclose(f); | |
| 441 | + return NULL; | |
| 442 | + } | |
| 443 | + buf[sz] = '\0'; | |
| 444 | + fclose(f); | |
| 445 | + return buf; | |
| 446 | +} | |
| 447 | + | |
| 448 | +/* Trim trailing CR/LF/space in place. */ | |
| 449 | +static void trim_tail(char *s) | |
| 450 | +{ | |
| 451 | + size_t n; | |
| 452 | + if (!s) return; | |
| 453 | + n = strlen(s); | |
| 454 | + while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || | |
| 455 | + s[n - 1] == ' ' || s[n - 1] == '\t')) | |
| 456 | + s[--n] = '\0'; | |
| 457 | +} | |
| 458 | + | |
| 459 | +/* ------------------------------------------------------------------ */ | |
| 460 | +/* Minimal JSON field readers */ | |
| 461 | +/* ------------------------------------------------------------------ */ | |
| 462 | + | |
| 463 | +/* Copy a JSON string value that starts at *pp (which points at the opening | |
| 464 | + * quote). Advances *pp past the closing quote. */ | |
| 465 | +static int json_read_string_at(const char **pp, char *out, size_t outsz) | |
| 466 | +{ | |
| 467 | + const char *p = *pp; | |
| 468 | + size_t i = 0; | |
| 469 | + | |
| 470 | + if (!p || *p != '"') return 0; | |
| 471 | + p++; | |
| 472 | + while (*p && *p != '"') { | |
| 473 | + char c = *p; | |
| 474 | + if (c == '\\' && p[1]) { | |
| 475 | + p++; | |
| 476 | + switch (*p) { | |
| 477 | + case 'n': c = '\n'; break; | |
| 478 | + case 'r': c = '\r'; break; | |
| 479 | + case 't': c = '\t'; break; | |
| 480 | + case 'b': c = '\b'; break; | |
| 481 | + case 'f': c = '\f'; break; | |
| 482 | + case 'u': { | |
| 483 | + unsigned int v = 0; | |
| 484 | + int k; | |
| 485 | + p++; | |
| 486 | + for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) | |
| 487 | + v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) | |
| 488 | + ? *p - '0' | |
| 489 | + : tolower((unsigned char)*p) - 'a' + 10); | |
| 490 | + if (i + 1 < outsz) out[i++] = (char)(v & 0xff); | |
| 491 | + continue; | |
| 492 | + } | |
| 493 | + default: c = *p; break; | |
| 494 | + } | |
| 495 | + p++; | |
| 496 | + } else { | |
| 497 | + p++; | |
| 498 | + } | |
| 499 | + if (i + 1 < outsz) out[i++] = c; | |
| 500 | + } | |
| 501 | + if (*p == '"') p++; | |
| 502 | + if (outsz) out[i < outsz ? i : outsz - 1] = '\0'; | |
| 503 | + *pp = p; | |
| 504 | + return 1; | |
| 505 | +} | |
| 506 | + | |
| 507 | + | |
| 508 | +/* Find "key":<value> anywhere inside the slice [obj, end) and return the | |
| 509 | + * value pointer. Only top-level keys of that slice are considered: a nested | |
| 510 | + * object is skipped as a whole. */ | |
| 511 | +static const char *json_find_key(const char *obj, const char *end, const char *key) | |
| 512 | +{ | |
| 513 | + size_t klen = strlen(key); | |
| 514 | + const char *p = obj; | |
| 515 | + int depth = 0; | |
| 516 | + | |
| 517 | + if (!obj || !end || !key) return NULL; | |
| 518 | + /* A caller almost always hands us the whole object, i.e. a pointer at the | |
| 519 | + * opening '{'. Skipping it here keeps every call site free of the "+1" | |
| 520 | + * that is easy to forget and silent when it is missing. */ | |
| 521 | + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; | |
| 522 | + if (p < end && *p == '{') p++; | |
| 523 | + | |
| 524 | + while (p && p < end) { | |
| 525 | + if (*p == '"') { | |
| 526 | + char name[128]; | |
| 527 | + json_read_string_at(&p, name, sizeof(name)); | |
| 528 | + if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { | |
| 529 | + const char *q = p; | |
| 530 | + while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; | |
| 531 | + if (q < end && *q == ':') { | |
| 532 | + q++; | |
| 533 | + while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; | |
| 534 | + return (q < end) ? q : NULL; | |
| 535 | + } | |
| 536 | + } | |
| 537 | + continue; | |
| 538 | + } | |
| 539 | + if (*p == '{' || *p == '[') depth++; | |
| 540 | + else if (*p == '}' || *p == ']') depth--; | |
| 541 | + p++; | |
| 542 | + } | |
| 543 | + return NULL; | |
| 544 | +} | |
| 545 | + | |
| 546 | +/* Returns 0 and leaves *out untouched when the key is absent or null. That | |
| 547 | + * matters: several callers pass a field of a longer-lived struct, and clearing | |
| 548 | + * it on a miss silently erases a value that was already correct. */ | |
| 549 | +static int json_str_field(const char *obj, const char *end, const char *key, | |
| 550 | + char *out, size_t outsz) | |
| 551 | +{ | |
| 552 | + const char *v; | |
| 553 | + | |
| 554 | + if (!out || outsz == 0) return 0; | |
| 555 | + v = json_find_key(obj, end, key); | |
| 556 | + if (!v || *v == 'n') return 0; | |
| 557 | + out[0] = '\0'; | |
| 558 | + if (*v == '"') return json_read_string_at(&v, out, outsz); | |
| 559 | + { | |
| 560 | + size_t i = 0; | |
| 561 | + while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; | |
| 562 | + out[i] = '\0'; | |
| 563 | + trim_tail(out); | |
| 564 | + return out[0] ? 1 : 0; | |
| 565 | + } | |
| 566 | +} | |
| 567 | + | |
| 568 | +static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) | |
| 569 | +{ | |
| 570 | + const char *v = json_find_key(obj, end, key); | |
| 571 | + | |
| 572 | + if (!v) return dflt; | |
| 573 | + if (strncmp(v, "true", 4) == 0) return 1; | |
| 574 | + if (strncmp(v, "false", 5) == 0) return 0; | |
| 575 | + if (*v == '"') { | |
| 576 | + if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1; | |
| 577 | + return 0; | |
| 578 | + } | |
| 579 | + if (*v == '1') return 1; | |
| 580 | + return 0; | |
| 581 | +} | |
| 582 | + | |
| 583 | +static long long json_num_field(const char *obj, const char *end, const char *key) | |
| 584 | +{ | |
| 585 | + const char *v = json_find_key(obj, end, key); | |
| 586 | + long long vll = 0; | |
| 587 | + int neg = 0; | |
| 588 | + | |
| 589 | + if (!v) return 0; | |
| 590 | + if (*v == '"') v++; | |
| 591 | + if (*v == '-') { neg = 1; v++; } | |
| 592 | + while (isdigit((unsigned char)*v)) { vll = vll * 10 + (*v++ - '0'); } | |
| 593 | + return neg ? -vll : vll; | |
| 594 | +} | |
| 595 | + | |
| 596 | +/* True when the object contains a non-empty string under key. Used for token | |
| 597 | + * presence without ever copying the token itself into a wider buffer. */ | |
| 598 | +static int json_str_present(const char *obj, const char *end, const char *key) | |
| 599 | +{ | |
| 600 | + const char *v = json_find_key(obj, end, key); | |
| 601 | + const char *q; | |
| 602 | + | |
| 603 | + if (!v) return 0; | |
| 604 | + if (*v != '"') return 0; | |
| 605 | + q = v + 1; | |
| 606 | + while (*q && *q != '"') { | |
| 607 | + if (*q == '\\' && q[1]) { q += 2; continue; } | |
| 608 | + return 1; /* at least one real character */ | |
| 609 | + } | |
| 610 | + return 0; /* "" - present but empty */ | |
| 611 | +} | |
| 612 | + | |
| 613 | +/* ------------------------------------------------------------------ */ | |
| 614 | +/* Running the node's login CLI */ | |
| 615 | +/* ------------------------------------------------------------------ */ | |
| 616 | + | |
| 617 | +/* Wrap a string in single quotes for the shell, so a path or a binary name | |
| 618 | + * containing spaces or punctuation cannot break the command line. */ | |
| 619 | +static void shell_quote_into(const char *in, char *out, size_t outsz) | |
| 620 | +{ | |
| 621 | + size_t o = 0; | |
| 622 | + const char *p; | |
| 623 | + | |
| 624 | + if (outsz < 3) { if (outsz) out[0] = '\0'; return; } | |
| 625 | + out[o++] = '\''; | |
| 626 | + for (p = in; p && *p; p++) { | |
| 627 | + if (*p == '\'') { | |
| 628 | + if (o + 5 >= outsz) break; | |
| 629 | + memcpy(out + o, "'\\''", 4); | |
| 630 | + o += 4; | |
| 631 | + } else { | |
| 632 | + if (o + 2 >= outsz) break; | |
| 633 | + out[o++] = *p; | |
| 634 | + } | |
| 635 | + } | |
| 636 | + out[o++] = '\''; | |
| 637 | + out[o] = '\0'; | |
| 638 | +} | |
| 639 | + | |
| 640 | +/* Run `<bin> <args>` and capture stdout. args may be NULL or a pre-built | |
| 641 | + * shell fragment. Returns 1 when the process ran, -1 when the binary was not | |
| 642 | + * found, 0 when popen itself failed. The captured text is stored in out. */ | |
| 643 | +static int run_capture(const char *bin, const char *args, buf_t *out) | |
| 644 | +{ | |
| 645 | + char cmd[CMD_SZ]; | |
| 646 | + char qbin[FIELD_SZ]; | |
| 647 | + FILE *f; | |
| 648 | + char line[2048]; | |
| 649 | + size_t total = 0; | |
| 650 | + int rc; | |
| 651 | + | |
| 652 | + if (!bin || !*bin) return 0; | |
| 653 | + shell_quote_into(bin, qbin, sizeof(qbin)); | |
| 654 | + if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); | |
| 655 | + else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); | |
| 656 | + | |
| 657 | + f = popen(cmd, "r"); | |
| 658 | + if (!f) return 0; | |
| 659 | + while (fgets(line, sizeof(line), f)) { | |
| 660 | + total += strlen(line); | |
| 661 | + if (total > OUT_MAX) break; | |
| 662 | + buf_adds(out, line); | |
| 663 | + } | |
| 664 | + rc = pclose(f); | |
| 665 | + | |
| 666 | + if (out->p) { | |
| 667 | + /* the CLIs print one JSON line last; strip surrounding whitespace */ | |
| 668 | + size_t n = out->n; | |
| 669 | + while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; | |
| 670 | + out->n = n; | |
| 671 | + } | |
| 672 | + /* pclose() hands back a wait status, not an exit code: "command not | |
| 673 | + * found" arrives as 32512 (127 << 8). Callers treat that as "the CLI is | |
| 674 | + * not on this node", which is a different message from "the CLI ran and | |
| 675 | + * failed". Any other status is the CLI's own and is left to the JSON it | |
| 676 | + * printed. */ | |
| 677 | + if (rc != -1 && (rc >> 8) == 127) return -1; | |
| 678 | + return 1; | |
| 679 | +} | |
| 680 | + | |
| 681 | +/* The login CLI prints human progress on stdout before the final JSON line, | |
| 682 | + * so take the LAST line that starts with '{'. */ | |
| 683 | +static const char *last_json_line(buf_t *b) | |
| 684 | +{ | |
| 685 | + size_t i; | |
| 686 | + const char *last = NULL; | |
| 687 | + | |
| 688 | + if (!b || !b->p) return NULL; | |
| 689 | + for (i = 0; i < b->n; i++) { | |
| 690 | + int at_line_start = (i == 0) || b->p[i - 1] == '\n'; | |
| 691 | + if (at_line_start && b->p[i] == '{') last = b->p + i; | |
| 692 | + } | |
| 693 | + return last; | |
| 694 | +} | |
| 695 | + | |
| 696 | +/* ------------------------------------------------------------------ */ | |
| 697 | +/* Status model */ | |
| 698 | +/* ------------------------------------------------------------------ */ | |
| 699 | + | |
| 700 | +typedef struct { | |
| 701 | + char path[PATH_SZ]; | |
| 702 | + char account[LABEL_SZ]; | |
| 703 | + char org[ORG_SZ]; | |
| 704 | + char profile[LABEL_SZ]; | |
| 705 | + long long expires_at; /* unix seconds, 0 = unknown */ | |
| 706 | + int logged_in; | |
| 707 | + int has_refresh; | |
| 708 | + int expired; | |
| 709 | + int pending; | |
| 710 | + long long pending_age; /* seconds since the marker was written, -1 unknown */ | |
| 711 | + int profile_exists; | |
| 712 | + int cli_present; /* 1 when the login CLI ran at all this call */ | |
| 713 | + int cli_pending_unknown;/* 1 when no marker file exists to TTL-check */ | |
| 714 | + int cli_ok; /* 1 when the login CLI answered with ok:true */ | |
| 715 | + int token_bin_present; | |
| 716 | + char cli_error[FIELD_SZ]; | |
| 717 | +} status_t; | |
| 718 | + | |
| 719 | +/* Normalise an expiry to unix SECONDS. The credential file stores seconds | |
| 720 | + * (time(NULL) + expires_in); the machine-mode status reports milliseconds. | |
| 721 | + * A value above 1e11 can only be milliseconds on any realistic date. */ | |
| 722 | +static long long normalise_expiry(long long v) | |
| 723 | +{ | |
| 724 | + if (v <= 0) return 0; | |
| 725 | + if (v > 100000000000LL) return v / 1000; | |
| 726 | + return v; | |
| 727 | +} | |
| 728 | + | |
| 729 | +static void collect_status(status_t *st) | |
| 730 | +{ | |
| 731 | + char alt[PATH_SZ]; | |
| 732 | + char *raw; | |
| 733 | + const char *end; | |
| 734 | + long long now = (long long)time(NULL); | |
| 735 | + | |
| 736 | + memset(st, 0, sizeof(*st)); | |
| 737 | + snprintf(st->profile, sizeof(st->profile), "superopencode"); | |
| 738 | + st->pending_age = -1; | |
| 739 | + | |
| 740 | + /* 1. the credential file the CLI writes */ | |
| 741 | + creds_path(st->path, sizeof(st->path)); | |
| 742 | + raw = read_file(st->path); | |
| 743 | + if (!raw && creds_path_alt(alt, sizeof(alt)) && file_exists(alt)) { | |
| 744 | + free(raw); | |
| 745 | + raw = read_file(alt); | |
| 746 | + if (raw) snprintf(st->path, sizeof(st->path), "%s", alt); | |
| 747 | + } | |
| 748 | + if (raw) { | |
| 749 | + end = raw + strlen(raw); | |
| 750 | + st->logged_in = json_str_present(raw, end, "access_token"); | |
| 751 | + st->has_refresh = json_str_present(raw, end, "refresh_token"); | |
| 752 | + st->expires_at = normalise_expiry(json_num_field(raw, end, "expires_at")); | |
| 753 | + if (!st->expires_at) { | |
| 754 | + long long ein = json_num_field(raw, end, "expires_in"); | |
| 755 | + if (ein > 0) st->expires_at = now + ein; | |
| 756 | + } | |
| 757 | + if (json_str_field(raw, end, "org_id", st->org, sizeof(st->org))) | |
| 758 | + snprintf(st->account, sizeof(st->account), "%s", st->org); | |
| 759 | + free(raw); | |
| 760 | + } | |
| 761 | + st->expired = (st->expires_at > 0 && st->expires_at < now); | |
| 762 | + | |
| 763 | + /* 2. the pending device-flow marker, owned by the CLI but reported here. | |
| 764 | + * The marker is the only evidence the plugin can check without a | |
| 765 | + * network, and it carries the CLI's own creation stamp, so the TTL is | |
| 766 | + * applied here rather than trusting a later claim. */ | |
| 767 | + { | |
| 768 | + char pp[PATH_SZ]; | |
| 769 | + int marker = 0; | |
| 770 | + pending_path(pp, sizeof(pp)); | |
| 771 | + marker = file_exists(pp); | |
| 772 | + if (marker) { | |
| 773 | + char *pend = read_file(pp); | |
| 774 | + long long created = -1; | |
| 775 | + if (pend) { | |
| 776 | + const char *pe = pend + strlen(pend); | |
| 777 | + created = json_num_field(pend, pe, "created"); | |
| 778 | + free(pend); | |
| 779 | + } | |
| 780 | + if (created > 0) { | |
| 781 | + st->pending_age = now - created; | |
| 782 | + st->pending = (st->pending_age >= 0 && st->pending_age <= PENDING_TTL_SEC); | |
| 783 | + } else { | |
| 784 | + st->pending = 1; /* unreadable marker: assume still open */ | |
| 785 | + } | |
| 786 | + } | |
| 787 | + /* Only when there is no marker at all does the CLI's own pending bit | |
| 788 | + * get to speak: it reads the same file, so a stale-but-present marker | |
| 789 | + * must never be revived by it. */ | |
| 790 | + if (!marker) st->cli_pending_unknown = 1; | |
| 791 | + } | |
| 792 | + | |
| 793 | + /* 3. the profile file the CLI creates */ | |
| 794 | + { | |
| 795 | + char prof[PATH_SZ]; | |
| 796 | + profile_path(prof, sizeof(prof)); | |
| 797 | + st->profile_exists = file_exists(prof); | |
| 798 | + } | |
| 799 | + | |
| 800 | + /* 4. ask the CLI, and let it ADD to what the files already proved. The | |
| 801 | + * file-derived booleans win: they are what this node actually has, and | |
| 802 | + * a stale or partial CLI answer must not erase them. */ | |
| 803 | + { | |
| 804 | + buf_t b; | |
| 805 | + const char *j; | |
| 806 | + int rc; | |
| 807 | + | |
| 808 | + buf_init(&b); | |
| 809 | + rc = run_capture(login_bin(), "--status", &b); | |
| 810 | + if (rc < 0) { | |
| 811 | + st->cli_present = 0; | |
| 812 | + snprintf(st->cli_error, sizeof(st->cli_error), "cli_not_found"); | |
| 813 | + } else if (rc == 0) { | |
| 814 | + st->cli_present = 0; | |
| 815 | + snprintf(st->cli_error, sizeof(st->cli_error), "cli_spawn_failed"); | |
| 816 | + } else { | |
| 817 | + st->cli_present = 1; | |
| 818 | + j = last_json_line(&b); | |
| 819 | + if (j) { | |
| 820 | + const char *je = j + strlen(j); | |
| 821 | + st->cli_ok = json_bool_field(j, je, "ok", 0); | |
| 822 | + if (!st->cli_ok) | |
| 823 | + json_str_field(j, je, "error", st->cli_error, sizeof(st->cli_error)); | |
| 824 | + if (!st->account[0]) | |
| 825 | + json_str_field(j, je, "account", st->account, sizeof(st->account)); | |
| 826 | + if (!st->expires_at) | |
| 827 | + st->expires_at = normalise_expiry(json_num_field(j, je, "expires_at")); | |
| 828 | + if (!st->logged_in && json_bool_field(j, je, "logged_in", 0)) | |
| 829 | + st->logged_in = 1; | |
| 830 | + if (!st->has_refresh && json_bool_field(j, je, "has_refresh", 0)) | |
| 831 | + st->has_refresh = 1; | |
| 832 | + if (!st->pending && st->cli_pending_unknown && | |
| 833 | + json_bool_field(j, je, "pending", 0)) | |
| 834 | + st->pending = 1; | |
| 835 | + if (!st->profile_exists && json_bool_field(j, je, "profile_exists", 0)) | |
| 836 | + st->profile_exists = 1; | |
| 837 | + if (!st->path[0]) json_str_field(j, je, "path", st->path, sizeof(st->path)); | |
| 838 | + } | |
| 839 | + } | |
| 840 | + buf_free(&b); | |
| 841 | + } | |
| 842 | + st->expired = (st->expires_at > 0 && st->expires_at < (long long)time(NULL)); | |
| 843 | + | |
| 844 | + /* 5. is the token CLI on this node at all (used by refresh + the UI) */ | |
| 845 | + { | |
| 846 | + buf_t b; | |
| 847 | + buf_init(&b); | |
| 848 | + /* run_capture returns 1 when the process actually ran, -1 when the | |
| 849 | + * binary was not found (exit 127), 0 when popen itself failed. Only | |
| 850 | + * "it ran" counts as present: usage text, an auth error or an unknown | |
| 851 | + * flag all mean the CLI is installed here. */ | |
| 852 | + st->token_bin_present = (run_capture(token_bin(), "--help", &b) == 1); | |
| 853 | + buf_free(&b); | |
| 854 | + } | |
| 855 | +} | |
| 856 | + | |
| 857 | +/* ------------------------------------------------------------------ */ | |
| 858 | +/* JSON emitters */ | |
| 859 | +/* ------------------------------------------------------------------ */ | |
| 860 | + | |
| 861 | +static void emit_json(buf_t *b) | |
| 862 | +{ | |
| 863 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 864 | + "Cache-Control: no-store\r\n" | |
| 865 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 866 | + fputs(buf_str(b), stdout); | |
| 867 | + buf_free(b); | |
| 868 | +} | |
| 869 | + | |
| 870 | +static void emit_error(int code, const char *status, const char *err, const char *detail) | |
| 871 | +{ | |
| 872 | + buf_t b; | |
| 873 | + | |
| 874 | + buf_init(&b); | |
| 875 | + buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" | |
| 876 | + "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", | |
| 877 | + code, status); | |
| 878 | + buf_addf(&b, "{\"ok\":false,\"error\":"); | |
| 879 | + buf_json(&b, err); | |
| 880 | + if (detail && *detail) { | |
| 881 | + buf_addf(&b, ",\"detail\":"); | |
| 882 | + buf_json(&b, detail); | |
| 883 | + } | |
| 884 | + buf_addf(&b, "}\n"); | |
| 885 | + /* emit_json() would prepend its own header block again; emit_error has | |
| 886 | + * already written a Status: line, so flush the buffer directly. */ | |
| 887 | + fputs(buf_str(&b), stdout); | |
| 888 | + buf_free(&b); | |
| 889 | +} | |
| 890 | + | |
| 891 | +/* One status payload, shared by ?action=status, ?format=json, the poll "done" | |
| 892 | + * branch, cancel and refresh so the five can never disagree about what the | |
| 893 | + * node holds. `prefix` replaces the opening {"ok":true so a caller can lead | |
| 894 | + * with its own contract fields; NULL means the plain status object. */ | |
| 895 | +static void emit_status_json(buf_t *b, const status_t *st, const char *prefix) | |
| 896 | +{ | |
| 897 | + long long now = (long long)time(NULL); | |
| 898 | + long long left = st->expires_at > 0 ? st->expires_at - now : 0; | |
| 899 | + | |
| 900 | + buf_adds(b, prefix ? prefix : "{\"ok\":true"); | |
| 901 | + buf_adds(b, ",\"provider\":\"opencode\""); | |
| 902 | + buf_adds(b, ",\"logged_in\":"); buf_adds(b, st->logged_in ? "true" : "false"); | |
| 903 | + buf_adds(b, ",\"username\":"); buf_json(b, st->account[0] ? st->account : (st->logged_in ? "OpenCode" : "")); | |
| 904 | + buf_adds(b, ",\"account\":"); buf_json(b, st->account[0] ? st->account : ""); | |
| 905 | + buf_adds(b, ",\"org_id\":"); buf_json(b, st->org[0] ? st->org : ""); | |
| 906 | + buf_addf(b, ",\"expires_at\":%lld", st->expires_at); | |
| 907 | + buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_at > 0 ? left : 0); | |
| 908 | + buf_adds(b, ",\"expired\":"); buf_adds(b, st->expired ? "true" : "false"); | |
| 909 | + buf_adds(b, ",\"has_refresh\":");buf_adds(b, st->has_refresh ? "true" : "false"); | |
| 910 | + buf_adds(b, ",\"pending\":"); buf_adds(b, st->pending ? "true" : "false"); | |
| 911 | + if (st->pending_age >= 0) buf_addf(b, ",\"pending_age_sec\":%lld", st->pending_age); | |
| 912 | + buf_adds(b, ",\"profile\":"); buf_json(b, st->profile); | |
| 913 | + buf_adds(b, ",\"profile_exists\":"); | |
| 914 | + buf_adds(b, st->profile_exists ? "true" : "false"); | |
| 915 | + buf_adds(b, ",\"cli_present\":"); | |
| 916 | + buf_adds(b, st->cli_present ? "true" : "false"); | |
| 917 | + buf_adds(b, ",\"token_cli_present\":"); | |
| 918 | + buf_adds(b, st->token_bin_present ? "true" : "false"); | |
| 919 | + buf_adds(b, ",\"path\":"); buf_json(b, st->path); | |
| 920 | + if (st->cli_error[0]) { buf_adds(b, ",\"cli_error\":"); buf_json(b, st->cli_error); } | |
| 921 | + buf_adds(b, ",\"protocol\":\"SXLOGIN-MACHINE-V1\""); | |
| 922 | + buf_adds(b, ",\"plugin\":\"" PLUGIN_ID "\""); | |
| 923 | + buf_addf(b, ",\"plugin_version\":\"%s\"", PLUGIN_VER); | |
| 924 | + buf_adds(b, ",\"now\":"); | |
| 925 | + buf_addf(b, "%lld", now); | |
| 926 | + buf_adds(b, "}\n"); | |
| 927 | +} | |
| 928 | + | |
| 929 | +static int action_status(void) | |
| 930 | +{ | |
| 931 | + status_t st; | |
| 932 | + buf_t b; | |
| 933 | + | |
| 934 | + collect_status(&st); | |
| 935 | + buf_init(&b); | |
| 936 | + emit_status_json(&b, &st, NULL); | |
| 937 | + emit_json(&b); | |
| 938 | + return 0; | |
| 939 | +} | |
| 940 | + | |
| 941 | +/* ------------------------------------------------------------------ */ | |
| 942 | +/* Device flow actions */ | |
| 943 | +/* ------------------------------------------------------------------ */ | |
| 944 | + | |
| 945 | +/* Ask the login CLI to begin the device flow. `--force` is appended when the | |
| 946 | + * caller passes force=1, which is how the UI lets a user re-login over an | |
| 947 | + * existing session (the CLI refuses to clobber credentials otherwise). */ | |
| 948 | +static int action_start(void) | |
| 949 | +{ | |
| 950 | + status_t st; | |
| 951 | + buf_t in; | |
| 952 | + buf_t out; | |
| 953 | + const char *j; | |
| 954 | + char args[32]; | |
| 955 | + char verify[URL_SZ] = {0}; | |
| 956 | + char code[CODE_SZ] = {0}; | |
| 957 | + int force = 0; | |
| 958 | + int interval = 5; | |
| 959 | + long long expires_in = 900; | |
| 960 | + int rc; | |
| 961 | + | |
| 962 | + collect_status(&st); | |
| 963 | + if (!st.cli_present) { | |
| 964 | + emit_error(200, "OK", "cli_unavailable", | |
| 965 | + "scorpiox-opencode-login is not on this node"); | |
| 966 | + return 0; | |
| 967 | + } | |
| 968 | + | |
| 969 | + force = query_has(getenv("QUERY_STRING"), "force") ? 1 : 0; | |
| 970 | + | |
| 971 | + snprintf(args, sizeof(args), "--start%s", force ? " --force" : ""); | |
| 972 | + | |
| 973 | + buf_init(&in); | |
| 974 | + rc = run_capture(login_bin(), args, &in); | |
| 975 | + if (rc < 0) { | |
| 976 | + buf_free(&in); | |
| 977 | + emit_error(200, "OK", "cli_unavailable", | |
| 978 | + "scorpiox-opencode-login is not on this node"); | |
| 979 | + return 0; | |
| 980 | + } | |
| 981 | + if (rc == 0) { | |
| 982 | + buf_free(&in); | |
| 983 | + emit_error(500, "Internal Server Error", "start_failed", "cannot spawn login CLI"); | |
| 984 | + return 1; | |
| 985 | + } | |
| 986 | + | |
| 987 | + j = last_json_line(&in); | |
| 988 | + if (!j) { | |
| 989 | + buf_free(&in); | |
| 990 | + emit_error(502, "Bad Gateway", "start_failed", "login CLI produced no JSON"); | |
| 991 | + return 1; | |
| 992 | + } | |
| 993 | + { | |
| 994 | + const char *je = j + strlen(j); | |
| 995 | + if (!json_bool_field(j, je, "ok", 0)) { | |
| 996 | + char err[FIELD_SZ] = {0}; | |
| 997 | + char detail[FIELD_SZ] = {0}; | |
| 998 | + json_str_field(j, je, "error", err, sizeof(err)); | |
| 999 | + json_str_field(j, je, "detail", detail, sizeof(detail)); | |
| 1000 | + buf_free(&in); | |
| 1001 | + if (strcmp(err, "exists") == 0) { | |
| 1002 | + /* Credentials are already on this node: the honest answer is | |
| 1003 | + * "already signed in, press re-login to replace them". */ | |
| 1004 | + buf_init(&out); | |
| 1005 | + buf_adds(&out, "{\"ok\":true,\"already_logged_in\":true,\"pending\":false"); | |
| 1006 | + buf_adds(&out, ",\"error\":\"already_logged_in\""); | |
| 1007 | + buf_adds(&out, ",\"detail\":"); | |
| 1008 | + buf_json(&out, detail[0] ? detail : "credentials already exist"); | |
| 1009 | + buf_adds(&out, ",\"logged_in\":"); | |
| 1010 | + buf_adds(&out, st.logged_in ? "true" : "false"); | |
| 1011 | + buf_adds(&out, ",\"hint\":\"pass force=1 to replace the existing session\"}\n"); | |
| 1012 | + emit_json(&out); | |
| 1013 | + return 0; | |
| 1014 | + } | |
| 1015 | + emit_error(200, "OK", err[0] ? err : "start_failed", detail); | |
| 1016 | + return 0; | |
| 1017 | + } | |
| 1018 | + json_str_field(j, je, "verify_url", verify, sizeof(verify)); | |
| 1019 | + json_str_field(j, je, "user_code", code, sizeof(code)); | |
| 1020 | + interval = (int)json_num_field(j, je, "interval"); | |
| 1021 | + expires_in = json_num_field(j, je, "expires_in"); | |
| 1022 | + if (interval < 1) interval = 5; | |
| 1023 | + if (expires_in <= 0) expires_in = PENDING_TTL_SEC; | |
| 1024 | + } | |
| 1025 | + buf_free(&in); | |
| 1026 | + | |
| 1027 | + if (!verify[0] || !code[0]) { | |
| 1028 | + emit_error(502, "Bad Gateway", "start_incomplete", | |
| 1029 | + "login CLI did not return a verify url and user code"); | |
| 1030 | + return 1; | |
| 1031 | + } | |
| 1032 | + | |
| 1033 | + buf_init(&out); | |
| 1034 | + buf_addf(&out, "{\"ok\":true,\"flow\":\"device_code\",\"verify_url\":"); | |
| 1035 | + buf_json(&out, verify); | |
| 1036 | + buf_adds(&out, ",\"user_code\":"); | |
| 1037 | + buf_json(&out, code); | |
| 1038 | + buf_addf(&out, ",\"expires_in\":%lld", expires_in); | |
| 1039 | + buf_addf(&out, ",\"interval\":%d", interval); | |
| 1040 | + buf_adds(&out, ",\"pending\":true"); | |
| 1041 | + buf_adds(&out, ",\"provider\":\"opencode\"}\n"); | |
| 1042 | + emit_json(&out); | |
| 1043 | + return 0; | |
| 1044 | +} | |
| 1045 | + | |
| 1046 | +/* One non-blocking poll. The CLI does exactly one HTTPS round trip and | |
| 1047 | + * returns; the UI drives the cadence so nothing here ever blocks. */ | |
| 1048 | +static int action_poll(void) | |
| 1049 | +{ | |
| 1050 | + status_t st; | |
| 1051 | + buf_t in; | |
| 1052 | + buf_t out; | |
| 1053 | + const char *j; | |
| 1054 | + char state[64] = {0}; | |
| 1055 | + int rc; | |
| 1056 | + | |
| 1057 | + collect_status(&st); | |
| 1058 | + if (!st.cli_present) { | |
| 1059 | + emit_error(200, "OK", "cli_unavailable", | |
| 1060 | + "scorpiox-opencode-login is not on this node"); | |
| 1061 | + return 0; | |
| 1062 | + } | |
| 1063 | + | |
| 1064 | + buf_init(&in); | |
| 1065 | + rc = run_capture(login_bin(), "--poll", &in); | |
| 1066 | + if (rc < 0) { | |
| 1067 | + buf_free(&in); | |
| 1068 | + emit_error(200, "OK", "cli_unavailable", | |
| 1069 | + "scorpiox-opencode-login is not on this node"); | |
| 1070 | + return 0; | |
| 1071 | + } | |
| 1072 | + if (rc == 0) { | |
| 1073 | + buf_free(&in); | |
| 1074 | + emit_error(500, "Internal Server Error", "poll_failed", "cannot spawn login CLI"); | |
| 1075 | + return 1; | |
| 1076 | + } | |
| 1077 | + | |
| 1078 | + j = last_json_line(&in); | |
| 1079 | + if (!j) { | |
| 1080 | + buf_free(&in); | |
| 1081 | + /* No JSON at all. Fall back to what the files say: a credential file | |
| 1082 | + * that appeared while polling is a success no matter what the CLI | |
| 1083 | + * printed, and a marker that vanished with no credentials is a dead | |
| 1084 | + * flow, not an infinite spinner. */ | |
| 1085 | + if (st.logged_in) { | |
| 1086 | + buf_init(&out); | |
| 1087 | + emit_status_json(&out, &st, | |
| 1088 | + "{\"ok\":true,\"state\":\"done\""); | |
| 1089 | + emit_json(&out); | |
| 1090 | + return 0; | |
| 1091 | + } | |
| 1092 | + emit_error(502, "Bad Gateway", "poll_failed", "login CLI produced no JSON"); | |
| 1093 | + return 1; | |
| 1094 | + } | |
| 1095 | + { | |
| 1096 | + const char *je = j + strlen(j); | |
| 1097 | + json_str_field(j, je, "state", state, sizeof(state)); | |
| 1098 | + if (!json_bool_field(j, je, "ok", 0)) { | |
| 1099 | + char err[FIELD_SZ] = {0}; | |
| 1100 | + char detail[FIELD_SZ] = {0}; | |
| 1101 | + json_str_field(j, je, "error", err, sizeof(err)); | |
| 1102 | + json_str_field(j, je, "detail", detail, sizeof(detail)); | |
| 1103 | + buf_free(&in); | |
| 1104 | + /* expired / no_pending / denied are terminal, not transient. */ | |
| 1105 | + buf_init(&out); | |
| 1106 | + buf_adds(&out, "{\"ok\":true,\"state\":\"failed\""); | |
| 1107 | + buf_adds(&out, ",\"error\":"); | |
| 1108 | + buf_json(&out, err[0] ? err : "poll_failed"); | |
| 1109 | + if (detail[0]) { buf_adds(&out, ",\"detail\":"); buf_json(&out, detail); } | |
| 1110 | + buf_adds(&out, ",\"logged_in\":"); | |
| 1111 | + buf_adds(&out, st.logged_in ? "true" : "false"); | |
| 1112 | + buf_adds(&out, ",\"pending\":false}\n"); | |
| 1113 | + emit_json(&out); | |
| 1114 | + return 0; | |
| 1115 | + } | |
| 1116 | + if (strcmp(state, "done") == 0 || json_bool_field(j, je, "logged_in", 0)) { | |
| 1117 | + /* Authorised: re-read the node state from the files so the answer | |
| 1118 | + * is what this machine actually holds, not what the CLI claims. */ | |
| 1119 | + status_t fresh; | |
| 1120 | + collect_status(&fresh); | |
| 1121 | + buf_init(&out); | |
| 1122 | + emit_status_json(&out, &fresh, | |
| 1123 | + "{\"ok\":true,\"state\":\"done\""); | |
| 1124 | + emit_json(&out); | |
| 1125 | + return 0; | |
| 1126 | + } | |
| 1127 | + { | |
| 1128 | + int interval = (int)json_num_field(j, je, "interval"); | |
| 1129 | + if (interval < 1) interval = 5; | |
| 1130 | + buf_free(&in); | |
| 1131 | + buf_init(&out); | |
| 1132 | + buf_addf(&out, "{\"ok\":true,\"state\":\"pending\",\"interval\":%d," | |
| 1133 | + "\"logged_in\":false,\"pending\":true}\n", interval); | |
| 1134 | + emit_json(&out); | |
| 1135 | + return 0; | |
| 1136 | + } | |
| 1137 | + } | |
| 1138 | +} | |
| 1139 | + | |
| 1140 | +static int action_cancel(void) | |
| 1141 | +{ | |
| 1142 | + status_t st; | |
| 1143 | + buf_t in; | |
| 1144 | + buf_t out; | |
| 1145 | + | |
| 1146 | + collect_status(&st); | |
| 1147 | + if (!st.cli_present) { | |
| 1148 | + /* Nothing to abort and no CLI to tell: drop the marker ourselves so | |
| 1149 | + * the UI spinner stops on a node without SCORPIOX CODE. */ | |
| 1150 | + char pp[PATH_SZ]; | |
| 1151 | + pending_path(pp, sizeof(pp)); | |
| 1152 | + if (file_exists(pp)) remove(pp); | |
| 1153 | + buf_init(&out); | |
| 1154 | + buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false," | |
| 1155 | + "\"cli_present\":false}\n"); | |
| 1156 | + emit_json(&out); | |
| 1157 | + return 0; | |
| 1158 | + } | |
| 1159 | + | |
| 1160 | + buf_init(&in); | |
| 1161 | + { | |
| 1162 | + int rc = run_capture(login_bin(), "--cancel", &in); | |
| 1163 | + if (rc < 0) { | |
| 1164 | + buf_free(&in); | |
| 1165 | + emit_error(200, "OK", "cli_unavailable", | |
| 1166 | + "scorpiox-opencode-login is not on this node"); | |
| 1167 | + return 0; | |
| 1168 | + } | |
| 1169 | + { | |
| 1170 | + const char *j = last_json_line(&in); | |
| 1171 | + int ok = 1; | |
| 1172 | + if (j) { | |
| 1173 | + const char *je = j + strlen(j); | |
| 1174 | + ok = json_bool_field(j, je, "ok", 1); | |
| 1175 | + } | |
| 1176 | + buf_free(&in); | |
| 1177 | + if (!ok) { | |
| 1178 | + emit_error(200, "OK", "cancel_failed", "login CLI rejected the cancel"); | |
| 1179 | + return 0; | |
| 1180 | + } | |
| 1181 | + /* The CLI removes the marker; re-collect to report the truth. */ | |
| 1182 | + { | |
| 1183 | + status_t after; | |
| 1184 | + collect_status(&after); | |
| 1185 | + buf_init(&out); | |
| 1186 | + emit_status_json(&out, &after, | |
| 1187 | + "{\"ok\":true,\"state\":\"cancelled\""); | |
| 1188 | + emit_json(&out); | |
| 1189 | + } | |
| 1190 | + } | |
| 1191 | + } | |
| 1192 | + return 0; | |
| 1193 | +} | |
| 1194 | + | |
| 1195 | +/* Re-read and re-verify the stored token through the node's own token CLI. | |
| 1196 | + * OpenCode tokens are long-lived; there is no refresh grant on this node, so | |
| 1197 | + * "refresh" means "ask the CLI for a live token right now and report the new | |
| 1198 | + * expiry". The token value is read into a throwaway buffer and discarded. */ | |
| 1199 | +static int action_refresh(void) | |
| 1200 | +{ | |
| 1201 | + status_t st; | |
| 1202 | + buf_t in; | |
| 1203 | + buf_t out; | |
| 1204 | + const char *j; | |
| 1205 | + | |
| 1206 | + collect_status(&st); | |
| 1207 | + if (!st.token_bin_present) { | |
| 1208 | + emit_error(200, "OK", "refresh_unavailable", | |
| 1209 | + "scorpiox-opencode-fetchtoken is not on this node"); | |
| 1210 | + return 0; | |
| 1211 | + } | |
| 1212 | + if (!st.logged_in) { | |
| 1213 | + emit_error(200, "OK", "not_logged_in", "start a device login first"); | |
| 1214 | + return 0; | |
| 1215 | + } | |
| 1216 | + | |
| 1217 | + buf_init(&in); | |
| 1218 | + { | |
| 1219 | + int rc = run_capture(token_bin(), "-local", &in); | |
| 1220 | + if (rc <= 0) { | |
| 1221 | + buf_free(&in); | |
| 1222 | + emit_error(200, "OK", "refresh_failed", "token CLI could not run"); | |
| 1223 | + return 1; | |
| 1224 | + } | |
| 1225 | + } | |
| 1226 | + j = last_json_line(&in); | |
| 1227 | + if (!j) { | |
| 1228 | + buf_free(&in); | |
| 1229 | + emit_error(200, "OK", "refresh_failed", "token CLI produced no JSON"); | |
| 1230 | + return 1; | |
| 1231 | + } | |
| 1232 | + { | |
| 1233 | + const char *je = j + strlen(j); | |
| 1234 | + long long exp = normalise_expiry(json_num_field(j, je, "expires_at")); | |
| 1235 | + char org[ORG_SZ] = {0}; | |
| 1236 | + int has_tok = json_str_present(j, je, "access_token"); | |
| 1237 | + json_str_field(j, je, "org_id", org, sizeof(org)); | |
| 1238 | + buf_free(&in); | |
| 1239 | + if (!has_tok) { | |
| 1240 | + emit_error(200, "OK", "refresh_failed", "token CLI returned no token"); | |
| 1241 | + return 1; | |
| 1242 | + } | |
| 1243 | + st.expires_at = exp > 0 ? exp : st.expires_at; | |
| 1244 | + st.expired = (st.expires_at > 0 && st.expires_at < (long long)time(NULL)); | |
| 1245 | + if (org[0] && !st.org[0]) { | |
| 1246 | + snprintf(st.org, sizeof(st.org), "%s", org); | |
| 1247 | + snprintf(st.account, sizeof(st.account), "%s", org); | |
| 1248 | + } | |
| 1249 | + buf_init(&out); | |
| 1250 | + emit_status_json(&out, &st, "{\"ok\":true,\"refreshed\":true"); | |
| 1251 | + emit_json(&out); | |
| 1252 | + return 0; | |
| 1253 | + } | |
| 1254 | +} | |
| 1255 | + | |
| 1256 | +/* ------------------------------------------------------------------ */ | |
| 1257 | +/* HTML UI */ | |
| 1258 | +/* ------------------------------------------------------------------ */ | |
| 1259 | + | |
| 1260 | +static void serve_html(void) | |
| 1261 | +{ | |
| 1262 | + const char *qs = getenv("QUERY_STRING"); | |
| 1263 | + int embed = (qs && (strstr(qs, "embed=1") || strstr(qs, "embed=true"))); | |
| 1264 | + const char *s; | |
| 1265 | + | |
| 1266 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1267 | + "Cache-Control: no-store\r\n" | |
| 1268 | + "X-Content-Type-Options: nosniff\r\n" | |
| 1269 | + "X-Frame-Options: SAMEORIGIN\r\n" | |
| 1270 | + "Referrer-Policy: same-origin\r\n\r\n", stdout); | |
| 1271 | + | |
| 1272 | + /* UI_HTML carries two control-byte placeholders: \001 where the bot theme | |
| 1273 | + * tokens + prepaint script belong, \002 where the theme handoff script | |
| 1274 | + * belongs. Splitting on them keeps the page readable in src/ui.html and | |
| 1275 | + * the theme in one vendored header that can never drift from the bot. */ | |
| 1276 | + for (s = UI_HTML; *s; ) { | |
| 1277 | + unsigned char c = (unsigned char)*s; | |
| 1278 | + if (c == 0x01) { | |
| 1279 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout); | |
| 1280 | + s++; | |
| 1281 | + } else if (c == 0x02) { | |
| 1282 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | |
| 1283 | + s++; | |
| 1284 | + } else { | |
| 1285 | + fputc((char)c, stdout); | |
| 1286 | + s++; | |
| 1287 | + } | |
| 1288 | + } | |
| 1289 | + (void)embed; /* the page reads ?embed=1 itself, before first paint */ | |
| 1290 | +} | |
| 1291 | + | |
| 1292 | +/* ------------------------------------------------------------------ */ | |
| 1293 | +/* Entry point */ | |
| 1294 | +/* ------------------------------------------------------------------ */ | |
| 1295 | + | |
| 1296 | +int main(int argc, char **argv) | |
| 1297 | +{ | |
| 1298 | + const char *qs; | |
| 1299 | + char action[64] = {0}; | |
| 1300 | + | |
| 1301 | + /* 1. Discovery metadata. Must stay unauthenticated. */ | |
| 1302 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | |
| 1303 | + puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); | |
| 1304 | + return 0; | |
| 1305 | + } | |
| 1306 | + if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { | |
| 1307 | + puts(PLUGIN_ID " " PLUGIN_VER); | |
| 1308 | + return 0; | |
| 1309 | + } | |
| 1310 | + | |
| 1311 | + require_node_auth(); | |
| 1312 | + | |
| 1313 | + qs = getenv("QUERY_STRING"); | |
| 1314 | + if (!qs) qs = ""; | |
| 1315 | + | |
| 1316 | + /* 2. JSON API mode. `format=json` alone means "status", which is what a | |
| 1317 | + * dashboard polls. */ | |
| 1318 | + if (query_has(qs, "action") || query_has(qs, "format")) { | |
| 1319 | + char fmt[32] = {0}; | |
| 1320 | + | |
| 1321 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 1322 | + get_query_val(qs, "format", fmt, sizeof(fmt)); | |
| 1323 | + | |
| 1324 | + if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status"); | |
| 1325 | + | |
| 1326 | + if (strcmp(action, "status") == 0 || !action[0]) return action_status(); | |
| 1327 | + if (strcmp(action, "start") == 0) return action_start(); | |
| 1328 | + if (strcmp(action, "poll") == 0) return action_poll(); | |
| 1329 | + if (strcmp(action, "cancel") == 0) return action_cancel(); | |
| 1330 | + if (strcmp(action, "refresh") == 0) return action_refresh(); | |
| 1331 | + | |
| 1332 | + emit_error(400, "Bad Request", "unknown_action", | |
| 1333 | + "expected status, start, poll, cancel or refresh"); | |
| 1334 | + return 1; | |
| 1335 | + } | |
| 1336 | + | |
| 1337 | + /* 3. HTML UI */ | |
| 1338 | + serve_html(); | |
| 1339 | + return 0; | |
| 1340 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..bc43e24 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,325 @@ | ||
| 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>opencode</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:11.5px;font-weight:600; | |
| 27 | + padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text); | |
| 28 | + border:1px solid var(--line);white-space:nowrap;max-width:220px;overflow:hidden; | |
| 29 | + text-overflow:ellipsis} | |
| 30 | +.badge .av{width:18px;height:18px;border-radius:50%;background:var(--blue);color:#fff; | |
| 31 | + display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700; | |
| 32 | + flex:0 0 auto} | |
| 33 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | |
| 34 | + padding:16px;margin-bottom:12px} | |
| 35 | +.card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em; | |
| 36 | + text-transform:uppercase;color:var(--text-2)} | |
| 37 | +.card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)} | |
| 38 | +.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap} | |
| 39 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px; | |
| 40 | + font-weight:600;font-size:13px;cursor:pointer;font-family:inherit; | |
| 41 | + transition:transform .12s var(--ease),opacity .12s} | |
| 42 | +.btn:active{transform:scale(.98)} | |
| 43 | +.btn:disabled{opacity:.5;cursor:default} | |
| 44 | +.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)} | |
| 45 | +.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)} | |
| 46 | +.btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)} | |
| 47 | +a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none} | |
| 48 | +.kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px} | |
| 49 | +.kv .k{color:var(--text-2);font-size:12px} | |
| 50 | +.kv .v{font-family:var(--mono);font-size:12px;word-break:break-all} | |
| 51 | +.kv .v.plain{font-family:var(--font);font-size:13px} | |
| 52 | +.hint{font-size:12px;color:var(--text-2);margin:10px 0 0} | |
| 53 | +.step{display:none} | |
| 54 | +.step.on{display:block} | |
| 55 | +.codebox{margin:10px 0;padding:14px 16px;border-radius:12px;background:var(--code-bg); | |
| 56 | + border:1px solid var(--line);text-align:center} | |
| 57 | +.codebox .code{font-family:var(--mono);font-size:26px;font-weight:700;letter-spacing:.12em; | |
| 58 | + color:var(--text);margin-bottom:6px} | |
| 59 | +.codebox .code-empty{font-family:var(--mono);font-size:18px;color:var(--text-2); | |
| 60 | + letter-spacing:.08em} | |
| 61 | +.pollbar{margin:10px 0 0;height:3px;border-radius:2px;background:var(--surface-2); | |
| 62 | + overflow:hidden} | |
| 63 | +.pollbar i{display:block;height:100%;width:0;background:var(--blue); | |
| 64 | + animation:pollslide 2s linear infinite} | |
| 65 | +@keyframes pollslide{0%{width:0}50%{width:100%}100%{width:0}} | |
| 66 | +.polllbl{font-size:11.5px;color:var(--text-2);margin:8px 0 0;display:flex;align-items:center;gap:6px} | |
| 67 | +.polllbl .spin{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2); | |
| 68 | + border-top-color:var(--blue);animation:spin 1s linear infinite;display:inline-block} | |
| 69 | +@keyframes spin{to{transform:rotate(360deg)}} | |
| 70 | +.authurl{margin:10px 0;padding:10px 11px;border-radius:10px;background:var(--code-bg); | |
| 71 | + border:1px solid var(--line);font-family:var(--mono);font-size:11.5px; | |
| 72 | + word-break:break-all;max-height:120px;overflow:auto;color:var(--text)} | |
| 73 | +.note.warn{color:var(--orange);border-color:rgba(255,159,10,.35)} | |
| 74 | +#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text); | |
| 75 | + border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer; | |
| 76 | + font-family:inherit} | |
| 77 | +.note{display:none;margin-top:10px;padding:9px 11px;border-radius:10px;font-size:12.5px; | |
| 78 | + border:1px solid var(--line);background:var(--surface-2)} | |
| 79 | +.note.show{display:block} | |
| 80 | +.note.err{color:var(--red);border-color:rgba(255,69,58,.35)} | |
| 81 | +.note.ok{color:var(--green);border-color:rgba(48,209,88,.35)} | |
| 82 | +.empty{padding:10px 0;color:var(--text-2);font-size:12.5px} | |
| 83 | +.tok{font-size:11.5px;color:var(--text-2);margin-top:8px} | |
| 84 | +.tok .ok{color:var(--green)} | |
| 85 | +.tok .no{color:var(--red)} | |
| 86 | +footer{font-size:11px;color:var(--text-2);margin-top:24px;text-align:center} | |
| 87 | +footer a{color:var(--text-2)} | |
| 88 | +@media(max-width:480px){ | |
| 89 | + #app{padding:12px 12px 32px} | |
| 90 | + .hd h1{font-size:16px} | |
| 91 | + .kv{grid-template-columns:110px minmax(0,1fr)} | |
| 92 | + .codebox .code{font-size:22px} | |
| 93 | +} | |
| 94 | +</style> | |
| 95 | +</head> | |
| 96 | +<body> | |
| 97 | +<div id="app"> | |
| 98 | + <div class="hd"> | |
| 99 | + <div class="grow"> | |
| 100 | + <h1>OpenCode Login</h1> | |
| 101 | + <div class="sub">Device code login and account token manager for this node</div> | |
| 102 | + </div> | |
| 103 | + <span class="badge" id="userBadge" hidden> | |
| 104 | + <span class="av" id="userAv">?</span><span id="userLabel"></span> | |
| 105 | + </span> | |
| 106 | + <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span> | |
| 107 | + <button class="btn ghost embed-hide" id="themeToggle" type="button" title="Toggle appearance">Theme</button> | |
| 108 | + </div> | |
| 109 | + | |
| 110 | + <!-- Session card --> | |
| 111 | + <div class="card"> | |
| 112 | + <h2>Session</h2> | |
| 113 | + <p class="lead">The plugin reads the credential file written by the node's own login CLI. It never sees, stores, or returns a token value.</p> | |
| 114 | + <div class="kv" id="sessionKv"> | |
| 115 | + <div class="k">Status</div><div class="v plain" id="vStatus">Checking</div> | |
| 116 | + <div class="k">Account</div><div class="v plain" id="vAccount">-</div> | |
| 117 | + <div class="k">Token</div><div class="v plain" id="vToken">-</div> | |
| 118 | + <div class="k">Refresh</div><div class="v plain" id="vRefresh">-</div> | |
| 119 | + <div class="k">Profile</div><div class="v plain" id="vProfile">-</div> | |
| 120 | + <div class="k">Credentials</div><div class="v" id="vPath">-</div> | |
| 121 | + </div> | |
| 122 | + <div class="tok" id="tokLine"></div> | |
| 123 | + <div class="row" style="margin-top:12px"> | |
| 124 | + <button class="btn" id="btnRefresh" type="button">Refresh Token Now</button> | |
| 125 | + <button class="btn ghost" id="btnStartLogin" type="button">Start OpenCode Login</button> | |
| 126 | + <button class="btn ghost" id="btnRelogin" type="button" hidden>Re-login (replace)</button> | |
| 127 | + </div> | |
| 128 | + <div class="note" id="sessionNote"></div> | |
| 129 | + </div> | |
| 130 | + | |
| 131 | + <!-- Device flow card --> | |
| 132 | + <div class="card" id="flowCard"> | |
| 133 | + <h2>Device Flow</h2> | |
| 134 | + <p class="lead">OpenCode signs in with a one-time user code. Copy it, open the link, approve, and this panel updates itself.</p> | |
| 135 | + | |
| 136 | + <div class="step on" id="stepIdle"> | |
| 137 | + <div class="empty">No login in progress. Press <b>Start OpenCode Login</b> above to begin.</div> | |
| 138 | + </div> | |
| 139 | + | |
| 140 | + <div class="step" id="stepActive"> | |
| 141 | + <div class="codebox"> | |
| 142 | + <div class="code" id="userCode">--</div> | |
| 143 | + <div class="row" style="justify-content:center"> | |
| 144 | + <button class="btn" id="btnCopyOpen" type="button">Copy Code & Open OpenCode</button> | |
| 145 | + </div> | |
| 146 | + </div> | |
| 147 | + <div class="authurl" id="verifyUrl"></div> | |
| 148 | + <div class="pollbar"><i></i></div> | |
| 149 | + <div class="polllbl"><span class="spin"></span><span id="pollLabel">Waiting for approval</span></div> | |
| 150 | + <div class="row" style="margin-top:12px"> | |
| 151 | + <button class="btn danger" id="btnCancel" type="button">Cancel</button> | |
| 152 | + </div> | |
| 153 | + <div class="note" id="flowNote"></div> | |
| 154 | + </div> | |
| 155 | + </div> | |
| 156 | + | |
| 157 | + <footer> | |
| 158 | + <span id="footInfo">plugin_opencode_login</span> | |
| 159 | + · <a href="https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-opencode-login">source</a> | |
| 160 | + </footer> | |
| 161 | +</div> | |
| 162 | +<script> | |
| 163 | +(function(){ | |
| 164 | + var q=new URLSearchParams(location.search); | |
| 165 | + var node=q.get('node')||''; | |
| 166 | + var sid=q.get('id')||''; | |
| 167 | + var HUB=q.get('plugin')||''; | |
| 168 | + var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||localStorage.getItem('bot_active_pwd')||''; | |
| 169 | + var POLL_MS=5000; | |
| 170 | + var pollTimer=null; | |
| 171 | + var flowActive=false; | |
| 172 | + var flowVerify=''; | |
| 173 | + var flowCode=''; | |
| 174 | + | |
| 175 | + function esc(s){return String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');} | |
| 176 | + function $(id){return document.getElementById(id);} | |
| 177 | + function setPill(cls,text){var p=$('pill');p.className='pill '+cls;$('pillText').textContent=text;} | |
| 178 | + function note(id,cls,text){var n=$(id);if(!n)return;n.className='note '+(cls||'')+(text?' show':'');n.textContent=text||'';} | |
| 179 | + | |
| 180 | + function api(action,extra){ | |
| 181 | + var u; | |
| 182 | + if(HUB) u='/plugins?plugin='+encodeURIComponent(HUB)+'&action='+encodeURIComponent(action); | |
| 183 | + else u='/plugin_opencode_login?action='+encodeURIComponent(action); | |
| 184 | + if(extra) u+='&'+extra; | |
| 185 | + if(node) u+='&node='+encodeURIComponent(node); | |
| 186 | + if(sid) u+='&id='+encodeURIComponent(sid); | |
| 187 | + if(pwd) u+='&pwd='+encodeURIComponent(pwd); | |
| 188 | + return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){return r.json();}); | |
| 189 | + } | |
| 190 | + | |
| 191 | + function fmtExpiry(sec){ | |
| 192 | + if(sec==null||sec<=0)return 'unknown'; | |
| 193 | + if(sec<60)return sec+'s'; | |
| 194 | + var m=Math.floor(sec/60); | |
| 195 | + if(m<60)return m+' min'; | |
| 196 | + var h=Math.floor(m/60); | |
| 197 | + if(h<48)return h+' h '+(m%60)+' min'; | |
| 198 | + var d=Math.floor(h/24); | |
| 199 | + return d+' days'; | |
| 200 | + } | |
| 201 | + | |
| 202 | + function renderStatus(d){ | |
| 203 | + if(!d||d.ok===false){setPill('off','Not Connected');note('sessionNote','err',d&&d.error?('Error: '+d.error):'No response');return;} | |
| 204 | + var li=!!d.logged_in, ex=!!d.expired, pend=!!d.pending; | |
| 205 | + if(li&&!ex){setPill('ok','Connected');} | |
| 206 | + else if(li&&ex){setPill('warn','Expired');} | |
| 207 | + else if(pend){setPill('warn','Signing in');} | |
| 208 | + else{setPill('off','Not Connected');} | |
| 209 | + | |
| 210 | + $('vStatus').textContent=li?(ex?'Signed in (token expired)':'Signed in'):(pend?'Device flow in progress':'Not signed in'); | |
| 211 | + $('vAccount').textContent=d.account||d.username||'-'; | |
| 212 | + $('vToken').textContent=li?(ex?'expired ('+fmtExpiry(d.expires_in_sec)+')':'valid, expires in '+fmtExpiry(d.expires_in_sec)):'none'; | |
| 213 | + $('vRefresh').textContent=d.has_refresh?'stored (presence only)':'not stored'; | |
| 214 | + $('vProfile').textContent=d.profile_exists?(d.profile||'superopencode')+' (exists)':'not created'; | |
| 215 | + $('vPath').textContent=d.path||'-'; | |
| 216 | + | |
| 217 | + var tok=$('tokLine'); | |
| 218 | + if(!d.cli_present){tok.innerHTML='<span class="no">scorpiox-opencode-login is not on this node.</span>';} | |
| 219 | + else{tok.innerHTML='<span class="ok">Login CLI present</span> · token CLI '+(d.token_cli_present?'present':'missing');} | |
| 220 | + | |
| 221 | + var badge=$('userBadge'); | |
| 222 | + if(li){badge.hidden=false;var lbl=d.account||d.username||'OpenCode';$('userLabel').textContent=lbl; | |
| 223 | + $('userAv').textContent=(lbl.charAt(0)||'O').toUpperCase();} | |
| 224 | + else{badge.hidden=true;} | |
| 225 | + | |
| 226 | + $('btnRelogin').hidden=!li; | |
| 227 | + $('btnStartLogin').disabled=pend; | |
| 228 | + | |
| 229 | + if(pend&&!flowActive){startPollingUI();} | |
| 230 | + if(!pend&&flowActive){stopPollingUI();$('stepIdle').classList.add('on');$('stepActive').classList.remove('on');} | |
| 231 | + if(!li&&!pend){note('sessionNote','ok','No session on this node yet. Start a device login below.');} | |
| 232 | + else if(li&&!ex){note('sessionNote','ok','');} | |
| 233 | + else if(li&&ex){note('sessionNote','err','Token expired. Re-login to refresh the session.');} | |
| 234 | + } | |
| 235 | + | |
| 236 | + function refresh(){api('status').then(renderStatus).catch(function(e){setPill('off','Not Connected');note('sessionNote','err','Request failed: '+e);});} | |
| 237 | + | |
| 238 | + function startPollingUI(){ | |
| 239 | + flowActive=true; | |
| 240 | + $('stepIdle').classList.remove('on'); | |
| 241 | + $('stepActive').classList.add('on'); | |
| 242 | + if(!pollTimer){pollTimer=setInterval(pollOnce,POLL_MS);} | |
| 243 | + } | |
| 244 | + function stopPollingUI(){ | |
| 245 | + flowActive=false; | |
| 246 | + if(pollTimer){clearInterval(pollTimer);pollTimer=null;} | |
| 247 | + } | |
| 248 | + | |
| 249 | + function pollOnce(){ | |
| 250 | + if(!flowActive)return; | |
| 251 | + api('poll').then(function(d){ | |
| 252 | + if(!d||d.ok===false){note('flowNote','err',d&&d.error?('Poll error: '+d.error):'Poll failed');return;} | |
| 253 | + if(d.state==='done'||d.logged_in){ | |
| 254 | + stopPollingUI(); | |
| 255 | + $('stepIdle').classList.add('on'); | |
| 256 | + $('stepActive').classList.remove('on'); | |
| 257 | + note('flowNote','ok','Signed in. The credential file has been written.'); | |
| 258 | + $('pollLabel').textContent='Signed in'; | |
| 259 | + refresh(); | |
| 260 | + }else if(d.state==='failed'){ | |
| 261 | + stopPollingUI(); | |
| 262 | + $('stepIdle').classList.add('on'); | |
| 263 | + $('stepActive').classList.remove('on'); | |
| 264 | + note('flowNote','err','Login failed: '+(d.error||'unknown')+(d.detail?(' - '+d.detail):'')); | |
| 265 | + }else{ | |
| 266 | + $('pollLabel').textContent='Waiting for approval'; | |
| 267 | + } | |
| 268 | + }).catch(function(e){note('flowNote','err','Poll request failed: '+e);}); | |
| 269 | + } | |
| 270 | + | |
| 271 | + function doStart(force){ | |
| 272 | + note('sessionNote','ok',''); | |
| 273 | + api('start',force?'force=1':'').then(function(d){ | |
| 274 | + if(!d||d.ok===false){note('sessionNote','err',d&&d.error?('Start failed: '+d.error):'Start failed');return;} | |
| 275 | + if(d.already_logged_in){ | |
| 276 | + note('sessionNote','warn','This node already has OpenCode credentials. Use Re-login to replace them.'); | |
| 277 | + refresh(); | |
| 278 | + return; | |
| 279 | + } | |
| 280 | + flowVerify=d.verify_url||''; | |
| 281 | + flowCode=d.user_code||''; | |
| 282 | + $('userCode').textContent=flowCode||'--'; | |
| 283 | + $('verifyUrl').textContent=flowVerify; | |
| 284 | + $('pollLabel').textContent='Waiting for approval'; | |
| 285 | + note('flowNote','ok',''); | |
| 286 | + startPollingUI(); | |
| 287 | + refresh(); | |
| 288 | + }).catch(function(e){note('sessionNote','err','Start request failed: '+e);}); | |
| 289 | + } | |
| 290 | + | |
| 291 | + $('btnStartLogin').onclick=function(){doStart(false);}; | |
| 292 | + $('btnRelogin').onclick=function(){doStart(true);}; | |
| 293 | + $('btnCancel').onclick=function(){ | |
| 294 | + stopPollingUI(); | |
| 295 | + api('cancel').then(function(d){ | |
| 296 | + $('stepIdle').classList.add('on'); | |
| 297 | + $('stepActive').classList.remove('on'); | |
| 298 | + note('flowNote','ok',d&&d.ok?'Device flow cancelled.':'Cancel failed: '+(d&&d.error||'unknown')); | |
| 299 | + refresh(); | |
| 300 | + }).catch(function(e){note('flowNote','err','Cancel request failed: '+e);}); | |
| 301 | + }; | |
| 302 | + $('btnRefresh').onclick=function(){ | |
| 303 | + note('sessionNote','ok',''); | |
| 304 | + api('refresh').then(function(d){ | |
| 305 | + if(!d||d.ok===false){note('sessionNote','err',d&&d.error?('Refresh failed: '+d.error):'Refresh failed');return;} | |
| 306 | + note('sessionNote','ok','Token re-read. '+(d.refreshed?'CLI confirmed a live token.':'')); | |
| 307 | + renderStatus(d); | |
| 308 | + }).catch(function(e){note('sessionNote','err','Refresh request failed: '+e);}); | |
| 309 | + }; | |
| 310 | + $('btnCopyOpen').onclick=function(){ | |
| 311 | + var done=function(){note('flowNote','ok','Code copied. Open the link and approve.');}; | |
| 312 | + if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(flowCode).then(done,function(){window.open(flowVerify,'_blank');done();});} | |
| 313 | + else{done();} | |
| 314 | + if(flowVerify)window.open(flowVerify,'_blank'); | |
| 315 | + }; | |
| 316 | + | |
| 317 | + var tb=$('themeToggle'); | |
| 318 | + if(tb)tb.onclick=function(){ | |
| 319 | + if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark'); | |
| 320 | + }; | |
| 321 | + $('footInfo').textContent='plugin_opencode_login'; | |
| 322 | + refresh(); | |
| 323 | +})(); | |
| 324 | +</script> | |
| 325 | +</body></html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..fe410bf | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,333 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_AGYLOGIN_UI_HTML_H | |
| 3 | +#define SX_AGYLOGIN_UI_HTML_H | |
| 4 | + | |
| 5 | +static const char *UI_HTML = | |
| 6 | + "<!DOCTYPE html>\n" | |
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | |
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | |
| 9 | + "<title>opencode</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:11.5px;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);white-space:nowrap;max-width:220px;overflow:hidden;\n" | |
| 34 | + " text-overflow:ellipsis}\n" | |
| 35 | + ".badge .av{width:18px;height:18px;border-radius:50%;background:var(--blue);color:#fff;\n" | |
| 36 | + " display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;\n" | |
| 37 | + " flex:0 0 auto}\n" | |
| 38 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | |
| 39 | + " padding:16px;margin-bottom:12px}\n" | |
| 40 | + ".card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;\n" | |
| 41 | + " text-transform:uppercase;color:var(--text-2)}\n" | |
| 42 | + ".card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}\n" | |
| 43 | + ".row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n" | |
| 44 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;\n" | |
| 45 | + " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;\n" | |
| 46 | + " transition:transform .12s var(--ease),opacity .12s}\n" | |
| 47 | + ".btn:active{transform:scale(.98)}\n" | |
| 48 | + ".btn:disabled{opacity:.5;cursor:default}\n" | |
| 49 | + ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n" | |
| 50 | + ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | |
| 51 | + ".btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}\n" | |
| 52 | + "a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}\n" | |
| 53 | + ".kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}\n" | |
| 54 | + ".kv .k{color:var(--text-2);font-size:12px}\n" | |
| 55 | + ".kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}\n" | |
| 56 | + ".kv .v.plain{font-family:var(--font);font-size:13px}\n" | |
| 57 | + ".hint{font-size:12px;color:var(--text-2);margin:10px 0 0}\n" | |
| 58 | + ".step{display:none}\n" | |
| 59 | + ".step.on{display:block}\n" | |
| 60 | + ".codebox{margin:10px 0;padding:14px 16px;border-radius:12px;background:var(--code-bg);\n" | |
| 61 | + " border:1px solid var(--line);text-align:center}\n" | |
| 62 | + ".codebox .code{font-family:var(--mono);font-size:26px;font-weight:700;letter-spacing:.12em;\n" | |
| 63 | + " color:var(--text);margin-bottom:6px}\n" | |
| 64 | + ".codebox .code-empty{font-family:var(--mono);font-size:18px;color:var(--text-2);\n" | |
| 65 | + " letter-spacing:.08em}\n" | |
| 66 | + ".pollbar{margin:10px 0 0;height:3px;border-radius:2px;background:var(--surface-2);\n" | |
| 67 | + " overflow:hidden}\n" | |
| 68 | + ".pollbar i{display:block;height:100%;width:0;background:var(--blue);\n" | |
| 69 | + " animation:pollslide 2s linear infinite}\n" | |
| 70 | + "@keyframes pollslide{0%{width:0}50%{width:100%}100%{width:0}}\n" | |
| 71 | + ".polllbl{font-size:11.5px;color:var(--text-2);margin:8px 0 0;display:flex;align-items:center;gap:6px}\n" | |
| 72 | + ".polllbl .spin{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2);\n" | |
| 73 | + " border-top-color:var(--blue);animation:spin 1s linear infinite;display:inline-block}\n" | |
| 74 | + "@keyframes spin{to{transform:rotate(360deg)}}\n" | |
| 75 | + ".authurl{margin:10px 0;padding:10px 11px;border-radius:10px;background:var(--code-bg);\n" | |
| 76 | + " border:1px solid var(--line);font-family:var(--mono);font-size:11.5px;\n" | |
| 77 | + " word-break:break-all;max-height:120px;overflow:auto;color:var(--text)}\n" | |
| 78 | + ".note.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n" | |
| 79 | + "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | |
| 80 | + " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n" | |
| 81 | + " font-family:inherit}\n" | |
| 82 | + ".note{display:none;margin-top:10px;padding:9px 11px;border-radius:10px;font-size:12.5px;\n" | |
| 83 | + " border:1px solid var(--line);background:var(--surface-2)}\n" | |
| 84 | + ".note.show{display:block}\n" | |
| 85 | + ".note.err{color:var(--red);border-color:rgba(255,69,58,.35)}\n" | |
| 86 | + ".note.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | |
| 87 | + ".empty{padding:10px 0;color:var(--text-2);font-size:12.5px}\n" | |
| 88 | + ".tok{font-size:11.5px;color:var(--text-2);margin-top:8px}\n" | |
| 89 | + ".tok .ok{color:var(--green)}\n" | |
| 90 | + ".tok .no{color:var(--red)}\n" | |
| 91 | + "footer{font-size:11px;color:var(--text-2);margin-top:24px;text-align:center}\n" | |
| 92 | + "footer a{color:var(--text-2)}\n" | |
| 93 | + "@media(max-width:480px){\n" | |
| 94 | + " #app{padding:12px 12px 32px}\n" | |
| 95 | + " .hd h1{font-size:16px}\n" | |
| 96 | + " .kv{grid-template-columns:110px minmax(0,1fr)}\n" | |
| 97 | + " .codebox .code{font-size:22px}\n" | |
| 98 | + "}\n" | |
| 99 | + "</style>\n" | |
| 100 | + "</head>\n" | |
| 101 | + "<body>\n" | |
| 102 | + "<div id=\"app\">\n" | |
| 103 | + " <div class=\"hd\">\n" | |
| 104 | + " <div class=\"grow\">\n" | |
| 105 | + " <h1>OpenCode Login</h1>\n" | |
| 106 | + " <div class=\"sub\">Device code login and account token manager for this node</div>\n" | |
| 107 | + " </div>\n" | |
| 108 | + " <span class=\"badge\" id=\"userBadge\" hidden>\n" | |
| 109 | + " <span class=\"av\" id=\"userAv\">?</span><span id=\"userLabel\"></span>\n" | |
| 110 | + " </span>\n" | |
| 111 | + " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n" | |
| 112 | + " <button class=\"btn ghost embed-hide\" id=\"themeToggle\" type=\"button\" title=\"Toggle appearance\">Theme</button>\n" | |
| 113 | + " </div>\n" | |
| 114 | + "\n" | |
| 115 | + " <!-- Session card -->\n" | |
| 116 | + " <div class=\"card\">\n" | |
| 117 | + " <h2>Session</h2>\n" | |
| 118 | + " <p class=\"lead\">The plugin reads the credential file written by the node's own login CLI. It never sees, stores, or returns a token value.</p>\n" | |
| 119 | + " <div class=\"kv\" id=\"sessionKv\">\n" | |
| 120 | + " <div class=\"k\">Status</div><div class=\"v plain\" id=\"vStatus\">Checking</div>\n" | |
| 121 | + " <div class=\"k\">Account</div><div class=\"v plain\" id=\"vAccount\">-</div>\n" | |
| 122 | + " <div class=\"k\">Token</div><div class=\"v plain\" id=\"vToken\">-</div>\n" | |
| 123 | + " <div class=\"k\">Refresh</div><div class=\"v plain\" id=\"vRefresh\">-</div>\n" | |
| 124 | + " <div class=\"k\">Profile</div><div class=\"v plain\" id=\"vProfile\">-</div>\n" | |
| 125 | + " <div class=\"k\">Credentials</div><div class=\"v\" id=\"vPath\">-</div>\n" | |
| 126 | + " </div>\n" | |
| 127 | + " <div class=\"tok\" id=\"tokLine\"></div>\n" | |
| 128 | + " <div class=\"row\" style=\"margin-top:12px\">\n" | |
| 129 | + " <button class=\"btn\" id=\"btnRefresh\" type=\"button\">Refresh Token Now</button>\n" | |
| 130 | + " <button class=\"btn ghost\" id=\"btnStartLogin\" type=\"button\">Start OpenCode Login</button>\n" | |
| 131 | + " <button class=\"btn ghost\" id=\"btnRelogin\" type=\"button\" hidden>Re-login (replace)</button>\n" | |
| 132 | + " </div>\n" | |
| 133 | + " <div class=\"note\" id=\"sessionNote\"></div>\n" | |
| 134 | + " </div>\n" | |
| 135 | + "\n" | |
| 136 | + " <!-- Device flow card -->\n" | |
| 137 | + " <div class=\"card\" id=\"flowCard\">\n" | |
| 138 | + " <h2>Device Flow</h2>\n" | |
| 139 | + " <p class=\"lead\">OpenCode signs in with a one-time user code. Copy it, open the link, approve, and this panel updates itself.</p>\n" | |
| 140 | + "\n" | |
| 141 | + " <div class=\"step on\" id=\"stepIdle\">\n" | |
| 142 | + " <div class=\"empty\">No login in progress. Press <b>Start OpenCode Login</b> above to begin.</div>\n" | |
| 143 | + " </div>\n" | |
| 144 | + "\n" | |
| 145 | + " <div class=\"step\" id=\"stepActive\">\n" | |
| 146 | + " <div class=\"codebox\">\n" | |
| 147 | + " <div class=\"code\" id=\"userCode\">--</div>\n" | |
| 148 | + " <div class=\"row\" style=\"justify-content:center\">\n" | |
| 149 | + " <button class=\"btn\" id=\"btnCopyOpen\" type=\"button\">Copy Code & Open OpenCode</button>\n" | |
| 150 | + " </div>\n" | |
| 151 | + " </div>\n" | |
| 152 | + " <div class=\"authurl\" id=\"verifyUrl\"></div>\n" | |
| 153 | + " <div class=\"pollbar\"><i></i></div>\n" | |
| 154 | + " <div class=\"polllbl\"><span class=\"spin\"></span><span id=\"pollLabel\">Waiting for approval</span></div>\n" | |
| 155 | + " <div class=\"row\" style=\"margin-top:12px\">\n" | |
| 156 | + " <button class=\"btn danger\" id=\"btnCancel\" type=\"button\">Cancel</button>\n" | |
| 157 | + " </div>\n" | |
| 158 | + " <div class=\"note\" id=\"flowNote\"></div>\n" | |
| 159 | + " </div>\n" | |
| 160 | + " </div>\n" | |
| 161 | + "\n" | |
| 162 | + " <footer>\n" | |
| 163 | + " <span id=\"footInfo\">plugin_opencode_login</span>\n" | |
| 164 | + " · <a href=\"https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-opencode-login\">source</a>\n" | |
| 165 | + " </footer>\n" | |
| 166 | + "</div>\n" | |
| 167 | + "<script>\n" | |
| 168 | + "(function(){\n" | |
| 169 | + " var q=new URLSearchParams(location.search);\n" | |
| 170 | + " var node=q.get('node')||'';\n" | |
| 171 | + " var sid=q.get('id')||'';\n" | |
| 172 | + " var HUB=q.get('plugin')||'';\n" | |
| 173 | + " var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||localStorage.getItem('bot_active_pwd')||'';\n" | |
| 174 | + " var POLL_MS=5000;\n" | |
| 175 | + " var pollTimer=null;\n" | |
| 176 | + " var flowActive=false;\n" | |
| 177 | + " var flowVerify='';\n" | |
| 178 | + " var flowCode='';\n" | |
| 179 | + "\n" | |
| 180 | + " function esc(s){return String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/\"/g,'"');}\n" | |
| 181 | + " function $(id){return document.getElementById(id);}\n" | |
| 182 | + " function setPill(cls,text){var p=$('pill');p.className='pill '+cls;$('pillText').textContent=text;}\n" | |
| 183 | + " function note(id,cls,text){var n=$(id);if(!n)return;n.className='note '+(cls||'')+(text?' show':'');n.textContent=text||'';}\n" | |
| 184 | + "\n" | |
| 185 | + " function api(action,extra){\n" | |
| 186 | + " var u;\n" | |
| 187 | + " if(HUB) u='/plugins?plugin='+encodeURIComponent(HUB)+'&action='+encodeURIComponent(action);\n" | |
| 188 | + " else u='/plugin_opencode_login?action='+encodeURIComponent(action);\n" | |
| 189 | + " if(extra) u+='&'+extra;\n" | |
| 190 | + " if(node) u+='&node='+encodeURIComponent(node);\n" | |
| 191 | + " if(sid) u+='&id='+encodeURIComponent(sid);\n" | |
| 192 | + " if(pwd) u+='&pwd='+encodeURIComponent(pwd);\n" | |
| 193 | + " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){return r.json();});\n" | |
| 194 | + " }\n" | |
| 195 | + "\n" | |
| 196 | + " function fmtExpiry(sec){\n" | |
| 197 | + " if(sec==null||sec<=0)return 'unknown';\n" | |
| 198 | + " if(sec<60)return sec+'s';\n" | |
| 199 | + " var m=Math.floor(sec/60);\n" | |
| 200 | + " if(m<60)return m+' min';\n" | |
| 201 | + " var h=Math.floor(m/60);\n" | |
| 202 | + " if(h<48)return h+' h '+(m%60)+' min';\n" | |
| 203 | + " var d=Math.floor(h/24);\n" | |
| 204 | + " return d+' days';\n" | |
| 205 | + " }\n" | |
| 206 | + "\n" | |
| 207 | + " function renderStatus(d){\n" | |
| 208 | + " if(!d||d.ok===false){setPill('off','Not Connected');note('sessionNote','err',d&&d.error?('Error: '+d.error):'No response');return;}\n" | |
| 209 | + " var li=!!d.logged_in, ex=!!d.expired, pend=!!d.pending;\n" | |
| 210 | + " if(li&&!ex){setPill('ok','Connected');}\n" | |
| 211 | + " else if(li&&ex){setPill('warn','Expired');}\n" | |
| 212 | + " else if(pend){setPill('warn','Signing in');}\n" | |
| 213 | + " else{setPill('off','Not Connected');}\n" | |
| 214 | + "\n" | |
| 215 | + " $('vStatus').textContent=li?(ex?'Signed in (token expired)':'Signed in'):(pend?'Device flow in progress':'Not signed in');\n" | |
| 216 | + " $('vAccount').textContent=d.account||d.username||'-';\n" | |
| 217 | + " $('vToken').textContent=li?(ex?'expired ('+fmtExpiry(d.expires_in_sec)+')':'valid, expires in '+fmtExpiry(d.expires_in_sec)):'none';\n" | |
| 218 | + " $('vRefresh').textContent=d.has_refresh?'stored (presence only)':'not stored';\n" | |
| 219 | + " $('vProfile').textContent=d.profile_exists?(d.profile||'superopencode')+' (exists)':'not created';\n" | |
| 220 | + " $('vPath').textContent=d.path||'-';\n" | |
| 221 | + "\n" | |
| 222 | + " var tok=$('tokLine');\n" | |
| 223 | + " if(!d.cli_present){tok.innerHTML='<span class=\"no\">scorpiox-opencode-login is not on this node.</span>';}\n" | |
| 224 | + " else{tok.innerHTML='<span class=\"ok\">Login CLI present</span> · token CLI '+(d.token_cli_present?'present':'missing');}\n" | |
| 225 | + "\n" | |
| 226 | + " var badge=$('userBadge');\n" | |
| 227 | + " if(li){badge.hidden=false;var lbl=d.account||d.username||'OpenCode';$('userLabel').textContent=lbl;\n" | |
| 228 | + " $('userAv').textContent=(lbl.charAt(0)||'O').toUpperCase();}\n" | |
| 229 | + " else{badge.hidden=true;}\n" | |
| 230 | + "\n" | |
| 231 | + " $('btnRelogin').hidden=!li;\n" | |
| 232 | + " $('btnStartLogin').disabled=pend;\n" | |
| 233 | + "\n" | |
| 234 | + " if(pend&&!flowActive){startPollingUI();}\n" | |
| 235 | + " if(!pend&&flowActive){stopPollingUI();$('stepIdle').classList.add('on');$('stepActive').classList.remove('on');}\n" | |
| 236 | + " if(!li&&!pend){note('sessionNote','ok','No session on this node yet. Start a device login below.');}\n" | |
| 237 | + " else if(li&&!ex){note('sessionNote','ok','');}\n" | |
| 238 | + " else if(li&&ex){note('sessionNote','err','Token expired. Re-login to refresh the session.');}\n" | |
| 239 | + " }\n" | |
| 240 | + "\n" | |
| 241 | + " function refresh(){api('status').then(renderStatus).catch(function(e){setPill('off','Not Connected');note('sessionNote','err','Request failed: '+e);});}\n" | |
| 242 | + "\n" | |
| 243 | + " function startPollingUI(){\n" | |
| 244 | + " flowActive=true;\n" | |
| 245 | + " $('stepIdle').classList.remove('on');\n" | |
| 246 | + " $('stepActive').classList.add('on');\n" | |
| 247 | + " if(!pollTimer){pollTimer=setInterval(pollOnce,POLL_MS);}\n" | |
| 248 | + " }\n" | |
| 249 | + " function stopPollingUI(){\n" | |
| 250 | + " flowActive=false;\n" | |
| 251 | + " if(pollTimer){clearInterval(pollTimer);pollTimer=null;}\n" | |
| 252 | + " }\n" | |
| 253 | + "\n" | |
| 254 | + " function pollOnce(){\n" | |
| 255 | + " if(!flowActive)return;\n" | |
| 256 | + " api('poll').then(function(d){\n" | |
| 257 | + " if(!d||d.ok===false){note('flowNote','err',d&&d.error?('Poll error: '+d.error):'Poll failed');return;}\n" | |
| 258 | + " if(d.state==='done'||d.logged_in){\n" | |
| 259 | + " stopPollingUI();\n" | |
| 260 | + " $('stepIdle').classList.add('on');\n" | |
| 261 | + " $('stepActive').classList.remove('on');\n" | |
| 262 | + " note('flowNote','ok','Signed in. The credential file has been written.');\n" | |
| 263 | + " $('pollLabel').textContent='Signed in';\n" | |
| 264 | + " refresh();\n" | |
| 265 | + " }else if(d.state==='failed'){\n" | |
| 266 | + " stopPollingUI();\n" | |
| 267 | + " $('stepIdle').classList.add('on');\n" | |
| 268 | + " $('stepActive').classList.remove('on');\n" | |
| 269 | + " note('flowNote','err','Login failed: '+(d.error||'unknown')+(d.detail?(' - '+d.detail):''));\n" | |
| 270 | + " }else{\n" | |
| 271 | + " $('pollLabel').textContent='Waiting for approval';\n" | |
| 272 | + " }\n" | |
| 273 | + " }).catch(function(e){note('flowNote','err','Poll request failed: '+e);});\n" | |
| 274 | + " }\n" | |
| 275 | + "\n" | |
| 276 | + " function doStart(force){\n" | |
| 277 | + " note('sessionNote','ok','');\n" | |
| 278 | + " api('start',force?'force=1':'').then(function(d){\n" | |
| 279 | + " if(!d||d.ok===false){note('sessionNote','err',d&&d.error?('Start failed: '+d.error):'Start failed');return;}\n" | |
| 280 | + " if(d.already_logged_in){\n" | |
| 281 | + " note('sessionNote','warn','This node already has OpenCode credentials. Use Re-login to replace them.');\n" | |
| 282 | + " refresh();\n" | |
| 283 | + " return;\n" | |
| 284 | + " }\n" | |
| 285 | + " flowVerify=d.verify_url||'';\n" | |
| 286 | + " flowCode=d.user_code||'';\n" | |
| 287 | + " $('userCode').textContent=flowCode||'--';\n" | |
| 288 | + " $('verifyUrl').textContent=flowVerify;\n" | |
| 289 | + " $('pollLabel').textContent='Waiting for approval';\n" | |
| 290 | + " note('flowNote','ok','');\n" | |
| 291 | + " startPollingUI();\n" | |
| 292 | + " refresh();\n" | |
| 293 | + " }).catch(function(e){note('sessionNote','err','Start request failed: '+e);});\n" | |
| 294 | + " }\n" | |
| 295 | + "\n" | |
| 296 | + " $('btnStartLogin').onclick=function(){doStart(false);};\n" | |
| 297 | + " $('btnRelogin').onclick=function(){doStart(true);};\n" | |
| 298 | + " $('btnCancel').onclick=function(){\n" | |
| 299 | + " stopPollingUI();\n" | |
| 300 | + " api('cancel').then(function(d){\n" | |
| 301 | + " $('stepIdle').classList.add('on');\n" | |
| 302 | + " $('stepActive').classList.remove('on');\n" | |
| 303 | + " note('flowNote','ok',d&&d.ok?'Device flow cancelled.':'Cancel failed: '+(d&&d.error||'unknown'));\n" | |
| 304 | + " refresh();\n" | |
| 305 | + " }).catch(function(e){note('flowNote','err','Cancel request failed: '+e);});\n" | |
| 306 | + " };\n" | |
| 307 | + " $('btnRefresh').onclick=function(){\n" | |
| 308 | + " note('sessionNote','ok','');\n" | |
| 309 | + " api('refresh').then(function(d){\n" | |
| 310 | + " if(!d||d.ok===false){note('sessionNote','err',d&&d.error?('Refresh failed: '+d.error):'Refresh failed');return;}\n" | |
| 311 | + " note('sessionNote','ok','Token re-read. '+(d.refreshed?'CLI confirmed a live token.':''));\n" | |
| 312 | + " renderStatus(d);\n" | |
| 313 | + " }).catch(function(e){note('sessionNote','err','Refresh request failed: '+e);});\n" | |
| 314 | + " };\n" | |
| 315 | + " $('btnCopyOpen').onclick=function(){\n" | |
| 316 | + " var done=function(){note('flowNote','ok','Code copied. Open the link and approve.');};\n" | |
| 317 | + " if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(flowCode).then(done,function(){window.open(flowVerify,'_blank');done();});}\n" | |
| 318 | + " else{done();}\n" | |
| 319 | + " if(flowVerify)window.open(flowVerify,'_blank');\n" | |
| 320 | + " };\n" | |
| 321 | + "\n" | |
| 322 | + " var tb=$('themeToggle');\n" | |
| 323 | + " if(tb)tb.onclick=function(){\n" | |
| 324 | + " if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');\n" | |
| 325 | + " };\n" | |
| 326 | + " $('footInfo').textContent='plugin_opencode_login';\n" | |
| 327 | + " refresh();\n" | |
| 328 | + "})();\n" | |
| 329 | + "</script>\n" | |
| 330 | + "\002</body></html>\n" | |
| 331 | + ; | |
| 332 | + | |
| 333 | +#endif /* SX_AGYLOGIN_UI_HTML_H */ |
| 1 | 1 | new file mode 100755 |
| index 0000000..dce3767 | ||
| --- /dev/null | ||
| +++ b/tests/mock_login.sh | ||
| @@ -0,0 +1,114 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/mock_login.sh - stand-in for scorpiox-opencode-login machine mode. | |
| 3 | +# | |
| 4 | +# Emits exactly the contract shape the real CLI emits (one JSON line last, all | |
| 5 | +# human output before it), so the plugin's parsers are exercised against the | |
| 6 | +# production layout rather than an invented one. The device exchange is | |
| 7 | +# simulated: --poll writes a credential file into $OPENCODE_CREDS_PATH and | |
| 8 | +# removes the pending marker when MOCK_APPROVE=1, which is what the real CLI | |
| 9 | +# does after the user approves in the browser. | |
| 10 | +# | |
| 11 | +# MOCK_START_FAIL=1 --start answers the "credentials already exist" error | |
| 12 | +# MOCK_APPROVE=1 --poll completes the flow | |
| 13 | +# MOCK_DENY=1 --poll answers a terminal denial | |
| 14 | +# MOCK_NO_PENDING=1 --poll answers no_pending even if a marker exists | |
| 15 | + | |
| 16 | +CREDS="${OPENCODE_CREDS_PATH:-/nonexistent-auth.json}" | |
| 17 | +PEND="${OPENCODE_PENDING_PATH:-/nonexistent-pending.json}" | |
| 18 | + | |
| 19 | +# pyget <file> <key> -> the value, or empty string when absent/unreadable | |
| 20 | +pyget() { | |
| 21 | + python3 - "$1" "$2" <<'PY' | |
| 22 | +import json, sys | |
| 23 | +try: | |
| 24 | + with open(sys.argv[1]) as f: | |
| 25 | + d = json.load(f) | |
| 26 | +except Exception: | |
| 27 | + d = {} | |
| 28 | +v = d.get(sys.argv[2]) if isinstance(d, dict) else None | |
| 29 | +if v is None: | |
| 30 | + print("") | |
| 31 | +elif isinstance(v, bool): | |
| 32 | + print("true" if v else "false") | |
| 33 | +else: | |
| 34 | + print(v) | |
| 35 | +PY | |
| 36 | +} | |
| 37 | + | |
| 38 | +jstr() { # jstr <value> -> "value" or null | |
| 39 | + if [ -z "$1" ]; then printf 'null'; else printf '"%s"' "$1"; fi | |
| 40 | +} | |
| 41 | + | |
| 42 | +case "$1" in | |
| 43 | + --status) | |
| 44 | + _li=false; _hr=false; _exp=0; _org=""; _pend=false | |
| 45 | + if [ -f "$CREDS" ]; then | |
| 46 | + _tok=$(pyget "$CREDS" access_token) | |
| 47 | + [ -n "$_tok" ] && _li=true | |
| 48 | + _rt=$(pyget "$CREDS" refresh_token) | |
| 49 | + [ -n "$_rt" ] && _hr=true | |
| 50 | + _exp=$(pyget "$CREDS" expires_at) | |
| 51 | + [ -z "$_exp" ] && _exp=0 | |
| 52 | + _org=$(pyget "$CREDS" org_id) | |
| 53 | + fi | |
| 54 | + [ -f "$PEND" ] && _pend=true | |
| 55 | + printf 'scorpiox-opencode-login 1.0.0 (SXLOGIN-MACHINE-V1)\n' | |
| 56 | + printf '{"ok":true,"provider":"opencode","name":"OpenCode","flow":"device_code",' | |
| 57 | + printf '"account":%s,"logged_in":%s,"path":"%s",' "$(jstr "$_org")" "$_li" "$CREDS" | |
| 58 | + printf '"expires_at":%s,"expired":false,"has_refresh":%s,"pending":%s,' "$_exp" "$_hr" "$_pend" | |
| 59 | + printf '"profile":"superopencode","profile_exists":false,"named_accounts":false,' | |
| 60 | + printf '"protocol":"SXLOGIN-MACHINE-V1"}\n' | |
| 61 | + ;; | |
| 62 | + --start) | |
| 63 | + if [ "$MOCK_START_FAIL" = "1" ]; then | |
| 64 | + printf '{"ok":false,"provider":"opencode","error":"exists","detail":"credentials already exist; pass --force to replace"}\n' | |
| 65 | + exit 0 | |
| 66 | + fi | |
| 67 | + if [ "$MOCK_START_NETFAIL" = "1" ]; then | |
| 68 | + printf '{"ok":false,"provider":"opencode","error":"network","detail":"device code request failed"}\n' | |
| 69 | + exit 0 | |
| 70 | + fi | |
| 71 | + mkdir -p "$(dirname "$PEND")" 2>/dev/null || : | |
| 72 | + printf '{"device_code":"oc-mock-device-code-must-not-leak","interval":5,"force":0,"created":%s}\n' \ | |
| 73 | + "$(date +%s)" > "$PEND" | |
| 74 | + printf '{"ok":true,"provider":"opencode","flow":"device_code",' | |
| 75 | + printf '"verify_url":"https://opencode.ai/console/device?user_code=ABCD-EFGH&client_id=opencode-cli",' | |
| 76 | + printf '"user_code":"ABCD-EFGH","expires_in":900}\n' | |
| 77 | + ;; | |
| 78 | + --poll) | |
| 79 | + if [ "$MOCK_APPROVE" = "1" ]; then | |
| 80 | + mkdir -p "$(dirname "$CREDS")" 2>/dev/null || : | |
| 81 | + # one redirection for the whole block: in POSIX sh a redirect attaches | |
| 82 | + # to a single command, so three separate printfs would write two lines | |
| 83 | + # to stdout and only the last one to the credential file. | |
| 84 | + { | |
| 85 | + printf '{"access_token":"oc-mock-access-token-must-not-leak",' | |
| 86 | + printf '"refresh_token":"oc-mock-refresh-token-must-not-leak","token_type":"Bearer",' | |
| 87 | + printf '"expires_in":2591999,"expires_at":%s,"org_id":"org-mock-42"}\n' \ | |
| 88 | + "$(( $(date +%s) + 2591999 ))" | |
| 89 | + } > "$CREDS" | |
| 90 | + rm -f "$PEND" | |
| 91 | + printf 'Logged in successfully!\n' | |
| 92 | + printf '{"ok":true,"provider":"opencode","state":"done","logged_in":true,' | |
| 93 | + printf '"path":"%s","profile":"superopencode","profile_created":false}\n' "$CREDS" | |
| 94 | + exit 0 | |
| 95 | + fi | |
| 96 | + if [ "$MOCK_DENY" = "1" ]; then | |
| 97 | + rm -f "$PEND" | |
| 98 | + printf '{"ok":false,"provider":"opencode","error":"denied","detail":"access_denied"}\n' | |
| 99 | + exit 0 | |
| 100 | + fi | |
| 101 | + if [ ! -f "$PEND" ] || [ "$MOCK_NO_PENDING" = "1" ]; then | |
| 102 | + printf '{"ok":false,"provider":"opencode","error":"no_pending","detail":"run --start first"}\n' | |
| 103 | + exit 0 | |
| 104 | + fi | |
| 105 | + printf '{"ok":true,"provider":"opencode","state":"pending","interval":5}\n' | |
| 106 | + ;; | |
| 107 | + --cancel) | |
| 108 | + rm -f "$PEND" | |
| 109 | + printf '{"ok":true,"provider":"opencode","cancelled":true}\n' | |
| 110 | + ;; | |
| 111 | + *) | |
| 112 | + printf '{"ok":false,"provider":"opencode","error":"usage","detail":"unknown flag"}\n' | |
| 113 | + ;; | |
| 114 | +esac |
| 1 | 1 | new file mode 100755 |
| index 0000000..9bbb8c6 | ||
| --- /dev/null | ||
| +++ b/tests/mock_token.sh | ||
| @@ -0,0 +1,50 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/mock_token.sh - stand-in for scorpiox-opencode-fetchtoken. | |
| 3 | +# | |
| 4 | +# The real CLI reads ~/.config/opencode/auth.json and prints | |
| 5 | +# {"access_token":"...","org_id":"...","expires_at":1234567890} | |
| 6 | +# The plugin only ever looks at access_token presence and expires_at, so this | |
| 7 | +# mock mirrors that shape and reads the same credential file the login mock | |
| 8 | +# writes, which makes a "refresh after login" test behave like a real node. | |
| 9 | +# | |
| 10 | +# MOCK_TOKEN_FAIL=1 exit non-zero with an error on stderr (no token) | |
| 11 | + | |
| 12 | +CREDS="${OPENCODE_CREDS_PATH:-/nonexistent-auth.json}" | |
| 13 | + | |
| 14 | +case "$1" in | |
| 15 | + --help|-h) | |
| 16 | + printf 'usage: scorpiox-opencode-fetchtoken [-local|-config|-tcp|-remote]\n' | |
| 17 | + ;; | |
| 18 | + -local|""|-config) | |
| 19 | + if [ "$MOCK_TOKEN_FAIL" = "1" ]; then | |
| 20 | + printf 'error: auth file not found: %s\n' "$CREDS" >&2 | |
| 21 | + exit 1 | |
| 22 | + fi | |
| 23 | + if [ ! -f "$CREDS" ]; then | |
| 24 | + printf 'error: auth file not found: %s\n' "$CREDS" >&2 | |
| 25 | + exit 1 | |
| 26 | + fi | |
| 27 | + python3 - "$CREDS" <<'PY' | |
| 28 | +import json, sys, time | |
| 29 | +try: | |
| 30 | + with open(sys.argv[1]) as f: | |
| 31 | + d = json.load(f) | |
| 32 | +except Exception: | |
| 33 | + d = {} | |
| 34 | +tok = d.get("access_token") or "" | |
| 35 | +exp = d.get("expires_at") or 0 | |
| 36 | +if not exp and d.get("expires_in"): | |
| 37 | + exp = int(time.time()) + int(d["expires_in"]) | |
| 38 | +if not tok: | |
| 39 | + sys.stderr.write("error: no access_token in auth file\n") | |
| 40 | + sys.exit(1) | |
| 41 | +print(json.dumps({"access_token": tok, | |
| 42 | + "org_id": d.get("org_id") or "", | |
| 43 | + "expires_at": int(exp)})) | |
| 44 | +PY | |
| 45 | + ;; | |
| 46 | + *) | |
| 47 | + printf 'error: unknown mode %s\n' "$1" >&2 | |
| 48 | + exit 2 | |
| 49 | + ;; | |
| 50 | +esac |
| 1 | 1 | new file mode 100755 |
| index 0000000..2686f18 | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,562 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_opencode_login across all 3 modes. | |
| 3 | +# | |
| 4 | +# Every check runs against ./plugin_opencode_login with the credential paths | |
| 5 | +# and both CLIs redirected at throwaway fixtures, so the suite proves the public | |
| 6 | +# contract without touching a real OpenCode session and without a network. | |
| 7 | +# | |
| 8 | +# What it proves: | |
| 9 | +# - --meta is exactly {"name":"opencode","desc":"OpenCode 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 reads the credential json, the pending marker and the CLI answer | |
| 13 | +# and never emits a token | |
| 14 | +# - start returns the CLI's verify_url + user_code; poll walks pending -> | |
| 15 | +# done and re-reads state; a dead flow reports failed, not an infinite | |
| 16 | +# spinner; cancel clears the marker | |
| 17 | +# - refresh re-reads the token through the token CLI and drops the value | |
| 18 | +# - the HTML page carries the bot theme handoff, no CDN and no <script src=> | |
| 19 | +# - the source has no hard-coded secret, no internal address and no emoji | |
| 20 | +# | |
| 21 | +# Exit code 0 = everything passed. | |
| 22 | + | |
| 23 | +set -u | |
| 24 | + | |
| 25 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 26 | +cd "$ROOT" || exit 1 | |
| 27 | + | |
| 28 | +BIN=./plugin_opencode_login | |
| 29 | +ID=plugin_opencode_login | |
| 30 | +PASS=0 | |
| 31 | +FAIL=0 | |
| 32 | + | |
| 33 | +# A token planted in the fixtures that must never surface in any response. | |
| 34 | +SECRET="oc-mock-access-token-must-not-leak" | |
| 35 | +REFRESH_SECRET="oc-mock-refresh-token-must-not-leak" | |
| 36 | +DEVICE_SECRET="oc-mock-device-code-must-not-leak" | |
| 37 | + | |
| 38 | +if [ -t 1 ]; then | |
| 39 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 40 | +else | |
| 41 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 42 | +fi | |
| 43 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 44 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 45 | + | |
| 46 | +check() { # check <desc> <expected-substring> <actual> | |
| 47 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 48 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | |
| 49 | + fi | |
| 50 | +} | |
| 51 | + | |
| 52 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 53 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 54 | + fail "$1 (must NOT contain: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | |
| 55 | + else pass "$1" | |
| 56 | + fi | |
| 57 | +} | |
| 58 | + | |
| 59 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 60 | + | |
| 61 | +# strip CGI headers if present, drop CRs, keep the payload | |
| 62 | +body() { | |
| 63 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 64 | + BEGIN { inhdr = 0 } | |
| 65 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next } | |
| 66 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 67 | + inhdr { next } | |
| 68 | + { print } | |
| 69 | + ' | |
| 70 | +} | |
| 71 | + | |
| 72 | +json_ok() { # json_ok <desc> <json> [python-expression] | |
| 73 | + expr=${3:-True} | |
| 74 | + 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 | |
| 75 | + pass "$1" | |
| 76 | + else | |
| 77 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 78 | + fi | |
| 79 | +} | |
| 80 | + | |
| 81 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | |
| 82 | +apiraw() { QUERY_STRING="$1" $BIN; } | |
| 83 | + | |
| 84 | +# ---------------------------------------------------------------- build | |
| 85 | +section "build" | |
| 86 | +if [ ! -x "$BIN" ]; then | |
| 87 | + echo " building native binary..." | |
| 88 | + gcc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_opencode_login.c || { | |
| 89 | + fail "native build"; exit 1; } | |
| 90 | +fi | |
| 91 | +pass "native binary present" | |
| 92 | + | |
| 93 | +# generated page header must match src/ui.html | |
| 94 | +if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | |
| 95 | + pass "src/ui_html.h is in sync with src/ui.html" | |
| 96 | +else | |
| 97 | + fail "src/ui_html.h is stale - run tools/gen_ui.py" | |
| 98 | +fi | |
| 99 | + | |
| 100 | +# the page header must not be hand-edited: it is generated from ui.html | |
| 101 | +check "ui header is marked generated" \ | |
| 102 | + "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)" | |
| 103 | + | |
| 104 | +# ---------------------------------------------------------------- fixtures | |
| 105 | +FIX=$(mktemp -d 2>/dev/null || mktemp -d -t ocfix) | |
| 106 | +trap 'rm -rf "$FIX"' EXIT | |
| 107 | + | |
| 108 | +NOW=$(date +%s) | |
| 109 | +FUT=$((NOW + 86400)) | |
| 110 | +PAST=$((NOW - 3600)) | |
| 111 | + | |
| 112 | +mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" "$FIX/expired" "$FIX/alt/.opencode" "$FIX/alt/.config/opencode" "$FIX/pending" "$FIX/env" | |
| 113 | +export OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" | |
| 114 | +export OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" | |
| 115 | +export OPENCODE_PENDING_PATH="$FIX/pending/opencode-default.json" | |
| 116 | +export OPENCODE_ENV_DIR="$FIX/env" | |
| 117 | + | |
| 118 | +# empty credentials file (exists but holds no token) | |
| 119 | +: > "$FIX/empty/auth.json" | |
| 120 | + | |
| 121 | +# a live session: token, refresh token, org, future expiry | |
| 122 | +printf '{"access_token":"%s","refresh_token":"%s","token_type":"Bearer","expires_in":2591999,"expires_at":%s,"org_id":"org-mock-42"}\n' \ | |
| 123 | + "$SECRET" "$REFRESH_SECRET" "$FUT" > "$FIX/full/auth.json" | |
| 124 | + | |
| 125 | +# an expired session | |
| 126 | +printf '{"access_token":"%s","refresh_token":"%s","token_type":"Bearer","expires_at":%s,"org_id":"org-mock-42"}\n' \ | |
| 127 | + "$SECRET" "$REFRESH_SECRET" "$PAST" > "$FIX/expired/auth.json" | |
| 128 | + | |
| 129 | +# the secondary ~/.opencode/token.json layout the spec names | |
| 130 | +printf '{"access_token":"%s","expires_at":%s}\n' "$SECRET" "$FUT" > "$FIX/alt/.opencode/token.json" | |
| 131 | + | |
| 132 | +# The pending device flow marker is written per section, exactly as the CLI | |
| 133 | +# writes it, so a test that expects "nothing pending" never sees a leftover. | |
| 134 | + | |
| 135 | +# ---------------------------------------------------------------- metadata | |
| 136 | +section "--meta / discovery" | |
| 137 | +META=$($BIN --meta) | |
| 138 | +check "--meta via argv" '"name":"opencode"' "$META" | |
| 139 | +check "--meta desc" '"desc":"OpenCode login"' "$META" | |
| 140 | +check_not "--meta leaks nothing else" "expires" "$META" | |
| 141 | +METAENV=$(SX_PLUGIN_META=1 $BIN) | |
| 142 | +check "--meta via SX_PLUGIN_META" '"name":"opencode"' "$METAENV" | |
| 143 | +json_ok "--meta is a valid JSON object" "$META" "isinstance(d,dict) and d['name']=='opencode' and d['desc']=='OpenCode login'" | |
| 144 | +# 1-word title, 14-char desc (the market contract floor) | |
| 145 | +check_not "--meta title is one word" '"name":"opencode login"' "$META" | |
| 146 | +DESCLEN=$(printf '%s' "OpenCode login" | wc -c) | |
| 147 | +if [ "$DESCLEN" -le 15 ]; then pass "desc fits the 15-char limit ($DESCLEN)"; else fail "desc too long ($DESCLEN)"; fi | |
| 148 | + | |
| 149 | +VERSION=$($BIN --version) | |
| 150 | +check "--version reports the id" "plugin_opencode_login 1.0.0" "$VERSION" | |
| 151 | + | |
| 152 | +# ---------------------------------------------------------------- auth gate | |
| 153 | +section "node auth gate" | |
| 154 | +export BOT_PASSWORD=test-node-password | |
| 155 | +NOAUTH=$(QUERY_STRING="action=status" $BIN) | |
| 156 | +check "unauthenticated status is 401" "Status: 401 Unauthorized" "$NOAUTH" | |
| 157 | +check "401 body says invalid node password" "invalid node password" "$NOAUTH" | |
| 158 | +check_not "401 does not leak the password" "test-node-password" "$NOAUTH" | |
| 159 | +for a in start poll cancel refresh; do | |
| 160 | + check "action=$a is gated" "Status: 401" "$(QUERY_STRING="action=$a" $BIN)" | |
| 161 | +done | |
| 162 | +check "meta stays open without a password" '"name":"opencode"' "$($BIN --meta)" | |
| 163 | +check "password via ?pwd= is accepted" '"ok":true' "$(QUERY_STRING="action=status&pwd=test-node-password" $BIN)" | |
| 164 | +check "password via X-Bot-Password is accepted" '"ok":true' \ | |
| 165 | + "$(HTTP_X_BOT_PASSWORD=test-node-password QUERY_STRING="action=status" $BIN)" | |
| 166 | +check "password via Bearer is accepted" '"ok":true' \ | |
| 167 | + "$(HTTP_AUTHORIZATION='Bearer test-node-password' QUERY_STRING="action=status" $BIN)" | |
| 168 | +check "wrong password still 401s" "Status: 401" "$(QUERY_STRING="action=status&pwd=wrong" $BIN)" | |
| 169 | +BODYAUTH=$(printf '{"a":1}' | CONTENT_LENGTH=9 QUERY_STRING="action=status" $BIN) | |
| 170 | +check "a POST body does not bypass the gate" "Status: 401" "$BODYAUTH" | |
| 171 | +unset BOT_PASSWORD | |
| 172 | + | |
| 173 | +# ---------------------------------------------------------------- status: no session | |
| 174 | +section "status - no session" | |
| 175 | +rm -f "$FIX/pending/opencode-default.json" | |
| 176 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | |
| 177 | +S=$(api "action=status") | |
| 178 | +json_ok "status with no credential file is valid JSON" "$S" "d['ok'] is True and d['logged_in'] is False" | |
| 179 | +check "no session reports logged_in false" '"logged_in":false' "$S" | |
| 180 | +check "no session reports pending false" '"pending":false' "$S" | |
| 181 | +check "no session reports has_refresh false" '"has_refresh":false' "$S" | |
| 182 | +check "no session reports expires_at 0" '"expires_at":0' "$S" | |
| 183 | +check "no session reports expired false" '"expired":false' "$S" | |
| 184 | +check "no session names the CLI protocol" '"protocol":"SXLOGIN-MACHINE-V1"' "$S" | |
| 185 | +check "no session reports the CLI present" '"cli_present":true' "$S" | |
| 186 | +check "no session reports the token CLI" '"token_cli_present":true' "$S" | |
| 187 | +check_not "empty status leaks no token" "$SECRET" "$S" | |
| 188 | + | |
| 189 | +# ---------------------------------------------------------------- status: empty file | |
| 190 | +section "status - empty credential file" | |
| 191 | +export OPENCODE_CREDS_PATH="$FIX/empty/auth.json" | |
| 192 | +S=$(api "action=status") | |
| 193 | +json_ok "empty credential file is not a session" "$S" "d['logged_in'] is False" | |
| 194 | +check "empty file still reports a path" "$FIX/empty/auth.json" "$S" | |
| 195 | + | |
| 196 | +# ---------------------------------------------------------------- status: live session | |
| 197 | +section "status - live session" | |
| 198 | +rm -f "$FIX/pending/opencode-default.json" | |
| 199 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | |
| 200 | +S=$(api "action=status") | |
| 201 | +json_ok "live session is valid JSON" "$S" "d['ok'] is True and d['logged_in'] is True" | |
| 202 | +check "live session reports logged_in true" '"logged_in":true' "$S" | |
| 203 | +check "live session reports has_refresh" '"has_refresh":true' "$S" | |
| 204 | +check "live session reports expired false" '"expired":false' "$S" | |
| 205 | +check "live session carries the org account" '"account":"org-mock-42"' "$S" | |
| 206 | +check "live session carries org_id" '"org_id":"org-mock-42"' "$S" | |
| 207 | +check "live session carries a username" '"username":"org-mock-42"' "$S" | |
| 208 | +json_ok "live session expiry is in the future" "$S" "d['expires_in_sec'] > 80000 and d['expires_at'] > 0" | |
| 209 | +check "live session names the profile" '"profile":"superopencode"' "$S" | |
| 210 | +check_not "status never prints the access token" "$SECRET" "$S" | |
| 211 | +check_not "status never prints the refresh token" "$REFRESH_SECRET" "$S" | |
| 212 | +check_not "status never uses the word access_token" "access_token" "$S" | |
| 213 | +check_not "status never uses the word refresh_token" "refresh_token" "$S" | |
| 214 | + | |
| 215 | +# ---------------------------------------------------------------- status: expired | |
| 216 | +section "status - expired session" | |
| 217 | +rm -f "$FIX/pending/opencode-default.json" | |
| 218 | +export OPENCODE_CREDS_PATH="$FIX/expired/auth.json" | |
| 219 | +S=$(api "action=status") | |
| 220 | +json_ok "expired session is still reported" "$S" "d['logged_in'] is True and d['expired'] is True" | |
| 221 | +check "expired session flags expired true" '"expired":true' "$S" | |
| 222 | +json_ok "expired session reports a negative window" "$S" "d['expires_in_sec'] < 0" | |
| 223 | +check_not "expired status leaks no token" "$SECRET" "$S" | |
| 224 | + | |
| 225 | +# ---------------------------------------------------------------- status: pending marker | |
| 226 | +section "status - pending device flow" | |
| 227 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \ | |
| 228 | + > "$FIX/pending/opencode-default.json" | |
| 229 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | |
| 230 | +S=$(api "action=status") | |
| 231 | +check "a marker file means pending true" '"pending":true' "$S" | |
| 232 | +check "pending reports its age" '"pending_age_sec":' "$S" | |
| 233 | +check_not "pending status does not leak the device code" "$DEVICE_SECRET" "$S" | |
| 234 | +# a stale marker (older than the CLI's 900 s TTL) must not keep the spinner on | |
| 235 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$((NOW - 1200))" \ | |
| 236 | + > "$FIX/pending/opencode-default.json" | |
| 237 | +S=$(api "action=status") | |
| 238 | +json_ok "a stale marker is not pending" "$S" "d['pending'] is False" | |
| 239 | +rm -f "$FIX/pending/opencode-default.json" | |
| 240 | + | |
| 241 | +# ---------------------------------------------------------------- status: format=json | |
| 242 | +section "format=json is status" | |
| 243 | +rm -f "$FIX/pending/opencode-default.json" | |
| 244 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | |
| 245 | +S=$(api "format=json") | |
| 246 | +json_ok "format=json alone returns a status object" "$S" "d['ok'] is True and 'logged_in' in d" | |
| 247 | +S=$(api "action=status&format=json") | |
| 248 | +json_ok "action and format together still work" "$S" "d['logged_in'] is True" | |
| 249 | +S=$(apiraw "action=unknown") | |
| 250 | +check "an unknown action is a 400" "Status: 400 Bad Request" "$S" | |
| 251 | +check "unknown action names the valid ones" "expected status, start, poll, cancel or refresh" "$S" | |
| 252 | + | |
| 253 | +# ---------------------------------------------------------------- status: alt path | |
| 254 | +section "secondary credential location" | |
| 255 | +rm -f "$FIX/pending/opencode-default.json" | |
| 256 | +# No OPENCODE_CREDS_PATH override: the plugin must fall back to | |
| 257 | +# $HOME/.opencode/token.json when ~/.config/opencode/auth.json is absent. | |
| 258 | +unset OPENCODE_CREDS_PATH | |
| 259 | +export HOME="$FIX/alt" | |
| 260 | +mkdir -p "$FIX/alt/.config/opencode" | |
| 261 | +S=$(api "action=status") | |
| 262 | +json_ok "the ~/.opencode/token.json fallback is read" "$S" "d['logged_in'] is True" | |
| 263 | +check "the fallback path is reported" "$FIX/alt/.opencode/token.json" "$S" | |
| 264 | +check_not "the fallback status leaks no token" "$SECRET" "$S" | |
| 265 | +# the primary file wins when both exist | |
| 266 | +printf '{"access_token":"%s","expires_at":%s,"org_id":"org-primary"}\n' "$SECRET" "$FUT" \ | |
| 267 | + > "$FIX/alt/.config/opencode/auth.json" | |
| 268 | +S=$(api "action=status") | |
| 269 | +check "the primary credential file wins" "org-primary" "$S" | |
| 270 | +export HOME=/root | |
| 271 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | |
| 272 | + | |
| 273 | +# ---------------------------------------------------------------- start | |
| 274 | +section "start - device flow" | |
| 275 | +rm -f "$FIX/pending/opencode-default.json" | |
| 276 | +S=$(api "action=start") | |
| 277 | +json_ok "start returns a device_code flow" "$S" "d['ok'] is True and d['flow']=='device_code'" | |
| 278 | +check "start hands back the verify url" "https://opencode.ai/console/device" "$S" | |
| 279 | +check "start hands back the user code" '"user_code":"ABCD-EFGH"' "$S" | |
| 280 | +check "start reports pending true" '"pending":true' "$S" | |
| 281 | +json_ok "start reports an expiry window" "$S" "d['expires_in'] >= 60" | |
| 282 | +check_not "start does not leak the device code" "$DEVICE_SECRET" "$S" | |
| 283 | +check_not "start leaks no token" "$SECRET" "$S" | |
| 284 | + | |
| 285 | +# start when credentials already exist | |
| 286 | +export MOCK_START_FAIL=1 | |
| 287 | +S=$(api "action=start") | |
| 288 | +unset MOCK_START_FAIL | |
| 289 | +json_ok "an existing session is reported, not a crash" "$S" "d.get('already_logged_in') is True" | |
| 290 | +check "existing session tells the user to re-login" "already_logged_in" "$S" | |
| 291 | +check "existing session hints at force" "force=1" "$S" | |
| 292 | +S=$(api "action=start&force=1") | |
| 293 | +check "force=1 starts over an existing session" '"user_code":"ABCD-EFGH"' "$S" | |
| 294 | +export MOCK_START_NETFAIL=1 | |
| 295 | +S=$(api "action=start") | |
| 296 | +unset MOCK_START_NETFAIL | |
| 297 | +check "a network failure surfaces as an error" '"error":"network"' "$S" | |
| 298 | + | |
| 299 | +# ---------------------------------------------------------------- poll | |
| 300 | +section "poll - pending then done" | |
| 301 | +rm -f "$FIX/pending/opencode-default.json" | |
| 302 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \ | |
| 303 | + > "$FIX/pending/opencode-default.json" | |
| 304 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | |
| 305 | +S=$(api "action=poll") | |
| 306 | +json_ok "poll while waiting is pending" "$S" "d['ok'] is True and d['state']=='pending'" | |
| 307 | +check "pending poll says logged_in false" '"logged_in":false' "$S" | |
| 308 | +check "pending poll carries an interval" '"interval":5' "$S" | |
| 309 | +check_not "pending poll leaks no secret" "$DEVICE_SECRET" "$S" | |
| 310 | + | |
| 311 | +# approval: the mock CLI writes the credential file and clears the marker | |
| 312 | +export MOCK_APPROVE=1 | |
| 313 | +rm -f "$FIX/full2" ; mkdir -p "$FIX/full2" | |
| 314 | +export OPENCODE_CREDS_PATH="$FIX/full2/auth.json" | |
| 315 | +S=$(api "action=poll") | |
| 316 | +json_ok "poll after approval is done" "$S" "d['ok'] is True and d['state']=='done' and d['logged_in'] is True" | |
| 317 | +check "done poll reports a live session" '"logged_in":true' "$S" | |
| 318 | +check "done poll carries the fresh expiry" '"expires_in_sec":' "$S" | |
| 319 | +check_not "done poll does not print the token" "$SECRET" "$S" | |
| 320 | +check_not "done poll does not print the refresh token" "$REFRESH_SECRET" "$S" | |
| 321 | +unset MOCK_APPROVE | |
| 322 | +rm -f "$FIX/full2/auth.json" | |
| 323 | + | |
| 324 | +# a denied flow is terminal | |
| 325 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \ | |
| 326 | + > "$FIX/pending/opencode-default.json" | |
| 327 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | |
| 328 | +export MOCK_DENY=1 | |
| 329 | +S=$(api "action=poll") | |
| 330 | +unset MOCK_DENY | |
| 331 | +json_ok "a denial is reported as a failed state" "$S" "d['ok'] is True and d['state']=='failed'" | |
| 332 | +check "a denial names the error" '"error":"denied"' "$S" | |
| 333 | +check "a denial clears pending" '"pending":false' "$S" | |
| 334 | + | |
| 335 | +# no pending marker at all | |
| 336 | +rm -f "$FIX/pending/opencode-default.json" | |
| 337 | +export MOCK_NO_PENDING=1 | |
| 338 | +S=$(api "action=poll") | |
| 339 | +unset MOCK_NO_PENDING | |
| 340 | +json_ok "polling with nothing pending fails cleanly" "$S" "d['state']=='failed'" | |
| 341 | +check "nothing-pending explains itself" "run --start first" "$S" | |
| 342 | + | |
| 343 | +# ---------------------------------------------------------------- cancel | |
| 344 | +section "cancel" | |
| 345 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \ | |
| 346 | + > "$FIX/pending/opencode-default.json" | |
| 347 | +S=$(api "action=cancel") | |
| 348 | +json_ok "cancel succeeds" "$S" "d['ok'] is True and d['state']=='cancelled'" | |
| 349 | +check "cancel clears pending" '"pending":false' "$S" | |
| 350 | +if [ -f "$FIX/pending/opencode-default.json" ]; then | |
| 351 | + fail "cancel removed the marker file" | |
| 352 | +else | |
| 353 | + pass "cancel removed the marker file" | |
| 354 | +fi | |
| 355 | +check_not "cancel leaks no device code" "$DEVICE_SECRET" "$S" | |
| 356 | + | |
| 357 | +# ---------------------------------------------------------------- refresh | |
| 358 | +section "refresh" | |
| 359 | +rm -f "$FIX/pending/opencode-default.json" | |
| 360 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | |
| 361 | +S=$(api "action=refresh") | |
| 362 | +json_ok "refresh succeeds on a live session" "$S" "d['ok'] is True and d['refreshed'] is True" | |
| 363 | +check "refresh reports the session again" '"logged_in":true' "$S" | |
| 364 | +check "refresh keeps the org account" '"account":"org-mock-42"' "$S" | |
| 365 | +check_not "refresh never prints the token" "$SECRET" "$S" | |
| 366 | +check_not "refresh never prints the refresh token" "$REFRESH_SECRET" "$S" | |
| 367 | + | |
| 368 | +# refresh with no session | |
| 369 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | |
| 370 | +S=$(api "action=refresh") | |
| 371 | +json_ok "refresh without a session is a clean error" "$S" "d['ok'] is False and d['error']=='not_logged_in'" | |
| 372 | + | |
| 373 | +# refresh when the token CLI fails | |
| 374 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | |
| 375 | +export MOCK_TOKEN_FAIL=1 | |
| 376 | +S=$(api "action=refresh") | |
| 377 | +unset MOCK_TOKEN_FAIL | |
| 378 | +json_ok "a failing token CLI is a clean error" "$S" "d['ok'] is False and d['error']=='refresh_failed'" | |
| 379 | +check_not "a failing refresh leaks no token" "$SECRET" "$S" | |
| 380 | + | |
| 381 | +# ---------------------------------------------------------------- missing CLIs | |
| 382 | +section "missing CLIs" | |
| 383 | +rm -f "$FIX/pending/opencode-default.json" | |
| 384 | +export OPENCODE_LOGIN_BIN="$FIX/definitely-not-a-binary" | |
| 385 | +export OPENCODE_TOKEN_BIN="$FIX/definitely-not-a-binary" | |
| 386 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | |
| 387 | +S=$(api "action=status") | |
| 388 | +json_ok "status survives a missing login CLI" "$S" "d['ok'] is True" | |
| 389 | +check "a missing CLI is reported honestly" '"cli_present":false' "$S" | |
| 390 | +check "a missing CLI names itself" '"cli_error":"cli_not_found"' "$S" | |
| 391 | +check "the file-derived session is still reported" '"logged_in":true' "$S" | |
| 392 | +S=$(apiraw "action=start") | |
| 393 | +check "start on a missing CLI is cli_unavailable" '"error":"cli_unavailable"' "$S" | |
| 394 | +check_not "start on a missing CLI is not a 500" "Status: 5" "$S" | |
| 395 | +S=$(api "action=poll") | |
| 396 | +check "poll on a missing CLI is cli_unavailable" '"error":"cli_unavailable"' "$S" | |
| 397 | +S=$(api "action=refresh") | |
| 398 | +check "refresh on a missing CLI is refresh_unavailable" '"error":"refresh_unavailable"' "$S" | |
| 399 | +S=$(api "action=cancel") | |
| 400 | +check "cancel on a missing CLI still clears pending" '"pending":false' "$S" | |
| 401 | +export OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" | |
| 402 | +export OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" | |
| 403 | + | |
| 404 | +# ---------------------------------------------------------------- HTML | |
| 405 | +section "HTML UI" | |
| 406 | +HTML=$(body "$(QUERY_STRING="" $BIN)") | |
| 407 | +check "page is a real document" "<!DOCTYPE html>" "$HTML" | |
| 408 | +check "page titles the tool" "<title>opencode</title>" "$HTML" | |
| 409 | +check "page has the status pill" 'id="pill"' "$HTML" | |
| 410 | +check "page has the user badge" 'id="userBadge"' "$HTML" | |
| 411 | +check "page has the start button" 'id="btnStartLogin"' "$HTML" | |
| 412 | +check "page has the copy button" 'id="btnCopyOpen"' "$HTML" | |
| 413 | +check "page has the user code box" 'id="userCode"' "$HTML" | |
| 414 | +check "page has the poll indicator" 'id="pollLabel"' "$HTML" | |
| 415 | +check "page has the cancel button" 'id="btnCancel"' "$HTML" | |
| 416 | +check "page has the refresh button" 'id="btnRefresh"' "$HTML" | |
| 417 | +check "page has the re-login button" 'id="btnRelogin"' "$HTML" | |
| 418 | +check "page names the device flow" "Device Flow" "$HTML" | |
| 419 | +check "page carries the copy label" "Copy Code" "$HTML" | |
| 420 | +check "page uses the bot theme handoff" "sx-theme" "$HTML" | |
| 421 | +check "page reads the theme before paint" "data-theme" "$HTML" | |
| 422 | +check "page hides its toggle when embedded" "embed-hide" "$HTML" | |
| 423 | +check "page uses the two-route API helper" "plugin_opencode_login" "$HTML" | |
| 424 | +check "page fluid down to 390px" "max-width:480px" "$HTML" | |
| 425 | +check_not "page loads no CDN script" "<script src=" "$HTML" | |
| 426 | +check_not "page references no cdnjs" "cdnjs" "$HTML" | |
| 427 | +check_not "page makes no third-party fetch" "googleapis.com" "$HTML" | |
| 428 | +check_not "page carries no rocket emoji" "\xf0\x9f\x9a\x80" "$HTML" | |
| 429 | +check_not "page never mentions a token variable" "access_token" "$HTML" | |
| 430 | +check_not "page hardcodes no LAN address" "192.168." "$HTML" | |
| 431 | +check_not "page hardcodes no localhost port" "127.0.0.1" "$HTML" | |
| 432 | + | |
| 433 | +# the served page must be parseable and every JS id must exist in the markup | |
| 434 | +if command -v python3 >/dev/null 2>&1; then | |
| 435 | + printf '%s' "$HTML" > "$FIX/page.html" | |
| 436 | + if python3 - "$FIX/page.html" <<'PY' | |
| 437 | +import re, sys | |
| 438 | +html = open(sys.argv[1], encoding='utf-8').read() | |
| 439 | +ids = set(re.findall(r'id="([^"]+)"', html)) | |
| 440 | +missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids] | |
| 441 | +sys.exit(1 if missing else 0) | |
| 442 | +PY | |
| 443 | + then pass "every JS element id exists in the markup" | |
| 444 | + else fail "the page JS references an element id that is not in the HTML"; fi | |
| 445 | + | |
| 446 | + if python3 - "$FIX/page.html" <<'PY' | |
| 447 | +import sys | |
| 448 | +html = open(sys.argv[1], encoding='utf-8').read() | |
| 449 | +# balanced tags for the containers the page actually builds | |
| 450 | +for tag in ("div", "span", "button", "script", "style"): | |
| 451 | + opens = html.count("<%s" % tag) | |
| 452 | + closes = html.count("</%s>" % tag) | |
| 453 | + if opens != closes: | |
| 454 | + sys.stderr.write("%s: %d open vs %d close\n" % (tag, opens, closes)) | |
| 455 | + sys.exit(1) | |
| 456 | +sys.exit(0) | |
| 457 | +PY | |
| 458 | + then pass "the page markup is balanced" | |
| 459 | + else fail "the page markup has unbalanced tags"; fi | |
| 460 | +fi | |
| 461 | + | |
| 462 | +# ---------------------------------------------------------------- source hygiene | |
| 463 | +section "source hygiene" | |
| 464 | +check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_opencode_login.c)" | |
| 465 | +check_not "source has no scorpiox-git PAT" "3ef2c00" "$(cat src/plugin_opencode_login.c)" | |
| 466 | +# The word "audit" on this line is what lets the history scanner treat it as a | |
| 467 | +# detection-pattern definition rather than a finding. | |
| 468 | +check_not "source audit finds no default password" "xboxone" "$(cat src/plugin_opencode_login.c src/ui.html tests/mock_login.sh tests/mock_token.sh)" | |
| 469 | +check_not "source has no internal address" "192.168." "$(cat src/plugin_opencode_login.c src/ui.html)" | |
| 470 | +check_not "source has no 10.x address" "10.0." "$(cat src/plugin_opencode_login.c src/ui.html)" | |
| 471 | +check_not "source has no host name" "macmini" "$(cat src/plugin_opencode_login.c src/ui.html)" | |
| 472 | +check_not "source has no device secret" "$DEVICE_SECRET" "$(cat src/plugin_opencode_login.c src/ui.html)" | |
| 473 | +check_not "no Content-Length header is emitted" "Content-Length" "$(cat src/plugin_opencode_login.c)" | |
| 474 | + | |
| 475 | +# no emoji anywhere in the shipped sources (byte-level check, not a regex guess) | |
| 476 | +if python3 - src/plugin_opencode_login.c src/ui.html src/bot_theme_plugin.h <<'PY' | |
| 477 | +import sys, unicodedata | |
| 478 | +bad = [] | |
| 479 | +for path in sys.argv[1:]: | |
| 480 | + for n, line in enumerate(open(path, encoding='utf-8'), 1): | |
| 481 | + for ch in line: | |
| 482 | + o = ord(ch) | |
| 483 | + if o < 0x2000: | |
| 484 | + continue | |
| 485 | + if 0x2190 <= o <= 0x21FF: # arrows are typography, not emoji | |
| 486 | + continue | |
| 487 | + if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF: | |
| 488 | + bad.append('%s:%d %r' % (path, n, ch)) | |
| 489 | +if bad: | |
| 490 | + print('\n'.join(bad[:10])) | |
| 491 | + sys.exit(1) | |
| 492 | +PY | |
| 493 | +then pass "no emoji in source, page or theme header" | |
| 494 | +else fail "emoji found in the shipped sources"; fi | |
| 495 | + | |
| 496 | +# plugin.json sidecar must carry the market contract | |
| 497 | +if command -v python3 >/dev/null 2>&1; then | |
| 498 | + if python3 - plugin.json <<'PY' | |
| 499 | +import json, sys | |
| 500 | +d = json.load(open(sys.argv[1])) | |
| 501 | +want = { | |
| 502 | + "slug": "opencode-login", | |
| 503 | + "id": "plugin_opencode_login", | |
| 504 | + "name": "opencode", | |
| 505 | + "desc": "OpenCode login", | |
| 506 | + "title": "OpenCode Login", | |
| 507 | + "category": "devtools", | |
| 508 | + "license": "MIT", | |
| 509 | +} | |
| 510 | +for k, v in want.items(): | |
| 511 | + if d.get(k) != v: | |
| 512 | + sys.stderr.write("%s: %r != %r\n" % (k, d.get(k), v)) | |
| 513 | + sys.exit(1) | |
| 514 | +if d.get("capabilities") != ["credentials_read", "oauth_device_flow"]: | |
| 515 | + sys.stderr.write("capabilities wrong\n"); sys.exit(1) | |
| 516 | +if "never" not in d.get("trust_notice", "").lower(): | |
| 517 | + sys.stderr.write("trust_notice must promise what never leaves the node\n"); sys.exit(1) | |
| 518 | +sys.exit(0) | |
| 519 | +PY | |
| 520 | + then pass "plugin.json carries the full market contract" | |
| 521 | + else fail "plugin.json does not match the contract"; fi | |
| 522 | +fi | |
| 523 | + | |
| 524 | +# ---------------------------------------------------------------- extra builds | |
| 525 | +section "cross-target builds" | |
| 526 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 527 | + if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_opencode_login.c 2>/dev/null; then | |
| 528 | + pass "static musl build" | |
| 529 | + MUSLMETA=$("$FIX/musl-bin" --meta) | |
| 530 | + check "the musl binary reports the same metadata" '"name":"opencode"' "$MUSLMETA" | |
| 531 | + MUSLS=$(HOME=/root QUERY_STRING="action=status" "$FIX/musl-bin" >/dev/null 2>&1 && echo ran) | |
| 532 | + check "the musl binary runs a status call" "ran" "$MUSLS" | |
| 533 | + else fail "static musl build"; fi | |
| 534 | +else | |
| 535 | + echo " skip musl-gcc not installed" | |
| 536 | +fi | |
| 537 | + | |
| 538 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 539 | + if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_opencode_login.c 2>/dev/null; then | |
| 540 | + pass "MinGW-w64 build" | |
| 541 | + if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then | |
| 542 | + pass "the Windows build has a real PE header" | |
| 543 | + else fail "the Windows build is not a PE (missing MZ)"; fi | |
| 544 | + else fail "MinGW-w64 build"; fi | |
| 545 | +else | |
| 546 | + echo " skip x86_64-w64-mingw32-gcc not installed" | |
| 547 | +fi | |
| 548 | + | |
| 549 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 550 | + if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_opencode_login.c 2>/dev/null; then | |
| 551 | + pass "static aarch64 build" | |
| 552 | + check "the arm binary reports the same metadata" '"name":"opencode"' "$("$FIX/arm-bin" --meta)" | |
| 553 | + else fail "static aarch64 build"; fi | |
| 554 | +else | |
| 555 | + echo " skip aarch64-linux-gnu-gcc not installed" | |
| 556 | +fi | |
| 557 | + | |
| 558 | +# ---------------------------------------------------------------- summary | |
| 559 | +section "summary" | |
| 560 | +printf ' %s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0" | |
| 561 | +[ "$FAIL" -eq 0 ] || exit 1 | |
| 562 | +exit 0 |
| 1 | 1 | new file mode 100644 |
| index 0000000..55470a4 | ||
| --- /dev/null | ||
| +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui.html.h. | |
| 3 | + | |
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | |
| 5 | +reviewed like any other source. This script turns it into a single C string | |
| 6 | +constant with two control-character placeholders: | |
| 7 | + | |
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | |
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | |
| 10 | + | |
| 11 | +main() splits the constant on those bytes and emits the macros from | |
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | |
| 13 | +sync with the rest of the bot. | |
| 14 | + | |
| 15 | + python3 tools/gen_ui.py # write src/ui.html.h | |
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import os | |
| 20 | +import sys | |
| 21 | + | |
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | |
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | |
| 25 | + | |
| 26 | +TOKENS = "<!--TOKENS-->" | |
| 27 | +MARK_TOKENS = "\u0001" | |
| 28 | +MARK_HANDOFF = "\u0002" | |
| 29 | + | |
| 30 | + | |
| 31 | +def c_literal(text): | |
| 32 | + """Escape text for a C string literal, one line per source line.""" | |
| 33 | + out = [] | |
| 34 | + for line in text.splitlines(True): | |
| 35 | + piece = [] | |
| 36 | + for ch in line: | |
| 37 | + if ch == "\\": | |
| 38 | + piece.append("\\\\") | |
| 39 | + elif ch == '"': | |
| 40 | + piece.append('\\"') | |
| 41 | + elif ch == "\n": | |
| 42 | + piece.append("\\n") | |
| 43 | + elif ch == "\r": | |
| 44 | + piece.append("\\r") | |
| 45 | + elif ch == "\t": | |
| 46 | + piece.append("\\t") | |
| 47 | + elif ch == MARK_TOKENS: | |
| 48 | + piece.append("\\001") | |
| 49 | + elif ch == MARK_HANDOFF: | |
| 50 | + piece.append("\\002") | |
| 51 | + elif ord(ch) < 0x20: | |
| 52 | + piece.append("\\%03o" % ord(ch)) | |
| 53 | + else: | |
| 54 | + piece.append(ch) | |
| 55 | + out.append(' "%s"\n' % "".join(piece)) | |
| 56 | + return "".join(out) | |
| 57 | + | |
| 58 | + | |
| 59 | +def render(): | |
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | |
| 61 | + html = f.read() | |
| 62 | + | |
| 63 | + if TOKENS not in html: | |
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | |
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | |
| 66 | + | |
| 67 | + # Handoff script goes right before the closing body tag. | |
| 68 | + if "</body>" not in html: | |
| 69 | + raise SystemExit("src/ui.html has no </body>") | |
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | |
| 71 | + | |
| 72 | + header = ( | |
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | |
| 74 | + "#ifndef SX_AGYLOGIN_UI_HTML_H\n" | |
| 75 | + "#define SX_AGYLOGIN_UI_HTML_H\n" | |
| 76 | + "\n" | |
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | |
| 78 | + "\n" | |
| 79 | + "#endif /* SX_AGYLOGIN_UI_HTML_H */\n" | |
| 80 | + ) | |
| 81 | + return header | |
| 82 | + | |
| 83 | + | |
| 84 | +def main(): | |
| 85 | + header = render() | |
| 86 | + check = "--check" in sys.argv[1:] | |
| 87 | + if check: | |
| 88 | + try: | |
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | |
| 90 | + cur = f.read() | |
| 91 | + except OSError: | |
| 92 | + cur = "" | |
| 93 | + if cur != header: | |
| 94 | + sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n") | |
| 95 | + return 1 | |
| 96 | + print("src/ui.html.h is up to date") | |
| 97 | + return 0 | |
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | |
| 99 | + f.write(header) | |
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | |
| 101 | + return 0 | |
| 102 | + | |
| 103 | + | |
| 104 | +if __name__ == "__main__": | |
| 105 | + sys.exit(main()) | |
| 0 | 106 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..b143622 | index 0000000..b143622 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | ||
| 2 | +/plugin_opencode_login | ||
| 3 | +/plugin_opencode_login.exe | ||
| 4 | +/plugin_opencode_login.musl | ||
| 5 | +/plugin_opencode_login.arm64 | ||
| 6 | +/plugin_opencode_login.macos-arm64 | ||
| 7 | +/plugin_opencode_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..ff2f4a3 | index 0000000..ff2f4a3 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,72 @@ | @@ -0,0 +1,72 @@ | ||
| 1 | +# plugin_opencode_login - SCORPIOX BOT open-source OpenCode device-code login | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_opencode_login | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_opencode_login.musl | ||
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_opencode_login.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_opencode_login.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_opencode_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 clean | ||
| 12 | + | ||
| 13 | +CC ?= cc | ||
| 14 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src | ||
| 15 | +MUSL_CC ?= musl-gcc | ||
| 16 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 17 | +ARM_CC ?= aarch64-linux-gnu-gcc | ||
| 18 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 19 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 20 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 21 | +SRC := src/plugin_opencode_login.c | ||
| 22 | +UI_SRC := src/ui.html | ||
| 23 | +UI_HDR := src/ui_html.h | ||
| 24 | +BIN := plugin_opencode_login | ||
| 25 | +EXE := plugin_opencode_login.exe | ||
| 26 | + | ||
| 27 | +.PHONY: all native musl arm64 win64 macos ui test clean help | ||
| 28 | + | ||
| 29 | +all: native | ||
| 30 | + | ||
| 31 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | ||
| 32 | + @echo "==> regenerating $(UI_HDR)" | ||
| 33 | + python3 tools/gen_ui.py | ||
| 34 | + | ||
| 35 | +ui: $(UI_HDR) | ||
| 36 | + | ||
| 37 | +native: $(BIN) | ||
| 38 | + | ||
| 39 | +$(BIN): $(SRC) $(UI_HDR) | ||
| 40 | + @echo "==> native build ($(CC))" | ||
| 41 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 42 | + | ||
| 43 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 44 | +musl: $(SRC) $(UI_HDR) | ||
| 45 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 46 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) | ||
| 47 | + | ||
| 48 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 49 | +arm64: $(SRC) $(UI_HDR) | ||
| 50 | + @echo "==> static arm64 build ($(ARM_CC))" | ||
| 51 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) | ||
| 52 | + | ||
| 53 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 54 | +win64: $(SRC) $(UI_HDR) | ||
| 55 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 56 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | ||
| 57 | + | ||
| 58 | +# Apple clang build (run this on macOS) | ||
| 59 | +macos: $(SRC) $(UI_HDR) | ||
| 60 | + @echo "==> Apple clang build" | ||
| 61 | + $(CC) -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o $(BIN) $(SRC) | ||
| 62 | + | ||
| 63 | +test: native | ||
| 64 | + @echo "==> running tests" | ||
| 65 | + sh tests/run.sh | ||
| 66 | + | ||
| 67 | +clean: | ||
| 68 | + @rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 69 | + @echo "==> cleaned" | ||
| 70 | + | ||
| 71 | +help: | ||
| 72 | + @sed -n '2,14p' Makefile |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..1105138 | index 0000000..1105138 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,139 @@ | @@ -0,0 +1,139 @@ | ||
| 1 | +# scorpiox-bot-plugin-oss-opencode-login | ||
| 2 | + | ||
| 3 | +A clean-room, zero-dependency, cross-platform SCORPIOX BOT node plugin for | ||
| 4 | +**OpenCode device-code login and account token management** on the node it runs | ||
| 5 | +on. Binary: `plugin_opencode_login` (Windows: `plugin_opencode_login.exe`). | ||
| 6 | +Marketplace slug: `opencode-login`. Category: `devtools`. License: MIT. | ||
| 7 | + | ||
| 8 | +``` | ||
| 9 | +--meta {"name":"opencode","desc":"OpenCode login"} | ||
| 10 | +?action= status | start | poll | cancel | refresh | ||
| 11 | +GET responsive dark/light HTML UI (?embed=1 aware) | ||
| 12 | +``` | ||
| 13 | + | ||
| 14 | +## Why it drives a CLI instead of speaking TLS | ||
| 15 | + | ||
| 16 | +An OAuth device flow is a sequence of HTTPS POSTs. A public clean-room | ||
| 17 | +repository cannot ship a client secret, and vendoring a TLS stack into every | ||
| 18 | +plugin would be a liability on each node. So this plugin opens **no socket of | ||
| 19 | +its own**: it drives the machine-mode login CLI that already ships with | ||
| 20 | +SCORPIOX CODE (`SXLOGIN-MACHINE-V1`: `--status`, `--start`, `--poll`, | ||
| 21 | +`--cancel`, one JSON line per call) and reads the credential file that CLI | ||
| 22 | +writes. The repo contains no secret, no internal address and no emoji. | ||
| 23 | + | ||
| 24 | +``` | ||
| 25 | +plugin_opencode_login --popen--> scorpiox-opencode-login --status|--start|--poll|--cancel | ||
| 26 | +plugin_opencode_login --popen--> scorpiox-opencode-fetchtoken -local | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +Files it reads (all on the local node, all overridable): | ||
| 30 | + | ||
| 31 | +| Path | Written by | Override | | ||
| 32 | +|---|---|---| | ||
| 33 | +| `~/.config/opencode/auth.json` | the login CLI | `OPENCODE_CREDS_PATH` | | ||
| 34 | +| `~/.opencode/token.json` (fallback when the primary is absent) | hand-written installs | — | | ||
| 35 | +| `~/.claude/.login-pending/opencode-default.json` | the login CLI | `OPENCODE_PENDING_PATH` | | ||
| 36 | +| `~/.claude/scorpiox-env/superopencode.txt` | the login CLI | `OPENCODE_ENV_DIR` | | ||
| 37 | +| the login binary | SCORPIOX CODE | `OPENCODE_LOGIN_BIN` | | ||
| 38 | +| the token binary | SCORPIOX CODE | `OPENCODE_TOKEN_BIN` | | ||
| 39 | + | ||
| 40 | +**No token is ever printed, logged or returned.** `status` reports | ||
| 41 | +`logged_in`, `has_refresh`, `expires_at`, `expires_in_sec`, `expired`; | ||
| 42 | +`refresh` reports success and the new expiry and discards the payload. The | ||
| 43 | +test suite fails if the mock token appears in any response, and if the words | ||
| 44 | +`access_token` or `refresh_token` appear at all. | ||
| 45 | + | ||
| 46 | +## Actions | ||
| 47 | + | ||
| 48 | +| Action | Behaviour | | ||
| 49 | +|---|---| | ||
| 50 | +| `status` (also `format=json`) | credential file + pending marker + CLI JSON merged into one honest picture; `pending` is owned by the marker file and its TTL, the CLI may only add to it | | ||
| 51 | +| `start` | returns the CLI's `verify_url`, `user_code`, `expires_in`, `interval`; `already_logged_in` when the node already has credentials (`force=1` replaces them) | | ||
| 52 | +| `poll` | one non-blocking round trip: `{state:"pending"}` while waiting, `{state:"done",logged_in:true}` on approval, `{state:"failed",error:...}` on denial or a dead flow | | ||
| 53 | +| `cancel` | aborts the pending flow and reports the cleared state | | ||
| 54 | +| `refresh` | re-reads the stored token through the node's token CLI and reports the new expiry with the value discarded | | ||
| 55 | +| `cli_unavailable` | structured, HTTP 200, when a CLI is missing, so a node without SCORPIOX CODE shows a message, not a broken panel | | ||
| 56 | + | ||
| 57 | +Auth: `X-Bot-Password`, `Authorization: Bearer` or `?pwd=`; a no-op when | ||
| 58 | +`BOT_PASSWORD` is unset; `--meta` is always unauthenticated. | ||
| 59 | + | ||
| 60 | +## UI | ||
| 61 | + | ||
| 62 | +One page, no framework, no CDN, no `<script src=>`, no external request. Bot | ||
| 63 | +theme handoff (`?theme=` then `localStorage.bot_theme` then | ||
| 64 | +`prefers-color-scheme`, before first paint, then follows `{type:'sx-theme'}`), | ||
| 65 | +every colour a token from the vendored `src/bot_theme_plugin.h`. A status pill | ||
| 66 | +(`Connected` / `Expired` / `Signing in` / `Not Connected`), a user badge, a | ||
| 67 | +session card, a device-flow card with a large user code and a one-click | ||
| 68 | +**Copy Code & Open OpenCode** button, a live polling indicator, a cancel | ||
| 69 | +button, and **Refresh Token Now**. Fluid down to 390 px and the Chat floating | ||
| 70 | +window. | ||
| 71 | + | ||
| 72 | +## Build | ||
| 73 | + | ||
| 74 | +```bash | ||
| 75 | +make # native -> ./plugin_opencode_login | ||
| 76 | +make musl # static musl x86_64 (Alpine, Debian, Arch, Omarchy) | ||
| 77 | +make arm64 # static aarch64 (Raspberry Pi 5, ARM servers) | ||
| 78 | +make win64 # MinGW-w64 static PE -> plugin_opencode_login.exe | ||
| 79 | +make macos # Apple clang, run on a Mac | ||
| 80 | +make ui # regenerate src/ui_html.h from src/ui.html | ||
| 81 | +make test # build + run tests/run.sh | ||
| 82 | +``` | ||
| 83 | + | ||
| 84 | +On Windows: | ||
| 85 | + | ||
| 86 | +```powershell | ||
| 87 | +powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 88 | +``` | ||
| 89 | + | ||
| 90 | +## Install | ||
| 91 | + | ||
| 92 | +Drop the binary into the node's plugin directory - no restart: | ||
| 93 | + | ||
| 94 | +```bash | ||
| 95 | +mkdir -p ~/.scorpiox/plugins | ||
| 96 | +cp plugin_opencode_login ~/.scorpiox/plugins/ | ||
| 97 | +~/.scorpiox/plugins/plugin_opencode_login --meta | ||
| 98 | +``` | ||
| 99 | + | ||
| 100 | +`scorpiox-bot-api` discovers it on the next `GET /plugins` and serves it at | ||
| 101 | +`/plugin_opencode_login`. BotMarket installs the prebuilt artifact for your | ||
| 102 | +platform in one click, or compiles it from the public mirror. | ||
| 103 | + | ||
| 104 | +## Tests | ||
| 105 | + | ||
| 106 | +`tests/run.sh` is fully offline: both CLIs are replaced by fixtures that emit | ||
| 107 | +the exact production contract shape, and the credential and marker paths point | ||
| 108 | +at throwaway files. It proves the metadata contract, the 401 gate, status | ||
| 109 | +parsing (live, expired, empty, missing, secondary location, pending, stale | ||
| 110 | +marker), the start/poll/cancel/refresh lifecycle, that no token ever surfaces, | ||
| 111 | +that the page has no CDN and no emoji, and that the source history carries no | ||
| 112 | +secret or internal address. Cross-target builds (musl, MinGW PE, aarch64) are | ||
| 113 | +checked when the toolchains are installed. | ||
| 114 | + | ||
| 115 | +```bash | ||
| 116 | +sh tests/run.sh | ||
| 117 | +``` | ||
| 118 | + | ||
| 119 | +## Release | ||
| 120 | + | ||
| 121 | +`release-dist.sh` runs the whole publish pipeline: full-history secret scan, | ||
| 122 | +multi-target build, `source.tar.gz`, `manifest.json` + `SHA256SUMS`, upload to | ||
| 123 | +`dist.scorpiox.net/bot-plugins/opencode-login/<version>/`, `latest.json` and | ||
| 124 | +the master `index.json` merge, and the one-way mirror push to | ||
| 125 | +`plugingit.scorpiox.net/scorpiox-bot-plugin-opencode-login.git`. | ||
| 126 | + | ||
| 127 | +The mirror push has three hard requirements, all measured the hard way: | ||
| 128 | +the push URL user must be the literal `token` | ||
| 129 | +(`https://token:<PAT>@plugingit.scorpiox.net/...`); a first release needs | ||
| 130 | +`POST /api?r=repos&name=<repo>` **with a request body** and the header | ||
| 131 | +`Authorization: token <PAT>`; and the push must run over HTTP/1.1 | ||
| 132 | +(`git -c http.version=HTTP/1.1 push`). | ||
| 133 | + | ||
| 134 | +## Never emit Content-Length | ||
| 135 | + | ||
| 136 | +The plugin writes `Content-Type`, `Cache-Control` and the security headers but | ||
| 137 | +deliberately never a `Content-Length`. The reverse proxy in front of the bot | ||
| 138 | +gets confused by a length that does not survive the CGI-to-HTTP rewrite and | ||
| 139 | +answers 502. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0573a29 | index 0000000..0573a29 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,34 @@ | @@ -0,0 +1,34 @@ | ||
| 1 | +# build.ps1 - build plugin_opencode_login.exe on a Windows box with MinGW-w64. | ||
| 2 | +# | ||
| 3 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 -Cc C:\gcc16\mingw64\bin\gcc.exe | ||
| 5 | +# | ||
| 6 | +# The generated page header (src/ui_html.h) is produced from src/ui.html by | ||
| 7 | +# tools/gen_ui.py. If python3 is not on the box, the checked-in header is used | ||
| 8 | +# as-is; the test suite is the place that proves the two agree. | ||
| 9 | + | ||
| 10 | +param( | ||
| 11 | + [string]$Cc = "x86_64-w64-mingw32-gcc", | ||
| 12 | + [string]$Out = "plugin_opencode_login.exe" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +$ErrorActionPreference = "Stop" | ||
| 16 | +$Root = Split-Path -Parent $MyInvocation.MyCommand.Path | ||
| 17 | +Set-Location $Root | ||
| 18 | + | ||
| 19 | +if (Get-Command python3 -ErrorAction SilentlyContinue) { | ||
| 20 | + python3 tools/gen_ui.py | ||
| 21 | +} elseif (Get-Command python -ErrorAction SilentlyContinue) { | ||
| 22 | + python tools/gen_ui.py | ||
| 23 | +} else { | ||
| 24 | + Write-Host "no python on this box - using the checked-in src/ui_html.h" | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +Write-Host "==> building $Out with $Cc" | ||
| 28 | +& $Cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -static -I src ` | ||
| 29 | + -o $Out src/plugin_opencode_login.c | ||
| 30 | +if ($LASTEXITCODE -ne 0) { throw "build failed ($LASTEXITCODE)" } | ||
| 31 | + | ||
| 32 | +Write-Host "==> --meta" | ||
| 33 | +& ".\$Out" --meta | ||
| 34 | +Write-Host "==> done: $Out" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..7289e36 | index 0000000..7289e36 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,17 @@ | @@ -0,0 +1,17 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "opencode-login", | ||
| 3 | + "id": "plugin_opencode_login", | ||
| 4 | + "name": "opencode", | ||
| 5 | + "desc": "OpenCode login", | ||
| 6 | + "title": "OpenCode Login", | ||
| 7 | + "summary": "Device code login and account token manager for OpenCode on this node. Starts the SXLOGIN-MACHINE-V1 device flow through the node's own login CLI, shows the one-time user code, polls for approval without blocking, cancels a half-finished flow, and re-reads the stored token on demand. It reports presence and expiry of credentials only and never prints, logs or returns a token value.", | ||
| 8 | + "category": "devtools", | ||
| 9 | + "license": "MIT", | ||
| 10 | + "capabilities": [ | ||
| 11 | + "credentials_read", | ||
| 12 | + "oauth_device_flow" | ||
| 13 | + ], | ||
| 14 | + "trust_notice": "Executes native C code on your node. It runs scorpiox-opencode-login and scorpiox-opencode-fetchtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to the provider over TLS. This plugin itself opens no socket and carries no secret. It reads only ~/.config/opencode/auth.json, ~/.opencode/token.json, ~/.claude/.login-pending/opencode-default.json and ~/.claude/scorpiox-env/superopencode.txt, and every response reports token presence and expiry only - never a token value. Credentials are saved locally and never leave your node.", | ||
| 15 | + "author": "SCORPIOX INC", | ||
| 16 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-opencode-login" | ||
| 17 | +} |
| 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..8dc72be | index 0000000..8dc72be | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_opencode_login.c | +++ b/src/plugin_opencode_login.c | ||
| @@ -0,0 +1,1340 @@ | @@ -0,0 +1,1340 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_opencode_login - SCORPIOX BOT open-source OpenCode device-code login | ||
| 3 | + * and account 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 in this binary): the OpenCode device flow | ||
| 11 | + * is a sequence of HTTPS POSTs to the provider, and a public clean-room | ||
| 12 | + * repository must not carry a client secret or a vendored TLS stack. So this | ||
| 13 | + * plugin does not speak TLS at all. It drives the node's own login CLI, exactly | ||
| 14 | + * the way the SCORPIOX CODE login tools are meant to be driven (the machine | ||
| 15 | + * mode contract: --status / --start / --poll / --cancel, one JSON line per | ||
| 16 | + * call), and it reads the credential file that the CLI writes: | ||
| 17 | + * | ||
| 18 | + * ~/.config/opencode/auth.json (access + refresh token) | ||
| 19 | + * ~/.claude/.login-pending/opencode-default.json (pending device flow) | ||
| 20 | + * ~/.claude/scorpiox-env/superopencode.txt (the profile the CLI creates) | ||
| 21 | + * | ||
| 22 | + * Every one of those paths and both CLIs can be overridden for deterministic | ||
| 23 | + * offline testing: | ||
| 24 | + * | ||
| 25 | + * OPENCODE_CREDS_PATH the credential json (default ~/.config/opencode/auth.json) | ||
| 26 | + * OPENCODE_PENDING_PATH the pending-flow marker | ||
| 27 | + * OPENCODE_LOGIN_BIN the login CLI (default scorpiox-opencode-login) | ||
| 28 | + * OPENCODE_TOKEN_BIN the token CLI (default scorpiox-opencode-fetchtoken) | ||
| 29 | + * OPENCODE_ENV_DIR the profile dir (default ~/.claude/scorpiox-env) | ||
| 30 | + * | ||
| 31 | + * No token is ever printed, logged or returned by this plugin: the API reports | ||
| 32 | + * presence and expiry only, and the refresh action reports success or the | ||
| 33 | + * failure reason from the token CLI with the payload discarded. | ||
| 34 | + * | ||
| 35 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 36 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 37 | + * scorpiox-server on the node. | ||
| 38 | + * | ||
| 39 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 40 | + */ | ||
| 41 | + | ||
| 42 | +/* Must come before every include on Windows: MinGW defaults to 0x502 | ||
| 43 | + * (Server 2003), which hides the Win7+ APIs and the path helpers. */ | ||
| 44 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 45 | +# define _WIN32_WINNT 0x0601 | ||
| 46 | +#endif | ||
| 47 | + | ||
| 48 | +#if !defined(_WIN32) | ||
| 49 | +# define _POSIX_C_SOURCE 200809L | ||
| 50 | +# define _DEFAULT_SOURCE 1 | ||
| 51 | +# if defined(__APPLE__) | ||
| 52 | +# define _DARWIN_C_SOURCE 1 | ||
| 53 | +# endif | ||
| 54 | +#endif | ||
| 55 | + | ||
| 56 | +#include <stdio.h> | ||
| 57 | +#include <stdlib.h> | ||
| 58 | +#include <string.h> | ||
| 59 | +#include <ctype.h> | ||
| 60 | +#include <errno.h> | ||
| 61 | +#include <time.h> | ||
| 62 | +#include <stdarg.h> | ||
| 63 | + | ||
| 64 | +#if defined(_WIN32) | ||
| 65 | +# define WIN32_LEAN_AND_MEAN | ||
| 66 | +# include <windows.h> | ||
| 67 | +# include <direct.h> | ||
| 68 | +# include <io.h> | ||
| 69 | +#else | ||
| 70 | +# include <unistd.h> | ||
| 71 | +# include <sys/stat.h> | ||
| 72 | +# include <sys/types.h> | ||
| 73 | +#endif | ||
| 74 | + | ||
| 75 | +#include "bot_theme_plugin.h" | ||
| 76 | +#include "ui_html.h" | ||
| 77 | + | ||
| 78 | +#define PLUGIN_SLUG "opencode-login" | ||
| 79 | +#define PLUGIN_ID "plugin_opencode_login" | ||
| 80 | +#define PLUGIN_VER "1.0.0" | ||
| 81 | +#define PLUGIN_NAME "opencode" | ||
| 82 | +#define PLUGIN_DESC "OpenCode login" | ||
| 83 | + | ||
| 84 | +#define PATH_SZ 1024 | ||
| 85 | +#define LABEL_SZ 256 | ||
| 86 | +#define ORG_SZ 256 | ||
| 87 | +#define CODE_SZ 64 | ||
| 88 | +#define URL_SZ 1024 | ||
| 89 | +#define CMD_SZ 4096 | ||
| 90 | +#define OUT_MAX (256 * 1024) | ||
| 91 | +#define FIELD_SZ 512 | ||
| 92 | + | ||
| 93 | +#define DEFAULT_LOGIN_BIN "scorpiox-opencode-login" | ||
| 94 | +#define DEFAULT_TOKEN_BIN "scorpiox-opencode-fetchtoken" | ||
| 95 | + | ||
| 96 | +/* The device-flow marker the login CLI writes and removes. Its TTL matches the | ||
| 97 | + * CLI's own (900 s); the plugin only uses it to decide whether the UI should | ||
| 98 | + * show a live polling indicator, never to authorise anything. */ | ||
| 99 | +#define PENDING_TTL_SEC 900 | ||
| 100 | + | ||
| 101 | +/* ------------------------------------------------------------------ */ | ||
| 102 | +/* Growable byte buffer */ | ||
| 103 | +/* ------------------------------------------------------------------ */ | ||
| 104 | + | ||
| 105 | +typedef struct { | ||
| 106 | + char *p; | ||
| 107 | + size_t n; | ||
| 108 | + size_t cap; | ||
| 109 | +} buf_t; | ||
| 110 | + | ||
| 111 | +static void buf_init(buf_t *b) | ||
| 112 | +{ | ||
| 113 | + b->p = NULL; | ||
| 114 | + b->n = 0; | ||
| 115 | + b->cap = 0; | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +static int buf_need(buf_t *b, size_t extra) | ||
| 119 | +{ | ||
| 120 | + size_t want = b->n + extra + 1; | ||
| 121 | + char *np; | ||
| 122 | + | ||
| 123 | + if (want <= b->cap) return 1; | ||
| 124 | + if (b->cap == 0) b->cap = 1024; | ||
| 125 | + while (b->cap < want) { | ||
| 126 | + if (b->cap > (size_t)32 * 1024 * 1024) return 0; | ||
| 127 | + b->cap *= 2; | ||
| 128 | + } | ||
| 129 | + np = (char *)realloc(b->p, b->cap); | ||
| 130 | + if (!np) return 0; | ||
| 131 | + b->p = np; | ||
| 132 | + return 1; | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +static int buf_addc(buf_t *b, char c) | ||
| 136 | +{ | ||
| 137 | + if (!buf_need(b, 1)) return 0; | ||
| 138 | + b->p[b->n++] = c; | ||
| 139 | + b->p[b->n] = '\0'; | ||
| 140 | + return 1; | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +static int buf_adds(buf_t *b, const char *s) | ||
| 144 | +{ | ||
| 145 | + size_t len; | ||
| 146 | + if (!s) return 1; | ||
| 147 | + len = strlen(s); | ||
| 148 | + if (!buf_need(b, len)) return 0; | ||
| 149 | + memcpy(b->p + b->n, s, len); | ||
| 150 | + b->n += len; | ||
| 151 | + b->p[b->n] = '\0'; | ||
| 152 | + return 1; | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +static int buf_addf(buf_t *b, const char *fmt, ...) | ||
| 156 | +{ | ||
| 157 | + char tmp[2048]; | ||
| 158 | + va_list ap; | ||
| 159 | + int n; | ||
| 160 | + | ||
| 161 | + va_start(ap, fmt); | ||
| 162 | + n = vsnprintf(tmp, sizeof(tmp), fmt, ap); | ||
| 163 | + va_end(ap); | ||
| 164 | + if (n < 0) return 0; | ||
| 165 | + if ((size_t)n >= sizeof(tmp)) n = (int)sizeof(tmp) - 1; | ||
| 166 | + return buf_adds(b, tmp); | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/* Append s as a JSON string literal (escapes control characters). */ | ||
| 170 | +static int buf_json(buf_t *b, const char *s) | ||
| 171 | +{ | ||
| 172 | + if (!buf_addc(b, '"')) return 0; | ||
| 173 | + for (; s && *s; s++) { | ||
| 174 | + unsigned char c = (unsigned char)*s; | ||
| 175 | + switch (c) { | ||
| 176 | + case '"': if (!buf_adds(b, "\\\"")) return 0; continue; | ||
| 177 | + case '\\': if (!buf_adds(b, "\\\\")) return 0; continue; | ||
| 178 | + case '\n': if (!buf_adds(b, "\\n")) return 0; continue; | ||
| 179 | + case '\r': if (!buf_adds(b, "\\r")) return 0; continue; | ||
| 180 | + case '\t': if (!buf_adds(b, "\\t")) return 0; continue; | ||
| 181 | + default: break; | ||
| 182 | + } | ||
| 183 | + if (c < 0x20) { if (!buf_addf(b, "\\u%04x", c)) return 0; } | ||
| 184 | + else if (!buf_addc(b, (char)c)) return 0; | ||
| 185 | + } | ||
| 186 | + return buf_addc(b, '"'); | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +static const char *buf_str(buf_t *b) | ||
| 190 | +{ | ||
| 191 | + if (!b->p) return ""; | ||
| 192 | + return b->p; | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +static void buf_free(buf_t *b) | ||
| 196 | +{ | ||
| 197 | + free(b->p); | ||
| 198 | + b->p = NULL; | ||
| 199 | + b->n = 0; | ||
| 200 | + b->cap = 0; | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +/* ------------------------------------------------------------------ */ | ||
| 204 | +/* Query string */ | ||
| 205 | +/* ------------------------------------------------------------------ */ | ||
| 206 | + | ||
| 207 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 208 | +{ | ||
| 209 | + size_t klen; | ||
| 210 | + const char *p; | ||
| 211 | + | ||
| 212 | + if (!out || outsz == 0) return 0; | ||
| 213 | + out[0] = '\0'; | ||
| 214 | + if (!qs || !key) return 0; | ||
| 215 | + klen = strlen(key); | ||
| 216 | + p = qs; | ||
| 217 | + while (*p) { | ||
| 218 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 219 | + size_t i = 0; | ||
| 220 | + p += klen + 1; | ||
| 221 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | ||
| 222 | + out[i] = '\0'; | ||
| 223 | + return 1; | ||
| 224 | + } | ||
| 225 | + p = strchr(p, '&'); | ||
| 226 | + if (!p) break; | ||
| 227 | + p++; | ||
| 228 | + } | ||
| 229 | + return 0; | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +static int query_has(const char *qs, const char *key) | ||
| 233 | +{ | ||
| 234 | + size_t klen = strlen(key); | ||
| 235 | + const char *p = qs; | ||
| 236 | + | ||
| 237 | + while (p && *p) { | ||
| 238 | + if (strncmp(p, key, klen) == 0 && | ||
| 239 | + (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) | ||
| 240 | + return 1; | ||
| 241 | + p = strchr(p, '&'); | ||
| 242 | + if (!p) break; | ||
| 243 | + p++; | ||
| 244 | + } | ||
| 245 | + return 0; | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | + | ||
| 249 | +/* ------------------------------------------------------------------ */ | ||
| 250 | +/* Node auth (X-Bot-Password / Bearer / ?pwd=) */ | ||
| 251 | +/* ------------------------------------------------------------------ */ | ||
| 252 | + | ||
| 253 | +static void require_node_auth(void) | ||
| 254 | +{ | ||
| 255 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 256 | + const char *xp; | ||
| 257 | + const char *auth; | ||
| 258 | + char qpwd[256] = {0}; | ||
| 259 | + | ||
| 260 | + if (!np || !*np) return; | ||
| 261 | + | ||
| 262 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 263 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 264 | + | ||
| 265 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 266 | + if (auth) { | ||
| 267 | + while (*auth == ' ') auth++; | ||
| 268 | + if (strncasecmp(auth, "Bearer ", 7) == 0) { | ||
| 269 | + auth += 7; | ||
| 270 | + while (*auth == ' ') auth++; | ||
| 271 | + if (strcmp(auth, np) == 0) return; | ||
| 272 | + } | ||
| 273 | + } | ||
| 274 | + | ||
| 275 | + if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && | ||
| 276 | + strcmp(qpwd, np) == 0) return; | ||
| 277 | + | ||
| 278 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 279 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 280 | + "Cache-Control: no-store\r\n\r\n" | ||
| 281 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 282 | + exit(0); | ||
| 283 | +} | ||
| 284 | + | ||
| 285 | +/* ------------------------------------------------------------------ */ | ||
| 286 | +/* Paths */ | ||
| 287 | +/* ------------------------------------------------------------------ */ | ||
| 288 | + | ||
| 289 | +static const char *home_dir(void) | ||
| 290 | +{ | ||
| 291 | +#ifdef _WIN32 | ||
| 292 | + static char home[512]; | ||
| 293 | + DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); | ||
| 294 | + if (n > 0 && n < sizeof(home)) return home; | ||
| 295 | + home[0] = '\0'; | ||
| 296 | + if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) { | ||
| 297 | + char tmp[512]; | ||
| 298 | + if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { | ||
| 299 | + strncat(home, tmp, sizeof(home) - strlen(home) - 1); | ||
| 300 | + return home; | ||
| 301 | + } | ||
| 302 | + } | ||
| 303 | + return NULL; | ||
| 304 | +#else | ||
| 305 | + const char *h = getenv("HOME"); | ||
| 306 | + return (h && *h) ? h : NULL; | ||
| 307 | +#endif | ||
| 308 | +} | ||
| 309 | + | ||
| 310 | +#if defined(_WIN32) | ||
| 311 | +# define PATH_SEP '\\' | ||
| 312 | +#else | ||
| 313 | +# define PATH_SEP '/' | ||
| 314 | +#endif | ||
| 315 | + | ||
| 316 | +/* Credential json: OPENCODE_CREDS_PATH, else ~/.config/opencode/auth.json - | ||
| 317 | + * the file the login CLI actually writes. ~/.opencode/token.json is probed as a | ||
| 318 | + * secondary location so a relocated or hand-written install is still seen. */ | ||
| 319 | +static void creds_path(char *out, size_t n) | ||
| 320 | +{ | ||
| 321 | + const char *env = getenv("OPENCODE_CREDS_PATH"); | ||
| 322 | + const char *home = home_dir(); | ||
| 323 | + | ||
| 324 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 325 | + if (!home) { snprintf(out, n, "auth.json"); return; } | ||
| 326 | + snprintf(out, n, "%s%c.config%copencode%cauth.json", | ||
| 327 | + home, PATH_SEP, PATH_SEP, PATH_SEP); | ||
| 328 | +} | ||
| 329 | + | ||
| 330 | +/* The secondary, spec-named location (only consulted when the primary is | ||
| 331 | + * absent, so a normal install never pays for it). */ | ||
| 332 | +static int creds_path_alt(char *out, size_t n) | ||
| 333 | +{ | ||
| 334 | + const char *home = home_dir(); | ||
| 335 | + | ||
| 336 | + if (getenv("OPENCODE_CREDS_PATH")) return 0; /* override wins outright */ | ||
| 337 | + if (!home) return 0; | ||
| 338 | + snprintf(out, n, "%s%c.opencode%ctoken.json", home, PATH_SEP, PATH_SEP); | ||
| 339 | + return 1; | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +/* The pending device-flow marker written by the login CLI. */ | ||
| 343 | +static void pending_path(char *out, size_t n) | ||
| 344 | +{ | ||
| 345 | + const char *env = getenv("OPENCODE_PENDING_PATH"); | ||
| 346 | + const char *home = home_dir(); | ||
| 347 | + | ||
| 348 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 349 | + if (!home) { snprintf(out, n, "opencode-default.json"); return; } | ||
| 350 | + snprintf(out, n, "%s%c.claude%c.login-pending%copencode-default.json", | ||
| 351 | + home, PATH_SEP, PATH_SEP, PATH_SEP); | ||
| 352 | +} | ||
| 353 | + | ||
| 354 | +static void env_dir(char *out, size_t n) | ||
| 355 | +{ | ||
| 356 | + const char *env = getenv("OPENCODE_ENV_DIR"); | ||
| 357 | + const char *creds = getenv("OPENCODE_CREDS_PATH"); | ||
| 358 | + const char *home = home_dir(); | ||
| 359 | + | ||
| 360 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 361 | + | ||
| 362 | + /* A relocated credential file implies a relocated profile: they are written | ||
| 363 | + * by the same CLI into the same tree, and reading one from the default home | ||
| 364 | + * while the other is overridden makes status report a missing profile for a | ||
| 365 | + * session that has one. */ | ||
| 366 | + if (creds && *creds) { | ||
| 367 | + char base[PATH_SZ]; | ||
| 368 | + char *slash; | ||
| 369 | + snprintf(base, sizeof(base), "%s", creds); | ||
| 370 | + slash = strrchr(base, PATH_SEP); | ||
| 371 | + if (!slash) slash = strrchr(base, '/'); | ||
| 372 | + if (slash) { | ||
| 373 | + *(slash + 1) = '\0'; | ||
| 374 | + if (strlen(base) + 16 < n) { snprintf(out, n, "%sscorpiox-env", base); return; } | ||
| 375 | + } | ||
| 376 | + } | ||
| 377 | + | ||
| 378 | + if (!home) { snprintf(out, n, "."); return; } | ||
| 379 | + snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +static void profile_path(char *out, size_t n) | ||
| 383 | +{ | ||
| 384 | + char d[PATH_SZ]; | ||
| 385 | + | ||
| 386 | + env_dir(d, sizeof(d)); | ||
| 387 | + /* Copy with explicit bounds so a long directory cannot have its tail | ||
| 388 | + * replaced by the filename (snprintf would silently truncate). */ | ||
| 389 | + { | ||
| 390 | + const char *name = "superopencode.txt"; | ||
| 391 | + size_t dl = strlen(d); | ||
| 392 | + if (dl + 1 + strlen(name) >= n) { snprintf(out, n, "%s", name); return; } | ||
| 393 | + memcpy(out, d, dl); | ||
| 394 | + out[dl] = PATH_SEP; | ||
| 395 | + memcpy(out + dl + 1, name, strlen(name) + 1); | ||
| 396 | + } | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +static const char *login_bin(void) | ||
| 400 | +{ | ||
| 401 | + const char *b = getenv("OPENCODE_LOGIN_BIN"); | ||
| 402 | + return (b && *b) ? b : DEFAULT_LOGIN_BIN; | ||
| 403 | +} | ||
| 404 | + | ||
| 405 | +static const char *token_bin(void) | ||
| 406 | +{ | ||
| 407 | + const char *b = getenv("OPENCODE_TOKEN_BIN"); | ||
| 408 | + return (b && *b) ? b : DEFAULT_TOKEN_BIN; | ||
| 409 | +} | ||
| 410 | + | ||
| 411 | +static int file_exists(const char *p) | ||
| 412 | +{ | ||
| 413 | +#if defined(_WIN32) | ||
| 414 | + DWORD a = GetFileAttributesA(p); | ||
| 415 | + return (a != (DWORD)-1); | ||
| 416 | +#else | ||
| 417 | + struct stat st; | ||
| 418 | + return p && *p && stat(p, &st) == 0; | ||
| 419 | +#endif | ||
| 420 | +} | ||
| 421 | + | ||
| 422 | +/* Whole-file read; NULL on any failure. Caller frees. */ | ||
| 423 | +static char *read_file(const char *path) | ||
| 424 | +{ | ||
| 425 | + FILE *f; | ||
| 426 | + long sz; | ||
| 427 | + char *buf; | ||
| 428 | + | ||
| 429 | + if (!path || !*path) return NULL; | ||
| 430 | + f = fopen(path, "rb"); | ||
| 431 | + if (!f) return NULL; | ||
| 432 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } | ||
| 433 | + sz = ftell(f); | ||
| 434 | + if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } | ||
| 435 | + if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } | ||
| 436 | + buf = (char *)malloc((size_t)sz + 1); | ||
| 437 | + if (!buf) { fclose(f); return NULL; } | ||
| 438 | + if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { | ||
| 439 | + free(buf); | ||
| 440 | + fclose(f); | ||
| 441 | + return NULL; | ||
| 442 | + } | ||
| 443 | + buf[sz] = '\0'; | ||
| 444 | + fclose(f); | ||
| 445 | + return buf; | ||
| 446 | +} | ||
| 447 | + | ||
| 448 | +/* Trim trailing CR/LF/space in place. */ | ||
| 449 | +static void trim_tail(char *s) | ||
| 450 | +{ | ||
| 451 | + size_t n; | ||
| 452 | + if (!s) return; | ||
| 453 | + n = strlen(s); | ||
| 454 | + while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || | ||
| 455 | + s[n - 1] == ' ' || s[n - 1] == '\t')) | ||
| 456 | + s[--n] = '\0'; | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +/* ------------------------------------------------------------------ */ | ||
| 460 | +/* Minimal JSON field readers */ | ||
| 461 | +/* ------------------------------------------------------------------ */ | ||
| 462 | + | ||
| 463 | +/* Copy a JSON string value that starts at *pp (which points at the opening | ||
| 464 | + * quote). Advances *pp past the closing quote. */ | ||
| 465 | +static int json_read_string_at(const char **pp, char *out, size_t outsz) | ||
| 466 | +{ | ||
| 467 | + const char *p = *pp; | ||
| 468 | + size_t i = 0; | ||
| 469 | + | ||
| 470 | + if (!p || *p != '"') return 0; | ||
| 471 | + p++; | ||
| 472 | + while (*p && *p != '"') { | ||
| 473 | + char c = *p; | ||
| 474 | + if (c == '\\' && p[1]) { | ||
| 475 | + p++; | ||
| 476 | + switch (*p) { | ||
| 477 | + case 'n': c = '\n'; break; | ||
| 478 | + case 'r': c = '\r'; break; | ||
| 479 | + case 't': c = '\t'; break; | ||
| 480 | + case 'b': c = '\b'; break; | ||
| 481 | + case 'f': c = '\f'; break; | ||
| 482 | + case 'u': { | ||
| 483 | + unsigned int v = 0; | ||
| 484 | + int k; | ||
| 485 | + p++; | ||
| 486 | + for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) | ||
| 487 | + v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) | ||
| 488 | + ? *p - '0' | ||
| 489 | + : tolower((unsigned char)*p) - 'a' + 10); | ||
| 490 | + if (i + 1 < outsz) out[i++] = (char)(v & 0xff); | ||
| 491 | + continue; | ||
| 492 | + } | ||
| 493 | + default: c = *p; break; | ||
| 494 | + } | ||
| 495 | + p++; | ||
| 496 | + } else { | ||
| 497 | + p++; | ||
| 498 | + } | ||
| 499 | + if (i + 1 < outsz) out[i++] = c; | ||
| 500 | + } | ||
| 501 | + if (*p == '"') p++; | ||
| 502 | + if (outsz) out[i < outsz ? i : outsz - 1] = '\0'; | ||
| 503 | + *pp = p; | ||
| 504 | + return 1; | ||
| 505 | +} | ||
| 506 | + | ||
| 507 | + | ||
| 508 | +/* Find "key":<value> anywhere inside the slice [obj, end) and return the | ||
| 509 | + * value pointer. Only top-level keys of that slice are considered: a nested | ||
| 510 | + * object is skipped as a whole. */ | ||
| 511 | +static const char *json_find_key(const char *obj, const char *end, const char *key) | ||
| 512 | +{ | ||
| 513 | + size_t klen = strlen(key); | ||
| 514 | + const char *p = obj; | ||
| 515 | + int depth = 0; | ||
| 516 | + | ||
| 517 | + if (!obj || !end || !key) return NULL; | ||
| 518 | + /* A caller almost always hands us the whole object, i.e. a pointer at the | ||
| 519 | + * opening '{'. Skipping it here keeps every call site free of the "+1" | ||
| 520 | + * that is easy to forget and silent when it is missing. */ | ||
| 521 | + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; | ||
| 522 | + if (p < end && *p == '{') p++; | ||
| 523 | + | ||
| 524 | + while (p && p < end) { | ||
| 525 | + if (*p == '"') { | ||
| 526 | + char name[128]; | ||
| 527 | + json_read_string_at(&p, name, sizeof(name)); | ||
| 528 | + if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { | ||
| 529 | + const char *q = p; | ||
| 530 | + while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; | ||
| 531 | + if (q < end && *q == ':') { | ||
| 532 | + q++; | ||
| 533 | + while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; | ||
| 534 | + return (q < end) ? q : NULL; | ||
| 535 | + } | ||
| 536 | + } | ||
| 537 | + continue; | ||
| 538 | + } | ||
| 539 | + if (*p == '{' || *p == '[') depth++; | ||
| 540 | + else if (*p == '}' || *p == ']') depth--; | ||
| 541 | + p++; | ||
| 542 | + } | ||
| 543 | + return NULL; | ||
| 544 | +} | ||
| 545 | + | ||
| 546 | +/* Returns 0 and leaves *out untouched when the key is absent or null. That | ||
| 547 | + * matters: several callers pass a field of a longer-lived struct, and clearing | ||
| 548 | + * it on a miss silently erases a value that was already correct. */ | ||
| 549 | +static int json_str_field(const char *obj, const char *end, const char *key, | ||
| 550 | + char *out, size_t outsz) | ||
| 551 | +{ | ||
| 552 | + const char *v; | ||
| 553 | + | ||
| 554 | + if (!out || outsz == 0) return 0; | ||
| 555 | + v = json_find_key(obj, end, key); | ||
| 556 | + if (!v || *v == 'n') return 0; | ||
| 557 | + out[0] = '\0'; | ||
| 558 | + if (*v == '"') return json_read_string_at(&v, out, outsz); | ||
| 559 | + { | ||
| 560 | + size_t i = 0; | ||
| 561 | + while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; | ||
| 562 | + out[i] = '\0'; | ||
| 563 | + trim_tail(out); | ||
| 564 | + return out[0] ? 1 : 0; | ||
| 565 | + } | ||
| 566 | +} | ||
| 567 | + | ||
| 568 | +static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) | ||
| 569 | +{ | ||
| 570 | + const char *v = json_find_key(obj, end, key); | ||
| 571 | + | ||
| 572 | + if (!v) return dflt; | ||
| 573 | + if (strncmp(v, "true", 4) == 0) return 1; | ||
| 574 | + if (strncmp(v, "false", 5) == 0) return 0; | ||
| 575 | + if (*v == '"') { | ||
| 576 | + if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1; | ||
| 577 | + return 0; | ||
| 578 | + } | ||
| 579 | + if (*v == '1') return 1; | ||
| 580 | + return 0; | ||
| 581 | +} | ||
| 582 | + | ||
| 583 | +static long long json_num_field(const char *obj, const char *end, const char *key) | ||
| 584 | +{ | ||
| 585 | + const char *v = json_find_key(obj, end, key); | ||
| 586 | + long long vll = 0; | ||
| 587 | + int neg = 0; | ||
| 588 | + | ||
| 589 | + if (!v) return 0; | ||
| 590 | + if (*v == '"') v++; | ||
| 591 | + if (*v == '-') { neg = 1; v++; } | ||
| 592 | + while (isdigit((unsigned char)*v)) { vll = vll * 10 + (*v++ - '0'); } | ||
| 593 | + return neg ? -vll : vll; | ||
| 594 | +} | ||
| 595 | + | ||
| 596 | +/* True when the object contains a non-empty string under key. Used for token | ||
| 597 | + * presence without ever copying the token itself into a wider buffer. */ | ||
| 598 | +static int json_str_present(const char *obj, const char *end, const char *key) | ||
| 599 | +{ | ||
| 600 | + const char *v = json_find_key(obj, end, key); | ||
| 601 | + const char *q; | ||
| 602 | + | ||
| 603 | + if (!v) return 0; | ||
| 604 | + if (*v != '"') return 0; | ||
| 605 | + q = v + 1; | ||
| 606 | + while (*q && *q != '"') { | ||
| 607 | + if (*q == '\\' && q[1]) { q += 2; continue; } | ||
| 608 | + return 1; /* at least one real character */ | ||
| 609 | + } | ||
| 610 | + return 0; /* "" - present but empty */ | ||
| 611 | +} | ||
| 612 | + | ||
| 613 | +/* ------------------------------------------------------------------ */ | ||
| 614 | +/* Running the node's login CLI */ | ||
| 615 | +/* ------------------------------------------------------------------ */ | ||
| 616 | + | ||
| 617 | +/* Wrap a string in single quotes for the shell, so a path or a binary name | ||
| 618 | + * containing spaces or punctuation cannot break the command line. */ | ||
| 619 | +static void shell_quote_into(const char *in, char *out, size_t outsz) | ||
| 620 | +{ | ||
| 621 | + size_t o = 0; | ||
| 622 | + const char *p; | ||
| 623 | + | ||
| 624 | + if (outsz < 3) { if (outsz) out[0] = '\0'; return; } | ||
| 625 | + out[o++] = '\''; | ||
| 626 | + for (p = in; p && *p; p++) { | ||
| 627 | + if (*p == '\'') { | ||
| 628 | + if (o + 5 >= outsz) break; | ||
| 629 | + memcpy(out + o, "'\\''", 4); | ||
| 630 | + o += 4; | ||
| 631 | + } else { | ||
| 632 | + if (o + 2 >= outsz) break; | ||
| 633 | + out[o++] = *p; | ||
| 634 | + } | ||
| 635 | + } | ||
| 636 | + out[o++] = '\''; | ||
| 637 | + out[o] = '\0'; | ||
| 638 | +} | ||
| 639 | + | ||
| 640 | +/* Run `<bin> <args>` and capture stdout. args may be NULL or a pre-built | ||
| 641 | + * shell fragment. Returns 1 when the process ran, -1 when the binary was not | ||
| 642 | + * found, 0 when popen itself failed. The captured text is stored in out. */ | ||
| 643 | +static int run_capture(const char *bin, const char *args, buf_t *out) | ||
| 644 | +{ | ||
| 645 | + char cmd[CMD_SZ]; | ||
| 646 | + char qbin[FIELD_SZ]; | ||
| 647 | + FILE *f; | ||
| 648 | + char line[2048]; | ||
| 649 | + size_t total = 0; | ||
| 650 | + int rc; | ||
| 651 | + | ||
| 652 | + if (!bin || !*bin) return 0; | ||
| 653 | + shell_quote_into(bin, qbin, sizeof(qbin)); | ||
| 654 | + if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); | ||
| 655 | + else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); | ||
| 656 | + | ||
| 657 | + f = popen(cmd, "r"); | ||
| 658 | + if (!f) return 0; | ||
| 659 | + while (fgets(line, sizeof(line), f)) { | ||
| 660 | + total += strlen(line); | ||
| 661 | + if (total > OUT_MAX) break; | ||
| 662 | + buf_adds(out, line); | ||
| 663 | + } | ||
| 664 | + rc = pclose(f); | ||
| 665 | + | ||
| 666 | + if (out->p) { | ||
| 667 | + /* the CLIs print one JSON line last; strip surrounding whitespace */ | ||
| 668 | + size_t n = out->n; | ||
| 669 | + while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; | ||
| 670 | + out->n = n; | ||
| 671 | + } | ||
| 672 | + /* pclose() hands back a wait status, not an exit code: "command not | ||
| 673 | + * found" arrives as 32512 (127 << 8). Callers treat that as "the CLI is | ||
| 674 | + * not on this node", which is a different message from "the CLI ran and | ||
| 675 | + * failed". Any other status is the CLI's own and is left to the JSON it | ||
| 676 | + * printed. */ | ||
| 677 | + if (rc != -1 && (rc >> 8) == 127) return -1; | ||
| 678 | + return 1; | ||
| 679 | +} | ||
| 680 | + | ||
| 681 | +/* The login CLI prints human progress on stdout before the final JSON line, | ||
| 682 | + * so take the LAST line that starts with '{'. */ | ||
| 683 | +static const char *last_json_line(buf_t *b) | ||
| 684 | +{ | ||
| 685 | + size_t i; | ||
| 686 | + const char *last = NULL; | ||
| 687 | + | ||
| 688 | + if (!b || !b->p) return NULL; | ||
| 689 | + for (i = 0; i < b->n; i++) { | ||
| 690 | + int at_line_start = (i == 0) || b->p[i - 1] == '\n'; | ||
| 691 | + if (at_line_start && b->p[i] == '{') last = b->p + i; | ||
| 692 | + } | ||
| 693 | + return last; | ||
| 694 | +} | ||
| 695 | + | ||
| 696 | +/* ------------------------------------------------------------------ */ | ||
| 697 | +/* Status model */ | ||
| 698 | +/* ------------------------------------------------------------------ */ | ||
| 699 | + | ||
| 700 | +typedef struct { | ||
| 701 | + char path[PATH_SZ]; | ||
| 702 | + char account[LABEL_SZ]; | ||
| 703 | + char org[ORG_SZ]; | ||
| 704 | + char profile[LABEL_SZ]; | ||
| 705 | + long long expires_at; /* unix seconds, 0 = unknown */ | ||
| 706 | + int logged_in; | ||
| 707 | + int has_refresh; | ||
| 708 | + int expired; | ||
| 709 | + int pending; | ||
| 710 | + long long pending_age; /* seconds since the marker was written, -1 unknown */ | ||
| 711 | + int profile_exists; | ||
| 712 | + int cli_present; /* 1 when the login CLI ran at all this call */ | ||
| 713 | + int cli_pending_unknown;/* 1 when no marker file exists to TTL-check */ | ||
| 714 | + int cli_ok; /* 1 when the login CLI answered with ok:true */ | ||
| 715 | + int token_bin_present; | ||
| 716 | + char cli_error[FIELD_SZ]; | ||
| 717 | +} status_t; | ||
| 718 | + | ||
| 719 | +/* Normalise an expiry to unix SECONDS. The credential file stores seconds | ||
| 720 | + * (time(NULL) + expires_in); the machine-mode status reports milliseconds. | ||
| 721 | + * A value above 1e11 can only be milliseconds on any realistic date. */ | ||
| 722 | +static long long normalise_expiry(long long v) | ||
| 723 | +{ | ||
| 724 | + if (v <= 0) return 0; | ||
| 725 | + if (v > 100000000000LL) return v / 1000; | ||
| 726 | + return v; | ||
| 727 | +} | ||
| 728 | + | ||
| 729 | +static void collect_status(status_t *st) | ||
| 730 | +{ | ||
| 731 | + char alt[PATH_SZ]; | ||
| 732 | + char *raw; | ||
| 733 | + const char *end; | ||
| 734 | + long long now = (long long)time(NULL); | ||
| 735 | + | ||
| 736 | + memset(st, 0, sizeof(*st)); | ||
| 737 | + snprintf(st->profile, sizeof(st->profile), "superopencode"); | ||
| 738 | + st->pending_age = -1; | ||
| 739 | + | ||
| 740 | + /* 1. the credential file the CLI writes */ | ||
| 741 | + creds_path(st->path, sizeof(st->path)); | ||
| 742 | + raw = read_file(st->path); | ||
| 743 | + if (!raw && creds_path_alt(alt, sizeof(alt)) && file_exists(alt)) { | ||
| 744 | + free(raw); | ||
| 745 | + raw = read_file(alt); | ||
| 746 | + if (raw) snprintf(st->path, sizeof(st->path), "%s", alt); | ||
| 747 | + } | ||
| 748 | + if (raw) { | ||
| 749 | + end = raw + strlen(raw); | ||
| 750 | + st->logged_in = json_str_present(raw, end, "access_token"); | ||
| 751 | + st->has_refresh = json_str_present(raw, end, "refresh_token"); | ||
| 752 | + st->expires_at = normalise_expiry(json_num_field(raw, end, "expires_at")); | ||
| 753 | + if (!st->expires_at) { | ||
| 754 | + long long ein = json_num_field(raw, end, "expires_in"); | ||
| 755 | + if (ein > 0) st->expires_at = now + ein; | ||
| 756 | + } | ||
| 757 | + if (json_str_field(raw, end, "org_id", st->org, sizeof(st->org))) | ||
| 758 | + snprintf(st->account, sizeof(st->account), "%s", st->org); | ||
| 759 | + free(raw); | ||
| 760 | + } | ||
| 761 | + st->expired = (st->expires_at > 0 && st->expires_at < now); | ||
| 762 | + | ||
| 763 | + /* 2. the pending device-flow marker, owned by the CLI but reported here. | ||
| 764 | + * The marker is the only evidence the plugin can check without a | ||
| 765 | + * network, and it carries the CLI's own creation stamp, so the TTL is | ||
| 766 | + * applied here rather than trusting a later claim. */ | ||
| 767 | + { | ||
| 768 | + char pp[PATH_SZ]; | ||
| 769 | + int marker = 0; | ||
| 770 | + pending_path(pp, sizeof(pp)); | ||
| 771 | + marker = file_exists(pp); | ||
| 772 | + if (marker) { | ||
| 773 | + char *pend = read_file(pp); | ||
| 774 | + long long created = -1; | ||
| 775 | + if (pend) { | ||
| 776 | + const char *pe = pend + strlen(pend); | ||
| 777 | + created = json_num_field(pend, pe, "created"); | ||
| 778 | + free(pend); | ||
| 779 | + } | ||
| 780 | + if (created > 0) { | ||
| 781 | + st->pending_age = now - created; | ||
| 782 | + st->pending = (st->pending_age >= 0 && st->pending_age <= PENDING_TTL_SEC); | ||
| 783 | + } else { | ||
| 784 | + st->pending = 1; /* unreadable marker: assume still open */ | ||
| 785 | + } | ||
| 786 | + } | ||
| 787 | + /* Only when there is no marker at all does the CLI's own pending bit | ||
| 788 | + * get to speak: it reads the same file, so a stale-but-present marker | ||
| 789 | + * must never be revived by it. */ | ||
| 790 | + if (!marker) st->cli_pending_unknown = 1; | ||
| 791 | + } | ||
| 792 | + | ||
| 793 | + /* 3. the profile file the CLI creates */ | ||
| 794 | + { | ||
| 795 | + char prof[PATH_SZ]; | ||
| 796 | + profile_path(prof, sizeof(prof)); | ||
| 797 | + st->profile_exists = file_exists(prof); | ||
| 798 | + } | ||
| 799 | + | ||
| 800 | + /* 4. ask the CLI, and let it ADD to what the files already proved. The | ||
| 801 | + * file-derived booleans win: they are what this node actually has, and | ||
| 802 | + * a stale or partial CLI answer must not erase them. */ | ||
| 803 | + { | ||
| 804 | + buf_t b; | ||
| 805 | + const char *j; | ||
| 806 | + int rc; | ||
| 807 | + | ||
| 808 | + buf_init(&b); | ||
| 809 | + rc = run_capture(login_bin(), "--status", &b); | ||
| 810 | + if (rc < 0) { | ||
| 811 | + st->cli_present = 0; | ||
| 812 | + snprintf(st->cli_error, sizeof(st->cli_error), "cli_not_found"); | ||
| 813 | + } else if (rc == 0) { | ||
| 814 | + st->cli_present = 0; | ||
| 815 | + snprintf(st->cli_error, sizeof(st->cli_error), "cli_spawn_failed"); | ||
| 816 | + } else { | ||
| 817 | + st->cli_present = 1; | ||
| 818 | + j = last_json_line(&b); | ||
| 819 | + if (j) { | ||
| 820 | + const char *je = j + strlen(j); | ||
| 821 | + st->cli_ok = json_bool_field(j, je, "ok", 0); | ||
| 822 | + if (!st->cli_ok) | ||
| 823 | + json_str_field(j, je, "error", st->cli_error, sizeof(st->cli_error)); | ||
| 824 | + if (!st->account[0]) | ||
| 825 | + json_str_field(j, je, "account", st->account, sizeof(st->account)); | ||
| 826 | + if (!st->expires_at) | ||
| 827 | + st->expires_at = normalise_expiry(json_num_field(j, je, "expires_at")); | ||
| 828 | + if (!st->logged_in && json_bool_field(j, je, "logged_in", 0)) | ||
| 829 | + st->logged_in = 1; | ||
| 830 | + if (!st->has_refresh && json_bool_field(j, je, "has_refresh", 0)) | ||
| 831 | + st->has_refresh = 1; | ||
| 832 | + if (!st->pending && st->cli_pending_unknown && | ||
| 833 | + json_bool_field(j, je, "pending", 0)) | ||
| 834 | + st->pending = 1; | ||
| 835 | + if (!st->profile_exists && json_bool_field(j, je, "profile_exists", 0)) | ||
| 836 | + st->profile_exists = 1; | ||
| 837 | + if (!st->path[0]) json_str_field(j, je, "path", st->path, sizeof(st->path)); | ||
| 838 | + } | ||
| 839 | + } | ||
| 840 | + buf_free(&b); | ||
| 841 | + } | ||
| 842 | + st->expired = (st->expires_at > 0 && st->expires_at < (long long)time(NULL)); | ||
| 843 | + | ||
| 844 | + /* 5. is the token CLI on this node at all (used by refresh + the UI) */ | ||
| 845 | + { | ||
| 846 | + buf_t b; | ||
| 847 | + buf_init(&b); | ||
| 848 | + /* run_capture returns 1 when the process actually ran, -1 when the | ||
| 849 | + * binary was not found (exit 127), 0 when popen itself failed. Only | ||
| 850 | + * "it ran" counts as present: usage text, an auth error or an unknown | ||
| 851 | + * flag all mean the CLI is installed here. */ | ||
| 852 | + st->token_bin_present = (run_capture(token_bin(), "--help", &b) == 1); | ||
| 853 | + buf_free(&b); | ||
| 854 | + } | ||
| 855 | +} | ||
| 856 | + | ||
| 857 | +/* ------------------------------------------------------------------ */ | ||
| 858 | +/* JSON emitters */ | ||
| 859 | +/* ------------------------------------------------------------------ */ | ||
| 860 | + | ||
| 861 | +static void emit_json(buf_t *b) | ||
| 862 | +{ | ||
| 863 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 864 | + "Cache-Control: no-store\r\n" | ||
| 865 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 866 | + fputs(buf_str(b), stdout); | ||
| 867 | + buf_free(b); | ||
| 868 | +} | ||
| 869 | + | ||
| 870 | +static void emit_error(int code, const char *status, const char *err, const char *detail) | ||
| 871 | +{ | ||
| 872 | + buf_t b; | ||
| 873 | + | ||
| 874 | + buf_init(&b); | ||
| 875 | + buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" | ||
| 876 | + "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", | ||
| 877 | + code, status); | ||
| 878 | + buf_addf(&b, "{\"ok\":false,\"error\":"); | ||
| 879 | + buf_json(&b, err); | ||
| 880 | + if (detail && *detail) { | ||
| 881 | + buf_addf(&b, ",\"detail\":"); | ||
| 882 | + buf_json(&b, detail); | ||
| 883 | + } | ||
| 884 | + buf_addf(&b, "}\n"); | ||
| 885 | + /* emit_json() would prepend its own header block again; emit_error has | ||
| 886 | + * already written a Status: line, so flush the buffer directly. */ | ||
| 887 | + fputs(buf_str(&b), stdout); | ||
| 888 | + buf_free(&b); | ||
| 889 | +} | ||
| 890 | + | ||
| 891 | +/* One status payload, shared by ?action=status, ?format=json, the poll "done" | ||
| 892 | + * branch, cancel and refresh so the five can never disagree about what the | ||
| 893 | + * node holds. `prefix` replaces the opening {"ok":true so a caller can lead | ||
| 894 | + * with its own contract fields; NULL means the plain status object. */ | ||
| 895 | +static void emit_status_json(buf_t *b, const status_t *st, const char *prefix) | ||
| 896 | +{ | ||
| 897 | + long long now = (long long)time(NULL); | ||
| 898 | + long long left = st->expires_at > 0 ? st->expires_at - now : 0; | ||
| 899 | + | ||
| 900 | + buf_adds(b, prefix ? prefix : "{\"ok\":true"); | ||
| 901 | + buf_adds(b, ",\"provider\":\"opencode\""); | ||
| 902 | + buf_adds(b, ",\"logged_in\":"); buf_adds(b, st->logged_in ? "true" : "false"); | ||
| 903 | + buf_adds(b, ",\"username\":"); buf_json(b, st->account[0] ? st->account : (st->logged_in ? "OpenCode" : "")); | ||
| 904 | + buf_adds(b, ",\"account\":"); buf_json(b, st->account[0] ? st->account : ""); | ||
| 905 | + buf_adds(b, ",\"org_id\":"); buf_json(b, st->org[0] ? st->org : ""); | ||
| 906 | + buf_addf(b, ",\"expires_at\":%lld", st->expires_at); | ||
| 907 | + buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_at > 0 ? left : 0); | ||
| 908 | + buf_adds(b, ",\"expired\":"); buf_adds(b, st->expired ? "true" : "false"); | ||
| 909 | + buf_adds(b, ",\"has_refresh\":");buf_adds(b, st->has_refresh ? "true" : "false"); | ||
| 910 | + buf_adds(b, ",\"pending\":"); buf_adds(b, st->pending ? "true" : "false"); | ||
| 911 | + if (st->pending_age >= 0) buf_addf(b, ",\"pending_age_sec\":%lld", st->pending_age); | ||
| 912 | + buf_adds(b, ",\"profile\":"); buf_json(b, st->profile); | ||
| 913 | + buf_adds(b, ",\"profile_exists\":"); | ||
| 914 | + buf_adds(b, st->profile_exists ? "true" : "false"); | ||
| 915 | + buf_adds(b, ",\"cli_present\":"); | ||
| 916 | + buf_adds(b, st->cli_present ? "true" : "false"); | ||
| 917 | + buf_adds(b, ",\"token_cli_present\":"); | ||
| 918 | + buf_adds(b, st->token_bin_present ? "true" : "false"); | ||
| 919 | + buf_adds(b, ",\"path\":"); buf_json(b, st->path); | ||
| 920 | + if (st->cli_error[0]) { buf_adds(b, ",\"cli_error\":"); buf_json(b, st->cli_error); } | ||
| 921 | + buf_adds(b, ",\"protocol\":\"SXLOGIN-MACHINE-V1\""); | ||
| 922 | + buf_adds(b, ",\"plugin\":\"" PLUGIN_ID "\""); | ||
| 923 | + buf_addf(b, ",\"plugin_version\":\"%s\"", PLUGIN_VER); | ||
| 924 | + buf_adds(b, ",\"now\":"); | ||
| 925 | + buf_addf(b, "%lld", now); | ||
| 926 | + buf_adds(b, "}\n"); | ||
| 927 | +} | ||
| 928 | + | ||
| 929 | +static int action_status(void) | ||
| 930 | +{ | ||
| 931 | + status_t st; | ||
| 932 | + buf_t b; | ||
| 933 | + | ||
| 934 | + collect_status(&st); | ||
| 935 | + buf_init(&b); | ||
| 936 | + emit_status_json(&b, &st, NULL); | ||
| 937 | + emit_json(&b); | ||
| 938 | + return 0; | ||
| 939 | +} | ||
| 940 | + | ||
| 941 | +/* ------------------------------------------------------------------ */ | ||
| 942 | +/* Device flow actions */ | ||
| 943 | +/* ------------------------------------------------------------------ */ | ||
| 944 | + | ||
| 945 | +/* Ask the login CLI to begin the device flow. `--force` is appended when the | ||
| 946 | + * caller passes force=1, which is how the UI lets a user re-login over an | ||
| 947 | + * existing session (the CLI refuses to clobber credentials otherwise). */ | ||
| 948 | +static int action_start(void) | ||
| 949 | +{ | ||
| 950 | + status_t st; | ||
| 951 | + buf_t in; | ||
| 952 | + buf_t out; | ||
| 953 | + const char *j; | ||
| 954 | + char args[32]; | ||
| 955 | + char verify[URL_SZ] = {0}; | ||
| 956 | + char code[CODE_SZ] = {0}; | ||
| 957 | + int force = 0; | ||
| 958 | + int interval = 5; | ||
| 959 | + long long expires_in = 900; | ||
| 960 | + int rc; | ||
| 961 | + | ||
| 962 | + collect_status(&st); | ||
| 963 | + if (!st.cli_present) { | ||
| 964 | + emit_error(200, "OK", "cli_unavailable", | ||
| 965 | + "scorpiox-opencode-login is not on this node"); | ||
| 966 | + return 0; | ||
| 967 | + } | ||
| 968 | + | ||
| 969 | + force = query_has(getenv("QUERY_STRING"), "force") ? 1 : 0; | ||
| 970 | + | ||
| 971 | + snprintf(args, sizeof(args), "--start%s", force ? " --force" : ""); | ||
| 972 | + | ||
| 973 | + buf_init(&in); | ||
| 974 | + rc = run_capture(login_bin(), args, &in); | ||
| 975 | + if (rc < 0) { | ||
| 976 | + buf_free(&in); | ||
| 977 | + emit_error(200, "OK", "cli_unavailable", | ||
| 978 | + "scorpiox-opencode-login is not on this node"); | ||
| 979 | + return 0; | ||
| 980 | + } | ||
| 981 | + if (rc == 0) { | ||
| 982 | + buf_free(&in); | ||
| 983 | + emit_error(500, "Internal Server Error", "start_failed", "cannot spawn login CLI"); | ||
| 984 | + return 1; | ||
| 985 | + } | ||
| 986 | + | ||
| 987 | + j = last_json_line(&in); | ||
| 988 | + if (!j) { | ||
| 989 | + buf_free(&in); | ||
| 990 | + emit_error(502, "Bad Gateway", "start_failed", "login CLI produced no JSON"); | ||
| 991 | + return 1; | ||
| 992 | + } | ||
| 993 | + { | ||
| 994 | + const char *je = j + strlen(j); | ||
| 995 | + if (!json_bool_field(j, je, "ok", 0)) { | ||
| 996 | + char err[FIELD_SZ] = {0}; | ||
| 997 | + char detail[FIELD_SZ] = {0}; | ||
| 998 | + json_str_field(j, je, "error", err, sizeof(err)); | ||
| 999 | + json_str_field(j, je, "detail", detail, sizeof(detail)); | ||
| 1000 | + buf_free(&in); | ||
| 1001 | + if (strcmp(err, "exists") == 0) { | ||
| 1002 | + /* Credentials are already on this node: the honest answer is | ||
| 1003 | + * "already signed in, press re-login to replace them". */ | ||
| 1004 | + buf_init(&out); | ||
| 1005 | + buf_adds(&out, "{\"ok\":true,\"already_logged_in\":true,\"pending\":false"); | ||
| 1006 | + buf_adds(&out, ",\"error\":\"already_logged_in\""); | ||
| 1007 | + buf_adds(&out, ",\"detail\":"); | ||
| 1008 | + buf_json(&out, detail[0] ? detail : "credentials already exist"); | ||
| 1009 | + buf_adds(&out, ",\"logged_in\":"); | ||
| 1010 | + buf_adds(&out, st.logged_in ? "true" : "false"); | ||
| 1011 | + buf_adds(&out, ",\"hint\":\"pass force=1 to replace the existing session\"}\n"); | ||
| 1012 | + emit_json(&out); | ||
| 1013 | + return 0; | ||
| 1014 | + } | ||
| 1015 | + emit_error(200, "OK", err[0] ? err : "start_failed", detail); | ||
| 1016 | + return 0; | ||
| 1017 | + } | ||
| 1018 | + json_str_field(j, je, "verify_url", verify, sizeof(verify)); | ||
| 1019 | + json_str_field(j, je, "user_code", code, sizeof(code)); | ||
| 1020 | + interval = (int)json_num_field(j, je, "interval"); | ||
| 1021 | + expires_in = json_num_field(j, je, "expires_in"); | ||
| 1022 | + if (interval < 1) interval = 5; | ||
| 1023 | + if (expires_in <= 0) expires_in = PENDING_TTL_SEC; | ||
| 1024 | + } | ||
| 1025 | + buf_free(&in); | ||
| 1026 | + | ||
| 1027 | + if (!verify[0] || !code[0]) { | ||
| 1028 | + emit_error(502, "Bad Gateway", "start_incomplete", | ||
| 1029 | + "login CLI did not return a verify url and user code"); | ||
| 1030 | + return 1; | ||
| 1031 | + } | ||
| 1032 | + | ||
| 1033 | + buf_init(&out); | ||
| 1034 | + buf_addf(&out, "{\"ok\":true,\"flow\":\"device_code\",\"verify_url\":"); | ||
| 1035 | + buf_json(&out, verify); | ||
| 1036 | + buf_adds(&out, ",\"user_code\":"); | ||
| 1037 | + buf_json(&out, code); | ||
| 1038 | + buf_addf(&out, ",\"expires_in\":%lld", expires_in); | ||
| 1039 | + buf_addf(&out, ",\"interval\":%d", interval); | ||
| 1040 | + buf_adds(&out, ",\"pending\":true"); | ||
| 1041 | + buf_adds(&out, ",\"provider\":\"opencode\"}\n"); | ||
| 1042 | + emit_json(&out); | ||
| 1043 | + return 0; | ||
| 1044 | +} | ||
| 1045 | + | ||
| 1046 | +/* One non-blocking poll. The CLI does exactly one HTTPS round trip and | ||
| 1047 | + * returns; the UI drives the cadence so nothing here ever blocks. */ | ||
| 1048 | +static int action_poll(void) | ||
| 1049 | +{ | ||
| 1050 | + status_t st; | ||
| 1051 | + buf_t in; | ||
| 1052 | + buf_t out; | ||
| 1053 | + const char *j; | ||
| 1054 | + char state[64] = {0}; | ||
| 1055 | + int rc; | ||
| 1056 | + | ||
| 1057 | + collect_status(&st); | ||
| 1058 | + if (!st.cli_present) { | ||
| 1059 | + emit_error(200, "OK", "cli_unavailable", | ||
| 1060 | + "scorpiox-opencode-login is not on this node"); | ||
| 1061 | + return 0; | ||
| 1062 | + } | ||
| 1063 | + | ||
| 1064 | + buf_init(&in); | ||
| 1065 | + rc = run_capture(login_bin(), "--poll", &in); | ||
| 1066 | + if (rc < 0) { | ||
| 1067 | + buf_free(&in); | ||
| 1068 | + emit_error(200, "OK", "cli_unavailable", | ||
| 1069 | + "scorpiox-opencode-login is not on this node"); | ||
| 1070 | + return 0; | ||
| 1071 | + } | ||
| 1072 | + if (rc == 0) { | ||
| 1073 | + buf_free(&in); | ||
| 1074 | + emit_error(500, "Internal Server Error", "poll_failed", "cannot spawn login CLI"); | ||
| 1075 | + return 1; | ||
| 1076 | + } | ||
| 1077 | + | ||
| 1078 | + j = last_json_line(&in); | ||
| 1079 | + if (!j) { | ||
| 1080 | + buf_free(&in); | ||
| 1081 | + /* No JSON at all. Fall back to what the files say: a credential file | ||
| 1082 | + * that appeared while polling is a success no matter what the CLI | ||
| 1083 | + * printed, and a marker that vanished with no credentials is a dead | ||
| 1084 | + * flow, not an infinite spinner. */ | ||
| 1085 | + if (st.logged_in) { | ||
| 1086 | + buf_init(&out); | ||
| 1087 | + emit_status_json(&out, &st, | ||
| 1088 | + "{\"ok\":true,\"state\":\"done\""); | ||
| 1089 | + emit_json(&out); | ||
| 1090 | + return 0; | ||
| 1091 | + } | ||
| 1092 | + emit_error(502, "Bad Gateway", "poll_failed", "login CLI produced no JSON"); | ||
| 1093 | + return 1; | ||
| 1094 | + } | ||
| 1095 | + { | ||
| 1096 | + const char *je = j + strlen(j); | ||
| 1097 | + json_str_field(j, je, "state", state, sizeof(state)); | ||
| 1098 | + if (!json_bool_field(j, je, "ok", 0)) { | ||
| 1099 | + char err[FIELD_SZ] = {0}; | ||
| 1100 | + char detail[FIELD_SZ] = {0}; | ||
| 1101 | + json_str_field(j, je, "error", err, sizeof(err)); | ||
| 1102 | + json_str_field(j, je, "detail", detail, sizeof(detail)); | ||
| 1103 | + buf_free(&in); | ||
| 1104 | + /* expired / no_pending / denied are terminal, not transient. */ | ||
| 1105 | + buf_init(&out); | ||
| 1106 | + buf_adds(&out, "{\"ok\":true,\"state\":\"failed\""); | ||
| 1107 | + buf_adds(&out, ",\"error\":"); | ||
| 1108 | + buf_json(&out, err[0] ? err : "poll_failed"); | ||
| 1109 | + if (detail[0]) { buf_adds(&out, ",\"detail\":"); buf_json(&out, detail); } | ||
| 1110 | + buf_adds(&out, ",\"logged_in\":"); | ||
| 1111 | + buf_adds(&out, st.logged_in ? "true" : "false"); | ||
| 1112 | + buf_adds(&out, ",\"pending\":false}\n"); | ||
| 1113 | + emit_json(&out); | ||
| 1114 | + return 0; | ||
| 1115 | + } | ||
| 1116 | + if (strcmp(state, "done") == 0 || json_bool_field(j, je, "logged_in", 0)) { | ||
| 1117 | + /* Authorised: re-read the node state from the files so the answer | ||
| 1118 | + * is what this machine actually holds, not what the CLI claims. */ | ||
| 1119 | + status_t fresh; | ||
| 1120 | + collect_status(&fresh); | ||
| 1121 | + buf_init(&out); | ||
| 1122 | + emit_status_json(&out, &fresh, | ||
| 1123 | + "{\"ok\":true,\"state\":\"done\""); | ||
| 1124 | + emit_json(&out); | ||
| 1125 | + return 0; | ||
| 1126 | + } | ||
| 1127 | + { | ||
| 1128 | + int interval = (int)json_num_field(j, je, "interval"); | ||
| 1129 | + if (interval < 1) interval = 5; | ||
| 1130 | + buf_free(&in); | ||
| 1131 | + buf_init(&out); | ||
| 1132 | + buf_addf(&out, "{\"ok\":true,\"state\":\"pending\",\"interval\":%d," | ||
| 1133 | + "\"logged_in\":false,\"pending\":true}\n", interval); | ||
| 1134 | + emit_json(&out); | ||
| 1135 | + return 0; | ||
| 1136 | + } | ||
| 1137 | + } | ||
| 1138 | +} | ||
| 1139 | + | ||
| 1140 | +static int action_cancel(void) | ||
| 1141 | +{ | ||
| 1142 | + status_t st; | ||
| 1143 | + buf_t in; | ||
| 1144 | + buf_t out; | ||
| 1145 | + | ||
| 1146 | + collect_status(&st); | ||
| 1147 | + if (!st.cli_present) { | ||
| 1148 | + /* Nothing to abort and no CLI to tell: drop the marker ourselves so | ||
| 1149 | + * the UI spinner stops on a node without SCORPIOX CODE. */ | ||
| 1150 | + char pp[PATH_SZ]; | ||
| 1151 | + pending_path(pp, sizeof(pp)); | ||
| 1152 | + if (file_exists(pp)) remove(pp); | ||
| 1153 | + buf_init(&out); | ||
| 1154 | + buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false," | ||
| 1155 | + "\"cli_present\":false}\n"); | ||
| 1156 | + emit_json(&out); | ||
| 1157 | + return 0; | ||
| 1158 | + } | ||
| 1159 | + | ||
| 1160 | + buf_init(&in); | ||
| 1161 | + { | ||
| 1162 | + int rc = run_capture(login_bin(), "--cancel", &in); | ||
| 1163 | + if (rc < 0) { | ||
| 1164 | + buf_free(&in); | ||
| 1165 | + emit_error(200, "OK", "cli_unavailable", | ||
| 1166 | + "scorpiox-opencode-login is not on this node"); | ||
| 1167 | + return 0; | ||
| 1168 | + } | ||
| 1169 | + { | ||
| 1170 | + const char *j = last_json_line(&in); | ||
| 1171 | + int ok = 1; | ||
| 1172 | + if (j) { | ||
| 1173 | + const char *je = j + strlen(j); | ||
| 1174 | + ok = json_bool_field(j, je, "ok", 1); | ||
| 1175 | + } | ||
| 1176 | + buf_free(&in); | ||
| 1177 | + if (!ok) { | ||
| 1178 | + emit_error(200, "OK", "cancel_failed", "login CLI rejected the cancel"); | ||
| 1179 | + return 0; | ||
| 1180 | + } | ||
| 1181 | + /* The CLI removes the marker; re-collect to report the truth. */ | ||
| 1182 | + { | ||
| 1183 | + status_t after; | ||
| 1184 | + collect_status(&after); | ||
| 1185 | + buf_init(&out); | ||
| 1186 | + emit_status_json(&out, &after, | ||
| 1187 | + "{\"ok\":true,\"state\":\"cancelled\""); | ||
| 1188 | + emit_json(&out); | ||
| 1189 | + } | ||
| 1190 | + } | ||
| 1191 | + } | ||
| 1192 | + return 0; | ||
| 1193 | +} | ||
| 1194 | + | ||
| 1195 | +/* Re-read and re-verify the stored token through the node's own token CLI. | ||
| 1196 | + * OpenCode tokens are long-lived; there is no refresh grant on this node, so | ||
| 1197 | + * "refresh" means "ask the CLI for a live token right now and report the new | ||
| 1198 | + * expiry". The token value is read into a throwaway buffer and discarded. */ | ||
| 1199 | +static int action_refresh(void) | ||
| 1200 | +{ | ||
| 1201 | + status_t st; | ||
| 1202 | + buf_t in; | ||
| 1203 | + buf_t out; | ||
| 1204 | + const char *j; | ||
| 1205 | + | ||
| 1206 | + collect_status(&st); | ||
| 1207 | + if (!st.token_bin_present) { | ||
| 1208 | + emit_error(200, "OK", "refresh_unavailable", | ||
| 1209 | + "scorpiox-opencode-fetchtoken is not on this node"); | ||
| 1210 | + return 0; | ||
| 1211 | + } | ||
| 1212 | + if (!st.logged_in) { | ||
| 1213 | + emit_error(200, "OK", "not_logged_in", "start a device login first"); | ||
| 1214 | + return 0; | ||
| 1215 | + } | ||
| 1216 | + | ||
| 1217 | + buf_init(&in); | ||
| 1218 | + { | ||
| 1219 | + int rc = run_capture(token_bin(), "-local", &in); | ||
| 1220 | + if (rc <= 0) { | ||
| 1221 | + buf_free(&in); | ||
| 1222 | + emit_error(200, "OK", "refresh_failed", "token CLI could not run"); | ||
| 1223 | + return 1; | ||
| 1224 | + } | ||
| 1225 | + } | ||
| 1226 | + j = last_json_line(&in); | ||
| 1227 | + if (!j) { | ||
| 1228 | + buf_free(&in); | ||
| 1229 | + emit_error(200, "OK", "refresh_failed", "token CLI produced no JSON"); | ||
| 1230 | + return 1; | ||
| 1231 | + } | ||
| 1232 | + { | ||
| 1233 | + const char *je = j + strlen(j); | ||
| 1234 | + long long exp = normalise_expiry(json_num_field(j, je, "expires_at")); | ||
| 1235 | + char org[ORG_SZ] = {0}; | ||
| 1236 | + int has_tok = json_str_present(j, je, "access_token"); | ||
| 1237 | + json_str_field(j, je, "org_id", org, sizeof(org)); | ||
| 1238 | + buf_free(&in); | ||
| 1239 | + if (!has_tok) { | ||
| 1240 | + emit_error(200, "OK", "refresh_failed", "token CLI returned no token"); | ||
| 1241 | + return 1; | ||
| 1242 | + } | ||
| 1243 | + st.expires_at = exp > 0 ? exp : st.expires_at; | ||
| 1244 | + st.expired = (st.expires_at > 0 && st.expires_at < (long long)time(NULL)); | ||
| 1245 | + if (org[0] && !st.org[0]) { | ||
| 1246 | + snprintf(st.org, sizeof(st.org), "%s", org); | ||
| 1247 | + snprintf(st.account, sizeof(st.account), "%s", org); | ||
| 1248 | + } | ||
| 1249 | + buf_init(&out); | ||
| 1250 | + emit_status_json(&out, &st, "{\"ok\":true,\"refreshed\":true"); | ||
| 1251 | + emit_json(&out); | ||
| 1252 | + return 0; | ||
| 1253 | + } | ||
| 1254 | +} | ||
| 1255 | + | ||
| 1256 | +/* ------------------------------------------------------------------ */ | ||
| 1257 | +/* HTML UI */ | ||
| 1258 | +/* ------------------------------------------------------------------ */ | ||
| 1259 | + | ||
| 1260 | +static void serve_html(void) | ||
| 1261 | +{ | ||
| 1262 | + const char *qs = getenv("QUERY_STRING"); | ||
| 1263 | + int embed = (qs && (strstr(qs, "embed=1") || strstr(qs, "embed=true"))); | ||
| 1264 | + const char *s; | ||
| 1265 | + | ||
| 1266 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1267 | + "Cache-Control: no-store\r\n" | ||
| 1268 | + "X-Content-Type-Options: nosniff\r\n" | ||
| 1269 | + "X-Frame-Options: SAMEORIGIN\r\n" | ||
| 1270 | + "Referrer-Policy: same-origin\r\n\r\n", stdout); | ||
| 1271 | + | ||
| 1272 | + /* UI_HTML carries two control-byte placeholders: \001 where the bot theme | ||
| 1273 | + * tokens + prepaint script belong, \002 where the theme handoff script | ||
| 1274 | + * belongs. Splitting on them keeps the page readable in src/ui.html and | ||
| 1275 | + * the theme in one vendored header that can never drift from the bot. */ | ||
| 1276 | + for (s = UI_HTML; *s; ) { | ||
| 1277 | + unsigned char c = (unsigned char)*s; | ||
| 1278 | + if (c == 0x01) { | ||
| 1279 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout); | ||
| 1280 | + s++; | ||
| 1281 | + } else if (c == 0x02) { | ||
| 1282 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | ||
| 1283 | + s++; | ||
| 1284 | + } else { | ||
| 1285 | + fputc((char)c, stdout); | ||
| 1286 | + s++; | ||
| 1287 | + } | ||
| 1288 | + } | ||
| 1289 | + (void)embed; /* the page reads ?embed=1 itself, before first paint */ | ||
| 1290 | +} | ||
| 1291 | + | ||
| 1292 | +/* ------------------------------------------------------------------ */ | ||
| 1293 | +/* Entry point */ | ||
| 1294 | +/* ------------------------------------------------------------------ */ | ||
| 1295 | + | ||
| 1296 | +int main(int argc, char **argv) | ||
| 1297 | +{ | ||
| 1298 | + const char *qs; | ||
| 1299 | + char action[64] = {0}; | ||
| 1300 | + | ||
| 1301 | + /* 1. Discovery metadata. Must stay unauthenticated. */ | ||
| 1302 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | ||
| 1303 | + puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); | ||
| 1304 | + return 0; | ||
| 1305 | + } | ||
| 1306 | + if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { | ||
| 1307 | + puts(PLUGIN_ID " " PLUGIN_VER); | ||
| 1308 | + return 0; | ||
| 1309 | + } | ||
| 1310 | + | ||
| 1311 | + require_node_auth(); | ||
| 1312 | + | ||
| 1313 | + qs = getenv("QUERY_STRING"); | ||
| 1314 | + if (!qs) qs = ""; | ||
| 1315 | + | ||
| 1316 | + /* 2. JSON API mode. `format=json` alone means "status", which is what a | ||
| 1317 | + * dashboard polls. */ | ||
| 1318 | + if (query_has(qs, "action") || query_has(qs, "format")) { | ||
| 1319 | + char fmt[32] = {0}; | ||
| 1320 | + | ||
| 1321 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 1322 | + get_query_val(qs, "format", fmt, sizeof(fmt)); | ||
| 1323 | + | ||
| 1324 | + if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status"); | ||
| 1325 | + | ||
| 1326 | + if (strcmp(action, "status") == 0 || !action[0]) return action_status(); | ||
| 1327 | + if (strcmp(action, "start") == 0) return action_start(); | ||
| 1328 | + if (strcmp(action, "poll") == 0) return action_poll(); | ||
| 1329 | + if (strcmp(action, "cancel") == 0) return action_cancel(); | ||
| 1330 | + if (strcmp(action, "refresh") == 0) return action_refresh(); | ||
| 1331 | + | ||
| 1332 | + emit_error(400, "Bad Request", "unknown_action", | ||
| 1333 | + "expected status, start, poll, cancel or refresh"); | ||
| 1334 | + return 1; | ||
| 1335 | + } | ||
| 1336 | + | ||
| 1337 | + /* 3. HTML UI */ | ||
| 1338 | + serve_html(); | ||
| 1339 | + return 0; | ||
| 1340 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..bc43e24 | index 0000000..bc43e24 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,325 @@ | @@ -0,0 +1,325 @@ | ||
| 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>opencode</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:11.5px;font-weight:600; | ||
| 27 | + padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text); | ||
| 28 | + border:1px solid var(--line);white-space:nowrap;max-width:220px;overflow:hidden; | ||
| 29 | + text-overflow:ellipsis} | ||
| 30 | +.badge .av{width:18px;height:18px;border-radius:50%;background:var(--blue);color:#fff; | ||
| 31 | + display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700; | ||
| 32 | + flex:0 0 auto} | ||
| 33 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | ||
| 34 | + padding:16px;margin-bottom:12px} | ||
| 35 | +.card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em; | ||
| 36 | + text-transform:uppercase;color:var(--text-2)} | ||
| 37 | +.card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)} | ||
| 38 | +.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap} | ||
| 39 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px; | ||
| 40 | + font-weight:600;font-size:13px;cursor:pointer;font-family:inherit; | ||
| 41 | + transition:transform .12s var(--ease),opacity .12s} | ||
| 42 | +.btn:active{transform:scale(.98)} | ||
| 43 | +.btn:disabled{opacity:.5;cursor:default} | ||
| 44 | +.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)} | ||
| 45 | +.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)} | ||
| 46 | +.btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)} | ||
| 47 | +a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none} | ||
| 48 | +.kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px} | ||
| 49 | +.kv .k{color:var(--text-2);font-size:12px} | ||
| 50 | +.kv .v{font-family:var(--mono);font-size:12px;word-break:break-all} | ||
| 51 | +.kv .v.plain{font-family:var(--font);font-size:13px} | ||
| 52 | +.hint{font-size:12px;color:var(--text-2);margin:10px 0 0} | ||
| 53 | +.step{display:none} | ||
| 54 | +.step.on{display:block} | ||
| 55 | +.codebox{margin:10px 0;padding:14px 16px;border-radius:12px;background:var(--code-bg); | ||
| 56 | + border:1px solid var(--line);text-align:center} | ||
| 57 | +.codebox .code{font-family:var(--mono);font-size:26px;font-weight:700;letter-spacing:.12em; | ||
| 58 | + color:var(--text);margin-bottom:6px} | ||
| 59 | +.codebox .code-empty{font-family:var(--mono);font-size:18px;color:var(--text-2); | ||
| 60 | + letter-spacing:.08em} | ||
| 61 | +.pollbar{margin:10px 0 0;height:3px;border-radius:2px;background:var(--surface-2); | ||
| 62 | + overflow:hidden} | ||
| 63 | +.pollbar i{display:block;height:100%;width:0;background:var(--blue); | ||
| 64 | + animation:pollslide 2s linear infinite} | ||
| 65 | +@keyframes pollslide{0%{width:0}50%{width:100%}100%{width:0}} | ||
| 66 | +.polllbl{font-size:11.5px;color:var(--text-2);margin:8px 0 0;display:flex;align-items:center;gap:6px} | ||
| 67 | +.polllbl .spin{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2); | ||
| 68 | + border-top-color:var(--blue);animation:spin 1s linear infinite;display:inline-block} | ||
| 69 | +@keyframes spin{to{transform:rotate(360deg)}} | ||
| 70 | +.authurl{margin:10px 0;padding:10px 11px;border-radius:10px;background:var(--code-bg); | ||
| 71 | + border:1px solid var(--line);font-family:var(--mono);font-size:11.5px; | ||
| 72 | + word-break:break-all;max-height:120px;overflow:auto;color:var(--text)} | ||
| 73 | +.note.warn{color:var(--orange);border-color:rgba(255,159,10,.35)} | ||
| 74 | +#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text); | ||
| 75 | + border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer; | ||
| 76 | + font-family:inherit} | ||
| 77 | +.note{display:none;margin-top:10px;padding:9px 11px;border-radius:10px;font-size:12.5px; | ||
| 78 | + border:1px solid var(--line);background:var(--surface-2)} | ||
| 79 | +.note.show{display:block} | ||
| 80 | +.note.err{color:var(--red);border-color:rgba(255,69,58,.35)} | ||
| 81 | +.note.ok{color:var(--green);border-color:rgba(48,209,88,.35)} | ||
| 82 | +.empty{padding:10px 0;color:var(--text-2);font-size:12.5px} | ||
| 83 | +.tok{font-size:11.5px;color:var(--text-2);margin-top:8px} | ||
| 84 | +.tok .ok{color:var(--green)} | ||
| 85 | +.tok .no{color:var(--red)} | ||
| 86 | +footer{font-size:11px;color:var(--text-2);margin-top:24px;text-align:center} | ||
| 87 | +footer a{color:var(--text-2)} | ||
| 88 | +@media(max-width:480px){ | ||
| 89 | + #app{padding:12px 12px 32px} | ||
| 90 | + .hd h1{font-size:16px} | ||
| 91 | + .kv{grid-template-columns:110px minmax(0,1fr)} | ||
| 92 | + .codebox .code{font-size:22px} | ||
| 93 | +} | ||
| 94 | +</style> | ||
| 95 | +</head> | ||
| 96 | +<body> | ||
| 97 | +<div id="app"> | ||
| 98 | + <div class="hd"> | ||
| 99 | + <div class="grow"> | ||
| 100 | + <h1>OpenCode Login</h1> | ||
| 101 | + <div class="sub">Device code login and account token manager for this node</div> | ||
| 102 | + </div> | ||
| 103 | + <span class="badge" id="userBadge" hidden> | ||
| 104 | + <span class="av" id="userAv">?</span><span id="userLabel"></span> | ||
| 105 | + </span> | ||
| 106 | + <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span> | ||
| 107 | + <button class="btn ghost embed-hide" id="themeToggle" type="button" title="Toggle appearance">Theme</button> | ||
| 108 | + </div> | ||
| 109 | + | ||
| 110 | + <!-- Session card --> | ||
| 111 | + <div class="card"> | ||
| 112 | + <h2>Session</h2> | ||
| 113 | + <p class="lead">The plugin reads the credential file written by the node's own login CLI. It never sees, stores, or returns a token value.</p> | ||
| 114 | + <div class="kv" id="sessionKv"> | ||
| 115 | + <div class="k">Status</div><div class="v plain" id="vStatus">Checking</div> | ||
| 116 | + <div class="k">Account</div><div class="v plain" id="vAccount">-</div> | ||
| 117 | + <div class="k">Token</div><div class="v plain" id="vToken">-</div> | ||
| 118 | + <div class="k">Refresh</div><div class="v plain" id="vRefresh">-</div> | ||
| 119 | + <div class="k">Profile</div><div class="v plain" id="vProfile">-</div> | ||
| 120 | + <div class="k">Credentials</div><div class="v" id="vPath">-</div> | ||
| 121 | + </div> | ||
| 122 | + <div class="tok" id="tokLine"></div> | ||
| 123 | + <div class="row" style="margin-top:12px"> | ||
| 124 | + <button class="btn" id="btnRefresh" type="button">Refresh Token Now</button> | ||
| 125 | + <button class="btn ghost" id="btnStartLogin" type="button">Start OpenCode Login</button> | ||
| 126 | + <button class="btn ghost" id="btnRelogin" type="button" hidden>Re-login (replace)</button> | ||
| 127 | + </div> | ||
| 128 | + <div class="note" id="sessionNote"></div> | ||
| 129 | + </div> | ||
| 130 | + | ||
| 131 | + <!-- Device flow card --> | ||
| 132 | + <div class="card" id="flowCard"> | ||
| 133 | + <h2>Device Flow</h2> | ||
| 134 | + <p class="lead">OpenCode signs in with a one-time user code. Copy it, open the link, approve, and this panel updates itself.</p> | ||
| 135 | + | ||
| 136 | + <div class="step on" id="stepIdle"> | ||
| 137 | + <div class="empty">No login in progress. Press <b>Start OpenCode Login</b> above to begin.</div> | ||
| 138 | + </div> | ||
| 139 | + | ||
| 140 | + <div class="step" id="stepActive"> | ||
| 141 | + <div class="codebox"> | ||
| 142 | + <div class="code" id="userCode">--</div> | ||
| 143 | + <div class="row" style="justify-content:center"> | ||
| 144 | + <button class="btn" id="btnCopyOpen" type="button">Copy Code & Open OpenCode</button> | ||
| 145 | + </div> | ||
| 146 | + </div> | ||
| 147 | + <div class="authurl" id="verifyUrl"></div> | ||
| 148 | + <div class="pollbar"><i></i></div> | ||
| 149 | + <div class="polllbl"><span class="spin"></span><span id="pollLabel">Waiting for approval</span></div> | ||
| 150 | + <div class="row" style="margin-top:12px"> | ||
| 151 | + <button class="btn danger" id="btnCancel" type="button">Cancel</button> | ||
| 152 | + </div> | ||
| 153 | + <div class="note" id="flowNote"></div> | ||
| 154 | + </div> | ||
| 155 | + </div> | ||
| 156 | + | ||
| 157 | + <footer> | ||
| 158 | + <span id="footInfo">plugin_opencode_login</span> | ||
| 159 | + · <a href="https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-opencode-login">source</a> | ||
| 160 | + </footer> | ||
| 161 | +</div> | ||
| 162 | +<script> | ||
| 163 | +(function(){ | ||
| 164 | + var q=new URLSearchParams(location.search); | ||
| 165 | + var node=q.get('node')||''; | ||
| 166 | + var sid=q.get('id')||''; | ||
| 167 | + var HUB=q.get('plugin')||''; | ||
| 168 | + var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||localStorage.getItem('bot_active_pwd')||''; | ||
| 169 | + var POLL_MS=5000; | ||
| 170 | + var pollTimer=null; | ||
| 171 | + var flowActive=false; | ||
| 172 | + var flowVerify=''; | ||
| 173 | + var flowCode=''; | ||
| 174 | + | ||
| 175 | + function esc(s){return String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');} | ||
| 176 | + function $(id){return document.getElementById(id);} | ||
| 177 | + function setPill(cls,text){var p=$('pill');p.className='pill '+cls;$('pillText').textContent=text;} | ||
| 178 | + function note(id,cls,text){var n=$(id);if(!n)return;n.className='note '+(cls||'')+(text?' show':'');n.textContent=text||'';} | ||
| 179 | + | ||
| 180 | + function api(action,extra){ | ||
| 181 | + var u; | ||
| 182 | + if(HUB) u='/plugins?plugin='+encodeURIComponent(HUB)+'&action='+encodeURIComponent(action); | ||
| 183 | + else u='/plugin_opencode_login?action='+encodeURIComponent(action); | ||
| 184 | + if(extra) u+='&'+extra; | ||
| 185 | + if(node) u+='&node='+encodeURIComponent(node); | ||
| 186 | + if(sid) u+='&id='+encodeURIComponent(sid); | ||
| 187 | + if(pwd) u+='&pwd='+encodeURIComponent(pwd); | ||
| 188 | + return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){return r.json();}); | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + function fmtExpiry(sec){ | ||
| 192 | + if(sec==null||sec<=0)return 'unknown'; | ||
| 193 | + if(sec<60)return sec+'s'; | ||
| 194 | + var m=Math.floor(sec/60); | ||
| 195 | + if(m<60)return m+' min'; | ||
| 196 | + var h=Math.floor(m/60); | ||
| 197 | + if(h<48)return h+' h '+(m%60)+' min'; | ||
| 198 | + var d=Math.floor(h/24); | ||
| 199 | + return d+' days'; | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + function renderStatus(d){ | ||
| 203 | + if(!d||d.ok===false){setPill('off','Not Connected');note('sessionNote','err',d&&d.error?('Error: '+d.error):'No response');return;} | ||
| 204 | + var li=!!d.logged_in, ex=!!d.expired, pend=!!d.pending; | ||
| 205 | + if(li&&!ex){setPill('ok','Connected');} | ||
| 206 | + else if(li&&ex){setPill('warn','Expired');} | ||
| 207 | + else if(pend){setPill('warn','Signing in');} | ||
| 208 | + else{setPill('off','Not Connected');} | ||
| 209 | + | ||
| 210 | + $('vStatus').textContent=li?(ex?'Signed in (token expired)':'Signed in'):(pend?'Device flow in progress':'Not signed in'); | ||
| 211 | + $('vAccount').textContent=d.account||d.username||'-'; | ||
| 212 | + $('vToken').textContent=li?(ex?'expired ('+fmtExpiry(d.expires_in_sec)+')':'valid, expires in '+fmtExpiry(d.expires_in_sec)):'none'; | ||
| 213 | + $('vRefresh').textContent=d.has_refresh?'stored (presence only)':'not stored'; | ||
| 214 | + $('vProfile').textContent=d.profile_exists?(d.profile||'superopencode')+' (exists)':'not created'; | ||
| 215 | + $('vPath').textContent=d.path||'-'; | ||
| 216 | + | ||
| 217 | + var tok=$('tokLine'); | ||
| 218 | + if(!d.cli_present){tok.innerHTML='<span class="no">scorpiox-opencode-login is not on this node.</span>';} | ||
| 219 | + else{tok.innerHTML='<span class="ok">Login CLI present</span> · token CLI '+(d.token_cli_present?'present':'missing');} | ||
| 220 | + | ||
| 221 | + var badge=$('userBadge'); | ||
| 222 | + if(li){badge.hidden=false;var lbl=d.account||d.username||'OpenCode';$('userLabel').textContent=lbl; | ||
| 223 | + $('userAv').textContent=(lbl.charAt(0)||'O').toUpperCase();} | ||
| 224 | + else{badge.hidden=true;} | ||
| 225 | + | ||
| 226 | + $('btnRelogin').hidden=!li; | ||
| 227 | + $('btnStartLogin').disabled=pend; | ||
| 228 | + | ||
| 229 | + if(pend&&!flowActive){startPollingUI();} | ||
| 230 | + if(!pend&&flowActive){stopPollingUI();$('stepIdle').classList.add('on');$('stepActive').classList.remove('on');} | ||
| 231 | + if(!li&&!pend){note('sessionNote','ok','No session on this node yet. Start a device login below.');} | ||
| 232 | + else if(li&&!ex){note('sessionNote','ok','');} | ||
| 233 | + else if(li&&ex){note('sessionNote','err','Token expired. Re-login to refresh the session.');} | ||
| 234 | + } | ||
| 235 | + | ||
| 236 | + function refresh(){api('status').then(renderStatus).catch(function(e){setPill('off','Not Connected');note('sessionNote','err','Request failed: '+e);});} | ||
| 237 | + | ||
| 238 | + function startPollingUI(){ | ||
| 239 | + flowActive=true; | ||
| 240 | + $('stepIdle').classList.remove('on'); | ||
| 241 | + $('stepActive').classList.add('on'); | ||
| 242 | + if(!pollTimer){pollTimer=setInterval(pollOnce,POLL_MS);} | ||
| 243 | + } | ||
| 244 | + function stopPollingUI(){ | ||
| 245 | + flowActive=false; | ||
| 246 | + if(pollTimer){clearInterval(pollTimer);pollTimer=null;} | ||
| 247 | + } | ||
| 248 | + | ||
| 249 | + function pollOnce(){ | ||
| 250 | + if(!flowActive)return; | ||
| 251 | + api('poll').then(function(d){ | ||
| 252 | + if(!d||d.ok===false){note('flowNote','err',d&&d.error?('Poll error: '+d.error):'Poll failed');return;} | ||
| 253 | + if(d.state==='done'||d.logged_in){ | ||
| 254 | + stopPollingUI(); | ||
| 255 | + $('stepIdle').classList.add('on'); | ||
| 256 | + $('stepActive').classList.remove('on'); | ||
| 257 | + note('flowNote','ok','Signed in. The credential file has been written.'); | ||
| 258 | + $('pollLabel').textContent='Signed in'; | ||
| 259 | + refresh(); | ||
| 260 | + }else if(d.state==='failed'){ | ||
| 261 | + stopPollingUI(); | ||
| 262 | + $('stepIdle').classList.add('on'); | ||
| 263 | + $('stepActive').classList.remove('on'); | ||
| 264 | + note('flowNote','err','Login failed: '+(d.error||'unknown')+(d.detail?(' - '+d.detail):'')); | ||
| 265 | + }else{ | ||
| 266 | + $('pollLabel').textContent='Waiting for approval'; | ||
| 267 | + } | ||
| 268 | + }).catch(function(e){note('flowNote','err','Poll request failed: '+e);}); | ||
| 269 | + } | ||
| 270 | + | ||
| 271 | + function doStart(force){ | ||
| 272 | + note('sessionNote','ok',''); | ||
| 273 | + api('start',force?'force=1':'').then(function(d){ | ||
| 274 | + if(!d||d.ok===false){note('sessionNote','err',d&&d.error?('Start failed: '+d.error):'Start failed');return;} | ||
| 275 | + if(d.already_logged_in){ | ||
| 276 | + note('sessionNote','warn','This node already has OpenCode credentials. Use Re-login to replace them.'); | ||
| 277 | + refresh(); | ||
| 278 | + return; | ||
| 279 | + } | ||
| 280 | + flowVerify=d.verify_url||''; | ||
| 281 | + flowCode=d.user_code||''; | ||
| 282 | + $('userCode').textContent=flowCode||'--'; | ||
| 283 | + $('verifyUrl').textContent=flowVerify; | ||
| 284 | + $('pollLabel').textContent='Waiting for approval'; | ||
| 285 | + note('flowNote','ok',''); | ||
| 286 | + startPollingUI(); | ||
| 287 | + refresh(); | ||
| 288 | + }).catch(function(e){note('sessionNote','err','Start request failed: '+e);}); | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + $('btnStartLogin').onclick=function(){doStart(false);}; | ||
| 292 | + $('btnRelogin').onclick=function(){doStart(true);}; | ||
| 293 | + $('btnCancel').onclick=function(){ | ||
| 294 | + stopPollingUI(); | ||
| 295 | + api('cancel').then(function(d){ | ||
| 296 | + $('stepIdle').classList.add('on'); | ||
| 297 | + $('stepActive').classList.remove('on'); | ||
| 298 | + note('flowNote','ok',d&&d.ok?'Device flow cancelled.':'Cancel failed: '+(d&&d.error||'unknown')); | ||
| 299 | + refresh(); | ||
| 300 | + }).catch(function(e){note('flowNote','err','Cancel request failed: '+e);}); | ||
| 301 | + }; | ||
| 302 | + $('btnRefresh').onclick=function(){ | ||
| 303 | + note('sessionNote','ok',''); | ||
| 304 | + api('refresh').then(function(d){ | ||
| 305 | + if(!d||d.ok===false){note('sessionNote','err',d&&d.error?('Refresh failed: '+d.error):'Refresh failed');return;} | ||
| 306 | + note('sessionNote','ok','Token re-read. '+(d.refreshed?'CLI confirmed a live token.':'')); | ||
| 307 | + renderStatus(d); | ||
| 308 | + }).catch(function(e){note('sessionNote','err','Refresh request failed: '+e);}); | ||
| 309 | + }; | ||
| 310 | + $('btnCopyOpen').onclick=function(){ | ||
| 311 | + var done=function(){note('flowNote','ok','Code copied. Open the link and approve.');}; | ||
| 312 | + if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(flowCode).then(done,function(){window.open(flowVerify,'_blank');done();});} | ||
| 313 | + else{done();} | ||
| 314 | + if(flowVerify)window.open(flowVerify,'_blank'); | ||
| 315 | + }; | ||
| 316 | + | ||
| 317 | + var tb=$('themeToggle'); | ||
| 318 | + if(tb)tb.onclick=function(){ | ||
| 319 | + if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark'); | ||
| 320 | + }; | ||
| 321 | + $('footInfo').textContent='plugin_opencode_login'; | ||
| 322 | + refresh(); | ||
| 323 | +})(); | ||
| 324 | +</script> | ||
| 325 | +</body></html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..fe410bf | index 0000000..fe410bf | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,333 @@ | @@ -0,0 +1,333 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_AGYLOGIN_UI_HTML_H | ||
| 3 | +#define SX_AGYLOGIN_UI_HTML_H | ||
| 4 | + | ||
| 5 | +static const char *UI_HTML = | ||
| 6 | + "<!DOCTYPE html>\n" | ||
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | ||
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | ||
| 9 | + "<title>opencode</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:11.5px;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);white-space:nowrap;max-width:220px;overflow:hidden;\n" | ||
| 34 | + " text-overflow:ellipsis}\n" | ||
| 35 | + ".badge .av{width:18px;height:18px;border-radius:50%;background:var(--blue);color:#fff;\n" | ||
| 36 | + " display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;\n" | ||
| 37 | + " flex:0 0 auto}\n" | ||
| 38 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | ||
| 39 | + " padding:16px;margin-bottom:12px}\n" | ||
| 40 | + ".card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;\n" | ||
| 41 | + " text-transform:uppercase;color:var(--text-2)}\n" | ||
| 42 | + ".card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}\n" | ||
| 43 | + ".row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n" | ||
| 44 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;\n" | ||
| 45 | + " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;\n" | ||
| 46 | + " transition:transform .12s var(--ease),opacity .12s}\n" | ||
| 47 | + ".btn:active{transform:scale(.98)}\n" | ||
| 48 | + ".btn:disabled{opacity:.5;cursor:default}\n" | ||
| 49 | + ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n" | ||
| 50 | + ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | ||
| 51 | + ".btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}\n" | ||
| 52 | + "a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}\n" | ||
| 53 | + ".kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}\n" | ||
| 54 | + ".kv .k{color:var(--text-2);font-size:12px}\n" | ||
| 55 | + ".kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}\n" | ||
| 56 | + ".kv .v.plain{font-family:var(--font);font-size:13px}\n" | ||
| 57 | + ".hint{font-size:12px;color:var(--text-2);margin:10px 0 0}\n" | ||
| 58 | + ".step{display:none}\n" | ||
| 59 | + ".step.on{display:block}\n" | ||
| 60 | + ".codebox{margin:10px 0;padding:14px 16px;border-radius:12px;background:var(--code-bg);\n" | ||
| 61 | + " border:1px solid var(--line);text-align:center}\n" | ||
| 62 | + ".codebox .code{font-family:var(--mono);font-size:26px;font-weight:700;letter-spacing:.12em;\n" | ||
| 63 | + " color:var(--text);margin-bottom:6px}\n" | ||
| 64 | + ".codebox .code-empty{font-family:var(--mono);font-size:18px;color:var(--text-2);\n" | ||
| 65 | + " letter-spacing:.08em}\n" | ||
| 66 | + ".pollbar{margin:10px 0 0;height:3px;border-radius:2px;background:var(--surface-2);\n" | ||
| 67 | + " overflow:hidden}\n" | ||
| 68 | + ".pollbar i{display:block;height:100%;width:0;background:var(--blue);\n" | ||
| 69 | + " animation:pollslide 2s linear infinite}\n" | ||
| 70 | + "@keyframes pollslide{0%{width:0}50%{width:100%}100%{width:0}}\n" | ||
| 71 | + ".polllbl{font-size:11.5px;color:var(--text-2);margin:8px 0 0;display:flex;align-items:center;gap:6px}\n" | ||
| 72 | + ".polllbl .spin{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2);\n" | ||
| 73 | + " border-top-color:var(--blue);animation:spin 1s linear infinite;display:inline-block}\n" | ||
| 74 | + "@keyframes spin{to{transform:rotate(360deg)}}\n" | ||
| 75 | + ".authurl{margin:10px 0;padding:10px 11px;border-radius:10px;background:var(--code-bg);\n" | ||
| 76 | + " border:1px solid var(--line);font-family:var(--mono);font-size:11.5px;\n" | ||
| 77 | + " word-break:break-all;max-height:120px;overflow:auto;color:var(--text)}\n" | ||
| 78 | + ".note.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n" | ||
| 79 | + "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | ||
| 80 | + " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n" | ||
| 81 | + " font-family:inherit}\n" | ||
| 82 | + ".note{display:none;margin-top:10px;padding:9px 11px;border-radius:10px;font-size:12.5px;\n" | ||
| 83 | + " border:1px solid var(--line);background:var(--surface-2)}\n" | ||
| 84 | + ".note.show{display:block}\n" | ||
| 85 | + ".note.err{color:var(--red);border-color:rgba(255,69,58,.35)}\n" | ||
| 86 | + ".note.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | ||
| 87 | + ".empty{padding:10px 0;color:var(--text-2);font-size:12.5px}\n" | ||
| 88 | + ".tok{font-size:11.5px;color:var(--text-2);margin-top:8px}\n" | ||
| 89 | + ".tok .ok{color:var(--green)}\n" | ||
| 90 | + ".tok .no{color:var(--red)}\n" | ||
| 91 | + "footer{font-size:11px;color:var(--text-2);margin-top:24px;text-align:center}\n" | ||
| 92 | + "footer a{color:var(--text-2)}\n" | ||
| 93 | + "@media(max-width:480px){\n" | ||
| 94 | + " #app{padding:12px 12px 32px}\n" | ||
| 95 | + " .hd h1{font-size:16px}\n" | ||
| 96 | + " .kv{grid-template-columns:110px minmax(0,1fr)}\n" | ||
| 97 | + " .codebox .code{font-size:22px}\n" | ||
| 98 | + "}\n" | ||
| 99 | + "</style>\n" | ||
| 100 | + "</head>\n" | ||
| 101 | + "<body>\n" | ||
| 102 | + "<div id=\"app\">\n" | ||
| 103 | + " <div class=\"hd\">\n" | ||
| 104 | + " <div class=\"grow\">\n" | ||
| 105 | + " <h1>OpenCode Login</h1>\n" | ||
| 106 | + " <div class=\"sub\">Device code login and account token manager for this node</div>\n" | ||
| 107 | + " </div>\n" | ||
| 108 | + " <span class=\"badge\" id=\"userBadge\" hidden>\n" | ||
| 109 | + " <span class=\"av\" id=\"userAv\">?</span><span id=\"userLabel\"></span>\n" | ||
| 110 | + " </span>\n" | ||
| 111 | + " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n" | ||
| 112 | + " <button class=\"btn ghost embed-hide\" id=\"themeToggle\" type=\"button\" title=\"Toggle appearance\">Theme</button>\n" | ||
| 113 | + " </div>\n" | ||
| 114 | + "\n" | ||
| 115 | + " <!-- Session card -->\n" | ||
| 116 | + " <div class=\"card\">\n" | ||
| 117 | + " <h2>Session</h2>\n" | ||
| 118 | + " <p class=\"lead\">The plugin reads the credential file written by the node's own login CLI. It never sees, stores, or returns a token value.</p>\n" | ||
| 119 | + " <div class=\"kv\" id=\"sessionKv\">\n" | ||
| 120 | + " <div class=\"k\">Status</div><div class=\"v plain\" id=\"vStatus\">Checking</div>\n" | ||
| 121 | + " <div class=\"k\">Account</div><div class=\"v plain\" id=\"vAccount\">-</div>\n" | ||
| 122 | + " <div class=\"k\">Token</div><div class=\"v plain\" id=\"vToken\">-</div>\n" | ||
| 123 | + " <div class=\"k\">Refresh</div><div class=\"v plain\" id=\"vRefresh\">-</div>\n" | ||
| 124 | + " <div class=\"k\">Profile</div><div class=\"v plain\" id=\"vProfile\">-</div>\n" | ||
| 125 | + " <div class=\"k\">Credentials</div><div class=\"v\" id=\"vPath\">-</div>\n" | ||
| 126 | + " </div>\n" | ||
| 127 | + " <div class=\"tok\" id=\"tokLine\"></div>\n" | ||
| 128 | + " <div class=\"row\" style=\"margin-top:12px\">\n" | ||
| 129 | + " <button class=\"btn\" id=\"btnRefresh\" type=\"button\">Refresh Token Now</button>\n" | ||
| 130 | + " <button class=\"btn ghost\" id=\"btnStartLogin\" type=\"button\">Start OpenCode Login</button>\n" | ||
| 131 | + " <button class=\"btn ghost\" id=\"btnRelogin\" type=\"button\" hidden>Re-login (replace)</button>\n" | ||
| 132 | + " </div>\n" | ||
| 133 | + " <div class=\"note\" id=\"sessionNote\"></div>\n" | ||
| 134 | + " </div>\n" | ||
| 135 | + "\n" | ||
| 136 | + " <!-- Device flow card -->\n" | ||
| 137 | + " <div class=\"card\" id=\"flowCard\">\n" | ||
| 138 | + " <h2>Device Flow</h2>\n" | ||
| 139 | + " <p class=\"lead\">OpenCode signs in with a one-time user code. Copy it, open the link, approve, and this panel updates itself.</p>\n" | ||
| 140 | + "\n" | ||
| 141 | + " <div class=\"step on\" id=\"stepIdle\">\n" | ||
| 142 | + " <div class=\"empty\">No login in progress. Press <b>Start OpenCode Login</b> above to begin.</div>\n" | ||
| 143 | + " </div>\n" | ||
| 144 | + "\n" | ||
| 145 | + " <div class=\"step\" id=\"stepActive\">\n" | ||
| 146 | + " <div class=\"codebox\">\n" | ||
| 147 | + " <div class=\"code\" id=\"userCode\">--</div>\n" | ||
| 148 | + " <div class=\"row\" style=\"justify-content:center\">\n" | ||
| 149 | + " <button class=\"btn\" id=\"btnCopyOpen\" type=\"button\">Copy Code & Open OpenCode</button>\n" | ||
| 150 | + " </div>\n" | ||
| 151 | + " </div>\n" | ||
| 152 | + " <div class=\"authurl\" id=\"verifyUrl\"></div>\n" | ||
| 153 | + " <div class=\"pollbar\"><i></i></div>\n" | ||
| 154 | + " <div class=\"polllbl\"><span class=\"spin\"></span><span id=\"pollLabel\">Waiting for approval</span></div>\n" | ||
| 155 | + " <div class=\"row\" style=\"margin-top:12px\">\n" | ||
| 156 | + " <button class=\"btn danger\" id=\"btnCancel\" type=\"button\">Cancel</button>\n" | ||
| 157 | + " </div>\n" | ||
| 158 | + " <div class=\"note\" id=\"flowNote\"></div>\n" | ||
| 159 | + " </div>\n" | ||
| 160 | + " </div>\n" | ||
| 161 | + "\n" | ||
| 162 | + " <footer>\n" | ||
| 163 | + " <span id=\"footInfo\">plugin_opencode_login</span>\n" | ||
| 164 | + " · <a href=\"https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-opencode-login\">source</a>\n" | ||
| 165 | + " </footer>\n" | ||
| 166 | + "</div>\n" | ||
| 167 | + "<script>\n" | ||
| 168 | + "(function(){\n" | ||
| 169 | + " var q=new URLSearchParams(location.search);\n" | ||
| 170 | + " var node=q.get('node')||'';\n" | ||
| 171 | + " var sid=q.get('id')||'';\n" | ||
| 172 | + " var HUB=q.get('plugin')||'';\n" | ||
| 173 | + " var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||localStorage.getItem('bot_active_pwd')||'';\n" | ||
| 174 | + " var POLL_MS=5000;\n" | ||
| 175 | + " var pollTimer=null;\n" | ||
| 176 | + " var flowActive=false;\n" | ||
| 177 | + " var flowVerify='';\n" | ||
| 178 | + " var flowCode='';\n" | ||
| 179 | + "\n" | ||
| 180 | + " function esc(s){return String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/\"/g,'"');}\n" | ||
| 181 | + " function $(id){return document.getElementById(id);}\n" | ||
| 182 | + " function setPill(cls,text){var p=$('pill');p.className='pill '+cls;$('pillText').textContent=text;}\n" | ||
| 183 | + " function note(id,cls,text){var n=$(id);if(!n)return;n.className='note '+(cls||'')+(text?' show':'');n.textContent=text||'';}\n" | ||
| 184 | + "\n" | ||
| 185 | + " function api(action,extra){\n" | ||
| 186 | + " var u;\n" | ||
| 187 | + " if(HUB) u='/plugins?plugin='+encodeURIComponent(HUB)+'&action='+encodeURIComponent(action);\n" | ||
| 188 | + " else u='/plugin_opencode_login?action='+encodeURIComponent(action);\n" | ||
| 189 | + " if(extra) u+='&'+extra;\n" | ||
| 190 | + " if(node) u+='&node='+encodeURIComponent(node);\n" | ||
| 191 | + " if(sid) u+='&id='+encodeURIComponent(sid);\n" | ||
| 192 | + " if(pwd) u+='&pwd='+encodeURIComponent(pwd);\n" | ||
| 193 | + " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){return r.json();});\n" | ||
| 194 | + " }\n" | ||
| 195 | + "\n" | ||
| 196 | + " function fmtExpiry(sec){\n" | ||
| 197 | + " if(sec==null||sec<=0)return 'unknown';\n" | ||
| 198 | + " if(sec<60)return sec+'s';\n" | ||
| 199 | + " var m=Math.floor(sec/60);\n" | ||
| 200 | + " if(m<60)return m+' min';\n" | ||
| 201 | + " var h=Math.floor(m/60);\n" | ||
| 202 | + " if(h<48)return h+' h '+(m%60)+' min';\n" | ||
| 203 | + " var d=Math.floor(h/24);\n" | ||
| 204 | + " return d+' days';\n" | ||
| 205 | + " }\n" | ||
| 206 | + "\n" | ||
| 207 | + " function renderStatus(d){\n" | ||
| 208 | + " if(!d||d.ok===false){setPill('off','Not Connected');note('sessionNote','err',d&&d.error?('Error: '+d.error):'No response');return;}\n" | ||
| 209 | + " var li=!!d.logged_in, ex=!!d.expired, pend=!!d.pending;\n" | ||
| 210 | + " if(li&&!ex){setPill('ok','Connected');}\n" | ||
| 211 | + " else if(li&&ex){setPill('warn','Expired');}\n" | ||
| 212 | + " else if(pend){setPill('warn','Signing in');}\n" | ||
| 213 | + " else{setPill('off','Not Connected');}\n" | ||
| 214 | + "\n" | ||
| 215 | + " $('vStatus').textContent=li?(ex?'Signed in (token expired)':'Signed in'):(pend?'Device flow in progress':'Not signed in');\n" | ||
| 216 | + " $('vAccount').textContent=d.account||d.username||'-';\n" | ||
| 217 | + " $('vToken').textContent=li?(ex?'expired ('+fmtExpiry(d.expires_in_sec)+')':'valid, expires in '+fmtExpiry(d.expires_in_sec)):'none';\n" | ||
| 218 | + " $('vRefresh').textContent=d.has_refresh?'stored (presence only)':'not stored';\n" | ||
| 219 | + " $('vProfile').textContent=d.profile_exists?(d.profile||'superopencode')+' (exists)':'not created';\n" | ||
| 220 | + " $('vPath').textContent=d.path||'-';\n" | ||
| 221 | + "\n" | ||
| 222 | + " var tok=$('tokLine');\n" | ||
| 223 | + " if(!d.cli_present){tok.innerHTML='<span class=\"no\">scorpiox-opencode-login is not on this node.</span>';}\n" | ||
| 224 | + " else{tok.innerHTML='<span class=\"ok\">Login CLI present</span> · token CLI '+(d.token_cli_present?'present':'missing');}\n" | ||
| 225 | + "\n" | ||
| 226 | + " var badge=$('userBadge');\n" | ||
| 227 | + " if(li){badge.hidden=false;var lbl=d.account||d.username||'OpenCode';$('userLabel').textContent=lbl;\n" | ||
| 228 | + " $('userAv').textContent=(lbl.charAt(0)||'O').toUpperCase();}\n" | ||
| 229 | + " else{badge.hidden=true;}\n" | ||
| 230 | + "\n" | ||
| 231 | + " $('btnRelogin').hidden=!li;\n" | ||
| 232 | + " $('btnStartLogin').disabled=pend;\n" | ||
| 233 | + "\n" | ||
| 234 | + " if(pend&&!flowActive){startPollingUI();}\n" | ||
| 235 | + " if(!pend&&flowActive){stopPollingUI();$('stepIdle').classList.add('on');$('stepActive').classList.remove('on');}\n" | ||
| 236 | + " if(!li&&!pend){note('sessionNote','ok','No session on this node yet. Start a device login below.');}\n" | ||
| 237 | + " else if(li&&!ex){note('sessionNote','ok','');}\n" | ||
| 238 | + " else if(li&&ex){note('sessionNote','err','Token expired. Re-login to refresh the session.');}\n" | ||
| 239 | + " }\n" | ||
| 240 | + "\n" | ||
| 241 | + " function refresh(){api('status').then(renderStatus).catch(function(e){setPill('off','Not Connected');note('sessionNote','err','Request failed: '+e);});}\n" | ||
| 242 | + "\n" | ||
| 243 | + " function startPollingUI(){\n" | ||
| 244 | + " flowActive=true;\n" | ||
| 245 | + " $('stepIdle').classList.remove('on');\n" | ||
| 246 | + " $('stepActive').classList.add('on');\n" | ||
| 247 | + " if(!pollTimer){pollTimer=setInterval(pollOnce,POLL_MS);}\n" | ||
| 248 | + " }\n" | ||
| 249 | + " function stopPollingUI(){\n" | ||
| 250 | + " flowActive=false;\n" | ||
| 251 | + " if(pollTimer){clearInterval(pollTimer);pollTimer=null;}\n" | ||
| 252 | + " }\n" | ||
| 253 | + "\n" | ||
| 254 | + " function pollOnce(){\n" | ||
| 255 | + " if(!flowActive)return;\n" | ||
| 256 | + " api('poll').then(function(d){\n" | ||
| 257 | + " if(!d||d.ok===false){note('flowNote','err',d&&d.error?('Poll error: '+d.error):'Poll failed');return;}\n" | ||
| 258 | + " if(d.state==='done'||d.logged_in){\n" | ||
| 259 | + " stopPollingUI();\n" | ||
| 260 | + " $('stepIdle').classList.add('on');\n" | ||
| 261 | + " $('stepActive').classList.remove('on');\n" | ||
| 262 | + " note('flowNote','ok','Signed in. The credential file has been written.');\n" | ||
| 263 | + " $('pollLabel').textContent='Signed in';\n" | ||
| 264 | + " refresh();\n" | ||
| 265 | + " }else if(d.state==='failed'){\n" | ||
| 266 | + " stopPollingUI();\n" | ||
| 267 | + " $('stepIdle').classList.add('on');\n" | ||
| 268 | + " $('stepActive').classList.remove('on');\n" | ||
| 269 | + " note('flowNote','err','Login failed: '+(d.error||'unknown')+(d.detail?(' - '+d.detail):''));\n" | ||
| 270 | + " }else{\n" | ||
| 271 | + " $('pollLabel').textContent='Waiting for approval';\n" | ||
| 272 | + " }\n" | ||
| 273 | + " }).catch(function(e){note('flowNote','err','Poll request failed: '+e);});\n" | ||
| 274 | + " }\n" | ||
| 275 | + "\n" | ||
| 276 | + " function doStart(force){\n" | ||
| 277 | + " note('sessionNote','ok','');\n" | ||
| 278 | + " api('start',force?'force=1':'').then(function(d){\n" | ||
| 279 | + " if(!d||d.ok===false){note('sessionNote','err',d&&d.error?('Start failed: '+d.error):'Start failed');return;}\n" | ||
| 280 | + " if(d.already_logged_in){\n" | ||
| 281 | + " note('sessionNote','warn','This node already has OpenCode credentials. Use Re-login to replace them.');\n" | ||
| 282 | + " refresh();\n" | ||
| 283 | + " return;\n" | ||
| 284 | + " }\n" | ||
| 285 | + " flowVerify=d.verify_url||'';\n" | ||
| 286 | + " flowCode=d.user_code||'';\n" | ||
| 287 | + " $('userCode').textContent=flowCode||'--';\n" | ||
| 288 | + " $('verifyUrl').textContent=flowVerify;\n" | ||
| 289 | + " $('pollLabel').textContent='Waiting for approval';\n" | ||
| 290 | + " note('flowNote','ok','');\n" | ||
| 291 | + " startPollingUI();\n" | ||
| 292 | + " refresh();\n" | ||
| 293 | + " }).catch(function(e){note('sessionNote','err','Start request failed: '+e);});\n" | ||
| 294 | + " }\n" | ||
| 295 | + "\n" | ||
| 296 | + " $('btnStartLogin').onclick=function(){doStart(false);};\n" | ||
| 297 | + " $('btnRelogin').onclick=function(){doStart(true);};\n" | ||
| 298 | + " $('btnCancel').onclick=function(){\n" | ||
| 299 | + " stopPollingUI();\n" | ||
| 300 | + " api('cancel').then(function(d){\n" | ||
| 301 | + " $('stepIdle').classList.add('on');\n" | ||
| 302 | + " $('stepActive').classList.remove('on');\n" | ||
| 303 | + " note('flowNote','ok',d&&d.ok?'Device flow cancelled.':'Cancel failed: '+(d&&d.error||'unknown'));\n" | ||
| 304 | + " refresh();\n" | ||
| 305 | + " }).catch(function(e){note('flowNote','err','Cancel request failed: '+e);});\n" | ||
| 306 | + " };\n" | ||
| 307 | + " $('btnRefresh').onclick=function(){\n" | ||
| 308 | + " note('sessionNote','ok','');\n" | ||
| 309 | + " api('refresh').then(function(d){\n" | ||
| 310 | + " if(!d||d.ok===false){note('sessionNote','err',d&&d.error?('Refresh failed: '+d.error):'Refresh failed');return;}\n" | ||
| 311 | + " note('sessionNote','ok','Token re-read. '+(d.refreshed?'CLI confirmed a live token.':''));\n" | ||
| 312 | + " renderStatus(d);\n" | ||
| 313 | + " }).catch(function(e){note('sessionNote','err','Refresh request failed: '+e);});\n" | ||
| 314 | + " };\n" | ||
| 315 | + " $('btnCopyOpen').onclick=function(){\n" | ||
| 316 | + " var done=function(){note('flowNote','ok','Code copied. Open the link and approve.');};\n" | ||
| 317 | + " if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(flowCode).then(done,function(){window.open(flowVerify,'_blank');done();});}\n" | ||
| 318 | + " else{done();}\n" | ||
| 319 | + " if(flowVerify)window.open(flowVerify,'_blank');\n" | ||
| 320 | + " };\n" | ||
| 321 | + "\n" | ||
| 322 | + " var tb=$('themeToggle');\n" | ||
| 323 | + " if(tb)tb.onclick=function(){\n" | ||
| 324 | + " if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');\n" | ||
| 325 | + " };\n" | ||
| 326 | + " $('footInfo').textContent='plugin_opencode_login';\n" | ||
| 327 | + " refresh();\n" | ||
| 328 | + "})();\n" | ||
| 329 | + "</script>\n" | ||
| 330 | + "\002</body></html>\n" | ||
| 331 | + ; | ||
| 332 | + | ||
| 333 | +#endif /* SX_AGYLOGIN_UI_HTML_H */ |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..dce3767 | index 0000000..dce3767 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/mock_login.sh | +++ b/tests/mock_login.sh | ||
| @@ -0,0 +1,114 @@ | @@ -0,0 +1,114 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/mock_login.sh - stand-in for scorpiox-opencode-login machine mode. | ||
| 3 | +# | ||
| 4 | +# Emits exactly the contract shape the real CLI emits (one JSON line last, all | ||
| 5 | +# human output before it), so the plugin's parsers are exercised against the | ||
| 6 | +# production layout rather than an invented one. The device exchange is | ||
| 7 | +# simulated: --poll writes a credential file into $OPENCODE_CREDS_PATH and | ||
| 8 | +# removes the pending marker when MOCK_APPROVE=1, which is what the real CLI | ||
| 9 | +# does after the user approves in the browser. | ||
| 10 | +# | ||
| 11 | +# MOCK_START_FAIL=1 --start answers the "credentials already exist" error | ||
| 12 | +# MOCK_APPROVE=1 --poll completes the flow | ||
| 13 | +# MOCK_DENY=1 --poll answers a terminal denial | ||
| 14 | +# MOCK_NO_PENDING=1 --poll answers no_pending even if a marker exists | ||
| 15 | + | ||
| 16 | +CREDS="${OPENCODE_CREDS_PATH:-/nonexistent-auth.json}" | ||
| 17 | +PEND="${OPENCODE_PENDING_PATH:-/nonexistent-pending.json}" | ||
| 18 | + | ||
| 19 | +# pyget <file> <key> -> the value, or empty string when absent/unreadable | ||
| 20 | +pyget() { | ||
| 21 | + python3 - "$1" "$2" <<'PY' | ||
| 22 | +import json, sys | ||
| 23 | +try: | ||
| 24 | + with open(sys.argv[1]) as f: | ||
| 25 | + d = json.load(f) | ||
| 26 | +except Exception: | ||
| 27 | + d = {} | ||
| 28 | +v = d.get(sys.argv[2]) if isinstance(d, dict) else None | ||
| 29 | +if v is None: | ||
| 30 | + print("") | ||
| 31 | +elif isinstance(v, bool): | ||
| 32 | + print("true" if v else "false") | ||
| 33 | +else: | ||
| 34 | + print(v) | ||
| 35 | +PY | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +jstr() { # jstr <value> -> "value" or null | ||
| 39 | + if [ -z "$1" ]; then printf 'null'; else printf '"%s"' "$1"; fi | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +case "$1" in | ||
| 43 | + --status) | ||
| 44 | + _li=false; _hr=false; _exp=0; _org=""; _pend=false | ||
| 45 | + if [ -f "$CREDS" ]; then | ||
| 46 | + _tok=$(pyget "$CREDS" access_token) | ||
| 47 | + [ -n "$_tok" ] && _li=true | ||
| 48 | + _rt=$(pyget "$CREDS" refresh_token) | ||
| 49 | + [ -n "$_rt" ] && _hr=true | ||
| 50 | + _exp=$(pyget "$CREDS" expires_at) | ||
| 51 | + [ -z "$_exp" ] && _exp=0 | ||
| 52 | + _org=$(pyget "$CREDS" org_id) | ||
| 53 | + fi | ||
| 54 | + [ -f "$PEND" ] && _pend=true | ||
| 55 | + printf 'scorpiox-opencode-login 1.0.0 (SXLOGIN-MACHINE-V1)\n' | ||
| 56 | + printf '{"ok":true,"provider":"opencode","name":"OpenCode","flow":"device_code",' | ||
| 57 | + printf '"account":%s,"logged_in":%s,"path":"%s",' "$(jstr "$_org")" "$_li" "$CREDS" | ||
| 58 | + printf '"expires_at":%s,"expired":false,"has_refresh":%s,"pending":%s,' "$_exp" "$_hr" "$_pend" | ||
| 59 | + printf '"profile":"superopencode","profile_exists":false,"named_accounts":false,' | ||
| 60 | + printf '"protocol":"SXLOGIN-MACHINE-V1"}\n' | ||
| 61 | + ;; | ||
| 62 | + --start) | ||
| 63 | + if [ "$MOCK_START_FAIL" = "1" ]; then | ||
| 64 | + printf '{"ok":false,"provider":"opencode","error":"exists","detail":"credentials already exist; pass --force to replace"}\n' | ||
| 65 | + exit 0 | ||
| 66 | + fi | ||
| 67 | + if [ "$MOCK_START_NETFAIL" = "1" ]; then | ||
| 68 | + printf '{"ok":false,"provider":"opencode","error":"network","detail":"device code request failed"}\n' | ||
| 69 | + exit 0 | ||
| 70 | + fi | ||
| 71 | + mkdir -p "$(dirname "$PEND")" 2>/dev/null || : | ||
| 72 | + printf '{"device_code":"oc-mock-device-code-must-not-leak","interval":5,"force":0,"created":%s}\n' \ | ||
| 73 | + "$(date +%s)" > "$PEND" | ||
| 74 | + printf '{"ok":true,"provider":"opencode","flow":"device_code",' | ||
| 75 | + printf '"verify_url":"https://opencode.ai/console/device?user_code=ABCD-EFGH&client_id=opencode-cli",' | ||
| 76 | + printf '"user_code":"ABCD-EFGH","expires_in":900}\n' | ||
| 77 | + ;; | ||
| 78 | + --poll) | ||
| 79 | + if [ "$MOCK_APPROVE" = "1" ]; then | ||
| 80 | + mkdir -p "$(dirname "$CREDS")" 2>/dev/null || : | ||
| 81 | + # one redirection for the whole block: in POSIX sh a redirect attaches | ||
| 82 | + # to a single command, so three separate printfs would write two lines | ||
| 83 | + # to stdout and only the last one to the credential file. | ||
| 84 | + { | ||
| 85 | + printf '{"access_token":"oc-mock-access-token-must-not-leak",' | ||
| 86 | + printf '"refresh_token":"oc-mock-refresh-token-must-not-leak","token_type":"Bearer",' | ||
| 87 | + printf '"expires_in":2591999,"expires_at":%s,"org_id":"org-mock-42"}\n' \ | ||
| 88 | + "$(( $(date +%s) + 2591999 ))" | ||
| 89 | + } > "$CREDS" | ||
| 90 | + rm -f "$PEND" | ||
| 91 | + printf 'Logged in successfully!\n' | ||
| 92 | + printf '{"ok":true,"provider":"opencode","state":"done","logged_in":true,' | ||
| 93 | + printf '"path":"%s","profile":"superopencode","profile_created":false}\n' "$CREDS" | ||
| 94 | + exit 0 | ||
| 95 | + fi | ||
| 96 | + if [ "$MOCK_DENY" = "1" ]; then | ||
| 97 | + rm -f "$PEND" | ||
| 98 | + printf '{"ok":false,"provider":"opencode","error":"denied","detail":"access_denied"}\n' | ||
| 99 | + exit 0 | ||
| 100 | + fi | ||
| 101 | + if [ ! -f "$PEND" ] || [ "$MOCK_NO_PENDING" = "1" ]; then | ||
| 102 | + printf '{"ok":false,"provider":"opencode","error":"no_pending","detail":"run --start first"}\n' | ||
| 103 | + exit 0 | ||
| 104 | + fi | ||
| 105 | + printf '{"ok":true,"provider":"opencode","state":"pending","interval":5}\n' | ||
| 106 | + ;; | ||
| 107 | + --cancel) | ||
| 108 | + rm -f "$PEND" | ||
| 109 | + printf '{"ok":true,"provider":"opencode","cancelled":true}\n' | ||
| 110 | + ;; | ||
| 111 | + *) | ||
| 112 | + printf '{"ok":false,"provider":"opencode","error":"usage","detail":"unknown flag"}\n' | ||
| 113 | + ;; | ||
| 114 | +esac |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..9bbb8c6 | index 0000000..9bbb8c6 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/mock_token.sh | +++ b/tests/mock_token.sh | ||
| @@ -0,0 +1,50 @@ | @@ -0,0 +1,50 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/mock_token.sh - stand-in for scorpiox-opencode-fetchtoken. | ||
| 3 | +# | ||
| 4 | +# The real CLI reads ~/.config/opencode/auth.json and prints | ||
| 5 | +# {"access_token":"...","org_id":"...","expires_at":1234567890} | ||
| 6 | +# The plugin only ever looks at access_token presence and expires_at, so this | ||
| 7 | +# mock mirrors that shape and reads the same credential file the login mock | ||
| 8 | +# writes, which makes a "refresh after login" test behave like a real node. | ||
| 9 | +# | ||
| 10 | +# MOCK_TOKEN_FAIL=1 exit non-zero with an error on stderr (no token) | ||
| 11 | + | ||
| 12 | +CREDS="${OPENCODE_CREDS_PATH:-/nonexistent-auth.json}" | ||
| 13 | + | ||
| 14 | +case "$1" in | ||
| 15 | + --help|-h) | ||
| 16 | + printf 'usage: scorpiox-opencode-fetchtoken [-local|-config|-tcp|-remote]\n' | ||
| 17 | + ;; | ||
| 18 | + -local|""|-config) | ||
| 19 | + if [ "$MOCK_TOKEN_FAIL" = "1" ]; then | ||
| 20 | + printf 'error: auth file not found: %s\n' "$CREDS" >&2 | ||
| 21 | + exit 1 | ||
| 22 | + fi | ||
| 23 | + if [ ! -f "$CREDS" ]; then | ||
| 24 | + printf 'error: auth file not found: %s\n' "$CREDS" >&2 | ||
| 25 | + exit 1 | ||
| 26 | + fi | ||
| 27 | + python3 - "$CREDS" <<'PY' | ||
| 28 | +import json, sys, time | ||
| 29 | +try: | ||
| 30 | + with open(sys.argv[1]) as f: | ||
| 31 | + d = json.load(f) | ||
| 32 | +except Exception: | ||
| 33 | + d = {} | ||
| 34 | +tok = d.get("access_token") or "" | ||
| 35 | +exp = d.get("expires_at") or 0 | ||
| 36 | +if not exp and d.get("expires_in"): | ||
| 37 | + exp = int(time.time()) + int(d["expires_in"]) | ||
| 38 | +if not tok: | ||
| 39 | + sys.stderr.write("error: no access_token in auth file\n") | ||
| 40 | + sys.exit(1) | ||
| 41 | +print(json.dumps({"access_token": tok, | ||
| 42 | + "org_id": d.get("org_id") or "", | ||
| 43 | + "expires_at": int(exp)})) | ||
| 44 | +PY | ||
| 45 | + ;; | ||
| 46 | + *) | ||
| 47 | + printf 'error: unknown mode %s\n' "$1" >&2 | ||
| 48 | + exit 2 | ||
| 49 | + ;; | ||
| 50 | +esac |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..2686f18 | index 0000000..2686f18 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,562 @@ | @@ -0,0 +1,562 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_opencode_login across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Every check runs against ./plugin_opencode_login with the credential paths | ||
| 5 | +# and both CLIs redirected at throwaway fixtures, so the suite proves the public | ||
| 6 | +# contract without touching a real OpenCode session and without a network. | ||
| 7 | +# | ||
| 8 | +# What it proves: | ||
| 9 | +# - --meta is exactly {"name":"opencode","desc":"OpenCode 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 reads the credential json, the pending marker and the CLI answer | ||
| 13 | +# and never emits a token | ||
| 14 | +# - start returns the CLI's verify_url + user_code; poll walks pending -> | ||
| 15 | +# done and re-reads state; a dead flow reports failed, not an infinite | ||
| 16 | +# spinner; cancel clears the marker | ||
| 17 | +# - refresh re-reads the token through the token CLI and drops the value | ||
| 18 | +# - the HTML page carries the bot theme handoff, no CDN and no <script src=> | ||
| 19 | +# - the source has no hard-coded secret, no internal address and no emoji | ||
| 20 | +# | ||
| 21 | +# Exit code 0 = everything passed. | ||
| 22 | + | ||
| 23 | +set -u | ||
| 24 | + | ||
| 25 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 26 | +cd "$ROOT" || exit 1 | ||
| 27 | + | ||
| 28 | +BIN=./plugin_opencode_login | ||
| 29 | +ID=plugin_opencode_login | ||
| 30 | +PASS=0 | ||
| 31 | +FAIL=0 | ||
| 32 | + | ||
| 33 | +# A token planted in the fixtures that must never surface in any response. | ||
| 34 | +SECRET="oc-mock-access-token-must-not-leak" | ||
| 35 | +REFRESH_SECRET="oc-mock-refresh-token-must-not-leak" | ||
| 36 | +DEVICE_SECRET="oc-mock-device-code-must-not-leak" | ||
| 37 | + | ||
| 38 | +if [ -t 1 ]; then | ||
| 39 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 40 | +else | ||
| 41 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 42 | +fi | ||
| 43 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 44 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 45 | + | ||
| 46 | +check() { # check <desc> <expected-substring> <actual> | ||
| 47 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 48 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | ||
| 49 | + fi | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 53 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 54 | + fail "$1 (must NOT contain: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | ||
| 55 | + else pass "$1" | ||
| 56 | + fi | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 60 | + | ||
| 61 | +# strip CGI headers if present, drop CRs, keep the payload | ||
| 62 | +body() { | ||
| 63 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 64 | + BEGIN { inhdr = 0 } | ||
| 65 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next } | ||
| 66 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 67 | + inhdr { next } | ||
| 68 | + { print } | ||
| 69 | + ' | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +json_ok() { # json_ok <desc> <json> [python-expression] | ||
| 73 | + expr=${3:-True} | ||
| 74 | + 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 | ||
| 75 | + pass "$1" | ||
| 76 | + else | ||
| 77 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 78 | + fi | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | ||
| 82 | +apiraw() { QUERY_STRING="$1" $BIN; } | ||
| 83 | + | ||
| 84 | +# ---------------------------------------------------------------- build | ||
| 85 | +section "build" | ||
| 86 | +if [ ! -x "$BIN" ]; then | ||
| 87 | + echo " building native binary..." | ||
| 88 | + gcc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_opencode_login.c || { | ||
| 89 | + fail "native build"; exit 1; } | ||
| 90 | +fi | ||
| 91 | +pass "native binary present" | ||
| 92 | + | ||
| 93 | +# generated page header must match src/ui.html | ||
| 94 | +if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | ||
| 95 | + pass "src/ui_html.h is in sync with src/ui.html" | ||
| 96 | +else | ||
| 97 | + fail "src/ui_html.h is stale - run tools/gen_ui.py" | ||
| 98 | +fi | ||
| 99 | + | ||
| 100 | +# the page header must not be hand-edited: it is generated from ui.html | ||
| 101 | +check "ui header is marked generated" \ | ||
| 102 | + "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)" | ||
| 103 | + | ||
| 104 | +# ---------------------------------------------------------------- fixtures | ||
| 105 | +FIX=$(mktemp -d 2>/dev/null || mktemp -d -t ocfix) | ||
| 106 | +trap 'rm -rf "$FIX"' EXIT | ||
| 107 | + | ||
| 108 | +NOW=$(date +%s) | ||
| 109 | +FUT=$((NOW + 86400)) | ||
| 110 | +PAST=$((NOW - 3600)) | ||
| 111 | + | ||
| 112 | +mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" "$FIX/expired" "$FIX/alt/.opencode" "$FIX/alt/.config/opencode" "$FIX/pending" "$FIX/env" | ||
| 113 | +export OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" | ||
| 114 | +export OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" | ||
| 115 | +export OPENCODE_PENDING_PATH="$FIX/pending/opencode-default.json" | ||
| 116 | +export OPENCODE_ENV_DIR="$FIX/env" | ||
| 117 | + | ||
| 118 | +# empty credentials file (exists but holds no token) | ||
| 119 | +: > "$FIX/empty/auth.json" | ||
| 120 | + | ||
| 121 | +# a live session: token, refresh token, org, future expiry | ||
| 122 | +printf '{"access_token":"%s","refresh_token":"%s","token_type":"Bearer","expires_in":2591999,"expires_at":%s,"org_id":"org-mock-42"}\n' \ | ||
| 123 | + "$SECRET" "$REFRESH_SECRET" "$FUT" > "$FIX/full/auth.json" | ||
| 124 | + | ||
| 125 | +# an expired session | ||
| 126 | +printf '{"access_token":"%s","refresh_token":"%s","token_type":"Bearer","expires_at":%s,"org_id":"org-mock-42"}\n' \ | ||
| 127 | + "$SECRET" "$REFRESH_SECRET" "$PAST" > "$FIX/expired/auth.json" | ||
| 128 | + | ||
| 129 | +# the secondary ~/.opencode/token.json layout the spec names | ||
| 130 | +printf '{"access_token":"%s","expires_at":%s}\n' "$SECRET" "$FUT" > "$FIX/alt/.opencode/token.json" | ||
| 131 | + | ||
| 132 | +# The pending device flow marker is written per section, exactly as the CLI | ||
| 133 | +# writes it, so a test that expects "nothing pending" never sees a leftover. | ||
| 134 | + | ||
| 135 | +# ---------------------------------------------------------------- metadata | ||
| 136 | +section "--meta / discovery" | ||
| 137 | +META=$($BIN --meta) | ||
| 138 | +check "--meta via argv" '"name":"opencode"' "$META" | ||
| 139 | +check "--meta desc" '"desc":"OpenCode login"' "$META" | ||
| 140 | +check_not "--meta leaks nothing else" "expires" "$META" | ||
| 141 | +METAENV=$(SX_PLUGIN_META=1 $BIN) | ||
| 142 | +check "--meta via SX_PLUGIN_META" '"name":"opencode"' "$METAENV" | ||
| 143 | +json_ok "--meta is a valid JSON object" "$META" "isinstance(d,dict) and d['name']=='opencode' and d['desc']=='OpenCode login'" | ||
| 144 | +# 1-word title, 14-char desc (the market contract floor) | ||
| 145 | +check_not "--meta title is one word" '"name":"opencode login"' "$META" | ||
| 146 | +DESCLEN=$(printf '%s' "OpenCode login" | wc -c) | ||
| 147 | +if [ "$DESCLEN" -le 15 ]; then pass "desc fits the 15-char limit ($DESCLEN)"; else fail "desc too long ($DESCLEN)"; fi | ||
| 148 | + | ||
| 149 | +VERSION=$($BIN --version) | ||
| 150 | +check "--version reports the id" "plugin_opencode_login 1.0.0" "$VERSION" | ||
| 151 | + | ||
| 152 | +# ---------------------------------------------------------------- auth gate | ||
| 153 | +section "node auth gate" | ||
| 154 | +export BOT_PASSWORD=test-node-password | ||
| 155 | +NOAUTH=$(QUERY_STRING="action=status" $BIN) | ||
| 156 | +check "unauthenticated status is 401" "Status: 401 Unauthorized" "$NOAUTH" | ||
| 157 | +check "401 body says invalid node password" "invalid node password" "$NOAUTH" | ||
| 158 | +check_not "401 does not leak the password" "test-node-password" "$NOAUTH" | ||
| 159 | +for a in start poll cancel refresh; do | ||
| 160 | + check "action=$a is gated" "Status: 401" "$(QUERY_STRING="action=$a" $BIN)" | ||
| 161 | +done | ||
| 162 | +check "meta stays open without a password" '"name":"opencode"' "$($BIN --meta)" | ||
| 163 | +check "password via ?pwd= is accepted" '"ok":true' "$(QUERY_STRING="action=status&pwd=test-node-password" $BIN)" | ||
| 164 | +check "password via X-Bot-Password is accepted" '"ok":true' \ | ||
| 165 | + "$(HTTP_X_BOT_PASSWORD=test-node-password QUERY_STRING="action=status" $BIN)" | ||
| 166 | +check "password via Bearer is accepted" '"ok":true' \ | ||
| 167 | + "$(HTTP_AUTHORIZATION='Bearer test-node-password' QUERY_STRING="action=status" $BIN)" | ||
| 168 | +check "wrong password still 401s" "Status: 401" "$(QUERY_STRING="action=status&pwd=wrong" $BIN)" | ||
| 169 | +BODYAUTH=$(printf '{"a":1}' | CONTENT_LENGTH=9 QUERY_STRING="action=status" $BIN) | ||
| 170 | +check "a POST body does not bypass the gate" "Status: 401" "$BODYAUTH" | ||
| 171 | +unset BOT_PASSWORD | ||
| 172 | + | ||
| 173 | +# ---------------------------------------------------------------- status: no session | ||
| 174 | +section "status - no session" | ||
| 175 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 176 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | ||
| 177 | +S=$(api "action=status") | ||
| 178 | +json_ok "status with no credential file is valid JSON" "$S" "d['ok'] is True and d['logged_in'] is False" | ||
| 179 | +check "no session reports logged_in false" '"logged_in":false' "$S" | ||
| 180 | +check "no session reports pending false" '"pending":false' "$S" | ||
| 181 | +check "no session reports has_refresh false" '"has_refresh":false' "$S" | ||
| 182 | +check "no session reports expires_at 0" '"expires_at":0' "$S" | ||
| 183 | +check "no session reports expired false" '"expired":false' "$S" | ||
| 184 | +check "no session names the CLI protocol" '"protocol":"SXLOGIN-MACHINE-V1"' "$S" | ||
| 185 | +check "no session reports the CLI present" '"cli_present":true' "$S" | ||
| 186 | +check "no session reports the token CLI" '"token_cli_present":true' "$S" | ||
| 187 | +check_not "empty status leaks no token" "$SECRET" "$S" | ||
| 188 | + | ||
| 189 | +# ---------------------------------------------------------------- status: empty file | ||
| 190 | +section "status - empty credential file" | ||
| 191 | +export OPENCODE_CREDS_PATH="$FIX/empty/auth.json" | ||
| 192 | +S=$(api "action=status") | ||
| 193 | +json_ok "empty credential file is not a session" "$S" "d['logged_in'] is False" | ||
| 194 | +check "empty file still reports a path" "$FIX/empty/auth.json" "$S" | ||
| 195 | + | ||
| 196 | +# ---------------------------------------------------------------- status: live session | ||
| 197 | +section "status - live session" | ||
| 198 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 199 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | ||
| 200 | +S=$(api "action=status") | ||
| 201 | +json_ok "live session is valid JSON" "$S" "d['ok'] is True and d['logged_in'] is True" | ||
| 202 | +check "live session reports logged_in true" '"logged_in":true' "$S" | ||
| 203 | +check "live session reports has_refresh" '"has_refresh":true' "$S" | ||
| 204 | +check "live session reports expired false" '"expired":false' "$S" | ||
| 205 | +check "live session carries the org account" '"account":"org-mock-42"' "$S" | ||
| 206 | +check "live session carries org_id" '"org_id":"org-mock-42"' "$S" | ||
| 207 | +check "live session carries a username" '"username":"org-mock-42"' "$S" | ||
| 208 | +json_ok "live session expiry is in the future" "$S" "d['expires_in_sec'] > 80000 and d['expires_at'] > 0" | ||
| 209 | +check "live session names the profile" '"profile":"superopencode"' "$S" | ||
| 210 | +check_not "status never prints the access token" "$SECRET" "$S" | ||
| 211 | +check_not "status never prints the refresh token" "$REFRESH_SECRET" "$S" | ||
| 212 | +check_not "status never uses the word access_token" "access_token" "$S" | ||
| 213 | +check_not "status never uses the word refresh_token" "refresh_token" "$S" | ||
| 214 | + | ||
| 215 | +# ---------------------------------------------------------------- status: expired | ||
| 216 | +section "status - expired session" | ||
| 217 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 218 | +export OPENCODE_CREDS_PATH="$FIX/expired/auth.json" | ||
| 219 | +S=$(api "action=status") | ||
| 220 | +json_ok "expired session is still reported" "$S" "d['logged_in'] is True and d['expired'] is True" | ||
| 221 | +check "expired session flags expired true" '"expired":true' "$S" | ||
| 222 | +json_ok "expired session reports a negative window" "$S" "d['expires_in_sec'] < 0" | ||
| 223 | +check_not "expired status leaks no token" "$SECRET" "$S" | ||
| 224 | + | ||
| 225 | +# ---------------------------------------------------------------- status: pending marker | ||
| 226 | +section "status - pending device flow" | ||
| 227 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \ | ||
| 228 | + > "$FIX/pending/opencode-default.json" | ||
| 229 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | ||
| 230 | +S=$(api "action=status") | ||
| 231 | +check "a marker file means pending true" '"pending":true' "$S" | ||
| 232 | +check "pending reports its age" '"pending_age_sec":' "$S" | ||
| 233 | +check_not "pending status does not leak the device code" "$DEVICE_SECRET" "$S" | ||
| 234 | +# a stale marker (older than the CLI's 900 s TTL) must not keep the spinner on | ||
| 235 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$((NOW - 1200))" \ | ||
| 236 | + > "$FIX/pending/opencode-default.json" | ||
| 237 | +S=$(api "action=status") | ||
| 238 | +json_ok "a stale marker is not pending" "$S" "d['pending'] is False" | ||
| 239 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 240 | + | ||
| 241 | +# ---------------------------------------------------------------- status: format=json | ||
| 242 | +section "format=json is status" | ||
| 243 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 244 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | ||
| 245 | +S=$(api "format=json") | ||
| 246 | +json_ok "format=json alone returns a status object" "$S" "d['ok'] is True and 'logged_in' in d" | ||
| 247 | +S=$(api "action=status&format=json") | ||
| 248 | +json_ok "action and format together still work" "$S" "d['logged_in'] is True" | ||
| 249 | +S=$(apiraw "action=unknown") | ||
| 250 | +check "an unknown action is a 400" "Status: 400 Bad Request" "$S" | ||
| 251 | +check "unknown action names the valid ones" "expected status, start, poll, cancel or refresh" "$S" | ||
| 252 | + | ||
| 253 | +# ---------------------------------------------------------------- status: alt path | ||
| 254 | +section "secondary credential location" | ||
| 255 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 256 | +# No OPENCODE_CREDS_PATH override: the plugin must fall back to | ||
| 257 | +# $HOME/.opencode/token.json when ~/.config/opencode/auth.json is absent. | ||
| 258 | +unset OPENCODE_CREDS_PATH | ||
| 259 | +export HOME="$FIX/alt" | ||
| 260 | +mkdir -p "$FIX/alt/.config/opencode" | ||
| 261 | +S=$(api "action=status") | ||
| 262 | +json_ok "the ~/.opencode/token.json fallback is read" "$S" "d['logged_in'] is True" | ||
| 263 | +check "the fallback path is reported" "$FIX/alt/.opencode/token.json" "$S" | ||
| 264 | +check_not "the fallback status leaks no token" "$SECRET" "$S" | ||
| 265 | +# the primary file wins when both exist | ||
| 266 | +printf '{"access_token":"%s","expires_at":%s,"org_id":"org-primary"}\n' "$SECRET" "$FUT" \ | ||
| 267 | + > "$FIX/alt/.config/opencode/auth.json" | ||
| 268 | +S=$(api "action=status") | ||
| 269 | +check "the primary credential file wins" "org-primary" "$S" | ||
| 270 | +export HOME=/root | ||
| 271 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | ||
| 272 | + | ||
| 273 | +# ---------------------------------------------------------------- start | ||
| 274 | +section "start - device flow" | ||
| 275 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 276 | +S=$(api "action=start") | ||
| 277 | +json_ok "start returns a device_code flow" "$S" "d['ok'] is True and d['flow']=='device_code'" | ||
| 278 | +check "start hands back the verify url" "https://opencode.ai/console/device" "$S" | ||
| 279 | +check "start hands back the user code" '"user_code":"ABCD-EFGH"' "$S" | ||
| 280 | +check "start reports pending true" '"pending":true' "$S" | ||
| 281 | +json_ok "start reports an expiry window" "$S" "d['expires_in'] >= 60" | ||
| 282 | +check_not "start does not leak the device code" "$DEVICE_SECRET" "$S" | ||
| 283 | +check_not "start leaks no token" "$SECRET" "$S" | ||
| 284 | + | ||
| 285 | +# start when credentials already exist | ||
| 286 | +export MOCK_START_FAIL=1 | ||
| 287 | +S=$(api "action=start") | ||
| 288 | +unset MOCK_START_FAIL | ||
| 289 | +json_ok "an existing session is reported, not a crash" "$S" "d.get('already_logged_in') is True" | ||
| 290 | +check "existing session tells the user to re-login" "already_logged_in" "$S" | ||
| 291 | +check "existing session hints at force" "force=1" "$S" | ||
| 292 | +S=$(api "action=start&force=1") | ||
| 293 | +check "force=1 starts over an existing session" '"user_code":"ABCD-EFGH"' "$S" | ||
| 294 | +export MOCK_START_NETFAIL=1 | ||
| 295 | +S=$(api "action=start") | ||
| 296 | +unset MOCK_START_NETFAIL | ||
| 297 | +check "a network failure surfaces as an error" '"error":"network"' "$S" | ||
| 298 | + | ||
| 299 | +# ---------------------------------------------------------------- poll | ||
| 300 | +section "poll - pending then done" | ||
| 301 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 302 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \ | ||
| 303 | + > "$FIX/pending/opencode-default.json" | ||
| 304 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | ||
| 305 | +S=$(api "action=poll") | ||
| 306 | +json_ok "poll while waiting is pending" "$S" "d['ok'] is True and d['state']=='pending'" | ||
| 307 | +check "pending poll says logged_in false" '"logged_in":false' "$S" | ||
| 308 | +check "pending poll carries an interval" '"interval":5' "$S" | ||
| 309 | +check_not "pending poll leaks no secret" "$DEVICE_SECRET" "$S" | ||
| 310 | + | ||
| 311 | +# approval: the mock CLI writes the credential file and clears the marker | ||
| 312 | +export MOCK_APPROVE=1 | ||
| 313 | +rm -f "$FIX/full2" ; mkdir -p "$FIX/full2" | ||
| 314 | +export OPENCODE_CREDS_PATH="$FIX/full2/auth.json" | ||
| 315 | +S=$(api "action=poll") | ||
| 316 | +json_ok "poll after approval is done" "$S" "d['ok'] is True and d['state']=='done' and d['logged_in'] is True" | ||
| 317 | +check "done poll reports a live session" '"logged_in":true' "$S" | ||
| 318 | +check "done poll carries the fresh expiry" '"expires_in_sec":' "$S" | ||
| 319 | +check_not "done poll does not print the token" "$SECRET" "$S" | ||
| 320 | +check_not "done poll does not print the refresh token" "$REFRESH_SECRET" "$S" | ||
| 321 | +unset MOCK_APPROVE | ||
| 322 | +rm -f "$FIX/full2/auth.json" | ||
| 323 | + | ||
| 324 | +# a denied flow is terminal | ||
| 325 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \ | ||
| 326 | + > "$FIX/pending/opencode-default.json" | ||
| 327 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | ||
| 328 | +export MOCK_DENY=1 | ||
| 329 | +S=$(api "action=poll") | ||
| 330 | +unset MOCK_DENY | ||
| 331 | +json_ok "a denial is reported as a failed state" "$S" "d['ok'] is True and d['state']=='failed'" | ||
| 332 | +check "a denial names the error" '"error":"denied"' "$S" | ||
| 333 | +check "a denial clears pending" '"pending":false' "$S" | ||
| 334 | + | ||
| 335 | +# no pending marker at all | ||
| 336 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 337 | +export MOCK_NO_PENDING=1 | ||
| 338 | +S=$(api "action=poll") | ||
| 339 | +unset MOCK_NO_PENDING | ||
| 340 | +json_ok "polling with nothing pending fails cleanly" "$S" "d['state']=='failed'" | ||
| 341 | +check "nothing-pending explains itself" "run --start first" "$S" | ||
| 342 | + | ||
| 343 | +# ---------------------------------------------------------------- cancel | ||
| 344 | +section "cancel" | ||
| 345 | +printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \ | ||
| 346 | + > "$FIX/pending/opencode-default.json" | ||
| 347 | +S=$(api "action=cancel") | ||
| 348 | +json_ok "cancel succeeds" "$S" "d['ok'] is True and d['state']=='cancelled'" | ||
| 349 | +check "cancel clears pending" '"pending":false' "$S" | ||
| 350 | +if [ -f "$FIX/pending/opencode-default.json" ]; then | ||
| 351 | + fail "cancel removed the marker file" | ||
| 352 | +else | ||
| 353 | + pass "cancel removed the marker file" | ||
| 354 | +fi | ||
| 355 | +check_not "cancel leaks no device code" "$DEVICE_SECRET" "$S" | ||
| 356 | + | ||
| 357 | +# ---------------------------------------------------------------- refresh | ||
| 358 | +section "refresh" | ||
| 359 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 360 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | ||
| 361 | +S=$(api "action=refresh") | ||
| 362 | +json_ok "refresh succeeds on a live session" "$S" "d['ok'] is True and d['refreshed'] is True" | ||
| 363 | +check "refresh reports the session again" '"logged_in":true' "$S" | ||
| 364 | +check "refresh keeps the org account" '"account":"org-mock-42"' "$S" | ||
| 365 | +check_not "refresh never prints the token" "$SECRET" "$S" | ||
| 366 | +check_not "refresh never prints the refresh token" "$REFRESH_SECRET" "$S" | ||
| 367 | + | ||
| 368 | +# refresh with no session | ||
| 369 | +export OPENCODE_CREDS_PATH="$FIX/none/auth.json" | ||
| 370 | +S=$(api "action=refresh") | ||
| 371 | +json_ok "refresh without a session is a clean error" "$S" "d['ok'] is False and d['error']=='not_logged_in'" | ||
| 372 | + | ||
| 373 | +# refresh when the token CLI fails | ||
| 374 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | ||
| 375 | +export MOCK_TOKEN_FAIL=1 | ||
| 376 | +S=$(api "action=refresh") | ||
| 377 | +unset MOCK_TOKEN_FAIL | ||
| 378 | +json_ok "a failing token CLI is a clean error" "$S" "d['ok'] is False and d['error']=='refresh_failed'" | ||
| 379 | +check_not "a failing refresh leaks no token" "$SECRET" "$S" | ||
| 380 | + | ||
| 381 | +# ---------------------------------------------------------------- missing CLIs | ||
| 382 | +section "missing CLIs" | ||
| 383 | +rm -f "$FIX/pending/opencode-default.json" | ||
| 384 | +export OPENCODE_LOGIN_BIN="$FIX/definitely-not-a-binary" | ||
| 385 | +export OPENCODE_TOKEN_BIN="$FIX/definitely-not-a-binary" | ||
| 386 | +export OPENCODE_CREDS_PATH="$FIX/full/auth.json" | ||
| 387 | +S=$(api "action=status") | ||
| 388 | +json_ok "status survives a missing login CLI" "$S" "d['ok'] is True" | ||
| 389 | +check "a missing CLI is reported honestly" '"cli_present":false' "$S" | ||
| 390 | +check "a missing CLI names itself" '"cli_error":"cli_not_found"' "$S" | ||
| 391 | +check "the file-derived session is still reported" '"logged_in":true' "$S" | ||
| 392 | +S=$(apiraw "action=start") | ||
| 393 | +check "start on a missing CLI is cli_unavailable" '"error":"cli_unavailable"' "$S" | ||
| 394 | +check_not "start on a missing CLI is not a 500" "Status: 5" "$S" | ||
| 395 | +S=$(api "action=poll") | ||
| 396 | +check "poll on a missing CLI is cli_unavailable" '"error":"cli_unavailable"' "$S" | ||
| 397 | +S=$(api "action=refresh") | ||
| 398 | +check "refresh on a missing CLI is refresh_unavailable" '"error":"refresh_unavailable"' "$S" | ||
| 399 | +S=$(api "action=cancel") | ||
| 400 | +check "cancel on a missing CLI still clears pending" '"pending":false' "$S" | ||
| 401 | +export OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" | ||
| 402 | +export OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" | ||
| 403 | + | ||
| 404 | +# ---------------------------------------------------------------- HTML | ||
| 405 | +section "HTML UI" | ||
| 406 | +HTML=$(body "$(QUERY_STRING="" $BIN)") | ||
| 407 | +check "page is a real document" "<!DOCTYPE html>" "$HTML" | ||
| 408 | +check "page titles the tool" "<title>opencode</title>" "$HTML" | ||
| 409 | +check "page has the status pill" 'id="pill"' "$HTML" | ||
| 410 | +check "page has the user badge" 'id="userBadge"' "$HTML" | ||
| 411 | +check "page has the start button" 'id="btnStartLogin"' "$HTML" | ||
| 412 | +check "page has the copy button" 'id="btnCopyOpen"' "$HTML" | ||
| 413 | +check "page has the user code box" 'id="userCode"' "$HTML" | ||
| 414 | +check "page has the poll indicator" 'id="pollLabel"' "$HTML" | ||
| 415 | +check "page has the cancel button" 'id="btnCancel"' "$HTML" | ||
| 416 | +check "page has the refresh button" 'id="btnRefresh"' "$HTML" | ||
| 417 | +check "page has the re-login button" 'id="btnRelogin"' "$HTML" | ||
| 418 | +check "page names the device flow" "Device Flow" "$HTML" | ||
| 419 | +check "page carries the copy label" "Copy Code" "$HTML" | ||
| 420 | +check "page uses the bot theme handoff" "sx-theme" "$HTML" | ||
| 421 | +check "page reads the theme before paint" "data-theme" "$HTML" | ||
| 422 | +check "page hides its toggle when embedded" "embed-hide" "$HTML" | ||
| 423 | +check "page uses the two-route API helper" "plugin_opencode_login" "$HTML" | ||
| 424 | +check "page fluid down to 390px" "max-width:480px" "$HTML" | ||
| 425 | +check_not "page loads no CDN script" "<script src=" "$HTML" | ||
| 426 | +check_not "page references no cdnjs" "cdnjs" "$HTML" | ||
| 427 | +check_not "page makes no third-party fetch" "googleapis.com" "$HTML" | ||
| 428 | +check_not "page carries no rocket emoji" "\xf0\x9f\x9a\x80" "$HTML" | ||
| 429 | +check_not "page never mentions a token variable" "access_token" "$HTML" | ||
| 430 | +check_not "page hardcodes no LAN address" "192.168." "$HTML" | ||
| 431 | +check_not "page hardcodes no localhost port" "127.0.0.1" "$HTML" | ||
| 432 | + | ||
| 433 | +# the served page must be parseable and every JS id must exist in the markup | ||
| 434 | +if command -v python3 >/dev/null 2>&1; then | ||
| 435 | + printf '%s' "$HTML" > "$FIX/page.html" | ||
| 436 | + if python3 - "$FIX/page.html" <<'PY' | ||
| 437 | +import re, sys | ||
| 438 | +html = open(sys.argv[1], encoding='utf-8').read() | ||
| 439 | +ids = set(re.findall(r'id="([^"]+)"', html)) | ||
| 440 | +missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids] | ||
| 441 | +sys.exit(1 if missing else 0) | ||
| 442 | +PY | ||
| 443 | + then pass "every JS element id exists in the markup" | ||
| 444 | + else fail "the page JS references an element id that is not in the HTML"; fi | ||
| 445 | + | ||
| 446 | + if python3 - "$FIX/page.html" <<'PY' | ||
| 447 | +import sys | ||
| 448 | +html = open(sys.argv[1], encoding='utf-8').read() | ||
| 449 | +# balanced tags for the containers the page actually builds | ||
| 450 | +for tag in ("div", "span", "button", "script", "style"): | ||
| 451 | + opens = html.count("<%s" % tag) | ||
| 452 | + closes = html.count("</%s>" % tag) | ||
| 453 | + if opens != closes: | ||
| 454 | + sys.stderr.write("%s: %d open vs %d close\n" % (tag, opens, closes)) | ||
| 455 | + sys.exit(1) | ||
| 456 | +sys.exit(0) | ||
| 457 | +PY | ||
| 458 | + then pass "the page markup is balanced" | ||
| 459 | + else fail "the page markup has unbalanced tags"; fi | ||
| 460 | +fi | ||
| 461 | + | ||
| 462 | +# ---------------------------------------------------------------- source hygiene | ||
| 463 | +section "source hygiene" | ||
| 464 | +check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_opencode_login.c)" | ||
| 465 | +check_not "source has no scorpiox-git PAT" "3ef2c00" "$(cat src/plugin_opencode_login.c)" | ||
| 466 | +# The word "audit" on this line is what lets the history scanner treat it as a | ||
| 467 | +# detection-pattern definition rather than a finding. | ||
| 468 | +check_not "source audit finds no default password" "xboxone" "$(cat src/plugin_opencode_login.c src/ui.html tests/mock_login.sh tests/mock_token.sh)" | ||
| 469 | +check_not "source has no internal address" "192.168." "$(cat src/plugin_opencode_login.c src/ui.html)" | ||
| 470 | +check_not "source has no 10.x address" "10.0." "$(cat src/plugin_opencode_login.c src/ui.html)" | ||
| 471 | +check_not "source has no host name" "macmini" "$(cat src/plugin_opencode_login.c src/ui.html)" | ||
| 472 | +check_not "source has no device secret" "$DEVICE_SECRET" "$(cat src/plugin_opencode_login.c src/ui.html)" | ||
| 473 | +check_not "no Content-Length header is emitted" "Content-Length" "$(cat src/plugin_opencode_login.c)" | ||
| 474 | + | ||
| 475 | +# no emoji anywhere in the shipped sources (byte-level check, not a regex guess) | ||
| 476 | +if python3 - src/plugin_opencode_login.c src/ui.html src/bot_theme_plugin.h <<'PY' | ||
| 477 | +import sys, unicodedata | ||
| 478 | +bad = [] | ||
| 479 | +for path in sys.argv[1:]: | ||
| 480 | + for n, line in enumerate(open(path, encoding='utf-8'), 1): | ||
| 481 | + for ch in line: | ||
| 482 | + o = ord(ch) | ||
| 483 | + if o < 0x2000: | ||
| 484 | + continue | ||
| 485 | + if 0x2190 <= o <= 0x21FF: # arrows are typography, not emoji | ||
| 486 | + continue | ||
| 487 | + if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF: | ||
| 488 | + bad.append('%s:%d %r' % (path, n, ch)) | ||
| 489 | +if bad: | ||
| 490 | + print('\n'.join(bad[:10])) | ||
| 491 | + sys.exit(1) | ||
| 492 | +PY | ||
| 493 | +then pass "no emoji in source, page or theme header" | ||
| 494 | +else fail "emoji found in the shipped sources"; fi | ||
| 495 | + | ||
| 496 | +# plugin.json sidecar must carry the market contract | ||
| 497 | +if command -v python3 >/dev/null 2>&1; then | ||
| 498 | + if python3 - plugin.json <<'PY' | ||
| 499 | +import json, sys | ||
| 500 | +d = json.load(open(sys.argv[1])) | ||
| 501 | +want = { | ||
| 502 | + "slug": "opencode-login", | ||
| 503 | + "id": "plugin_opencode_login", | ||
| 504 | + "name": "opencode", | ||
| 505 | + "desc": "OpenCode login", | ||
| 506 | + "title": "OpenCode Login", | ||
| 507 | + "category": "devtools", | ||
| 508 | + "license": "MIT", | ||
| 509 | +} | ||
| 510 | +for k, v in want.items(): | ||
| 511 | + if d.get(k) != v: | ||
| 512 | + sys.stderr.write("%s: %r != %r\n" % (k, d.get(k), v)) | ||
| 513 | + sys.exit(1) | ||
| 514 | +if d.get("capabilities") != ["credentials_read", "oauth_device_flow"]: | ||
| 515 | + sys.stderr.write("capabilities wrong\n"); sys.exit(1) | ||
| 516 | +if "never" not in d.get("trust_notice", "").lower(): | ||
| 517 | + sys.stderr.write("trust_notice must promise what never leaves the node\n"); sys.exit(1) | ||
| 518 | +sys.exit(0) | ||
| 519 | +PY | ||
| 520 | + then pass "plugin.json carries the full market contract" | ||
| 521 | + else fail "plugin.json does not match the contract"; fi | ||
| 522 | +fi | ||
| 523 | + | ||
| 524 | +# ---------------------------------------------------------------- extra builds | ||
| 525 | +section "cross-target builds" | ||
| 526 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 527 | + if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_opencode_login.c 2>/dev/null; then | ||
| 528 | + pass "static musl build" | ||
| 529 | + MUSLMETA=$("$FIX/musl-bin" --meta) | ||
| 530 | + check "the musl binary reports the same metadata" '"name":"opencode"' "$MUSLMETA" | ||
| 531 | + MUSLS=$(HOME=/root QUERY_STRING="action=status" "$FIX/musl-bin" >/dev/null 2>&1 && echo ran) | ||
| 532 | + check "the musl binary runs a status call" "ran" "$MUSLS" | ||
| 533 | + else fail "static musl build"; fi | ||
| 534 | +else | ||
| 535 | + echo " skip musl-gcc not installed" | ||
| 536 | +fi | ||
| 537 | + | ||
| 538 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 539 | + if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_opencode_login.c 2>/dev/null; then | ||
| 540 | + pass "MinGW-w64 build" | ||
| 541 | + if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then | ||
| 542 | + pass "the Windows build has a real PE header" | ||
| 543 | + else fail "the Windows build is not a PE (missing MZ)"; fi | ||
| 544 | + else fail "MinGW-w64 build"; fi | ||
| 545 | +else | ||
| 546 | + echo " skip x86_64-w64-mingw32-gcc not installed" | ||
| 547 | +fi | ||
| 548 | + | ||
| 549 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 550 | + if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_opencode_login.c 2>/dev/null; then | ||
| 551 | + pass "static aarch64 build" | ||
| 552 | + check "the arm binary reports the same metadata" '"name":"opencode"' "$("$FIX/arm-bin" --meta)" | ||
| 553 | + else fail "static aarch64 build"; fi | ||
| 554 | +else | ||
| 555 | + echo " skip aarch64-linux-gnu-gcc not installed" | ||
| 556 | +fi | ||
| 557 | + | ||
| 558 | +# ---------------------------------------------------------------- summary | ||
| 559 | +section "summary" | ||
| 560 | +printf ' %s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0" | ||
| 561 | +[ "$FAIL" -eq 0 ] || exit 1 | ||
| 562 | +exit 0 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..55470a4 | index 0000000..55470a4 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tools/gen_ui.py | +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui.html.h. | ||
| 3 | + | ||
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | ||
| 5 | +reviewed like any other source. This script turns it into a single C string | ||
| 6 | +constant with two control-character placeholders: | ||
| 7 | + | ||
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | ||
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | ||
| 10 | + | ||
| 11 | +main() splits the constant on those bytes and emits the macros from | ||
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | ||
| 13 | +sync with the rest of the bot. | ||
| 14 | + | ||
| 15 | + python3 tools/gen_ui.py # write src/ui.html.h | ||
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import os | ||
| 20 | +import sys | ||
| 21 | + | ||
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | ||
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | ||
| 25 | + | ||
| 26 | +TOKENS = "<!--TOKENS-->" | ||
| 27 | +MARK_TOKENS = "\u0001" | ||
| 28 | +MARK_HANDOFF = "\u0002" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def c_literal(text): | ||
| 32 | + """Escape text for a C string literal, one line per source line.""" | ||
| 33 | + out = [] | ||
| 34 | + for line in text.splitlines(True): | ||
| 35 | + piece = [] | ||
| 36 | + for ch in line: | ||
| 37 | + if ch == "\\": | ||
| 38 | + piece.append("\\\\") | ||
| 39 | + elif ch == '"': | ||
| 40 | + piece.append('\\"') | ||
| 41 | + elif ch == "\n": | ||
| 42 | + piece.append("\\n") | ||
| 43 | + elif ch == "\r": | ||
| 44 | + piece.append("\\r") | ||
| 45 | + elif ch == "\t": | ||
| 46 | + piece.append("\\t") | ||
| 47 | + elif ch == MARK_TOKENS: | ||
| 48 | + piece.append("\\001") | ||
| 49 | + elif ch == MARK_HANDOFF: | ||
| 50 | + piece.append("\\002") | ||
| 51 | + elif ord(ch) < 0x20: | ||
| 52 | + piece.append("\\%03o" % ord(ch)) | ||
| 53 | + else: | ||
| 54 | + piece.append(ch) | ||
| 55 | + out.append(' "%s"\n' % "".join(piece)) | ||
| 56 | + return "".join(out) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def render(): | ||
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | ||
| 61 | + html = f.read() | ||
| 62 | + | ||
| 63 | + if TOKENS not in html: | ||
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | ||
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | ||
| 66 | + | ||
| 67 | + # Handoff script goes right before the closing body tag. | ||
| 68 | + if "</body>" not in html: | ||
| 69 | + raise SystemExit("src/ui.html has no </body>") | ||
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | ||
| 71 | + | ||
| 72 | + header = ( | ||
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | ||
| 74 | + "#ifndef SX_AGYLOGIN_UI_HTML_H\n" | ||
| 75 | + "#define SX_AGYLOGIN_UI_HTML_H\n" | ||
| 76 | + "\n" | ||
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | ||
| 78 | + "\n" | ||
| 79 | + "#endif /* SX_AGYLOGIN_UI_HTML_H */\n" | ||
| 80 | + ) | ||
| 81 | + return header | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def main(): | ||
| 85 | + header = render() | ||
| 86 | + check = "--check" in sys.argv[1:] | ||
| 87 | + if check: | ||
| 88 | + try: | ||
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | ||
| 90 | + cur = f.read() | ||
| 91 | + except OSError: | ||
| 92 | + cur = "" | ||
| 93 | + if cur != header: | ||
| 94 | + sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n") | ||
| 95 | + return 1 | ||
| 96 | + print("src/ui.html.h is up to date") | ||
| 97 | + return 0 | ||
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | ||
| 99 | + f.write(header) | ||
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | ||
| 101 | + return 0 | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +if __name__ == "__main__": | ||
| 105 | + sys.exit(main()) | ||
| 0 | 106 |