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.
Files changed (53) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +22 -12
  3. package/package.json +8 -4
  4. package/src/admin-auth.ts +233 -3
  5. package/src/dashboard-app.ts +257 -0
  6. package/src/dashboard-live.ts +654 -0
  7. package/src/dashboard-types.ts +192 -0
  8. package/src/dashboard.ts +165 -732
  9. package/src/db-store.ts +43 -0
  10. package/src/exposure.ts +21 -1
  11. package/src/providers/opencode-zen/catalog.ts +2 -0
  12. package/src/providers/opencode-zen/forward.ts +18 -15
  13. package/src/providers/opencode-zen/login.ts +2 -1
  14. package/src/providers/opencode-zen/quota.ts +2 -1
  15. package/src/proxy.ts +71 -25
  16. package/src/rotator.ts +30 -30
  17. package/src/settings-repository.ts +7 -0
  18. package/src/types.ts +2 -0
  19. package/src/web/app.tsx +765 -0
  20. package/src/web/components/charts.tsx +338 -0
  21. package/src/web/components/command.tsx +279 -0
  22. package/src/web/components/icons.tsx +357 -0
  23. package/src/web/components/overlays.tsx +432 -0
  24. package/src/web/components/ui.tsx +421 -0
  25. package/src/web/lib/accounts.ts +109 -0
  26. package/src/web/lib/attention.ts +219 -0
  27. package/src/web/lib/colors.ts +103 -0
  28. package/src/web/lib/format.ts +113 -0
  29. package/src/web/lib/mask.ts +92 -0
  30. package/src/web/lib/pools.ts +199 -0
  31. package/src/web/lib/status.ts +242 -0
  32. package/src/web/lib/usage.ts +296 -0
  33. package/src/web/main.tsx +16 -0
  34. package/src/web/nav.ts +28 -0
  35. package/src/web/pages/AccountDetail.tsx +346 -0
  36. package/src/web/pages/Accounts.tsx +581 -0
  37. package/src/web/pages/Keys.tsx +431 -0
  38. package/src/web/pages/Overview.tsx +600 -0
  39. package/src/web/pages/Requests.tsx +644 -0
  40. package/src/web/pages/Settings.tsx +546 -0
  41. package/src/web/pages/Usage.tsx +346 -0
  42. package/src/web/pages/shared.ts +36 -0
  43. package/src/web/state/actions.ts +211 -0
  44. package/src/web/state/api.ts +273 -0
  45. package/src/web/state/prefs.ts +19 -0
  46. package/src/web/state/router.ts +92 -0
  47. package/src/web/state/store.ts +266 -0
  48. package/src/web/styles/app.css +5043 -0
  49. package/src/web/tsconfig.json +14 -0
  50. package/src/static/dashboard-keys.js +0 -535
  51. package/src/static/dashboard-logs.js +0 -800
  52. package/src/static/dashboard.css +0 -2741
  53. package/src/static/dashboard.js +0 -3334
package/src/dashboard.ts CHANGED
@@ -1,12 +1,30 @@
1
- // Web dashboard for monitoring account rotation status
1
+ // Admin API handlers behind the web dashboard. The dashboard UI itself is the
2
+ // Preact app in src/web, served by dashboard-app.ts.
2
3
 
3
- import { readFileSync } from "node:fs";
4
- import { join, dirname } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
4
  import type { IncomingMessage, ServerResponse } from "node:http";
7
5
  import type { Config } from "./types.js";
8
6
  import type { AccountRotator } from "./rotator.js";
7
+ import type { SessionInfo } from "./dashboard-types.js";
9
8
  import { readLimitedBody } from "./body-limit.js";
