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.
Files changed (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
package/src/index.ts ADDED
@@ -0,0 +1,267 @@
1
+ // Entry point - loads config and starts the proxy
2
+
3
+ import { join } from "node:path";
4
+ import type { Config } from "./types.js";
5
+ import { AccountRotator } from "./rotator.js";
6
+ import { startProxy } from "./proxy.js";
7
+ import { getConfigDir } from "./paths.js";
8
+ import { TelemetryReporter, setActiveReporter } from "./telemetry.js";
9
+ import { loadConfig as loadConfigFromStore, importLegacyOllamaRotatorAccounts } from "./account-store.js";
10
+ import {
11
+ ensureAdminToken,
12
+ getConfiguredAdminToken,
13
+ setPersistedAdminToken,
14
+ } from "./admin-auth.js";
15
+ import { warnIfUsingFallbackOAuthCreds } from "./providers/google-antigravity/oauth.js";
16
+ import { warnIfInsecureTelemetryEndpoint } from "./telemetry.js";
17
+ import {
18
+ setModelSpecsOverride,
19
+ loadResponsesStore,
20
+ flushResponsesStore,
21
+ } from "./compat.js";
22
+ import { setModelAliasesOverride } from "./types.js";
23
+ import { readTextFile, writeTextFileAtomic } from "./storage.js";
24
+ import { initDb } from "./db-store.js";
25
+ import { runKeyMigrations } from "./key-migrations.js";
26
+ import { flushSpendLogs, stopRetentionCleanup, startRetentionCleanup } from "./spend-logger.js";
27
+ import { stopPendingSessionReaper } from "./onboarding.js";
28
+ import { getProxyExposureWarning } from "./exposure.js";
29
+ import { closeProxyDispatchers } from "./providers/proxy-dispatcher.js";
30
+
31
+ function loadConfig(): Config {
32
+ try {
33
+ const config = loadConfigFromStore();
34
+
35
+ if (!config.accounts || config.accounts.length === 0) {
36
+ console.error(
37
+ "No accounts configured. Run 'tuxevil-rotator login' to add one.",
38
+ );
39
+ process.exit(1);
40
+ }
41
+
42
+ return config;
43
+ } catch (err) {
44
+ console.error(`Failed to load config: ${err}`);
45
+ process.exit(1);
46
+ }
47
+ }
48
+
49
+ const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
50
+
51
+ /**
52
+ * Show a one-time, non-intrusive star reminder after 24h since first install.
53
+ * Creates .first-boot on first run, shows prompt once after 24h,
54
+ * then writes .star-prompted so it never appears again.
55
+ */
56
+ async function maybeShowStarNudge(): Promise<void> {
57
+ const dir = getConfigDir();
58
+ const promptedPath = join(dir, ".star-prompted");
59
+ try {
60
+ if ((await readTextFile(promptedPath)) !== null) return;
61
+ } catch {
62
+ return;
63
+ }
64
+
65
+ const firstBootPath = join(dir, ".first-boot");
66
+ let firstBootMs: number;
67
+
68
+ try {
69
+ const firstBoot = await readTextFile(firstBootPath);
70
+ if (firstBoot !== null) {
71
+ firstBootMs = parseInt(firstBoot.trim(), 10);
72
+ if (Number.isNaN(firstBootMs)) return;
73
+ } else {
74
+ // First ever boot — record timestamp
75
+ firstBootMs = Date.now();
76
+ try {
77
+ await writeTextFileAtomic(firstBootPath, String(firstBootMs));
78
+ } catch {
79
+ /* best effort */
80
+ }
81
+ return; // too early, come back after 24h
82
+ }
83
+ } catch {
84
+ return;
85
+ }
86
+
87
+ if (Date.now() - firstBootMs < TWENTY_FOUR_HOURS_MS) return; // not yet
88
+
89
+ // Show it once
90
+ console.log(" ╭──────────────────────────────────────────────────────────╮");
91
+ console.log(" │ ⭐ Enjoying tuxevil-rotator? │");
92
+ console.log(" │ github.com/tuxevil/tuxevil-rotator │");
93
+ console.log(" │ A star helps others find it. Thanks! │");
94
+ console.log(" ╰──────────────────────────────────────────────────────────╯");
95
+ console.log();
96
+
97
+ try {
98
+ await writeTextFileAtomic(promptedPath, String(Date.now()));
99
+ } catch {
100
+ /* best effort */
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Resolve the effective admin token at startup. If no TUXEVIL_ROTATOR_ADMIN_TOKEN
106
+ * env var is set and no persisted token exists, a new token is generated,
107
+ * saved to the repository, and printed to the operator once. This ensures
108
+ * admin routes are protected by default on first run.
109
+ */
110
+ async function bootstrapAdminToken(): Promise<void> {
111
+ const resolved = await ensureAdminToken();
112
+ setPersistedAdminToken(resolved.token);
113
+ if (resolved.source === "generated") {
114
+ console.log();
115
+ console.log(
116
+ " ╭──────────────────────────────────────────────────────────╮",
117
+ );
118
+ console.log(
119
+ " │ Generated admin token (saved to repository): │",
120
+ );
121
+ const tokenPreview =
122
+ resolved.token.length > 12
123
+ ? `${resolved.token.slice(0, 8)}…${resolved.token.slice(-4)}`
124
+ : resolved.token;
125
+ console.log(` │ ${tokenPreview} │`);
126
+ console.log(
127
+ " │ │",
128
+ );
129
+ console.log(
130
+ " │ Header: x-rotator-admin-token: <token> │",
131
+ );
132
+ console.log(
133
+ " │ Bearer: Authorization: Bearer <token> │",
134
+ );
135
+ console.log(
136
+ " │ URL: <url>?token=<token> │",
137
+ );
138
+ console.log(
139
+ " ╰──────────────────────────────────────────────────────────╯",
140
+ );
141
+ console.log();
142
+ }
143
+ }
144
+
145
+ function maybeWarnAboutAdminExposure(config: Config): void {
146
+ if (getConfiguredAdminToken()) return;
147
+ console.warn("WARNING: TUXEVIL_ROTATOR_ADMIN_TOKEN is not configured.");
148
+ console.warn(
149
+ `WARNING: Dashboard and /api/* routes are open on ${config.bindHost}:${config.proxyPort}.`,
150
+ );
151
+ console.warn(
152
+ "WARNING: For local-only use, prefer bindHost=127.0.0.1 or set TUXEVIL_ROTATOR_ADMIN_TOKEN.",
153
+ );
154
+ console.warn();
155
+ }
156
+
157
+ function maybeWarnAboutProxyExposure(config: Config): void {
158
+ const warning = getProxyExposureWarning(config);
159
+ if (!warning) return;
160
+ console.warn(`WARNING: ${warning}`);
161
+ console.warn(
162
+ "WARNING: TUXEVIL_ROTATOR_ADMIN_TOKEN protects dashboard/admin APIs, but not the native or /v1 proxy routes.",
163
+ );
164
+ console.warn();
165
+ }
166
+
167
+ export async function main(): Promise<void> {
168
+ console.log("=== Tuxevil Rotator ===");
169
+ console.log();
170
+
171
+ await initDb();
172
+ await runKeyMigrations();
173
+ await importLegacyOllamaRotatorAccounts();
174
+ startRetentionCleanup();
175
+
176
+ const config = loadConfig();
177
+ console.log(`Loaded ${config.accounts.length} accounts`);
178
+ console.log(
179
+ `Rotation: ${config.requestsPerRotation} requests / ${config.rotateOnQuotaDrop}% quota drop`,
180
+ );
181
+ console.log(
182
+ `Quota poll: every ${Math.round((config.quotaPollIntervalMs || 300000) / 1000)}s`,
183
+ );
184
+ console.log(
185
+ `Concurrency cap: ${config.maxConcurrentRequestsPerAccount} request/account, ${config.maxConcurrentRequestsPerProjectModel} request/project+model`,
186
+ );
187
+ console.log(`Bind host: ${config.bindHost}`);
188
+ console.log(`Routing policy: ${config.routingPolicy}`);
189
+ console.log(
190
+ `Safety breaker: ${config.projectCircuitBreaker429Threshold} provider 429s / ${Math.round((config.projectCircuitBreakerWindowMs || 0) / 60000)}m pauses project+model for ${Math.round((config.projectCircuitBreakerCooldownMs || 0) / 60000)}m`,
191
+ );
192
+ console.log(
193
+ `Protective pause: ${Math.round((config.protectivePauseMs || 0) / 3600000)}h after serious flag`,
194
+ );
195
+ console.log();
196
+
197
+ for (const account of config.accounts) {
198
+ console.log(` ${account.label || account.email} (${account.email})`);
199
+ }
200
+ console.log();
201
+
202
+ await maybeShowStarNudge();
203
+ await bootstrapAdminToken();
204
+ maybeWarnAboutAdminExposure(config);
205
+ maybeWarnAboutProxyExposure(config);
206
+ warnIfUsingFallbackOAuthCreds();
207
+ warnIfInsecureTelemetryEndpoint();
208
+ setModelSpecsOverride(config.modelSpecs ?? null);
209
+ setModelAliasesOverride(config.modelAliases ?? null);
210
+ void loadResponsesStore();
211
+
212
+ const rotator = new AccountRotator(config);
213
+ await rotator.primeOllamaCatalog();
214
+
215
+ // ── Telemetry (anonymous, opt-out via TUXEVIL_ROTATOR_TELEMETRY=off) ──
216
+ const telemetry = new TelemetryReporter(() => {
217
+ const status = rotator.getStatus();
218
+
219
+ // getTokenUsage() deduplicates rolled-up buckets and exposes tokensByModel
220
+ const tu = rotator.getTokenUsage();
221
+ const tokensByModel = tu.tokensByModel;
222
+
223
+ return {
224
+ accountCount: status.accounts.length,
225
+ modelsUsed: Object.keys(status.activeAccounts),
226
+ totalRequests: status.totalRequestsAllAccounts,
227
+ uptimeSeconds: Math.round(status.uptime / 1000),
228
+ routingHealthState: status.routingHealth.state,
229
+ flaggedCount: status.routingHealth.flaggedCount,
230
+ disabledCount: status.routingHealth.disabledCount,
231
+ proCount: status.accounts.filter((a) => a.proDetected).length,
232
+ freeCount: status.accounts.filter((a) => !a.proDetected).length,
233
+ tokensByModel,
234
+ };
235
+ });
236
+ setActiveReporter(telemetry);
237
+ void telemetry.start();
238
+
239
+ // ── Graceful shutdown ──
240
+ const shutdown = async (): Promise<void> => {
241
+ console.log("\nShutting down...");
242
+ stopRetentionCleanup();
243
+ await flushSpendLogs();
244
+ await flushResponsesStore();
245
+ await rotator.flushPendingStateSave();
246
+ await rotator.flushPendingTokenUsageSave();
247
+ await telemetry.shutdown();
248
+ rotator.stopQuotaPolling();
249
+ stopPendingSessionReaper();
250
+ await closeProxyDispatchers();
251
+ const { closeDb } = await import("./db-store.js");
252
+ await closeDb();
253
+ process.exit(0);
254
+ };
255
+ process.on("SIGINT", () => void shutdown());
256
+ process.on("SIGTERM", () => void shutdown());
257
+
258
+ startProxy(rotator, config.proxyPort, config.bindHost || "0.0.0.0");
259
+ }
260
+
261
+ // Direct execution
262
+ if (process.argv[1]?.includes("index")) {
263
+ main().catch((err) => {
264
+ console.error("Fatal startup error:", err);
265
+ process.exit(1);
266
+ });
267
+ }
@@ -0,0 +1,159 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { VirtualKey } from "./types.js";
3
+ import {
4
+ hasAnyVirtualKeys,
5
+ lookupVirtualKey,
6
+ touchVirtualKeyLastActive,
7
+ } from "./virtual-keys.js";
8
+ import { isDbConfigured } from "./db-store.js";
9
+
10
+ export interface KeyAuthResult {
11
+ authenticated: boolean;
12
+ key: VirtualKey | null;
13
+ rawKey?: string;
14
+ error?: string;
15
+ statusCode?: number;
16
+ }
17
+
18
+ /**
19
+ * Extracts virtual key raw string from headers or query parameters.
20
+ */
21
+ export function extractVirtualKey(req: IncomingMessage): string | null {
22
+ // 1. Authorization: Bearer rk-...
23
+ const authHeader = req.headers["authorization"];
24
+ if (authHeader) {
25
+ const parts = authHeader.split(" ");
26
+ if (parts.length === 2 && /^bearer$/i.test(parts[0])) {
27
+ const val = parts[1].trim();
28
+ if (val.startsWith("rk-")) return val;
29
+ }
30
+ }
31
+
32
+ // 2. Custom headers: x-rotator-key, x-api-key
33
+ const rotatorKeyHeader =
34
+ req.headers["x-rotator-key"] || req.headers["x-api-key"];
35
+ if (typeof rotatorKeyHeader === "string") {
36
+ const val = rotatorKeyHeader.trim();
37
+ if (val.startsWith("rk-")) return val;
38
+ }
39
+
40
+ // 3. Query string: ?rotator_key=rk-... or ?key=rk-...
41
+ if (req.url && req.url.includes("rk-")) {
42
+ try {
43
+ const parsedUrl = new URL(req.url, `http://${req.headers.host || "localhost"}`);
44
+ const param =
45
+ parsedUrl.searchParams.get("rotator_key") ||
46
+ parsedUrl.searchParams.get("key") ||
47
+ parsedUrl.searchParams.get("api_key");
48
+ if (param && param.startsWith("rk-")) return param.trim();
49
+ } catch {
50
+ // Ignore URL parse error
51
+ }
52
+ }
53
+
54
+ return null;
55
+ }
56
+
57
+ /**
58
+ * Validates request authentication against virtual keys.
59
+ *
60
+ * Rules:
61
+ * - If DB is not configured OR no virtual keys exist in DB, auth is not enforced.
62
+ * - If keys exist, valid key is mandatory for proxy routes.
63
+ * - Key must not be blocked.
64
+ * - If targetModel is provided and key has model scope, targetModel must be allowed.
65
+ */
66
+ export async function authenticateVirtualKey(
67
+ req: IncomingMessage,
68
+ targetModel?: string,
69
+ ): Promise<KeyAuthResult> {
70
+ const isEnforced = isDbConfigured() && (await hasAnyVirtualKeys());
71
+
72
+ const rawKey = extractVirtualKey(req);
73
+
74
+ if (!isEnforced) {
75
+ // If a key was sent anyway, try looking it up to associate spend log with key if valid
76
+ let key: VirtualKey | null = null;
77
+ if (rawKey) {
78
+ key = await lookupVirtualKey(rawKey);
79
+ }
80
+ return { authenticated: true, key, rawKey: rawKey || undefined };
81
+ }
82
+
83
+ if (!rawKey) {
84
+ return {
85
+ authenticated: false,
86
+ key: null,
87
+ error: "Virtual API Key required. Pass header 'Authorization: Bearer rk-...' or 'x-rotator-key: rk-...'",
88
+ statusCode: 401,
89
+ };
90
+ }
91
+
92
+ const key = await lookupVirtualKey(rawKey);
93
+ if (!key) {
94
+ return {
95
+ authenticated: false,
96
+ key: null,
97
+ error: "Invalid Virtual API Key",
98
+ statusCode: 401,
99
+ };
100
+ }
101
+
102
+ if (key.blocked) {
103
+ return {
104
+ authenticated: false,
105
+ key,
106
+ rawKey,
107
+ error: "Virtual API Key is blocked/disabled",
108
+ statusCode: 403,
109
+ };
110
+ }
111
+
112
+ // Model access restrictions
113
+ if (
114
+ targetModel &&
115
+ key.models &&
116
+ key.models.length > 0 &&
117
+ !key.models.includes("*")
118
+ ) {
119
+ const normalizedTarget = targetModel.toLowerCase();
120
+ const isAllowed = key.models.some(
121
+ (m) =>
122
+ m.toLowerCase() === normalizedTarget ||
123
+ normalizedTarget.includes(m.toLowerCase()),
124
+ );
125
+
126
+ if (!isAllowed) {
127
+ return {
128
+ authenticated: false,
129
+ key,
130
+ rawKey,
131
+ error: `Model '${targetModel}' is not allowed for this Virtual Key`,
132
+ statusCode: 403,
133
+ };
134
+ }
135
+ }
136
+
137
+ touchVirtualKeyLastActive(key.tokenHash);
138
+ return { authenticated: true, key, rawKey };
139
+ }
140
+
141
+ /**
142
+ * Helper to write HTTP error response for failed auth.
143
+ */
144
+ export function sendAuthErrorResponse(
145
+ res: ServerResponse,
146
+ authResult: KeyAuthResult,
147
+ ): void {
148
+ const statusCode = authResult.statusCode || 401;
149
+ res.writeHead(statusCode, { "Content-Type": "application/json" });
150
+ res.end(
151
+ JSON.stringify({
152
+ error: {
153
+ message: authResult.error || "Authentication failed",
154
+ type: statusCode === 403 ? "permission_error" : "authentication_error",
155
+ code: statusCode === 403 ? "forbidden" : "invalid_api_key",
156
+ },
157
+ }),
158
+ );
159
+ }
@@ -0,0 +1,84 @@
1
+ import { isDbConfigured, queryDb } from "./db-store.js";
2
+
3
+ /**
4
+ * Runs database migrations for virtual keys, spend logs, and daily spend aggregation tables.
5
+ * Safe to run multiple times (uses IF NOT EXISTS).
6
+ */
7
+ export async function runKeyMigrations(): Promise<void> {
8
+ if (!isDbConfigured()) return;
9
+
10
+ try {
11
+ // 1. Virtual keys table
12
+ await queryDb(`
13
+ CREATE TABLE IF NOT EXISTS rotator_virtual_keys (
14
+ token_hash VARCHAR(64) PRIMARY KEY,
15
+ key_name VARCHAR(255) NOT NULL,
16
+ key_alias VARCHAR(255) NOT NULL,
17
+ user_id VARCHAR(255),
18
+ models TEXT[],
19
+ metadata JSONB DEFAULT '{}',
20
+ blocked BOOLEAN DEFAULT FALSE,
21
+ last_active TIMESTAMPTZ,
22
+ created_at TIMESTAMPTZ DEFAULT NOW(),
23
+ created_by VARCHAR(255)
24
+ );
25
+ `);
26
+
27
+ // 2. Spend logs table
28
+ await queryDb(`
29
+ CREATE TABLE IF NOT EXISTS rotator_spend_logs (
30
+ request_id VARCHAR(64) PRIMARY KEY,
31
+ api_key_hash VARCHAR(64),
32
+ model VARCHAR(255) NOT NULL,
33
+ account_email VARCHAR(255),
34
+ call_type VARCHAR(50) NOT NULL,
35
+ status VARCHAR(20) NOT NULL,
36
+ prompt_tokens INTEGER DEFAULT 0,
37
+ completion_tokens INTEGER DEFAULT 0,
38
+ total_tokens INTEGER DEFAULT 0,
39
+ start_time TIMESTAMPTZ NOT NULL,
40
+ end_time TIMESTAMPTZ NOT NULL,
41
+ ttfb_ms INTEGER,
42
+ duration_ms INTEGER NOT NULL,
43
+ request_messages JSONB,
44
+ response_content JSONB,
45
+ metadata JSONB DEFAULT '{}',
46
+ requester_ip VARCHAR(45),
47
+ created_at TIMESTAMPTZ DEFAULT NOW()
48
+ );
49
+ `);
50
+
51
+ await queryDb(
52
+ `CREATE INDEX IF NOT EXISTS idx_spend_logs_key ON rotator_spend_logs(api_key_hash);`,
53
+ );
54
+ await queryDb(
55
+ `CREATE INDEX IF NOT EXISTS idx_spend_logs_time ON rotator_spend_logs(created_at);`,
56
+ );
57
+ await queryDb(
58
+ `CREATE INDEX IF NOT EXISTS idx_spend_logs_model ON rotator_spend_logs(model);`,
59
+ );
60
+
61
+ // 3. Daily spend aggregation table
62
+ await queryDb(`
63
+ CREATE TABLE IF NOT EXISTS rotator_daily_spend (
64
+ id SERIAL PRIMARY KEY,
65
+ api_key_hash VARCHAR(64),
66
+ model VARCHAR(255) NOT NULL,
67
+ date DATE NOT NULL,
68
+ prompt_tokens BIGINT DEFAULT 0,
69
+ completion_tokens BIGINT DEFAULT 0,
70
+ total_requests INTEGER DEFAULT 0,
71
+ successful_requests INTEGER DEFAULT 0,
72
+ failed_requests INTEGER DEFAULT 0,
73
+ total_duration_ms BIGINT DEFAULT 0,
74
+ UNIQUE(api_key_hash, model, date)
75
+ );
76
+ `);
77
+ await queryDb(
78
+ `CREATE INDEX IF NOT EXISTS idx_daily_spend_key_date ON rotator_daily_spend(api_key_hash, date);`,
79
+ );
80
+ } catch (err) {
81
+ console.error("Failed to run virtual key & spend log migrations:", err);
82
+ throw err;
83
+ }
84
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,92 @@
1
+ import { rotatorEnv } from "./env.js";
2
+
3
+ export type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
4
+
5
+ type WritableLogLevel = Exclude<LogLevel, "silent">;
6
+
7
+ const LEVEL_PRIORITY: Record<LogLevel, number> = {
8
+ debug: 10,
9
+ info: 20,
10
+ warn: 30,
11
+ error: 40,
12
+ silent: 50,
13
+ };
14
+
15
+ export interface LoggerOptions {
16
+ level?: LogLevel;
17
+ writer?: (line: string, level: WritableLogLevel) => void;
18
+ now?: () => Date;
19
+ }
20
+
21
+ export function parseLogLevel(value: string | undefined): LogLevel {
22
+ if (value === "debug" || value === "info" || value === "warn" || value === "error" || value === "silent") {
23
+ return value;
24
+ }
25
+ return "info";
26
+ }
27
+
28
+ export function shouldLog(messageLevel: WritableLogLevel, configuredLevel: LogLevel): boolean {
29
+ return LEVEL_PRIORITY[messageLevel] >= LEVEL_PRIORITY[configuredLevel];
30
+ }
31
+
32
+ export function redactSensitive(input: unknown): string {
33
+ return String(input)
34
+ .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [REDACTED]")
35
+ .replace(/(authorization["'\s:=]+)(Bearer\s+)?[A-Za-z0-9._~+/=-]+/gi, "$1[REDACTED]")
36
+ .replace(/("?(?:refresh_token|refreshToken|access_token|accessToken|client_secret|clientSecret)"?\s*[:=]\s*")[^"]+(")/gi, "$1[REDACTED]$2")
37
+ .replace(/("?(?:refresh_token|refreshToken|access_token|accessToken|client_secret|clientSecret)"?\s*[:=]\s*)[^\s,&}]+/gi, "$1[REDACTED]")
38
+ .replace(/1\/\/[A-Za-z0-9._~+/=-]+/g, "1//[REDACTED]")
39
+ // Redact sensitive keys when they appear as querystring parameters (?key=val&...)
40
+ // or as path segments. Matches both with and without surrounding quotes/encoding.
41
+ .replace(/([?&](?:access_token|accessToken|refresh_token|refreshToken|token|api_key|apikey|key)=)[^&\s#]+/gi, "$1[REDACTED]")
42
+ // Redact when the key is followed by = and a value in a query-like context
43
+ .replace(/(\?|&)(token|access_token|accessToken|refresh_token|refreshToken|api_key|apikey|key)=([^&\s#]+)/gi, "$1$2=[REDACTED]");
44
+ }
45
+
46
+ export class Logger {
47
+ private readonly level: LogLevel;
48
+ private readonly writer: (line: string, level: WritableLogLevel) => void;
49
+ private readonly now: () => Date;
50
+
51
+ constructor(options: LoggerOptions = {}) {
52
+ this.level = options.level ?? parseLogLevel(rotatorEnv("LOG_LEVEL"));
53
+ this.writer = options.writer ?? ((line) => console.log(line));
54
+ this.now = options.now ?? (() => new Date());
55
+ }
56
+
57
+ child(scope: string): ScopedLogger {
58
+ return new ScopedLogger(this, scope);
59
+ }
60
+
61
+ log(level: WritableLogLevel, scope: string, message: unknown): void {
62
+ if (!shouldLog(level, this.level)) return;
63
+ const ts = this.now().toISOString().slice(11, 19);
64
+ this.writer(`[${ts}] [${scope}] ${redactSensitive(message)}`, level);
65
+ }
66
+ }
67
+
68
+ export class ScopedLogger {
69
+ constructor(private readonly logger: Logger, private readonly scope: string) {}
70
+
71
+ debug(message: unknown): void {
72
+ this.logger.log("debug", this.scope, message);
73
+ }
74
+
75
+ info(message: unknown): void {
76
+ this.logger.log("info", this.scope, message);
77
+ }
78
+
79
+ warn(message: unknown): void {
80
+ this.logger.log("warn", this.scope, message);
81
+ }
82
+
83
+ error(message: unknown): void {
84
+ this.logger.log("error", this.scope, message);
85
+ }
86
+
87
+ log(level: WritableLogLevel, message: unknown): void {
88
+ this.logger.log(level, this.scope, message);
89
+ }
90
+ }
91
+
92
+ export const logger = new Logger();
package/src/login.ts ADDED
@@ -0,0 +1,48 @@
1
+ // Generic login orchestrator: delegates the interactive flow to the selected
2
+ // provider adapter and persists the resulting account.
3
+ // Usage: npm run login [--provider <id>] (default: google-antigravity)
4
+
5
+ import {
6
+ addAccountToConfig,
7
+ ensurePiAuthConfig,
8
+ ensurePiModelsConfig,
9
+ loadOrCreateAccountsConfig,
10
+ } from "./account-store.js";
11
+ import type { AccountConfig } from "./types.js";
12
+ import { getAccountsPath } from "./paths.js";
13
+ import { getProviderAdapter, DEFAULT_PROVIDER } from "./providers/registry.js";
14
+
15
+ const ACCOUNTS_FILE = getAccountsPath();
16
+
17
+ export async function runLogin(providerId?: string): Promise<void> {
18
+ const provider = providerId || DEFAULT_PROVIDER;
19
+ const adapter = getProviderAdapter(provider);
20
+
21
+ console.log(`Adding a ${adapter.displayName} account via ${adapter.credentialKind} flow.`);
22
+
23
+ const entry: AccountConfig = await adapter.runLogin();
24
+ entry.provider = provider;
25
+
26
+ const { isNew } = await addAccountToConfig(entry);
27
+ console.log(` ${isNew ? "Added" : "Updated"} ${entry.email} in ${ACCOUNTS_FILE}`);
28
+
29
+ // The Google flow also keeps the Pi IDE config in sync.
30
+ if (provider === "google-antigravity") {
31
+ await ensurePiModelsConfig();
32
+ await ensurePiAuthConfig();
33
+ }
34
+
35
+ const config = loadOrCreateAccountsConfig();
36
+ console.log();
37
+ console.log(`Done. ${config.accounts.length} account(s) configured:`);
38
+ for (const a of config.accounts) {
39
+ const providers =
40
+ (a.credentials ?? [])
41
+ .map((c) => c.provider)
42
+ .join("+") || a.provider ||
43
+ DEFAULT_PROVIDER;
44
+ console.log(` ${a.label || a.email} (${a.email}) [${providers}]`);
45
+ }
46
+ console.log();
47
+ console.log("Run 'npm start' to start the proxy.");
48
+ }