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
package/src/storage.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import {
|
|
2
|
+
mkdir,
|
|
3
|
+
readFile,
|
|
4
|
+
readdir,
|
|
5
|
+
rename,
|
|
6
|
+
rm,
|
|
7
|
+
writeFile,
|
|
8
|
+
} from "node:fs/promises";
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { getConfigDir } from "./paths.js";
|
|
12
|
+
|
|
13
|
+
const pendingAtomicWrites = new Map<string, Promise<void>>();
|
|
14
|
+
|
|
15
|
+
async function ensureParentDir(path: string): Promise<void> {
|
|
16
|
+
await mkdir(dirname(path), { recursive: true });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function readTextFile(path: string): Promise<string | null> {
|
|
20
|
+
try {
|
|
21
|
+
return await readFile(path, "utf-8");
|
|
22
|
+
} catch (err) {
|
|
23
|
+
if (isNotFoundError(err)) return null;
|
|
24
|
+
throw err;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function writeTextFileAtomic(
|
|
29
|
+
path: string,
|
|
30
|
+
contents: string,
|
|
31
|
+
): Promise<void> {
|
|
32
|
+
const previous = pendingAtomicWrites.get(path) ?? Promise.resolve();
|
|
33
|
+
const write = previous.catch(() => undefined).then(async () => {
|
|
34
|
+
await ensureParentDir(path);
|
|
35
|
+
const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
36
|
+
try {
|
|
37
|
+
await writeFile(tempPath, contents, "utf-8");
|
|
38
|
+
await rename(tempPath, path);
|
|
39
|
+
} catch (err) {
|
|
40
|
+
await rm(tempPath, { force: true }).catch(() => undefined);
|
|
41
|
+
throw err;
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
pendingAtomicWrites.set(path, write);
|
|
46
|
+
const clear = (): void => {
|
|
47
|
+
if (pendingAtomicWrites.get(path) === write) {
|
|
48
|
+
pendingAtomicWrites.delete(path);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
void write.then(clear, clear);
|
|
52
|
+
await write;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function readJsonFile<T>(path: string): Promise<T | null> {
|
|
56
|
+
const raw = await readTextFile(path);
|
|
57
|
+
if (!raw) return null;
|
|
58
|
+
return JSON.parse(raw) as T;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function writeJsonFileAtomic(
|
|
62
|
+
path: string,
|
|
63
|
+
value: unknown,
|
|
64
|
+
): Promise<void> {
|
|
65
|
+
await writeTextFileAtomic(path, `${JSON.stringify(value, null, 2)}\n`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function getBackupDir(): Promise<string> {
|
|
69
|
+
const dir = join(getConfigDir(), "backups");
|
|
70
|
+
await mkdir(dir, { recursive: true });
|
|
71
|
+
return dir;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function backupFile(
|
|
75
|
+
path: string,
|
|
76
|
+
label: string,
|
|
77
|
+
): Promise<string | null> {
|
|
78
|
+
const contents = await readTextFile(path);
|
|
79
|
+
if (contents === null) return null;
|
|
80
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
81
|
+
const backupPath = join(await getBackupDir(), `${label}-${stamp}.bak`);
|
|
82
|
+
await writeTextFileAtomic(backupPath, contents);
|
|
83
|
+
return backupPath;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function listBackups(): Promise<string[]> {
|
|
87
|
+
const dir = await getBackupDir();
|
|
88
|
+
return (await readdir(dir))
|
|
89
|
+
.filter((name) => name.endsWith(".bak"))
|
|
90
|
+
.sort()
|
|
91
|
+
.reverse()
|
|
92
|
+
.map((name) => join(dir, name));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function removeFileIfExists(path: string): Promise<void> {
|
|
96
|
+
await rm(path, { force: true });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function isNotFoundError(err: unknown): boolean {
|
|
100
|
+
return (
|
|
101
|
+
err instanceof Error &&
|
|
102
|
+
"code" in err &&
|
|
103
|
+
(err as NodeJS.ErrnoException).code === "ENOENT"
|
|
104
|
+
);
|
|
105
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Load environment variables from the installed systemd service unit so the
|
|
2
|
+
// CLI talks to the same backend data store (and OAuth client) as the running
|
|
3
|
+
// rotator service.
|
|
4
|
+
//
|
|
5
|
+
// The service is configured via systemd drop-ins such as:
|
|
6
|
+
// /etc/systemd/system/tuxevil-rotator.service
|
|
7
|
+
// /etc/systemd/system/tuxevil-rotator.service.d/database.conf
|
|
8
|
+
// /etc/systemd/system/tuxevil-rotator.service.d/oauth.conf
|
|
9
|
+
//
|
|
10
|
+
// When invoked from a plain shell (e.g. `tuxevil-rotator login`) those
|
|
11
|
+
// Environment=/EnvironmentFile= lines are NOT present in the CLI process, so
|
|
12
|
+
// the CLI used to fall back to the on-disk FileSettingsRepository while the
|
|
13
|
+
// service wrote to PostgreSQL. This module mirrors the service environment
|
|
14
|
+
// into the CLI process so both stay consistent.
|
|
15
|
+
|
|
16
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
|
|
19
|
+
/** Keys that are safe/meaningful to mirror from the systemd unit. */
|
|
20
|
+
const MIRROR_PREFIXES = ["TUXEVIL_ROTATOR_", "PI_ROTATOR_", "ANTIGRAVITY_", "OLLAMA_"];
|
|
21
|
+
const MIRROR_EXACT = new Set(["DATABASE_URL", "ENCRYPTION_KEY"]);
|
|
22
|
+
|
|
23
|
+
export interface SystemdEnvironmentSource {
|
|
24
|
+
/** Systemd base directories to search (defaults to the distro standard set). */
|
|
25
|
+
unitDirs?: string[];
|
|
26
|
+
/** Service name including the .service suffix. */
|
|
27
|
+
serviceName?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function isMirrorableKey(key: string): boolean {
|
|
31
|
+
if (MIRROR_EXACT.has(key)) return true;
|
|
32
|
+
return MIRROR_PREFIXES.some((p) => key.startsWith(p));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Split a systemd Environment= value into individual KEY=VALUE assignments. */
|
|
36
|
+
export function tokenizeEnvAssignments(input: string): string[] {
|
|
37
|
+
const tokens: string[] = [];
|
|
38
|
+
let current = "";
|
|
39
|
+
let quote: "'" | '"' | null = null;
|
|
40
|
+
for (const ch of input) {
|
|
41
|
+
if (quote) {
|
|
42
|
+
if (ch === quote) quote = null;
|
|
43
|
+
else current += ch;
|
|
44
|
+
} else if (ch === "'" || ch === '"') {
|
|
45
|
+
quote = ch;
|
|
46
|
+
} else if (ch === " " || ch === "\t") {
|
|
47
|
+
if (current) {
|
|
48
|
+
tokens.push(current);
|
|
49
|
+
current = "";
|
|
50
|
+
}
|
|
51
|
+
} else {
|
|
52
|
+
current += ch;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (current) tokens.push(current);
|
|
56
|
+
return tokens;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Parse a systemd EnvironmentFile line (path with optional -/@ prefix). */
|
|
60
|
+
export function stripEnvironmentFilePrefix(path: string): string {
|
|
61
|
+
let p = path.trim();
|
|
62
|
+
while (p.startsWith("-") || p.startsWith("@")) p = p.slice(1);
|
|
63
|
+
return p.trim();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Parse `KEY=VALUE` lines from a dotenv-style environment file. */
|
|
67
|
+
export function parseEnvironmentFile(content: string): Record<string, string> {
|
|
68
|
+
const out: Record<string, string> = {};
|
|
69
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
70
|
+
const line = rawLine.trim();
|
|
71
|
+
if (!line || line.startsWith("#") || line.startsWith(";")) continue;
|
|
72
|
+
const withoutExport = line.replace(/^export\s+/, "");
|
|
73
|
+
const eq = withoutExport.indexOf("=");
|
|
74
|
+
if (eq <= 0) continue;
|
|
75
|
+
const key = withoutExport.slice(0, eq).trim();
|
|
76
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
|
|
77
|
+
let value = withoutExport.slice(eq + 1).trim();
|
|
78
|
+
if (
|
|
79
|
+
(value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
|
|
80
|
+
(value.startsWith("'") && value.endsWith("'") && value.length >= 2)
|
|
81
|
+
) {
|
|
82
|
+
value = value.slice(1, -1);
|
|
83
|
+
}
|
|
84
|
+
out[key] = value;
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Parse a systemd unit file into a list of env assignments and env file paths. */
|
|
90
|
+
export function parseSystemdUnit(
|
|
91
|
+
content: string,
|
|
92
|
+
): { env: Record<string, string>; envFiles: string[] } {
|
|
93
|
+
const env: Record<string, string> = {};
|
|
94
|
+
const envFiles: string[] = [];
|
|
95
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
96
|
+
const line = rawLine.trim();
|
|
97
|
+
if (!line || line.startsWith("#") || line.startsWith(";")) continue;
|
|
98
|
+
if (line.startsWith("Environment=")) {
|
|
99
|
+
for (const token of tokenizeEnvAssignments(line.slice("Environment=".length).trim())) {
|
|
100
|
+
const eq = token.indexOf("=");
|
|
101
|
+
if (eq <= 0) continue;
|
|
102
|
+
const key = token.slice(0, eq).trim();
|
|
103
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) env[key] = token.slice(eq + 1);
|
|
104
|
+
}
|
|
105
|
+
} else if (line.startsWith("EnvironmentFile=")) {
|
|
106
|
+
const rawFile = stripInlineComment(line.slice("EnvironmentFile=".length));
|
|
107
|
+
const file = stripEnvironmentFilePrefix(rawFile);
|
|
108
|
+
if (file) envFiles.push(file);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { env, envFiles };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function stripInlineComment(line: string): string {
|
|
115
|
+
let quote: "'" | '"' | null = null;
|
|
116
|
+
for (let i = 0; i < line.length; i++) {
|
|
117
|
+
const ch = line[i];
|
|
118
|
+
if (quote) {
|
|
119
|
+
if (ch === quote) quote = null;
|
|
120
|
+
} else if (ch === "'" || ch === '"') {
|
|
121
|
+
quote = ch;
|
|
122
|
+
} else if (ch === "#") {
|
|
123
|
+
return line.slice(0, i);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return line;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Locate the unit file and its drop-in .conf files for a service. */
|
|
130
|
+
export function findSystemdUnitFiles(
|
|
131
|
+
unitDirs: string[],
|
|
132
|
+
serviceName: string,
|
|
133
|
+
): { baseDir: string | null; dropins: string[] } {
|
|
134
|
+
let baseDir: string | null = null;
|
|
135
|
+
for (const dir of unitDirs) {
|
|
136
|
+
if (existsSync(join(dir, serviceName))) {
|
|
137
|
+
baseDir = dir;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (!baseDir) return { baseDir: null, dropins: [] };
|
|
142
|
+
|
|
143
|
+
const dropinDir = join(baseDir, `${serviceName}.d`);
|
|
144
|
+
const dropins: string[] = [];
|
|
145
|
+
if (existsSync(dropinDir)) {
|
|
146
|
+
for (const entry of readdirSync(dropinDir).sort()) {
|
|
147
|
+
if (entry.endsWith(".conf")) dropins.push(join(dropinDir, entry));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return { baseDir, dropins };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Load the systemd unit environment and mirror it into `env` (defaults to
|
|
155
|
+
* process.env). Only keys that are not already present are applied so that an
|
|
156
|
+
* explicitly-provided value (e.g. from the shell) always wins.
|
|
157
|
+
*
|
|
158
|
+
* Returns the list of environment variable names that were applied.
|
|
159
|
+
*/
|
|
160
|
+
export function loadSystemdEnvironment(
|
|
161
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
162
|
+
source: SystemdEnvironmentSource = {},
|
|
163
|
+
): string[] {
|
|
164
|
+
const unitDirs = source.unitDirs ?? [
|
|
165
|
+
"/etc/systemd/system",
|
|
166
|
+
"/usr/lib/systemd/system",
|
|
167
|
+
"/lib/systemd/system",
|
|
168
|
+
];
|
|
169
|
+
const serviceName =
|
|
170
|
+
source.serviceName ??
|
|
171
|
+
(findSystemdUnitFiles(unitDirs, "tuxevil-rotator.service").baseDir
|
|
172
|
+
? "tuxevil-rotator.service"
|
|
173
|
+
: "pi-antigravity-rotator.service");
|
|
174
|
+
const applied: string[] = [];
|
|
175
|
+
|
|
176
|
+
const { baseDir, dropins } = findSystemdUnitFiles(unitDirs, serviceName);
|
|
177
|
+
if (!baseDir) return applied;
|
|
178
|
+
|
|
179
|
+
// Systemd applies the base unit first, then drop-ins in lexicographic order.
|
|
180
|
+
const unitFiles = [join(baseDir, serviceName), ...dropins];
|
|
181
|
+
|
|
182
|
+
const envFiles: string[] = [];
|
|
183
|
+
const assignments: Record<string, string> = {};
|
|
184
|
+
for (const file of unitFiles) {
|
|
185
|
+
let content: string;
|
|
186
|
+
try {
|
|
187
|
+
content = readFileSync(file, "utf8");
|
|
188
|
+
} catch {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const parsed = parseSystemdUnit(content);
|
|
192
|
+
Object.assign(assignments, parsed.env);
|
|
193
|
+
envFiles.push(...parsed.envFiles);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const resolvedEnv: Record<string, string> = {};
|
|
197
|
+
for (const file of [...new Set(envFiles)]) {
|
|
198
|
+
if (!existsSync(file)) continue;
|
|
199
|
+
try {
|
|
200
|
+
Object.assign(resolvedEnv, parseEnvironmentFile(readFileSync(file, "utf8")));
|
|
201
|
+
} catch {
|
|
202
|
+
// Skip unreadable env files.
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const merged: Record<string, string> = { ...assignments, ...resolvedEnv };
|
|
207
|
+
for (const key of Object.keys(merged)) {
|
|
208
|
+
if (!isMirrorableKey(key)) continue;
|
|
209
|
+
if (env[key] !== undefined) continue;
|
|
210
|
+
env[key] = merged[key];
|
|
211
|
+
applied.push(key);
|
|
212
|
+
}
|
|
213
|
+
return applied;
|
|
214
|
+
}
|
package/src/telemetry.ts
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
// Anonymous usage telemetry — opt-out via TUXEVIL_ROTATOR_TELEMETRY=off
|
|
2
|
+
//
|
|
3
|
+
// What we collect (all anonymous):
|
|
4
|
+
// - Random install ID (UUID, not tied to any account)
|
|
5
|
+
// - Rotator version, Node version, OS, arch
|
|
6
|
+
// - Account count, models used, total requests, uptime, savings USD
|
|
7
|
+
// - Routing health state, flagged/disabled/pro/free counts
|
|
8
|
+
// - Features used (dashboard, login, toggles — booleans only)
|
|
9
|
+
// - Flag events: HTTP status, matched patterns, model, pool state,
|
|
10
|
+
// request velocity — everything needed to improve the anti-flag algorithm
|
|
11
|
+
//
|
|
12
|
+
// What we NEVER include in telemetry payloads or event files:
|
|
13
|
+
// - Emails, tokens, project IDs, request bodies, error message text
|
|
14
|
+
// Source IPs are not part of the JSON telemetry payload, but the receiver and
|
|
15
|
+
// network path can observe them for transport and rate limiting.
|
|
16
|
+
//
|
|
17
|
+
// Docs: https://github.com/tuxevil/tuxevil-rotator#telemetry
|
|
18
|
+
|
|
19
|
+
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
|
20
|
+
import { randomUUID } from "node:crypto";
|
|
21
|
+
import { join, dirname } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { getConfigDir } from "./paths.js";
|
|
24
|
+
import { logger } from "./logger.js";
|
|
25
|
+
import { rotatorEnv } from "./env.js";
|
|
26
|
+
|
|
27
|
+
const telemetryLogger = logger.child("telemetry");
|
|
28
|
+
|
|
29
|
+
// ── Public telemetry endpoint (not a secret — anonymous data only) ───
|
|
30
|
+
// Update this URL to your VPS before publishing to npm.
|
|
31
|
+
// Can be overridden via TUXEVIL_ROTATOR_TELEMETRY_URL.
|
|
32
|
+
// HTTPS is preferred to avoid leaking the operator's IP in plaintext.
|
|
33
|
+
const DEFAULT_TELEMETRY_ENDPOINT = "https://telemetry.tuxevil.com/v1/events";
|
|
34
|
+
|
|
35
|
+
export function resolveTelemetryEndpoint(raw: string | undefined): string {
|
|
36
|
+
const candidate = raw?.trim();
|
|
37
|
+
if (!candidate) return DEFAULT_TELEMETRY_ENDPOINT;
|
|
38
|
+
try {
|
|
39
|
+
const url = new URL(candidate);
|
|
40
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("unsupported protocol");
|
|
41
|
+
return candidate;
|
|
42
|
+
} catch {
|
|
43
|
+
telemetryLogger.log(
|
|
44
|
+
"warn",
|
|
45
|
+
"Ignoring invalid TUXEVIL_ROTATOR_TELEMETRY_URL; using the default HTTPS endpoint.",
|
|
46
|
+
);
|
|
47
|
+
return DEFAULT_TELEMETRY_ENDPOINT;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const TELEMETRY_ENDPOINT = resolveTelemetryEndpoint(rotatorEnv("TELEMETRY_URL"));
|
|
52
|
+
|
|
53
|
+
const HEARTBEAT_INTERVAL_MS = 1 * 60 * 60 * 1000; // 1 hour
|
|
54
|
+
const SEND_TIMEOUT_MS = 5000;
|
|
55
|
+
|
|
56
|
+
// ── Known flag patterns (same list used in proxy.ts for detection) ───
|
|
57
|
+
export const FLAG_PATTERNS = [
|
|
58
|
+
"infring", "suspend", "abus", "terminat",
|
|
59
|
+
"violat", "banned", "policy", "forbidden", "verif",
|
|
60
|
+
] as const;
|
|
61
|
+
export type FlagPattern = typeof FLAG_PATTERNS[number];
|
|
62
|
+
|
|
63
|
+
// ── Version ──────────────────────────────────────────────────────────
|
|
64
|
+
let _version: string | null = null;
|
|
65
|
+
function getVersion(): string {
|
|
66
|
+
if (_version) return _version;
|
|
67
|
+
try {
|
|
68
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
69
|
+
const pkg = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8"));
|
|
70
|
+
_version = pkg.version ?? "unknown";
|
|
71
|
+
} catch {
|
|
72
|
+
_version = "unknown";
|
|
73
|
+
}
|
|
74
|
+
return _version!;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ── Opt-out check ────────────────────────────────────────────────────
|
|
78
|
+
export function isTelemetryEnabled(): boolean {
|
|
79
|
+
const env = rotatorEnv("TELEMETRY")?.toLowerCase();
|
|
80
|
+
return env !== "off" && env !== "false" && env !== "0";
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ── Insecure-endpoint warning ───────────────────────────────────────
|
|
84
|
+
let warnedAboutInsecureTelemetry = false;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Emit a one-time warning if the telemetry endpoint is plain HTTP, since that
|
|
88
|
+
* leaks the operator's IP and network metadata to any on-path observer.
|
|
89
|
+
* The warning can be silenced with TUXEVIL_ROTATOR_TELEMETRY_INSECURE_OK=1.
|
|
90
|
+
*
|
|
91
|
+
* The INSECURE_OK check runs before the once-flag so the operator's explicit
|
|
92
|
+
* acknowledgement is always honored, even after a previous run warned.
|
|
93
|
+
*/
|
|
94
|
+
export function warnIfInsecureTelemetryEndpoint(
|
|
95
|
+
endpoint: string = TELEMETRY_ENDPOINT,
|
|
96
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
97
|
+
): boolean {
|
|
98
|
+
if (!/^http:\/\//i.test(endpoint)) return false;
|
|
99
|
+
if (
|
|
100
|
+
(env.TUXEVIL_ROTATOR_TELEMETRY_INSECURE_OK ??
|
|
101
|
+
env.PI_ROTATOR_TELEMETRY_INSECURE_OK) === "1"
|
|
102
|
+
)
|
|
103
|
+
return false;
|
|
104
|
+
if (warnedAboutInsecureTelemetry) return true;
|
|
105
|
+
warnedAboutInsecureTelemetry = true;
|
|
106
|
+
telemetryLogger.log(
|
|
107
|
+
"warn",
|
|
108
|
+
`Telemetry endpoint uses plain HTTP (${endpoint}). This leaks the operator's IP on every heartbeat. ` +
|
|
109
|
+
`Set TUXEVIL_ROTATOR_TELEMETRY_URL to an https:// endpoint, or TUXEVIL_ROTATOR_TELEMETRY_INSECURE_OK=1 to silence this warning.`,
|
|
110
|
+
);
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── Feature tracking (set by other modules) ──────────────────────────
|
|
115
|
+
const _featuresUsed = new Set<string>();
|
|
116
|
+
|
|
117
|
+
export function trackFeature(feature: string): void {
|
|
118
|
+
_featuresUsed.add(feature);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function getFeaturesSnapshot(): Record<string, boolean> {
|
|
122
|
+
return {
|
|
123
|
+
dashboard: _featuresUsed.has("dashboard"),
|
|
124
|
+
freshWindowToggle: _featuresUsed.has("freshWindowToggle"),
|
|
125
|
+
hostedLogin: _featuresUsed.has("hostedLogin"),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ── Install ID (persisted random UUID — no PII) ─────────────────────
|
|
130
|
+
function getOrCreateInstallId(): string {
|
|
131
|
+
const idPath = join(getConfigDir(), ".telemetry-id");
|
|
132
|
+
try {
|
|
133
|
+
if (existsSync(idPath)) {
|
|
134
|
+
const existing = readFileSync(idPath, "utf-8").trim();
|
|
135
|
+
if (existing.length > 0) return existing;
|
|
136
|
+
}
|
|
137
|
+
} catch { /* regenerate */ }
|
|
138
|
+
|
|
139
|
+
const id = randomUUID();
|
|
140
|
+
try {
|
|
141
|
+
writeFileSync(idPath, id, "utf-8");
|
|
142
|
+
} catch { /* best effort */ }
|
|
143
|
+
return id;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ── First-run notice ─────────────────────────────────────────────────
|
|
147
|
+
function isFirstRun(): boolean {
|
|
148
|
+
const idPath = join(getConfigDir(), ".telemetry-id");
|
|
149
|
+
return !existsSync(idPath);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function printTelemetryNotice(): void {
|
|
153
|
+
console.log();
|
|
154
|
+
console.log(" ╭──────────────────────────────────────────────────────────╮");
|
|
155
|
+
console.log(" │ Anonymous telemetry is enabled to help improve the │");
|
|
156
|
+
console.log(" │ rotator. No emails, tokens, project IDs, request bodies │");
|
|
157
|
+
console.log(" │ or error text are sent — only aggregate usage stats. │");
|
|
158
|
+
console.log(" │ │");
|
|
159
|
+
console.log(" │ Flag events help us improve the anti-flag algorithm │");
|
|
160
|
+
console.log(" │ for everyone. Consider keeping telemetry on! │");
|
|
161
|
+
console.log(" │ │");
|
|
162
|
+
console.log(" │ Opt out anytime: TUXEVIL_ROTATOR_TELEMETRY=off │");
|
|
163
|
+
console.log(" │ Details: github.com/tuxevil/tuxevil-rotator │");
|
|
164
|
+
console.log(" ╰──────────────────────────────────────────────────────────╯");
|
|
165
|
+
console.log();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ── Metrics supplier (injected by caller) ────────────────────────────
|
|
169
|
+
export interface TelemetryMetrics {
|
|
170
|
+
accountCount: number;
|
|
171
|
+
modelsUsed: string[];
|
|
172
|
+
totalRequests: number;
|
|
173
|
+
uptimeSeconds: number;
|
|
174
|
+
routingHealthState: string;
|
|
175
|
+
flaggedCount: number;
|
|
176
|
+
disabledCount: number;
|
|
177
|
+
proCount: number;
|
|
178
|
+
freeCount: number;
|
|
179
|
+
tokensByModel: Record<string, { input: number; output: number; requests: number }>;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ── Heartbeat payload ────────────────────────────────────────────────
|
|
183
|
+
export interface TelemetryPayload {
|
|
184
|
+
event: "boot" | "heartbeat" | "shutdown";
|
|
185
|
+
installId: string;
|
|
186
|
+
version: string;
|
|
187
|
+
nodeVersion: string;
|
|
188
|
+
os: string;
|
|
189
|
+
arch: string;
|
|
190
|
+
ts: string;
|
|
191
|
+
accountCount: number;
|
|
192
|
+
modelsUsed: string[];
|
|
193
|
+
totalRequests: number;
|
|
194
|
+
uptimeSeconds: number;
|
|
195
|
+
routingHealthState: string;
|
|
196
|
+
flaggedCount: number;
|
|
197
|
+
disabledCount: number;
|
|
198
|
+
proCount: number;
|
|
199
|
+
freeCount: number;
|
|
200
|
+
tokensByModel: Record<string, { input: number; output: number; requests: number }>;
|
|
201
|
+
featuresUsed: Record<string, boolean>;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ── Flag event payload ───────────────────────────────────────────────
|
|
205
|
+
// Sent immediately when an account gets flagged by Google.
|
|
206
|
+
// This is the most important telemetry signal — it drives anti-flag
|
|
207
|
+
// algorithm improvements that benefit all users.
|
|
208
|
+
//
|
|
209
|
+
// NO PII in the payload: no email, no error text, no projectId, no request body.
|
|
210
|
+
// Only structured, anonymous context about what happened.
|
|
211
|
+
export interface FlagEventData {
|
|
212
|
+
// What triggered it
|
|
213
|
+
flagHttpStatus: number; // 401 or 403
|
|
214
|
+
flagPatternsMatched: FlagPattern[]; // which known patterns matched
|
|
215
|
+
|
|
216
|
+
// What was happening
|
|
217
|
+
model: string; // model key being requested
|
|
218
|
+
timerType: "fresh" | "5h" | "7d" | "unknown"; // quota window state
|
|
219
|
+
accountQuotaPercent: number; // quota % at time of flag (-1 if unknown)
|
|
220
|
+
|
|
221
|
+
// Account state (anonymous — no email)
|
|
222
|
+
wasProAccount: boolean; // was the account in Pro tier
|
|
223
|
+
accountTotalRequests: number; // lifetime requests on this account
|
|
224
|
+
accountRequestsLastHour: number; // requests in the last 60min on this account
|
|
225
|
+
accountConcurrentAtFlag: number; // in-flight requests when flag hit
|
|
226
|
+
|
|
227
|
+
// Pool state
|
|
228
|
+
poolSize: number; // total accounts
|
|
229
|
+
poolHealthyCount: number; // accounts still routing after this flag
|
|
230
|
+
protectivePauseTriggered: boolean; // did this flag trigger a protective pause
|
|
231
|
+
|
|
232
|
+
// Timing
|
|
233
|
+
uptimeSeconds: number; // process uptime
|
|
234
|
+
timeSinceLastFlagSeconds: number; // seconds since the previous flag (-1 if first)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export interface FlagTelemetryPayload {
|
|
238
|
+
event: "flag";
|
|
239
|
+
installId: string;
|
|
240
|
+
version: string;
|
|
241
|
+
ts: string;
|
|
242
|
+
flag: FlagEventData;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ── Module-level reporter reference for flag reporting ───────────────
|
|
246
|
+
let _activeReporter: TelemetryReporter | null = null;
|
|
247
|
+
|
|
248
|
+
export function setActiveReporter(reporter: TelemetryReporter): void {
|
|
249
|
+
_activeReporter = reporter;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Report a flag event. Called from proxy.ts when an account gets flagged.
|
|
254
|
+
* Fire-and-forget: never throws, never blocks, never affects proxy flow.
|
|
255
|
+
*/
|
|
256
|
+
export function reportFlagEvent(data: FlagEventData): void {
|
|
257
|
+
_activeReporter?.reportFlag(data);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ── Reporter ─────────────────────────────────────────────────────────
|
|
261
|
+
export class TelemetryReporter {
|
|
262
|
+
private installId: string = "";
|
|
263
|
+
private timer: ReturnType<typeof setInterval> | null = null;
|
|
264
|
+
private getMetrics: () => TelemetryMetrics;
|
|
265
|
+
private enabled: boolean;
|
|
266
|
+
private lastFlagTimestamp: number = 0;
|
|
267
|
+
|
|
268
|
+
constructor(getMetrics: () => TelemetryMetrics) {
|
|
269
|
+
this.getMetrics = getMetrics;
|
|
270
|
+
this.enabled = isTelemetryEnabled();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async start(): Promise<void> {
|
|
274
|
+
if (!this.enabled) {
|
|
275
|
+
telemetryLogger.log("debug", "Telemetry disabled by user");
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const firstRun = isFirstRun();
|
|
280
|
+
this.installId = getOrCreateInstallId();
|
|
281
|
+
|
|
282
|
+
if (firstRun) {
|
|
283
|
+
printTelemetryNotice();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
telemetryLogger.log("debug", `Telemetry active (id=${this.installId.slice(0, 8)}…)`);
|
|
287
|
+
|
|
288
|
+
await this.send("boot");
|
|
289
|
+
|
|
290
|
+
this.timer = setInterval(() => void this.send("heartbeat"), HEARTBEAT_INTERVAL_MS);
|
|
291
|
+
this.timer.unref(); // don't prevent process exit
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async shutdown(): Promise<void> {
|
|
295
|
+
if (this.timer) {
|
|
296
|
+
clearInterval(this.timer);
|
|
297
|
+
this.timer = null;
|
|
298
|
+
}
|
|
299
|
+
if (!this.enabled) return;
|
|
300
|
+
await this.send("shutdown");
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Send a flag event immediately. Called via reportFlagEvent().
|
|
305
|
+
*/
|
|
306
|
+
reportFlag(data: FlagEventData): void {
|
|
307
|
+
if (!this.enabled) return;
|
|
308
|
+
|
|
309
|
+
const now = Date.now();
|
|
310
|
+
data.timeSinceLastFlagSeconds = this.lastFlagTimestamp > 0
|
|
311
|
+
? Math.round((now - this.lastFlagTimestamp) / 1000)
|
|
312
|
+
: -1;
|
|
313
|
+
this.lastFlagTimestamp = now;
|
|
314
|
+
|
|
315
|
+
const payload: FlagTelemetryPayload = {
|
|
316
|
+
event: "flag",
|
|
317
|
+
installId: this.installId,
|
|
318
|
+
version: getVersion(),
|
|
319
|
+
ts: new Date().toISOString(),
|
|
320
|
+
flag: data,
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
// Fire-and-forget
|
|
324
|
+
void this.sendPayload(payload);
|
|
325
|
+
|
|
326
|
+
telemetryLogger.log("info",
|
|
327
|
+
`Flag event reported: ${data.flagHttpStatus} [${data.flagPatternsMatched.join(",")}] model=${data.model}`,
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
private buildPayload(event: TelemetryPayload["event"]): TelemetryPayload {
|
|
332
|
+
const metrics = this.getMetrics();
|
|
333
|
+
return {
|
|
334
|
+
event,
|
|
335
|
+
installId: this.installId,
|
|
336
|
+
version: getVersion(),
|
|
337
|
+
nodeVersion: process.version,
|
|
338
|
+
os: process.platform,
|
|
339
|
+
arch: process.arch,
|
|
340
|
+
ts: new Date().toISOString(),
|
|
341
|
+
...metrics,
|
|
342
|
+
featuresUsed: getFeaturesSnapshot(),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
private async send(event: TelemetryPayload["event"]): Promise<void> {
|
|
347
|
+
try {
|
|
348
|
+
const payload = this.buildPayload(event);
|
|
349
|
+
await this.sendPayload(payload);
|
|
350
|
+
telemetryLogger.log("debug", `Telemetry ${event} sent`);
|
|
351
|
+
} catch {
|
|
352
|
+
// Fire-and-forget — never crash, never surface errors to user.
|
|
353
|
+
// Telemetry failures must be completely invisible.
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private async sendPayload(payload: TelemetryPayload | FlagTelemetryPayload): Promise<void> {
|
|
358
|
+
await fetch(TELEMETRY_ENDPOINT, {
|
|
359
|
+
method: "POST",
|
|
360
|
+
headers: { "Content-Type": "application/json" },
|
|
361
|
+
body: JSON.stringify(payload),
|
|
362
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// ── For testing ──────────────────────────────────────────────────
|
|
367
|
+
/** Expose payload builder for tests (does NOT send) */
|
|
368
|
+
_buildPayloadForTest(event: TelemetryPayload["event"]): TelemetryPayload {
|
|
369
|
+
if (!this.installId) this.installId = getOrCreateInstallId();
|
|
370
|
+
return this.buildPayload(event);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Expose flag payload builder for tests (does NOT send) */
|
|
374
|
+
_buildFlagPayloadForTest(data: FlagEventData): FlagTelemetryPayload {
|
|
375
|
+
if (!this.installId) this.installId = getOrCreateInstallId();
|
|
376
|
+
return {
|
|
377
|
+
event: "flag",
|
|
378
|
+
installId: this.installId,
|
|
379
|
+
version: getVersion(),
|
|
380
|
+
ts: new Date().toISOString(),
|
|
381
|
+
flag: data,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
}
|