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,542 @@
|
|
|
1
|
+
import { mkdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { getAccountsPath } from "./paths.js";
|
|
5
|
+
import type { AccountConfig, ProviderCredential } from "./types.js";
|
|
6
|
+
import { writeJsonFileAtomic } from "./storage.js";
|
|
7
|
+
import {
|
|
8
|
+
loadConfig,
|
|
9
|
+
loadOrCreateAccountsConfig,
|
|
10
|
+
saveAccountsConfig,
|
|
11
|
+
} from "./config-storage.js";
|
|
12
|
+
import { applyConfigDefaults, getDefaultConfig } from "./config-defaults.js";
|
|
13
|
+
import { hasCredential } from "./providers/credential-helpers.js";
|
|
14
|
+
import { normalizeAccountConfig } from "./config-normalize.js";
|
|
15
|
+
import { validateAccountConfig } from "./validators.js";
|
|
16
|
+
|
|
17
|
+
export {
|
|
18
|
+
loadConfig,
|
|
19
|
+
loadOrCreateAccountsConfig,
|
|
20
|
+
saveAccountsConfig,
|
|
21
|
+
applyConfigDefaults,
|
|
22
|
+
getDefaultConfig,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export { normalizeAccountConfig } from "./config-normalize.js";
|
|
26
|
+
|
|
27
|
+
const ACCOUNTS_FILE = getAccountsPath();
|
|
28
|
+
const PI_DIR = join(homedir(), ".pi", "agent");
|
|
29
|
+
const PI_MODELS_FILE = join(PI_DIR, "models.json");
|
|
30
|
+
const PI_AUTH_FILE = join(PI_DIR, "auth.json");
|
|
31
|
+
const TOKEN_USAGE_FILE = join(join(ACCOUNTS_FILE, ".."), "token-usage.json");
|
|
32
|
+
|
|
33
|
+
export function getTokenUsagePath(): string {
|
|
34
|
+
return TOKEN_USAGE_FILE;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Reasonable upper bounds on per-account fields. These are defensive
|
|
38
|
+
// limits to prevent a malicious or buggy caller from growing
|
|
39
|
+
// accounts.json without bound, which would slow every subsequent
|
|
40
|
+
// saveState. The numbers are well above any realistic real value.
|
|
41
|
+
export const MAX_EMAIL_LENGTH = 254; // RFC 5321
|
|
42
|
+
export const MAX_LABEL_LENGTH = 100;
|
|
43
|
+
export const MAX_PROJECT_ID_LENGTH = 100;
|
|
44
|
+
export const MAX_REFRESH_TOKEN_LENGTH = 4096;
|
|
45
|
+
export const MAX_PROXY_URL_LENGTH = 2048;
|
|
46
|
+
|
|
47
|
+
function validateAccountConfigLengths(entry: AccountConfig): void {
|
|
48
|
+
const checks: Array<[string, number]> = [
|
|
49
|
+
["email", MAX_EMAIL_LENGTH],
|
|
50
|
+
["label", MAX_LABEL_LENGTH],
|
|
51
|
+
["projectId", MAX_PROJECT_ID_LENGTH],
|
|
52
|
+
["refreshToken", MAX_REFRESH_TOKEN_LENGTH],
|
|
53
|
+
["proxyUrl", MAX_PROXY_URL_LENGTH],
|
|
54
|
+
];
|
|
55
|
+
for (const [field, max] of checks) {
|
|
56
|
+
const value = entry[field as keyof AccountConfig];
|
|
57
|
+
if (typeof value === "string" && value.length > max) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`Account ${field} exceeds maximum length ${max} (got ${value.length}). ` +
|
|
60
|
+
`This usually indicates a malformed input — refusing to write to accounts.json.`,
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
validateCredentialLengths(entry.credentials);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function validateCredentialLengths(
|
|
68
|
+
credentials: AccountConfig["credentials"],
|
|
69
|
+
): void {
|
|
70
|
+
if (!Array.isArray(credentials)) return;
|
|
71
|
+
for (const cred of credentials) {
|
|
72
|
+
if (typeof cred.apiKey === "string" && cred.apiKey.length > MAX_REFRESH_TOKEN_LENGTH) {
|
|
73
|
+
throw new Error(`Credential apiKey for ${cred.provider} exceeds maximum length`);
|
|
74
|
+
}
|
|
75
|
+
if (typeof cred.projectId === "string" && cred.projectId.length > MAX_PROJECT_ID_LENGTH) {
|
|
76
|
+
throw new Error(`Credential projectId for ${cred.provider} exceeds maximum length`);
|
|
77
|
+
}
|
|
78
|
+
if (typeof cred.refreshToken === "string" && cred.refreshToken.length > MAX_REFRESH_TOKEN_LENGTH) {
|
|
79
|
+
throw new Error(`Credential refreshToken for ${cred.provider} exceeds maximum length`);
|
|
80
|
+
}
|
|
81
|
+
if (typeof cred.proxyUrl === "string" && cred.proxyUrl.length > MAX_PROXY_URL_LENGTH) {
|
|
82
|
+
throw new Error(`Credential proxyUrl for ${cred.provider} exceeds maximum length`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export { validateAccountConfigLengths };
|
|
88
|
+
|
|
89
|
+
function mergeCredentials(
|
|
90
|
+
existing: AccountConfig["credentials"] | undefined,
|
|
91
|
+
incoming: AccountConfig["credentials"] | undefined,
|
|
92
|
+
): AccountConfig["credentials"] {
|
|
93
|
+
const out: NonNullable<AccountConfig["credentials"]> = [];
|
|
94
|
+
const seen = new Set<string>();
|
|
95
|
+
for (const cred of [...(existing ?? []), ...(incoming ?? [])]) {
|
|
96
|
+
if (seen.has(cred.provider)) continue;
|
|
97
|
+
seen.add(cred.provider);
|
|
98
|
+
out.push(cred);
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function addAccountToConfig(
|
|
104
|
+
entry: AccountConfig,
|
|
105
|
+
): Promise<{ isNew: boolean }> {
|
|
106
|
+
validateAccountConfigLengths(entry);
|
|
107
|
+
const entryNorm = normalizeAccountConfig(entry);
|
|
108
|
+
const config = loadOrCreateAccountsConfig();
|
|
109
|
+
const existing = config.accounts.find((a) => a.email === entryNorm.email);
|
|
110
|
+
if (existing) {
|
|
111
|
+
validateCredentialLengths(entryNorm.credentials);
|
|
112
|
+
config.accounts[config.accounts.indexOf(existing)] = {
|
|
113
|
+
...normalizeAccountConfig(existing),
|
|
114
|
+
...entryNorm,
|
|
115
|
+
credentials: mergeCredentials(existing.credentials, entryNorm.credentials),
|
|
116
|
+
};
|
|
117
|
+
await saveAccountsConfig(config);
|
|
118
|
+
return { isNew: false };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
config.accounts.push(entryNorm);
|
|
122
|
+
await saveAccountsConfig(config);
|
|
123
|
+
return { isNew: true };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface AccountImportResult {
|
|
127
|
+
added: number;
|
|
128
|
+
updated: number;
|
|
129
|
+
unchanged: number;
|
|
130
|
+
skipped: number;
|
|
131
|
+
total: number;
|
|
132
|
+
errors: string[];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isImportRecord(value: unknown): value is Record<string, unknown> {
|
|
136
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function importEntries(input: unknown): unknown[] {
|
|
140
|
+
if (Array.isArray(input)) return input;
|
|
141
|
+
if (isImportRecord(input) && Array.isArray(input.accounts)) {
|
|
142
|
+
return input.accounts;
|
|
143
|
+
}
|
|
144
|
+
if (isImportRecord(input) && "email" in input) return [input];
|
|
145
|
+
throw new Error(
|
|
146
|
+
"Invalid accounts import format: expected a JSON array or an object with an accounts array",
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function firstImportString(
|
|
151
|
+
record: Record<string, unknown>,
|
|
152
|
+
keys: string[],
|
|
153
|
+
path: string,
|
|
154
|
+
errors: string[],
|
|
155
|
+
): string | undefined {
|
|
156
|
+
for (const key of keys) {
|
|
157
|
+
if (!(key in record)) continue;
|
|
158
|
+
const value = record[key];
|
|
159
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
160
|
+
errors.push(`${path}.${key} must be a non-empty string`);
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
return value.trim();
|
|
164
|
+
}
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function importedGoogleCredential(
|
|
169
|
+
record: Record<string, unknown>,
|
|
170
|
+
path: string,
|
|
171
|
+
errors: string[],
|
|
172
|
+
): ProviderCredential | null {
|
|
173
|
+
const nested = Array.isArray(record.credentials)
|
|
174
|
+
? record.credentials.find(
|
|
175
|
+
(value) =>
|
|
176
|
+
isImportRecord(value) &&
|
|
177
|
+
(value.provider === "google-antigravity" || value.provider === "google"),
|
|
178
|
+
)
|
|
179
|
+
: undefined;
|
|
180
|
+
const nestedRecord = isImportRecord(nested) ? nested : undefined;
|
|
181
|
+
const source = nestedRecord ? { ...nestedRecord, ...record } : record;
|
|
182
|
+
const refreshToken = firstImportString(
|
|
183
|
+
source,
|
|
184
|
+
["refreshToken", "refresh_token"],
|
|
185
|
+
path,
|
|
186
|
+
errors,
|
|
187
|
+
);
|
|
188
|
+
const projectId = firstImportString(
|
|
189
|
+
source,
|
|
190
|
+
["projectId", "project_id"],
|
|
191
|
+
path,
|
|
192
|
+
errors,
|
|
193
|
+
);
|
|
194
|
+
if (!refreshToken) errors.push(`${path}.refreshToken is required`);
|
|
195
|
+
if (!projectId) {
|
|
196
|
+
errors.push(
|
|
197
|
+
`${path}.projectId is required; refusing to invent a shared default project`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
if (!refreshToken || !projectId) return null;
|
|
201
|
+
|
|
202
|
+
const projectSource = source.projectSource ?? source.project_source;
|
|
203
|
+
if (
|
|
204
|
+
projectSource !== undefined &&
|
|
205
|
+
projectSource !== "google" &&
|
|
206
|
+
projectSource !== "manual"
|
|
207
|
+
) {
|
|
208
|
+
errors.push(`${path}.projectSource must be "google" or "manual"`);
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
const proxyUrl = firstImportString(
|
|
212
|
+
source,
|
|
213
|
+
["proxyUrl", "proxy_url", "proxy"],
|
|
214
|
+
path,
|
|
215
|
+
errors,
|
|
216
|
+
);
|
|
217
|
+
return {
|
|
218
|
+
provider: "google-antigravity",
|
|
219
|
+
refreshToken,
|
|
220
|
+
projectId,
|
|
221
|
+
...(proxyUrl !== undefined ? { proxyUrl } : {}),
|
|
222
|
+
...(projectSource !== undefined ? { projectSource } : {}),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function parseImportedGoogleAccount(
|
|
227
|
+
value: unknown,
|
|
228
|
+
index: number,
|
|
229
|
+
): { account: AccountConfig | null; errors: string[] } {
|
|
230
|
+
const path = `accounts[${index}]`;
|
|
231
|
+
if (!isImportRecord(value)) {
|
|
232
|
+
return { account: null, errors: [`${path} must be an object`] };
|
|
233
|
+
}
|
|
234
|
+
const errors: string[] = [];
|
|
235
|
+
const email = firstImportString(value, ["email"], path, errors);
|
|
236
|
+
if (value.label !== undefined && typeof value.label !== "string") {
|
|
237
|
+
errors.push(`${path}.label must be a string`);
|
|
238
|
+
}
|
|
239
|
+
const provider = value.provider;
|
|
240
|
+
if (
|
|
241
|
+
provider !== undefined &&
|
|
242
|
+
provider !== "google-antigravity" &&
|
|
243
|
+
provider !== "google"
|
|
244
|
+
) {
|
|
245
|
+
errors.push(`${path}.provider must identify Google Antigravity`);
|
|
246
|
+
}
|
|
247
|
+
const credential = importedGoogleCredential(value, path, errors);
|
|
248
|
+
if (!email || !credential || errors.length > 0) {
|
|
249
|
+
return { account: null, errors };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const account: AccountConfig = {
|
|
253
|
+
email,
|
|
254
|
+
provider: "google-antigravity",
|
|
255
|
+
refreshToken: credential.refreshToken,
|
|
256
|
+
projectId: credential.projectId,
|
|
257
|
+
...(credential.projectSource
|
|
258
|
+
? { projectSource: credential.projectSource }
|
|
259
|
+
: {}),
|
|
260
|
+
credentials: [credential],
|
|
261
|
+
label:
|
|
262
|
+
typeof value.label === "string" && value.label.trim() !== ""
|
|
263
|
+
? value.label.trim()
|
|
264
|
+
: email.split("@")[0],
|
|
265
|
+
};
|
|
266
|
+
for (const key of ["type", "tier", "familyManager"] as const) {
|
|
267
|
+
if (value[key] !== undefined) {
|
|
268
|
+
(account as unknown as Record<string, unknown>)[key] = value[key];
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const validation = validateAccountConfig(account, path);
|
|
273
|
+
if (!validation.ok) return { account: null, errors: validation.errors };
|
|
274
|
+
try {
|
|
275
|
+
validateAccountConfigLengths(account);
|
|
276
|
+
} catch (err) {
|
|
277
|
+
return {
|
|
278
|
+
account: null,
|
|
279
|
+
errors: [err instanceof Error ? err.message : `${path} is invalid`],
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
return { account, errors: [] };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function upsertImportedGoogleAccount(
|
|
286
|
+
config: ReturnType<typeof loadOrCreateAccountsConfig>,
|
|
287
|
+
incoming: AccountConfig,
|
|
288
|
+
): "added" | "updated" | "unchanged" {
|
|
289
|
+
const existing = config.accounts.find((entry) => entry.email === incoming.email);
|
|
290
|
+
if (!existing) {
|
|
291
|
+
config.accounts.push(incoming);
|
|
292
|
+
return "added";
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const normalized = normalizeAccountConfig(existing);
|
|
296
|
+
const incomingCredential = incoming.credentials![0];
|
|
297
|
+
const existingCredentials = normalized.credentials ?? [];
|
|
298
|
+
const existingGoogle = existingCredentials.findIndex(
|
|
299
|
+
(credential) => credential.provider === "google-antigravity",
|
|
300
|
+
);
|
|
301
|
+
const mergedCredential =
|
|
302
|
+
existingGoogle >= 0
|
|
303
|
+
? {
|
|
304
|
+
...existingCredentials[existingGoogle],
|
|
305
|
+
...incomingCredential,
|
|
306
|
+
}
|
|
307
|
+
: incomingCredential;
|
|
308
|
+
const mergedCredentials =
|
|
309
|
+
existingGoogle >= 0
|
|
310
|
+
? existingCredentials.map((credential, index) =>
|
|
311
|
+
index === existingGoogle ? mergedCredential : credential,
|
|
312
|
+
)
|
|
313
|
+
: [incomingCredential, ...existingCredentials];
|
|
314
|
+
const next: AccountConfig = {
|
|
315
|
+
...normalized,
|
|
316
|
+
provider: normalized.provider ?? "google-antigravity",
|
|
317
|
+
refreshToken: incoming.refreshToken,
|
|
318
|
+
projectId: incoming.projectId,
|
|
319
|
+
...(incoming.projectSource
|
|
320
|
+
? { projectSource: incoming.projectSource }
|
|
321
|
+
: {}),
|
|
322
|
+
credentials: mergedCredentials,
|
|
323
|
+
...(incoming.label ? { label: incoming.label } : {}),
|
|
324
|
+
...(incoming.type !== undefined ? { type: incoming.type } : {}),
|
|
325
|
+
...(incoming.tier !== undefined ? { tier: incoming.tier } : {}),
|
|
326
|
+
...(incoming.familyManager !== undefined
|
|
327
|
+
? { familyManager: incoming.familyManager }
|
|
328
|
+
: {}),
|
|
329
|
+
};
|
|
330
|
+
validateAccountConfigLengths(next);
|
|
331
|
+
const changed = JSON.stringify(existing) !== JSON.stringify(next);
|
|
332
|
+
config.accounts[config.accounts.indexOf(existing)] = next;
|
|
333
|
+
return changed ? "updated" : "unchanged";
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Import Google Antigravity/Pi account exports into the parent-account model.
|
|
338
|
+
* The importer accepts camelCase and snake_case token/project fields, keeps
|
|
339
|
+
* Google credentials ahead of an existing Ollama credential, and never
|
|
340
|
+
* invents a project id when the source omits one.
|
|
341
|
+
*/
|
|
342
|
+
export async function importAccountsToConfig(
|
|
343
|
+
input: unknown,
|
|
344
|
+
): Promise<AccountImportResult> {
|
|
345
|
+
const entries = importEntries(input);
|
|
346
|
+
const config = loadOrCreateAccountsConfig();
|
|
347
|
+
const result: AccountImportResult = {
|
|
348
|
+
added: 0,
|
|
349
|
+
updated: 0,
|
|
350
|
+
unchanged: 0,
|
|
351
|
+
skipped: 0,
|
|
352
|
+
total: entries.length,
|
|
353
|
+
errors: [],
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
for (let index = 0; index < entries.length; index++) {
|
|
357
|
+
const parsed = parseImportedGoogleAccount(entries[index], index);
|
|
358
|
+
if (!parsed.account) {
|
|
359
|
+
result.skipped++;
|
|
360
|
+
result.errors.push(...parsed.errors);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
const outcome = upsertImportedGoogleAccount(config, parsed.account);
|
|
364
|
+
result[outcome]++;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (result.added + result.updated > 0) {
|
|
368
|
+
await saveAccountsConfig(config);
|
|
369
|
+
}
|
|
370
|
+
return result;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export async function removeAccountFromConfig(email: string): Promise<boolean> {
|
|
374
|
+
const config = loadOrCreateAccountsConfig();
|
|
375
|
+
const idx = config.accounts.findIndex((a) => a.email === email);
|
|
376
|
+
if (idx < 0) return false;
|
|
377
|
+
config.accounts.splice(idx, 1);
|
|
378
|
+
await saveAccountsConfig(config);
|
|
379
|
+
return true;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function legacyOllamaRotatorAccountsFile(): string {
|
|
383
|
+
const envDir = process.env.OLLAMA_ROTATOR_DIR;
|
|
384
|
+
return join(envDir ?? homedir(), envDir ? "" : ".ollama-rotator", "accounts.json");
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Import Ollama Cloud accounts from a legacy ~/ollama-rotator accounts.json
|
|
389
|
+
* (the predecessor product) into the parent-account model: each entry's
|
|
390
|
+
* API key becomes an `ollama` credential, merged onto the account with the
|
|
391
|
+
* same email (the account itself is created when the email is unknown).
|
|
392
|
+
*
|
|
393
|
+
* Returns the number of credentials imported (0 when no legacy config exists).
|
|
394
|
+
*/
|
|
395
|
+
export async function importLegacyOllamaRotatorAccounts(
|
|
396
|
+
legacyFile = legacyOllamaRotatorAccountsFile(),
|
|
397
|
+
): Promise<number> {
|
|
398
|
+
let raw: string;
|
|
399
|
+
try {
|
|
400
|
+
raw = await readFile(legacyFile, "utf-8");
|
|
401
|
+
} catch {
|
|
402
|
+
// No legacy config — nothing to do.
|
|
403
|
+
return 0;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
let entries: unknown;
|
|
407
|
+
try {
|
|
408
|
+
entries = JSON.parse(raw);
|
|
409
|
+
} catch {
|
|
410
|
+
console.warn(`Skipping legacy ${legacyFile}: not valid JSON`);
|
|
411
|
+
return 0;
|
|
412
|
+
}
|
|
413
|
+
// The predecessor's accounts.json is the full Config object
|
|
414
|
+
// ({proxyPort, routingPolicy, ..., accounts: [...]}); a bare array of
|
|
415
|
+
// accounts is accepted too for simplicity.
|
|
416
|
+
const rawAccounts = Array.isArray(entries)
|
|
417
|
+
? entries
|
|
418
|
+
: typeof entries === "object" &&
|
|
419
|
+
entries !== null &&
|
|
420
|
+
Array.isArray((entries as { accounts?: unknown }).accounts)
|
|
421
|
+
? (entries as { accounts: unknown[] }).accounts
|
|
422
|
+
: [];
|
|
423
|
+
if (rawAccounts.length === 0) return 0;
|
|
424
|
+
|
|
425
|
+
const config = loadOrCreateAccountsConfig();
|
|
426
|
+
let imported = 0;
|
|
427
|
+
let merged = 0;
|
|
428
|
+
let added = 0;
|
|
429
|
+
|
|
430
|
+
for (const entry of rawAccounts) {
|
|
431
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
432
|
+
const { email, apiKey, label, tier, type } = entry as Record<string, unknown>;
|
|
433
|
+
if (typeof email !== "string" || email.length === 0) continue;
|
|
434
|
+
if (typeof apiKey !== "string" || apiKey.trim() === "") {
|
|
435
|
+
console.warn(` Skipping legacy account ${email}: missing apiKey`);
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const credential: ProviderCredential = {
|
|
440
|
+
provider: "ollama",
|
|
441
|
+
apiKey: apiKey.trim(),
|
|
442
|
+
};
|
|
443
|
+
const account: AccountConfig = {
|
|
444
|
+
email,
|
|
445
|
+
credentials: [credential],
|
|
446
|
+
};
|
|
447
|
+
if (typeof label === "string" && label !== "") account.label = label;
|
|
448
|
+
if (typeof tier === "string") account.tier = tier as AccountConfig["tier"];
|
|
449
|
+
if (typeof type === "string") account.type = type as AccountConfig["type"];
|
|
450
|
+
try {
|
|
451
|
+
validateAccountConfigLengths(account);
|
|
452
|
+
} catch {
|
|
453
|
+
console.warn(` Skipping legacy account ${email}: invalid fields`);
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
const existing = config.accounts.find((a) => a.email === email);
|
|
458
|
+
if (existing) {
|
|
459
|
+
const normalized = normalizeAccountConfig(existing);
|
|
460
|
+
if (hasCredential(normalized, "ollama")) {
|
|
461
|
+
// Credential already present (e.g. re-import after a previous run).
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
const idx = config.accounts.indexOf(existing);
|
|
465
|
+
config.accounts[idx] = {
|
|
466
|
+
...normalized,
|
|
467
|
+
credentials: [...(normalized.credentials ?? []), credential],
|
|
468
|
+
};
|
|
469
|
+
merged += 1;
|
|
470
|
+
} else {
|
|
471
|
+
config.accounts.push(account);
|
|
472
|
+
added += 1;
|
|
473
|
+
}
|
|
474
|
+
imported += 1;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (imported > 0) {
|
|
478
|
+
await saveAccountsConfig(config);
|
|
479
|
+
console.log(
|
|
480
|
+
`Imported ${imported} Ollama Cloud credential(s) from legacy ${legacyFile} ` +
|
|
481
|
+
`(${added} new account(s), ${merged} merged into existing account(s))`,
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
return imported;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export async function ensurePiModelsConfig(): Promise<void> {
|
|
488
|
+
await mkdir(PI_DIR, { recursive: true });
|
|
489
|
+
|
|
490
|
+
let models: Record<string, unknown> = {};
|
|
491
|
+
try {
|
|
492
|
+
models = JSON.parse(await readFile(PI_MODELS_FILE, "utf-8"));
|
|
493
|
+
} catch {
|
|
494
|
+
// Missing or corrupted, will overwrite.
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const providers = (models.providers || {}) as Record<
|
|
498
|
+
string,
|
|
499
|
+
Record<string, unknown>
|
|
500
|
+
>;
|
|
501
|
+
const antigravity = providers["google-antigravity"] || {};
|
|
502
|
+
|
|
503
|
+
if (antigravity.baseUrl === "http://localhost:51200") {
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
antigravity.baseUrl = "http://localhost:51200";
|
|
508
|
+
providers["google-antigravity"] = antigravity;
|
|
509
|
+
models.providers = providers;
|
|
510
|
+
|
|
511
|
+
await writeJsonFileAtomic(PI_MODELS_FILE, models);
|
|
512
|
+
console.log(` Updated ${PI_MODELS_FILE}`);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
export async function ensurePiAuthConfig(): Promise<void> {
|
|
516
|
+
await mkdir(PI_DIR, { recursive: true });
|
|
517
|
+
|
|
518
|
+
let auth: Record<string, unknown> = {};
|
|
519
|
+
try {
|
|
520
|
+
auth = JSON.parse(await readFile(PI_AUTH_FILE, "utf-8"));
|
|
521
|
+
} catch {
|
|
522
|
+
// Missing or corrupted, will overwrite.
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const existing = auth["google-antigravity"] as
|
|
526
|
+
| Record<string, unknown>
|
|
527
|
+
| undefined;
|
|
528
|
+
if (existing?.type === "oauth" && existing?.refresh === "proxy-managed") {
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
auth["google-antigravity"] = {
|
|
533
|
+
type: "oauth",
|
|
534
|
+
refresh: "proxy-managed",
|
|
535
|
+
access: "proxy-managed",
|
|
536
|
+
expires: 32503680000000,
|
|
537
|
+
projectId: "proxy-managed",
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
await writeJsonFileAtomic(PI_AUTH_FILE, auth);
|
|
541
|
+
console.log(` Updated ${PI_AUTH_FILE}`);
|
|
542
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { getCachedAdminToken, setCachedAdminToken } from "./db-store.js";
|
|
4
|
+
|
|
5
|
+
interface AdminAuthRequest {
|
|
6
|
+
url?: string;
|
|
7
|
+
headers: IncomingMessage["headers"];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
let persistedToken: string | null = null;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Set the persisted admin token at runtime. Called by index.ts after
|
|
14
|
+
* ensureAdminToken resolves the effective token. Subsequent calls to
|
|
15
|
+
* getConfiguredAdminToken() will return this token if no env var is set.
|
|
16
|
+
*/
|
|
17
|
+
export function setPersistedAdminToken(token: string | null): void {
|
|
18
|
+
persistedToken = token && token.length > 0 ? token : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function getConfiguredAdminToken(
|
|
22
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
23
|
+
): string | null {
|
|
24
|
+
const token =
|
|
25
|
+
env.TUXEVIL_ROTATOR_ADMIN_TOKEN?.trim() ||
|
|
26
|
+
env.PI_ROTATOR_ADMIN_TOKEN?.trim();
|
|
27
|
+
if (token) return token;
|
|
28
|
+
return persistedToken;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Generate a cryptographically secure admin token (32 random bytes, hex).
|
|
33
|
+
* 64 hex characters = 256 bits of entropy.
|
|
34
|
+
*/
|
|
35
|
+
export function generateAdminToken(): string {
|
|
36
|
+
return randomBytes(32).toString("hex");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function readPersistedAdminToken(): string | null {
|
|
40
|
+
return getCachedAdminToken();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function writePersistedAdminToken(token: string): Promise<void> {
|
|
44
|
+
await setCachedAdminToken(token);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ResolvedAdminToken {
|
|
48
|
+
token: string;
|
|
49
|
+
source: "env" | "repository" | "generated";
|
|
50
|
+
generated: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Resolve the effective admin token, generating and persisting one if needed.
|
|
55
|
+
* Priority: TUXEVIL_ROTATOR_ADMIN_TOKEN env var > repository > generate new.
|
|
56
|
+
*
|
|
57
|
+
* When a token is generated, it is persisted to the repository and returned.
|
|
58
|
+
* The caller is responsible for printing it to the operator.
|
|
59
|
+
*/
|
|
60
|
+
export async function ensureAdminToken(
|
|
61
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
62
|
+
): Promise<ResolvedAdminToken> {
|
|
63
|
+
const envToken =
|
|
64
|
+
env.TUXEVIL_ROTATOR_ADMIN_TOKEN?.trim() ||
|
|
65
|
+
env.PI_ROTATOR_ADMIN_TOKEN?.trim();
|
|
66
|
+
if (envToken) {
|
|
67
|
+
return { token: envToken, source: "env", generated: false };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const existing = readPersistedAdminToken();
|
|
71
|
+
if (existing) {
|
|
72
|
+
return { token: existing, source: "repository", generated: false };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const newToken = generateAdminToken();
|
|
76
|
+
try {
|
|
77
|
+
await writePersistedAdminToken(newToken);
|
|
78
|
+
} catch {
|
|
79
|
+
// If we cannot persist (e.g. DB down, read-only fs), still return the
|
|
80
|
+
// token for this session. The next restart will simply generate again.
|
|
81
|
+
}
|
|
82
|
+
return { token: newToken, source: "generated", generated: true };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function getRequestAdminToken(req: AdminAuthRequest): string | null {
|
|
86
|
+
const headerToken = req.headers["x-rotator-admin-token"];
|
|
87
|
+
if (typeof headerToken === "string" && headerToken) return headerToken;
|
|
88
|
+
if (Array.isArray(headerToken) && headerToken[0]) return headerToken[0];
|
|
89
|
+
|
|
90
|
+
const authorization = req.headers.authorization;
|
|
91
|
+
if (
|
|
92
|
+
typeof authorization === "string" &&
|
|
93
|
+
authorization.toLowerCase().startsWith("bearer ")
|
|
94
|
+
) {
|
|
95
|
+
return authorization.slice("bearer ".length).trim();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const requestUrl = new URL(req.url || "/", "http://localhost");
|
|
100
|
+
return requestUrl.searchParams.get("token");
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function isAdminAuthorized(
|
|
107
|
+
req: AdminAuthRequest,
|
|
108
|
+
expectedToken: string | null = getConfiguredAdminToken(),
|
|
109
|
+
): boolean {
|
|
110
|
+
if (!expectedToken) return true;
|
|
111
|
+
return getRequestAdminToken(req) === expectedToken;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function requireAdmin(
|
|
115
|
+
req: IncomingMessage,
|
|
116
|
+
res: ServerResponse,
|
|
117
|
+
): boolean {
|
|
118
|
+
if (isAdminAuthorized(req)) return true;
|
|
119
|
+
res.writeHead(401, {
|
|
120
|
+
"Content-Type": "application/json",
|
|
121
|
+
"Cache-Control": "no-store",
|
|
122
|
+
"WWW-Authenticate": "Bearer",
|
|
123
|
+
});
|
|
124
|
+
res.end(JSON.stringify({ error: "Unauthorized" }));
|
|
125
|
+
return false;
|
|
126
|
+
}
|