tuxevil-rotator 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +773 -0
- package/LICENSE +21 -0
- package/README.md +341 -0
- package/bin/pi-antigravity-rotator.js +27 -0
- package/bin/tuxevil-rotator.js +5 -0
- package/package.json +63 -0
- package/src/account-store.ts +542 -0
- package/src/admin-auth.ts +126 -0
- package/src/body-limit.ts +52 -0
- package/src/cli.ts +293 -0
- package/src/compat/cache.ts +38 -0
- package/src/compat/model-specs.ts +82 -0
- package/src/compat/schema-sanitizer.ts +284 -0
- package/src/compat.ts +2357 -0
- package/src/compression/index.ts +92 -0
- package/src/compression/lite.ts +210 -0
- package/src/compression/preservation.ts +183 -0
- package/src/compression/rtk/command-detector.ts +170 -0
- package/src/compression/rtk/deduplicator.ts +39 -0
- package/src/compression/rtk/filter-loader.ts +84 -0
- package/src/compression/rtk/filter-types.ts +25 -0
- package/src/compression/rtk/filters/aws.json +34 -0
- package/src/compression/rtk/filters/biome.json +35 -0
- package/src/compression/rtk/filters/build-eslint.json +37 -0
- package/src/compression/rtk/filters/build-typescript.json +33 -0
- package/src/compression/rtk/filters/build-vite.json +41 -0
- package/src/compression/rtk/filters/build-webpack.json +34 -0
- package/src/compression/rtk/filters/bundle-install.json +35 -0
- package/src/compression/rtk/filters/composer.json +81 -0
- package/src/compression/rtk/filters/curl.json +34 -0
- package/src/compression/rtk/filters/df.json +34 -0
- package/src/compression/rtk/filters/docker-build.json +78 -0
- package/src/compression/rtk/filters/docker-logs.json +42 -0
- package/src/compression/rtk/filters/docker-ps.json +33 -0
- package/src/compression/rtk/filters/dotnet.json +47 -0
- package/src/compression/rtk/filters/du.json +33 -0
- package/src/compression/rtk/filters/error-stacktrace.json +41 -0
- package/src/compression/rtk/filters/gcloud.json +34 -0
- package/src/compression/rtk/filters/generic-output.json +32 -0
- package/src/compression/rtk/filters/gh.json +98 -0
- package/src/compression/rtk/filters/git-branch.json +45 -0
- package/src/compression/rtk/filters/git-diff.json +33 -0
- package/src/compression/rtk/filters/git-log.json +33 -0
- package/src/compression/rtk/filters/git-status.json +40 -0
- package/src/compression/rtk/filters/golangci-lint.json +34 -0
- package/src/compression/rtk/filters/gradle.json +47 -0
- package/src/compression/rtk/filters/json-output.json +40 -0
- package/src/compression/rtk/filters/kubectl.json +99 -0
- package/src/compression/rtk/filters/make.json +38 -0
- package/src/compression/rtk/filters/mypy.json +34 -0
- package/src/compression/rtk/filters/npm-audit.json +43 -0
- package/src/compression/rtk/filters/npm-install.json +41 -0
- package/src/compression/rtk/filters/nx.json +34 -0
- package/src/compression/rtk/filters/pip.json +41 -0
- package/src/compression/rtk/filters/playwright.json +42 -0
- package/src/compression/rtk/filters/poetry-install.json +35 -0
- package/src/compression/rtk/filters/prettier.json +40 -0
- package/src/compression/rtk/filters/ps.json +34 -0
- package/src/compression/rtk/filters/rsync.json +33 -0
- package/src/compression/rtk/filters/rubocop.json +34 -0
- package/src/compression/rtk/filters/ruff.json +40 -0
- package/src/compression/rtk/filters/shell-find.json +33 -0
- package/src/compression/rtk/filters/shell-grep.json +37 -0
- package/src/compression/rtk/filters/shell-ls.json +33 -0
- package/src/compression/rtk/filters/ssh.json +43 -0
- package/src/compression/rtk/filters/systemctl-status.json +43 -0
- package/src/compression/rtk/filters/terraform-plan.json +34 -0
- package/src/compression/rtk/filters/test-cargo.json +42 -0
- package/src/compression/rtk/filters/test-go.json +41 -0
- package/src/compression/rtk/filters/test-jest.json +43 -0
- package/src/compression/rtk/filters/test-pytest.json +41 -0
- package/src/compression/rtk/filters/test-vitest.json +43 -0
- package/src/compression/rtk/filters/tofu-plan.json +34 -0
- package/src/compression/rtk/filters/turbo.json +34 -0
- package/src/compression/rtk/filters/uv-sync.json +35 -0
- package/src/compression/rtk/filters/wget.json +34 -0
- package/src/compression/rtk/index.ts +103 -0
- package/src/compression/rtk/line-filter.ts +124 -0
- package/src/compression/rtk/smart-truncate.ts +71 -0
- package/src/config-defaults.ts +93 -0
- package/src/config-normalize.ts +48 -0
- package/src/config-storage.ts +21 -0
- package/src/dashboard.ts +1169 -0
- package/src/db-store.ts +188 -0
- package/src/doctor.ts +115 -0
- package/src/env.ts +15 -0
- package/src/exposure.ts +17 -0
- package/src/fetch-with-retry.ts +93 -0
- package/src/idempotency.ts +137 -0
- package/src/index.ts +267 -0
- package/src/key-auth.ts +159 -0
- package/src/key-migrations.ts +84 -0
- package/src/logger.ts +92 -0
- package/src/login.ts +48 -0
- package/src/notification-poller.ts +155 -0
- package/src/onboarding.ts +754 -0
- package/src/paths.ts +153 -0
- package/src/providers/adapter.ts +131 -0
- package/src/providers/credential-helpers.ts +72 -0
- package/src/providers/google-antigravity/code-assist.ts +161 -0
- package/src/providers/google-antigravity/credentials.ts +24 -0
- package/src/providers/google-antigravity/forward.ts +424 -0
- package/src/providers/google-antigravity/index.ts +168 -0
- package/src/providers/google-antigravity/login.ts +285 -0
- package/src/providers/google-antigravity/oauth.ts +314 -0
- package/src/providers/google-antigravity/quota.ts +152 -0
- package/src/providers/google-antigravity/translators.ts +1663 -0
- package/src/providers/ollama/api-key-validation.ts +59 -0
- package/src/providers/ollama/credentials.ts +28 -0
- package/src/providers/ollama/forward.ts +306 -0
- package/src/providers/ollama/index.ts +85 -0
- package/src/providers/ollama/login.ts +55 -0
- package/src/providers/ollama/prediction.ts +188 -0
- package/src/providers/ollama/quota-poll-store.ts +160 -0
- package/src/providers/ollama/quota.ts +189 -0
- package/src/providers/ollama/translators.ts +256 -0
- package/src/providers/ollama/usage-windows.ts +48 -0
- package/src/providers/proxy-dispatcher.ts +269 -0
- package/src/providers/registry.ts +70 -0
- package/src/proxy.ts +2446 -0
- package/src/rate-limit-parser.ts +126 -0
- package/src/response-headers.ts +98 -0
- package/src/responses-store.ts +159 -0
- package/src/rotator.ts +3614 -0
- package/src/settings-repository.ts +327 -0
- package/src/spend-logger.ts +696 -0
- package/src/static/dashboard-keys.js +384 -0
- package/src/static/dashboard-logs.js +797 -0
- package/src/static/dashboard.css +2740 -0
- package/src/static/dashboard.js +3177 -0
- package/src/storage.ts +105 -0
- package/src/systemd-env.ts +214 -0
- package/src/telemetry.ts +384 -0
- package/src/token-encryption.ts +199 -0
- package/src/types.ts +897 -0
- package/src/validators.ts +218 -0
- package/src/version-check.ts +225 -0
- package/src/virtual-keys.ts +312 -0
- package/tools/telemetry-receiver/README.md +147 -0
- package/tools/telemetry-receiver/package.json +13 -0
- package/tools/telemetry-receiver/receiver.js +2334 -0
- package/tuxevil-rotator_logo.png +0 -0
|
@@ -0,0 +1,2334 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// ── Tuxevil Rotator — Telemetry Receiver ──────────────────────
|
|
4
|
+
//
|
|
5
|
+
// Minimal HTTP server that receives anonymous telemetry events
|
|
6
|
+
// and stores them as JSONL (one file per day).
|
|
7
|
+
//
|
|
8
|
+
// Zero dependencies — runs on Node.js 18+ with native http/fs.
|
|
9
|
+
//
|
|
10
|
+
// Usage:
|
|
11
|
+
// PORT=3800 DATA_DIR=./data node receiver.js
|
|
12
|
+
//
|
|
13
|
+
// Endpoints:
|
|
14
|
+
// POST /v1/events — Receive a telemetry payload
|
|
15
|
+
// GET /v1/stats — Aggregate stats (protected by STATS_TOKEN)
|
|
16
|
+
// GET /v1/public-stats — Public aggregate stats for badges (no auth, 5-min cache)
|
|
17
|
+
// GET /stats — Public aggregate stats page
|
|
18
|
+
// GET /v1/health — Health check
|
|
19
|
+
//
|
|
20
|
+
// Environment:
|
|
21
|
+
// PORT — Listen port (default: 3800)
|
|
22
|
+
// DATA_DIR — JSONL storage directory (default: ./data)
|
|
23
|
+
// STATS_TOKEN — Bearer token to access /v1/stats (required for stats)
|
|
24
|
+
|
|
25
|
+
import { createServer } from "node:http";
|
|
26
|
+
import {
|
|
27
|
+
appendFileSync,
|
|
28
|
+
writeFileSync,
|
|
29
|
+
mkdirSync,
|
|
30
|
+
existsSync,
|
|
31
|
+
readdirSync,
|
|
32
|
+
readFileSync,
|
|
33
|
+
} from "node:fs";
|
|
34
|
+
import { join } from "node:path";
|
|
35
|
+
import { randomUUID } from "node:crypto";
|
|
36
|
+
|
|
37
|
+
const PORT = parseInt(process.env.PORT || "3800", 10);
|
|
38
|
+
const DATA_DIR = process.env.DATA_DIR || "./data";
|
|
39
|
+
const STATS_TOKEN = process.env.STATS_TOKEN || "";
|
|
40
|
+
|
|
41
|
+
if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
|
|
42
|
+
|
|
43
|
+
function isStatsAuthorized(req) {
|
|
44
|
+
return STATS_TOKEN.length > 0 &&
|
|
45
|
+
req.headers.authorization === "Bearer " + STATS_TOKEN;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function sendUnauthorized(res) {
|
|
49
|
+
res.writeHead(401, { "Content-Type": "application/json" });
|
|
50
|
+
res.end(JSON.stringify({ error: "Unauthorized" }));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function requireStatsAuth(req, res) {
|
|
54
|
+
if (!STATS_TOKEN) {
|
|
55
|
+
res.writeHead(403, { "Content-Type": "application/json" });
|
|
56
|
+
res.end(JSON.stringify({ error: "STATS_TOKEN not configured" }));
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
if (!isStatsAuthorized(req)) {
|
|
60
|
+
sendUnauthorized(res);
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ── Notifications Storage ────────────────────────────────────────────
|
|
67
|
+
const NOTIFICATIONS_FILE = join(DATA_DIR, "notifications.json");
|
|
68
|
+
|
|
69
|
+
function loadNotifications() {
|
|
70
|
+
try {
|
|
71
|
+
if (existsSync(NOTIFICATIONS_FILE)) {
|
|
72
|
+
return JSON.parse(readFileSync(NOTIFICATIONS_FILE, "utf-8"));
|
|
73
|
+
}
|
|
74
|
+
} catch { /* corrupted file, start fresh */ }
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function saveNotifications(notifications) {
|
|
79
|
+
writeFileSync(NOTIFICATIONS_FILE, JSON.stringify(notifications, null, 2), "utf-8");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const NOTIFICATION_TYPES = new Set(["info", "warning", "critical"]);
|
|
83
|
+
const MAX_NOTIFICATION_STRING_LEN = 2048;
|
|
84
|
+
|
|
85
|
+
function isOptionalNotificationString(value) {
|
|
86
|
+
return value === undefined || value === null ||
|
|
87
|
+
(typeof value === "string" && value.length <= MAX_NOTIFICATION_STRING_LEN);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isSafeNotificationUrl(value) {
|
|
91
|
+
if (value === undefined || value === null || value === "") return true;
|
|
92
|
+
if (typeof value !== "string" || value.length > MAX_NOTIFICATION_STRING_LEN) return false;
|
|
93
|
+
try {
|
|
94
|
+
const parsed = new URL(value, "http://localhost");
|
|
95
|
+
return parsed.protocol === "http:" || parsed.protocol === "https:";
|
|
96
|
+
} catch {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function isValidNotificationInput(data) {
|
|
102
|
+
if (typeof data !== "object" || data === null) return false;
|
|
103
|
+
if (data.id !== undefined && (typeof data.id !== "string" || data.id.length > MAX_NOTIFICATION_STRING_LEN)) return false;
|
|
104
|
+
if (typeof data.title !== "string" || data.title.length === 0 || data.title.length > MAX_NOTIFICATION_STRING_LEN) return false;
|
|
105
|
+
if (typeof data.message !== "string" || data.message.length === 0 || data.message.length > MAX_NOTIFICATION_STRING_LEN) return false;
|
|
106
|
+
if (data.type !== undefined && !NOTIFICATION_TYPES.has(data.type)) return false;
|
|
107
|
+
if (!isOptionalNotificationString(data.createdAt)) return false;
|
|
108
|
+
if (!isOptionalNotificationString(data.expiresAt)) return false;
|
|
109
|
+
if (!isOptionalNotificationString(data.minVersion)) return false;
|
|
110
|
+
if (!isOptionalNotificationString(data.maxVersion)) return false;
|
|
111
|
+
if (!isSafeNotificationUrl(data.actionUrl)) return false;
|
|
112
|
+
if (!isOptionalNotificationString(data.actionLabel)) return false;
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Simple semver comparison: returns true if a < b.
|
|
118
|
+
*/
|
|
119
|
+
function semverLt(a, b) {
|
|
120
|
+
const pa = a.split(".").map(Number);
|
|
121
|
+
const pb = b.split(".").map(Number);
|
|
122
|
+
for (let i = 0; i < 3; i++) {
|
|
123
|
+
const av = pa[i] ?? 0;
|
|
124
|
+
const bv = pb[i] ?? 0;
|
|
125
|
+
if (av < bv) return true;
|
|
126
|
+
if (av > bv) return false;
|
|
127
|
+
}
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function semverLte(a, b) {
|
|
132
|
+
return a === b || semverLt(a, b);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Filter notifications for a client with a given version.
|
|
137
|
+
* Removes expired notifications and applies version targeting.
|
|
138
|
+
*/
|
|
139
|
+
function getActiveNotifications(clientVersion) {
|
|
140
|
+
const all = loadNotifications();
|
|
141
|
+
const now = new Date().toISOString();
|
|
142
|
+
return all.filter((n) => {
|
|
143
|
+
// Filter expired
|
|
144
|
+
if (n.expiresAt && n.expiresAt < now) return false;
|
|
145
|
+
// Version targeting
|
|
146
|
+
if (clientVersion) {
|
|
147
|
+
if (n.minVersion && semverLt(clientVersion, n.minVersion)) return false;
|
|
148
|
+
if (n.maxVersion && !semverLte(clientVersion, n.maxVersion)) return false;
|
|
149
|
+
}
|
|
150
|
+
return true;
|
|
151
|
+
}).map((n) => ({
|
|
152
|
+
id: n.id,
|
|
153
|
+
type: n.type || "info",
|
|
154
|
+
title: n.title,
|
|
155
|
+
message: n.message,
|
|
156
|
+
createdAt: n.createdAt,
|
|
157
|
+
actionUrl: n.actionUrl || null,
|
|
158
|
+
actionLabel: n.actionLabel || null,
|
|
159
|
+
}));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ── Validation ───────────────────────────────────────────────────────
|
|
163
|
+
const ALLOWED_EVENTS = new Set(["boot", "heartbeat", "shutdown", "flag"]);
|
|
164
|
+
const MAX_BODY_BYTES = 4096;
|
|
165
|
+
const MAX_MODELS = 20;
|
|
166
|
+
const MAX_STRING_LEN = 128;
|
|
167
|
+
|
|
168
|
+
function isCorePayload(data) {
|
|
169
|
+
if (typeof data !== "object" || data === null) return false;
|
|
170
|
+
if (typeof data.installId !== "string" || data.installId.length > 64) return false;
|
|
171
|
+
if (typeof data.version !== "string" || data.version.length > MAX_STRING_LEN) return false;
|
|
172
|
+
if (typeof data.ts !== "string" || data.ts.length > 30) return false;
|
|
173
|
+
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function isHeartbeatPayload(data) {
|
|
178
|
+
if (!isCorePayload(data)) return false;
|
|
179
|
+
if (typeof data.nodeVersion !== "string" || data.nodeVersion.length > MAX_STRING_LEN) return false;
|
|
180
|
+
if (typeof data.os !== "string" || data.os.length > MAX_STRING_LEN) return false;
|
|
181
|
+
if (typeof data.arch !== "string" || data.arch.length > MAX_STRING_LEN) return false;
|
|
182
|
+
if (typeof data.accountCount !== "number" || data.accountCount < 0 || data.accountCount > 1000) return false;
|
|
183
|
+
if (!Array.isArray(data.modelsUsed) || data.modelsUsed.length > MAX_MODELS) return false;
|
|
184
|
+
if (typeof data.totalRequests !== "number" || data.totalRequests < 0) return false;
|
|
185
|
+
if (typeof data.uptimeSeconds !== "number" || data.uptimeSeconds < 0) return false;
|
|
186
|
+
if (typeof data.routingHealthState !== "string" || data.routingHealthState.length > 30) return false;
|
|
187
|
+
|
|
188
|
+
// Reject if any email-like string is detected anywhere
|
|
189
|
+
const serialized = JSON.stringify(data);
|
|
190
|
+
if (serialized.includes("@") && /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]/.test(serialized)) {
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function isFlagPayload(data) {
|
|
198
|
+
if (!isCorePayload(data)) return false;
|
|
199
|
+
if (data.event !== "flag") return false;
|
|
200
|
+
if (typeof data.flag !== "object" || data.flag === null) return false;
|
|
201
|
+
const flag = data.flag;
|
|
202
|
+
if (typeof flag.flagHttpStatus !== "number") return false;
|
|
203
|
+
if (!Array.isArray(flag.flagPatternsMatched)) return false;
|
|
204
|
+
if (typeof flag.model !== "string") return false;
|
|
205
|
+
if (typeof flag.timerType !== "string") return false;
|
|
206
|
+
if (typeof flag.accountQuotaPercent !== "number") return false;
|
|
207
|
+
if (typeof flag.wasProAccount !== "boolean") return false;
|
|
208
|
+
if (typeof flag.accountTotalRequests !== "number") return false;
|
|
209
|
+
if (typeof flag.accountRequestsLastHour !== "number") return false;
|
|
210
|
+
if (typeof flag.accountConcurrentAtFlag !== "number") return false;
|
|
211
|
+
if (typeof flag.poolSize !== "number") return false;
|
|
212
|
+
if (typeof flag.poolHealthyCount !== "number") return false;
|
|
213
|
+
if (typeof flag.protectivePauseTriggered !== "boolean") return false;
|
|
214
|
+
if (typeof flag.uptimeSeconds !== "number") return false;
|
|
215
|
+
if (typeof flag.timeSinceLastFlagSeconds !== "number") return false;
|
|
216
|
+
|
|
217
|
+
const serialized = JSON.stringify(data);
|
|
218
|
+
if (serialized.includes("@") && /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]/.test(serialized)) {
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function isValidPayload(data) {
|
|
226
|
+
if (typeof data !== "object" || data === null) return false;
|
|
227
|
+
if (!ALLOWED_EVENTS.has(data.event)) return false;
|
|
228
|
+
if (data.event === "flag") return isFlagPayload(data);
|
|
229
|
+
return isHeartbeatPayload(data);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ── Storage ──────────────────────────────────────────────────────────
|
|
233
|
+
function getDailyFile() {
|
|
234
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
235
|
+
return join(DATA_DIR, `${date}.jsonl`);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function storeEvent(payload) {
|
|
239
|
+
// Sanitize: keep only known fields
|
|
240
|
+
const clean = {
|
|
241
|
+
event: payload.event,
|
|
242
|
+
installId: payload.installId,
|
|
243
|
+
version: payload.version,
|
|
244
|
+
nodeVersion: payload.nodeVersion,
|
|
245
|
+
os: payload.os,
|
|
246
|
+
arch: payload.arch,
|
|
247
|
+
ts: payload.ts,
|
|
248
|
+
receivedAt: new Date().toISOString(),
|
|
249
|
+
accountCount: payload.accountCount,
|
|
250
|
+
modelsUsed: payload.modelsUsed,
|
|
251
|
+
totalRequests: payload.totalRequests,
|
|
252
|
+
uptimeSeconds: payload.uptimeSeconds,
|
|
253
|
+
routingHealthState: payload.routingHealthState,
|
|
254
|
+
flaggedCount: payload.flaggedCount ?? 0,
|
|
255
|
+
disabledCount: payload.disabledCount ?? 0,
|
|
256
|
+
proCount: payload.proCount ?? 0,
|
|
257
|
+
freeCount: payload.freeCount ?? 0,
|
|
258
|
+
tokensByModel: sanitizeTokensByModel(payload.tokensByModel),
|
|
259
|
+
featuresUsed: payload.featuresUsed ?? {},
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
appendFileSync(getDailyFile(), JSON.stringify(clean) + "\n", "utf-8");
|
|
263
|
+
|
|
264
|
+
// Flag events also go to a dedicated file for easy analysis
|
|
265
|
+
if (payload.event === "flag" && payload.flag) {
|
|
266
|
+
const flagClean = {
|
|
267
|
+
installId: payload.installId,
|
|
268
|
+
version: payload.version,
|
|
269
|
+
ts: payload.ts,
|
|
270
|
+
receivedAt: new Date().toISOString(),
|
|
271
|
+
...sanitizeFlagData(payload.flag),
|
|
272
|
+
};
|
|
273
|
+
const flagFile = getDailyFile().replace(".jsonl", "-flags.jsonl");
|
|
274
|
+
appendFileSync(flagFile, JSON.stringify(flagClean) + "\n", "utf-8");
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function sanitizeFlagData(flag) {
|
|
279
|
+
const ALLOWED_PATTERNS = new Set([
|
|
280
|
+
"infring", "suspend", "abus", "terminat",
|
|
281
|
+
"violat", "banned", "policy", "forbidden", "verif",
|
|
282
|
+
"blocked_401",
|
|
283
|
+
]);
|
|
284
|
+
return {
|
|
285
|
+
flagHttpStatus: typeof flag.flagHttpStatus === "number" ? flag.flagHttpStatus : 0,
|
|
286
|
+
flagPatternsMatched: Array.isArray(flag.flagPatternsMatched)
|
|
287
|
+
? flag.flagPatternsMatched.filter((p) => ALLOWED_PATTERNS.has(p))
|
|
288
|
+
: [],
|
|
289
|
+
model: typeof flag.model === "string" ? flag.model.slice(0, 64) : "unknown",
|
|
290
|
+
timerType: typeof flag.timerType === "string" ? flag.timerType.slice(0, 10) : "unknown",
|
|
291
|
+
accountQuotaPercent: typeof flag.accountQuotaPercent === "number" ? flag.accountQuotaPercent : -1,
|
|
292
|
+
wasProAccount: !!flag.wasProAccount,
|
|
293
|
+
accountTotalRequests: typeof flag.accountTotalRequests === "number" ? flag.accountTotalRequests : 0,
|
|
294
|
+
accountRequestsLastHour: typeof flag.accountRequestsLastHour === "number" ? flag.accountRequestsLastHour : 0,
|
|
295
|
+
accountConcurrentAtFlag: typeof flag.accountConcurrentAtFlag === "number" ? flag.accountConcurrentAtFlag : 0,
|
|
296
|
+
poolSize: typeof flag.poolSize === "number" ? flag.poolSize : 0,
|
|
297
|
+
poolHealthyCount: typeof flag.poolHealthyCount === "number" ? flag.poolHealthyCount : 0,
|
|
298
|
+
protectivePauseTriggered: !!flag.protectivePauseTriggered,
|
|
299
|
+
uptimeSeconds: typeof flag.uptimeSeconds === "number" ? flag.uptimeSeconds : 0,
|
|
300
|
+
timeSinceLastFlagSeconds: typeof flag.timeSinceLastFlagSeconds === "number" ? flag.timeSinceLastFlagSeconds : -1,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function sanitizeTokensByModel(raw) {
|
|
305
|
+
if (typeof raw !== "object" || raw === null) return {};
|
|
306
|
+
const MAX_MODELS = 20;
|
|
307
|
+
const clean = Object.create(null);
|
|
308
|
+
let count = 0;
|
|
309
|
+
for (const [model, data] of Object.entries(raw)) {
|
|
310
|
+
if (count >= MAX_MODELS) break;
|
|
311
|
+
if (typeof model !== "string" || model.length > 64) continue;
|
|
312
|
+
if (typeof data !== "object" || data === null) continue;
|
|
313
|
+
clean[model] = {
|
|
314
|
+
input: typeof data.input === "number" && data.input >= 0 ? data.input : 0,
|
|
315
|
+
output: typeof data.output === "number" && data.output >= 0 ? data.output : 0,
|
|
316
|
+
requests: typeof data.requests === "number" && data.requests >= 0 ? data.requests : 0,
|
|
317
|
+
};
|
|
318
|
+
count++;
|
|
319
|
+
}
|
|
320
|
+
return clean;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Pricing per 1M tokens (USD) — mirrors MODEL_PRICING in the rotator
|
|
324
|
+
const MODEL_PRICING = {
|
|
325
|
+
"claude-opus-4-6-thinking": { inputPer1M: 5.00, outputPer1M: 25.00 },
|
|
326
|
+
"claude-sonnet-4-6": { inputPer1M: 3.00, outputPer1M: 15.00 },
|
|
327
|
+
"gemini-3.1-pro": { inputPer1M: 2.00, outputPer1M: 12.00 },
|
|
328
|
+
"gemini-3.1-pro-low": { inputPer1M: 2.00, outputPer1M: 12.00 },
|
|
329
|
+
"gemini-3.1-pro-high": { inputPer1M: 2.00, outputPer1M: 12.00 },
|
|
330
|
+
"gemini-3-flash": { inputPer1M: 0.50, outputPer1M: 3.00 },
|
|
331
|
+
"gemini-3.5-flash": { inputPer1M: 1.50, outputPer1M: 9.00 },
|
|
332
|
+
"gemini-3.5-flash-low": { inputPer1M: 1.50, outputPer1M: 9.00 },
|
|
333
|
+
"gemini-3.5-flash-medium": { inputPer1M: 1.50, outputPer1M: 9.00 },
|
|
334
|
+
"gemini-3.5-flash-high": { inputPer1M: 1.50, outputPer1M: 9.00 },
|
|
335
|
+
"gemini-3.6-flash": { inputPer1M: 1.50, outputPer1M: 7.50 },
|
|
336
|
+
"gemini-3.6-flash-high": { inputPer1M: 1.50, outputPer1M: 7.50 },
|
|
337
|
+
"gemini-3.6-flash-medium": { inputPer1M: 1.50, outputPer1M: 7.50 },
|
|
338
|
+
"gemini-3.6-flash-low": { inputPer1M: 1.50, outputPer1M: 7.50 },
|
|
339
|
+
"gemini-3.6-flash-tiered": { inputPer1M: 1.50, outputPer1M: 7.50 },
|
|
340
|
+
"gpt-oss-120b-medium": { inputPer1M: 2.00, outputPer1M: 10.00 },
|
|
341
|
+
|
|
342
|
+
// Ollama Cloud models — mirrors MODEL_PRICING in src/types.ts
|
|
343
|
+
"gpt-oss:20b": { inputPer1M: 0.075, outputPer1M: 0.30 },
|
|
344
|
+
"gpt-oss:120b": { inputPer1M: 0.15, outputPer1M: 0.60 },
|
|
345
|
+
"deepseek-v4-flash:preview": { inputPer1M: 0.14, outputPer1M: 0.28 },
|
|
346
|
+
"deepseek-v4-flash:0731": { inputPer1M: 0.14, outputPer1M: 0.28 },
|
|
347
|
+
"deepseek-v4-pro": { inputPer1M: 0.435, outputPer1M: 0.87 },
|
|
348
|
+
"qwen3.5:397b": { inputPer1M: 0.60, outputPer1M: 3.60 },
|
|
349
|
+
"glm-5.1": { inputPer1M: 0.80, outputPer1M: 2.56 },
|
|
350
|
+
"glm-5.2": { inputPer1M: 0.80, outputPer1M: 2.56 },
|
|
351
|
+
"gemma4:31b": { inputPer1M: 0.38, outputPer1M: 1.15 },
|
|
352
|
+
"kimi-k2.6": { inputPer1M: 0.95, outputPer1M: 4.00 },
|
|
353
|
+
"kimi-k2.7-code": { inputPer1M: 0.95, outputPer1M: 4.00 },
|
|
354
|
+
"kimi-k3": { inputPer1M: 0.95, outputPer1M: 4.00 },
|
|
355
|
+
"minimax-m2.7": { inputPer1M: 0.30, outputPer1M: 1.20 },
|
|
356
|
+
"minimax-m3": { inputPer1M: 0.30, outputPer1M: 1.20 },
|
|
357
|
+
"mistral-large-3:675b": { inputPer1M: 0.50, outputPer1M: 1.50 },
|
|
358
|
+
"nemotron-3-nano:30b": { inputPer1M: 0.50, outputPer1M: 1.50 },
|
|
359
|
+
"nemotron-3-super": { inputPer1M: 0.60, outputPer1M: 1.80 },
|
|
360
|
+
"nemotron-3-ultra": { inputPer1M: 0.60, outputPer1M: 1.80 },
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
function getModelPricing(model) {
|
|
364
|
+
if (MODEL_PRICING[model]) return MODEL_PRICING[model];
|
|
365
|
+
const lower = (model || "").toLowerCase();
|
|
366
|
+
if (lower.includes("opus")) return MODEL_PRICING["claude-opus-4-6-thinking"];
|
|
367
|
+
if (lower.includes("sonnet")) return MODEL_PRICING["claude-sonnet-4-6"];
|
|
368
|
+
if (lower.includes("3.6-flash")) return MODEL_PRICING["gemini-3.6-flash-high"];
|
|
369
|
+
if (lower.includes("3.5-flash")) return MODEL_PRICING["gemini-3.5-flash-high"];
|
|
370
|
+
if (lower.includes("flash")) return MODEL_PRICING["gemini-3-flash"];
|
|
371
|
+
if (lower.includes("pro")) return MODEL_PRICING["gemini-3.1-pro"];
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function calculateSavings(tokensByModel) {
|
|
376
|
+
let totalUsd = 0;
|
|
377
|
+
const byModel = Object.create(null);
|
|
378
|
+
for (const [model, data] of Object.entries(tokensByModel)) {
|
|
379
|
+
const pricing = getModelPricing(model);
|
|
380
|
+
if (!pricing) continue;
|
|
381
|
+
const inputUsd = (data.input / 1_000_000) * pricing.inputPer1M;
|
|
382
|
+
const outputUsd = (data.output / 1_000_000) * pricing.outputPer1M;
|
|
383
|
+
byModel[model] = { inputUsd: Math.round(inputUsd * 100) / 100, outputUsd: Math.round(outputUsd * 100) / 100, totalUsd: Math.round((inputUsd + outputUsd) * 100) / 100 };
|
|
384
|
+
totalUsd += inputUsd + outputUsd;
|
|
385
|
+
}
|
|
386
|
+
return { totalUsd: Math.round(totalUsd * 100) / 100, byModel };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// ── Stats ────────────────────────────────────────────────────────────
|
|
390
|
+
// ── Stats filtering ───────────────────────────────────────────────────
|
|
391
|
+
function parseQueryString(url) {
|
|
392
|
+
const idx = url.indexOf("?");
|
|
393
|
+
if (idx === -1) return {};
|
|
394
|
+
const params = Object.create(null);
|
|
395
|
+
for (const part of url.slice(idx + 1).split("&")) {
|
|
396
|
+
const separator = part.indexOf("=");
|
|
397
|
+
const rawKey = separator === -1 ? part : part.slice(0, separator);
|
|
398
|
+
const rawValue = separator === -1 ? "" : part.slice(separator + 1);
|
|
399
|
+
try {
|
|
400
|
+
const k = decodeURIComponent(rawKey);
|
|
401
|
+
if (k) params[k] = decodeURIComponent(rawValue);
|
|
402
|
+
} catch {
|
|
403
|
+
// Ignore malformed query components.
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return params;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Collect all raw events + flag events from JSONL files
|
|
410
|
+
function loadAllEvents() {
|
|
411
|
+
const allFiles = readdirSync(DATA_DIR).filter((f) => f.endsWith(".jsonl") && !f.endsWith("-flags.jsonl")).sort();
|
|
412
|
+
const flagFiles = readdirSync(DATA_DIR).filter((f) => f.endsWith("-flags.jsonl")).sort();
|
|
413
|
+
const events = [];
|
|
414
|
+
const flagEvents = [];
|
|
415
|
+
for (const file of allFiles) {
|
|
416
|
+
const lines = readFileSync(join(DATA_DIR, file), "utf-8").split("\n").filter(Boolean);
|
|
417
|
+
for (const line of lines) {
|
|
418
|
+
try { events.push({ file, ev: JSON.parse(line) }); } catch { /* skip */ }
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
for (const file of flagFiles) {
|
|
422
|
+
const lines = readFileSync(join(DATA_DIR, file), "utf-8").split("\n").filter(Boolean);
|
|
423
|
+
for (const line of lines) {
|
|
424
|
+
try { flagEvents.push({ file, fl: JSON.parse(line) }); } catch { /* skip */ }
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return { events, flagEvents, allFiles, flagFiles };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// Extract filter options from all events (unfiltered, for populating dropdowns)
|
|
431
|
+
function buildFilterOptions(events, flagEvents) {
|
|
432
|
+
const installIds = new Set();
|
|
433
|
+
const versions = new Set();
|
|
434
|
+
const osList = new Set();
|
|
435
|
+
const models = new Set();
|
|
436
|
+
const dates = new Set();
|
|
437
|
+
for (const { ev, file } of events) {
|
|
438
|
+
if (ev.installId) installIds.add(ev.installId);
|
|
439
|
+
if (ev.version) versions.add(ev.version);
|
|
440
|
+
if (ev.os) osList.add(ev.os);
|
|
441
|
+
for (const m of ev.modelsUsed || []) models.add(m);
|
|
442
|
+
const date = file.replace(".jsonl", "");
|
|
443
|
+
if (date) dates.add(date);
|
|
444
|
+
}
|
|
445
|
+
return {
|
|
446
|
+
installIds: [...installIds].sort(),
|
|
447
|
+
versions: [...versions].sort(),
|
|
448
|
+
os: [...osList].sort(),
|
|
449
|
+
models: [...models].sort(),
|
|
450
|
+
dateRange: { from: [...dates].sort()[0] ?? null, to: [...dates].sort().at(-1) ?? null },
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
// ── Per-install list ─────────────────────────────────────────────────
|
|
456
|
+
// Returns one summary row per unique installId based on their latest
|
|
457
|
+
// heartbeat/boot event + flag count over the same filtered window.
|
|
458
|
+
function computeInstallList(filters = {}) {
|
|
459
|
+
const { events: allEvents, flagEvents: allFlagEvents } = loadAllEvents();
|
|
460
|
+
|
|
461
|
+
// Apply same filters as computeStats
|
|
462
|
+
const events = allEvents.filter(({ ev, file }) => {
|
|
463
|
+
if (filters.installId && ev.installId !== filters.installId) return false;
|
|
464
|
+
if (filters.version && ev.version !== filters.version) return false;
|
|
465
|
+
if (filters.os && ev.os !== filters.os) return false;
|
|
466
|
+
if (filters.model && !(ev.modelsUsed || []).includes(filters.model)) return false;
|
|
467
|
+
const date = file.replace('.jsonl', '');
|
|
468
|
+
if (filters.from && date < filters.from) return false;
|
|
469
|
+
if (filters.to && date > filters.to) return false;
|
|
470
|
+
return true;
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
const flagEvents = allFlagEvents.filter(({ fl, file }) => {
|
|
474
|
+
if (filters.installId && fl.installId !== filters.installId) return false;
|
|
475
|
+
const date = file.replace('-flags.jsonl', '');
|
|
476
|
+
if (filters.from && date < filters.from) return false;
|
|
477
|
+
if (filters.to && date > filters.to) return false;
|
|
478
|
+
return true;
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
// Latest heartbeat snapshot per install
|
|
482
|
+
const latest = Object.create(null); // installId -> ev
|
|
483
|
+
for (const { ev } of events) {
|
|
484
|
+
const prev = latest[ev.installId];
|
|
485
|
+
if (!prev || ev.ts >= prev.ts) latest[ev.installId] = ev;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// First seen per install
|
|
489
|
+
const firstSeen = Object.create(null);
|
|
490
|
+
for (const { ev } of events) {
|
|
491
|
+
if (!firstSeen[ev.installId] || ev.ts < firstSeen[ev.installId])
|
|
492
|
+
firstSeen[ev.installId] = ev.ts;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// Flag counts per install
|
|
496
|
+
const flagsByInstall = Object.create(null);
|
|
497
|
+
for (const { fl } of flagEvents) {
|
|
498
|
+
flagsByInstall[fl.installId] = (flagsByInstall[fl.installId] || 0) + 1;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// Total requests per install (max across all events — it's cumulative)
|
|
502
|
+
const maxRequests = Object.create(null);
|
|
503
|
+
for (const { ev } of events) {
|
|
504
|
+
const cur = maxRequests[ev.installId] || 0;
|
|
505
|
+
if ((ev.totalRequests || 0) > cur) maxRequests[ev.installId] = ev.totalRequests || 0;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const list = Object.values(latest).map((ev) => {
|
|
509
|
+
const tokens = ev.tokensByModel && typeof ev.tokensByModel === 'object'
|
|
510
|
+
? ev.tokensByModel : {};
|
|
511
|
+
const savings = calculateSavings(tokens);
|
|
512
|
+
return {
|
|
513
|
+
installId: ev.installId,
|
|
514
|
+
version: ev.version || '?',
|
|
515
|
+
os: ev.os || '?',
|
|
516
|
+
arch: ev.arch || '?',
|
|
517
|
+
accountCount: ev.accountCount || 0,
|
|
518
|
+
totalRequests: maxRequests[ev.installId] || 0,
|
|
519
|
+
routingHealthState: ev.routingHealthState || 'unknown',
|
|
520
|
+
flaggedCount: ev.flaggedCount || 0,
|
|
521
|
+
disabledCount: ev.disabledCount || 0,
|
|
522
|
+
proCount: ev.proCount || 0,
|
|
523
|
+
freeCount: ev.freeCount || 0,
|
|
524
|
+
tokensByModel: tokens,
|
|
525
|
+
savingsUsd: savings.totalUsd,
|
|
526
|
+
flagEvents: flagsByInstall[ev.installId] || 0,
|
|
527
|
+
lastSeen: ev.ts,
|
|
528
|
+
firstSeen: firstSeen[ev.installId] || ev.ts,
|
|
529
|
+
featuresUsed: ev.featuresUsed || {},
|
|
530
|
+
};
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
// Sort by totalRequests desc by default
|
|
534
|
+
list.sort((a, b) => b.totalRequests - a.totalRequests);
|
|
535
|
+
return list;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function computeStats(filters = {}) {
|
|
539
|
+
const { events: allEvents, flagEvents: allFlagEvents, allFiles } = loadAllEvents();
|
|
540
|
+
|
|
541
|
+
// Apply filters to main events
|
|
542
|
+
const events = allEvents.filter(({ ev, file }) => {
|
|
543
|
+
if (filters.installId && ev.installId !== filters.installId) return false;
|
|
544
|
+
if (filters.version && ev.version !== filters.version) return false;
|
|
545
|
+
if (filters.os && ev.os !== filters.os) return false;
|
|
546
|
+
if (filters.model && !(ev.modelsUsed || []).includes(filters.model)) return false;
|
|
547
|
+
const date = file.replace(".jsonl", "");
|
|
548
|
+
if (filters.from && date < filters.from) return false;
|
|
549
|
+
if (filters.to && date > filters.to) return false;
|
|
550
|
+
return true;
|
|
551
|
+
});
|
|
552
|
+
|
|
553
|
+
// Apply filters to flag events (by installId, date)
|
|
554
|
+
const flagEvents = allFlagEvents.filter(({ fl, file }) => {
|
|
555
|
+
if (filters.installId && fl.installId !== filters.installId) return false;
|
|
556
|
+
if (filters.model && fl.model !== filters.model) return false;
|
|
557
|
+
const date = file.replace("-flags.jsonl", "");
|
|
558
|
+
if (filters.from && date < filters.from) return false;
|
|
559
|
+
if (filters.to && date > filters.to) return false;
|
|
560
|
+
return true;
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
const uniqueInstalls = new Set();
|
|
564
|
+
let totalEvents = 0;
|
|
565
|
+
let totalBoots = 0;
|
|
566
|
+
let totalFlags = 0;
|
|
567
|
+
const versionCounts = Object.create(null);
|
|
568
|
+
const osCounts = Object.create(null);
|
|
569
|
+
const archCounts = Object.create(null);
|
|
570
|
+
const modelCounts = Object.create(null);
|
|
571
|
+
const healthCounts = Object.create(null);
|
|
572
|
+
let totalAccounts = 0;
|
|
573
|
+
let totalRequests = 0;
|
|
574
|
+
let featuresCount = { dashboard: 0, proAdvisor: 0, freshWindowToggle: 0, hostedLogin: 0 };
|
|
575
|
+
|
|
576
|
+
// tokensByModel is CUMULATIVE per install (each heartbeat sends total-since-boot).
|
|
577
|
+
// To avoid multi-counting, track the LATEST snapshot per installId and sum those.
|
|
578
|
+
const latestTokenSnapshotByInstall = Object.create(null); // installId → { ts, tokensByModel }
|
|
579
|
+
|
|
580
|
+
for (const { ev } of events) {
|
|
581
|
+
totalEvents++;
|
|
582
|
+
uniqueInstalls.add(ev.installId);
|
|
583
|
+
if (ev.event === "boot") totalBoots++;
|
|
584
|
+
if (ev.event === "flag") totalFlags++;
|
|
585
|
+
versionCounts[ev.version] = (versionCounts[ev.version] || 0) + 1;
|
|
586
|
+
osCounts[ev.os] = (osCounts[ev.os] || 0) + 1;
|
|
587
|
+
archCounts[ev.arch] = (archCounts[ev.arch] || 0) + 1;
|
|
588
|
+
healthCounts[ev.routingHealthState] = (healthCounts[ev.routingHealthState] || 0) + 1;
|
|
589
|
+
totalAccounts += ev.accountCount || 0;
|
|
590
|
+
totalRequests += ev.totalRequests || 0;
|
|
591
|
+
// Keep only the most recent token snapshot per install
|
|
592
|
+
if (ev.tokensByModel && typeof ev.tokensByModel === "object") {
|
|
593
|
+
const prev = latestTokenSnapshotByInstall[ev.installId];
|
|
594
|
+
if (!prev || ev.ts >= prev.ts) {
|
|
595
|
+
latestTokenSnapshotByInstall[ev.installId] = { ts: ev.ts, tokensByModel: ev.tokensByModel };
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
for (const m of ev.modelsUsed || []) modelCounts[m] = (modelCounts[m] || 0) + 1;
|
|
599
|
+
if (ev.featuresUsed) {
|
|
600
|
+
for (const [k, v] of Object.entries(ev.featuresUsed)) {
|
|
601
|
+
if (v && k in featuresCount) featuresCount[k]++;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// Aggregate latest token snapshot per install into global totals
|
|
607
|
+
const globalTokensByModel = Object.create(null);
|
|
608
|
+
for (const { tokensByModel } of Object.values(latestTokenSnapshotByInstall)) {
|
|
609
|
+
for (const [model, data] of Object.entries(tokensByModel)) {
|
|
610
|
+
if (!globalTokensByModel[model]) globalTokensByModel[model] = { input: 0, output: 0, requests: 0 };
|
|
611
|
+
globalTokensByModel[model].input += data.input || 0;
|
|
612
|
+
globalTokensByModel[model].output += data.output || 0;
|
|
613
|
+
globalTokensByModel[model].requests += data.requests || 0;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// Flag aggregates
|
|
618
|
+
const flagsByStatus = Object.create(null);
|
|
619
|
+
const flagsByPattern = Object.create(null);
|
|
620
|
+
const flagsByModel = Object.create(null);
|
|
621
|
+
const flagsByTimerType = Object.create(null);
|
|
622
|
+
let flagsOnProAccounts = 0;
|
|
623
|
+
let flagsOnFreeAccounts = 0;
|
|
624
|
+
let flagRequestsTotal = 0;
|
|
625
|
+
let flagCount = 0;
|
|
626
|
+
const uniqueFlagSignatures = new Set();
|
|
627
|
+
|
|
628
|
+
for (const { fl } of flagEvents) {
|
|
629
|
+
flagCount++;
|
|
630
|
+
flagsByStatus[fl.flagHttpStatus] = (flagsByStatus[fl.flagHttpStatus] || 0) + 1;
|
|
631
|
+
for (const p of fl.flagPatternsMatched || []) flagsByPattern[p] = (flagsByPattern[p] || 0) + 1;
|
|
632
|
+
if (fl.model) flagsByModel[fl.model] = (flagsByModel[fl.model] || 0) + 1;
|
|
633
|
+
if (fl.timerType) flagsByTimerType[fl.timerType] = (flagsByTimerType[fl.timerType] || 0) + 1;
|
|
634
|
+
if (fl.wasProAccount) flagsOnProAccounts++;
|
|
635
|
+
else flagsOnFreeAccounts++;
|
|
636
|
+
flagRequestsTotal += fl.accountTotalRequests || 0;
|
|
637
|
+
const signature = JSON.stringify({
|
|
638
|
+
status: fl.flagHttpStatus,
|
|
639
|
+
patterns: [...(fl.flagPatternsMatched || [])].sort(),
|
|
640
|
+
model: fl.model || "",
|
|
641
|
+
timerType: fl.timerType || "",
|
|
642
|
+
quota: fl.accountQuotaPercent,
|
|
643
|
+
pro: !!fl.wasProAccount,
|
|
644
|
+
pause: !!fl.protectivePauseTriggered,
|
|
645
|
+
});
|
|
646
|
+
uniqueFlagSignatures.add(signature);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
const avgRequestsBeforeFlag = flagCount > 0 ? Math.round(flagRequestsTotal / flagCount) : 0;
|
|
650
|
+
const uniqueFlagIncidents = uniqueFlagSignatures.size;
|
|
651
|
+
|
|
652
|
+
// Build filter options from ALL events (unfiltered) for dropdown population
|
|
653
|
+
const filterOptions = buildFilterOptions(allEvents, allFlagEvents);
|
|
654
|
+
|
|
655
|
+
return {
|
|
656
|
+
filters: { ...filters },
|
|
657
|
+
filterOptions,
|
|
658
|
+
period: {
|
|
659
|
+
from: allFiles[0]?.replace(".jsonl", "") ?? null,
|
|
660
|
+
to: allFiles[allFiles.length - 1]?.replace(".jsonl", "") ?? null,
|
|
661
|
+
},
|
|
662
|
+
uniqueInstalls: uniqueInstalls.size,
|
|
663
|
+
totalEvents,
|
|
664
|
+
totalBoots,
|
|
665
|
+
avgAccountsPerEvent: totalEvents > 0 ? Math.round(totalAccounts / totalEvents * 10) / 10 : 0,
|
|
666
|
+
totalRequestsAcrossAll: totalRequests,
|
|
667
|
+
tokensByModel: globalTokensByModel,
|
|
668
|
+
savings: calculateSavings(globalTokensByModel),
|
|
669
|
+
versions: versionCounts,
|
|
670
|
+
os: osCounts,
|
|
671
|
+
arch: archCounts,
|
|
672
|
+
modelsUsed: modelCounts,
|
|
673
|
+
routingHealth: healthCounts,
|
|
674
|
+
featuresUsed: featuresCount,
|
|
675
|
+
flags: {
|
|
676
|
+
totalFlags: totalFlags + flagCount,
|
|
677
|
+
uniqueIncidents: uniqueFlagIncidents,
|
|
678
|
+
byHttpStatus: flagsByStatus,
|
|
679
|
+
byPattern: flagsByPattern,
|
|
680
|
+
byModel: flagsByModel,
|
|
681
|
+
byTimerType: flagsByTimerType,
|
|
682
|
+
onProAccounts: flagsOnProAccounts,
|
|
683
|
+
onFreeAccounts: flagsOnFreeAccounts,
|
|
684
|
+
avgRequestsBeforeFlag,
|
|
685
|
+
},
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// ── Public stats cache (5-minute TTL, no auth required) ──────────────
|
|
690
|
+
let publicStatsCache = null;
|
|
691
|
+
let publicStatsCacheTs = 0;
|
|
692
|
+
const PUBLIC_STATS_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
693
|
+
|
|
694
|
+
function formatLargeNumber(n) {
|
|
695
|
+
if (n >= 1_000_000_000) return `${Math.floor(n / 1_000_000_000 * 10) / 10}B`;
|
|
696
|
+
if (n >= 1_000_000) return `${Math.floor(n / 1_000_000 * 10) / 10}M`;
|
|
697
|
+
if (n >= 1_000) return `${Math.floor(n / 1_000 * 10) / 10}K`;
|
|
698
|
+
return String(n);
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function getPublicStats() {
|
|
702
|
+
const now = Date.now();
|
|
703
|
+
if (publicStatsCache && now - publicStatsCacheTs < PUBLIC_STATS_TTL_MS) {
|
|
704
|
+
return publicStatsCache;
|
|
705
|
+
}
|
|
706
|
+
try {
|
|
707
|
+
const stats = computeStats({});
|
|
708
|
+
const savingsTotal = stats.savings?.totalUsd ?? 0;
|
|
709
|
+
const requests = stats.totalRequestsAcrossAll ?? 0;
|
|
710
|
+
const installs = stats.uniqueInstalls ?? 0;
|
|
711
|
+
|
|
712
|
+
// Aggregate total input/output tokens across all models
|
|
713
|
+
let totalInputTokens = 0;
|
|
714
|
+
let totalOutputTokens = 0;
|
|
715
|
+
for (const data of Object.values(stats.tokensByModel ?? {})) {
|
|
716
|
+
totalInputTokens += data.input || 0;
|
|
717
|
+
totalOutputTokens += data.output || 0;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
publicStatsCache = {
|
|
721
|
+
installs,
|
|
722
|
+
installsFormatted: formatLargeNumber(installs),
|
|
723
|
+
requests,
|
|
724
|
+
requestsFormatted: formatLargeNumber(requests),
|
|
725
|
+
savingsUsd: savingsTotal,
|
|
726
|
+
savingsFormatted: `$${formatLargeNumber(Math.round(savingsTotal))}`,
|
|
727
|
+
tokensInput: totalInputTokens,
|
|
728
|
+
tokensInputFormatted: formatLargeNumber(totalInputTokens),
|
|
729
|
+
tokensOutput: totalOutputTokens,
|
|
730
|
+
tokensOutputFormatted: formatLargeNumber(totalOutputTokens),
|
|
731
|
+
updatedAt: new Date().toISOString(),
|
|
732
|
+
};
|
|
733
|
+
publicStatsCacheTs = now;
|
|
734
|
+
} catch {
|
|
735
|
+
// Return last cache or zeros on failure
|
|
736
|
+
if (!publicStatsCache) {
|
|
737
|
+
publicStatsCache = {
|
|
738
|
+
installs: 0, installsFormatted: "0",
|
|
739
|
+
requests: 0, requestsFormatted: "0",
|
|
740
|
+
savingsUsd: 0, savingsFormatted: "$0",
|
|
741
|
+
updatedAt: new Date().toISOString(),
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
return publicStatsCache;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// ── Public stats page ─────────────────────────────────────────────────
|
|
749
|
+
function buildPublicStatsHtml() {
|
|
750
|
+
return `<!DOCTYPE html>
|
|
751
|
+
<html lang="en">
|
|
752
|
+
<head>
|
|
753
|
+
<meta charset="UTF-8">
|
|
754
|
+
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
|
755
|
+
<meta name="description" content="Anonymous usage statistics for Tuxevil Rotator">
|
|
756
|
+
<title>Tuxevil Rotator Stats</title>
|
|
757
|
+
<style>
|
|
758
|
+
:root{color-scheme:dark;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#0f1117;color:#e2e8f0}
|
|
759
|
+
*{box-sizing:border-box}
|
|
760
|
+
body{margin:0;min-height:100vh;background:radial-gradient(circle at top,#1a2538 0,#0f1117 42rem);padding:24px}
|
|
761
|
+
main{max-width:920px;margin:0 auto;padding:clamp(28px,7vw,72px) 0}
|
|
762
|
+
.eyebrow{color:#63b3ed;font-size:12px;font-weight:700;letter-spacing:.14em;text-transform:uppercase}
|
|
763
|
+
h1{margin:10px 0 12px;color:#fff;font-size:clamp(32px,6vw,56px);letter-spacing:-.04em;line-height:1}
|
|
764
|
+
.intro{max-width:560px;margin:0;color:#a0aec0;font-size:16px;line-height:1.6}
|
|
765
|
+
.intro a,.footer a{color:#90cdf4;text-decoration:none}
|
|
766
|
+
.intro a:hover,.footer a:hover{text-decoration:underline}
|
|
767
|
+
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin:40px 0 18px}
|
|
768
|
+
.stat{min-height:126px;padding:20px;background:rgba(26,31,46,.88);border:1px solid #2d3748;border-radius:14px;box-shadow:0 12px 30px rgba(0,0,0,.16)}
|
|
769
|
+
.stat-label{color:#718096;font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase}
|
|
770
|
+
.stat-value{margin-top:16px;color:#fff;font-size:clamp(25px,4vw,36px);font-weight:800;letter-spacing:-.03em}
|
|
771
|
+
.stat:nth-child(1) .stat-value{color:#b794f4}
|
|
772
|
+
.stat:nth-child(2) .stat-value{color:#68d391}
|
|
773
|
+
.stat:nth-child(3) .stat-value{color:#f6e05e}
|
|
774
|
+
.stat:nth-child(4) .stat-value{color:#63b3ed}
|
|
775
|
+
.stat:nth-child(5) .stat-value{color:#90cdf4}
|
|
776
|
+
.status{min-height:20px;color:#718096;font-size:12px}
|
|
777
|
+
.status.error{color:#fc8181}
|
|
778
|
+
.footer{display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-top:56px;padding-top:16px;border-top:1px solid #2d3748;color:#718096;font-size:12px}
|
|
779
|
+
@media (max-width:520px){body{padding:18px}.stats-grid{margin-top:30px}.stat{min-height:112px;padding:16px}.stat-value{margin-top:12px}}
|
|
780
|
+
</style>
|
|
781
|
+
</head>
|
|
782
|
+
<body>
|
|
783
|
+
<main>
|
|
784
|
+
<div class="eyebrow">Tuxevil Rotator</div>
|
|
785
|
+
<h1>Usage at a glance.</h1>
|
|
786
|
+
<p class="intro">Anonymous aggregate telemetry from the community. Values refresh automatically every five minutes. <a href="/v1/public-stats">View the raw data</a>.</p>
|
|
787
|
+
<section class="stats-grid" aria-label="Public usage statistics">
|
|
788
|
+
<article class="stat"><div class="stat-label">Installations</div><div class="stat-value" id="installs">-</div></article>
|
|
789
|
+
<article class="stat"><div class="stat-label">Requests routed</div><div class="stat-value" id="requests">-</div></article>
|
|
790
|
+
<article class="stat"><div class="stat-label">Estimated savings</div><div class="stat-value" id="savings">-</div></article>
|
|
791
|
+
<article class="stat"><div class="stat-label">Input tokens</div><div class="stat-value" id="tokensInput">-</div></article>
|
|
792
|
+
<article class="stat"><div class="stat-label">Output tokens</div><div class="stat-value" id="tokensOutput">-</div></article>
|
|
793
|
+
</section>
|
|
794
|
+
<div class="status" id="status" role="status" aria-live="polite">Loading live totals...</div>
|
|
795
|
+
<footer class="footer"><span>Updated from anonymous telemetry</span><a href="https://github.com/tuxevil/tuxevil-rotator">View the project on GitHub</a></footer>
|
|
796
|
+
</main>
|
|
797
|
+
<script>
|
|
798
|
+
const REFRESH_MS = 5 * 60 * 1000;
|
|
799
|
+
const fields = [
|
|
800
|
+
["installs", "installsFormatted"],
|
|
801
|
+
["requests", "requestsFormatted"],
|
|
802
|
+
["savings", "savingsFormatted"],
|
|
803
|
+
["tokensInput", "tokensInputFormatted"],
|
|
804
|
+
["tokensOutput", "tokensOutputFormatted"],
|
|
805
|
+
];
|
|
806
|
+
|
|
807
|
+
function formatUpdatedAt(value) {
|
|
808
|
+
if (!value) return "Updated just now";
|
|
809
|
+
const date = new Date(value);
|
|
810
|
+
return Number.isNaN(date.getTime()) ? "Updated just now" : "Updated " + date.toLocaleString();
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
async function loadStats() {
|
|
814
|
+
const status = document.getElementById("status");
|
|
815
|
+
try {
|
|
816
|
+
const response = await fetch("/v1/public-stats", { cache: "no-store" });
|
|
817
|
+
if (!response.ok) throw new Error("HTTP " + response.status);
|
|
818
|
+
const stats = await response.json();
|
|
819
|
+
for (const [elementId, field] of fields) {
|
|
820
|
+
document.getElementById(elementId).textContent = stats[field] ?? "-";
|
|
821
|
+
}
|
|
822
|
+
status.className = "status";
|
|
823
|
+
status.textContent = formatUpdatedAt(stats.updatedAt);
|
|
824
|
+
} catch (error) {
|
|
825
|
+
status.className = "status error";
|
|
826
|
+
status.textContent = "Live totals are temporarily unavailable. Retrying in five minutes.";
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
loadStats();
|
|
831
|
+
setInterval(loadStats, REFRESH_MS);
|
|
832
|
+
</script>
|
|
833
|
+
</body>
|
|
834
|
+
</html>`;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// ── Rate limiting (simple in-memory per-IP) ──────────────────────────
|
|
838
|
+
const rateLimitMap = new Map();
|
|
839
|
+
const RATE_LIMIT_WINDOW_MS = 60_000;
|
|
840
|
+
const RATE_LIMIT_MAX = 12; // 12 requests per minute per IP
|
|
841
|
+
|
|
842
|
+
function isRateLimited(ip) {
|
|
843
|
+
const now = Date.now();
|
|
844
|
+
let entry = rateLimitMap.get(ip);
|
|
845
|
+
if (!entry || now - entry.windowStart > RATE_LIMIT_WINDOW_MS) {
|
|
846
|
+
entry = { windowStart: now, count: 0 };
|
|
847
|
+
rateLimitMap.set(ip, entry);
|
|
848
|
+
}
|
|
849
|
+
entry.count++;
|
|
850
|
+
return entry.count > RATE_LIMIT_MAX;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// Cleanup stale entries every 5 minutes
|
|
854
|
+
setInterval(() => {
|
|
855
|
+
const now = Date.now();
|
|
856
|
+
for (const [ip, entry] of rateLimitMap) {
|
|
857
|
+
if (now - entry.windowStart > RATE_LIMIT_WINDOW_MS * 2) {
|
|
858
|
+
rateLimitMap.delete(ip);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}, 5 * 60_000).unref();
|
|
862
|
+
|
|
863
|
+
// ── Dashboard HTML ───────────────────────────────────────────────────
|
|
864
|
+
function buildDashboardHtml() {
|
|
865
|
+
return `<!DOCTYPE html>
|
|
866
|
+
<html lang="en">
|
|
867
|
+
<head>
|
|
868
|
+
<meta charset="UTF-8">
|
|
869
|
+
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
|
870
|
+
<title>Tuxevil Rotator Telemetry</title>
|
|
871
|
+
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"><\/script>
|
|
872
|
+
<style>
|
|
873
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
874
|
+
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#0f1117;color:#e2e8f0;min-height:100vh}
|
|
875
|
+
.header{background:#1a1f2e;border-bottom:1px solid #2d3748;padding:14px 24px;display:flex;align-items:center;gap:12px}
|
|
876
|
+
.header h1{font-size:17px;font-weight:700;color:#fff}
|
|
877
|
+
.header .ts{font-size:11px;color:#718096;background:#2d3748;padding:2px 8px;border-radius:10px;margin-left:auto}
|
|
878
|
+
.token-bar{background:#1a1f2e;border-bottom:1px solid #2d3748;padding:10px 24px;display:flex;gap:8px;align-items:center}
|
|
879
|
+
.token-bar input[type=password]{flex:1;background:#0f1117;border:1px solid #2d3748;border-radius:6px;padding:7px 12px;color:#e2e8f0;font-size:13px;font-family:monospace}
|
|
880
|
+
.token-bar input[type=password]:focus{outline:none;border-color:#4299e1}
|
|
881
|
+
.token-bar button{background:#4299e1;color:#fff;border:none;border-radius:6px;padding:7px 16px;cursor:pointer;font-size:13px;font-weight:600;white-space:nowrap}
|
|
882
|
+
.token-bar button:hover{background:#3182ce}
|
|
883
|
+
.filter-bar{background:#141820;border-bottom:1px solid #2d3748;padding:10px 24px;display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end}
|
|
884
|
+
.filter-group{display:flex;flex-direction:column;gap:3px;min-width:140px}
|
|
885
|
+
.filter-group label{font-size:10px;color:#718096;text-transform:uppercase;letter-spacing:.06em}
|
|
886
|
+
select,input[type=date]{background:#1a1f2e;border:1px solid #2d3748;border-radius:6px;padding:6px 10px;color:#e2e8f0;font-size:12px;cursor:pointer}
|
|
887
|
+
select:focus,input[type=date]:focus{outline:none;border-color:#4299e1}
|
|
888
|
+
.filter-actions{display:flex;gap:6px;margin-top:14px}
|
|
889
|
+
.btn-apply{background:#4299e1;color:#fff;border:none;border-radius:6px;padding:6px 14px;cursor:pointer;font-size:12px;font-weight:600}
|
|
890
|
+
.btn-clear{background:#2d3748;color:#a0aec0;border:none;border-radius:6px;padding:6px 14px;cursor:pointer;font-size:12px}
|
|
891
|
+
.filter-active{background:#1c4532;border:1px solid #276749;border-radius:6px;padding:4px 10px;font-size:11px;color:#68d391;display:none;align-items:center;gap:6px}
|
|
892
|
+
.filter-active.show{display:flex}
|
|
893
|
+
.main{padding:20px 24px;max-width:1400px;margin:0 auto}
|
|
894
|
+
.kpi-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(155px,1fr));gap:10px;margin-bottom:18px}
|
|
895
|
+
.kpi{background:#1a1f2e;border:1px solid #2d3748;border-radius:10px;padding:14px}
|
|
896
|
+
.kpi .label{font-size:10px;color:#718096;text-transform:uppercase;letter-spacing:.05em;margin-bottom:5px}
|
|
897
|
+
.kpi .value{font-size:24px;font-weight:700;color:#fff}
|
|
898
|
+
.kpi .sub{font-size:10px;color:#718096;margin-top:3px}
|
|
899
|
+
.kpi.green .value{color:#68d391}.kpi.blue .value{color:#63b3ed}
|
|
900
|
+
.kpi.yellow .value{color:#f6e05e}.kpi.red .value{color:#fc8181}
|
|
901
|
+
.section{background:#1a1f2e;border:1px solid #2d3748;border-radius:10px;padding:18px;margin-bottom:14px}
|
|
902
|
+
.section h2{font-size:11px;font-weight:700;color:#718096;text-transform:uppercase;letter-spacing:.08em;margin-bottom:14px}
|
|
903
|
+
.charts{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:14px;margin-bottom:14px}
|
|
904
|
+
.chart-box{background:#1a1f2e;border:1px solid #2d3748;border-radius:10px;padding:18px}
|
|
905
|
+
.chart-box h2{font-size:11px;font-weight:700;color:#718096;text-transform:uppercase;letter-spacing:.08em;margin-bottom:12px}
|
|
906
|
+
.chart-box canvas{max-height:190px}
|
|
907
|
+
.flag-kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin-bottom:14px}
|
|
908
|
+
.flag-kpi{background:#2d1f1f;border:1px solid #742a2a;border-radius:8px;padding:12px}
|
|
909
|
+
.flag-kpi .label{font-size:10px;color:#fc8181;text-transform:uppercase;letter-spacing:.05em;margin-bottom:5px}
|
|
910
|
+
.flag-kpi .value{font-size:20px;font-weight:700;color:#feb2b2}
|
|
911
|
+
table{width:100%;border-collapse:collapse;font-size:12px}
|
|
912
|
+
th{text-align:left;padding:7px 12px;color:#718096;border-bottom:1px solid #2d3748;font-weight:500;white-space:nowrap}
|
|
913
|
+
td{padding:7px 12px;border-bottom:1px solid #1f2535;color:#e2e8f0}
|
|
914
|
+
tr:last-child td{border-bottom:none}
|
|
915
|
+
.mono{font-family:monospace;color:#68d391}
|
|
916
|
+
.savings-big{font-size:36px;font-weight:800;color:#68d391;margin-bottom:3px}
|
|
917
|
+
.savings-sub{font-size:12px;color:#718096;margin-bottom:14px}
|
|
918
|
+
.error{background:#2d1515;border:1px solid #742a2a;border-radius:8px;padding:12px;color:#fc8181;margin-bottom:14px}
|
|
919
|
+
.empty{color:#4a5568;font-size:12px;padding:20px;text-align:center}
|
|
920
|
+
|
|
921
|
+
/* ── View toggle ── */
|
|
922
|
+
.view-tabs{display:flex;gap:8px;padding:12px 24px;background:#141820;border-bottom:1px solid #2d3748}
|
|
923
|
+
.view-tab{font-size:12px;font-weight:600;padding:5px 14px;border-radius:999px;border:1px solid #2d3748;background:transparent;color:#718096;cursor:pointer;font-family:inherit;transition:all .2s}
|
|
924
|
+
.view-tab.active{background:rgba(66,153,225,.15);border-color:rgba(66,153,225,.4);color:#63b3ed}
|
|
925
|
+
.view-tab:hover:not(.active){background:rgba(255,255,255,.04);color:#e2e8f0}
|
|
926
|
+
|
|
927
|
+
/* ── Installs list ── */
|
|
928
|
+
.install-toolbar{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}
|
|
929
|
+
.install-search{background:#0f1117;border:1px solid #2d3748;border-radius:6px;padding:6px 12px;color:#e2e8f0;font-size:12px;font-family:inherit;width:200px;outline:none;transition:border-color .2s}
|
|
930
|
+
.install-search:focus{border-color:#4299e1}
|
|
931
|
+
.sort-btn{font-size:11px;padding:4px 10px;border:1px solid #2d3748;background:transparent;color:#718096;border-radius:6px;cursor:pointer;font-family:inherit;font-weight:600;transition:all .2s}
|
|
932
|
+
.sort-btn.active{border-color:rgba(66,153,225,.4);color:#63b3ed;background:rgba(66,153,225,.08)}
|
|
933
|
+
.install-table{width:100%;border-collapse:collapse}
|
|
934
|
+
.install-table th{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#718096;padding:8px 12px;text-align:left;border-bottom:1px solid #2d3748;background:rgba(255,255,255,.02);white-space:nowrap;cursor:pointer;user-select:none}
|
|
935
|
+
.install-table th:hover{color:#e2e8f0}
|
|
936
|
+
.install-table th .arr{display:inline-block;margin-left:3px;opacity:.35;font-size:9px}
|
|
937
|
+
.install-table th.sort-active .arr{opacity:1;color:#63b3ed}
|
|
938
|
+
.install-table td{padding:9px 12px;font-size:12px;border-bottom:1px solid #1f2535;vertical-align:middle}
|
|
939
|
+
.install-table tr:last-child td{border-bottom:none}
|
|
940
|
+
.install-row{cursor:pointer;transition:background .15s}
|
|
941
|
+
.install-row:hover td{background:rgba(66,153,225,.05)}
|
|
942
|
+
.install-row.selected td{background:rgba(66,153,225,.1)}
|
|
943
|
+
.install-id{font-family:monospace;font-size:11px;color:#718096}
|
|
944
|
+
.install-id strong{color:#63b3ed;display:block;font-size:12px;margin-bottom:1px}
|
|
945
|
+
.mini-bar{display:flex;align-items:center;gap:5px}
|
|
946
|
+
.mini-bar-bg{width:50px;height:4px;background:rgba(255,255,255,.08);border-radius:2px;overflow:hidden;flex-shrink:0}
|
|
947
|
+
.mini-bar-fill{height:100%;border-radius:2px}
|
|
948
|
+
.health-dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:5px;flex-shrink:0}
|
|
949
|
+
.install-list-panel{background:#1a1f2e;border:1px solid #2d3748;border-radius:10px;padding:18px}
|
|
950
|
+
.install-list-panel h2{font-size:11px;font-weight:700;color:#718096;text-transform:uppercase;letter-spacing:.08em;margin-bottom:14px}
|
|
951
|
+
</style>
|
|
952
|
+
<style>
|
|
953
|
+
:root{color-scheme:dark;--bg:#0b0f17;--panel:#141b29;--panel-2:#192235;--line:#29364b;--muted:#7d8ca5;--text:#e8eef8;--blue:#78b7ff;--green:#72dfa0;--yellow:#f6d365;--red:#ff8b8b;--purple:#aa9cff}
|
|
954
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
955
|
+
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:radial-gradient(circle at 18% -10%,#1c304b 0,#0f1117 38rem);color:var(--text);min-height:100vh}
|
|
956
|
+
button,input,textarea,select{font:inherit}
|
|
957
|
+
button{border:0}
|
|
958
|
+
button:focus-visible,a:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:2px solid var(--blue);outline-offset:2px}
|
|
959
|
+
a{color:inherit}
|
|
960
|
+
.topbar{border-bottom:1px solid rgba(125,140,165,.18);background:rgba(11,15,23,.72);backdrop-filter:blur(14px)}
|
|
961
|
+
.topbar-inner{max-width:1240px;margin:0 auto;padding:17px 28px;display:flex;align-items:center;gap:24px}
|
|
962
|
+
.brand{display:flex;align-items:center;gap:11px;text-decoration:none;min-width:0}
|
|
963
|
+
.brand-mark{width:31px;height:31px;border-radius:10px;background:linear-gradient(135deg,#78b7ff,#8b7dff);box-shadow:0 0 24px rgba(120,183,255,.25);position:relative;flex-shrink:0}
|
|
964
|
+
.brand-mark:after{content:'';position:absolute;width:9px;height:9px;border-radius:50%;background:#fff;left:11px;top:11px;box-shadow:0 0 0 4px rgba(255,255,255,.2)}
|
|
965
|
+
.brand strong{display:block;color:#fff;font-size:14px;letter-spacing:.01em}.brand small{display:block;color:var(--muted);font-size:10px;letter-spacing:.08em;text-transform:uppercase;margin-top:2px}
|
|
966
|
+
.nav{margin-left:auto;display:flex;align-items:center;gap:7px}.nav a,.nav-lock{color:var(--muted);font-size:12px;text-decoration:none;padding:7px 10px;border-radius:7px;transition:color .2s,background .2s}.nav a:hover{color:#fff;background:rgba(255,255,255,.07)}
|
|
967
|
+
.nav-lock{color:var(--green);background:rgba(114,223,160,.08);font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase}
|
|
968
|
+
.auth-strip{border-bottom:1px solid rgba(125,140,165,.18);background:rgba(20,27,41,.76)}
|
|
969
|
+
.auth-inner{max-width:1240px;margin:0 auto;padding:18px 28px;display:flex;align-items:center;justify-content:space-between;gap:24px}
|
|
970
|
+
.auth-kicker,.eyebrow,.section-kicker{color:var(--blue);font-size:10px;font-weight:800;letter-spacing:.14em;text-transform:uppercase}
|
|
971
|
+
.auth-title{color:#fff;font-size:16px;font-weight:700;margin-top:4px}.auth-note{color:var(--muted);font-size:12px;margin-top:3px}
|
|
972
|
+
.auth-controls{display:flex;align-items:center;gap:12px;min-width:min(100%,500px)}
|
|
973
|
+
.connection{display:flex;align-items:center;gap:7px;white-space:nowrap;color:var(--muted);font-size:11px;font-weight:600}.connection-dot{width:8px;height:8px;border-radius:50%;background:#59677d;box-shadow:0 0 0 4px rgba(89,103,125,.12)}
|
|
974
|
+
.connection.connected{color:var(--green)}.connection.connected .connection-dot{background:var(--green);box-shadow:0 0 0 4px rgba(114,223,160,.12)}
|
|
975
|
+
.connection.connecting{color:var(--yellow)}.connection.connecting .connection-dot{background:var(--yellow);box-shadow:0 0 0 4px rgba(246,211,101,.12);animation:pulse 1.2s ease-in-out infinite}
|
|
976
|
+
.connection.error{color:var(--red)}.connection.error .connection-dot{background:var(--red);box-shadow:0 0 0 4px rgba(255,139,139,.12)}
|
|
977
|
+
.token-form{display:flex;gap:8px;flex:1}.token-form input{width:100%;min-width:0;background:#0b1019;border:1px solid var(--line);border-radius:8px;padding:9px 12px;color:var(--text);font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.token-form input::placeholder{color:#56657c}.token-form input:focus{border-color:var(--blue);outline:none;box-shadow:0 0 0 3px rgba(120,183,255,.12)}
|
|
978
|
+
.dashboard-shell{max-width:1240px;margin:0 auto;padding:34px 28px 64px}.dashboard-hero{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;margin-bottom:22px}.dashboard-hero h1{color:#fff;font-size:clamp(28px,4vw,44px);line-height:1.05;letter-spacing:-.045em;margin:10px 0}.dashboard-hero p{max-width:650px;color:#91a0b7;font-size:14px;line-height:1.6}.hero-actions{display:flex;align-items:center;gap:12px;flex-shrink:0}.sync-note{color:var(--muted);font-size:11px;white-space:nowrap}
|
|
979
|
+
.dashboard-tabs{display:flex;align-items:center;gap:8px;margin-bottom:13px}.view-tabs{max-width:1240px;margin:0 auto;padding:0 28px 14px;background:transparent;display:flex;gap:8px;border:0}.view-tab{font-size:11px;font-weight:800;padding:8px 13px;border-radius:8px;border:1px solid var(--line);background:rgba(20,27,41,.72);color:var(--muted);cursor:pointer;font-family:inherit;transition:all .2s;letter-spacing:.02em}.view-tab.active{background:rgba(120,183,255,.13);border-color:rgba(120,183,255,.42);color:var(--blue)}.view-tab:hover:not(.active){background:rgba(255,255,255,.05);color:#fff}
|
|
980
|
+
.filter-bar{max-width:1240px;margin:0 auto 17px;padding:14px 28px;background:rgba(20,27,41,.88);border:1px solid var(--line);border-radius:12px;display:flex;flex-wrap:wrap;gap:9px;align-items:flex-end}.filter-group{display:flex;flex-direction:column;gap:5px;min-width:135px;flex:1}.filter-group label{font-size:9px;color:var(--muted);text-transform:uppercase;letter-spacing:.1em;font-weight:800}.filter-group select,.filter-group input[type=date]{width:100%;background:#0c121d;border:1px solid var(--line);border-radius:8px;padding:8px 10px;color:var(--text);font-size:12px;cursor:pointer}.filter-group select:focus,.filter-group input[type=date]:focus{outline:none;border-color:var(--blue);box-shadow:0 0 0 3px rgba(120,183,255,.1)}.filter-actions{display:flex;gap:7px}.btn-apply,.btn-clear,.btn-refresh{border-radius:8px;padding:8px 12px;cursor:pointer;font-size:11px;font-weight:800;transition:background .2s,border-color .2s,color .2s}.btn-apply{background:var(--blue);color:#08111d}.btn-apply:hover{background:#9bcaff}.btn-clear{background:#26334a;color:#b5c3d6}.btn-clear:hover{background:#33435c;color:#fff}.btn-refresh{background:rgba(120,183,255,.08);border:1px solid rgba(120,183,255,.25);color:var(--blue)}.btn-refresh:hover{background:rgba(120,183,255,.15)}.filter-active{background:rgba(114,223,160,.1);border:1px solid rgba(114,223,160,.28);border-radius:8px;padding:7px 10px;font-size:10px;color:var(--green);display:none;align-items:center;gap:6px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.filter-active.show{display:flex}
|
|
981
|
+
.main{padding:0;max-width:none;margin:0}.main>.error{margin:0 0 16px}.error{background:rgba(255,139,139,.1);border:1px solid rgba(255,139,139,.32);border-radius:10px;padding:12px 14px;color:var(--red);font-size:12px;line-height:1.4}.app-shell{display:block}
|
|
982
|
+
.kpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:17px}.kpi{position:relative;overflow:hidden;background:linear-gradient(145deg,rgba(25,34,53,.92),rgba(17,24,38,.92));border:1px solid var(--line);border-radius:12px;padding:15px 16px;min-height:98px}.kpi:after{content:'';position:absolute;width:70px;height:70px;border-radius:50%;right:-28px;bottom:-38px;background:var(--metric-color,#78b7ff);opacity:.08;filter:blur(3px)}.kpi .label{color:var(--muted);font-size:9px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}.kpi .value{color:#fff;font-size:23px;font-weight:800;letter-spacing:-.04em;margin-top:11px;overflow-wrap:anywhere}.kpi .sub{color:#61718a;font-size:10px;margin-top:3px}.kpi.green{--metric-color:var(--green)}.kpi.blue{--metric-color:var(--blue)}.kpi.yellow{--metric-color:var(--yellow)}.kpi.red{--metric-color:var(--red)}.kpi.green .value{color:var(--green)}.kpi.blue .value{color:var(--blue)}.kpi.yellow .value{color:var(--yellow)}.kpi.red .value{color:var(--red)}
|
|
983
|
+
.section{background:rgba(20,27,41,.9);border:1px solid var(--line);border-radius:14px;padding:21px;margin-bottom:15px;box-shadow:0 18px 45px rgba(0,0,0,.1)}.section h2{color:#fff;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;margin-bottom:15px}.section-title{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;margin-bottom:17px}.section-title h2{margin:6px 0 0;font-size:18px;letter-spacing:-.02em;text-transform:none}.section-title p{color:var(--muted);font-size:11px;margin-top:5px}
|
|
984
|
+
.savings-layout{display:grid;grid-template-columns:minmax(220px,.65fr) minmax(0,1.35fr);gap:20px;align-items:start}.savings-big{font-size:clamp(32px,5vw,47px);font-weight:850;letter-spacing:-.055em;color:var(--green);margin:4px 0 3px}.savings-sub{font-size:12px;color:var(--muted);line-height:1.5;margin-bottom:13px}.savings-note{color:#61718a;font-size:10px;line-height:1.5;max-width:240px}
|
|
985
|
+
.flag-kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:9px;margin-bottom:16px}.flag-kpi{background:rgba(255,139,139,.07);border:1px solid rgba(255,139,139,.22);border-radius:10px;padding:12px}.flag-kpi .label{font-size:9px;color:#e08b95;text-transform:uppercase;letter-spacing:.08em;font-weight:800}.flag-kpi .value{font-size:20px;font-weight:800;color:#ffb0b0;margin-top:7px}.charts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:13px;margin-bottom:15px}.charts:last-child{margin-bottom:0}.chart-box{min-width:0;background:rgba(11,16,25,.52);border:1px solid #243148;border-radius:11px;padding:16px}.chart-box h2{font-size:10px;color:var(--muted);letter-spacing:.1em;margin-bottom:12px}.chart-box canvas{max-height:205px}
|
|
986
|
+
table{width:100%;border-collapse:collapse;font-size:12px}th{text-align:left;padding:8px 11px;color:var(--muted);border-bottom:1px solid var(--line);font-weight:600;white-space:nowrap}td{padding:9px 11px;border-bottom:1px solid rgba(41,54,75,.55);color:#d8e1ee;vertical-align:top}tr:last-child td{border-bottom:none}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--green);font-size:11px}.empty{border:1px dashed #33445e;border-radius:10px;color:#6e7e96;font-size:12px;line-height:1.5;padding:28px 20px;text-align:center}.install-list-panel{background:rgba(20,27,41,.9);border:1px solid var(--line);border-radius:14px;padding:21px;box-shadow:0 18px 45px rgba(0,0,0,.1)}.install-list-panel h2{color:#fff;font-size:18px;letter-spacing:-.02em;text-transform:none;margin:6px 0 0}.install-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;margin-bottom:17px}.install-heading p{color:var(--muted);font-size:11px;margin-top:5px}.install-count{color:var(--blue);font-size:11px;font-weight:700;background:rgba(120,183,255,.09);border:1px solid rgba(120,183,255,.22);border-radius:999px;padding:5px 9px}.install-toolbar{display:flex;align-items:center;gap:8px;margin-bottom:14px;flex-wrap:wrap}.install-search{background:#0c121d;border:1px solid var(--line);border-radius:8px;padding:9px 11px;color:var(--text);font-size:12px;font-family:inherit;width:240px;outline:none;transition:border-color .2s}.install-search:focus{border-color:var(--blue);box-shadow:0 0 0 3px rgba(120,183,255,.1)}.sort-btn{font-size:10px;padding:7px 9px;border:1px solid var(--line);background:transparent;color:var(--muted);border-radius:7px;cursor:pointer;font-family:inherit;font-weight:700;transition:all .2s}.sort-btn.active{border-color:rgba(120,183,255,.4);color:var(--blue);background:rgba(120,183,255,.08)}.sort-btn:hover{color:#fff;background:rgba(255,255,255,.05)}.install-table{width:100%;border-collapse:collapse}.install-table th{font-size:9px;font-weight:800;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);padding:9px 11px;text-align:left;border-bottom:1px solid var(--line);background:rgba(255,255,255,.02);white-space:nowrap;cursor:pointer;user-select:none}.install-table th:hover{color:#fff}.install-table th .arr{display:inline-block;margin-left:3px;opacity:.35;font-size:9px}.install-table th.sort-active .arr{opacity:1;color:var(--blue)}.install-table td{padding:10px 11px;font-size:12px;border-bottom:1px solid rgba(41,54,75,.55);vertical-align:middle}.install-table tr:last-child td{border-bottom:none}.install-row{cursor:pointer;transition:background .15s}.install-row:hover td{background:rgba(120,183,255,.05)}.install-row.selected td{background:rgba(120,183,255,.1)}.install-id{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;color:var(--muted)}.install-id strong{color:var(--blue);display:block;font-size:12px;margin-bottom:1px}.health-dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:5px;flex-shrink:0}
|
|
987
|
+
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@keyframes pulse{50%{opacity:.45}}
|
|
988
|
+
@media(max-width:980px){.auth-inner{align-items:flex-start;flex-direction:column;gap:14px}.auth-controls{width:100%;max-width:none}.kpi-grid{grid-template-columns:repeat(3,1fr)}.charts{grid-template-columns:repeat(2,minmax(0,1fr))}.savings-layout{grid-template-columns:1fr}.savings-note{max-width:none}}
|
|
989
|
+
@media(max-width:680px){.topbar-inner,.auth-inner,.dashboard-shell,.view-tabs,.filter-bar{padding-left:17px;padding-right:17px}.nav a{display:none}.nav-lock{padding:6px 8px}.dashboard-shell{padding-top:28px}.dashboard-hero{align-items:flex-start;flex-direction:column;margin-bottom:18px}.hero-actions{width:100%;justify-content:space-between}.kpi-grid{grid-template-columns:repeat(2,1fr);gap:8px}.kpi{min-height:90px;padding:13px}.kpi .value{font-size:21px}.view-tabs{overflow:auto}.filter-bar{align-items:stretch;flex-direction:column}.filter-group{min-width:0}.filter-actions{width:100%}.filter-actions button{flex:1}.filter-active{max-width:none}.section,.install-list-panel{padding:17px}.section-title,.install-heading{align-items:flex-start;flex-direction:column;gap:4px}.charts,.flag-kpis{grid-template-columns:1fr}.chart-box{min-height:220px}.install-toolbar{align-items:stretch;flex-direction:column}.install-search{width:100%}.install-table{display:block;overflow-x:auto;white-space:nowrap}.auth-controls{align-items:stretch;flex-direction:column}.token-form{width:100%}}
|
|
990
|
+
</style>
|
|
991
|
+
</head>
|
|
992
|
+
<body>
|
|
993
|
+
<header class="topbar">
|
|
994
|
+
<div class="topbar-inner">
|
|
995
|
+
<a class="brand" href="/">
|
|
996
|
+
<span class="brand-mark" aria-hidden="true"></span>
|
|
997
|
+
<span><strong>Tuxevil Rotator</strong><small>Operations</small></span>
|
|
998
|
+
</a>
|
|
999
|
+
<nav class="nav" aria-label="Operator navigation">
|
|
1000
|
+
<a href="/notifications">Notifications</a>
|
|
1001
|
+
<a href="/stats">Public stats</a>
|
|
1002
|
+
<span class="nav-lock">Private</span>
|
|
1003
|
+
</nav>
|
|
1004
|
+
</div>
|
|
1005
|
+
</header>
|
|
1006
|
+
<section class="auth-strip">
|
|
1007
|
+
<div class="auth-inner">
|
|
1008
|
+
<div>
|
|
1009
|
+
<div class="auth-kicker">Operator access</div>
|
|
1010
|
+
<div class="auth-title">Telemetry control room</div>
|
|
1011
|
+
<div class="auth-note">Inspect aggregate usage, account health and routing signals.</div>
|
|
1012
|
+
</div>
|
|
1013
|
+
<div class="auth-controls">
|
|
1014
|
+
<div class="connection" id="dashboardConnection"><span class="connection-dot"></span><span id="dashboardConnectionLabel">Not connected</span></div>
|
|
1015
|
+
<form class="token-form" id="dashboardAuthForm" onsubmit="load(event)">
|
|
1016
|
+
<label class="sr-only" for="tok">STATS_TOKEN</label>
|
|
1017
|
+
<input type="password" id="tok" autocomplete="current-password" placeholder="Paste STATS_TOKEN" />
|
|
1018
|
+
<button class="btn-apply" id="loadBtn" type="submit">Connect</button>
|
|
1019
|
+
</form>
|
|
1020
|
+
</div>
|
|
1021
|
+
</div>
|
|
1022
|
+
</section>
|
|
1023
|
+
|
|
1024
|
+
<div class="view-tabs" id="viewTabs" style="display:none"><button class="view-tab active" id="vtAgg" type="button" onclick="switchView('agg')">Overview</button><button class="view-tab" id="vtList" type="button" onclick="switchView('list')">Installations</button></div>
|
|
1025
|
+
<div class="filter-bar" id="filterBar" style="display:none">
|
|
1026
|
+
<div class="filter-group"><label for="fInstall">Install ID</label><select id="fInstall"><option value="">All installs</option></select></div>
|
|
1027
|
+
<div class="filter-group"><label for="fVersion">Version</label><select id="fVersion"><option value="">All versions</option></select></div>
|
|
1028
|
+
<div class="filter-group"><label for="fOS">Operating system</label><select id="fOS"><option value="">All OS</option></select></div>
|
|
1029
|
+
<div class="filter-group"><label for="fModel">Model</label><select id="fModel"><option value="">All models</option></select></div>
|
|
1030
|
+
<div class="filter-group"><label for="fFrom">From</label><input type="date" id="fFrom" /></div>
|
|
1031
|
+
<div class="filter-group"><label for="fTo">To</label><input type="date" id="fTo" /></div>
|
|
1032
|
+
<div class="filter-actions"><button class="btn-apply" type="button" onclick="applyFilters()">Apply</button><button class="btn-clear" type="button" onclick="clearFilters()">Clear</button></div>
|
|
1033
|
+
<div class="filter-active" id="filterActive">Filtered view</div>
|
|
1034
|
+
</div>
|
|
1035
|
+
|
|
1036
|
+
<div class="dashboard-shell">
|
|
1037
|
+
<div class="dashboard-hero">
|
|
1038
|
+
<div><div class="eyebrow">Observability / Telemetry</div><h1>See the system in motion.</h1><p>Understand adoption, routing health and account signals from one focused operational view.</p></div>
|
|
1039
|
+
<div class="hero-actions"><span class="sync-note" id="ts">Not synced</span><button class="btn-refresh" id="refreshBtn" type="button" onclick="refreshDashboard()">Refresh</button></div>
|
|
1040
|
+
</div>
|
|
1041
|
+
<div class="main">
|
|
1042
|
+
<div class="error" id="err" style="display:none"></div>
|
|
1043
|
+
<div id="app" class="app-shell" style="display:none">
|
|
1044
|
+
<div class="kpi-grid" id="kpis"></div>
|
|
1045
|
+
<section class="section savings-section">
|
|
1046
|
+
<div class="section-title"><div><div class="section-kicker">Efficiency</div><h2>Estimated savings</h2><p>USD avoided versus a paid API across the selected period.</p></div></div>
|
|
1047
|
+
<div class="savings-layout"><div><div class="savings-big" id="savTotal">$0.00</div><div class="savings-sub">Total saved across the current filter set</div><p class="savings-note">Use the filters above to compare cohorts, versions, models or individual installs.</p></div><div id="savTable"></div></div>
|
|
1048
|
+
</section>
|
|
1049
|
+
<section class="section">
|
|
1050
|
+
<div class="section-title"><div><div class="section-kicker">Safety signals</div><h2>Flag analysis</h2><p>Patterns that need operator attention.</p></div></div>
|
|
1051
|
+
<div class="flag-kpis" id="flagKpis"></div>
|
|
1052
|
+
<div class="charts"><div class="chart-box"><h2>By pattern</h2><canvas id="cPatterns"></canvas></div><div class="chart-box"><h2>By model</h2><canvas id="cFlagModels"></canvas></div><div class="chart-box"><h2>By timer type</h2><canvas id="cTimerType"></canvas></div></div>
|
|
1053
|
+
</section>
|
|
1054
|
+
<section class="section">
|
|
1055
|
+
<div class="section-title"><div><div class="section-kicker">Consumption</div><h2>Token usage by model</h2><p>Input, output and request volume for the selected cohort.</p></div></div>
|
|
1056
|
+
<div id="tokTable"></div>
|
|
1057
|
+
</section>
|
|
1058
|
+
<div class="charts">
|
|
1059
|
+
<div class="chart-box"><h2>Versions</h2><canvas id="cVersions"></canvas></div><div class="chart-box"><h2>Operating systems</h2><canvas id="cOS"></canvas></div><div class="chart-box"><h2>Active models</h2><canvas id="cModels"></canvas></div><div class="chart-box"><h2>Routing health</h2><canvas id="cHealth"></canvas></div><div class="chart-box"><h2>Features used</h2><canvas id="cFeatures"></canvas></div>
|
|
1060
|
+
</div>
|
|
1061
|
+
</div>
|
|
1062
|
+
</div>
|
|
1063
|
+
</div>
|
|
1064
|
+
|
|
1065
|
+
<script>
|
|
1066
|
+
const C=['#63b3ed','#68d391','#f6e05e','#b794f4','#fc8181','#fbd38d','#76e4f7','#a3bffa'];
|
|
1067
|
+
const R=['#fc8181','#f6ad55','#faf089','#b794f4','#feb2b2'];
|
|
1068
|
+
const charts={};
|
|
1069
|
+
let _token='';
|
|
1070
|
+
let _filterOptions={};
|
|
1071
|
+
|
|
1072
|
+
function $(i){return document.getElementById(i)}
|
|
1073
|
+
function fmt(n){return n==null?'—':Number(n).toLocaleString()}
|
|
1074
|
+
function usd(n){return '$'+Number(n||0).toFixed(2)}
|
|
1075
|
+
function esc(s){
|
|
1076
|
+
return String(s==null?'':s)
|
|
1077
|
+
.replace(/&/g,'&')
|
|
1078
|
+
.replace(/</g,'<')
|
|
1079
|
+
.replace(/>/g,'>')
|
|
1080
|
+
.replace(/"/g,'"')
|
|
1081
|
+
.replace(/'/g,''');
|
|
1082
|
+
}
|
|
1083
|
+
function jsString(s){
|
|
1084
|
+
return esc(String(s==null?'':s)
|
|
1085
|
+
.replace(/\\\\/g,'\\\\\\\\')
|
|
1086
|
+
.replace(/'/g,"\\\\'")
|
|
1087
|
+
.replace(/\\r/g,'\\\\r')
|
|
1088
|
+
.replace(/\\n/g,'\\\\n'));
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
function mkChart(id,type,labels,datasets){
|
|
1092
|
+
if(charts[id])charts[id].destroy();
|
|
1093
|
+
const ctx=$(id)?.getContext('2d');if(!ctx)return;
|
|
1094
|
+
charts[id]=new Chart(ctx,{type,data:{labels,datasets},options:{
|
|
1095
|
+
responsive:true,maintainAspectRatio:true,
|
|
1096
|
+
plugins:{legend:{labels:{color:'#a0aec0',font:{size:11}}}},
|
|
1097
|
+
scales:type==='bar'?{x:{ticks:{color:'#718096'},grid:{color:'#2d3748'}},y:{ticks:{color:'#718096'},grid:{color:'#2d3748'}}}:undefined
|
|
1098
|
+
}});
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
function setDashboardConnection(state, label) {
|
|
1102
|
+
var el = $('dashboardConnection');
|
|
1103
|
+
if (!el) return;
|
|
1104
|
+
el.className = 'connection' + (state ? ' ' + state : '');
|
|
1105
|
+
$('dashboardConnectionLabel').textContent = label;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
async function load(event){
|
|
1109
|
+
if(event)event.preventDefault();
|
|
1110
|
+
const t=$('tok').value.trim();
|
|
1111
|
+
if(!t)return;
|
|
1112
|
+
_token=t;
|
|
1113
|
+
localStorage.setItem('st',t);
|
|
1114
|
+
setDashboardConnection('connecting','Connecting...');
|
|
1115
|
+
$('loadBtn').disabled=true;
|
|
1116
|
+
try { await go({}); }
|
|
1117
|
+
finally { $('loadBtn').disabled=false; }
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
function buildParams(f){
|
|
1121
|
+
const p=new URLSearchParams();
|
|
1122
|
+
if(f.installId)p.set('installId',f.installId);
|
|
1123
|
+
if(f.version)p.set('version',f.version);
|
|
1124
|
+
if(f.os)p.set('os',f.os);
|
|
1125
|
+
if(f.model)p.set('model',f.model);
|
|
1126
|
+
if(f.from)p.set('from',f.from);
|
|
1127
|
+
if(f.to)p.set('to',f.to);
|
|
1128
|
+
return p.toString();
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
async function go(filters){
|
|
1132
|
+
const qs=buildParams(filters);
|
|
1133
|
+
const url='/v1/stats'+(qs?'?'+qs:'');
|
|
1134
|
+
const refreshButton=$('refreshBtn');
|
|
1135
|
+
if(refreshButton)refreshButton.disabled=true;
|
|
1136
|
+
try{
|
|
1137
|
+
const r=await fetch(url,{headers:{'Authorization':'Bearer '+_token}});
|
|
1138
|
+
if(r.status===401){$('app').style.display='none';$('viewTabs').style.display='none';$('filterBar').style.display='none';var unauthorizedList=$('installsView');if(unauthorizedList)unauthorizedList.style.display='none';setDashboardConnection('error','Invalid token');showErr('Invalid token');return false}
|
|
1139
|
+
if(!r.ok){setDashboardConnection('error','Request failed');showErr('Server error '+r.status);return false}
|
|
1140
|
+
const d=await r.json();
|
|
1141
|
+
$('err').style.display='none';
|
|
1142
|
+
$('viewTabs').style.display='flex';
|
|
1143
|
+
var listView=$('installsView');
|
|
1144
|
+
if(CURRENT_VIEW==='list'&&listView){$('app').style.display='none';$('filterBar').style.display='none';listView.style.display='block';}
|
|
1145
|
+
else{$('app').style.display='block';$('filterBar').style.display='flex';if(listView)listView.style.display='none';}
|
|
1146
|
+
$('ts').textContent='Updated '+new Date().toLocaleTimeString();
|
|
1147
|
+
setDashboardConnection('connected','Connected');
|
|
1148
|
+
render(d,filters);
|
|
1149
|
+
return true;
|
|
1150
|
+
}catch(e){setDashboardConnection('error','Request failed');showErr(e.message);return false;}
|
|
1151
|
+
finally{if(refreshButton)refreshButton.disabled=false;}
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
function showErr(msg){$('err').textContent='Error: '+msg;$('err').style.display='';}
|
|
1155
|
+
|
|
1156
|
+
function currentFilters(){
|
|
1157
|
+
const f={};
|
|
1158
|
+
const i=$('fInstall').value;if(i)f.installId=i;
|
|
1159
|
+
const v=$('fVersion').value;if(v)f.version=v;
|
|
1160
|
+
const o=$('fOS').value;if(o)f.os=o;
|
|
1161
|
+
const m=$('fModel').value;if(m)f.model=m;
|
|
1162
|
+
const fr=$('fFrom').value;if(fr)f.from=fr;
|
|
1163
|
+
const to=$('fTo').value;if(to)f.to=to;
|
|
1164
|
+
return f;
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
function refreshDashboard(){go(currentFilters());}
|
|
1168
|
+
|
|
1169
|
+
function applyFilters(){
|
|
1170
|
+
const f=currentFilters();
|
|
1171
|
+
const hasFilters=Object.keys(f).length>0;
|
|
1172
|
+
const fa=$('filterActive');
|
|
1173
|
+
if(hasFilters){fa.classList.add('show');fa.textContent='Filtered: '+Object.entries(f).map(([k,v])=>k+'='+v).join(', ');}
|
|
1174
|
+
else{fa.classList.remove('show');}
|
|
1175
|
+
go(f);
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
function clearFilters(){
|
|
1179
|
+
$('fInstall').value='';
|
|
1180
|
+
$('fVersion').value='';
|
|
1181
|
+
$('fOS').value='';
|
|
1182
|
+
$('fModel').value='';
|
|
1183
|
+
$('fFrom').value='';
|
|
1184
|
+
$('fTo').value='';
|
|
1185
|
+
$('filterActive').classList.remove('show');
|
|
1186
|
+
go({});
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
function populateDropdowns(opts){
|
|
1190
|
+
_filterOptions=opts;
|
|
1191
|
+
const cur={install:$('fInstall').value,ver:$('fVersion').value,os:$('fOS').value,model:$('fModel').value};
|
|
1192
|
+
fillSelect('fInstall',opts.installIds,'All installs',cur.install);
|
|
1193
|
+
fillSelect('fVersion',opts.versions,'All versions',cur.ver);
|
|
1194
|
+
fillSelect('fOS',opts.os,'All OS',cur.os);
|
|
1195
|
+
fillSelect('fModel',opts.models,'All models',cur.model);
|
|
1196
|
+
if(opts.dateRange?.from&&!$('fFrom').value)$('fFrom').value=opts.dateRange.from;
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
function fillSelect(id,items,placeholder,selected){
|
|
1200
|
+
const el=$(id);
|
|
1201
|
+
el.innerHTML='<option value="">'+placeholder+'</option>';
|
|
1202
|
+
for(const it of items){
|
|
1203
|
+
const o=document.createElement('option');
|
|
1204
|
+
o.value=it;o.textContent=it;
|
|
1205
|
+
if(it===selected)o.selected=true;
|
|
1206
|
+
el.appendChild(o);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
function render(d, filters={}){
|
|
1211
|
+
if(d.filterOptions)populateDropdowns(d.filterOptions);
|
|
1212
|
+
|
|
1213
|
+
$('kpis').innerHTML=[
|
|
1214
|
+
{l:'Unique Installs',v:fmt(d.uniqueInstalls),c:'green'},
|
|
1215
|
+
{l:'Total Events',v:fmt(d.totalEvents),c:'blue'},
|
|
1216
|
+
{l:'Boots',v:fmt(d.totalBoots),c:'blue'},
|
|
1217
|
+
{l:'Avg Accounts',v:d.avgAccountsPerEvent,c:''},
|
|
1218
|
+
{l:'Total Requests',v:fmt(d.totalRequestsAcrossAll),c:'yellow'},
|
|
1219
|
+
{l:'Flag Events',v:fmt(d.flags?.totalFlags||0),c:'red'},
|
|
1220
|
+
{l:'Unique Flag Incidents',v:fmt(d.flags?.uniqueIncidents||0),c:'red'},
|
|
1221
|
+
{l:'Avg Req/Flag',v:fmt(d.flags?.avgRequestsBeforeFlag||0),c:'red'},
|
|
1222
|
+
{l:'Period',v:d.period?.from||'—',sub:d.period?.to?'→ '+d.period.to:''},
|
|
1223
|
+
].map(k=>'<div class="kpi '+esc(k.c)+'"><div class="label">'+esc(k.l)+'</div><div class="value">'+esc(k.v)+'</div>'+(k.sub?'<div class="sub">'+esc(k.sub)+'</div>':'')+'</div>').join('');
|
|
1224
|
+
|
|
1225
|
+
const sv=d.savings||{};
|
|
1226
|
+
$('savTotal').textContent=usd(sv.totalUsd);
|
|
1227
|
+
const svRows=Object.entries(sv.byModel||{}).map(([m,v])=>'<tr><td class="mono">'+esc(m)+'</td><td>'+usd(v.inputUsd)+'</td><td>'+usd(v.outputUsd)+'</td><td><strong>'+usd(v.totalUsd)+'</strong></td></tr>').join('');
|
|
1228
|
+
$('savTable').innerHTML=svRows?'<table><thead><tr><th>Model</th><th>Input</th><th>Output</th><th>Total</th></tr></thead><tbody>'+svRows+'</tbody></table>':'<div class="empty">No data yet</div>';
|
|
1229
|
+
|
|
1230
|
+
const fl=d.flags||{};
|
|
1231
|
+
$('flagKpis').innerHTML=[
|
|
1232
|
+
{l:'Total Flags',v:fmt(fl.totalFlags||0)},
|
|
1233
|
+
{l:'On Pro Accounts',v:fmt(fl.onProAccounts||0)},
|
|
1234
|
+
{l:'On Free Accounts',v:fmt(fl.onFreeAccounts||0)},
|
|
1235
|
+
{l:'Avg Requests Before Flag',v:fmt(fl.avgRequestsBeforeFlag||0)},
|
|
1236
|
+
].map(k=>'<div class="flag-kpi"><div class="label">'+esc(k.l)+'</div><div class="value">'+esc(k.v)+'</div></div>').join('');
|
|
1237
|
+
mkChart('cPatterns','bar',Object.keys(fl.byPattern||{}),[{label:'Count',data:Object.values(fl.byPattern||{}),backgroundColor:R}]);
|
|
1238
|
+
mkChart('cFlagModels','doughnut',Object.keys(fl.byModel||{}),[{data:Object.values(fl.byModel||{}),backgroundColor:C}]);
|
|
1239
|
+
mkChart('cTimerType','doughnut',Object.keys(fl.byTimerType||{}),[{data:Object.values(fl.byTimerType||{}),backgroundColor:['#63b3ed','#f6e05e','#68d391']}]);
|
|
1240
|
+
|
|
1241
|
+
const tk=d.tokensByModel||{};
|
|
1242
|
+
$('tokTable').innerHTML=Object.keys(tk).length?'<table><thead><tr><th>Model</th><th>Input Tokens</th><th>Output Tokens</th><th>Requests</th></tr></thead><tbody>'+Object.entries(tk).map(([m,v])=>'<tr><td class="mono">'+esc(m)+'</td><td>'+fmt(v.input)+'</td><td>'+fmt(v.output)+'</td><td>'+fmt(v.requests)+'</td></tr>').join('')+'</tbody></table>':'<div class="empty">No token data yet</div>';
|
|
1243
|
+
|
|
1244
|
+
mkChart('cVersions','bar',Object.keys(d.versions||{}),[{label:'Events',data:Object.values(d.versions||{}),backgroundColor:'#63b3ed'}]);
|
|
1245
|
+
mkChart('cOS','doughnut',Object.keys(d.os||{}),[{data:Object.values(d.os||{}),backgroundColor:C}]);
|
|
1246
|
+
mkChart('cModels','doughnut',Object.keys(d.modelsUsed||{}),[{data:Object.values(d.modelsUsed||{}),backgroundColor:C}]);
|
|
1247
|
+
mkChart('cHealth','doughnut',Object.keys(d.routingHealth||{}),[{data:Object.values(d.routingHealth||{}),backgroundColor:['#68d391','#f6e05e','#fc8181','#718096']}]);
|
|
1248
|
+
mkChart('cFeatures','bar',Object.keys(d.featuresUsed||{}),[{label:'Times used',data:Object.values(d.featuresUsed||{}),backgroundColor:'#b794f4'}]);
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
const saved=localStorage.getItem('st');
|
|
1252
|
+
if(saved){_token=saved;$('tok').value=saved;setDashboardConnection('connecting','Connecting...');go({});}
|
|
1253
|
+
|
|
1254
|
+
// ── Installs list view ───────────────────────────────────────────────
|
|
1255
|
+
var CURRENT_VIEW = 'agg';
|
|
1256
|
+
var INSTALL_SORT = 'requests';
|
|
1257
|
+
var INSTALL_SORT_DIR = -1;
|
|
1258
|
+
var _installs = [];
|
|
1259
|
+
|
|
1260
|
+
function switchView(view) {
|
|
1261
|
+
CURRENT_VIEW = view;
|
|
1262
|
+
$('vtAgg').className = 'view-tab' + (view === 'agg' ? ' active' : '');
|
|
1263
|
+
$('vtList').className = 'view-tab' + (view === 'list' ? ' active' : '');
|
|
1264
|
+
$('filterBar').style.display = view === 'agg' ? 'flex' : 'none';
|
|
1265
|
+
var ae = $('app'); if(ae) ae.style.display = view === 'agg' ? 'block' : 'none';
|
|
1266
|
+
var le = $('installsView'); if(le) le.style.display = view === 'list' ? 'block' : 'none';
|
|
1267
|
+
if (view === 'list') loadInstalls();
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
async function loadInstalls() {
|
|
1271
|
+
if (!_token) return;
|
|
1272
|
+
try {
|
|
1273
|
+
var r = await fetch('/v1/installs', { headers: { 'Authorization': 'Bearer ' + _token } });
|
|
1274
|
+
if (!r.ok) { showErr('Failed to load installs: ' + r.status); return; }
|
|
1275
|
+
_installs = await r.json();
|
|
1276
|
+
$('installCount').textContent = _installs.length + (_installs.length === 1 ? ' install' : ' installs');
|
|
1277
|
+
renderInstallList();
|
|
1278
|
+
} catch(e) { showErr(e.message); }
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
function setInstallSort(col) {
|
|
1282
|
+
if (INSTALL_SORT === col) { INSTALL_SORT_DIR = -INSTALL_SORT_DIR; }
|
|
1283
|
+
else { INSTALL_SORT = col; INSTALL_SORT_DIR = -1; }
|
|
1284
|
+
['requests','savings','accounts','flags','lastseen'].forEach(function(c) {
|
|
1285
|
+
var b = $('isort-' + c);
|
|
1286
|
+
if (b) b.className = 'sort-btn' + (c === INSTALL_SORT ? ' active' : '');
|
|
1287
|
+
});
|
|
1288
|
+
renderInstallList();
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
function renderInstallList() {
|
|
1292
|
+
var wrap = $('installTableWrap');
|
|
1293
|
+
if (!wrap) return;
|
|
1294
|
+
var q = (($('installSearch')||{}).value||'').toLowerCase();
|
|
1295
|
+
var rows = _installs.slice().filter(function(r) {
|
|
1296
|
+
if (!q) return true;
|
|
1297
|
+
return r.installId.toLowerCase().indexOf(q)!==-1 ||
|
|
1298
|
+
(r.version||'').toLowerCase().indexOf(q)!==-1 ||
|
|
1299
|
+
(r.os||'').toLowerCase().indexOf(q)!==-1;
|
|
1300
|
+
});
|
|
1301
|
+
rows.sort(function(a,b) {
|
|
1302
|
+
var av,bv;
|
|
1303
|
+
if (INSTALL_SORT==='requests') {av=a.totalRequests;bv=b.totalRequests;}
|
|
1304
|
+
else if (INSTALL_SORT==='savings') {av=a.savingsUsd;bv=b.savingsUsd;}
|
|
1305
|
+
else if (INSTALL_SORT==='accounts') {av=a.accountCount;bv=b.accountCount;}
|
|
1306
|
+
else if (INSTALL_SORT==='flags') {av=a.flagEvents;bv=b.flagEvents;}
|
|
1307
|
+
else if (INSTALL_SORT==='lastseen') {av=a.lastSeen;bv=b.lastSeen;}
|
|
1308
|
+
else {av=0;bv=0;}
|
|
1309
|
+
if(av<bv) return INSTALL_SORT_DIR;
|
|
1310
|
+
if(av>bv) return -INSTALL_SORT_DIR;
|
|
1311
|
+
return 0;
|
|
1312
|
+
});
|
|
1313
|
+
if (rows.length===0) { wrap.innerHTML='<div class="empty">No installs found.</div>'; return; }
|
|
1314
|
+
var HC={healthy:'#68d391',cooldown_wait:'#f6e05e',busy:'#63b3ed',paused:'#fc8181',stopped:'#fc8181'};
|
|
1315
|
+
function ar(col) {
|
|
1316
|
+
if(INSTALL_SORT!==col) return '<span class="arr">↕</span>';
|
|
1317
|
+
return '<span class="arr">'+(INSTALL_SORT_DIR===-1?'↓':'↑')+'</span>';
|
|
1318
|
+
}
|
|
1319
|
+
var html='<table class="install-table"><thead><tr>'+
|
|
1320
|
+
'<th>Install ID</th>'+
|
|
1321
|
+
'<th onclick="setInstallSort('requests')" class="'+(INSTALL_SORT==='requests'?'sort-active':'')+'">Requests'+ar('requests')+'</th>'+
|
|
1322
|
+
'<th onclick="setInstallSort('accounts')" class="'+(INSTALL_SORT==='accounts'?'sort-active':'')+'">Accounts'+ar('accounts')+'</th>'+
|
|
1323
|
+
'<th onclick="setInstallSort('savings')" class="'+(INSTALL_SORT==='savings' ?'sort-active':'')+'">Savings' +ar('savings') +'</th>'+
|
|
1324
|
+
'<th onclick="setInstallSort('flags')" class="'+(INSTALL_SORT==='flags' ?'sort-active':'')+'">Flags' +ar('flags') +'</th>'+
|
|
1325
|
+
'<th>Health</th>'+
|
|
1326
|
+
'<th>Version / OS</th>'+
|
|
1327
|
+
'<th onclick="setInstallSort('lastseen')" class="'+(INSTALL_SORT==='lastseen'?'sort-active':'')+'">Last Seen'+ar('lastseen')+'</th>'+
|
|
1328
|
+
'<th></th>'+
|
|
1329
|
+
'</tr></thead><tbody>';
|
|
1330
|
+
rows.forEach(function(r) {
|
|
1331
|
+
var hc=HC[r.routingHealthState]||'#718096';
|
|
1332
|
+
var shortId=esc(r.installId.slice(0,8)+'…');
|
|
1333
|
+
var ls=r.lastSeen?new Date(r.lastSeen).toLocaleString():'—';
|
|
1334
|
+
var fc=r.flagEvents>0?'#fc8181':'#718096';
|
|
1335
|
+
var pf='';
|
|
1336
|
+
if(r.proCount>0||r.freeCount>0)
|
|
1337
|
+
pf='<span style="color:#68d391;font-size:10px">P:'+r.proCount+'</span> <span style="color:#718096;font-size:10px">F:'+r.freeCount+'</span>';
|
|
1338
|
+
html+='<tr class="install-row" onclick="drillDown(''+jsString(r.installId)+'')">'+
|
|
1339
|
+
'<td><div class="install-id"><strong>'+shortId+'</strong>'+esc(r.installId.slice(8))+'</div></td>'+
|
|
1340
|
+
'<td style="font-family:monospace;font-weight:700">'+fmt(r.totalRequests)+'</td>'+
|
|
1341
|
+
'<td>'+esc(r.accountCount)+(pf?'<br>'+pf:'')+'</td>'+
|
|
1342
|
+
'<td style="color:#68d391;font-family:monospace;font-weight:700">'+usd(r.savingsUsd)+'</td>'+
|
|
1343
|
+
'<td style="color:'+fc+';font-weight:700;font-family:monospace">'+esc(r.flagEvents)+'</td>'+
|
|
1344
|
+
'<td><span class="health-dot" style="background:'+hc+'"></span><span style="font-size:11px;color:'+hc+'">'+escI(r.routingHealthState||'?')+'</span></td>'+
|
|
1345
|
+
'<td style="font-size:11px"><span style="color:#63b3ed">v'+escI(r.version)+'</span> <span style="color:#718096">'+escI(r.os)+'/'+escI(r.arch)+'</span></td>'+
|
|
1346
|
+
'<td style="font-size:11px;color:#718096;font-family:monospace">'+esc(ls)+'</td>'+
|
|
1347
|
+
'<td><button class="sort-btn" style="padding:3px 8px;font-size:10px" onclick="event.stopPropagation();drillDown(''+jsString(r.installId)+'')">Filter →</button></td>'+
|
|
1348
|
+
'</tr>';
|
|
1349
|
+
});
|
|
1350
|
+
html+='</tbody></table>';
|
|
1351
|
+
wrap.innerHTML=html;
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
function drillDown(installId) {
|
|
1355
|
+
switchView('agg');
|
|
1356
|
+
var sel=$('fInstall');
|
|
1357
|
+
if(sel) { sel.value=installId; }
|
|
1358
|
+
applyFilters();
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
function escI(s){if(!s)return '';return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}
|
|
1362
|
+
|
|
1363
|
+
setInterval(()=>{if(_token&&CURRENT_VIEW==='agg')go(currentFilters());},60000);
|
|
1364
|
+
</script>
|
|
1365
|
+
<div class="dashboard-shell" id="installsView" style="display:none">
|
|
1366
|
+
<div class="install-list-panel">
|
|
1367
|
+
<div class="install-heading"><div><div class="section-kicker">Fleet / Installations</div><h2>Connected installations</h2><p>Inspect routing health, usage and recent activity. Select a row to drill into its aggregate view.</p></div><span class="install-count" id="installCount">0 installs</span></div>
|
|
1368
|
+
<div class="install-toolbar">
|
|
1369
|
+
<label><span class="sr-only">Search installations</span><input class="install-search" id="installSearch" placeholder="Search installations..." oninput="renderInstallList()" /></label>
|
|
1370
|
+
<button class="sort-btn" id="isort-requests" type="button" onclick="setInstallSort('requests')">Requests</button>
|
|
1371
|
+
<button class="sort-btn" id="isort-savings" type="button" onclick="setInstallSort('savings')">Savings</button>
|
|
1372
|
+
<button class="sort-btn" id="isort-accounts" type="button" onclick="setInstallSort('accounts')">Accounts</button>
|
|
1373
|
+
<button class="sort-btn" id="isort-flags" type="button" onclick="setInstallSort('flags')">Flags</button>
|
|
1374
|
+
<button class="sort-btn" id="isort-lastseen" type="button" onclick="setInstallSort('lastseen')">Last seen</button>
|
|
1375
|
+
</div>
|
|
1376
|
+
<div id="installTableWrap"></div>
|
|
1377
|
+
</div>
|
|
1378
|
+
</div>
|
|
1379
|
+
</body></html>`;
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
// ── Notifications Admin UI ───────────────────────────────────────────
|
|
1383
|
+
function buildNotificationsAdminHtml() {
|
|
1384
|
+
return `<!DOCTYPE html>
|
|
1385
|
+
<html lang="en">
|
|
1386
|
+
<head>
|
|
1387
|
+
<meta charset="UTF-8">
|
|
1388
|
+
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
|
1389
|
+
<title>Tuxevil Rotator — Notification Manager</title>
|
|
1390
|
+
<style>
|
|
1391
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
1392
|
+
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#0f1117;color:#e2e8f0;min-height:100vh}
|
|
1393
|
+
.header{background:#1a1f2e;border-bottom:1px solid #2d3748;padding:14px 24px;display:flex;align-items:center;gap:12px}
|
|
1394
|
+
.header h1{font-size:17px;font-weight:700;color:#fff}
|
|
1395
|
+
.header .nav{margin-left:auto;display:flex;gap:10px;align-items:center}
|
|
1396
|
+
.header .nav a{color:#718096;font-size:13px;text-decoration:none;padding:4px 10px;border-radius:6px;transition:color .2s,background .2s}
|
|
1397
|
+
.header .nav a:hover{color:#e2e8f0;background:rgba(255,255,255,.06)}
|
|
1398
|
+
.token-bar{background:#1a1f2e;border-bottom:1px solid #2d3748;padding:10px 24px;display:flex;gap:8px;align-items:center}
|
|
1399
|
+
.token-bar input[type=password]{flex:1;background:#0f1117;border:1px solid #2d3748;border-radius:6px;padding:7px 12px;color:#e2e8f0;font-size:13px;font-family:monospace}
|
|
1400
|
+
.token-bar input[type=password]:focus{outline:none;border-color:#4299e1}
|
|
1401
|
+
.token-bar button{background:#4299e1;color:#fff;border:none;border-radius:6px;padding:7px 16px;cursor:pointer;font-size:13px;font-weight:600;white-space:nowrap}
|
|
1402
|
+
.token-bar button:hover{background:#3182ce}
|
|
1403
|
+
.main{padding:20px 24px;max-width:1100px;margin:0 auto}
|
|
1404
|
+
.section{background:#1a1f2e;border:1px solid #2d3748;border-radius:10px;padding:18px;margin-bottom:14px}
|
|
1405
|
+
.section h2{font-size:11px;font-weight:700;color:#718096;text-transform:uppercase;letter-spacing:.08em;margin-bottom:14px}
|
|
1406
|
+
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
|
|
1407
|
+
.form-group{display:flex;flex-direction:column;gap:4px}
|
|
1408
|
+
.form-group.full{grid-column:1/-1}
|
|
1409
|
+
.form-group label{font-size:11px;color:#718096;text-transform:uppercase;letter-spacing:.05em;font-weight:600}
|
|
1410
|
+
.form-group input,.form-group textarea,.form-group select{background:#0f1117;border:1px solid #2d3748;border-radius:6px;padding:8px 12px;color:#e2e8f0;font-size:13px;font-family:inherit}
|
|
1411
|
+
.form-group input:focus,.form-group textarea:focus,.form-group select:focus{outline:none;border-color:#4299e1}
|
|
1412
|
+
.form-group textarea{min-height:80px;resize:vertical}
|
|
1413
|
+
.form-actions{display:flex;gap:8px;margin-top:14px;grid-column:1/-1}
|
|
1414
|
+
.btn-primary{background:#4299e1;color:#fff;border:none;border-radius:6px;padding:8px 20px;cursor:pointer;font-size:13px;font-weight:600}
|
|
1415
|
+
.btn-primary:hover{background:#3182ce}
|
|
1416
|
+
.btn-primary:disabled{opacity:.5;cursor:not-allowed}
|
|
1417
|
+
.btn-secondary{background:#2d3748;color:#a0aec0;border:none;border-radius:6px;padding:8px 16px;cursor:pointer;font-size:13px}
|
|
1418
|
+
.btn-secondary:hover{background:#3d4a5e}
|
|
1419
|
+
.btn-danger{background:rgba(248,113,113,.15);color:#fc8181;border:1px solid rgba(248,113,113,.3);border-radius:6px;padding:4px 10px;cursor:pointer;font-size:11px;font-weight:600}
|
|
1420
|
+
.btn-danger:hover{background:rgba(248,113,113,.25)}
|
|
1421
|
+
.btn-edit{background:rgba(66,153,225,.12);color:#63b3ed;border:1px solid rgba(66,153,225,.3);border-radius:6px;padding:4px 10px;cursor:pointer;font-size:11px;font-weight:600}
|
|
1422
|
+
.btn-edit:hover{background:rgba(66,153,225,.22)}
|
|
1423
|
+
|
|
1424
|
+
table{width:100%;border-collapse:collapse;font-size:12px}
|
|
1425
|
+
th{text-align:left;padding:7px 12px;color:#718096;border-bottom:1px solid #2d3748;font-weight:500;white-space:nowrap}
|
|
1426
|
+
td{padding:7px 12px;border-bottom:1px solid #1f2535;color:#e2e8f0;vertical-align:top}
|
|
1427
|
+
tr:last-child td{border-bottom:none}
|
|
1428
|
+
.mono{font-family:monospace;color:#68d391;font-size:11px}
|
|
1429
|
+
.type-badge{display:inline-block;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em}
|
|
1430
|
+
.type-info{background:rgba(66,153,225,.15);color:#63b3ed}
|
|
1431
|
+
.type-warning{background:rgba(251,191,36,.15);color:#fbbf24}
|
|
1432
|
+
.type-critical{background:rgba(248,113,113,.15);color:#fc8181}
|
|
1433
|
+
.status-active{color:#68d391;font-weight:600;font-size:11px}
|
|
1434
|
+
.status-expired{color:#718096;font-style:italic;font-size:11px}
|
|
1435
|
+
.empty{color:#4a5568;font-size:12px;padding:20px;text-align:center}
|
|
1436
|
+
.error{background:#2d1515;border:1px solid #742a2a;border-radius:8px;padding:12px;color:#fc8181;margin-bottom:14px}
|
|
1437
|
+
.success{background:#1c2d1c;border:1px solid #276749;border-radius:8px;padding:12px;color:#68d391;margin-bottom:14px}
|
|
1438
|
+
|
|
1439
|
+
.preview{margin-top:14px;grid-column:1/-1}
|
|
1440
|
+
.preview-label{font-size:10px;color:#718096;text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px;font-weight:700}
|
|
1441
|
+
.preview-card{border-radius:10px;padding:14px 18px;display:flex;align-items:center;gap:12px}
|
|
1442
|
+
.preview-card.p-info{background:linear-gradient(135deg,rgba(66,153,225,.12),rgba(99,179,237,.08));border:1px solid rgba(66,153,225,.35)}
|
|
1443
|
+
.preview-card.p-warning{background:linear-gradient(135deg,rgba(251,191,36,.12),rgba(246,224,94,.08));border:1px solid rgba(251,191,36,.35)}
|
|
1444
|
+
.preview-card.p-critical{background:linear-gradient(135deg,rgba(248,113,113,.12),rgba(252,129,129,.08));border:1px solid rgba(248,113,113,.35)}
|
|
1445
|
+
.preview-icon{font-size:22px;flex-shrink:0}
|
|
1446
|
+
.preview-content{flex:1;min-width:0}
|
|
1447
|
+
.preview-title{font-weight:700;font-size:14px;margin-bottom:3px}
|
|
1448
|
+
.preview-msg{font-size:12px;color:#a0aec0;line-height:1.4}
|
|
1449
|
+
.preview-btn{display:inline-block;margin-top:6px;padding:4px 12px;border-radius:6px;font-size:11px;font-weight:600;text-decoration:none;border:1px solid rgba(255,255,255,.15);color:#e2e8f0;background:rgba(255,255,255,.06)}
|
|
1450
|
+
.p-info .preview-title{color:#63b3ed}
|
|
1451
|
+
.p-warning .preview-title{color:#fbbf24}
|
|
1452
|
+
.p-critical .preview-title{color:#fc8181}
|
|
1453
|
+
.version-hint{font-size:10px;color:#4a5568;margin-top:2px}
|
|
1454
|
+
@media(max-width:700px){.form-grid{grid-template-columns:1fr}}
|
|
1455
|
+
</style>
|
|
1456
|
+
<style>
|
|
1457
|
+
:root{color-scheme:dark;--bg:#0b0f17;--panel:#141b29;--panel-2:#192235;--line:#29364b;--muted:#7d8ca5;--text:#e8eef8;--blue:#78b7ff;--green:#72dfa0;--yellow:#f6d365;--red:#ff8b8b}
|
|
1458
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
1459
|
+
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:radial-gradient(circle at 20% -10%,#1c304b 0,#0f1117 38rem);color:var(--text);min-height:100vh}
|
|
1460
|
+
button,input,textarea,select{font:inherit}
|
|
1461
|
+
button{border:0}
|
|
1462
|
+
button:focus-visible,a:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:2px solid var(--blue);outline-offset:2px}
|
|
1463
|
+
a{color:inherit}
|
|
1464
|
+
.topbar{border-bottom:1px solid rgba(125,140,165,.18);background:rgba(11,15,23,.72);backdrop-filter:blur(14px)}
|
|
1465
|
+
.topbar-inner{max-width:1240px;margin:0 auto;padding:17px 28px;display:flex;align-items:center;gap:24px}
|
|
1466
|
+
.brand{display:flex;align-items:center;gap:11px;text-decoration:none;min-width:0}
|
|
1467
|
+
.brand-mark{width:31px;height:31px;border-radius:10px;background:linear-gradient(135deg,#78b7ff,#8b7dff);box-shadow:0 0 24px rgba(120,183,255,.25);position:relative;flex-shrink:0}
|
|
1468
|
+
.brand-mark:after{content:'';position:absolute;width:9px;height:9px;border-radius:50%;background:#fff;left:11px;top:11px;box-shadow:0 0 0 4px rgba(255,255,255,.2)}
|
|
1469
|
+
.brand strong{display:block;color:#fff;font-size:14px;letter-spacing:.01em}
|
|
1470
|
+
.brand small{display:block;color:var(--muted);font-size:10px;letter-spacing:.08em;text-transform:uppercase;margin-top:2px}
|
|
1471
|
+
.nav{margin-left:auto;display:flex;align-items:center;gap:7px}
|
|
1472
|
+
.nav a,.nav-lock{color:var(--muted);font-size:12px;text-decoration:none;padding:7px 10px;border-radius:7px;transition:color .2s,background .2s}
|
|
1473
|
+
.nav a:hover{color:#fff;background:rgba(255,255,255,.07)}
|
|
1474
|
+
.nav-lock{color:var(--green);background:rgba(114,223,160,.08);font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase}
|
|
1475
|
+
.auth-strip{border-bottom:1px solid rgba(125,140,165,.18);background:rgba(20,27,41,.76)}
|
|
1476
|
+
.auth-inner{max-width:1240px;margin:0 auto;padding:18px 28px;display:flex;align-items:center;justify-content:space-between;gap:24px}
|
|
1477
|
+
.auth-kicker,.eyebrow,.section-kicker{color:var(--blue);font-size:10px;font-weight:800;letter-spacing:.14em;text-transform:uppercase}
|
|
1478
|
+
.auth-title{color:#fff;font-size:16px;font-weight:700;margin-top:4px}
|
|
1479
|
+
.auth-note{color:var(--muted);font-size:12px;margin-top:3px}
|
|
1480
|
+
.auth-controls{display:flex;align-items:center;gap:12px;min-width:min(100%,500px)}
|
|
1481
|
+
.connection{display:flex;align-items:center;gap:7px;white-space:nowrap;color:var(--muted);font-size:11px;font-weight:600}
|
|
1482
|
+
.connection-dot{width:8px;height:8px;border-radius:50%;background:#59677d;box-shadow:0 0 0 4px rgba(89,103,125,.12)}
|
|
1483
|
+
.connection.connected{color:var(--green)}
|
|
1484
|
+
.connection.connected .connection-dot{background:var(--green);box-shadow:0 0 0 4px rgba(114,223,160,.12)}
|
|
1485
|
+
.connection.connecting{color:var(--yellow)}
|
|
1486
|
+
.connection.connecting .connection-dot{background:var(--yellow);box-shadow:0 0 0 4px rgba(246,211,101,.12);animation:pulse 1.2s ease-in-out infinite}
|
|
1487
|
+
.connection.error{color:var(--red)}
|
|
1488
|
+
.connection.error .connection-dot{background:var(--red);box-shadow:0 0 0 4px rgba(255,139,139,.12)}
|
|
1489
|
+
.token-form{display:flex;gap:8px;flex:1}
|
|
1490
|
+
.token-form input{width:100%;min-width:0;background:#0b1019;border:1px solid var(--line);border-radius:8px;padding:9px 12px;color:var(--text);font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
1491
|
+
.token-form input::placeholder{color:#56657c}
|
|
1492
|
+
.token-form input:focus{border-color:var(--blue);outline:none;box-shadow:0 0 0 3px rgba(120,183,255,.12)}
|
|
1493
|
+
.page{max-width:1240px;margin:0 auto;padding:38px 28px 64px}
|
|
1494
|
+
.hero{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;margin-bottom:25px}
|
|
1495
|
+
.hero h1{color:#fff;font-size:clamp(28px,4vw,43px);line-height:1.05;letter-spacing:-.045em;margin:10px 0}
|
|
1496
|
+
.hero p{max-width:630px;color:#91a0b7;font-size:14px;line-height:1.6}
|
|
1497
|
+
.hero-actions{display:flex;align-items:center;gap:12px;flex-shrink:0}
|
|
1498
|
+
.sync-note{color:var(--muted);font-size:11px;white-space:nowrap}
|
|
1499
|
+
.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:18px}
|
|
1500
|
+
.metric{position:relative;overflow:hidden;background:linear-gradient(145deg,rgba(25,34,53,.92),rgba(17,24,38,.92));border:1px solid var(--line);border-radius:13px;padding:17px 18px;min-height:105px}
|
|
1501
|
+
.metric:after{content:'';position:absolute;width:80px;height:80px;border-radius:50%;right:-32px;bottom:-40px;background:var(--metric-color,#78b7ff);opacity:.08;filter:blur(4px)}
|
|
1502
|
+
.metric-label{color:var(--muted);font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase}
|
|
1503
|
+
.metric-value{color:#fff;font-size:28px;font-weight:800;letter-spacing:-.04em;margin-top:11px}
|
|
1504
|
+
.metric-sub{color:#61718a;font-size:10px;margin-top:3px}
|
|
1505
|
+
.metric.blue{--metric-color:var(--blue)}.metric.green{--metric-color:var(--green)}.metric.yellow{--metric-color:var(--yellow)}.metric.red{--metric-color:var(--red)}
|
|
1506
|
+
.metric.blue .metric-value{color:var(--blue)}.metric.green .metric-value{color:var(--green)}.metric.yellow .metric-value{color:var(--yellow)}.metric.red .metric-value{color:var(--red)}
|
|
1507
|
+
.flash{border-radius:10px;padding:12px 14px;margin-bottom:16px;font-size:12px;line-height:1.4}
|
|
1508
|
+
.error{background:rgba(255,139,139,.1);border:1px solid rgba(255,139,139,.32);color:var(--red)}
|
|
1509
|
+
.success{background:rgba(114,223,160,.1);border:1px solid rgba(114,223,160,.3);color:var(--green)}
|
|
1510
|
+
.workspace{display:grid;grid-template-columns:minmax(0,1.18fr) minmax(320px,.82fr);gap:16px;align-items:start;margin-bottom:18px}
|
|
1511
|
+
.panel{background:rgba(20,27,41,.9);border:1px solid var(--line);border-radius:14px;box-shadow:0 18px 45px rgba(0,0,0,.12)}
|
|
1512
|
+
.compose-panel{padding:22px}
|
|
1513
|
+
.panel-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:20px}
|
|
1514
|
+
.panel-title{color:#fff;font-size:18px;letter-spacing:-.02em;margin-top:6px}
|
|
1515
|
+
.panel-description{color:var(--muted);font-size:12px;line-height:1.5;margin-top:5px}
|
|
1516
|
+
.mode-pill,.count-pill{display:inline-flex;align-items:center;justify-content:center;border:1px solid rgba(120,183,255,.28);border-radius:999px;padding:5px 9px;color:var(--blue);background:rgba(120,183,255,.09);font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;white-space:nowrap}
|
|
1517
|
+
.count-pill{padding:4px 8px;font-size:10px;color:var(--muted);background:rgba(125,140,165,.1);border-color:rgba(125,140,165,.2);letter-spacing:.02em;text-transform:none}
|
|
1518
|
+
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:17px 13px}
|
|
1519
|
+
.form-group{display:flex;flex-direction:column;gap:6px;min-width:0}
|
|
1520
|
+
.form-group.full{grid-column:1/-1}
|
|
1521
|
+
.form-group label{color:#a9b6c9;font-size:11px;font-weight:700;letter-spacing:.04em}
|
|
1522
|
+
.form-group input,.form-group textarea,.form-group select{width:100%;background:#0c121d;border:1px solid var(--line);border-radius:8px;padding:10px 12px;color:var(--text);font-size:13px;transition:border-color .2s,box-shadow .2s}
|
|
1523
|
+
.form-group input::placeholder,.form-group textarea::placeholder{color:#56657c}
|
|
1524
|
+
.form-group input:focus,.form-group textarea:focus,.form-group select:focus{border-color:var(--blue);outline:none;box-shadow:0 0 0 3px rgba(120,183,255,.1)}
|
|
1525
|
+
.form-group textarea{min-height:116px;resize:vertical;line-height:1.5}
|
|
1526
|
+
.field-meta{display:flex;justify-content:space-between;gap:12px;color:#5f7089;font-size:10px;margin-top:-1px}
|
|
1527
|
+
.form-divider{grid-column:1/-1;display:flex;align-items:center;gap:10px;color:#62728a;font-size:10px;font-weight:800;letter-spacing:.12em;text-transform:uppercase;margin:1px 0 -3px}
|
|
1528
|
+
.form-divider:after{content:'';height:1px;background:var(--line);flex:1}
|
|
1529
|
+
.form-actions{display:flex;align-items:center;gap:9px;margin-top:3px;grid-column:1/-1}
|
|
1530
|
+
.btn-primary,.btn-secondary,.btn-ghost,.btn-danger,.btn-edit{border-radius:8px;cursor:pointer;font-size:12px;font-weight:700;transition:background .2s,border-color .2s,color .2s,transform .2s}
|
|
1531
|
+
.btn-primary{background:var(--blue);color:#08111d;padding:10px 17px;box-shadow:0 8px 22px rgba(120,183,255,.16)}
|
|
1532
|
+
.btn-primary:hover{background:#9bcaff;transform:translateY(-1px)}
|
|
1533
|
+
.btn-primary:disabled{opacity:.5;cursor:not-allowed;transform:none}
|
|
1534
|
+
.btn-secondary{background:#26334a;color:#b5c3d6;padding:10px 15px}
|
|
1535
|
+
.btn-secondary:hover{background:#33435c;color:#fff}
|
|
1536
|
+
.btn-ghost{background:rgba(120,183,255,.08);border:1px solid rgba(120,183,255,.25);color:var(--blue);padding:8px 12px}
|
|
1537
|
+
.btn-ghost:hover{background:rgba(120,183,255,.15);border-color:rgba(120,183,255,.5)}
|
|
1538
|
+
.btn-danger{background:rgba(255,139,139,.08);border:1px solid rgba(255,139,139,.24);color:var(--red);padding:7px 10px}
|
|
1539
|
+
.btn-danger:hover{background:rgba(255,139,139,.17);border-color:rgba(255,139,139,.46)}
|
|
1540
|
+
.btn-edit{background:rgba(120,183,255,.08);border:1px solid rgba(120,183,255,.24);color:var(--blue);padding:7px 10px}
|
|
1541
|
+
.btn-edit:hover{background:rgba(120,183,255,.16);border-color:rgba(120,183,255,.46)}
|
|
1542
|
+
.preview-panel{position:sticky;top:18px;padding:22px}
|
|
1543
|
+
.preview-panel .panel-head{margin-bottom:16px}
|
|
1544
|
+
.preview-shell{background:#0b1019;border:1px solid #233047;border-radius:12px;padding:10px;box-shadow:inset 0 1px 0 rgba(255,255,255,.03)}
|
|
1545
|
+
.preview-chrome{display:flex;align-items:center;gap:5px;padding:3px 5px 10px}
|
|
1546
|
+
.preview-chrome i{width:6px;height:6px;border-radius:50%;background:#405069}
|
|
1547
|
+
.preview-chrome span{margin-left:6px;color:#52627a;font-size:9px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
1548
|
+
.preview-card{border-radius:10px;padding:19px;display:flex;align-items:flex-start;gap:13px;min-height:164px;transition:background .2s,border-color .2s}
|
|
1549
|
+
.preview-card.p-info{background:linear-gradient(145deg,rgba(66,153,225,.16),rgba(27,46,72,.55));border:1px solid rgba(120,183,255,.38)}
|
|
1550
|
+
.preview-card.p-warning{background:linear-gradient(145deg,rgba(246,211,101,.14),rgba(62,54,30,.55));border:1px solid rgba(246,211,101,.4)}
|
|
1551
|
+
.preview-card.p-critical{background:linear-gradient(145deg,rgba(255,139,139,.14),rgba(65,35,42,.55));border:1px solid rgba(255,139,139,.4)}
|
|
1552
|
+
.preview-icon{width:29px;height:29px;display:inline-flex;align-items:center;justify-content:center;border-radius:9px;background:rgba(255,255,255,.12);color:#fff;font-weight:800;font-size:14px;flex-shrink:0}
|
|
1553
|
+
.preview-content{flex:1;min-width:0}
|
|
1554
|
+
.preview-eyebrow{color:#7890ac;font-size:9px;font-weight:800;letter-spacing:.13em;text-transform:uppercase;margin-bottom:7px}
|
|
1555
|
+
.preview-title{font-weight:800;font-size:16px;line-height:1.25;margin-bottom:6px;color:#fff;overflow-wrap:anywhere}
|
|
1556
|
+
.preview-msg{font-size:12px;color:#a9b7ca;line-height:1.55;white-space:pre-wrap;overflow-wrap:anywhere}
|
|
1557
|
+
.preview-action{display:inline-flex;margin-top:13px;padding:6px 10px;border-radius:7px;font-size:11px;font-weight:700;text-decoration:none;border:1px solid rgba(255,255,255,.16);color:#e8eef8;background:rgba(255,255,255,.07)}
|
|
1558
|
+
.p-info .preview-title{color:#9bcaff}.p-warning .preview-title{color:#f6d365}.p-critical .preview-title{color:#ffaaaa}
|
|
1559
|
+
.preview-details{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:12px}
|
|
1560
|
+
.preview-detail{background:rgba(255,255,255,.035);border:1px solid rgba(125,140,165,.13);border-radius:8px;padding:9px 10px}
|
|
1561
|
+
.preview-detail span{display:block;color:#63728a;font-size:9px;text-transform:uppercase;letter-spacing:.08em;font-weight:800}
|
|
1562
|
+
.preview-detail strong{display:block;color:#b7c4d5;font-size:11px;margin-top:4px;font-weight:600;overflow-wrap:anywhere}
|
|
1563
|
+
.preview-note{color:#63728a;font-size:10px;line-height:1.45;margin-top:12px}
|
|
1564
|
+
.list-panel{padding:22px}
|
|
1565
|
+
.list-head{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;margin-bottom:18px}
|
|
1566
|
+
.list-head h2{display:flex;align-items:center;gap:9px;color:#fff;font-size:18px;letter-spacing:-.02em;margin-top:6px}
|
|
1567
|
+
.list-head p{color:var(--muted);font-size:12px;margin-top:5px}
|
|
1568
|
+
.list-tools{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:14px}
|
|
1569
|
+
.search-wrap{position:relative;flex:1;min-width:190px}
|
|
1570
|
+
.search-wrap input,.list-tools select{width:100%;background:#0c121d;border:1px solid var(--line);border-radius:8px;padding:9px 11px;color:var(--text);font-size:12px}
|
|
1571
|
+
.search-wrap input::placeholder{color:#56657c}
|
|
1572
|
+
.list-tools select{width:auto;min-width:120px}
|
|
1573
|
+
.search-wrap input:focus,.list-tools select:focus{border-color:var(--blue);outline:none;box-shadow:0 0 0 3px rgba(120,183,255,.1)}
|
|
1574
|
+
.notification-list{display:flex;flex-direction:column;gap:8px}
|
|
1575
|
+
.notification-row{display:flex;position:relative;overflow:hidden;background:rgba(11,16,25,.6);border:1px solid #243148;border-radius:11px;transition:border-color .2s,background .2s,transform .2s}
|
|
1576
|
+
.notification-row:hover{background:rgba(25,34,53,.7);border-color:#3a4c69;transform:translateY(-1px)}
|
|
1577
|
+
.notification-accent{width:3px;background:var(--blue);flex-shrink:0}.notification-row.type-warning .notification-accent{background:var(--yellow)}.notification-row.type-critical .notification-accent{background:var(--red)}
|
|
1578
|
+
.notification-main{min-width:0;flex:1;padding:15px 16px}
|
|
1579
|
+
.notification-top{display:flex;align-items:flex-start;justify-content:space-between;gap:14px}
|
|
1580
|
+
.notification-title{color:#fff;font-size:13px;font-weight:750;overflow-wrap:anywhere}
|
|
1581
|
+
.notification-message{color:#94a3b8;font-size:12px;line-height:1.5;margin-top:6px;white-space:pre-wrap;overflow-wrap:anywhere}
|
|
1582
|
+
.notification-meta{display:flex;align-items:center;gap:7px;flex-wrap:wrap;margin-top:11px;color:#667791;font-size:10px}
|
|
1583
|
+
.meta-chip{display:inline-flex;align-items:center;gap:4px;background:rgba(125,140,165,.08);border:1px solid rgba(125,140,165,.14);border-radius:999px;padding:4px 7px}
|
|
1584
|
+
.type-badge,.status-badge{display:inline-flex;align-items:center;border-radius:999px;padding:4px 8px;font-size:9px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;white-space:nowrap}
|
|
1585
|
+
.type-badge.info{background:rgba(120,183,255,.12);color:var(--blue)}.type-badge.warning{background:rgba(246,211,101,.12);color:var(--yellow)}.type-badge.critical{background:rgba(255,139,139,.12);color:var(--red)}
|
|
1586
|
+
.status-badge.active{background:rgba(114,223,160,.1);color:var(--green)}.status-badge.expired{background:rgba(125,140,165,.1);color:#8796ad}
|
|
1587
|
+
.notification-actions{display:flex;align-items:center;gap:7px;padding:15px 16px;flex-shrink:0}
|
|
1588
|
+
.empty{border:1px dashed #33445e;border-radius:11px;color:#6e7e96;font-size:12px;line-height:1.5;padding:32px 20px;text-align:center}
|
|
1589
|
+
.version-hint{color:#5f7089;font-size:10px;font-weight:400;margin-left:3px}
|
|
1590
|
+
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
|
|
1591
|
+
@keyframes pulse{50%{opacity:.45}}
|
|
1592
|
+
@media(max-width:960px){.auth-inner{align-items:flex-start;flex-direction:column;gap:14px}.auth-controls{width:100%;max-width:none}.workspace{grid-template-columns:1fr}.preview-panel{position:static}.metrics{grid-template-columns:repeat(2,1fr)}}
|
|
1593
|
+
@media(max-width:650px){.topbar-inner,.auth-inner,.page{padding-left:17px;padding-right:17px}.topbar-inner{gap:12px}.nav a{display:none}.nav-lock{padding:6px 8px}.page{padding-top:28px}.hero{align-items:flex-start;flex-direction:column;margin-bottom:20px}.hero-actions{width:100%;justify-content:space-between}.metrics{gap:8px}.metric{min-height:92px;padding:14px}.metric-value{font-size:24px}.compose-panel,.preview-panel,.list-panel{padding:17px}.form-grid{grid-template-columns:1fr;gap:15px}.form-divider,.form-group.full,.form-actions{grid-column:auto}.list-head{flex-direction:column;gap:8px}.list-tools{align-items:stretch;flex-direction:column}.search-wrap,.list-tools select{width:100%}.notification-row{display:block}.notification-actions{padding:0 16px 15px}.auth-controls{align-items:stretch;flex-direction:column}.token-form{width:100%}}
|
|
1594
|
+
</style>
|
|
1595
|
+
</head>
|
|
1596
|
+
<body>
|
|
1597
|
+
<header class="topbar">
|
|
1598
|
+
<div class="topbar-inner">
|
|
1599
|
+
<a class="brand" href="/notifications">
|
|
1600
|
+
<span class="brand-mark" aria-hidden="true"></span>
|
|
1601
|
+
<span><strong>Tuxevil Rotator</strong><small>Operations</small></span>
|
|
1602
|
+
</a>
|
|
1603
|
+
<nav class="nav" aria-label="Operator navigation">
|
|
1604
|
+
<a href="/">Telemetry</a>
|
|
1605
|
+
<a href="/stats">Public stats</a>
|
|
1606
|
+
<span class="nav-lock">Private</span>
|
|
1607
|
+
</nav>
|
|
1608
|
+
</div>
|
|
1609
|
+
</header>
|
|
1610
|
+
<section class="auth-strip">
|
|
1611
|
+
<div class="auth-inner">
|
|
1612
|
+
<div>
|
|
1613
|
+
<div class="auth-kicker">Operator access</div>
|
|
1614
|
+
<div class="auth-title">Notification Manager</div>
|
|
1615
|
+
<div class="auth-note">Connect with STATS_TOKEN to publish and manage broadcasts.</div>
|
|
1616
|
+
</div>
|
|
1617
|
+
<div class="auth-controls">
|
|
1618
|
+
<div class="connection" id="connectionState"><span class="connection-dot" id="connectionDot"></span><span id="connectionLabel">Not connected</span></div>
|
|
1619
|
+
<form class="token-form" id="authForm" onsubmit="authenticate(event)">
|
|
1620
|
+
<label class="sr-only" for="tok">STATS_TOKEN</label>
|
|
1621
|
+
<input type="password" id="tok" autocomplete="current-password" placeholder="Paste STATS_TOKEN" />
|
|
1622
|
+
<button class="btn-primary" id="connectBtn" type="submit">Connect</button>
|
|
1623
|
+
</form>
|
|
1624
|
+
</div>
|
|
1625
|
+
</div>
|
|
1626
|
+
</section>
|
|
1627
|
+
|
|
1628
|
+
<main class="page">
|
|
1629
|
+
<div class="flash error" id="errMsg" style="display:none"></div>
|
|
1630
|
+
<div class="flash success" id="successMsg" style="display:none"></div>
|
|
1631
|
+
|
|
1632
|
+
<div id="authedContent" style="display:none">
|
|
1633
|
+
<section class="hero">
|
|
1634
|
+
<div>
|
|
1635
|
+
<div class="eyebrow">Operations / Broadcasts</div>
|
|
1636
|
+
<h1>Keep operators in the loop.</h1>
|
|
1637
|
+
<p>Compose clear, targeted announcements for every connected rotator. Preview the client-facing card before it reaches users.</p>
|
|
1638
|
+
</div>
|
|
1639
|
+
<div class="hero-actions">
|
|
1640
|
+
<span class="sync-note" id="lastSync">Not synced</span>
|
|
1641
|
+
<button class="btn-ghost" id="refreshBtn" type="button" onclick="refreshList()">Refresh</button>
|
|
1642
|
+
</div>
|
|
1643
|
+
</section>
|
|
1644
|
+
|
|
1645
|
+
<section class="metrics" aria-label="Notification summary">
|
|
1646
|
+
<article class="metric blue"><div class="metric-label">Total</div><div class="metric-value" id="metricTotal">0</div><div class="metric-sub">All saved broadcasts</div></article>
|
|
1647
|
+
<article class="metric green"><div class="metric-label">Live</div><div class="metric-value" id="metricActive">0</div><div class="metric-sub">Currently deliverable</div></article>
|
|
1648
|
+
<article class="metric yellow"><div class="metric-label">Expiring</div><div class="metric-value" id="metricExpiring">0</div><div class="metric-sub">Have a future expiry</div></article>
|
|
1649
|
+
<article class="metric red"><div class="metric-label">Expired</div><div class="metric-value" id="metricExpired">0</div><div class="metric-sub">Kept for audit history</div></article>
|
|
1650
|
+
</section>
|
|
1651
|
+
|
|
1652
|
+
<div class="workspace">
|
|
1653
|
+
<section class="panel compose-panel" id="composePanel">
|
|
1654
|
+
<div class="panel-head">
|
|
1655
|
+
<div>
|
|
1656
|
+
<div class="section-kicker">Message studio</div>
|
|
1657
|
+
<h2 class="panel-title" id="formTitle">Compose new notification</h2>
|
|
1658
|
+
<p class="panel-description" id="formDescription">Write a concise update, then target the right client versions.</p>
|
|
1659
|
+
</div>
|
|
1660
|
+
<span class="mode-pill" id="formMode">New</span>
|
|
1661
|
+
</div>
|
|
1662
|
+
<form id="notificationForm" onsubmit="submitNotification(event)">
|
|
1663
|
+
<div class="form-grid">
|
|
1664
|
+
<input type="hidden" id="editId" value="" />
|
|
1665
|
+
<div class="form-group">
|
|
1666
|
+
<label for="nType">Severity</label>
|
|
1667
|
+
<select id="nType" onchange="updatePreview()">
|
|
1668
|
+
<option value="info">Info - routine update</option>
|
|
1669
|
+
<option value="warning">Warning - action recommended</option>
|
|
1670
|
+
<option value="critical">Critical - action required</option>
|
|
1671
|
+
</select>
|
|
1672
|
+
</div>
|
|
1673
|
+
<div class="form-group">
|
|
1674
|
+
<label for="nExpires">Expiry <span class="version-hint">optional</span></label>
|
|
1675
|
+
<input type="datetime-local" id="nExpires" onchange="updatePreview()" />
|
|
1676
|
+
</div>
|
|
1677
|
+
<div class="form-group full">
|
|
1678
|
+
<label for="nTitle">Headline</label>
|
|
1679
|
+
<input type="text" id="nTitle" maxlength="2048" placeholder="Short headline for the notification" oninput="updatePreview()" />
|
|
1680
|
+
</div>
|
|
1681
|
+
<div class="form-group full">
|
|
1682
|
+
<label for="nMessage">Message</label>
|
|
1683
|
+
<textarea id="nMessage" maxlength="2048" placeholder="Explain what changed and what users need to do." oninput="updatePreview()"><\/textarea>
|
|
1684
|
+
<div class="field-meta"><span>Shown in the client broadcast banner</span><span id="messageCount">0 / 2048</span></div>
|
|
1685
|
+
</div>
|
|
1686
|
+
<div class="form-divider">Delivery targeting</div>
|
|
1687
|
+
<div class="form-group">
|
|
1688
|
+
<label for="nMinVer">Minimum version <span class="version-hint">inclusive</span></label>
|
|
1689
|
+
<input type="text" id="nMinVer" maxlength="2048" placeholder="e.g. 1.0.0" onchange="updatePreview()" />
|
|
1690
|
+
</div>
|
|
1691
|
+
<div class="form-group">
|
|
1692
|
+
<label for="nMaxVer">Maximum version <span class="version-hint">inclusive</span></label>
|
|
1693
|
+
<input type="text" id="nMaxVer" maxlength="2048" placeholder="e.g. 1.5.1" onchange="updatePreview()" />
|
|
1694
|
+
</div>
|
|
1695
|
+
<div class="form-group">
|
|
1696
|
+
<label for="nActionUrl">Action URL <span class="version-hint">optional</span></label>
|
|
1697
|
+
<input type="text" id="nActionUrl" maxlength="2048" placeholder="https://github.com/..." oninput="updatePreview()" />
|
|
1698
|
+
</div>
|
|
1699
|
+
<div class="form-group">
|
|
1700
|
+
<label for="nActionLabel">Action label <span class="version-hint">optional</span></label>
|
|
1701
|
+
<input type="text" id="nActionLabel" maxlength="2048" placeholder="e.g. View README" oninput="updatePreview()" />
|
|
1702
|
+
</div>
|
|
1703
|
+
<div class="form-actions">
|
|
1704
|
+
<button class="btn-primary" id="btnSubmit" type="submit">Publish notification</button>
|
|
1705
|
+
<button class="btn-secondary" id="btnCancel" type="button" onclick="cancelEdit()" style="display:none">Cancel edit</button>
|
|
1706
|
+
</div>
|
|
1707
|
+
</div>
|
|
1708
|
+
</form>
|
|
1709
|
+
</section>
|
|
1710
|
+
|
|
1711
|
+
<aside class="panel preview-panel" aria-label="Live notification preview">
|
|
1712
|
+
<div class="panel-head">
|
|
1713
|
+
<div>
|
|
1714
|
+
<div class="section-kicker">Client preview</div>
|
|
1715
|
+
<h2 class="panel-title">This is what users see.</h2>
|
|
1716
|
+
</div>
|
|
1717
|
+
</div>
|
|
1718
|
+
<div class="preview-shell">
|
|
1719
|
+
<div class="preview-chrome"><i></i><i></i><i></i><span>tuxevil rotator / broadcast</span></div>
|
|
1720
|
+
<div class="preview-card p-info" id="previewCard">
|
|
1721
|
+
<span class="preview-icon" id="previewIcon">i</span>
|
|
1722
|
+
<div class="preview-content">
|
|
1723
|
+
<div class="preview-eyebrow" id="previewType">Info update</div>
|
|
1724
|
+
<div class="preview-title" id="previewTitle">Notification title</div>
|
|
1725
|
+
<div class="preview-msg" id="previewMsg">Notification message will appear here.</div>
|
|
1726
|
+
<a class="preview-action" id="previewAction" href="#" onclick="return false" style="display:none">Learn more</a>
|
|
1727
|
+
</div>
|
|
1728
|
+
</div>
|
|
1729
|
+
<div class="preview-details">
|
|
1730
|
+
<div class="preview-detail"><span>Audience</span><strong id="previewAudience">All versions</strong></div>
|
|
1731
|
+
<div class="preview-detail"><span>Availability</span><strong id="previewExpiry">No expiry</strong></div>
|
|
1732
|
+
</div>
|
|
1733
|
+
</div>
|
|
1734
|
+
<p class="preview-note">The preview updates as you type. Version targeting is applied when clients poll for active notifications.</p>
|
|
1735
|
+
</aside>
|
|
1736
|
+
</div>
|
|
1737
|
+
|
|
1738
|
+
<section class="panel list-panel">
|
|
1739
|
+
<div class="list-head">
|
|
1740
|
+
<div>
|
|
1741
|
+
<div class="section-kicker">Broadcast library</div>
|
|
1742
|
+
<h2>All notifications <span class="count-pill" id="notifCount">0 shown</span></h2>
|
|
1743
|
+
<p>Review active and historical messages, or edit a broadcast in place.</p>
|
|
1744
|
+
</div>
|
|
1745
|
+
</div>
|
|
1746
|
+
<div class="list-tools">
|
|
1747
|
+
<label class="search-wrap"><span class="sr-only">Search notifications</span><input type="search" id="notifSearch" placeholder="Search title or message..." oninput="renderTable()" /></label>
|
|
1748
|
+
<label><span class="sr-only">Filter by status</span><select id="notifStatus" onchange="renderTable()"><option value="all">All statuses</option><option value="active">Live only</option><option value="expired">Expired only</option></select></label>
|
|
1749
|
+
<label><span class="sr-only">Filter by severity</span><select id="notifTypeFilter" onchange="renderTable()"><option value="all">All severities</option><option value="info">Info</option><option value="warning">Warning</option><option value="critical">Critical</option></select></label>
|
|
1750
|
+
<button class="btn-ghost" type="button" onclick="refreshList()">Sync list</button>
|
|
1751
|
+
</div>
|
|
1752
|
+
<div class="notification-list" id="notifTable"></div>
|
|
1753
|
+
</section>
|
|
1754
|
+
</div>
|
|
1755
|
+
</main>
|
|
1756
|
+
|
|
1757
|
+
<script>
|
|
1758
|
+
|
|
1759
|
+
var _token = '';
|
|
1760
|
+
var _notifications = [];
|
|
1761
|
+
|
|
1762
|
+
function $(i) { return document.getElementById(i); }
|
|
1763
|
+
|
|
1764
|
+
function setConnection(state, label) {
|
|
1765
|
+
var el = $('connectionState');
|
|
1766
|
+
el.className = 'connection' + (state ? ' ' + state : '');
|
|
1767
|
+
$('connectionLabel').textContent = label;
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
function authenticate(event) {
|
|
1771
|
+
if (event) event.preventDefault();
|
|
1772
|
+
var t = $('tok').value.trim();
|
|
1773
|
+
if (!t) return;
|
|
1774
|
+
_token = t;
|
|
1775
|
+
localStorage.setItem('notif_token', t);
|
|
1776
|
+
loadAll();
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
async function loadAll() {
|
|
1780
|
+
setConnection('connecting', 'Connecting...');
|
|
1781
|
+
$('connectBtn').disabled = true;
|
|
1782
|
+
try {
|
|
1783
|
+
var r = await fetch('/v1/stats', { headers: { 'Authorization': 'Bearer ' + _token } });
|
|
1784
|
+
if (r.status === 401) throw new Error('Invalid token');
|
|
1785
|
+
if (!r.ok) throw new Error('Unable to connect (HTTP ' + r.status + ')');
|
|
1786
|
+
hideErr();
|
|
1787
|
+
$('authedContent').style.display = 'block';
|
|
1788
|
+
if (await refreshList()) setConnection('connected', 'Connected');
|
|
1789
|
+
else setConnection('error', 'Connection failed');
|
|
1790
|
+
} catch(e) {
|
|
1791
|
+
$('authedContent').style.display = 'none';
|
|
1792
|
+
setConnection('error', 'Connection failed');
|
|
1793
|
+
showErr(e.message);
|
|
1794
|
+
} finally {
|
|
1795
|
+
$('connectBtn').disabled = false;
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
async function refreshList() {
|
|
1800
|
+
if (!_token) return false;
|
|
1801
|
+
var refreshButton = $('refreshBtn');
|
|
1802
|
+
if (refreshButton) refreshButton.disabled = true;
|
|
1803
|
+
try {
|
|
1804
|
+
var r = await fetch('/v1/notifications?all=true', {
|
|
1805
|
+
headers: { 'Authorization': 'Bearer ' + _token }
|
|
1806
|
+
});
|
|
1807
|
+
if (r.status === 401) {
|
|
1808
|
+
$('authedContent').style.display = 'none';
|
|
1809
|
+
setConnection('error', 'Session expired');
|
|
1810
|
+
throw new Error('Session expired. Connect again.');
|
|
1811
|
+
}
|
|
1812
|
+
if (!r.ok) throw new Error('Failed to load notifications (HTTP ' + r.status + ')');
|
|
1813
|
+
_notifications = await r.json();
|
|
1814
|
+
renderTable();
|
|
1815
|
+
updateOverview();
|
|
1816
|
+
$('lastSync').textContent = 'Synced ' + new Date().toLocaleTimeString();
|
|
1817
|
+
return true;
|
|
1818
|
+
} catch(e) {
|
|
1819
|
+
showErr(e.message);
|
|
1820
|
+
return false;
|
|
1821
|
+
} finally {
|
|
1822
|
+
if (refreshButton) refreshButton.disabled = false;
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
function isExpired(n, now) {
|
|
1827
|
+
if (!n.expiresAt) return false;
|
|
1828
|
+
var timestamp = Date.parse(n.expiresAt);
|
|
1829
|
+
return Number.isFinite(timestamp) && timestamp <= now;
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
function formatDate(value) {
|
|
1833
|
+
if (!value) return 'Unknown date';
|
|
1834
|
+
var date = new Date(value);
|
|
1835
|
+
return Number.isNaN(date.getTime()) ? 'Unknown date' : date.toLocaleString();
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
function audienceLabel(n) {
|
|
1839
|
+
if (n.minVersion && n.maxVersion) return 'v' + n.minVersion + ' - v' + n.maxVersion;
|
|
1840
|
+
if (n.minVersion) return 'v' + n.minVersion + ' and newer';
|
|
1841
|
+
if (n.maxVersion) return 'Up to v' + n.maxVersion;
|
|
1842
|
+
return 'All versions';
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
function updateOverview() {
|
|
1846
|
+
var now = Date.now();
|
|
1847
|
+
var expired = _notifications.filter(function(n) { return isExpired(n, now); }).length;
|
|
1848
|
+
var expiring = _notifications.filter(function(n) { return Boolean(n.expiresAt) && !isExpired(n, now); }).length;
|
|
1849
|
+
$('metricTotal').textContent = _notifications.length;
|
|
1850
|
+
$('metricActive').textContent = _notifications.length - expired;
|
|
1851
|
+
$('metricExpiring').textContent = expiring;
|
|
1852
|
+
$('metricExpired').textContent = expired;
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
function renderTable() {
|
|
1856
|
+
var tb = $('notifTable');
|
|
1857
|
+
var query = (($('notifSearch') || {}).value || '').trim().toLowerCase();
|
|
1858
|
+
var statusFilter = ($('notifStatus') || {}).value || 'all';
|
|
1859
|
+
var typeFilter = ($('notifTypeFilter') || {}).value || 'all';
|
|
1860
|
+
var now = Date.now();
|
|
1861
|
+
var rows = _notifications.map(function(n, index) { return { notification: n, index: index }; }).filter(function(entry) {
|
|
1862
|
+
var n = entry.notification;
|
|
1863
|
+
var expired = isExpired(n, now);
|
|
1864
|
+
var haystack = [n.title, n.message, n.actionLabel, n.minVersion, n.maxVersion].filter(Boolean).join(' ').toLowerCase();
|
|
1865
|
+
if (query && haystack.indexOf(query) === -1) return false;
|
|
1866
|
+
if (statusFilter === 'active' && expired) return false;
|
|
1867
|
+
if (statusFilter === 'expired' && !expired) return false;
|
|
1868
|
+
if (typeFilter !== 'all' && n.type !== typeFilter) return false;
|
|
1869
|
+
return true;
|
|
1870
|
+
});
|
|
1871
|
+
|
|
1872
|
+
$('notifCount').textContent = rows.length + ' shown';
|
|
1873
|
+
if (rows.length === 0) {
|
|
1874
|
+
tb.innerHTML = _notifications.length === 0
|
|
1875
|
+
? '<div class="empty">No notifications yet. Compose the first broadcast above.</div>'
|
|
1876
|
+
: '<div class="empty">No notifications match these filters.<br>Try a different search or status.</div>';
|
|
1877
|
+
return;
|
|
1878
|
+
}
|
|
1879
|
+
|
|
1880
|
+
var html = '';
|
|
1881
|
+
rows.forEach(function(entry) {
|
|
1882
|
+
var n = entry.notification;
|
|
1883
|
+
var expired = isExpired(n, now);
|
|
1884
|
+
var type = ['info', 'warning', 'critical'].includes(n.type) ? n.type : 'info';
|
|
1885
|
+
var message = String(n.message || '');
|
|
1886
|
+
var messagePreview = message.length > 220 ? message.slice(0, 220) + '...' : message;
|
|
1887
|
+
var expiry = n.expiresAt ? (expired ? 'Expired ' : 'Expires ') + formatDate(n.expiresAt) : 'No expiry';
|
|
1888
|
+
var action = n.actionUrl ? '<span class="meta-chip">Action: ' + esc(n.actionLabel || 'Open link') + '</span>' : '';
|
|
1889
|
+
html += '<article class="notification-row type-' + type + '">' +
|
|
1890
|
+
'<div class="notification-accent"></div>' +
|
|
1891
|
+
'<div class="notification-main">' +
|
|
1892
|
+
'<div class="notification-top">' +
|
|
1893
|
+
'<div class="notification-title">' + esc(n.title || 'Untitled notification') + '</div>' +
|
|
1894
|
+
'<span class="status-badge ' + (expired ? 'expired' : 'active') + '">' + (expired ? 'Expired' : 'Live') + '</span>' +
|
|
1895
|
+
'</div>' +
|
|
1896
|
+
'<div class="notification-message">' + esc(messagePreview) + '</div>' +
|
|
1897
|
+
'<div class="notification-meta">' +
|
|
1898
|
+
'<span class="type-badge ' + type + '">' + type + '</span>' +
|
|
1899
|
+
'<span class="meta-chip">Audience: ' + esc(audienceLabel(n)) + '</span>' +
|
|
1900
|
+
'<span class="meta-chip">' + esc(expiry) + '</span>' +
|
|
1901
|
+
'<span class="meta-chip">Created ' + esc(formatDate(n.createdAt)) + '</span>' +
|
|
1902
|
+
action +
|
|
1903
|
+
'</div>' +
|
|
1904
|
+
'</div>' +
|
|
1905
|
+
'<div class="notification-actions">' +
|
|
1906
|
+
'<button class="btn-edit" type="button" onclick="editNotif(' + entry.index + ')">Edit</button>' +
|
|
1907
|
+
'<button class="btn-danger" type="button" onclick="deleteNotif(\\'' + jsString(n.id) + '\\')">Delete</button>' +
|
|
1908
|
+
'</div>' +
|
|
1909
|
+
'</article>';
|
|
1910
|
+
});
|
|
1911
|
+
tb.innerHTML = html;
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
function editNotif(idx) {
|
|
1915
|
+
var n = _notifications[idx];
|
|
1916
|
+
if (!n) return;
|
|
1917
|
+
$('editId').value = n.id;
|
|
1918
|
+
$('nType').value = n.type || 'info';
|
|
1919
|
+
$('nTitle').value = n.title || '';
|
|
1920
|
+
$('nMessage').value = n.message || '';
|
|
1921
|
+
$('nMinVer').value = n.minVersion || '';
|
|
1922
|
+
$('nMaxVer').value = n.maxVersion || '';
|
|
1923
|
+
$('nActionUrl').value = n.actionUrl || '';
|
|
1924
|
+
$('nActionLabel').value = n.actionLabel || '';
|
|
1925
|
+
if (n.expiresAt) {
|
|
1926
|
+
$('nExpires').value = n.expiresAt.slice(0, 16);
|
|
1927
|
+
} else {
|
|
1928
|
+
$('nExpires').value = '';
|
|
1929
|
+
}
|
|
1930
|
+
$('formTitle').textContent = 'Edit notification';
|
|
1931
|
+
$('formDescription').textContent = 'Update the message or delivery rules, then save the revised broadcast.';
|
|
1932
|
+
$('formMode').textContent = 'Editing';
|
|
1933
|
+
$('btnSubmit').textContent = 'Save changes';
|
|
1934
|
+
$('btnCancel').style.display = '';
|
|
1935
|
+
updatePreview();
|
|
1936
|
+
$('composePanel').scrollIntoView({ block: 'start', behavior: 'smooth' });
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
function cancelEdit() {
|
|
1940
|
+
$('editId').value = '';
|
|
1941
|
+
$('nType').value = 'info';
|
|
1942
|
+
$('nTitle').value = '';
|
|
1943
|
+
$('nMessage').value = '';
|
|
1944
|
+
$('nMinVer').value = '';
|
|
1945
|
+
$('nMaxVer').value = '';
|
|
1946
|
+
$('nActionUrl').value = '';
|
|
1947
|
+
$('nActionLabel').value = '';
|
|
1948
|
+
$('nExpires').value = '';
|
|
1949
|
+
$('formTitle').textContent = 'Compose new notification';
|
|
1950
|
+
$('formDescription').textContent = 'Write a concise update, then target the right client versions.';
|
|
1951
|
+
$('formMode').textContent = 'New';
|
|
1952
|
+
$('btnSubmit').textContent = 'Publish notification';
|
|
1953
|
+
$('btnCancel').style.display = 'none';
|
|
1954
|
+
updatePreview();
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
async function submitNotification(event) {
|
|
1958
|
+
if (event) event.preventDefault();
|
|
1959
|
+
var title = $('nTitle').value.trim();
|
|
1960
|
+
var message = $('nMessage').value.trim();
|
|
1961
|
+
if (!title || !message) { showErr('Title and message are required'); return; }
|
|
1962
|
+
|
|
1963
|
+
var payload = {
|
|
1964
|
+
type: $('nType').value,
|
|
1965
|
+
title: title,
|
|
1966
|
+
message: message,
|
|
1967
|
+
minVersion: $('nMinVer').value.trim() || null,
|
|
1968
|
+
maxVersion: $('nMaxVer').value.trim() || null,
|
|
1969
|
+
actionUrl: $('nActionUrl').value.trim() || null,
|
|
1970
|
+
actionLabel: $('nActionLabel').value.trim() || null,
|
|
1971
|
+
expiresAt: $('nExpires').value ? new Date($('nExpires').value).toISOString() : null,
|
|
1972
|
+
};
|
|
1973
|
+
|
|
1974
|
+
var editId = $('editId').value;
|
|
1975
|
+
if (editId) payload.id = editId;
|
|
1976
|
+
|
|
1977
|
+
var button = $('btnSubmit');
|
|
1978
|
+
button.disabled = true;
|
|
1979
|
+
button.textContent = editId ? 'Saving changes...' : 'Publishing...';
|
|
1980
|
+
try {
|
|
1981
|
+
var r = await fetch('/v1/notifications', {
|
|
1982
|
+
method: 'POST',
|
|
1983
|
+
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + _token },
|
|
1984
|
+
body: JSON.stringify(payload),
|
|
1985
|
+
});
|
|
1986
|
+
var result = await r.json();
|
|
1987
|
+
if (r.ok && result.ok) {
|
|
1988
|
+
showSuccess(editId ? 'Notification updated!' : 'Notification created!');
|
|
1989
|
+
cancelEdit();
|
|
1990
|
+
await refreshList();
|
|
1991
|
+
} else {
|
|
1992
|
+
showErr(result.error || 'Failed to save notification');
|
|
1993
|
+
}
|
|
1994
|
+
} catch(e) {
|
|
1995
|
+
showErr(e.message);
|
|
1996
|
+
} finally {
|
|
1997
|
+
button.disabled = false;
|
|
1998
|
+
if ($('editId').value) button.textContent = 'Save changes';
|
|
1999
|
+
else button.textContent = 'Publish notification';
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
async function deleteNotif(id) {
|
|
2004
|
+
if (!confirm('Delete this notification?')) return;
|
|
2005
|
+
try {
|
|
2006
|
+
var r = await fetch('/v1/notifications/' + encodeURIComponent(id), {
|
|
2007
|
+
method: 'DELETE',
|
|
2008
|
+
headers: { 'Authorization': 'Bearer ' + _token },
|
|
2009
|
+
});
|
|
2010
|
+
var result = await r.json();
|
|
2011
|
+
if (r.ok && result.ok) {
|
|
2012
|
+
showSuccess('Notification deleted');
|
|
2013
|
+
await refreshList();
|
|
2014
|
+
} else {
|
|
2015
|
+
showErr(result.error || 'Failed to delete');
|
|
2016
|
+
}
|
|
2017
|
+
} catch(e) { showErr(e.message); }
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
var ICONS = { info: 'i', warning: '!', critical: '!' };
|
|
2021
|
+
var TYPE_LABELS = { info: 'Info update', warning: 'Warning', critical: 'Critical alert' };
|
|
2022
|
+
|
|
2023
|
+
function updatePreview() {
|
|
2024
|
+
var type = $('nType').value;
|
|
2025
|
+
var title = $('nTitle').value || 'Notification title';
|
|
2026
|
+
var msg = $('nMessage').value || 'Notification message will appear here';
|
|
2027
|
+
var actionUrl = $('nActionUrl').value;
|
|
2028
|
+
var actionLabel = $('nActionLabel').value || 'Learn More';
|
|
2029
|
+
var card = $('previewCard');
|
|
2030
|
+
card.className = 'preview-card p-' + type;
|
|
2031
|
+
$('previewIcon').textContent = ICONS[type] || ICONS.info;
|
|
2032
|
+
$('previewType').textContent = TYPE_LABELS[type] || TYPE_LABELS.info;
|
|
2033
|
+
$('previewTitle').textContent = title;
|
|
2034
|
+
$('previewMsg').textContent = msg;
|
|
2035
|
+
var action = $('previewAction');
|
|
2036
|
+
action.textContent = actionLabel;
|
|
2037
|
+
action.href = /^https?:\\/\\//i.test(actionUrl) ? actionUrl : '#';
|
|
2038
|
+
action.style.display = actionUrl ? 'inline-flex' : 'none';
|
|
2039
|
+
var minVersion = $('nMinVer').value.trim();
|
|
2040
|
+
var maxVersion = $('nMaxVer').value.trim();
|
|
2041
|
+
if (minVersion && maxVersion) $('previewAudience').textContent = 'v' + minVersion + ' - v' + maxVersion;
|
|
2042
|
+
else if (minVersion) $('previewAudience').textContent = 'v' + minVersion + ' and newer';
|
|
2043
|
+
else if (maxVersion) $('previewAudience').textContent = 'Up to v' + maxVersion;
|
|
2044
|
+
else $('previewAudience').textContent = 'All versions';
|
|
2045
|
+
var expiry = $('nExpires').value;
|
|
2046
|
+
$('previewExpiry').textContent = expiry ? formatDate(new Date(expiry).toISOString()) : 'No expiry';
|
|
2047
|
+
updateMessageCount();
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
function updateMessageCount() {
|
|
2051
|
+
var message = $('nMessage').value || '';
|
|
2052
|
+
$('messageCount').textContent = message.length + ' / 2048';
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
function esc(s) { if (!s) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,'''); }
|
|
2056
|
+
function jsString(s) {
|
|
2057
|
+
return esc(String(s == null ? '' : s)
|
|
2058
|
+
.replace(/\\\\/g, '\\\\\\\\')
|
|
2059
|
+
.replace(/'/g, "\\\\'")
|
|
2060
|
+
.replace(/\\r/g, '\\\\r')
|
|
2061
|
+
.replace(/\\n/g, '\\\\n'));
|
|
2062
|
+
}
|
|
2063
|
+
function showErr(m) { $('errMsg').textContent = 'Error: ' + m; $('errMsg').style.display = ''; setTimeout(function(){ $('errMsg').style.display='none'; }, 8000); }
|
|
2064
|
+
function hideErr() { $('errMsg').style.display = 'none'; }
|
|
2065
|
+
function showSuccess(m) { $('successMsg').textContent = 'Saved: ' + m; $('successMsg').style.display = ''; setTimeout(function(){ $('successMsg').style.display='none'; }, 4000); }
|
|
2066
|
+
|
|
2067
|
+
// Auto-connect from saved token
|
|
2068
|
+
var saved = localStorage.getItem('notif_token');
|
|
2069
|
+
if (saved) { _token = saved; $('tok').value = saved; loadAll(); }
|
|
2070
|
+
updatePreview();
|
|
2071
|
+
updateMessageCount();
|
|
2072
|
+
<\/script>
|
|
2073
|
+
</body></html>`;
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
// ── HTTP Server ──────────────────────────────────────────────────────
|
|
2077
|
+
function readBody(req) {
|
|
2078
|
+
return new Promise((resolve, reject) => {
|
|
2079
|
+
const chunks = [];
|
|
2080
|
+
let size = 0;
|
|
2081
|
+
let rejected = false;
|
|
2082
|
+
req.on("data", (chunk) => {
|
|
2083
|
+
if (rejected) return;
|
|
2084
|
+
size += chunk.length;
|
|
2085
|
+
if (size > MAX_BODY_BYTES) {
|
|
2086
|
+
rejected = true;
|
|
2087
|
+
req.destroy();
|
|
2088
|
+
reject(new Error("Payload too large"));
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
chunks.push(chunk);
|
|
2092
|
+
});
|
|
2093
|
+
req.on("end", () => {
|
|
2094
|
+
if (!rejected) resolve(Buffer.concat(chunks).toString("utf-8"));
|
|
2095
|
+
});
|
|
2096
|
+
req.on("error", reject);
|
|
2097
|
+
});
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
const server = createServer(async (req, res) => {
|
|
2101
|
+
const method = req.method?.toUpperCase();
|
|
2102
|
+
const url = req.url || "";
|
|
2103
|
+
|
|
2104
|
+
// CORS
|
|
2105
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
2106
|
+
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
|
2107
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
|
2108
|
+
if (method === "OPTIONS") {
|
|
2109
|
+
res.writeHead(204);
|
|
2110
|
+
res.end();
|
|
2111
|
+
return;
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
// Dashboard
|
|
2115
|
+
if (method === "GET" && (url === "/" || url === "/dashboard")) {
|
|
2116
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
2117
|
+
res.end(buildDashboardHtml());
|
|
2118
|
+
return;
|
|
2119
|
+
}
|
|
2120
|
+
|
|
2121
|
+
// Public stats page
|
|
2122
|
+
if (method === "GET" && url === "/stats") {
|
|
2123
|
+
res.writeHead(200, {
|
|
2124
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
2125
|
+
"Cache-Control": "no-cache",
|
|
2126
|
+
});
|
|
2127
|
+
res.end(buildPublicStatsHtml());
|
|
2128
|
+
return;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
// Notifications Admin UI
|
|
2132
|
+
if (method === "GET" && url === "/notifications") {
|
|
2133
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
2134
|
+
res.end(buildNotificationsAdminHtml());
|
|
2135
|
+
return;
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
// ── Notifications API ──────────────────────────────────────────
|
|
2139
|
+
// GET /v1/notifications — Public, returns active notifications
|
|
2140
|
+
// Add ?all=true to load all (including expired) for admin UI
|
|
2141
|
+
if (method === "GET" && url.startsWith("/v1/notifications")) {
|
|
2142
|
+
try {
|
|
2143
|
+
const q = parseQueryString(url);
|
|
2144
|
+
if (q.all === "true") {
|
|
2145
|
+
// Return ALL notifications (for admin management UI)
|
|
2146
|
+
if (!requireStatsAuth(req, res)) return;
|
|
2147
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
2148
|
+
res.end(JSON.stringify(loadNotifications()));
|
|
2149
|
+
} else {
|
|
2150
|
+
const clientVersion = q.version || null;
|
|
2151
|
+
const active = getActiveNotifications(clientVersion);
|
|
2152
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
2153
|
+
res.end(JSON.stringify(active));
|
|
2154
|
+
}
|
|
2155
|
+
} catch (err) {
|
|
2156
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2157
|
+
res.end(JSON.stringify({ error: "Failed to load notifications" }));
|
|
2158
|
+
}
|
|
2159
|
+
return;
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
// POST /v1/notifications — Create/update notification (auth required)
|
|
2163
|
+
if (method === "POST" && url === "/v1/notifications") {
|
|
2164
|
+
if (!requireStatsAuth(req, res)) return;
|
|
2165
|
+
try {
|
|
2166
|
+
const body = await readBody(req);
|
|
2167
|
+
const data = JSON.parse(body);
|
|
2168
|
+
if (!isValidNotificationInput(data)) {
|
|
2169
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
2170
|
+
res.end(JSON.stringify({ error: "Invalid notification fields" }));
|
|
2171
|
+
return;
|
|
2172
|
+
}
|
|
2173
|
+
const notifications = loadNotifications();
|
|
2174
|
+
const notification = {
|
|
2175
|
+
id: data.id || randomUUID(),
|
|
2176
|
+
type: data.type || "info",
|
|
2177
|
+
title: data.title,
|
|
2178
|
+
message: data.message,
|
|
2179
|
+
createdAt: data.createdAt || new Date().toISOString(),
|
|
2180
|
+
expiresAt: data.expiresAt || null,
|
|
2181
|
+
minVersion: data.minVersion || null,
|
|
2182
|
+
maxVersion: data.maxVersion || null,
|
|
2183
|
+
actionUrl: data.actionUrl || null,
|
|
2184
|
+
actionLabel: data.actionLabel || null,
|
|
2185
|
+
};
|
|
2186
|
+
// Update if id exists, otherwise add
|
|
2187
|
+
const existingIdx = notifications.findIndex((n) => n.id === notification.id);
|
|
2188
|
+
if (existingIdx >= 0) {
|
|
2189
|
+
notifications[existingIdx] = notification;
|
|
2190
|
+
} else {
|
|
2191
|
+
notifications.push(notification);
|
|
2192
|
+
}
|
|
2193
|
+
saveNotifications(notifications);
|
|
2194
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
2195
|
+
res.end(JSON.stringify({ ok: true, notification }));
|
|
2196
|
+
} catch (err) {
|
|
2197
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
2198
|
+
res.end(JSON.stringify({ error: "Bad request" }));
|
|
2199
|
+
}
|
|
2200
|
+
return;
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
// DELETE /v1/notifications/:id — Remove notification (auth required)
|
|
2204
|
+
if (method === "DELETE" && url.startsWith("/v1/notifications/")) {
|
|
2205
|
+
if (!requireStatsAuth(req, res)) return;
|
|
2206
|
+
try {
|
|
2207
|
+
const id = decodeURIComponent(url.slice("/v1/notifications/".length));
|
|
2208
|
+
const notifications = loadNotifications();
|
|
2209
|
+
const filtered = notifications.filter((n) => n.id !== id);
|
|
2210
|
+
if (filtered.length === notifications.length) {
|
|
2211
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
2212
|
+
res.end(JSON.stringify({ error: "Notification not found" }));
|
|
2213
|
+
return;
|
|
2214
|
+
}
|
|
2215
|
+
saveNotifications(filtered);
|
|
2216
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
2217
|
+
res.end(JSON.stringify({ ok: true, deleted: id }));
|
|
2218
|
+
} catch {
|
|
2219
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2220
|
+
res.end(JSON.stringify({ error: "Failed to delete notification" }));
|
|
2221
|
+
}
|
|
2222
|
+
return;
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
// Public stats (no auth required, 5-minute cache)
|
|
2226
|
+
if (method === "GET" && url === "/v1/public-stats") {
|
|
2227
|
+
const corsHeaders = {
|
|
2228
|
+
"Content-Type": "application/json",
|
|
2229
|
+
"Cache-Control": "public, max-age=300",
|
|
2230
|
+
"Access-Control-Allow-Origin": "*",
|
|
2231
|
+
};
|
|
2232
|
+
try {
|
|
2233
|
+
const stats = getPublicStats();
|
|
2234
|
+
res.writeHead(200, corsHeaders);
|
|
2235
|
+
res.end(JSON.stringify(stats));
|
|
2236
|
+
} catch {
|
|
2237
|
+
res.writeHead(500, corsHeaders);
|
|
2238
|
+
res.end(JSON.stringify({ error: "Failed to compute public stats" }));
|
|
2239
|
+
}
|
|
2240
|
+
return;
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
// Health check
|
|
2244
|
+
if (method === "GET" && url === "/v1/health") {
|
|
2245
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
2246
|
+
res.end(JSON.stringify({ status: "ok", ts: new Date().toISOString() }));
|
|
2247
|
+
return;
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
// Installs list (protected)
|
|
2251
|
+
if (method === "GET" && url.startsWith("/v1/installs")) {
|
|
2252
|
+
if (!requireStatsAuth(req, res)) return;
|
|
2253
|
+
try {
|
|
2254
|
+
const q = parseQueryString(url);
|
|
2255
|
+
const filters = {};
|
|
2256
|
+
if (q.from) filters.from = q.from;
|
|
2257
|
+
if (q.to) filters.to = q.to;
|
|
2258
|
+
if (q.version) filters.version = q.version;
|
|
2259
|
+
if (q.os) filters.os = q.os;
|
|
2260
|
+
const list = computeInstallList(filters);
|
|
2261
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
2262
|
+
res.end(JSON.stringify(list));
|
|
2263
|
+
} catch (err) {
|
|
2264
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2265
|
+
res.end(JSON.stringify({ error: "Failed to compute install list" }));
|
|
2266
|
+
}
|
|
2267
|
+
return;
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
// Stats (protected)
|
|
2271
|
+
if (method === "GET" && url.startsWith("/v1/stats")) {
|
|
2272
|
+
if (!requireStatsAuth(req, res)) return;
|
|
2273
|
+
try {
|
|
2274
|
+
const q = parseQueryString(url);
|
|
2275
|
+
const filters = {};
|
|
2276
|
+
if (q.installId) filters.installId = q.installId;
|
|
2277
|
+
if (q.version) filters.version = q.version;
|
|
2278
|
+
if (q.os) filters.os = q.os;
|
|
2279
|
+
if (q.model) filters.model = q.model;
|
|
2280
|
+
if (q.from) filters.from = q.from;
|
|
2281
|
+
if (q.to) filters.to = q.to;
|
|
2282
|
+
const stats = computeStats(filters);
|
|
2283
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
2284
|
+
res.end(JSON.stringify(stats, null, 2));
|
|
2285
|
+
} catch (err) {
|
|
2286
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2287
|
+
res.end(JSON.stringify({ error: "Failed to compute stats" }));
|
|
2288
|
+
}
|
|
2289
|
+
return;
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
// Collect telemetry
|
|
2293
|
+
if (method === "POST" && url === "/v1/events") {
|
|
2294
|
+
const ip = req.headers["x-forwarded-for"]?.toString().split(",")[0]?.trim() || req.socket.remoteAddress || "unknown";
|
|
2295
|
+
if (isRateLimited(ip)) {
|
|
2296
|
+
res.writeHead(429, { "Content-Type": "application/json" });
|
|
2297
|
+
res.end(JSON.stringify({ error: "Too many requests" }));
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
try {
|
|
2302
|
+
const body = await readBody(req);
|
|
2303
|
+
const data = JSON.parse(body);
|
|
2304
|
+
|
|
2305
|
+
if (!isValidPayload(data)) {
|
|
2306
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
2307
|
+
res.end(JSON.stringify({ error: "Invalid payload" }));
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
storeEvent(data);
|
|
2312
|
+
res.writeHead(202, { "Content-Type": "application/json" });
|
|
2313
|
+
res.end(JSON.stringify({ accepted: true }));
|
|
2314
|
+
} catch (err) {
|
|
2315
|
+
if (err.message === "Payload too large") {
|
|
2316
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
2317
|
+
res.end(JSON.stringify({ error: "Payload too large" }));
|
|
2318
|
+
} else {
|
|
2319
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
2320
|
+
res.end(JSON.stringify({ error: "Bad request" }));
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
return;
|
|
2324
|
+
}
|
|
2325
|
+
|
|
2326
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
2327
|
+
res.end(JSON.stringify({ error: "Not found" }));
|
|
2328
|
+
});
|
|
2329
|
+
|
|
2330
|
+
server.listen(PORT, "0.0.0.0", () => {
|
|
2331
|
+
console.log(`Telemetry receiver listening on 0.0.0.0:${PORT}`);
|
|
2332
|
+
console.log(`Data dir: ${DATA_DIR}`);
|
|
2333
|
+
console.log(`Stats: ${STATS_TOKEN ? "protected by STATS_TOKEN" : "⚠ STATS_TOKEN not set — /v1/stats disabled"}`);
|
|
2334
|
+
});
|