tuxevil-rotator 3.11.0 → 4.1.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.
Files changed (68) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +18 -12
  3. package/package.json +8 -4
  4. package/src/admin-auth.ts +233 -3
  5. package/src/audio-transcription.ts +44 -4
  6. package/src/compat.ts +196 -222
  7. package/src/config-defaults.ts +5 -0
  8. package/src/dashboard-app.ts +257 -0
  9. package/src/dashboard-live.ts +656 -0
  10. package/src/dashboard-types.ts +230 -0
  11. package/src/dashboard.ts +320 -732
  12. package/src/db-store.ts +43 -0
  13. package/src/exposure.ts +21 -1
  14. package/src/model-catalog-revision.ts +17 -0
  15. package/src/model-catalog.ts +302 -0
  16. package/src/providers/adapter.ts +18 -0
  17. package/src/providers/google-antigravity/catalog.ts +190 -1
  18. package/src/providers/google-antigravity/forward.ts +2 -0
  19. package/src/providers/google-antigravity/index.ts +11 -0
  20. package/src/providers/google-antigravity/translators.ts +4 -0
  21. package/src/providers/ollama/index.ts +11 -1
  22. package/src/providers/ollama/quota-poll-store.ts +22 -1
  23. package/src/providers/ollama/quota.ts +95 -23
  24. package/src/providers/openai-codex/index.ts +18 -2
  25. package/src/providers/opencode-zen/index.ts +11 -2
  26. package/src/proxy.ts +214 -53
  27. package/src/rotator.ts +249 -40
  28. package/src/settings-repository.ts +43 -5
  29. package/src/types.ts +70 -26
  30. package/src/validators.ts +35 -0
  31. package/src/web/app.tsx +769 -0
  32. package/src/web/components/charts.tsx +338 -0
  33. package/src/web/components/command.tsx +279 -0
  34. package/src/web/components/icons.tsx +386 -0
  35. package/src/web/components/overlays.tsx +432 -0
  36. package/src/web/components/ui.tsx +426 -0
  37. package/src/web/lib/accounts.ts +110 -0
  38. package/src/web/lib/attention.ts +231 -0
  39. package/src/web/lib/colors.ts +103 -0
  40. package/src/web/lib/format.ts +113 -0
  41. package/src/web/lib/mask.ts +92 -0
  42. package/src/web/lib/models.ts +279 -0
  43. package/src/web/lib/pools.ts +243 -0
  44. package/src/web/lib/status.ts +252 -0
  45. package/src/web/lib/usage.ts +296 -0
  46. package/src/web/main.tsx +16 -0
  47. package/src/web/nav.ts +29 -0
  48. package/src/web/pages/AccountDetail.tsx +360 -0
  49. package/src/web/pages/Accounts.tsx +581 -0
  50. package/src/web/pages/Keys.tsx +431 -0
  51. package/src/web/pages/Models.tsx +852 -0
  52. package/src/web/pages/Overview.tsx +616 -0
  53. package/src/web/pages/Requests.tsx +644 -0
  54. package/src/web/pages/Settings.tsx +546 -0
  55. package/src/web/pages/Usage.tsx +346 -0
  56. package/src/web/pages/shared.ts +36 -0
  57. package/src/web/state/actions.ts +211 -0
  58. package/src/web/state/api.ts +291 -0
  59. package/src/web/state/model-catalog.ts +103 -0
  60. package/src/web/state/prefs.ts +19 -0
  61. package/src/web/state/router.ts +100 -0
  62. package/src/web/state/store.ts +266 -0
  63. package/src/web/styles/app.css +5337 -0
  64. package/src/web/tsconfig.json +14 -0
  65. package/src/static/dashboard-keys.js +0 -535
  66. package/src/static/dashboard-logs.js +0 -800
  67. package/src/static/dashboard.css +0 -2741
  68. package/src/static/dashboard.js +0 -3334
