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
@@ -0,0 +1,754 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { addAccountToConfig } from "./account-store.js";
3
+ import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
4
+ import {
5
+ buildAuthUrl,
6
+ discoverProject,
7
+ exchangeAuthorizationCode,
8
+ generatePkce,
9
+ generateState,
10
+ getOAuthClientConfig,
11
+ getUserEmail,
12
+ isHostedOAuthConfigured,
13
+ } from "./providers/google-antigravity/oauth.js";
14
+ import {
15
+ defaultAccountEmail,
16
+ validateApiKey,
17
+ } from "./providers/ollama/api-key-validation.js";
18
+ import type { AccountConfig } from "./types.js";
19
+
20
+ interface AccountSink {
21
+ addOrUpdateAccount(account: AccountConfig): Promise<void>;
22
+ }
23
+
24
+ interface PendingSession {
25
+ verifier: string;
26
+ createdAt: number;
27
+ }
28
+
29
+ const pendingSessions = new Map<string, PendingSession>();
30
+ const SESSION_TTL_MS = 15 * 60 * 1000;
31
+ const SESSION_PRUNE_INTERVAL_MS = 5 * 60 * 1000;
32
+ const MAX_CLI_LOGIN_BODY_BYTES = 64 * 1024;
33
+
34
+ function escapeHtml(value: unknown): string {
35
+ return String(value)
36
+ .replace(/&/g, "&amp;")
37
+ .replace(/</g, "&lt;")
38
+ .replace(/>/g, "&gt;")
39
+ .replace(/"/g, "&quot;")
40
+ .replace(/'/g, "&#39;");
41
+ }
42
+
43
+ function prunePendingSessions(): void {
44
+ const cutoff = Date.now() - SESSION_TTL_MS;
45
+ for (const [state, session] of pendingSessions.entries()) {
46
+ if (session.createdAt < cutoff) {
47
+ pendingSessions.delete(state);
48
+ }
49
+ }
50
+ }
51
+
52
+ // Background reaper. Without this, a long-lived proxy that never sees
53
+ // /auth/antigravity/start or /callback would accumulate stale sessions
54
+ // (each is a 96-byte PKCE verifier + timestamp). The interval is unref'd
55
+ // so it does not block process exit.
56
+ let pruneTimer: ReturnType<typeof setInterval> | null = null;
57
+ function startPendingSessionReaper(): void {
58
+ if (pruneTimer) return;
59
+ pruneTimer = setInterval(
60
+ () => prunePendingSessions(),
61
+ SESSION_PRUNE_INTERVAL_MS,
62
+ );
63
+ if (pruneTimer.unref) pruneTimer.unref();
64
+ }
65
+ export function stopPendingSessionReaper(): void {
66
+ if (pruneTimer) {
67
+ clearInterval(pruneTimer);
68
+ pruneTimer = null;
69
+ }
70
+ }
71
+ startPendingSessionReaper();
72
+
73
+ function renderPage(title: string, body: string): string {
74
+ return `<!DOCTYPE html>
75
+ <html lang="en">
76
+ <head>
77
+ <meta charset="utf-8">
78
+ <meta name="viewport" content="width=device-width, initial-scale=1">
79
+ <title>${escapeHtml(title)}</title>
80
+ <style>
81
+ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;700&family=IBM+Plex+Mono:wght@400;500&display=swap');
82
+ :root {
83
+ --bg: #f4efe6;
84
+ --ink: #1f2a1f;
85
+ --muted: #5b6659;
86
+ --card: rgba(255,255,255,0.8);
87
+ --line: rgba(31,42,31,0.12);
88
+ --accent: #1e6b52;
89
+ --accent-2: #d99058;
90
+ --warn: #9a4b3f;
91
+ }
92
+ * { box-sizing: border-box; }
93
+ body {
94
+ margin: 0;
95
+ min-height: 100vh;
96
+ font-family: 'Space Grotesk', system-ui, sans-serif;
97
+ color: var(--ink);
98
+ background:
99
+ radial-gradient(circle at top left, rgba(217,144,88,0.28), transparent 32%),
100
+ radial-gradient(circle at bottom right, rgba(30,107,82,0.22), transparent 28%),
101
+ linear-gradient(160deg, #f7f1e8, #efe5d6 52%, #e9ddcb);
102
+ display: grid;
103
+ place-items: center;
104
+ padding: 24px;
105
+ }
106
+ .card {
107
+ width: min(760px, 100%);
108
+ background: var(--card);
109
+ backdrop-filter: blur(14px);
110
+ border: 1px solid var(--line);
111
+ border-radius: 24px;
112
+ padding: 28px;
113
+ box-shadow: 0 20px 80px rgba(31, 42, 31, 0.08);
114
+ }
115
+ h1 {
116
+ margin: 0 0 10px;
117
+ font-size: clamp(32px, 6vw, 56px);
118
+ line-height: 0.96;
119
+ letter-spacing: -0.04em;
120
+ }
121
+ p, li {
122
+ font-size: 16px;
123
+ line-height: 1.6;
124
+ color: var(--muted);
125
+ }
126
+ .mono {
127
+ font-family: 'IBM Plex Mono', monospace;
128
+ font-size: 13px;
129
+ color: var(--ink);
130
+ background: rgba(31,42,31,0.05);
131
+ border: 1px solid rgba(31,42,31,0.08);
132
+ border-radius: 12px;
133
+ padding: 12px 14px;
134
+ overflow-wrap: anywhere;
135
+ }
136
+ .cta {
137
+ display: inline-flex;
138
+ align-items: center;
139
+ justify-content: center;
140
+ margin-top: 18px;
141
+ padding: 14px 20px;
142
+ border-radius: 999px;
143
+ background: var(--accent);
144
+ color: white;
145
+ text-decoration: none;
146
+ font-weight: 700;
147
+ box-shadow: 0 12px 30px rgba(30,107,82,0.22);
148
+ }
149
+ .cta:hover { background: #185843; }
150
+ .note {
151
+ margin-top: 18px;
152
+ padding: 14px 16px;
153
+ border-left: 4px solid var(--accent-2);
154
+ background: rgba(217,144,88,0.12);
155
+ border-radius: 12px;
156
+ }
157
+ .error {
158
+ border-left-color: var(--warn);
159
+ background: rgba(154,75,63,0.12);
160
+ }
161
+ ul {
162
+ padding-left: 18px;
163
+ margin: 16px 0 0;
164
+ }
165
+ .field {
166
+ width: 100%;
167
+ margin-top: 12px;
168
+ font-family: 'IBM Plex Mono', monospace;
169
+ font-size: 13px;
170
+ padding: 12px 14px;
171
+ border-radius: 12px;
172
+ border: 1px solid var(--line);
173
+ background: rgba(31,42,31,0.03);
174
+ }
175
+ label {
176
+ display: block;
177
+ margin-top: 14px;
178
+ font-size: 14px;
179
+ font-weight: 600;
180
+ color: var(--ink);
181
+ }
182
+ .tabs {
183
+ display: flex;
184
+ gap: 8px;
185
+ margin: 20px 0 4px;
186
+ flex-wrap: wrap;
187
+ }
188
+ .tab {
189
+ padding: 10px 16px;
190
+ border-radius: 999px;
191
+ border: 1px solid var(--line);
192
+ background: rgba(31,42,31,0.04);
193
+ color: var(--muted);
194
+ font-family: inherit;
195
+ font-size: 14px;
196
+ font-weight: 600;
197
+ cursor: pointer;
198
+ }
199
+ .tab.active {
200
+ background: var(--accent);
201
+ border-color: var(--accent);
202
+ color: white;
203
+ }
204
+ .panel { display: none; }
205
+ .panel.active { display: block; }
206
+ </style>
207
+ </head>
208
+ <body>
209
+ <main class="card">
210
+ ${body}
211
+ </main>
212
+ </body>
213
+ </html>`;
214
+ }
215
+
216
+ export function serveLoginLanding(res: ServerResponse): void {
217
+ const hostedReady = isHostedOAuthConfigured();
218
+ const oauth = hostedReady ? getOAuthClientConfig() : null;
219
+ const message = hostedReady
220
+ ? `<p>This page starts the Antigravity sign-in flow and returns here automatically so the account can be added to this rotator.</p>
221
+ <p class="mono">Configured callback: ${escapeHtml(oauth?.redirectUri)}</p>
222
+ <div class="note">Signing in here grants this server a refresh token for the selected Google account. That allows the rotator to keep using that account until access is revoked.</div>
223
+ <a class="cta" href="/auth/antigravity/start">Continue With Google</a>`
224
+ : `<p>This server is not yet configured for hosted OAuth.</p>
225
+ <p class="mono">Set ANTIGRAVITY_REDIRECT_URI, and usually ANTIGRAVITY_CLIENT_ID plus ANTIGRAVITY_CLIENT_SECRET, to a public callback URL registered with the OAuth client.</p>
226
+ <div class="note error">The current redirect is still loopback-only, so the transparent public callback cannot complete yet.</div>`;
227
+
228
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
229
+ res.end(
230
+ renderPage("Antigravity Login", `<h1>Connect Your Account</h1>${message}`),
231
+ );
232
+ }
233
+
234
+ export function startHostedLogin(
235
+ req: IncomingMessage,
236
+ res: ServerResponse,
237
+ ): void {
238
+ if (!isHostedOAuthConfigured()) {
239
+ res.writeHead(409, { "Content-Type": "text/html; charset=utf-8" });
240
+ res.end(
241
+ renderPage(
242
+ "Hosted OAuth Not Configured",
243
+ "<h1>Hosted Login Isn’t Ready</h1><p>This server still uses a loopback redirect URI. Configure a public redirect before sharing this page.</p>",
244
+ ),
245
+ );
246
+ return;
247
+ }
248
+
249
+ prunePendingSessions();
250
+ const { verifier, challenge } = generatePkce();
251
+ const state = generateState();
252
+ pendingSessions.set(state, { verifier, createdAt: Date.now() });
253
+
254
+ const authUrl = buildAuthUrl(state, challenge);
255
+ res.writeHead(302, { Location: authUrl });
256
+ res.end();
257
+ }
258
+
259
+ // ── Web-based CLI login (/login-cli) ──────────────────────────────────────────
260
+ // Replicates the CLI login flow in the browser: shows the Google OAuth URL,
261
+ // user signs in and pastes the redirect URL back, server exchanges the code.
262
+
263
+ interface CliLoginSession {
264
+ verifier: string;
265
+ challenge: string;
266
+ oauthState: string;
267
+ authUrl: string;
268
+ createdAt: number;
269
+ }
270
+
271
+ const cliLoginSessions = new Map<string, CliLoginSession>();
272
+
273
+ function pruneCliSessions(): void {
274
+ const cutoff = Date.now() - SESSION_TTL_MS;
275
+ for (const [id, session] of cliLoginSessions.entries()) {
276
+ if (session.createdAt < cutoff) {
277
+ cliLoginSessions.delete(id);
278
+ }
279
+ }
280
+ }
281
+
282
+ export function serveCliLogin(res: ServerResponse): void {
283
+ pruneCliSessions();
284
+ const { verifier, challenge } = generatePkce();
285
+ const oauthState = generateState();
286
+ let authUrl: string;
287
+ try {
288
+ authUrl = buildAuthUrl(oauthState, challenge);
289
+ } catch (err) {
290
+ res.writeHead(503, { "Content-Type": "text/html; charset=utf-8" });
291
+ res.end(
292
+ renderPage(
293
+ "OAuth Not Configured",
294
+ `<h1>OAuth Login Isn’t Ready</h1><p>${escapeHtml(err instanceof Error ? err.message : String(err))}</p>`,
295
+ ),
296
+ );
297
+ return;
298
+ }
299
+ const sessionId = generateState();
300
+ cliLoginSessions.set(sessionId, {
301
+ verifier,
302
+ challenge,
303
+ oauthState,
304
+ authUrl,
305
+ createdAt: Date.now(),
306
+ });
307
+
308
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
309
+ res.end(
310
+ renderPage(
311
+ "Add Account",
312
+ `<h1>Add Account</h1>
313
+ <p>This page works like the CLI login. Pick a provider below and follow the steps to add an account to the rotator.</p>
314
+
315
+ <div class="tabs">
316
+ <button class="tab active" data-panel="panel-google">Google (Antigravity)</button>
317
+ <button class="tab" data-panel="panel-ollama">Ollama Cloud</button>
318
+ </div>
319
+
320
+ <div class="panel active" id="panel-google">
321
+ <h3 style="margin:24px 0 8px;font-size:18px;">Step 1 &mdash; Sign in with Google</h3>
322
+ <p>Click the button below to open the Google sign-in page in a new tab:</p>
323
+ <a class="cta" href="${escapeHtml(authUrl)}" target="_blank" rel="noopener" style="font-size:16px;">
324
+ Sign in with Google &nearr;
325
+ </a>
326
+
327
+ <h3 style="margin:24px 0 8px;font-size:18px;">Step 2 &mdash; Paste the redirect URL</h3>
328
+ <p>After signing in, Google will redirect to <code>localhost</code> (which will fail — that's expected). Copy the <strong>full URL</strong> from your browser's address bar and paste it here:</p>
329
+ <form id="pasteForm" style="margin-top:12px;">
330
+ <input type="hidden" name="session" value="${escapeHtml(sessionId)}" />
331
+ <textarea name="redirectUrl" rows="4" placeholder="Paste the redirect URL here (starts with http://localhost:51121/oauth-callback?...)" style="
332
+ width:100%;font-family:'IBM Plex Mono',monospace;font-size:13px;
333
+ padding:12px 14px;border-radius:12px;border:1px solid rgba(31,42,31,0.15);
334
+ background:rgba(31,42,31,0.03);resize:vertical;
335
+ "></textarea>
336
+ <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:12px;">
337
+ Connect Account
338
+ </button>
339
+ </form>
340
+ </div>
341
+
342
+ <div class="panel" id="panel-ollama">
343
+ <p>Paste an Ollama Cloud API key to add the account to this rotator. The key is validated against ollama.com before saving.</p>
344
+ <p class="mono">Create a key at https://ollama.com/settings/keys</p>
345
+ <form id="keyForm" style="margin-top:12px;">
346
+ <label for="email">Account identifier (email or label)</label>
347
+ <input id="email" name="email" class="field" placeholder="me@example.com (optional)" autocomplete="off" />
348
+ <label for="apiKey">Ollama API key</label>
349
+ <input id="apiKey" name="apiKey" class="field" type="password" placeholder="ollama-..." autocomplete="off" required />
350
+ <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:12px;">
351
+ Connect Account
352
+ </button>
353
+ </form>
354
+ </div>
355
+
356
+ <div id="result" style="margin-top:18px;"></div>
357
+
358
+ <script>
359
+ document.querySelectorAll('.tab').forEach((tab) => {
360
+ tab.addEventListener('click', () => {
361
+ document.querySelectorAll('.tab').forEach((t) => t.classList.toggle('active', t === tab));
362
+ document.querySelectorAll('.panel').forEach((p) => p.classList.toggle('active', p.id === tab.dataset.panel));
363
+ });
364
+ });
365
+
366
+ function showResult(html) {
367
+ document.getElementById('result').innerHTML = html;
368
+ }
369
+
370
+ document.getElementById('pasteForm').addEventListener('submit', async (e) => {
371
+ e.preventDefault();
372
+ const form = e.target;
373
+ const btn = form.querySelector('button[type=submit]');
374
+ const resultDiv = document.getElementById('result');
375
+ const redirectUrl = form.redirectUrl.value.trim();
376
+ const session = form.session.value;
377
+ if (!redirectUrl) { showResult('<div class="note error">Please paste the redirect URL.</div>'); return; }
378
+ btn.disabled = true;
379
+ btn.textContent = 'Connecting...';
380
+ showResult('<div class="note">Exchanging code for tokens...</div>');
381
+ try {
382
+ const params = new URLSearchParams(window.location.search);
383
+ const token = params.get('token') || '';
384
+ const res = await fetch('/api/cli-login', {
385
+ method: 'POST',
386
+ headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
387
+ body: JSON.stringify({ provider: 'google-antigravity', session, redirectUrl }),
388
+ });
389
+ const data = await res.json();
390
+ if (data.ok) {
391
+ showResult('<div class="note" style="border-left-color:var(--accent);background:rgba(30,107,82,0.12);">' +
392
+ '<strong id="loginResultEmail"></strong> ' + (data.isNew ? 'added' : 'updated') + ' successfully.<br>' +
393
+ 'Project: <span id="loginResultProject" class="mono" style="padding:2px 6px;"></span>' +
394
+ '</div>');
395
+ document.getElementById('loginResultEmail').textContent = data.email || '';
396
+ document.getElementById('loginResultProject').textContent = data.projectId || '';
397
+ } else {
398
+ var errorDiv = document.createElement('div');
399
+ errorDiv.className = 'note error';
400
+ errorDiv.textContent = data.error || 'Unknown error';
401
+ resultDiv.innerHTML = '';
402
+ resultDiv.appendChild(errorDiv);
403
+ }
404
+ } catch (err) {
405
+ var errDiv = document.createElement('div');
406
+ errDiv.className = 'note error';
407
+ errDiv.textContent = 'Request failed: ' + err.message;
408
+ resultDiv.innerHTML = '';
409
+ resultDiv.appendChild(errDiv);
410
+ } finally {
411
+ btn.disabled = false;
412
+ btn.textContent = 'Connect Account';
413
+ }
414
+ });
415
+
416
+ document.getElementById('keyForm').addEventListener('submit', async (e) => {
417
+ e.preventDefault();
418
+ const form = e.target;
419
+ const btn = form.querySelector('button[type=submit]');
420
+ const apiKey = form.apiKey.value.trim();
421
+ const email = form.email.value.trim();
422
+ if (!apiKey) { showResult('<div class="note error">Please paste an API key.</div>'); return; }
423
+ btn.disabled = true;
424
+ btn.textContent = 'Validating...';
425
+ showResult('<div class="note">Checking the key against ollama.com...</div>');
426
+ try {
427
+ const params = new URLSearchParams(window.location.search);
428
+ const token = params.get('token') || '';
429
+ const res = await fetch('/api/cli-login', {
430
+ method: 'POST',
431
+ headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
432
+ body: JSON.stringify({ provider: 'ollama', email, apiKey }),
433
+ });
434
+ const data = await res.json();
435
+ if (data.ok) {
436
+ showResult('<div class="note" style="border-left-color:var(--accent);background:rgba(30,107,82,0.12);">' +
437
+ '<strong>' + (data.email || '') + '</strong> ' + (data.isNew ? 'added' : 'updated') + ' successfully. The rotator will start using it on the next poll.</div>');
438
+ } else {
439
+ var keyErrDiv = document.createElement('div');
440
+ keyErrDiv.className = 'note error';
441
+ keyErrDiv.textContent = data.error || 'Unknown error';
442
+ document.getElementById('result').innerHTML = '';
443
+ document.getElementById('result').appendChild(keyErrDiv);
444
+ }
445
+ } catch (err) {
446
+ var keyErr2 = document.createElement('div');
447
+ keyErr2.className = 'note error';
448
+ keyErr2.textContent = 'Request failed: ' + err.message;
449
+ document.getElementById('result').innerHTML = '';
450
+ document.getElementById('result').appendChild(keyErr2);
451
+ } finally {
452
+ btn.disabled = false;
453
+ btn.textContent = 'Connect Account';
454
+ }
455
+ });
456
+ </script>
457
+ `,
458
+ ),
459
+ );
460
+ }
461
+
462
+ export async function handleCliLoginApi(
463
+ req: IncomingMessage,
464
+ res: ServerResponse,
465
+ rotator: AccountSink,
466
+ ): Promise<void> {
467
+ let body: {
468
+ provider?: string;
469
+ session?: string;
470
+ redirectUrl?: string;
471
+ email?: string;
472
+ apiKey?: string;
473
+ };
474
+ try {
475
+ const raw = await readLimitedBody(req, MAX_CLI_LOGIN_BODY_BYTES);
476
+ const parsed: unknown = JSON.parse(raw.toString("utf-8"));
477
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
478
+ throw new Error("Request body must be an object");
479
+ }
480
+ body = parsed as {
481
+ provider?: string;
482
+ session?: string;
483
+ redirectUrl?: string;
484
+ email?: string;
485
+ apiKey?: string;
486
+ };
487
+ } catch (err) {
488
+ res.writeHead(err instanceof PayloadTooLargeError ? 413 : 400, {
489
+ "Content-Type": "application/json",
490
+ });
491
+ res.end(JSON.stringify({ ok: false, error: "Invalid JSON body" }));
492
+ return;
493
+ }
494
+
495
+ const provider = body.provider || "google-antigravity";
496
+
497
+ if (provider === "ollama") {
498
+ await handleOllamaCliLogin(body, res, rotator);
499
+ return;
500
+ }
501
+
502
+ if (provider !== "google-antigravity") {
503
+ res.writeHead(400, { "Content-Type": "application/json" });
504
+ res.end(JSON.stringify({ ok: false, error: `Unknown provider "${provider}"` }));
505
+ return;
506
+ }
507
+
508
+ const { session: sessionId, redirectUrl } = body;
509
+ if (
510
+ typeof sessionId !== "string" ||
511
+ typeof redirectUrl !== "string" ||
512
+ sessionId.length === 0 ||
513
+ redirectUrl.length === 0 ||
514
+ sessionId.length > 256 ||
515
+ redirectUrl.length > 8 * 1024
516
+ ) {
517
+ res.writeHead(400, { "Content-Type": "application/json" });
518
+ res.end(
519
+ JSON.stringify({ ok: false, error: "Missing session or redirectUrl" }),
520
+ );
521
+ return;
522
+ }
523
+
524
+ pruneCliSessions();
525
+ const session = cliLoginSessions.get(sessionId);
526
+ if (!session) {
527
+ res.writeHead(400, { "Content-Type": "application/json" });
528
+ res.end(
529
+ JSON.stringify({
530
+ ok: false,
531
+ error: "Session expired or invalid. Reload the page and try again.",
532
+ }),
533
+ );
534
+ return;
535
+ }
536
+
537
+ // Parse the redirect URL to extract code
538
+ let code: string | undefined;
539
+ let state: string | null;
540
+ try {
541
+ const url = new URL(redirectUrl.trim());
542
+ code = url.searchParams.get("code") ?? undefined;
543
+ state = url.searchParams.get("state");
544
+ } catch {
545
+ res.writeHead(400, { "Content-Type": "application/json" });
546
+ res.end(
547
+ JSON.stringify({
548
+ ok: false,
549
+ error:
550
+ "Could not parse the URL. Make sure you pasted the full redirect URL.",
551
+ }),
552
+ );
553
+ return;
554
+ }
555
+
556
+ if (!code) {
557
+ res.writeHead(400, { "Content-Type": "application/json" });
558
+ res.end(
559
+ JSON.stringify({
560
+ ok: false,
561
+ error: "No authorization code found in the URL.",
562
+ }),
563
+ );
564
+ return;
565
+ }
566
+ if (state !== session.oauthState) {
567
+ res.writeHead(400, { "Content-Type": "application/json" });
568
+ res.end(
569
+ JSON.stringify({
570
+ ok: false,
571
+ error: "State mismatch - reload the login page and try again.",
572
+ }),
573
+ );
574
+ return;
575
+ }
576
+
577
+ cliLoginSessions.delete(sessionId);
578
+
579
+ try {
580
+ const tokenData = await exchangeAuthorizationCode(code, session.verifier);
581
+ const email = await getUserEmail(tokenData.accessToken);
582
+ const project = await discoverProject(tokenData.accessToken);
583
+ const label = email ? email.split("@")[0] : "Account";
584
+ const entry = {
585
+ email: email || "unknown@gmail.com",
586
+ refreshToken: tokenData.refreshToken,
587
+ projectId: project.projectId,
588
+ projectSource: project.source,
589
+ label,
590
+ };
591
+
592
+ const { isNew } = await addAccountToConfig(entry);
593
+ await rotator.addOrUpdateAccount(entry);
594
+
595
+ res.writeHead(200, { "Content-Type": "application/json" });
596
+ res.end(
597
+ JSON.stringify({
598
+ ok: true,
599
+ email: entry.email,
600
+ isNew,
601
+ projectId: project.projectId,
602
+ }),
603
+ );
604
+ } catch {
605
+ res.writeHead(500, { "Content-Type": "application/json" });
606
+ res.end(
607
+ JSON.stringify({
608
+ ok: false,
609
+ error: "Unable to complete login. Please try again.",
610
+ }),
611
+ );
612
+ }
613
+ }
614
+
615
+ const MAX_ACCOUNT_EMAIL_LENGTH = 320;
616
+ const MAX_ACCOUNT_LABEL_LENGTH = 200;
617
+
618
+ async function handleOllamaCliLogin(
619
+ body: { email?: string; apiKey?: string },
620
+ res: ServerResponse,
621
+ rotator: AccountSink,
622
+ ): Promise<void> {
623
+ const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
624
+ const email = typeof body.email === "string" ? body.email.trim() : "";
625
+
626
+ if (!apiKey) {
627
+ res.writeHead(400, { "Content-Type": "application/json" });
628
+ res.end(JSON.stringify({ ok: false, error: "Missing apiKey" }));
629
+ return;
630
+ }
631
+ if (apiKey.length > 4096) {
632
+ res.writeHead(400, { "Content-Type": "application/json" });
633
+ res.end(JSON.stringify({ ok: false, error: "API key too long" }));
634
+ return;
635
+ }
636
+ if (email.length > MAX_ACCOUNT_EMAIL_LENGTH) {
637
+ res.writeHead(400, { "Content-Type": "application/json" });
638
+ res.end(JSON.stringify({ ok: false, error: "Account identifier too long" }));
639
+ return;
640
+ }
641
+
642
+ const validation = await validateApiKey(apiKey);
643
+ if (!validation.ok) {
644
+ res.writeHead(400, { "Content-Type": "application/json" });
645
+ res.end(
646
+ JSON.stringify({
647
+ ok: false,
648
+ error: `Key rejected (${validation.status}): ${validation.error}`,
649
+ }),
650
+ );
651
+ return;
652
+ }
653
+
654
+ const entry = {
655
+ email: email || defaultAccountEmail(apiKey),
656
+ apiKey,
657
+ label: email || defaultAccountEmail(apiKey).split("@")[0],
658
+ };
659
+ if (entry.label.length > MAX_ACCOUNT_LABEL_LENGTH) {
660
+ res.writeHead(400, { "Content-Type": "application/json" });
661
+ res.end(JSON.stringify({ ok: false, error: "Account label too long" }));
662
+ return;
663
+ }
664
+
665
+ const { isNew } = await addAccountToConfig(entry);
666
+ await rotator.addOrUpdateAccount(entry);
667
+
668
+ res.writeHead(200, { "Content-Type": "application/json" });
669
+ res.end(JSON.stringify({ ok: true, email: entry.email, isNew }));
670
+ }
671
+
672
+ export async function handleHostedCallback(
673
+ req: IncomingMessage,
674
+ res: ServerResponse,
675
+ rotator: AccountSink,
676
+ ): Promise<void> {
677
+ const requestUrl = new URL(req.url || "/", "http://localhost");
678
+ const code = requestUrl.searchParams.get("code");
679
+ const state = requestUrl.searchParams.get("state");
680
+ const error = requestUrl.searchParams.get("error");
681
+
682
+ if (error) {
683
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
684
+ res.end(
685
+ renderPage(
686
+ "Sign-In Cancelled",
687
+ `<h1>Sign-In Cancelled</h1><p>Google returned: ${escapeHtml(error)}</p>`,
688
+ ),
689
+ );
690
+ return;
691
+ }
692
+
693
+ if (!code || !state) {
694
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
695
+ res.end(
696
+ renderPage(
697
+ "Missing Parameters",
698
+ "<h1>Missing Parameters</h1><p>The callback did not include a valid code and state.</p>",
699
+ ),
700
+ );
701
+ return;
702
+ }
703
+
704
+ prunePendingSessions();
705
+ const session = pendingSessions.get(state);
706
+ if (!session) {
707
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
708
+ res.end(
709
+ renderPage(
710
+ "Session Expired",
711
+ "<h1>Session Expired</h1><p>This sign-in session is no longer valid. Start again from the login page.</p>",
712
+ ),
713
+ );
714
+ return;
715
+ }
716
+ pendingSessions.delete(state);
717
+
718
+ try {
719
+ const tokenData = await exchangeAuthorizationCode(code, session.verifier);
720
+ const email = await getUserEmail(tokenData.accessToken);
721
+ const project = await discoverProject(tokenData.accessToken);
722
+ const label = email ? email.split("@")[0] : "Account";
723
+ const entry = {
724
+ email: email || "unknown@gmail.com",
725
+ refreshToken: tokenData.refreshToken,
726
+ projectId: project.projectId,
727
+ projectSource: project.source,
728
+ label,
729
+ };
730
+
731
+ const { isNew } = await addAccountToConfig(entry);
732
+ await rotator.addOrUpdateAccount(entry);
733
+
734
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
735
+ res.end(
736
+ renderPage(
737
+ "Account Connected",
738
+ `<h1>Account Connected</h1>
739
+ <p><strong>${escapeHtml(entry.email)}</strong> was ${isNew ? "added" : "updated"} successfully.</p>
740
+ <p>Project: <span class="mono">${escapeHtml(project.projectId)}</span> via ${escapeHtml(project.source)}.</p>
741
+ <p>The rotator can start using this account immediately.</p>
742
+ <div class="note">If you ever want to stop sharing access, revoke this app's access from the Google account security settings.</div>`,
743
+ ),
744
+ );
745
+ } catch (err) {
746
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
747
+ res.end(
748
+ renderPage(
749
+ "Sign-In Failed",
750
+ `<h1>Sign-In Failed</h1><p>${escapeHtml(err instanceof Error ? err.message : String(err))}</p>`,
751
+ ),
752
+ );
753
+ }
754
+ }