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,218 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MAX_QUOTA_POLL_INTERVAL_MS,
|
|
3
|
+
MIN_QUOTA_POLL_INTERVAL_MS,
|
|
4
|
+
type AccountConfig,
|
|
5
|
+
type Config,
|
|
6
|
+
} from "./types.js";
|
|
7
|
+
import { getProxyConfigurationError } from "./providers/proxy-dispatcher.js";
|
|
8
|
+
|
|
9
|
+
export interface ValidationResult<T> {
|
|
10
|
+
ok: boolean;
|
|
11
|
+
value?: T;
|
|
12
|
+
errors: string[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function ok<T>(value: T): ValidationResult<T> {
|
|
16
|
+
return { ok: true, value, errors: [] };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function fail<T>(errors: string[]): ValidationResult<T> {
|
|
20
|
+
return { ok: false, errors };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
24
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isNonEmptyString(value: unknown): value is string {
|
|
28
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isPositiveNumber(value: unknown): value is number {
|
|
32
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isNonNegativeNumber(value: unknown): value is number {
|
|
36
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isNonNegativeInteger(value: unknown): value is number {
|
|
40
|
+
return isNonNegativeNumber(value) && Number.isInteger(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function validateAccountConfig(value: unknown, path = "account"): ValidationResult<AccountConfig> {
|
|
44
|
+
if (!isRecord(value)) return fail([`${path} must be an object`]);
|
|
45
|
+
const errors: string[] = [];
|
|
46
|
+
|
|
47
|
+
if (!isNonEmptyString(value.email)) errors.push(`${path}.email must be a non-empty string`);
|
|
48
|
+
const accountProxyError = getProxyConfigurationError(value.proxyUrl);
|
|
49
|
+
if (accountProxyError) errors.push(`${path}.${accountProxyError}`);
|
|
50
|
+
// Parent-account model: email owns per-provider credentials.
|
|
51
|
+
// Legacy flat shape (provider/apiKey/refreshToken at top level) is
|
|
52
|
+
// still accepted and normalized on load.
|
|
53
|
+
const hasCredentials =
|
|
54
|
+
Array.isArray((value as { credentials?: unknown }).credentials) &&
|
|
55
|
+
((value as { credentials: unknown[] }).credentials).length > 0;
|
|
56
|
+
if (hasCredentials) {
|
|
57
|
+
const credentials = (value as { credentials: Array<Record<string, unknown>> }).credentials;
|
|
58
|
+
if (credentials.length === 0) errors.push(`${path}.credentials must not be empty`);
|
|
59
|
+
for (let i = 0; i < credentials.length; i++) {
|
|
60
|
+
const cred = credentials[i];
|
|
61
|
+
const cpath = `${path}.credentials[${i}]`;
|
|
62
|
+
if (!isRecord(cred)) {
|
|
63
|
+
errors.push(`${cpath} must be an object`);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (!isNonEmptyString(cred.provider)) errors.push(`${cpath}.provider must be a non-empty string`);
|
|
67
|
+
const proxyError = getProxyConfigurationError(cred.proxyUrl);
|
|
68
|
+
if (proxyError) errors.push(`${cpath}.${proxyError}`);
|
|
69
|
+
if (cred.provider === "ollama") {
|
|
70
|
+
if (!isNonEmptyString(cred.apiKey)) errors.push(`${cpath}.apiKey must be a non-empty string`);
|
|
71
|
+
} else {
|
|
72
|
+
if (!isNonEmptyString(cred.refreshToken)) errors.push(`${cpath}.refreshToken must be a non-empty string`);
|
|
73
|
+
if (!isNonEmptyString(cred.projectId)) errors.push(`${cpath}.projectId must be a non-empty string`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
} else {
|
|
77
|
+
const provider = typeof value.provider === "string" ? value.provider : "google-antigravity";
|
|
78
|
+
if (provider === "ollama") {
|
|
79
|
+
if (!isNonEmptyString(value.apiKey)) errors.push(`${path}.apiKey must be a non-empty string`);
|
|
80
|
+
} else {
|
|
81
|
+
if (!isNonEmptyString(value.refreshToken)) errors.push(`${path}.refreshToken must be a non-empty string`);
|
|
82
|
+
if (!isNonEmptyString(value.projectId)) errors.push(`${path}.projectId must be a non-empty string`);
|
|
83
|
+
}
|
|
84
|
+
if (value.provider !== undefined && typeof value.provider !== "string") errors.push(`${path}.provider must be a string`);
|
|
85
|
+
}
|
|
86
|
+
if (value.label !== undefined && typeof value.label !== "string") errors.push(`${path}.label must be a string`);
|
|
87
|
+
if (value.type !== undefined && value.type !== "pro" && value.type !== "free") errors.push(`${path}.type must be "pro" or "free"`);
|
|
88
|
+
if (value.tier !== undefined && !["ultra", "pro", "plus", "free", "unknown", "max", "team"].includes(String(value.tier))) {
|
|
89
|
+
errors.push(`${path}.tier must be "ultra", "pro", "plus", "free", "unknown", "max", or "team"`);
|
|
90
|
+
}
|
|
91
|
+
if (value.familyManager !== undefined && typeof value.familyManager !== "boolean") errors.push(`${path}.familyManager must be a boolean`);
|
|
92
|
+
|
|
93
|
+
return errors.length > 0 ? fail(errors) : ok(value as unknown as AccountConfig);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function validateConfig(value: unknown): ValidationResult<Config> {
|
|
97
|
+
if (!isRecord(value)) return fail(["config must be an object"]);
|
|
98
|
+
const errors: string[] = [];
|
|
99
|
+
|
|
100
|
+
if (!Array.isArray(value.accounts)) {
|
|
101
|
+
errors.push("config.accounts must be an array");
|
|
102
|
+
} else {
|
|
103
|
+
value.accounts.forEach((account, index) => {
|
|
104
|
+
const result = validateAccountConfig(account, `config.accounts[${index}]`);
|
|
105
|
+
errors.push(...result.errors);
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (value.proxyPort !== undefined && !isPositiveNumber(value.proxyPort)) errors.push("config.proxyPort must be a positive number");
|
|
110
|
+
if (value.bindHost !== undefined && !isNonEmptyString(value.bindHost)) errors.push("config.bindHost must be a non-empty string");
|
|
111
|
+
if (value.routingPolicy !== undefined && !["timer-first", "tier-first", "quota-first", "hybrid", "sequential-quota", "sticky-quota"].includes(String(value.routingPolicy))) {
|
|
112
|
+
errors.push('config.routingPolicy must be "timer-first", "tier-first", "quota-first", "hybrid", "sequential-quota", or "sticky-quota"');
|
|
113
|
+
}
|
|
114
|
+
if (value.requestsPerRotation !== undefined && !isPositiveNumber(value.requestsPerRotation)) errors.push("config.requestsPerRotation must be a positive number");
|
|
115
|
+
if (value.rotateOnQuotaDrop !== undefined && !isNonNegativeNumber(value.rotateOnQuotaDrop)) errors.push("config.rotateOnQuotaDrop must be a non-negative number");
|
|
116
|
+
if (value.quotaPollIntervalMs !== undefined && (!isPositiveNumber(value.quotaPollIntervalMs) || value.quotaPollIntervalMs < MIN_QUOTA_POLL_INTERVAL_MS || value.quotaPollIntervalMs > MAX_QUOTA_POLL_INTERVAL_MS)) {
|
|
117
|
+
errors.push(`config.quotaPollIntervalMs must be between ${MIN_QUOTA_POLL_INTERVAL_MS} and ${MAX_QUOTA_POLL_INTERVAL_MS} ms`);
|
|
118
|
+
}
|
|
119
|
+
if (value.proSlots !== undefined && !isPositiveNumber(value.proSlots)) errors.push("config.proSlots must be a positive number");
|
|
120
|
+
if (value.maxConcurrentRequestsPerAccount !== undefined && !isPositiveNumber(value.maxConcurrentRequestsPerAccount)) errors.push("config.maxConcurrentRequestsPerAccount must be a positive number");
|
|
121
|
+
if (value.maxConcurrentRequestsPerProjectModel !== undefined && !isPositiveNumber(value.maxConcurrentRequestsPerProjectModel)) errors.push("config.maxConcurrentRequestsPerProjectModel must be a positive number");
|
|
122
|
+
if (value.projectCircuitBreaker429Threshold !== undefined && !isPositiveNumber(value.projectCircuitBreaker429Threshold)) errors.push("config.projectCircuitBreaker429Threshold must be a positive number");
|
|
123
|
+
if (value.projectCircuitBreakerWindowMs !== undefined && !isPositiveNumber(value.projectCircuitBreakerWindowMs)) errors.push("config.projectCircuitBreakerWindowMs must be a positive number");
|
|
124
|
+
if (value.projectCircuitBreakerCooldownMs !== undefined && !isPositiveNumber(value.projectCircuitBreakerCooldownMs)) errors.push("config.projectCircuitBreakerCooldownMs must be a positive number");
|
|
125
|
+
if (value.modelCircuitBreaker429Threshold !== undefined && !isPositiveNumber(value.modelCircuitBreaker429Threshold)) errors.push("config.modelCircuitBreaker429Threshold must be a positive number");
|
|
126
|
+
if (value.modelCircuitBreakerCooldownMs !== undefined && !isPositiveNumber(value.modelCircuitBreakerCooldownMs)) errors.push("config.modelCircuitBreakerCooldownMs must be a positive number");
|
|
127
|
+
if (value.dailyAccountSlowRequests !== undefined && !isPositiveNumber(value.dailyAccountSlowRequests)) errors.push("config.dailyAccountSlowRequests must be a positive number");
|
|
128
|
+
if (value.dailyAccountStopRequests !== undefined && !isPositiveNumber(value.dailyAccountStopRequests)) errors.push("config.dailyAccountStopRequests must be a positive number");
|
|
129
|
+
if (value.dailyProjectSlowRequests !== undefined && !isPositiveNumber(value.dailyProjectSlowRequests)) errors.push("config.dailyProjectSlowRequests must be a positive number");
|
|
130
|
+
if (value.dailyProjectStopRequests !== undefined && !isPositiveNumber(value.dailyProjectStopRequests)) errors.push("config.dailyProjectStopRequests must be a positive number");
|
|
131
|
+
if (value.slowModeJitterMinMs !== undefined && !isNonNegativeNumber(value.slowModeJitterMinMs)) errors.push("config.slowModeJitterMinMs must be a non-negative number");
|
|
132
|
+
if (value.slowModeJitterMaxMs !== undefined && !isNonNegativeNumber(value.slowModeJitterMaxMs)) errors.push("config.slowModeJitterMaxMs must be a non-negative number");
|
|
133
|
+
if (value.protectivePauseMs !== undefined && !isNonNegativeNumber(value.protectivePauseMs)) errors.push("config.protectivePauseMs must be a non-negative number");
|
|
134
|
+
if (value.useRequestCountRotationWhenQuotaUnknownOnly !== undefined && typeof value.useRequestCountRotationWhenQuotaUnknownOnly !== "boolean") {
|
|
135
|
+
errors.push("config.useRequestCountRotationWhenQuotaUnknownOnly must be a boolean");
|
|
136
|
+
}
|
|
137
|
+
if (value.tokenBucketEnabled !== undefined && typeof value.tokenBucketEnabled !== "boolean") {
|
|
138
|
+
errors.push("config.tokenBucketEnabled must be a boolean");
|
|
139
|
+
}
|
|
140
|
+
if (value.tokenBucketMaxTokens !== undefined && !isPositiveNumber(value.tokenBucketMaxTokens)) {
|
|
141
|
+
errors.push("config.tokenBucketMaxTokens must be a positive number");
|
|
142
|
+
}
|
|
143
|
+
if (value.tokenBucketRefillPerMinute !== undefined && !isPositiveNumber(value.tokenBucketRefillPerMinute)) {
|
|
144
|
+
errors.push("config.tokenBucketRefillPerMinute must be a positive number");
|
|
145
|
+
}
|
|
146
|
+
if (value.tokenBucketInitialTokens !== undefined && !isNonNegativeNumber(value.tokenBucketInitialTokens)) {
|
|
147
|
+
errors.push("config.tokenBucketInitialTokens must be a non-negative number");
|
|
148
|
+
}
|
|
149
|
+
if (value.streamRecoveryMaxRetries !== undefined && !isNonNegativeInteger(value.streamRecoveryMaxRetries)) {
|
|
150
|
+
errors.push("config.streamRecoveryMaxRetries must be a non-negative integer");
|
|
151
|
+
}
|
|
152
|
+
if (value.modelSpecs !== undefined) {
|
|
153
|
+
if (!isRecord(value.modelSpecs)) {
|
|
154
|
+
errors.push("config.modelSpecs must be an object when provided");
|
|
155
|
+
} else {
|
|
156
|
+
for (const [key, spec] of Object.entries(value.modelSpecs)) {
|
|
157
|
+
if (!isRecord(spec)) {
|
|
158
|
+
errors.push(`config.modelSpecs.${key} must be an object`);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (spec.maxOutputTokens !== undefined && !isPositiveNumber(spec.maxOutputTokens)) {
|
|
162
|
+
errors.push(`config.modelSpecs.${key}.maxOutputTokens must be a positive number`);
|
|
163
|
+
}
|
|
164
|
+
if (spec.thinkingBudget !== undefined && (typeof spec.thinkingBudget !== "number" || !Number.isFinite(spec.thinkingBudget))) {
|
|
165
|
+
errors.push(`config.modelSpecs.${key}.thinkingBudget must be a number`);
|
|
166
|
+
}
|
|
167
|
+
if (spec.isThinking !== undefined && typeof spec.isThinking !== "boolean") {
|
|
168
|
+
errors.push(`config.modelSpecs.${key}.isThinking must be a boolean`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (value.modelAliases !== undefined) {
|
|
174
|
+
if (!isRecord(value.modelAliases)) {
|
|
175
|
+
errors.push("config.modelAliases must be an object when provided");
|
|
176
|
+
} else {
|
|
177
|
+
for (const [from, to] of Object.entries(value.modelAliases)) {
|
|
178
|
+
if (typeof from !== "string" || from.length === 0) {
|
|
179
|
+
errors.push("config.modelAliases keys must be non-empty strings");
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
if (typeof to !== "string" || to.length === 0) {
|
|
183
|
+
errors.push(`config.modelAliases.${from} must be a non-empty string`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return errors.length > 0 ? fail(errors) : ok(value as unknown as Config);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface MinimalProxyRequestBody {
|
|
193
|
+
model: string;
|
|
194
|
+
request: unknown;
|
|
195
|
+
project?: string;
|
|
196
|
+
requestType?: string;
|
|
197
|
+
userAgent?: string;
|
|
198
|
+
requestId?: string;
|
|
199
|
+
[key: string]: unknown;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function validateProxyRequestBody(value: unknown): ValidationResult<MinimalProxyRequestBody> {
|
|
203
|
+
if (!isRecord(value)) return fail(["request body must be a JSON object"]);
|
|
204
|
+
const errors: string[] = [];
|
|
205
|
+
|
|
206
|
+
if (!isNonEmptyString(value.model)) errors.push("body.model must be a non-empty string");
|
|
207
|
+
if (!("request" in value)) errors.push("body.request is required");
|
|
208
|
+
if (value.project !== undefined && typeof value.project !== "string") errors.push("body.project must be a string when provided");
|
|
209
|
+
if (value.requestType !== undefined && typeof value.requestType !== "string") errors.push("body.requestType must be a string when provided");
|
|
210
|
+
if (value.userAgent !== undefined && typeof value.userAgent !== "string") errors.push("body.userAgent must be a string when provided");
|
|
211
|
+
if (value.requestId !== undefined && typeof value.requestId !== "string") errors.push("body.requestId must be a string when provided");
|
|
212
|
+
|
|
213
|
+
return errors.length > 0 ? fail(errors) : ok(value as MinimalProxyRequestBody);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function formatValidationErrors(errors: string[]): string {
|
|
217
|
+
return errors.join("; ");
|
|
218
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// Version check and self-update functionality
|
|
2
|
+
// Polls npm registry periodically to detect new releases
|
|
3
|
+
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { join, dirname } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { logger } from "./logger.js";
|
|
9
|
+
|
|
10
|
+
const versionLogger = logger.child("version-check");
|
|
11
|
+
|
|
12
|
+
export interface UpdateInfo {
|
|
13
|
+
currentVersion: string;
|
|
14
|
+
latestVersion: string | null;
|
|
15
|
+
updateAvailable: boolean;
|
|
16
|
+
checkedAt: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const PACKAGE_NAME = "tuxevil-rotator";
|
|
20
|
+
const REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`;
|
|
21
|
+
const CHECK_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes
|
|
22
|
+
|
|
23
|
+
let cachedInfo: UpdateInfo = {
|
|
24
|
+
currentVersion: "",
|
|
25
|
+
latestVersion: null,
|
|
26
|
+
updateAvailable: false,
|
|
27
|
+
checkedAt: 0,
|
|
28
|
+
};
|
|
29
|
+
let initialCheckTimer: ReturnType<typeof setTimeout> | null = null;
|
|
30
|
+
let checkTimer: ReturnType<typeof setInterval> | null = null;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Read the current version from package.json.
|
|
34
|
+
*/
|
|
35
|
+
function getCurrentVersion(): string {
|
|
36
|
+
try {
|
|
37
|
+
// Resolve relative to this source file
|
|
38
|
+
const thisDir = dirname(fileURLToPath(import.meta.url));
|
|
39
|
+
const pkgPath = join(thisDir, "..", "package.json");
|
|
40
|
+
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
|
41
|
+
return pkg.version || "0.0.0";
|
|
42
|
+
} catch {
|
|
43
|
+
return "0.0.0";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Simple semver comparison: returns true if b > a.
|
|
49
|
+
* Handles standard x.y.z format.
|
|
50
|
+
*/
|
|
51
|
+
function isNewerVersion(current: string, latest: string): boolean {
|
|
52
|
+
const a = current.split(".").map(Number);
|
|
53
|
+
const b = latest.split(".").map(Number);
|
|
54
|
+
for (let i = 0; i < 3; i++) {
|
|
55
|
+
const av = a[i] ?? 0;
|
|
56
|
+
const bv = b[i] ?? 0;
|
|
57
|
+
if (bv > av) return true;
|
|
58
|
+
if (bv < av) return false;
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Fetch latest version from npm registry.
|
|
65
|
+
*/
|
|
66
|
+
async function fetchLatestVersion(): Promise<string | null> {
|
|
67
|
+
try {
|
|
68
|
+
const controller = new AbortController();
|
|
69
|
+
const timeout = setTimeout(() => controller.abort(), 10_000);
|
|
70
|
+
const response = await fetch(REGISTRY_URL, {
|
|
71
|
+
headers: { Accept: "application/vnd.npm.install-v1+json" },
|
|
72
|
+
signal: controller.signal,
|
|
73
|
+
});
|
|
74
|
+
clearTimeout(timeout);
|
|
75
|
+
|
|
76
|
+
if (!response.ok) {
|
|
77
|
+
versionLogger.log("warn", `npm registry returned ${response.status}`);
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const data = (await response.json()) as { "dist-tags"?: { latest?: string } };
|
|
82
|
+
return data["dist-tags"]?.latest ?? null;
|
|
83
|
+
} catch (err) {
|
|
84
|
+
// Silently fail — user may be offline
|
|
85
|
+
versionLogger.log("info", `Version check skipped: ${err instanceof Error ? err.message : String(err)}`);
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Perform a version check against npm registry.
|
|
92
|
+
*/
|
|
93
|
+
async function checkForUpdate(): Promise<UpdateInfo> {
|
|
94
|
+
const currentVersion = getCurrentVersion();
|
|
95
|
+
const latestVersion = await fetchLatestVersion();
|
|
96
|
+
|
|
97
|
+
cachedInfo = {
|
|
98
|
+
currentVersion,
|
|
99
|
+
latestVersion,
|
|
100
|
+
updateAvailable: latestVersion !== null && isNewerVersion(currentVersion, latestVersion),
|
|
101
|
+
checkedAt: Date.now(),
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
if (cachedInfo.updateAvailable) {
|
|
105
|
+
versionLogger.log("info", `New version available: ${latestVersion} (current: ${currentVersion})`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return cachedInfo;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Get the cached update info. Returns immediately.
|
|
113
|
+
*/
|
|
114
|
+
export function getUpdateInfo(): UpdateInfo {
|
|
115
|
+
if (!cachedInfo.currentVersion) {
|
|
116
|
+
cachedInfo.currentVersion = getCurrentVersion();
|
|
117
|
+
}
|
|
118
|
+
return { ...cachedInfo };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Start periodic version checking.
|
|
123
|
+
* Performs an initial check after a short delay (10s) to avoid slowing down startup.
|
|
124
|
+
*/
|
|
125
|
+
export function startVersionChecker(): void {
|
|
126
|
+
// Initial delayed check
|
|
127
|
+
if (!initialCheckTimer) {
|
|
128
|
+
initialCheckTimer = setTimeout(() => {
|
|
129
|
+
initialCheckTimer = null;
|
|
130
|
+
void checkForUpdate();
|
|
131
|
+
}, 10_000);
|
|
132
|
+
if (initialCheckTimer.unref) {
|
|
133
|
+
initialCheckTimer.unref();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Periodic check
|
|
138
|
+
if (!checkTimer) {
|
|
139
|
+
checkTimer = setInterval(() => {
|
|
140
|
+
void checkForUpdate();
|
|
141
|
+
}, CHECK_INTERVAL_MS);
|
|
142
|
+
|
|
143
|
+
// Don't keep process alive just for version checking
|
|
144
|
+
if (checkTimer.unref) {
|
|
145
|
+
checkTimer.unref();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Stop periodic version checking.
|
|
152
|
+
*/
|
|
153
|
+
export function stopVersionChecker(): void {
|
|
154
|
+
if (initialCheckTimer) {
|
|
155
|
+
clearTimeout(initialCheckTimer);
|
|
156
|
+
initialCheckTimer = null;
|
|
157
|
+
}
|
|
158
|
+
if (checkTimer) {
|
|
159
|
+
clearInterval(checkTimer);
|
|
160
|
+
checkTimer = null;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Attempt to self-update by running npm install.
|
|
166
|
+
* Returns a result object with success/failure info.
|
|
167
|
+
*/
|
|
168
|
+
export function performSelfUpdate(): { ok: boolean; from: string; to: string; message: string } {
|
|
169
|
+
const currentVersion = getCurrentVersion();
|
|
170
|
+
const targetVersion = cachedInfo.latestVersion || "latest";
|
|
171
|
+
|
|
172
|
+
try {
|
|
173
|
+
// Detect install method: check if we're running from a global npm install
|
|
174
|
+
const isGlobal = isGlobalInstall();
|
|
175
|
+
const args = isGlobal
|
|
176
|
+
? ["install", "-g", `${PACKAGE_NAME}@latest`]
|
|
177
|
+
: ["install", `${PACKAGE_NAME}@latest`];
|
|
178
|
+
const cmd = ["npm", ...args].join(" ");
|
|
179
|
+
|
|
180
|
+
versionLogger.log("info", `Self-update: running "${cmd}"`);
|
|
181
|
+
|
|
182
|
+
const output = execFileSync("npm", args, {
|
|
183
|
+
encoding: "utf-8",
|
|
184
|
+
timeout: 120_000, // 2 minute timeout
|
|
185
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
versionLogger.log("info", `Self-update completed: ${output.trim().slice(0, 200)}`);
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
ok: true,
|
|
192
|
+
from: currentVersion,
|
|
193
|
+
to: targetVersion,
|
|
194
|
+
message: `Updated from v${currentVersion} to v${targetVersion}. Restart the process to apply the update.`,
|
|
195
|
+
};
|
|
196
|
+
} catch (err) {
|
|
197
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
198
|
+
versionLogger.log("error", `Self-update failed: ${errorMsg}`);
|
|
199
|
+
|
|
200
|
+
return {
|
|
201
|
+
ok: false,
|
|
202
|
+
from: currentVersion,
|
|
203
|
+
to: targetVersion,
|
|
204
|
+
message: `Update failed: ${errorMsg.slice(0, 300)}. Try manually: npm install -g ${PACKAGE_NAME}@latest`,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Detect if the package was installed globally.
|
|
211
|
+
*/
|
|
212
|
+
function isGlobalInstall(): boolean {
|
|
213
|
+
try {
|
|
214
|
+
// Check if we're in the global npm prefix
|
|
215
|
+
const globalPrefix = execFileSync("npm", ["prefix", "-g"], {
|
|
216
|
+
encoding: "utf-8",
|
|
217
|
+
timeout: 5000,
|
|
218
|
+
}).trim();
|
|
219
|
+
const thisDir = dirname(fileURLToPath(import.meta.url));
|
|
220
|
+
return thisDir.startsWith(globalPrefix);
|
|
221
|
+
} catch {
|
|
222
|
+
// If we can't determine, default to global (safer for npx users)
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
}
|