package/CHANGELOG.md CHANGED
@@ -2,6 +2,81 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [4.1.0] - 2026-10-13
6
+
7
+ ### Added
8
+
9
+ - **Models page**: a new dashboard page at `/dashboard/models` to manage connected providers and the models they serve. ([PR #39](https://github.com/tuxevil/tuxevil-rotator/pull/39) by [@CyR1en](https://github.com/CyR1en))
10
+ - Turn a provider off without signing its accounts out, turn it off for one account only, or turn individual models off. Models that are off leave `/v1/models` and `model: "auto"`, and requests for them get `404 model_not_found`.
11
+ - Set the provider order that decides who serves a model id more than one provider lists.
12
+ - Optionally hold models a provider adds later until you review them.
13
+ - Settings are saved as `providerOrder`, `disabledProviders`, `disabledModels`, `autoEnableNewModels` and `reviewedModels` in the configuration file; per-account switches are kept with the account's state. New `/api/catalog` admin endpoints back the page.
14
+ - The switches also cover requests that reach a model through an alias or effort routing, native `/v1internal` and `/api/chat` requests, audio transcription (with no Language Server fallback around them), benchmarks and warm-up requests.
15
+ - Accounts with every provider turned off show a new **Off** status instead of **Ready**.
16
+
17
+ ### Changed
18
+
19
+ - **One model-to-provider rule**: the proxy, the rotator and the OpenAI, Anthropic and Gemini endpoints now share one rule for which provider serves a model. Each provider lists its models, and ids no provider lists keep the old checks, so routing is unchanged by default.
20
+ - An Ollama model whose name ends in `-free` now goes to Ollama instead of OpenCode Zen when Zen does not list it.
21
+ - `/v1/models` lists an id that more than one provider serves once, under the provider its requests go to.
22
+ - `/v1/messages` answers a Codex model with `400` and a pointer to `/v1/chat/completions` and `/v1/responses`, instead of sending it to Codex in the wrong format.
23
+
24
+ ### Improved
25
+
26
+ - **Codex authentication visibility**: Rejected Codex credentials now appear in the dashboard's Needs you list and the Accounts Needs attention filter, with a direct link to the affected account.
27
+
28
+ ### Fixed
29
+
30
+ - **Dispatch-time switches**: recheck per-account provider switches after token validation in compatibility and native requests, release reservations, and re-admit another account when possible. HTTP audio transcription and WebSocket segments retain the requested model (including `whisper-1`) for dispatch-time checks, so switching it off prevents forwarding and Language Server fallback. Benchmarks also recheck switches after token validation. ([PR #39](https://github.com/tuxevil/tuxevil-rotator/pull/39) by [@CyR1en](https://github.com/CyR1en))
31
+ - **Dashboard provider visibility**: connected providers appear on Overview even before quota data arrives; removed redundant provider grouping headings.
32
+ - **Ollama savings estimates**: align estimated savings with official model pricing.
33
+ - **Dashboard dev server**: `npm run dashboard:dev` no longer crashes on `GET /v1/models`.
34
+ - **Settings writes**: writes to one settings key now run in order, so quick successive changes can no longer leave an older configuration or state on disk.
35
+ - **Ollama quota polling**: Read remaining credits and renewal dates from `/api/balance` instead of treating the consumption histogram at `/api/usage` as quota data. Overview and account details show actual credit balances, invalid responses preserve prior quotas, and purchased credits remain routable after the included balance runs out.
36
+ - **Codex reauthentication state**: A successful Codex login now clears the previous provider rejection and cached Codex access token, so reauthenticated accounts leave Needs attention immediately.
37
+
38
+ ### Contributors
39
+
40
+ - Thanks to [@CyR1en](https://github.com/CyR1en) for the Models page, shared provider catalogs, routing controls, account identity handling, switch-enforcement fixes, documentation, and regression tests in [PR #39](https://github.com/tuxevil/tuxevil-rotator/pull/39).
41
+
42
+ ## [4.0.0] - 2026-10-05
43
+
44
+ ### Changed
45
+
46
+ - **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))
47
+ - **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.
48
+ - **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.
49
+ - **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.
50
+ - **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.
51
+ - **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.
52
+ - **Shareable URLs.** Every view, filter and the open drawer is in the URL. `/dashboard/logs` redirects to the request history.
53
+ - **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.
54
+ - **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.
55
+
56
+ ### Security
57
+
58
+ - **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.
59
+ - **Content Security Policy**: dashboard pages are served with `script-src 'self'`, `style-src 'self'`, `frame-ancestors 'none'` and no inline handlers or styles.
60
+
61
+ ### Improved
62
+
63
+ - **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.
64
+
65
+ ### Added
66
+
67
+ - **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.
68
+
69
+ ### Fixed
70
+
71
+ - **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.
72
+ - **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.
73
+ - **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.
74
+
75
+ ### Documentation
76
+
77
+ - **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`.
78
+ - **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.
79
+
5
80
  ## [3.11.0] - 2026-10-03
6
81
 
7
82
  ### Added
package/README.md CHANGED
@@ -53,6 +53,9 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
53
53
 
54
54
  ## Current Model Update
55
55
 
56
+ - **v4.1.0: Models and provider controls**: Manage provider order, provider and per-account switches, individual model availability, and review of newly discovered models at `/dashboard/models`. Controls apply to aliases, automatic routing, native requests, audio, benchmarks, and warm-up. Includes Ollama credit-balance polling and clearer Codex reauthentication status. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.1.0); [PR #39](https://github.com/tuxevil/tuxevil-rotator/pull/39) by [@CyR1en](https://github.com/CyR1en))
57
+
58
+ - **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))
56
59
  - **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))
57
60
  - **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))
58
61
  - **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))
@@ -157,7 +160,7 @@ Existing `enc:v1` records remain decryptable during migration; newly written rec
157
160
  - **Virtual Keys & access control** — Issue scoped `rk-...` keys for teams, agents, or CI pipelines with per-key model restrictions
158
161
  - **Spend logging & audit inspector** — Full request/response audit trail with 6-decimal USD cost estimates for both Antigravity and Ollama traffic (requires PostgreSQL)
159
162
  - **Legacy importer** — On startup, automatically merges Ollama Cloud accounts from `~/.ollama-rotator/accounts.json` (the predecessor product) onto existing accounts, idempotently
160
- - **Web dashboard** — Real-time routing state, quota bars, latency tracking (p50/p95), savings chart, activity heatmap, and routing inspector
163
+ - **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
161
164
  - **State persistence** — Survives restarts; routing assignments, cooldowns, and flags saved to disk or PostgreSQL
162
165
  - **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).
163
166
  - **Reasoning/thinking visibility** — Interleaved thinking blocks exposed as `reasoning_content` / `thinking_delta` in real time
@@ -266,6 +269,8 @@ graph LR
266
269
  I -.Usage API<br/>every 5 min.-> B
267
270
  ```
268
271
 
272
+ Ollama Cloud quotas come from `GET /api/balance`: the dashboard shows included credit balances, purchased credits, and provider-reported renewal dates. `GET /api/usage` now reports historical consumption rather than remaining quota. Unrecognized quota responses retain the last known values.
273
+
269
274
  Each model routes to its own best available account independently. The same email can hold both a Google OAuth credential and an Ollama Cloud API key (parent-account model) — the rotator picks the right credential at request time based on the destination model.
270
275
 
271
276
  How model routing works:
@@ -279,20 +284,20 @@ How model routing works:
279
284
 
280
285
  ## Dashboard
281
286
 
282
- After starting the proxy, open `http://localhost:51200/dashboard`.
287
+ 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.
288
+
289
+ - **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
290
+ - **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)
291
+ - **Models** — provider order, provider and per-account switches, individual model switches, quota and health summaries, and optional review of newly discovered models
292
+ - **Requests** — a live tail of requests and rotator events, and with PostgreSQL the full history with payloads and per-key totals
293
+ - **Usage** — token volume by model with 1h–30d ranges, estimated savings at list prices, latency percentiles and a 60-day activity heatmap
294
+ - **Virtual keys** and **Settings** — key management, routing controls and policy, a benchmark, and the raw configuration file
283
295
 
284
- The dashboard shows:
285
- - **Routing state** — real-time status, uptime, requests, protective pause timers
286
- - **Account cards** — quota bars (Antigravity family buckets `claude` / `gemini`; Ollama monthly usage), per-model timers, health scores, flagged alerts
287
- - **Token usage & savings** — interactive chart with time ranges and CSV/JSON export (real USD for both providers)
288
- - **Latency (p50/p95)** — per-model TTFB and total duration
289
- - **Activity heatmap** — 60-day GitHub-style request intensity grid
290
- - **Quota forecast** — tier-weighted depletion predictions
291
- - **Routing inspector** — on-demand modal with candidate scores, health-score breakdown, and rejection reasons
296
+ 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.
292
297
 
293
298
  ![Dashboard](dashboard.png)
294
299
 
295
- [Dashboard reference →](docs/adding-accounts.md)
300
+ [Dashboard guide →](docs/dashboard.md)
296
301
 
297
302
  ## Virtual Keys & Spend Logging
298
303
 
@@ -317,6 +322,7 @@ tuxevil-rotator keys generate --alias "cursor-agent" --models "gemini-3.6-flash-
317
322
  |-------|------|
318
323
  | How It Works | [docs/how-it-works.md](docs/how-it-works.md) |
319
324
  | Configuration | [docs/configuration.md](docs/configuration.md) |
325
+ | Dashboard | [docs/dashboard.md](docs/dashboard.md) |
320
326
  | Virtual Keys & Spend Logging | [docs/virtual-keys.md](docs/virtual-keys.md) |
321
327
  | API Reference | [docs/api-reference.md](docs/api-reference.md) |
322
328
  | Compatibility Adapters | [docs/compatibility.md](docs/compatibility.md) |
@@ -371,7 +377,7 @@ Thanks to these amazing people who have contributed to the project:
371
377
 
372
378
  - **[@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))
373
379
  - **[@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))
