tuxevil-rotator 3.10.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +22 -12
- package/package.json +8 -4
- package/src/admin-auth.ts +233 -3
- package/src/dashboard-app.ts +257 -0
- package/src/dashboard-live.ts +654 -0
- package/src/dashboard-types.ts +192 -0
- package/src/dashboard.ts +165 -732
- package/src/db-store.ts +43 -0
- package/src/exposure.ts +21 -1
- package/src/providers/opencode-zen/catalog.ts +2 -0
- package/src/providers/opencode-zen/forward.ts +18 -15
- package/src/providers/opencode-zen/login.ts +2 -1
- package/src/providers/opencode-zen/quota.ts +2 -1
- package/src/proxy.ts +71 -25
- package/src/rotator.ts +30 -30
- package/src/settings-repository.ts +7 -0
- package/src/types.ts +2 -0
- package/src/web/app.tsx +765 -0
- package/src/web/components/charts.tsx +338 -0
- package/src/web/components/command.tsx +279 -0
- package/src/web/components/icons.tsx +357 -0
- package/src/web/components/overlays.tsx +432 -0
- package/src/web/components/ui.tsx +421 -0
- package/src/web/lib/accounts.ts +109 -0
- package/src/web/lib/attention.ts +219 -0
- package/src/web/lib/colors.ts +103 -0
- package/src/web/lib/format.ts +113 -0
- package/src/web/lib/mask.ts +92 -0
- package/src/web/lib/pools.ts +199 -0
- package/src/web/lib/status.ts +242 -0
- package/src/web/lib/usage.ts +296 -0
- package/src/web/main.tsx +16 -0
- package/src/web/nav.ts +28 -0
- package/src/web/pages/AccountDetail.tsx +346 -0
- package/src/web/pages/Accounts.tsx +581 -0
- package/src/web/pages/Keys.tsx +431 -0
- package/src/web/pages/Overview.tsx +600 -0
- package/src/web/pages/Requests.tsx +644 -0
- package/src/web/pages/Settings.tsx +546 -0
- package/src/web/pages/Usage.tsx +346 -0
- package/src/web/pages/shared.ts +36 -0
- package/src/web/state/actions.ts +211 -0
- package/src/web/state/api.ts +273 -0
- package/src/web/state/prefs.ts +19 -0
- package/src/web/state/router.ts +92 -0
- package/src/web/state/store.ts +266 -0
- package/src/web/styles/app.css +5043 -0
- package/src/web/tsconfig.json +14 -0
- package/src/static/dashboard-keys.js +0 -535
- package/src/static/dashboard-logs.js +0 -800
- package/src/static/dashboard.css +0 -2741
- package/src/static/dashboard.js +0 -3334
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,58 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [4.0.0] - 2026-10-05
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
|
|
9
|
+
- **Rebuilt web dashboard**: the dashboard is now a TypeScript + Preact single-page app (`src/web`), bundled in memory by esbuild at startup, so there is still no separate build step. It replaces about 8,600 lines of string-built HTML, global-function JavaScript and CSS in `src/dashboard.ts` and `src/static/`. ([PR #38](https://github.com/tuxevil/tuxevil-rotator/pull/38) by [@CyR1en](https://github.com/CyR1en))
|
|
10
|
+
- **Organized around models.** A new Overview answers whether routing works and for how long: one row per quota pool (Claude, Gemini, Codex, Ollama, OpenCode) with pooled quota weighted by tier, the serving account, the next accounts in line, the next reset and a burn-rate estimate. Each row expands into the routing decisions that used to sit in the Routing Inspector modal.
|
|
11
|
+
- **Inline attention list.** Quarantined, erroring and disabled accounts, open circuit breakers, unroutable models, protective pauses and security warnings appear on the Overview with the fixing action next to each, replacing the header-badge modal.
|
|
12
|
+
- **Account cards, list and drawer.** Accounts show as cards (quota per model with reset countdowns and a Start button for idle windows, requests, health and last use, plus the error and the fix for accounts out of service) or as a compact sortable list; filters, sort and the view are in the URL and the view is remembered. Each account opens a drawer at `/dashboard/accounts/<email>` with quota windows, per-model routing decisions, the health-score breakdown, daily budgets and every action.
|
|
13
|
+
- **One Requests page.** It has a live tail of the in-memory request log with rotator and proxy events interleaved, and (with PostgreSQL) the stored history with payload inspector and per-key totals, replacing Spend Logs and the old request-log and recent-events panels.
|
|
14
|
+
- **Usage and Settings pages.** Usage holds the token chart, savings by model, latency percentiles and the 60-day heatmap. Settings holds routing controls, a routing-policy form, the benchmark, the configuration file editor with import/export, appearance and project information.
|
|
15
|
+
- **Shareable URLs.** Every view, filter and the open drawer is in the URL. `/dashboard/logs` redirects to the request history.
|
|
16
|
+
- **Dashboard data API**: `/api/dashboard/snapshot`, `/api/dashboard/usage`, `/api/dashboard/activity` and `/api/dashboard/usage/export` split the old all-in-one status payload. `/api/dashboard/stream` sends a snapshot and then only what changed (changed accounts, overview sections, new requests and events) instead of the full status every second; countdowns are absolute timestamps, so an idle rotator sends nothing. `/api/status` and `/api/events` are unchanged.
|
|
17
|
+
- **Visual design**: an app-style shell. A top bar (brand and live status, sidebar toggle, add account, search and a "Needs you" inbox) and an icon rail that expands to labels frame the page in a floating, rounded canvas; the account drawer and dialogs float the same way. <kbd>⌘K</kbd> opens a command palette for pages, accounts and quick actions, and theme, privacy mask and sign-out live in a profile menu at the foot of the rail. Light and dark themes (system by default), neutral quota bars that turn amber or red only when a pool runs low or empty, one status vocabulary (Serving, Ready, Cooling down, Out of quota, Erroring, Disabled, Quarantined), and layouts that work on phones, where the rail becomes a slide-over sheet and the drawer a bottom sheet. The support prompt is a dismissible note in the sidebar instead of a modal.
|
|
18
|
+
|
|
19
|
+
### Security
|
|
20
|
+
|
|
21
|
+
- **Dashboard session cookie**: the admin token is no longer kept in `localStorage` or put in URLs by the dashboard. `/dashboard?token=…` links and the new sign-in screen exchange it for an `HttpOnly`, `SameSite=Strict` cookie (an HMAC keyed by the admin token, valid for 30 days) and strip the token from the address bar. Cookie-authenticated writes must be same-origin, and a live session that fails that check gets `403` instead of being signed out. Signing out persists a hash of the revoked session, so the cookie remains invalid across restarts. Tokens stored by older dashboards are migrated once and deleted.
|
|
22
|
+
- **Content Security Policy**: dashboard pages are served with `script-src 'self'`, `style-src 'self'`, `frame-ancestors 'none'` and no inline handlers or styles.
|
|
23
|
+
|
|
24
|
+
### Improved
|
|
25
|
+
|
|
26
|
+
- **Token usage chart**: the headline numbers describe the selected range (tokens, requests, peak and estimated savings), with all-time totals shown separately. Ranges are 1h, 6h, 24h, 7d and 30d, each built on the granularity the rotator stores (per minute, 5 minutes, hour, day), so older hourly data is no longer drawn as one spike at the top of each hour. The axis uses real clock times and dates on round ticks, bars show a hover breakdown per model, and legend entries hide or highlight a model. Savings use the server's model price list instead of a copy in the browser.
|
|
27
|
+
|
|
28
|
+
### Added
|
|
29
|
+
|
|
30
|
+
- **Dashboard dev server**: `npm run dashboard:dev` serves the real dashboard routes against a simulated rotator (scenarios: `MOCK_SCENARIO=healthy|degraded|paused|empty|large`, `MOCK_DB=0` for no PostgreSQL), rebuilding the bundle on every page load.
|
|
31
|
+
|
|
32
|
+
### Fixed
|
|
33
|
+
|
|
34
|
+
- **Token usage rollup**: period keys are UTC but were compared as local time, and hour keys did not parse at all. On hosts ahead of UTC, minute buckets were folded into hours too early (immediately at UTC+12), which emptied the 1h and 6h charts; hour buckets were never rolled up, so the stored hourly history grew without bound. Minutes are now kept for 12 hours and hours for 61 days in every timezone. **On the first request after upgrading, hour buckets older than 61 days are folded into monthly totals**; all-time totals are unchanged and the 60-day heatmap and every chart range keep their data.
|
|
35
|
+
- **All-time token totals**: the totals, per-model token counts and savings skipped any minute, hour or day bucket whose parent period had already started rolling up, so they left out up to an hour of traffic from about 12 hours earlier and shifted as buckets rolled. Rollups move buckets rather than copy them, so the totals now add every tier.
|
|
36
|
+
- **Docker exposure warning**: every Docker install showed a security warning, titled "Admin routes are exposed", because the rotator has to listen on `0.0.0.0` inside a container. The title now names what is exposed (the proxy routes, or the admin routes when no admin token is set), and inside a container (the image sets `TUXEVIL_ROTATOR_CONTAINER=1`; Docker and Podman are also detected) the proxy warning is a note that points at the published port, so it no longer counts in the "Needs you" bell.
|
|
37
|
+
|
|
38
|
+
### Documentation
|
|
39
|
+
|
|
40
|
+
- **Dashboard guide**: new `docs/dashboard.md` covers sign-in, navigation and the command palette, the status vocabulary, every page and the privacy mask, with screenshots taken from the dashboard dev server's sample data. `CONTRIBUTING.md` documents `npm run dashboard:dev`.
|
|
41
|
+
- **Updated for the new dashboard**: account management, troubleshooting (sign-in sessions, `403` behind a reverse proxy, quarantined accounts, rejected Codex credentials), the nginx example (`X-Forwarded-Proto`), virtual keys and request history.
|
|
42
|
+
|
|
43
|
+
## [3.11.0] - 2026-10-03
|
|
44
|
+
|
|
45
|
+
### Added
|
|
46
|
+
|
|
47
|
+
- **Automatic agent installation**: `install-agent` configures detected or selected OpenCode, Hermes, Pi, and Codex clients locally or over SSH. `install-opencode` installs the bundled discovery plugin, which reads `/v1/models` and adds model limits and capabilities to OpenCode.
|
|
48
|
+
|
|
49
|
+
### Improved
|
|
50
|
+
|
|
51
|
+
- **OpenCode Zen request compatibility**: Requests use a consistent User-Agent and forward the authentic OpenCode session context upstream.
|
|
52
|
+
|
|
53
|
+
### Changed
|
|
54
|
+
|
|
55
|
+
- Updated the locked `undici` dependency to `7.29.1`.
|
|
56
|
+
|
|
5
57
|
## [3.10.0] - 2026-09-28
|
|
6
58
|
|
|
7
59
|
### Added
|
package/README.md
CHANGED
|
@@ -53,6 +53,8 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
|
|
|
53
53
|
|
|
54
54
|
## Current Model Update
|
|
55
55
|
|
|
56
|
+
- **v4.0.0: Redesigned WebUI**: A complete dashboard refresh with live routing health, account management, request history, usage analytics, shareable views, and a responsive Preact interface. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.0.0); [PR #38](https://github.com/tuxevil/tuxevil-rotator/pull/38) by [@CyR1en](https://github.com/CyR1en))
|
|
57
|
+
- **v3.11.0: automatic agent setup and OpenCode model discovery**: Configure detected or selected agents locally or over SSH with `install-agent`; OpenCode can populate its model catalog from the rotator's live `/v1/models` endpoint. OpenCode Zen requests also forward the real session context and use a consistent User-Agent. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.11.0))
|
|
56
58
|
- **v3.10.0: Claude tools, account-flag diagnostics, and audio reliability**: Fixed Claude Opus 4.6 Thinking tool-schema errors; account verification reasons now persist and flow into anonymous telemetry with a protected recent-incidents dashboard; audio transcription and WebSocket streaming use active Antigravity accounts with Language Server fallback. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.10.0); audio hardening in [PR #36](https://github.com/tuxevil/tuxevil-rotator/pull/36) by [@javargasm](https://github.com/javargasm))
|
|
57
59
|
- **Rotator-Backed Audio Transcription and Live-Streaming Hardening**: Batch transcription and live WebSocket sessions use active Antigravity accounts with Language Server fallback after rotator errors and timeouts. Virtual-key scopes follow the executed model; live streams preserve segment order, echo Ping payloads, and avoid fallback after client cancellation. ([PR #36](https://github.com/tuxevil/tuxevil-rotator/pull/36) by [@javargasm](https://github.com/javargasm))
|
|
58
60
|
- **OpenAI Codex GPT-6 catalog**: Added GPT-6 Astra, Sol, and Luna to the Codex options while keeping GPT-5.6 Sol, Terra, and Luna available. ([v3.9.0](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.9.0))
|
|
@@ -156,7 +158,7 @@ Existing `enc:v1` records remain decryptable during migration; newly written rec
|
|
|
156
158
|
- **Virtual Keys & access control** — Issue scoped `rk-...` keys for teams, agents, or CI pipelines with per-key model restrictions
|
|
157
159
|
- **Spend logging & audit inspector** — Full request/response audit trail with 6-decimal USD cost estimates for both Antigravity and Ollama traffic (requires PostgreSQL)
|
|
158
160
|
- **Legacy importer** — On startup, automatically merges Ollama Cloud accounts from `~/.ollama-rotator/accounts.json` (the predecessor product) onto existing accounts, idempotently
|
|
159
|
-
- **Web dashboard** —
|
|
161
|
+
- **Web dashboard** — Live routing health and per-model quota runway, account cards with one-click fixes, a live request tail, token usage and savings, latency (p50/p95), an activity heatmap, and per-model routing decisions
|
|
160
162
|
- **State persistence** — Survives restarts; routing assignments, cooldowns, and flags saved to disk or PostgreSQL
|
|
161
163
|
- **Tool/function calling** — Fully supported in OpenAI and Anthropic formats, including multi-turn and parallel tool calls, with reliable function-name resolution for tool responses across turns. Ollama forwards `function.arguments` as a parsed object (OpenAI sends it as a JSON string and Ollama's Go API rejects that).
|
|
162
164
|
- **Reasoning/thinking visibility** — Interleaved thinking blocks exposed as `reasoning_content` / `thinking_delta` in real time
|
|
@@ -220,6 +222,14 @@ Dashboard opens at `http://localhost:51200/dashboard`
|
|
|
220
222
|
|
|
221
223
|
Point any OpenAI-compatible agent to `http://localhost:51200/v1` with API key `tuxevil` (or a [Virtual Key](docs/virtual-keys.md)):
|
|
222
224
|
|
|
225
|
+
You can configure supported local agents automatically with:
|
|
226
|
+
|
|
227
|
+
```bash
|
|
228
|
+
tuxevil-rotator install-agent --target auto
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
Use `--target all` or a comma-separated list (`opencode,hermes,pi,codex`) to choose clients. Add `--host <hostname> --user <ssh-user>` to configure them over SSH, or `--dry-run` to review the generated installer first. For OpenCode's live model catalog, use `tuxevil-rotator install-opencode`; see the [OpenCode integration guide](docs/integrations/opencode.md).
|
|
232
|
+
|
|
223
233
|
| Agent | Guide |
|
|
224
234
|
|-------|-------|
|
|
225
235
|
| Pi | [docs/integrations/pi.md](docs/integrations/pi.md) |
|
|
@@ -270,20 +280,19 @@ How model routing works:
|
|
|
270
280
|
|
|
271
281
|
## Dashboard
|
|
272
282
|
|
|
273
|
-
After starting the proxy, open `http://localhost:51200/dashboard
|
|
283
|
+
After starting the proxy, open `http://localhost:51200/dashboard` and sign in with the admin token (`TUXEVIL_ROTATOR_ADMIN_TOKEN`). A link of the form `/dashboard?token=<token>` signs in directly; either way the browser gets a session cookie and the token is removed from the URL.
|
|
284
|
+
|
|
285
|
+
- **Overview** — whether routing works right now, one row per model pool (Claude, Gemini, Codex, Ollama, OpenCode) with pooled quota, the account serving it, what is next in line, the next reset and how long the quota lasts at the current rate, plus a list of what needs you with the fix one click away
|
|
286
|
+
- **Accounts** — cards with each account's quota per model, or a compact sortable list; each account opens a drawer with its quota windows, routing decisions, health breakdown, limits and every action (re-enable, restore, start idle windows, tier, quarantine, remove)
|
|
287
|
+
- **Requests** — a live tail of requests and rotator events, and with PostgreSQL the full history with payloads and per-key totals
|
|
288
|
+
- **Usage** — token volume by model with 1h–30d ranges, estimated savings at list prices, latency percentiles and a 60-day activity heatmap
|
|
289
|
+
- **Virtual keys** and **Settings** — key management, routing controls and policy, a benchmark, and the raw configuration file
|
|
274
290
|
|
|
275
|
-
|
|
276
|
-
- **Routing state** — real-time status, uptime, requests, protective pause timers
|
|
277
|
-
- **Account cards** — quota bars (Antigravity family buckets `claude` / `gemini`; Ollama monthly usage), per-model timers, health scores, flagged alerts
|
|
278
|
-
- **Token usage & savings** — interactive chart with time ranges and CSV/JSON export (real USD for both providers)
|
|
279
|
-
- **Latency (p50/p95)** — per-model TTFB and total duration
|
|
280
|
-
- **Activity heatmap** — 60-day GitHub-style request intensity grid
|
|
281
|
-
- **Quota forecast** — tier-weighted depletion predictions
|
|
282
|
-
- **Routing inspector** — on-demand modal with candidate scores, health-score breakdown, and rejection reasons
|
|
291
|
+
Press <kbd>⌘K</kbd> (<kbd>Ctrl</kbd>+<kbd>K</kbd>) to jump to any page or account or run a quick action, and the bell in the top bar lists what needs you. Light and dark themes follow the system unless you pick one in the profile menu at the bottom of the sidebar; the privacy mask there (or `?mask=1`) hides names, emails and keys for screenshots.
|
|
283
292
|
|
|
284
293
|

|
|
285
294
|
|
|
286
|
-
[Dashboard
|
|
295
|
+
[Dashboard guide →](docs/dashboard.md)
|
|
287
296
|
|
|
288
297
|
## Virtual Keys & Spend Logging
|
|
289
298
|
|
|
@@ -308,6 +317,7 @@ tuxevil-rotator keys generate --alias "cursor-agent" --models "gemini-3.6-flash-
|
|
|
308
317
|
|-------|------|
|
|
309
318
|
| How It Works | [docs/how-it-works.md](docs/how-it-works.md) |
|
|
310
319
|
| Configuration | [docs/configuration.md](docs/configuration.md) |
|
|
320
|
+
| Dashboard | [docs/dashboard.md](docs/dashboard.md) |
|
|
311
321
|
| Virtual Keys & Spend Logging | [docs/virtual-keys.md](docs/virtual-keys.md) |
|
|
312
322
|
| API Reference | [docs/api-reference.md](docs/api-reference.md) |
|
|
313
323
|
| Compatibility Adapters | [docs/compatibility.md](docs/compatibility.md) |
|
|
@@ -362,7 +372,7 @@ Thanks to these amazing people who have contributed to the project:
|
|
|
362
372
|
|
|
363
373
|
- **[@CelestialCreator](https://github.com/CelestialCreator)** (Akshay) — Fixed admin token propagation on the hosted login landing page (`/login` to `/auth/antigravity/start`). ([PR #25](https://github.com/tuxevil/tuxevil-rotator/pull/25))
|
|
364
374
|
- **[@Codder-hermes](https://github.com/Codder-hermes)** — Fixed Claude Code tool-schema requests by stripping the unsupported JSON Schema `propertyNames` keyword for Gemini and Claude-via-Gemini routes, with regression coverage for both compatibility paths. ([PR #19](https://github.com/tuxevil/tuxevil-rotator/pull/19))
|
|
365
|
-
- **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6, Gemini 3.7, and Gemini 3.8 Flash model families, shared quota-pool routing, pricing, dashboard support, integration documentation, effort-based model routing, and regression coverage. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21), [PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28), [PR #32](https://github.com/tuxevil/tuxevil-rotator/pull/32))
|
|
375
|
+
- **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6, Gemini 3.7, and Gemini 3.8 Flash model families, shared quota-pool routing, pricing, dashboard support, integration documentation, effort-based model routing, the rebuilt WebUI, and regression coverage. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21), [PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28), [PR #32](https://github.com/tuxevil/tuxevil-rotator/pull/32), [PR #38](https://github.com/tuxevil/tuxevil-rotator/pull/38))
|
|
366
376
|
- **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Modularized the compatibility layer architecture, added multimodal tool response support, fixed streaming pass-through for tool executions, and added PostgreSQL storage and weighted pool quota forecasting. ([PR #8](https://github.com/tuxevil/tuxevil-rotator/pull/8), [PR #9](https://github.com/tuxevil/tuxevil-rotator/pull/9), [PR #11](https://github.com/tuxevil/tuxevil-rotator/pull/11), [PR #13](https://github.com/tuxevil/tuxevil-rotator/pull/13), [PR #14](https://github.com/tuxevil/tuxevil-rotator/pull/14))
|
|
367
377
|
- **[@yashyadav711](https://github.com/yashyadav711)** (Yash) — Fixed Draft-2020-12 inline JSON-Schema union type mapping for Gemini tools support. ([PR #10](https://github.com/tuxevil/tuxevil-rotator/pull/10))
|
|
368
378
|
- **[@toRolex](https://github.com/toRolex)** (Rolex) — Added cached prompt-token extraction from Google Antigravity/Cloud Code usage and mapped it to OpenAI and Anthropic compatibility responses, with focused regression tests, plus transport-error retry recovery for single-account and exhausted-account pools. ([PR #34](https://github.com/tuxevil/tuxevil-rotator/pull/34), [PR #35](https://github.com/tuxevil/tuxevil-rotator/pull/35))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tuxevil-rotator",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -14,12 +14,13 @@
|
|
|
14
14
|
"scripts": {
|
|
15
15
|
"start": "tsx src/cli.ts start",
|
|
16
16
|
"login": "tsx src/cli.ts login",
|
|
17
|
-
"typecheck": "tsc --noEmit",
|
|
17
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p src/web",
|
|
18
18
|
"typecheck:test": "tsc --project tsconfig.test.json",
|
|
19
19
|
"test": "TUXEVIL_ROTATOR_ADMIN_TOKEN= PI_ROTATOR_ADMIN_TOKEN= ANTIGRAVITY_CLIENT_ID=test-client-id ANTIGRAVITY_CLIENT_SECRET=test-client-secret TUXEVIL_ROTATOR_DIR=/tmp/tuxevil-rotator-test node --import tsx/esm --test \"test/**/*.test.ts\"",
|
|
20
|
-
"lint": "eslint src test",
|
|
20
|
+
"lint": "eslint src test scripts/dashboard-dev.ts",
|
|
21
21
|
"coverage": "c8 --reporter=text --reporter=html --check-coverage --lines=60 --branches=50 --functions=60 --statements=60 npm test",
|
|
22
|
-
"check": "npm run typecheck && npm run typecheck:test && npm test && npm run lint"
|
|
22
|
+
"check": "npm run typecheck && npm run typecheck:test && npm test && npm run lint",
|
|
23
|
+
"dashboard:dev": "tsx scripts/dashboard-dev.ts"
|
|
23
24
|
},
|
|
24
25
|
"files": [
|
|
25
26
|
"bin/",
|
|
@@ -48,8 +49,11 @@
|
|
|
48
49
|
},
|
|
49
50
|
"author": "Sebastián Real (tuxevil)",
|
|
50
51
|
"dependencies": {
|
|
52
|
+
"@preact/signals": "^2.11.3",
|
|
51
53
|
"@typesafe-ai/sdk": "^0.6.0",
|
|
54
|
+
"esbuild": "^0.28.2",
|
|
52
55
|
"pg": "^8.22.0",
|
|
56
|
+
"preact": "^10.29.8",
|
|
53
57
|
"tsx": "^4.22.4",
|
|
54
58
|
"undici": "^7.29.0"
|
|
55
59
|
},
|
package/src/admin-auth.ts
CHANGED
|
@@ -1,12 +1,28 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import {
|
|
3
|
+
createHash,
|
|
4
|
+
createHmac,
|
|
5
|
+
randomBytes,
|
|
6
|
+
timingSafeEqual,
|
|
7
|
+
} from "node:crypto";
|
|
8
|
+
import {
|
|
9
|
+
getCachedAdminToken,
|
|
10
|
+
getCachedDashboardRevokedSessions,
|
|
11
|
+
isSettingsRepositoryInitialized,
|
|
12
|
+
setCachedAdminToken,
|
|
13
|
+
setCachedDashboardRevokedSessions,
|
|
14
|
+
} from "./db-store.js";
|
|
4
15
|
|
|
5
16
|
interface AdminAuthRequest {
|
|
6
17
|
url?: string;
|
|
18
|
+
method?: string;
|
|
7
19
|
headers: IncomingMessage["headers"];
|
|
8
20
|
}
|
|
9
21
|
|
|
22
|
+
/** Dashboard session cookie, exchanged for the admin token on first visit. */
|
|
23
|
+
export const DASHBOARD_SESSION_COOKIE = "tuxevil_session";
|
|
24
|
+
export const DASHBOARD_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
25
|
+
|
|
10
26
|
let persistedToken: string | null = null;
|
|
11
27
|
|
|
12
28
|
/**
|
|
@@ -103,12 +119,211 @@ export function getRequestAdminToken(req: AdminAuthRequest): string | null {
|
|
|
103
119
|
}
|
|
104
120
|
}
|
|
105
121
|
|
|
122
|
+
function safeEqual(a: string, b: string): boolean {
|
|
123
|
+
const left = Buffer.from(a);
|
|
124
|
+
const right = Buffer.from(b);
|
|
125
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function sessionSignature(token: string, expiresAt: number): string {
|
|
129
|
+
return createHmac("sha256", token)
|
|
130
|
+
.update(`tuxevil-dashboard-session:${expiresAt}`)
|
|
131
|
+
.digest("base64url");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Session value is `<expiresAt>.<hmac>` keyed by the admin token, so the
|
|
136
|
+
* cookie never carries the token itself and rotating the token signs every
|
|
137
|
+
* session out.
|
|
138
|
+
*/
|
|
139
|
+
export function createDashboardSession(
|
|
140
|
+
token: string,
|
|
141
|
+
now: number = Date.now(),
|
|
142
|
+
): { value: string; expiresAt: number } {
|
|
143
|
+
const expiresAt = now + DASHBOARD_SESSION_TTL_MS;
|
|
144
|
+
return { value: `${expiresAt}.${sessionSignature(token, expiresAt)}`, expiresAt };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function verifyDashboardSession(
|
|
148
|
+
value: string | null | undefined,
|
|
149
|
+
token: string,
|
|
150
|
+
now: number = Date.now(),
|
|
151
|
+
): boolean {
|
|
152
|
+
if (!value) return false;
|
|
153
|
+
const dot = value.indexOf(".");
|
|
154
|
+
if (dot <= 0) return false;
|
|
155
|
+
const expiresAt = Number(value.slice(0, dot));
|
|
156
|
+
if (!Number.isSafeInteger(expiresAt) || expiresAt <= now) return false;
|
|
157
|
+
return safeEqual(value.slice(dot + 1), sessionSignature(token, expiresAt));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function readRequestCookie(
|
|
161
|
+
req: AdminAuthRequest,
|
|
162
|
+
name: string,
|
|
163
|
+
): string | null {
|
|
164
|
+
const header = req.headers.cookie;
|
|
165
|
+
const raw = Array.isArray(header) ? header.join("; ") : header;
|
|
166
|
+
if (!raw) return null;
|
|
167
|
+
for (const part of raw.split(";")) {
|
|
168
|
+
const eq = part.indexOf("=");
|
|
169
|
+
if (eq < 0) continue;
|
|
170
|
+
if (part.slice(0, eq).trim() !== name) continue;
|
|
171
|
+
try {
|
|
172
|
+
return decodeURIComponent(part.slice(eq + 1).trim());
|
|
173
|
+
} catch {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function firstHeader(req: AdminAuthRequest, name: string): string | undefined {
|
|
181
|
+
const value = req.headers[name];
|
|
182
|
+
return Array.isArray(value) ? value[0] : value;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function isSecureRequest(req: IncomingMessage): boolean {
|
|
186
|
+
const proto = firstHeader(req, "x-forwarded-proto");
|
|
187
|
+
if (proto) return proto.split(",")[0].trim().toLowerCase() === "https";
|
|
188
|
+
return Boolean((req.socket as { encrypted?: boolean } | undefined)?.encrypted);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Cookie-authenticated writes must come from the dashboard itself. Browsers
|
|
193
|
+
* set Sec-Fetch-Site and Origin; page scripts cannot forge either.
|
|
194
|
+
*/
|
|
195
|
+
export function isSameOriginRequest(req: AdminAuthRequest): boolean {
|
|
196
|
+
const site = firstHeader(req, "sec-fetch-site");
|
|
197
|
+
if (site) return site === "same-origin";
|
|
198
|
+
const origin = firstHeader(req, "origin");
|
|
199
|
+
if (!origin) return false;
|
|
200
|
+
let originHost: string;
|
|
201
|
+
try {
|
|
202
|
+
originHost = new URL(origin).host;
|
|
203
|
+
} catch {
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
return [firstHeader(req, "host"), firstHeader(req, "x-forwarded-host")]
|
|
207
|
+
.filter(Boolean)
|
|
208
|
+
.some((host) => host!.split(",")[0].trim() === originHost);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Session hashes signed out before they expire. */
|
|
212
|
+
const revokedSessions = new Map<string, number>();
|
|
213
|
+
let persistedRevocationsLoaded = false;
|
|
214
|
+
let persistedRevocationsLoadError: Error | null = null;
|
|
215
|
+
let pendingRevocationWrite: Promise<void> = Promise.resolve();
|
|
216
|
+
|
|
217
|
+
function sessionHash(value: string): string {
|
|
218
|
+
return createHash("sha256").update(value).digest("hex");
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function loadPersistedRevocations(): void {
|
|
222
|
+
// Route tests and library consumers may use auth before initDb(); do not
|
|
223
|
+
// cache an empty result in that case, since production initializes storage
|
|
224
|
+
// before accepting requests.
|
|
225
|
+
if (persistedRevocationsLoaded || !isSettingsRepositoryInitialized()) return;
|
|
226
|
+
try {
|
|
227
|
+
const persisted = getCachedDashboardRevokedSessions();
|
|
228
|
+
if (persisted) {
|
|
229
|
+
for (const [hash, expiresAt] of Object.entries(persisted)) {
|
|
230
|
+
if (expiresAt > Date.now()) revokedSessions.set(hash, expiresAt);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
} catch (err) {
|
|
234
|
+
persistedRevocationsLoadError =
|
|
235
|
+
err instanceof Error ? err : new Error(String(err));
|
|
236
|
+
console.error(`Failed to load dashboard session revocations: ${err}`);
|
|
237
|
+
}
|
|
238
|
+
persistedRevocationsLoaded = true;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function pruneRevokedSessions(now: number): void {
|
|
242
|
+
for (const [hash, expiresAt] of revokedSessions) {
|
|
243
|
+
if (expiresAt <= now) revokedSessions.delete(hash);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function persistRevokedSessions(): Promise<void> {
|
|
248
|
+
if (!isSettingsRepositoryInitialized()) return Promise.resolve();
|
|
249
|
+
const snapshot = Object.fromEntries(revokedSessions);
|
|
250
|
+
const write = pendingRevocationWrite
|
|
251
|
+
.catch(() => undefined)
|
|
252
|
+
.then(() => setCachedDashboardRevokedSessions(snapshot));
|
|
253
|
+
pendingRevocationWrite = write;
|
|
254
|
+
return write;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Sign-out: stop honouring the request's session cookie, not just clear it. */
|
|
258
|
+
export async function revokeDashboardSession(
|
|
259
|
+
req: AdminAuthRequest,
|
|
260
|
+
now: number = Date.now(),
|
|
261
|
+
): Promise<void> {
|
|
262
|
+
loadPersistedRevocations();
|
|
263
|
+
if (persistedRevocationsLoadError) {
|
|
264
|
+
throw new Error("Dashboard session revocations could not be loaded", {
|
|
265
|
+
cause: persistedRevocationsLoadError,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
const value = readRequestCookie(req, DASHBOARD_SESSION_COOKIE);
|
|
269
|
+
const token = getConfiguredAdminToken();
|
|
270
|
+
if (!value || !token || !verifyDashboardSession(value, token, now)) return;
|
|
271
|
+
pruneRevokedSessions(now);
|
|
272
|
+
revokedSessions.set(sessionHash(value), Number(value.slice(0, value.indexOf("."))));
|
|
273
|
+
await persistRevokedSessions();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export function hasValidDashboardSession(
|
|
277
|
+
req: AdminAuthRequest,
|
|
278
|
+
expectedToken: string | null = getConfiguredAdminToken(),
|
|
279
|
+
): boolean {
|
|
280
|
+
if (!expectedToken) return false;
|
|
281
|
+
const value = readRequestCookie(req, DASHBOARD_SESSION_COOKIE);
|
|
282
|
+
loadPersistedRevocations();
|
|
283
|
+
if (persistedRevocationsLoadError && isSettingsRepositoryInitialized()) {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
if (value && revokedSessions.has(sessionHash(value))) return false;
|
|
287
|
+
return verifyDashboardSession(value, expectedToken);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function isAdminTokenValid(
|
|
291
|
+
candidate: string | null | undefined,
|
|
292
|
+
expectedToken: string | null = getConfiguredAdminToken(),
|
|
293
|
+
): boolean {
|
|
294
|
+
if (!expectedToken) return true;
|
|
295
|
+
return typeof candidate === "string" && safeEqual(candidate, expectedToken);
|
|
296
|
+
}
|
|
297
|
+
|
|
106
298
|
export function isAdminAuthorized(
|
|
107
299
|
req: AdminAuthRequest,
|
|
108
300
|
expectedToken: string | null = getConfiguredAdminToken(),
|
|
109
301
|
): boolean {
|
|
110
302
|
if (!expectedToken) return true;
|
|
111
|
-
|
|
303
|
+
if (isAdminTokenValid(getRequestAdminToken(req), expectedToken)) return true;
|
|
304
|
+
if (!hasValidDashboardSession(req, expectedToken)) return false;
|
|
305
|
+
const method = (req.method || "GET").toUpperCase();
|
|
306
|
+
if (method === "GET" || method === "HEAD") return true;
|
|
307
|
+
return isSameOriginRequest(req);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export function dashboardSessionCookie(
|
|
311
|
+
value: string,
|
|
312
|
+
opts: { secure: boolean; maxAgeMs?: number },
|
|
313
|
+
): string {
|
|
314
|
+
const maxAge = Math.floor((opts.maxAgeMs ?? DASHBOARD_SESSION_TTL_MS) / 1000);
|
|
315
|
+
return [
|
|
316
|
+
`${DASHBOARD_SESSION_COOKIE}=${encodeURIComponent(value)}`,
|
|
317
|
+
"Path=/",
|
|
318
|
+
"HttpOnly",
|
|
319
|
+
"SameSite=Strict",
|
|
320
|
+
`Max-Age=${maxAge}`,
|
|
321
|
+
...(opts.secure ? ["Secure"] : []),
|
|
322
|
+
].join("; ");
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function clearDashboardSessionCookie(secure: boolean): string {
|
|
326
|
+
return dashboardSessionCookie("", { secure, maxAgeMs: 0 });
|
|
112
327
|
}
|
|
113
328
|
|
|
114
329
|
export function requireAdmin(
|
|
@@ -116,6 +331,21 @@ export function requireAdmin(
|
|
|
116
331
|
res: ServerResponse,
|
|
117
332
|
): boolean {
|
|
118
333
|
if (isAdminAuthorized(req)) return true;
|
|
334
|
+
// A live session that fails the same-origin check is refused, not signed
|
|
335
|
+
// out: 401 would send the dashboard back to its login screen.
|
|
336
|
+
if (hasValidDashboardSession(req)) {
|
|
337
|
+
res.writeHead(403, {
|
|
338
|
+
"Content-Type": "application/json",
|
|
339
|
+
"Cache-Control": "no-store",
|
|
340
|
+
});
|
|
341
|
+
res.end(
|
|
342
|
+
JSON.stringify({
|
|
343
|
+
error:
|
|
344
|
+
"Blocked: the request did not come from the dashboard's own origin. Behind a reverse proxy, forward the Host or X-Forwarded-Host header.",
|
|
345
|
+
}),
|
|
346
|
+
);
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
119
349
|
res.writeHead(401, {
|
|
120
350
|
"Content-Type": "application/json",
|
|
121
351
|
"Cache-Control": "no-store",
|