Spaces:
Paused
Paused
File size: 13,845 Bytes
4ebb914 deae086 4ebb914 deae086 4ebb914 deae086 4ebb914 deae086 4ebb914 deae086 4ebb914 deae086 4ebb914 deae086 4ebb914 deae086 4ebb914 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | /**
* ProxyPool β per-account proxy management with health checks.
*
* Stores proxy entries and accountβproxy assignments.
* Supports manual assignment, "auto" round-robin, "direct" (no proxy),
* and "global" (use the globally detected proxy).
*
* Persistence: data/proxies.json (atomic write via tmp + rename).
* Health checks: periodic + on-demand, using api.ipify.org for exit IP.
*/
import {
readFileSync,
writeFileSync,
renameSync,
existsSync,
mkdirSync,
} from "fs";
import { resolve, dirname } from "path";
import { getDataDir } from "../paths.js";
import { getTransport } from "../tls/transport.js";
function getProxiesFile(): string {
return resolve(getDataDir(), "proxies.json");
}
// ββ Types βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export interface ProxyHealthInfo {
exitIp: string | null;
latencyMs: number;
lastChecked: string;
error: string | null;
}
export type ProxyStatus = "active" | "unreachable" | "disabled";
export interface ProxyEntry {
id: string;
name: string;
url: string;
status: ProxyStatus;
health: ProxyHealthInfo | null;
addedAt: string;
}
/** Special assignment values (not a proxy ID). */
export type SpecialAssignment = "global" | "direct" | "auto";
export interface ProxyAssignment {
accountId: string;
proxyId: string; // ProxyEntry.id | SpecialAssignment
}
interface ProxiesFile {
proxies: ProxyEntry[];
assignments: ProxyAssignment[];
healthCheckIntervalMinutes: number;
}
const HEALTH_CHECK_URL = "https://api.ipify.org?format=json";
const DEFAULT_HEALTH_INTERVAL_MIN = 5;
// ββ ProxyPool βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export class ProxyPool {
private proxies: Map<string, ProxyEntry> = new Map();
private assignments: Map<string, string> = new Map(); // accountId β proxyId
private healthIntervalMin = DEFAULT_HEALTH_INTERVAL_MIN;
private persistTimer: ReturnType<typeof setTimeout> | null = null;
private healthTimer: ReturnType<typeof setInterval> | null = null;
private _roundRobinIndex = 0;
constructor() {
this.load();
}
// ββ CRUD ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
add(name: string, url: string): string {
const trimmedUrl = url.trim();
// Reject duplicate URLs
for (const existing of this.proxies.values()) {
if (existing.url === trimmedUrl) {
return existing.id;
}
}
const id = randomHex(8);
const entry: ProxyEntry = {
id,
name: name.trim(),
url: trimmedUrl,
status: "active",
health: null,
addedAt: new Date().toISOString(),
};
this.proxies.set(id, entry);
this.persistNow();
return id;
}
remove(id: string): boolean {
if (!this.proxies.delete(id)) return false;
// Clean up assignments pointing to this proxy
for (const [accountId, proxyId] of this.assignments) {
if (proxyId === id) {
this.assignments.delete(accountId);
}
}
this.persistNow();
return true;
}
update(id: string, fields: { name?: string; url?: string }): boolean {
const entry = this.proxies.get(id);
if (!entry) return false;
if (fields.name !== undefined) entry.name = fields.name.trim();
if (fields.url !== undefined) {
entry.url = fields.url.trim();
entry.health = null; // reset health on URL change
entry.status = "active";
}
this.schedulePersist();
return true;
}
getAll(): ProxyEntry[] {
return Array.from(this.proxies.values());
}
/** Returns all proxies with credentials masked in URLs. */
getAllMasked(): ProxyEntry[] {
return this.getAll().map((p) => ({ ...p, url: maskProxyUrl(p.url) }));
}
getById(id: string): ProxyEntry | undefined {
return this.proxies.get(id);
}
enable(id: string): boolean {
const entry = this.proxies.get(id);
if (!entry) return false;
entry.status = "active";
this.schedulePersist();
return true;
}
disable(id: string): boolean {
const entry = this.proxies.get(id);
if (!entry) return false;
entry.status = "disabled";
this.schedulePersist();
return true;
}
// ββ Assignment ββββββββββββββββββββββββββββββββββββββββββββββββββββ
assign(accountId: string, proxyId: string): void {
this.assignments.set(accountId, proxyId);
this.persistNow();
}
unassign(accountId: string): void {
if (this.assignments.delete(accountId)) {
this.persistNow();
}
}
getAssignment(accountId: string): string {
return this.assignments.get(accountId) ?? "global";
}
getAllAssignments(): ProxyAssignment[] {
const result: ProxyAssignment[] = [];
for (const [accountId, proxyId] of this.assignments) {
result.push({ accountId, proxyId });
}
return result;
}
/**
* Get display name for an assignment.
*/
getAssignmentDisplayName(accountId: string): string {
const assignment = this.getAssignment(accountId);
if (assignment === "global") return "Global Default";
if (assignment === "direct") return "Direct (No Proxy)";
if (assignment === "auto") return "Auto (Round-Robin)";
const proxy = this.proxies.get(assignment);
return proxy ? proxy.name : "Unknown Proxy";
}
// ββ Resolution ββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Resolve the proxy URL for an account.
* Returns:
* undefined β use global proxy (default behavior)
* null β direct connection (no proxy)
* string β specific proxy URL
*/
resolveProxyUrl(accountId: string): string | null | undefined {
const assignment = this.getAssignment(accountId);
if (assignment === "global") return undefined;
if (assignment === "direct") return null;
if (assignment === "auto") {
return this.pickRoundRobin();
}
// Specific proxy ID
const proxy = this.proxies.get(assignment);
if (!proxy || proxy.status !== "active") {
// Proxy deleted or unreachable/disabled β fall back to global
return undefined;
}
return proxy.url;
}
/**
* Round-robin pick from active proxies.
* Returns undefined (global) if no active proxies exist.
*/
private pickRoundRobin(): string | undefined {
const active = Array.from(this.proxies.values()).filter(
(p) => p.status === "active",
);
if (active.length === 0) return undefined;
this._roundRobinIndex = this._roundRobinIndex % active.length;
const picked = active[this._roundRobinIndex];
this._roundRobinIndex = (this._roundRobinIndex + 1) % active.length;
return picked.url;
}
// ββ Health Check ββββββββββββββββββββββββββββββββββββββββββββββββββ
async healthCheck(id: string): Promise<ProxyHealthInfo> {
const proxy = this.proxies.get(id);
if (!proxy) {
throw new Error(`Proxy ${id} not found`);
}
const transport = getTransport();
const start = Date.now();
try {
const result = await transport.get(
HEALTH_CHECK_URL,
{ Accept: "application/json" },
10,
proxy.url,
);
const latencyMs = Date.now() - start;
let exitIp: string | null = null;
try {
const parsed = JSON.parse(result.body) as { ip?: string };
exitIp = parsed.ip ?? null;
} catch {
// Could not parse IP
}
const info: ProxyHealthInfo = {
exitIp,
latencyMs,
lastChecked: new Date().toISOString(),
error: null,
};
proxy.health = info;
// Only change status if not manually disabled
if (proxy.status !== "disabled") {
proxy.status = "active";
}
this.schedulePersist();
return info;
} catch (err) {
const latencyMs = Date.now() - start;
const error = err instanceof Error ? err.message : String(err);
const info: ProxyHealthInfo = {
exitIp: null,
latencyMs,
lastChecked: new Date().toISOString(),
error,
};
proxy.health = info;
if (proxy.status !== "disabled") {
proxy.status = "unreachable";
}
this.schedulePersist();
return info;
}
}
async healthCheckAll(): Promise<void> {
const targets = Array.from(this.proxies.values()).filter(
(p) => p.status !== "disabled",
);
if (targets.length === 0) return;
console.log(`[ProxyPool] Health checking ${targets.length} proxies...`);
await Promise.allSettled(targets.map((p) => this.healthCheck(p.id)));
const active = targets.filter((p) => p.status === "active").length;
console.log(
`[ProxyPool] Health check complete: ${active}/${targets.length} active`,
);
}
startHealthCheckTimer(): void {
this.stopHealthCheckTimer();
if (this.proxies.size === 0) return;
const intervalMs = this.healthIntervalMin * 60 * 1000;
this.healthTimer = setInterval(() => {
this.healthCheckAll().catch((err) => {
const msg = err instanceof Error ? err.message : String(err);
console.warn(`[ProxyPool] Periodic health check error: ${msg}`);
});
}, intervalMs);
if (this.healthTimer.unref) this.healthTimer.unref();
console.log(
`[ProxyPool] Health check timer started (every ${this.healthIntervalMin}min)`,
);
}
stopHealthCheckTimer(): void {
if (this.healthTimer) {
clearInterval(this.healthTimer);
this.healthTimer = null;
}
}
getHealthIntervalMinutes(): number {
return this.healthIntervalMin;
}
setHealthIntervalMinutes(minutes: number): void {
this.healthIntervalMin = Math.max(1, minutes);
this.schedulePersist();
// Restart timer with new interval
if (this.healthTimer) {
this.startHealthCheckTimer();
}
}
// ββ Persistence βββββββββββββββββββββββββββββββββββββββββββββββββββ
private schedulePersist(): void {
if (this.persistTimer) return;
this.persistTimer = setTimeout(() => {
this.persistTimer = null;
this.persistNow();
}, 1000);
}
persistNow(): void {
if (this.persistTimer) {
clearTimeout(this.persistTimer);
this.persistTimer = null;
}
try {
const filePath = getProxiesFile();
const dir = dirname(filePath);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
const data: ProxiesFile = {
proxies: Array.from(this.proxies.values()),
assignments: this.getAllAssignments(),
healthCheckIntervalMinutes: this.healthIntervalMin,
};
const tmpFile = filePath + ".tmp";
writeFileSync(tmpFile, JSON.stringify(data, null, 2), "utf-8");
renameSync(tmpFile, filePath);
} catch (err) {
console.warn(
"[ProxyPool] Failed to persist:",
err instanceof Error ? err.message : err,
);
}
}
private load(): void {
try {
const filePath = getProxiesFile();
if (!existsSync(filePath)) return;
const raw = readFileSync(filePath, "utf-8");
const data = JSON.parse(raw) as Partial<ProxiesFile>;
if (Array.isArray(data.proxies)) {
for (const p of data.proxies) {
if (p && typeof p.id === "string" && typeof p.url === "string") {
this.proxies.set(p.id, {
id: p.id,
name: p.name ?? "",
url: p.url,
status: p.status ?? "active",
health: p.health ?? null,
addedAt: p.addedAt ?? new Date().toISOString(),
});
}
}
}
if (Array.isArray(data.assignments)) {
for (const a of data.assignments) {
if (
a &&
typeof a.accountId === "string" &&
typeof a.proxyId === "string"
) {
this.assignments.set(a.accountId, a.proxyId);
}
}
}
if (typeof data.healthCheckIntervalMinutes === "number") {
this.healthIntervalMin = Math.max(1, data.healthCheckIntervalMinutes);
}
if (this.proxies.size > 0) {
console.log(
`[ProxyPool] Loaded ${this.proxies.size} proxies, ${this.assignments.size} assignments`,
);
}
} catch (err) {
console.warn(
"[ProxyPool] Failed to load:",
err instanceof Error ? err.message : err,
);
}
}
destroy(): void {
this.stopHealthCheckTimer();
if (this.persistTimer) {
clearTimeout(this.persistTimer);
this.persistTimer = null;
}
this.persistNow();
}
}
// ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function maskProxyUrl(url: string): string {
try {
const u = new URL(url);
if (u.password) u.password = "***";
return u.toString();
} catch {
return url;
}
}
function randomHex(bytes: number): string {
const arr = new Uint8Array(bytes);
crypto.getRandomValues(arr);
return Array.from(arr)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
|