374
- - **[@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))
380
+ - **[@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, the Models page with provider/model controls and dispatch-time switch enforcement, 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), [PR #39](https://github.com/tuxevil/tuxevil-rotator/pull/39))
375
381
  - **[@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))
376
382
  - **[@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))
377
383
  - **[@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.11.0",
3
+ "version": "4.1.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 { randomBytes } from "node:crypto";
3
- import { getCachedAdminToken, setCachedAdminToken } from "./db-store.js";
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
- return getRequestAdminToken(req) === expectedToken;
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",
@@ -14,6 +14,7 @@ import type { AccountRotator } from "./rotator.js";
14
14
  import { withRotation, type RequestBody } from "./proxy.js";
15
15
  import { extractRetryAfterSeconds } from "./compat.js";
16
16
  import { getModelSpec } from "./compat/model-specs.js";
17
+ import { isRequestOff, modelOffMessage } from "./model-catalog.js";
17
18
 
18
19
  const audioLogger = logger.child("audio-transcription");
19
20
  const AUDIO_SESSION_START_TIMEOUT_MS = 10_000;
@@ -111,6 +112,8 @@ export function resolveMimeType(fileName: string, mimeType?: string): string {
111
112
  export interface TranscribeOptions {
112
113
  mimeType?: string;
113
114
  model?: string;
115
+ /** Model the client asked for (e.g. whisper-1), rechecked against the switches at dispatch. */
116
+ catalogModel?: string;
114
117
  prompt?: string;
115
118
  language?: string;
116
119
  signal?: AbortSignal;
@@ -272,6 +275,7 @@ export async function transcribeAudioWithRotator(
272
275
 
273
276
  const body: RequestBody = {
274
277
  model: targetModel,
278
+ catalogModel: options.catalogModel,
275
279
  project: "",
276
280
  request: {
277
281
  contents: [
@@ -935,6 +939,21 @@ export async function handleOpenAIAudioTranscriptions(
935
939
  sendAuthErrorResponse(res, modelAuth);
936
940
  return;
937
941
  }
942
+ if (rotator && isRequestOff(rotator, { model: executedModel, catalogModel: requestedModel ?? "whisper-1" })) {
943
+ logRequest("failure");
944
+ res.writeHead(404, { "Content-Type": "application/json" });
945
+ res.end(
946
+ JSON.stringify({
947
+ error: {
948
+ message: modelOffMessage(requestedModel ?? "whisper-1"),
949
+ type: "invalid_request_error",
950
+ param: "model",
951
+ code: "model_not_found",
952
+ },
953
+ }),
954
+ );
955
+ return;
956
+ }
938
957
  // Every executed request is accounted to the model that actually ran upstream.
939
958
  spendModel = executedModel;
940
959
  apiKeyHash = modelAuth.key?.tokenHash || (modelAuth.rawKey ? hashKey(modelAuth.rawKey) : apiKeyHash);
@@ -976,6 +995,7 @@ export async function handleOpenAIAudioTranscriptions(
976
995
  transcribedText = await transcribeAudioWithRotator(rotator, audioBuffer, {
977
996
  mimeType,
978
997
  model: executedModel,
998
+ catalogModel: requestedModel ?? "whisper-1",
979
999
  prompt,
980
1000
  language,
981
1001
  signal: transcriptionSignal,
@@ -984,6 +1004,10 @@ export async function handleOpenAIAudioTranscriptions(
984
1004
  if (clientAbortController.signal.aborted || isRotatorTranscriptionTimeout(rotatorErr)) {
985
1005
  throw rotatorErr;
986
1006
  }
1007
+ // A switch turned off mid-request: the fallback would bypass it.
1008
+ if (isRequestOff(rotator, { model: executedModel, catalogModel: requestedModel ?? "whisper-1" })) {
1009
+ throw new AudioTranscriptionError(modelOffMessage(requestedModel ?? "whisper-1"), 404);
1010
+ }
987
1011
  audioLogger.warn(
988
1012
  `Rotator transcription failed: ${(rotatorErr as Error).message}, attempting Language Server fallback`,
989
1013
  );
@@ -1050,7 +1074,7 @@ export async function handleOpenAIAudioTranscriptions(
1050
1074
  logRequest("failure");
1051
1075
  audioLogger.error(`Transcription failed: ${error.message}`);
1052
1076
  const status =
1053
- err instanceof AudioTranscriptionError && [429, 502, 503, 504].includes(err.status) ? err.status : 500;
1077
+ err instanceof AudioTranscriptionError && [404, 429, 502, 503, 504].includes(err.status) ? err.status : 500;
1054
1078
  let retrySec: number | null = null;
1055
1079
  if (err instanceof AudioTranscriptionError && (status === 429 || status === 503)) {
1056
1080
  retrySec = err.retryAfterMs
@@ -1066,8 +1090,8 @@ export async function handleOpenAIAudioTranscriptions(
1066
1090
  JSON.stringify({
1067
1091
  error: {
1068
1092
  message: `Transcription error: ${error.message}`,
1069
- type: status === 429 ? "rate_limit_error" : "api_error",
1070
- code: status === 429 ? "rate_limit_exceeded" : null,
1093
+ type: status === 429 ? "rate_limit_error" : status === 404 ? "invalid_request_error" : "api_error",
1094
+ code: status === 429 ? "rate_limit_exceeded" : status === 404 ? "model_not_found" : null,
1071
1095
  ...(retrySec ? { retry_after_seconds: retrySec } : {}),
1072
1096
  },
1073
1097
  }),
@@ -1684,6 +1708,7 @@ export function appendDeduplicated(existing: string, addition: string): string {
1684
1708
  export class RotatorAudioSession implements AudioTranscriptionSession {
1685
1709
  public sessionId: string;
1686
1710
  public model: string;
1711
+ private catalogModel?: string;
1687
1712
  public continuous: boolean;
1688
1713
  public language?: string;
1689
1714
  private rotator: AccountRotator;
@@ -1725,6 +1750,7 @@ export class RotatorAudioSession implements AudioTranscriptionSession {
1725
1750
  rotator: AccountRotator,
1726
1751
  options: {
1727
1752
  model?: string;
1753
+ catalogModel?: string;
1728
1754
  continuous?: boolean;
1729
1755
  language?: string;
1730
1756
  onEvent?: (event: any) => void;
@@ -1734,6 +1760,7 @@ export class RotatorAudioSession implements AudioTranscriptionSession {
1734
1760
  this.rotator = rotator;
1735
1761
  this.sessionId = `session-rotator-${Date.now()}-${crypto.randomUUID()}`;
1736
1762
  this.model = resolveAudioTranscriptionModel(options.model);
1763
+ this.catalogModel = options.catalogModel;
1737
1764
  this.continuous = options.continuous ?? false;
1738
1765
  this.language = options.language;
1739
1766
  this.onEvent = options.onEvent || (() => {});
@@ -1892,6 +1919,7 @@ export class RotatorAudioSession implements AudioTranscriptionSession {
1892
1919
  try {
1893
1920
  rawText = await transcribeAudioWithRotator(this.rotator, wav, {
1894
1921
  model: this.model,
1922
+ catalogModel: this.catalogModel,
1895
1923
  language: this.language,
1896
1924
  timeoutMs: LIVE_ROTATOR_TRANSCRIPTION_TIMEOUT_MS,
1897
1925
  signal: segmentSignal,
@@ -1918,6 +1946,9 @@ export class RotatorAudioSession implements AudioTranscriptionSession {
1918
1946
  if (this.abortController.signal.aborted || segmentDeadlineController.signal.aborted) {
1919
1947
  throw rotatorErr;
1920
1948
  }
1949
+ if (isRequestOff(this.rotator, { model: this.model, catalogModel: this.catalogModel })) {
1950
+ throw new AudioTranscriptionError(modelOffMessage(this.catalogModel ?? this.model), 404);
1951
+ }
1921
1952
  audioLogger.warn(
1922
1953
  `[RotatorAudioSession] Segment #${item.seqId} rotator transcription failed: ${(rotatorErr as Error)?.message || rotatorErr}, attempting Language Server fallback`,
1923
1954
  );
@@ -2184,7 +2215,7 @@ async function authorizeClientModel(
2184
2215
  function createClientSession(
2185
2216
  client: AudioWsClient,
2186
2217
  model: string,
2187
- options: { preCursorText?: string; postCursorText?: string; continuous?: boolean; language?: string },
2218
+ options: { catalogModel?: string; preCursorText?: string; postCursorText?: string; continuous?: boolean; language?: string },
2188
2219
  ): AudioTranscriptionSession {
2189
2220
  client.tStartTime = Date.now();
2190
2221
  client.tFirstAntigravity = null;
@@ -2270,6 +2301,14 @@ async function handleClientCommand(client: AudioWsClient, cmd: any): Promise<voi
2270
2301
  const requested = cmd.antigravityModel || cmd.model ? String(cmd.antigravityModel || cmd.model) : undefined;
2271
2302
  const model = resolveClientExecutedModel(client, requested);
2272
2303
  if (!(await authorizeClientModel(client, model, requested))) return;
2304
+ if (
2305
+ client.rotator &&
2306
+ typeof client.rotator.getActiveAccount === "function" &&
2307
+ isRequestOff(client.rotator, { model, catalogModel: requested ?? "whisper-1" })
2308
+ ) {
2309
+ client.send({ type: "antigravity_error", event: "error", message: modelOffMessage(requested ?? model) });
2310
+ return;
2311
+ }
2273
2312
  if (client.antigravity) {
2274
2313
  finishClientSpend(client, "success");
2275
2314
  destroyClientSession(client);
@@ -2282,6 +2321,7 @@ async function handleClientCommand(client: AudioWsClient, cmd: any): Promise<voi
2282
2321
  });
2283
2322
 
2284
2323
  const session = createClientSession(client, model, {
2324
+ catalogModel: requested ?? "whisper-1",
2285
2325
  preCursorText: cmd.preCursorText || "",
2286
2326
  postCursorText: cmd.postCursorText || "",
2287
2327
  continuous: cmd.continuous ?? false,