9
+ import {
10
+ clearDashboardSessionCookie,
11
+ createDashboardSession,
12
+ dashboardSessionCookie,
13
+ getConfiguredAdminToken,
14
+ hasValidDashboardSession,
15
+ isAdminAuthorized,
16
+ isAdminTokenValid,
17
+ isSecureRequest,
18
+ revokeDashboardSession,
19
+ } from "./admin-auth.js";
20
+ import {
21
+ buildActivity,
22
+ buildUsage,
23
+ isUsageRange,
24
+ tokenUsageCsv,
25
+ type DashboardLiveHub,
26
+ } from "./dashboard-live.js";
27
+ import { sendDashboardJson } from "./dashboard-app.js";
10
28
  import {
11
29
  generateVirtualKey,
12
30
  listVirtualKeys,
@@ -20,73 +38,6 @@ import { logger } from "./logger.js";
20
38
 
21
39
  const dashboardLogger = logger.child("dashboard");
22
40
 
23
- const __dirname = dirname(fileURLToPath(import.meta.url));
24
-
25
- // Static assets are read once at startup and served via dedicated routes.
26
- const DASHBOARD_CSS = readFileSync(
27
- join(__dirname, "static", "dashboard.css"),
28
- "utf-8",
29
- );
30
- const DASHBOARD_JS = readFileSync(
31
- join(__dirname, "static", "dashboard.js"),
32
- "utf-8",
33
- );
34
- const DASHBOARD_KEYS_JS = readFileSync(
35
- join(__dirname, "static", "dashboard-keys.js"),
36
- "utf-8",
37
- );
38
- const DASHBOARD_LOGS_JS = readFileSync(
39
- join(__dirname, "static", "dashboard-logs.js"),
40
- "utf-8",
41
- );
42
-
43
- export function serveDashboard(res: ServerResponse): void {
44
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
45
- res.end(DASHBOARD_HTML);
46
- }
47
-
48
- export function serveStaticCss(res: ServerResponse): void {
49
- res.writeHead(200, {
50
- "Content-Type": "text/css; charset=utf-8",
51
- "Cache-Control": "no-cache, must-revalidate",
52
- });
53
- res.end(DASHBOARD_CSS);
54
- }
55
-
56
- export function serveStaticJs(res: ServerResponse): void {
57
- res.writeHead(200, {
58
- "Content-Type": "application/javascript; charset=utf-8",
59
- "Cache-Control": "no-cache, must-revalidate",
60
- });
61
- res.end(DASHBOARD_JS);
62
- }
63
-
64
- export function serveStaticKeysJs(res: ServerResponse): void {
65
- res.writeHead(200, {
66
- "Content-Type": "application/javascript; charset=utf-8",
67
- "Cache-Control": "no-cache, must-revalidate",
68
- });
69
- res.end(DASHBOARD_KEYS_JS);
70
- }
71
-
72
- export function serveStaticLogsJs(res: ServerResponse): void {
73
- res.writeHead(200, {
74
- "Content-Type": "application/javascript; charset=utf-8",
75
- "Cache-Control": "no-cache, must-revalidate",
76
- });
77
- res.end(DASHBOARD_LOGS_JS);
78
- }
79
-
80
- export function serveDashboardKeys(res: ServerResponse): void {
81
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
82
- res.end(DASHBOARD_KEYS_HTML);
83
- }
84
-
85
- export function serveDashboardLogs(res: ServerResponse): void {
86
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
87
- res.end(DASHBOARD_LOGS_HTML);
88
- }
89
-
90
41
  export function serveStatusApi(
91
42
  res: ServerResponse,
92
43
  rotator: AccountRotator,
@@ -495,676 +446,158 @@ export async function serveGetSpendByKeyApi(
495
446
  }
496
447
  }
497
448
 
498
- function renderAppShell(opts: {
499
- title: string;
500
- activeTab: "accounts" | "keys" | "logs";
501
- contentHtml: string;
502
- scriptSrc: string;
503
- }): string {
504
- const pageTitle = opts.title === "Tuxevil Rotator" ? opts.title : (opts.title + " — Tuxevil Rotator");
505
- return `<!DOCTYPE html>
506
- <html lang="en">
507
- <head>
508
- <meta charset="utf-8">
509
- <meta name="viewport" content="width=device-width, initial-scale=1">
510
- <title>${pageTitle}</title>
511
- <link rel="stylesheet" href="/static/dashboard.css">
512
- </head>
513
- <body class="${opts.activeTab}-page">
514
-
515
- <div class="update-banner" id="updateBanner">
516
- <span class="update-badge" id="updateBadgeLabel">NEW</span>
517
- <div class="update-message" id="updateMessage"></div>
518
- <div class="update-banner-actions" id="updateActions"></div>
519
- </div>
520
-
521
- <div class="notif-container" id="notifContainer"></div>
449
+ // ── Dashboard session (cookie exchanged for the admin token) ─────────────
522
450
 
523
- <div class="header">
524
- <div class="header-main">
525
- <div class="header-title-row">
526
- <div class="header-brand-group">
527
- <h1>Tuxevil Rotator</h1>
528
- <span class="header-version" id="headerVersion">v--</span>
529
- <button id="maskBtn" class="mask-btn" onclick="toggleMask()">PII: Visible</button>
530
- </div>
531
-
532
- <nav class="header-nav-bar" id="appNav">
533
- <a class="header-nav-tab ${opts.activeTab === "accounts" ? "active" : ""}" id="navAccounts" href="/dashboard">
534
- <svg viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
535
- Accounts
536
- </a>
537
- <a class="header-nav-tab ${opts.activeTab === "keys" ? "active" : ""}" id="navKeys" href="/dashboard/keys">
538
- <svg viewBox="0 0 24 24"><path d="m21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
539
- Virtual Keys
540
- </a>
541
- <a class="header-nav-tab ${opts.activeTab === "logs" ? "active" : ""}" id="navLogs" href="/dashboard/logs">
542
- <svg viewBox="0 0 24 24"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
543
- Spend Logs
544
- </a>
545
- </nav>
546
- </div>
547
- <div class="header-stats">
548
- Uptime: <span id="uptime">--</span> |
549
- Port: <span id="port">--</span> |
550
- Rotation: <span id="rotation">--</span> reqs |
551
- Updated: <span id="lastRefresh">--</span> |
552
- Requests: <span id="totalRequests">0</span>
553
- </div>
554
- </div>
555
- <div class="header-actions">
556
- <button class="header-icon-btn attention" id="attentionBtn" onclick="openModal('attentionModal')" title="Attention Needed" aria-label="Open attention needed">
557
- <svg viewBox="0 0 24 24"><path d="M12 8v5"/><path d="M12 17.5h.01"/><path d="M10.3 3.8 2.9 17a2 2 0 0 0 1.75 3h14.7A2 2 0 0 0 21.1 17L13.7 3.8a2 2 0 0 0-3.4 0Z"/></svg>
558
- <span class="header-icon-badge attention" id="attentionBadge" style="display:none">0</span>
559
- </button>
560
-
561
- <button class="header-icon-btn heart-beat" id="kofiBtn" onclick="openModal('donationModal')" title="Support the Project" aria-label="Support the project">
562
- <svg viewBox="0 0 24 24"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>
563
- </button>
451
+ export function serveSessionInfoApi(
452
+ req: IncomingMessage,
453
+ res: ServerResponse,
454
+ ): void {
455
+ const token = getConfiguredAdminToken();
456
+ const info: SessionInfo = {
457
+ authRequired: Boolean(token),
458
+ authenticated: !token || isAdminAuthorized(req, token),
459
+ };
460
+ sendDashboardJson(req, res, 200, info);
461
+ }
564
462
 
565
- <a class="header-icon-btn website-btn" id="websiteBtn" href="https://tuxevil.com" target="_blank" title="tuxevil.com" aria-label="Visit tuxevil.com">
566
- <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
567
- </a>
568
- </div>
569
- </div>
463
+ /** Exchange `{ token }` for an HttpOnly session cookie. */
464
+ export async function serveCreateSessionApi(
465
+ req: IncomingMessage,
466
+ res: ServerResponse,
467
+ ): Promise<void> {
468
+ let candidate: unknown;
469
+ try {
470
+ const raw = await readLimitedBody(req, 4096);
471
+ candidate = raw.length > 0 ? JSON.parse(raw.toString("utf-8"))?.token : null;
472
+ } catch {
473
+ candidate = null;
474
+ }
475
+ const token = getConfiguredAdminToken();
476
+ if (!token) {
477
+ sendDashboardJson(req, res, 200, { ok: true, authRequired: false });
478
+ return;
479
+ }
480
+ if (typeof candidate !== "string" || !isAdminTokenValid(candidate.trim(), token)) {
481
+ sendDashboardJson(req, res, 401, { ok: false, error: "That admin token was not accepted." });
482
+ return;
483
+ }
484
+ const session = createDashboardSession(token);
485
+ res.setHeader(
486
+ "Set-Cookie",
487
+ dashboardSessionCookie(session.value, { secure: isSecureRequest(req) }),
488
+ );
489
+ sendDashboardJson(req, res, 200, { ok: true, expiresAt: session.expiresAt });
490
+ }
570
491
 
571
- <script>
572
- (function(){
573
- var urlParams = new URLSearchParams(window.location.search);
574
- var t = urlParams.get("token") || localStorage.getItem("rotatorAdminToken");
575
- var mask = urlParams.has("mask");
576
- if (t || mask) {
577
- ["navAccounts", "navKeys", "navLogs"].forEach(function(id) {
578
- var el = document.getElementById(id);
579
- if (el && el.getAttribute("href")) {
580
- var base = el.getAttribute("href").split("?")[0];
581
- var params = new URLSearchParams();
582
- if (t) params.set("token", t);
583
- if (mask) params.set("mask", "1");
584
- el.href = base + "?" + params.toString();
585
- }
492
+ export async function serveDeleteSessionApi(
493
+ req: IncomingMessage,
494
+ res: ServerResponse,
495
+ ): Promise<void> {
496
+ try {
497
+ await revokeDashboardSession(req);
498
+ } catch (err) {
499
+ dashboardLogger.error(`Failed to persist dashboard session revocation: ${err}`);
500
+ sendDashboardJson(req, res, 503, {
501
+ ok: false,
502
+ error: "Could not persist the sign-out. Please try again.",
586
503
  });
504
+ return;
587
505
  }
588
- })();
589
- </script>
590
-
591
- ${opts.contentHtml}
592
-
593
- <div class="modal" id="attentionModal" onclick="closeModal(event, 'attentionModal')">
594
- <div class="modal-card" onclick="event.stopPropagation()">
595
- <div class="modal-header">
596
- <strong>Attention Needed</strong>
597
- <button class="modal-close" onclick="closeModal(null, 'attentionModal')" aria-label="Close attention modal">×</button>
598
- </div>
599
- <div id="attentionPanel"></div>
600
- </div>
601
- </div>
602
-
603
- <div class="modal" id="donationModal" onclick="closeModal(event, 'donationModal')">
604
- <div class="modal-card" onclick="event.stopPropagation()" style="max-width: 500px;">
605
- <div class="modal-header">
606
- <strong>Support the Project</strong>
607
- <button class="modal-close" onclick="closeModal(null, 'donationModal')" aria-label="Close support modal">x</button>
608
- </div>
609
- <div style="padding: 16px; font-size: 0.95rem; line-height: 1.5; color: var(--text);">
610
- <p style="margin-bottom:12px;">If this tool has helped you save money on AI API costs, consider supporting its continued development.</p>
611
- <div style="display:flex;flex-direction:column;gap:16px;margin-bottom:20px;">
612
- <a href="https://ko-fi.com/tuxevil" target="_blank" style="display:inline-flex;flex-direction:column;align-items:center;background-color:#FF5E5B;color:white;padding:12px 24px;border-radius:6px;text-decoration:none;transition:opacity 0.2s;width:100%;box-sizing:border-box;text-align:center;" onmouseover="this.style.opacity='0.9'" onmouseout="this.style.opacity='1'">
613
- <span style="font-weight:bold;font-size:1.1rem;">Support on Ko-fi</span>
614
- <span style="font-size:0.85rem;margin-top:4px;opacity:0.85;">ko-fi.com/tuxevil</span>
615
- </a>
616
- <div style="width:100%; padding:14px; border: 1px solid var(--border); border-radius: 8px; background: rgba(255,255,255,0.02); box-sizing: border-box;">
617
- <p style="margin-bottom:10px;font-weight:bold;color:var(--accent);font-size:0.95rem;">Free ways to support</p>
618
- <ul style="margin-left:18px; font-size:0.85rem; color:var(--text-dim); line-height:1.7; list-style:none; padding:0;">
619
- <li style="margin-bottom:6px;margin-left:0;">&#11088; <a href="https://github.com/tuxevil/tuxevil-rotator" target="_blank" style="color:var(--accent);text-decoration:underline;">Star the project on GitHub</a> — helps with visibility</li>
620
- <li style="margin-bottom:6px;margin-left:0;">&#128027; <a href="https://github.com/tuxevil/tuxevil-rotator/issues" target="_blank" style="color:var(--accent);text-decoration:underline;">Report bugs & contribute</a> — open issues or submit PRs</li>
621
- <li style="margin-bottom:0;margin-left:0;">&#128227; Share the project with colleagues or communities who might find it useful</li>
622
- </ul>
623
- </div>
624
- </div>
625
- <div style="text-align: center;">
626
- <button class="btn-secondary" onclick="hideDonationModalPermanently()">Dismiss</button>
627
- </div>
628
- </div>
629
- </div>
630
- </div>
631
-
632
- <footer class="app-footer">
633
- <div class="app-footer-inner">
634
- <span class="app-footer-brand">Tuxevil Rotator</span>
635
- <span class="app-footer-sep"></span>
636
- <a href="https://tuxevil.com" target="_blank">tuxevil.com</a>
637
- <span class="app-footer-sep"></span>
638
- <a href="https://github.com/tuxevil/tuxevil-rotator" target="_blank">GitHub</a>
639
- </div>
640
- </footer>
641
-
642
- <script src="${opts.scriptSrc}"></script>
643
- </body>
644
- </html>`;
506
+ res.setHeader("Set-Cookie", clearDashboardSessionCookie(isSecureRequest(req)));
507
+ sendDashboardJson(req, res, 200, { ok: true });
645
508
  }
646
509
 
647
- const DASHBOARD_HTML = renderAppShell({
648
- title: "Tuxevil Rotator",
649
- activeTab: "accounts",
650
- scriptSrc: "/static/dashboard.js",
651
- contentHtml: `
652
- <div class="accounts-dashboard">
653
- <div class="dashboard-intro">
654
- <div>
655
- <div class="dashboard-kicker">Operations / Account fleet</div>
656
- <h2>Keep the fleet moving.</h2>
657
- <p>Scan routing health, quota windows and account actions from one focused control room.</p>
658
- </div>
659
- <div class="dashboard-intro-actions">
660
- <span class="dashboard-live-chip"><span class="dashboard-live-dot"></span>Live polling</span>
661
- <button class="btn-secondary dashboard-refresh-btn" onclick="refresh()">Refresh now</button>
662
- </div>
663
- </div>
664
-
665
- <div class="view-toggle-bar">
666
- <button class="view-tab active" id="viewTabGrid" onclick="switchView('grid')">⊞ Grid</button>
667
- <button class="view-tab" id="viewTabList" onclick="switchView('list')">☰ List</button>
668
- </div>
669
-
670
- <div class="routing-panel state-stopped" id="routingHealth"></div>
671
-
672
- <div class="routing-panel" id="tokenUsagePanel" style="margin-top:12px">
673
- <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px">
674
- <strong style="min-width:max-content">Token Usage</strong>
675
- <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
676
- <div id="tokenTotals" style="font-family:JetBrains Mono,monospace;font-size:0.85rem;color:var(--text-dim);margin-right:12px"></div>
677
- <button class="btn-secondary btn-sm" onclick="exportData('csv')" title="Export CSV" style="padding:2px 6px">CSV</button>
678
- <button class="btn-secondary btn-sm" onclick="exportData('json')" title="Export JSON" style="padding:2px 6px;margin-right:8px">JSON</button>
679
- <div style="width:1px;height:16px;background:var(--border);margin-right:8px"></div>
680
- <button class="btn-secondary btn-sm" onclick="setTokenView('1h')" id="tbtn-1h">1h</button>
681
- <button class="btn-secondary btn-sm" onclick="setTokenView('2h')" id="tbtn-2h">2h</button>
682
- <button class="btn-secondary btn-sm" onclick="setTokenView('4h')" id="tbtn-4h">4h</button>
683
- <button class="btn-secondary btn-sm" onclick="setTokenView('8h')" id="tbtn-8h">8h</button>
684
- <button class="btn-secondary btn-sm" onclick="setTokenView('12h')" id="tbtn-12h">12h</button>
685
- <button class="btn-secondary btn-sm" onclick="setTokenView('1d')" id="tbtn-1d">1d</button>
686
- <button class="btn-secondary btn-sm" onclick="setTokenView('7d')" id="tbtn-7d">7d</button>
687
- <button class="btn-secondary btn-sm" onclick="setTokenView('1m')" id="tbtn-1m">1m</button>
688
- </div>
689
- </div>
690
- <div id="tokenChart" style="width:100%;overflow-x:auto"></div>
691
- <div id="tokenLegend" style="margin-top:8px;display:flex;gap:16px;flex-wrap:wrap;font-size:0.8rem"></div>
692
- </div>
693
-
694
- <div class="routing-panel" id="latencyPanel" style="margin-top:12px;display:none">
695
- <strong>Latency (last 200 requests)</strong>
696
- <div id="latencyGrid" style="margin-top:8px"></div>
697
- </div>
698
-
699
- <div class="routing-panel" id="forecastPanel" style="margin-top:12px;display:none">
700
- <strong>Quota Forecast</strong>
701
- <div id="forecastGrid" style="margin-top:8px"></div>
702
- </div>
703
-
704
- <div class="routing-panel" id="benchmarkPanel" style="margin-top:12px">
705
- <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
706
- <div>
707
- <strong>Account Benchmark</strong>
708
- <div id="benchmarkStatus" style="color:var(--text-dim);font-size:0.8rem;margin-top:4px">Measure active account performance without persisting results.</div>
709
- </div>
710
- <button class="btn-secondary" id="benchmarkBtn" onclick="runBenchmark()">Benchmark Active Accounts</button>
711
- </div>
712
- <div id="benchmarkResults" style="margin-top:12px;overflow-x:auto"></div>
713
- </div>
714
-
715
- <div class="accounts-grid" id="accounts"></div>
716
-
717
- <div class="list-panel" id="listPanel" style="display:none">
718
- <div class="list-toolbar">
719
- <span class="list-toolbar-label">Installations</span>
720
- <input class="list-search" id="listSearch" placeholder="Search…" oninput="renderListView()" />
721
- <button class="list-sort-btn" id="lsort-requests" onclick="setListSort('requests')">Requests ↕</button>
722
- <button class="list-sort-btn" id="lsort-quota" onclick="setListSort('quota')">Quota ↕</button>
723
- <button class="list-sort-btn" id="lsort-tokens" onclick="setListSort('tokens')">Tokens ↕</button>
724
- <button class="list-sort-btn" id="lsort-status" onclick="setListSort('status')">Status ↕</button>
725
- </div>
726
- <div id="listTableWrap"></div>
727
- </div>
728
-
729
- <div class="routing-panel" id="heatmapPanel" style="margin-top:12px;display:none">
730
- <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
731
- <strong>Activity Heatmap (last 60d)</strong>
732
- <span style="color:var(--text-dim);font-size:0.75rem">rows: hour · cols: day</span>
733
- </div>
734
- <div id="heatmapGrid"></div>
735
- </div>
736
-
737
- <div class="routing-panel" id="requestLogPanel" style="margin-top:12px;display:none">
738
- <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
739
- <strong>Request Log</strong>
740
- <div style="display:flex;gap:6px">
741
- <input id="logFilterModel" placeholder="model" style="background:var(--card-bg);border:1px solid var(--border);color:var(--text);padding:2px 6px;border-radius:4px;font-size:0.75rem;width:100px" />
742
- <input id="logFilterAccount" placeholder="account" style="background:var(--card-bg);border:1px solid var(--border);color:var(--text);padding:2px 6px;border-radius:4px;font-size:0.75rem;width:100px" />
743
- <input id="logFilterStatus" placeholder="status" style="background:var(--card-bg);border:1px solid var(--border);color:var(--text);padding:2px 6px;border-radius:4px;font-size:0.75rem;width:60px" />
744
- </div>
745
- </div>
746
- <div id="requestLogGrid" style="max-height:320px;overflow-y:auto"></div>
747
- </div>
748
-
749
- <div class="events-panel" id="recentEventsPanel" style="display:none"></div>
750
-
751
- </div>
752
-
753
- <div class="modal" id="configEditorModal" onclick="closeModal(event, 'configEditorModal')">
754
- <div class="modal-card" onclick="event.stopPropagation()" style="max-width: 960px; width: min(960px, 92vw);">
755
- <div class="modal-header">
756
- <strong>Config Editor</strong>
757
- <button class="modal-close" onclick="closeModal(null, 'configEditorModal')" aria-label="Close config editor modal">×</button>
758
- </div>
759
- <div style="padding:16px;">
760
- <div style="display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px">
761
- <div id="configEditorStatus" style="font-size:12px;color:var(--text-dim)"></div>
762
- <div style="display:flex;gap:8px;flex-wrap:wrap">
763
- <button class="btn-secondary" onclick="loadConfigEditor()">Reload</button>
764
- <button class="btn-secondary" onclick="saveConfigEditor()">Save</button>
765
- <button class="btn-secondary" onclick="exportConfig()">Export</button>
766
- <button class="btn-secondary" onclick="importConfigPrompt()">Import</button>
767
- <button class="btn-secondary" onclick="window.location.href='/login' + (ADMIN_TOKEN ? ('?token=' + encodeURIComponent(ADMIN_TOKEN)) : '')">Hosted Login</button>
768
- </div>
769
- </div>
770
- <textarea id="configEditor" spellcheck="false" style="width:100%;min-height:420px;background:rgba(255,255,255,0.03);border:1px solid var(--border);border-radius:8px;color:var(--text);padding:12px;font-family:'JetBrains Mono', monospace;font-size:12px;line-height:1.5"></textarea>
771
- <div style="margin-top:8px;font-size:12px;color:var(--text-dim)">routingPolicy: timer-first, tier-first, quota-first, hybrid, sequential-quota o sticky-quota. Las políticas quota-aware evitan la rotación por contador; sticky-quota vuelve a la cuenta preferida después de un cooldown.</div>
772
- </div>
773
- </div>
774
- </div>
775
-
776
- <div class="modal" id="routingInspectorModal" onclick="closeModal(event, 'routingInspectorModal')">
777
- <div class="modal-card" onclick="event.stopPropagation()" style="max-width: 1100px; width: min(1100px, 94vw);">
778
- <div class="modal-header">
779
- <strong>Routing Inspector</strong>
780
- <button class="modal-close" onclick="closeModal(null, 'routingInspectorModal')" aria-label="Close routing inspector modal">×</button>
781
- </div>
782
- <div id="routingInspectorPanel" style="padding:16px;"></div>
783
- </div>
784
- </div>
785
- `,
786
- });
787
-
788
- const DASHBOARD_KEYS_HTML = renderAppShell({
789
- title: "Virtual Keys",
790
- activeTab: "keys",
791
- scriptSrc: "/static/dashboard-keys.js",
792
- contentHtml: `
793
- <div class="keys-workspace">
794
- <div class="workspace-intro">
795
- <div>
796
- <div class="workspace-kicker">Access / Credentials</div>
797
- <h2>Virtual Keys &amp; Access Control</h2>
798
- <p>Manage API credentials, agent assignments, and per-model authorization rules from one operator workspace.</p>
799
- </div>
800
- <div class="workspace-intro-actions">
801
- <span class="workspace-live-chip"><span class="workspace-live-dot"></span>Registry live</span>
802
- <button class="btn-modal-submit workspace-primary-action" onclick="showGenerateModal()" style="display:inline-flex;align-items:center;gap:8px">
803
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
804
- Generate Virtual Key
805
- </button>
806
- </div>
807
- </div>
808
-
809
- <div class="stats-summary-grid keys-stats">
810
- <div class="summary-card">
811
- <div class="summary-card-header">
812
- <span>Total Credentials</span>
813
- <div class="summary-card-icon">
814
- <svg viewBox="0 0 24 24"><path d="m21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
815
- </div>
816
- </div>
817
- <div class="summary-card-value" id="statTotalKeys">0</div>
818
- <div class="summary-card-sub">Registered virtual keys</div>
819
- </div>
820
-
821
- <div class="summary-card">
822
- <div class="summary-card-header">
823
- <span>Active Keys</span>
824
- <div class="summary-card-icon" style="background:rgba(52,211,153,0.1);color:var(--green)">
825
- <svg viewBox="0 0 24 24"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
826
- </div>
827
- </div>
828
- <div class="summary-card-value" id="statActiveKeys" style="color:var(--green)">0</div>
829
- <div class="summary-card-sub">Authorized for requests</div>
830
- </div>
831
-
832
- <div class="summary-card">
833
- <div class="summary-card-header">
834
- <span>Blocked Keys</span>
835
- <div class="summary-card-icon" style="background:rgba(248,113,113,0.1);color:var(--red)">
836
- <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
837
- </div>
838
- </div>
839
- <div class="summary-card-value" id="statBlockedKeys" style="color:var(--red)">0</div>
840
- <div class="summary-card-sub">Revoked access</div>
841
- </div>
842
-
843
- <div class="summary-card">
844
- <div class="summary-card-header">
845
- <span>Supported Models</span>
846
- <div class="summary-card-icon" style="background:rgba(96,165,250,0.1);color:var(--blue)">
847
- <svg viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
848
- </div>
849
- </div>
850
- <div class="summary-card-value" id="statAvailableModels">12</div>
851
- <div class="summary-card-sub">Gemini, Claude, GPT-OSS</div>
852
- </div>
853
- </div>
854
-
855
- <div class="list-panel keys-list-panel">
856
- <div class="list-toolbar keys-list-toolbar">
857
- <span class="list-toolbar-label">Virtual Keys</span>
858
- <div class="filter-input-group" style="width:260px">
859
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
860
- <input id="keySearchInput" placeholder="Search alias, key name, user..." oninput="renderKeys()">
861
- </div>
862
- <div class="filter-input-group" style="width:140px">
863
- <select id="keyStatusFilter" onchange="renderKeys()">
864
- <option value="all">All Statuses</option>
865
- <option value="active">Active Only</option>
866
- <option value="blocked">Blocked Only</option>
867
- </select>
868
- </div>
869
- </div>
870
-
871
- <div style="overflow-x:auto">
872
- <table class="compact-table">
873
- <thead>
874
- <tr>
875
- <th>Key Alias &amp; Name</th>
876
- <th>User ID</th>
877
- <th>Allowed Models</th>
878
- <th>Status</th>
879
- <th>Last Active</th>
880
- <th style="width:110px;text-align:right">Actions</th>
881
- </tr>
882
- </thead>
883
- <tbody id="keysTbody"></tbody>
884
- </table>
885
- </div>
886
- </div>
887
- </div>
888
-
889
- <div id="keyModal" class="modal" onclick="if(event.target===this) hideModal()">
890
- <div class="modal-card" onclick="event.stopPropagation()" style="max-width:640px;display:flex;flex-direction:column;max-height:90vh;overflow:hidden">
891
- <div class="modal-header">
892
- <div class="modal-title-group">
893
- <div class="modal-icon">
894
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path></svg>
895
- </div>
896
- <div>
897
- <h3 id="modalTitle" class="modal-title">Generate Virtual Key</h3>
898
- <p id="modalSubtitle" class="modal-subtitle">Configure key access and model restrictions</p>
899
- </div>
900
- </div>
901
- <button class="modal-close-btn" onclick="hideModal()" type="button" aria-label="Close">&times;</button>
902
- </div>
903
-
904
- <div class="modal-body" style="overflow-y:auto;flex:1">
905
- <div class="form-grid">
906
- <div class="form-group">
907
- <label class="form-label" for="keyFormAlias">Key Alias <span class="req">*</span></label>
908
- <input id="keyFormAlias" class="form-input" placeholder="e.g. cursor-agent" autofocus>
909
- </div>
910
- <div class="form-group">
911
- <label class="form-label" for="keyFormUserId">User ID <span class="opt">(optional)</span></label>
912
- <input id="keyFormUserId" class="form-input" placeholder="e.g. seba">
913
- </div>
914
- </div>
915
-
916
- <div id="modelCheckboxes" class="models-section">
917
- <div class="models-header">
918
- <div>
919
- <span class="form-label">Allowed Models</span>
920
- <span class="models-badge" id="modelsCountBadge">All models allowed</span>
921
- </div>
922
- <div class="models-actions">
923
- <button class="pill-btn" onclick="selectAllModels()" type="button">Select All</button>
924
- <button class="pill-btn" onclick="selectNoModels()" type="button">Clear All</button>
925
- </div>
926
- </div>
927
-
928
- <!--
929
- The model grid is populated dynamically by dashboard-keys.js from
930
- GET /api/models, which returns the live provider catalog (Google
931
- Antigravity + every active Ollama / OpenAI Codex / OpenCode Zen
932
- account). Each entry is grouped by its owned_by provider so the
933
- checkbox UI surfaces every model the rotator can actually route
934
- today, including those added by future providers.
935
- -->
936
- <div class="model-grid" id="modelGrid"></div>
937
- <div class="model-grid-empty" id="modelGridEmpty" style="display:none;color:var(--text-dim);font-size:0.85rem;padding:8px 0">
938
- No models available. Configure a provider or refresh.
939
- </div>
940
- </div>
941
-
942
- <div id="keyFormError" class="modal-error"></div>
943
-
944
- <div id="generatedKeyResult" class="generated-key-box" style="display:none">
945
- <div class="key-warn-header">
946
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>
947
- Save this key now — it won't be shown again!
948
- </div>
949
- <div class="raw" id="generatedRawKey"></div>
950
- <button id="copyKeyBtn" class="btn-secondary" onclick="copyRawKey()" style="margin-top:8px" type="button">Copy Key</button>
951
- </div>
952
- </div>
953
-
954
- <div class="modal-footer">
955
- <button class="btn-modal-cancel" onclick="hideModal()" type="button">Cancel</button>
956
- <button class="btn-modal-submit" onclick="submitKeyForm()" id="submitKeyBtn" type="button">Generate Key</button>
957
- </div>
958
- </div>
959
- </div>
960
- `,
961
- });
962
-
963
- const DASHBOARD_LOGS_HTML = renderAppShell({
964
- title: "Spend Logs",
965
- activeTab: "logs",
966
- scriptSrc: "/static/dashboard-logs.js",
967
- contentHtml: `
968
- <div class="logs-workspace">
969
- <div class="workspace-intro">
970
- <div>
971
- <div class="workspace-kicker">Observability / Spend telemetry</div>
972
- <h2>Spend Logs &amp; Usage Analytics</h2>
973
- <p>Trace request cost, token flow, latency, and payload context through a focused audit console.</p>
974
- </div>
975
- <div class="workspace-intro-actions">
976
- <span class="workspace-live-chip"><span class="workspace-live-dot"></span>Live audit</span>
977
- <button class="btn-secondary workspace-refresh-action" onclick="loadLogs(0)">Refresh logs</button>
978
- </div>
979
- </div>
980
-
981
- <div class="stats-summary-grid logs-stats">
982
- <div class="summary-card">
983
- <div class="summary-card-header">
984
- <span>Total Requests</span>
985
- <div class="summary-card-icon">
986
- <svg viewBox="0 0 24 24"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
987
- </div>
988
- </div>
989
- <div class="summary-card-value" id="statLogRequests">0</div>
990
- <div class="summary-card-sub" id="statLogRequestsSub">Logged requests</div>
991
- </div>
992
-
993
- <div class="summary-card">
994
- <div class="summary-card-header">
995
- <span>Prompt Tokens</span>
996
- <div class="summary-card-icon" style="background:rgba(124,92,252,0.1);color:var(--accent)">
997
- <svg viewBox="0 0 24 24"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>
998
- </div>
999
- </div>
1000
- <div class="summary-card-value" id="statLogPromptTokens">0</div>
1001
- <div class="summary-card-sub">Input tokens processed</div>
1002
- </div>
1003
-
1004
- <div class="summary-card">
1005
- <div class="summary-card-header">
1006
- <span>Completion Tokens</span>
1007
- <div class="summary-card-icon" style="background:rgba(52,211,153,0.1);color:var(--green)">
1008
- <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
1009
- </div>
1010
- </div>
1011
- <div class="summary-card-value" id="statLogCompletionTokens" style="color:var(--green)">0</div>
1012
- <div class="summary-card-sub">Output tokens generated</div>
1013
- </div>
1014
-
1015
- <div class="summary-card">
1016
- <div class="summary-card-header">
1017
- <span>Est. Cost</span>
1018
- <div class="summary-card-icon" style="background:rgba(59,130,246,0.1);color:#3b82f6">
1019
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
1020
- </div>
1021
- </div>
1022
- <div class="summary-card-value" id="statLogCost" style="color:#3b82f6">$0.000000</div>
1023
- <div class="summary-card-sub">Estimated USD cost</div>
1024
- </div>
1025
-
1026
- <div class="summary-card">
1027
- <div class="summary-card-header">
1028
- <span>Avg Latency</span>
1029
- <div class="summary-card-icon" style="background:rgba(251,191,36,0.1);color:var(--yellow)">
1030
- <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
1031
- </div>
1032
- </div>
1033
- <div class="summary-card-value" id="statLogAvgLatency" style="color:var(--yellow)">--</div>
1034
- <div class="summary-card-sub">Average round-trip duration</div>
1035
- </div>
1036
- </div>
1037
-
1038
- <div id="byKeySummary" class="logs-by-key-summary"></div>
1039
-
1040
- <div class="filter-panel logs-filter-panel">
1041
- <div class="logs-filter-heading">
1042
- <div>
1043
- <span class="logs-filter-kicker">Query console</span>
1044
- <strong>Filter request history</strong>
1045
- </div>
1046
- <span>Use filters to narrow the audit window, then expand any row for payload context.</span>
1047
- </div>
1048
- <div class="multiselect-container" id="keyMultiselectContainer">
1049
- <div class="multiselect-trigger" id="keyMultiselectTrigger" onclick="toggleMultiselect(event, 'key')">
1050
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
1051
- <span class="multiselect-label" id="keyMultiselectLabel">All Keys</span>
1052
- <svg class="multiselect-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
1053
- </div>
1054
- <div class="multiselect-menu" id="keyMultiselectMenu" style="display:none">
1055
- <div class="multiselect-header">
1056
- <input type="text" class="multiselect-search" id="keySearchInput" placeholder="Search keys..." onclick="event.stopPropagation()" oninput="filterMultiselectOptions('key')">
1057
- <div class="multiselect-actions">
1058
- <button type="button" class="multiselect-action-btn" onclick="selectAllMultiselect('key')">Select All</button>
1059
- <button type="button" class="multiselect-action-btn" onclick="clearMultiselect('key')">Clear</button>
1060
- </div>
1061
- </div>
1062
- <div class="multiselect-options" id="keyMultiselectOptions">
1063
- <div style="padding:8px;color:var(--text-dim);font-size:12px;text-align:center">Loading keys...</div>
1064
- </div>
1065
- </div>
1066
- </div>
1067
-
1068
- <div class="multiselect-container" id="modelMultiselectContainer">
1069
- <div class="multiselect-trigger" id="modelMultiselectTrigger" onclick="toggleMultiselect(event, 'model')">
1070
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
1071
- <span class="multiselect-label" id="modelMultiselectLabel">All Models</span>
1072
- <svg class="multiselect-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
1073
- </div>
1074
- <div class="multiselect-menu" id="modelMultiselectMenu" style="display:none">
1075
- <div class="multiselect-header">
1076
- <input type="text" class="multiselect-search" id="modelSearchInput" placeholder="Search models..." onclick="event.stopPropagation()" oninput="filterMultiselectOptions('model')">
1077
- <div class="multiselect-actions">
1078
- <button type="button" class="multiselect-action-btn" onclick="selectAllMultiselect('model')">Select All</button>
1079
- <button type="button" class="multiselect-action-btn" onclick="clearMultiselect('model')">Clear</button>
1080
- </div>
1081
- </div>
1082
- <div class="multiselect-options" id="modelMultiselectOptions">
1083
- <div style="padding:8px;color:var(--text-dim);font-size:12px;text-align:center">Loading models...</div>
1084
- </div>
1085
- </div>
1086
- </div>
1087
-
1088
- <div class="filter-input-group" style="width:150px">
1089
- <select id="filterStatus">
1090
- <option value="">All Statuses</option>
1091
- <option value="success">Success (200)</option>
1092
- <option value="failure">Failure / Error</option>
1093
- </select>
1094
- </div>
1095
-
1096
- <div class="filter-input-group" style="width:150px">
1097
- <input id="filterStartDate" type="date" title="From Date">
1098
- </div>
1099
-
1100
- <div class="filter-input-group" style="width:150px">
1101
- <input id="filterEndDate" type="date" title="To Date">
1102
- </div>
510
+ /**
511
+ * `/dashboard?token=…` links (printed by the CLI) trade the token for a
512
+ * session cookie and redirect to the same URL without it, so the token
513
+ * does not linger in history, bookmarks or Referer headers.
514
+ */
515
+ export function redirectDashboardTokenLink(
516
+ req: IncomingMessage,
517
+ res: ServerResponse,
518
+ ): boolean {
519
+ const url = new URL(req.url || "/", "http://localhost");
520
+ const candidate = url.searchParams.get("token");
521
+ if (candidate === null) return false;
522
+ url.searchParams.delete("token");
523
+ const token = getConfiguredAdminToken();
524
+ const headers: Record<string, string> = { "Cache-Control": "no-store" };
525
+ if (token && isAdminTokenValid(candidate, token)) {
526
+ const session = createDashboardSession(token);
527
+ headers["Set-Cookie"] = dashboardSessionCookie(session.value, {
528
+ secure: isSecureRequest(req),
529
+ });
530
+ } else if (token && !hasValidDashboardSession(req, token)) {
531
+ url.searchParams.set("auth", "invalid");
532
+ }
533
+ headers.Location = url.pathname + url.search;
534
+ res.writeHead(302, headers);
535
+ res.end();
536
+ return true;
537
+ }
1103
538
 
1104
- <button class="pill-btn" onclick="applyFilters()" style="background:var(--accent);color:#fff;border:none;padding:7px 14px;font-weight:600;cursor:pointer">Apply</button>
1105
- <button class="pill-btn" onclick="resetFilters()" style="padding:7px 12px;cursor:pointer">Reset</button>
539
+ // ── Dashboard data (/api/dashboard/*) ────────────────────────────────────
1106
540
 
1107
- <div class="filter-input-group" style="width:160px;margin-left:auto">
1108
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;height:14px;color:var(--text-dim)"><path d="M23 4v6h-6"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
1109
- <select id="autoRefreshSelect" onchange="changeAutoRefresh(this.value)" title="Auto Refresh">
1110
- <option value="0">Auto-refresh: Off</option>
1111
- <option value="5">Auto-refresh: 5s</option>
1112
- <option value="10">Auto-refresh: 10s</option>
1113
- <option value="30">Auto-refresh: 30s</option>
1114
- <option value="60">Auto-refresh: 60s</option>
1115
- </select>
1116
- </div>
541
+ export function serveDashboardSnapshotApi(
542
+ req: IncomingMessage,
543
+ res: ServerResponse,
544
+ hub: DashboardLiveHub,
545
+ ): void {
546
+ sendDashboardJson(req, res, 200, hub.snapshot());
547
+ }
1117
548
 
1118
- <div class="col-picker-container" style="position:relative">
1119
- <button class="pill-btn" onclick="toggleColumnPicker(event)" type="button" style="display:inline-flex;align-items:center;gap:6px;padding:7px 12px;cursor:pointer">
1120
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/><path d="M15 3v18"/></svg>
1121
- <span>Columns</span>
1122
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
1123
- </button>
1124
- <div id="colPickerMenu" class="col-picker-menu" style="display:none" onclick="event.stopPropagation()">
1125
- <div class="col-picker-header">
1126
- <span>Visible Columns</span>
1127
- <button type="button" class="col-picker-reset" onclick="resetColumns()">Reset</button>
1128
- </div>
1129
- <div class="col-picker-list">
1130
- <label class="col-picker-item"><input type="checkbox" data-col="time" checked onchange="toggleColumn('time')"> Time</label>
1131
- <label class="col-picker-item"><input type="checkbox" data-col="key" checked onchange="toggleColumn('key')"> Key / Agent</label>
1132
- <label class="col-picker-item"><input type="checkbox" data-col="model" checked onchange="toggleColumn('model')"> Model</label>
1133
- <label class="col-picker-item"><input type="checkbox" data-col="type" checked onchange="toggleColumn('type')"> Call Type</label>
1134
- <label class="col-picker-item"><input type="checkbox" data-col="status" checked onchange="toggleColumn('status')"> Status</label>
1135
- <label class="col-picker-item"><input type="checkbox" data-col="tokens" checked onchange="toggleColumn('tokens')"> Tokens (In / Out)</label>
1136
- <label class="col-picker-item"><input type="checkbox" data-col="cost" checked onchange="toggleColumn('cost')"> Est. Cost</label>
1137
- <label class="col-picker-item"><input type="checkbox" data-col="duration" checked onchange="toggleColumn('duration')"> Duration</label>
1138
- <label class="col-picker-item"><input type="checkbox" data-col="ttfb" checked onchange="toggleColumn('ttfb')"> TTFB</label>
1139
- <label class="col-picker-item"><input type="checkbox" data-col="ip" checked onchange="toggleColumn('ip')"> IP Address</label>
1140
- </div>
1141
- </div>
1142
- </div>
1143
- </div>
549
+ export function serveDashboardUsageApi(
550
+ req: IncomingMessage,
551
+ res: ServerResponse,
552
+ rotator: AccountRotator,
553
+ ): void {
554
+ const url = new URL(req.url || "/", "http://localhost");
555
+ const range = url.searchParams.get("range") || "1h";
556
+ if (!isUsageRange(range)) {
557
+ sendDashboardJson(req, res, 400, { ok: false, error: "Unknown range" });
558
+ return;
559
+ }
560
+ sendDashboardJson(
561
+ req,
562
+ res,
563
+ 200,
564
+ buildUsage(
565
+ rotator.getTokenUsage(),
566
+ rotator.getLatencyStats(),
567
+ range,
568
+ Date.now(),
569
+ ),
570
+ );
571
+ }
1144
572
 
1145
- <div class="list-panel logs-list-panel">
1146
- <div style="overflow-x:auto">
1147
- <table id="logsTable" class="compact-table">
1148
- <thead>
1149
- <tr>
1150
- <th class="col-time">Time</th>
1151
- <th class="col-key">Key / Agent</th>
1152
- <th class="col-model">Model</th>
1153
- <th class="col-type">Call Type</th>
1154
- <th class="col-status">Status</th>
1155
- <th class="col-tokens">Tokens (In / Out)</th>
1156
- <th class="col-cost">Est. Cost</th>
1157
- <th class="col-duration">Duration</th>
1158
- <th class="col-ttfb">TTFB</th>
1159
- <th class="col-ip">IP</th>
1160
- </tr>
1161
- </thead>
1162
- <tbody id="logsBody"></tbody>
1163
- </table>
1164
- </div>
1165
- </div>
573
+ export function serveDashboardActivityApi(
574
+ req: IncomingMessage,
575
+ res: ServerResponse,
576
+ rotator: AccountRotator,
577
+ ): void {
578
+ sendDashboardJson(
579
+ req,
580
+ res,
581
+ 200,
582
+ buildActivity(rotator.getTokenUsage(), Date.now()),
583
+ );
584
+ }
1166
585
 
1167
- <div id="pagination" class="logs-pagination" style="margin-top:16px;display:flex;justify-content:center;align-items:center;gap:8px;font-size:0.85rem"></div>
1168
- </div>
1169
- `,
1170
- });
586
+ export function serveDashboardUsageExportApi(
587
+ req: IncomingMessage,
588
+ res: ServerResponse,
589
+ rotator: AccountRotator,
590
+ ): void {
591
+ const url = new URL(req.url || "/", "http://localhost");
592
+ const format = url.searchParams.get("format") === "csv" ? "csv" : "json";
593
+ const usage = rotator.getTokenUsage();
594
+ const body =
595
+ format === "csv" ? tokenUsageCsv(usage) : JSON.stringify(usage, null, 2);
596
+ res.writeHead(200, {
597
+ "Content-Type":
598
+ format === "csv" ? "text/csv; charset=utf-8" : "application/json; charset=utf-8",
599
+ "Content-Disposition": `attachment; filename="rotator-token-usage.${format}"`,
600
+ "Cache-Control": "no-store",
601
+ });
602
+ res.end(body);
603
+ }