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,327 @@
1
+ // Repository pattern for rotator settings persistence.
2
+ //
3
+ // Two implementations:
4
+ // PostgresSettingsRepository — backed by a `rotator_settings` table
5
+ // FileSettingsRepository — backed by JSON files on disk
6
+
7
+ import pg from "pg";
8
+ import { chmod } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ import { getConfigDir } from "./paths.js";
11
+ import { rotatorEnv } from "./env.js";
12
+ import {
13
+ backupFile,
14
+ readTextFile,
15
+ writeJsonFileAtomic,
16
+ writeTextFileAtomic,
17
+ } from "./storage.js";
18
+
19
+ const { Pool } = pg;
20
+
21
+ /**
22
+ * Generic key-value settings repository.
23
+ *
24
+ * Callers use string keys; the values are opaque strings (typically
25
+ * JSON-serialized objects). Both implementations guarantee that `get()`
26
+ * always returns the latest value set via `set()` (in-process consistency).
27
+ */
28
+ export interface ISettingsRepository {
29
+ /** Initialize the repository (create table / load from disk) */
30
+ init(): Promise<void>;
31
+
32
+ /** Get a value by key */
33
+ get(key: string): string | null;
34
+
35
+ /** Persist a value by key */
36
+ set(key: string, value: string): Promise<void>;
37
+
38
+ /** Close connections / flush pending writes */
39
+ close(): Promise<void>;
40
+ }
41
+
42
+ // ----- Key → disk-file mapping -----
43
+
44
+ interface DiskFileSpec {
45
+ filename: string;
46
+ /** Whether to back up the file before overwriting */
47
+ backup: boolean;
48
+ /** Whether to trim whitespace on read (e.g. admin_token) */
49
+ trim: boolean;
50
+ /** File mode to set after writing (e.g. 0o600 for secrets) */
51
+ mode?: number;
52
+ }
53
+
54
+ const DISK_FILES: Record<string, DiskFileSpec> = {
55
+ accounts_json: { filename: "accounts.json", backup: true, trim: false },
56
+ admin_token: {
57
+ filename: ".admin-token",
58
+ backup: false,
59
+ trim: true,
60
+ mode: 0o600,
61
+ },
62
+ rotator_state: { filename: "state.json", backup: true, trim: false },
63
+ token_usage: { filename: "token-usage.json", backup: false, trim: false },
64
+ responses_store: { filename: "responses.json", backup: false, trim: false },
65
+ };
66
+
67
+ function diskPath(key: string): string | null {
68
+ const spec = DISK_FILES[key];
69
+ if (!spec) return null;
70
+ return join(getConfigDir(), spec.filename);
71
+ }
72
+
73
+ // ----- PostgresSettingsRepository -----
74
+
75
+ const RETRY_DELAY_MS = 5_000;
76
+ const MAX_RETRIES = 3;
77
+
78
+ interface PendingWrite {
79
+ value: string;
80
+ attempts: number;
81
+ }
82
+
83
+ export class PostgresSettingsRepository implements ISettingsRepository {
84
+ private pool: pg.Pool | null = null;
85
+ private cache = new Map<string, string>();
86
+ private initialized = false;
87
+ private pendingRetries = new Map<string, PendingWrite>();
88
+ private retryTimer: ReturnType<typeof setTimeout> | null = null;
89
+
90
+ async init(): Promise<void> {
91
+ if (this.initialized) return;
92
+
93
+ const connectionString =
94
+ rotatorEnv("DATABASE_URL") || process.env.DATABASE_URL;
95
+ this.pool = new Pool({
96
+ connectionString,
97
+ ssl:
98
+ connectionString?.includes("sslmode=require") ||
99
+ connectionString?.includes("ssl=")
100
+ ? { rejectUnauthorized: false }
101
+ : undefined,
102
+ });
103
+
104
+ // Create table if it doesn't exist
105
+ await this.pool.query(`
106
+ CREATE TABLE IF NOT EXISTS rotator_settings (
107
+ key VARCHAR(255) PRIMARY KEY,
108
+ value TEXT NOT NULL,
109
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
110
+ );
111
+ `);
112
+
113
+ // Load all rows into cache
114
+ const result = await this.pool.query(
115
+ "SELECT key, value FROM rotator_settings",
116
+ );
117
+ for (const row of result.rows) {
118
+ this.cache.set(row.key, row.value);
119
+ }
120
+
121
+ // Migrate from disk for any keys not already in DB
122
+ for (const [key, spec] of Object.entries(DISK_FILES)) {
123
+ if (this.cache.has(key)) continue;
124
+ try {
125
+ const path = join(getConfigDir(), spec.filename);
126
+ const content = await readTextFile(path);
127
+ if (!content) continue;
128
+ const value = spec.trim ? content.trim() : content;
129
+ if (!value) continue;
130
+ this.cache.set(key, value);
131
+ // Persist migration to DB (blocking on init is intentional)
132
+ await this.pool.query(
133
+ `INSERT INTO rotator_settings (key, value, updated_at)
134
+ VALUES ($1, $2, CURRENT_TIMESTAMP)
135
+ ON CONFLICT (key) DO UPDATE
136
+ SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
137
+ [key, value],
138
+ );
139
+ console.log(`Migrated ${spec.filename} from disk to database`);
140
+ } catch (err) {
141
+ console.error(`Failed to migrate ${spec.filename} from disk: ${err}`);
142
+ }
143
+ }
144
+
145
+ this.initialized = true;
146
+ }
147
+
148
+ getPool(): pg.Pool | null {
149
+ return this.pool;
150
+ }
151
+
152
+ async query<R extends pg.QueryResultRow = pg.QueryResultRow>(
153
+ text: string,
154
+ params?: unknown[],
155
+ ): Promise<pg.QueryResult<R>> {
156
+ if (!this.pool) {
157
+ throw new Error("Database pool is not initialized");
158
+ }
159
+ return this.pool.query<R>(text, params);
160
+ }
161
+
162
+ get(key: string): string | null {
163
+ return this.cache.get(key) ?? null;
164
+ }
165
+
166
+ async set(key: string, value: string): Promise<void> {
167
+ this.cache.set(key, value);
168
+ if (this.pool) {
169
+ // Non-blocking background save
170
+ this.pool
171
+ .query(
172
+ `INSERT INTO rotator_settings (key, value, updated_at)
173
+ VALUES ($1, $2, CURRENT_TIMESTAMP)
174
+ ON CONFLICT (key) DO UPDATE
175
+ SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
176
+ [key, value],
177
+ )
178
+ .catch((err) => {
179
+ console.error(
180
+ `Failed to save ${key} to database in background: ${err}`,
181
+ );
182
+ this.enqueueRetry(key, value);
183
+ });
184
+ }
185
+ }
186
+
187
+ private enqueueRetry(key: string, value: string): void {
188
+ const existing = this.pendingRetries.get(key);
189
+ // If the key is already pending, keep the higher attempt count
190
+ // but always use the latest value.
191
+ this.pendingRetries.set(key, {
192
+ value,
193
+ attempts: existing ? existing.attempts + 1 : 1,
194
+ });
195
+ this.scheduleRetryFlush();
196
+ }
197
+
198
+ private scheduleRetryFlush(): void {
199
+ if (this.retryTimer) return; // already scheduled
200
+ this.retryTimer = setTimeout(() => {
201
+ this.retryTimer = null;
202
+ void this.flushPendingRetries();
203
+ }, RETRY_DELAY_MS);
204
+ // Don't keep the process alive just for retries
205
+ this.retryTimer.unref();
206
+ }
207
+
208
+ private async flushPendingRetries(): Promise<void> {
209
+ if (!this.pool || this.pendingRetries.size === 0) return;
210
+
211
+ const entries = [...this.pendingRetries.entries()];
212
+ this.pendingRetries.clear();
213
+
214
+ for (const [key, pending] of entries) {
215
+ try {
216
+ await this.pool.query(
217
+ `INSERT INTO rotator_settings (key, value, updated_at)
218
+ VALUES ($1, $2, CURRENT_TIMESTAMP)
219
+ ON CONFLICT (key) DO UPDATE
220
+ SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
221
+ [key, pending.value],
222
+ );
223
+ } catch (err) {
224
+ if (pending.attempts >= MAX_RETRIES) {
225
+ console.error(
226
+ `Giving up on persisting ${key} after ${pending.attempts} failed attempts: ${err}`,
227
+ );
228
+ } else {
229
+ console.error(
230
+ `Retry ${pending.attempts}/${MAX_RETRIES} failed for ${key}: ${err}`,
231
+ );
232
+ this.pendingRetries.set(key, {
233
+ value: pending.value,
234
+ attempts: pending.attempts + 1,
235
+ });
236
+ }
237
+ }
238
+ }
239
+
240
+ // If there are still entries that failed, schedule another round
241
+ if (this.pendingRetries.size > 0) {
242
+ this.scheduleRetryFlush();
243
+ }
244
+ }
245
+
246
+ async close(): Promise<void> {
247
+ if (this.retryTimer) {
248
+ clearTimeout(this.retryTimer);
249
+ this.retryTimer = null;
250
+ }
251
+ if (this.pool) {
252
+ // Final attempt to drain any pending retries before shutdown
253
+ await this.flushPendingRetries();
254
+ await this.pool.end();
255
+ this.pool = null;
256
+ }
257
+ this.initialized = false;
258
+ }
259
+ }
260
+
261
+ // ----- FileSettingsRepository -----
262
+ //
263
+ // Reads and writes directly to disk files. Keeps an in-memory cache so
264
+ // repeated `get()` calls within the same process don't re-parse from disk.
265
+
266
+ export class FileSettingsRepository implements ISettingsRepository {
267
+ private cache = new Map<string, string>();
268
+
269
+ async init(): Promise<void> {
270
+ // Pre-load all known keys from their disk files into cache
271
+ for (const [key, spec] of Object.entries(DISK_FILES)) {
272
+ try {
273
+ const path = join(getConfigDir(), spec.filename);
274
+ const content = await readTextFile(path);
275
+ if (!content) continue;
276
+ this.cache.set(key, spec.trim ? content.trim() : content);
277
+ } catch {
278
+ // Ignore unreadable files — callers handle missing data
279
+ }
280
+ }
281
+ }
282
+
283
+ get(key: string): string | null {
284
+ return this.cache.get(key) ?? null;
285
+ }
286
+
287
+ async set(key: string, value: string): Promise<void> {
288
+ this.cache.set(key, value);
289
+
290
+ // Persist to disk
291
+ const path = diskPath(key);
292
+ if (!path) return;
293
+
294
+ const spec = DISK_FILES[key];
295
+ try {
296
+ if (spec?.backup) {
297
+ await backupFile(path, spec.filename.replace(".json", ""));
298
+ }
299
+ if (spec?.trim) {
300
+ // Plain text file (e.g. admin_token)
301
+ await writeTextFileAtomic(path, value);
302
+ } else {
303
+ // JSON files — try to pretty-print, fall back to raw string
304
+ try {
305
+ const parsed = JSON.parse(value);
306
+ await writeJsonFileAtomic(path, parsed);
307
+ } catch {
308
+ await writeTextFileAtomic(path, value);
309
+ }
310
+ }
311
+ // Apply restricted permissions when specified (e.g. secrets)
312
+ if (spec?.mode) {
313
+ try {
314
+ await chmod(path, spec.mode);
315
+ } catch {
316
+ // Best effort: some filesystems (e.g. Windows) don't support POSIX perms.
317
+ }
318
+ }
319
+ } catch (err) {
320
+ console.error(`Failed to save ${key} to disk (${path}): ${err}`);
321
+ }
322
+ }
323
+
324
+ async close(): Promise<void> {
325
+ // no-op — callers await each write before closing
326
+ }
327
+ }