Spaces:
Paused
Paused
Upload unified-server.js
Browse files- unified-server.js +76 -40
unified-server.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
| 1 |
-
// unified-server.js (v16 - API Key Sanitization Fix)
|
| 2 |
-
|
| 3 |
-
// --- 核心依赖 ---
|
| 4 |
const express = require('express');
|
| 5 |
const WebSocket = require('ws');
|
| 6 |
const http = require('http');
|
|
@@ -412,7 +409,7 @@ class RequestHandler {
|
|
| 412 |
|
| 413 |
this.logger.info('==================================================');
|
| 414 |
this.logger.info(`🔄 [Auth] 开始账号切换流程`);
|
| 415 |
-
this.logger.info(` • 失败次数: ${this.failureCount}/${this.config.failureThreshold}`);
|
| 416 |
this.logger.info(` • 当前账号索引: ${this.currentAuthIndex}`);
|
| 417 |
this.logger.info(` • 目标账号索引: ${nextAuthIndex}`);
|
| 418 |
this.logger.info(` • 可用账号总数: ${maxAuthIndex}`);
|
|
@@ -434,6 +431,42 @@ class RequestHandler {
|
|
| 434 |
this.isAuthSwitching = false;
|
| 435 |
}
|
| 436 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
|
| 438 |
async processRequest(req, res) {
|
| 439 |
this.logger.info(`[Request] 处理请求: ${req.method} ${req.path}`);
|
|
@@ -497,6 +530,7 @@ class RequestHandler {
|
|
| 497 |
this._forwardRequest(proxyRequest);
|
| 498 |
lastMessage = await messageQueue.dequeue();
|
| 499 |
if (lastMessage.event_type === 'error' && lastMessage.status >= 400 && lastMessage.status <= 599) {
|
|
|
|
| 500 |
const errorText = `收到 ${lastMessage.status} 错误。${attempt < this.maxRetries ? `将在 ${this.retryDelay / 1000}秒后重试...` : '已达到最大重试次数。'}`;
|
| 501 |
this._sendErrorChunkToClient(res, errorText);
|
| 502 |
if (attempt < this.maxRetries) {
|
|
@@ -508,19 +542,6 @@ class RequestHandler {
|
|
| 508 |
break;
|
| 509 |
}
|
| 510 |
if (lastMessage.event_type === 'error' || requestFailed) {
|
| 511 |
-
this.failureCount++;
|
| 512 |
-
this.logger.warn(`⚠️ [Auth] 请求失败 - 失败计数: ${this.failureCount}/${this.config.failureThreshold} (当前账号索引: ${this.currentAuthIndex})`);
|
| 513 |
-
if (this.failureCount >= this.config.failureThreshold) {
|
| 514 |
-
this.logger.warn(`🔴 [Auth] 达到失败阈值!准备切换账号...`);
|
| 515 |
-
this._sendErrorChunkToClient(res, `连续失败${this.failureCount}次,正在尝试切换账号...`);
|
| 516 |
-
try {
|
| 517 |
-
await this._switchToNextAuth();
|
| 518 |
-
this._sendErrorChunkToClient(res, `已切换到账号索引 ${this.currentAuthIndex},请重试`);
|
| 519 |
-
} catch (switchError) {
|
| 520 |
-
this.logger.error(`🔴 [Auth] 账号切换失败: ${switchError.message}`);
|
| 521 |
-
this._sendErrorChunkToClient(res, `切换账号失败: ${switchError.message}`);
|
| 522 |
-
}
|
| 523 |
-
}
|
| 524 |
throw new Error(lastMessage.message || '请求失败');
|
| 525 |
}
|
| 526 |
if (this.failureCount > 0) {
|
|
@@ -547,6 +568,7 @@ class RequestHandler {
|
|
| 547 |
this._forwardRequest(proxyRequest);
|
| 548 |
headerMessage = await messageQueue.dequeue();
|
| 549 |
if (headerMessage.event_type === 'error' && headerMessage.status >= 400 && headerMessage.status <= 599) {
|
|
|
|
| 550 |
this.logger.warn(`[Request] 收到 ${headerMessage.status} 错误,将在 ${this.retryDelay / 1000}秒后重试...`);
|
| 551 |
if (attempt < this.maxRetries) {
|
| 552 |
await new Promise(resolve => setTimeout(resolve, this.retryDelay));
|
|
@@ -557,16 +579,6 @@ class RequestHandler {
|
|
| 557 |
break;
|
| 558 |
}
|
| 559 |
if (headerMessage.event_type === 'error' || requestFailed) {
|
| 560 |
-
this.failureCount++;
|
| 561 |
-
this.logger.warn(`⚠️ [Auth] 请求失败 - 失败计数: ${this.failureCount}/${this.config.failureThreshold} (当前账号索引: ${this.currentAuthIndex})`);
|
| 562 |
-
if (this.failureCount >= this.config.failureThreshold) {
|
| 563 |
-
this.logger.warn(`🔴 [Auth] 达到失败阈值!准备切换账号...`);
|
| 564 |
-
try {
|
| 565 |
-
await this._switchToNextAuth();
|
| 566 |
-
} catch (switchError) {
|
| 567 |
-
this.logger.error(`🔴 [Auth] 账号切换失败: ${switchError.message}`);
|
| 568 |
-
}
|
| 569 |
-
}
|
| 570 |
return this._sendErrorResponse(res, headerMessage.status, headerMessage.message);
|
| 571 |
}
|
| 572 |
if (this.failureCount > 0) {
|
|
@@ -642,8 +654,10 @@ class ProxyServerSystem extends EventEmitter {
|
|
| 642 |
_loadConfiguration() {
|
| 643 |
let config = {
|
| 644 |
httpPort: 7860, host: '0.0.0.0', wsPort: 9998, streamingMode: 'real',
|
| 645 |
-
failureThreshold:
|
|
|
|
| 646 |
apiKeys: [],
|
|
|
|
| 647 |
};
|
| 648 |
|
| 649 |
const configPath = path.join(__dirname, 'config.json');
|
|
@@ -667,26 +681,48 @@ class ProxyServerSystem extends EventEmitter {
|
|
| 667 |
if (process.env.API_KEYS) {
|
| 668 |
config.apiKeys = process.env.API_KEYS.split(',');
|
| 669 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 670 |
|
| 671 |
-
// --- CRITICAL FIX: Sanitize the apiKeys array to remove empty/whitespace-only keys ---
|
| 672 |
if (Array.isArray(config.apiKeys)) {
|
| 673 |
config.apiKeys = config.apiKeys.map(k => String(k).trim()).filter(k => k);
|
| 674 |
} else {
|
| 675 |
-
config.apiKeys = [];
|
| 676 |
}
|
| 677 |
|
| 678 |
this.config = config;
|
| 679 |
-
this.logger.info('================ [
|
| 680 |
-
this.logger.info(` HTTP
|
| 681 |
-
this.logger.info(`
|
| 682 |
-
this.logger.info(`
|
| 683 |
-
|
| 684 |
-
this.logger.info(`
|
| 685 |
-
this.logger.info(`
|
|
|
|
|
|
|
| 686 |
if (this.config.apiKeys && this.config.apiKeys.length > 0) {
|
| 687 |
-
this.logger.info(` API
|
| 688 |
} else {
|
| 689 |
-
this.logger.info(` API
|
| 690 |
}
|
| 691 |
this.logger.info('=============================================================');
|
| 692 |
}
|
|
@@ -735,7 +771,6 @@ class ProxyServerSystem extends EventEmitter {
|
|
| 735 |
if (serverApiKeys.includes(clientKey)) {
|
| 736 |
this.logger.info(`[Auth] API Key 在 '${keySource}' 中找到,验证通过。`);
|
| 737 |
|
| 738 |
-
// --- CRITICAL FIX: Clean up the request object if key was in query ---
|
| 739 |
if (keySource === 'Query Parameter') {
|
| 740 |
delete req.query.key;
|
| 741 |
this.logger.debug(`[Auth-Cleanup] 已从 req.query 中移除 API Key,以确保请求纯净。`);
|
|
@@ -790,6 +825,7 @@ class ProxyServerSystem extends EventEmitter {
|
|
| 790 |
config: {
|
| 791 |
streamingMode: this.streamingMode,
|
| 792 |
failureThreshold: this.config.failureThreshold,
|
|
|
|
| 793 |
maxRetries: this.config.maxRetries,
|
| 794 |
authMode: this.authSource.authMode,
|
| 795 |
apiKeyAuth: (this.config.apiKeys && this.config.apiKeys.length > 0) ? 'Enabled' : 'Disabled',
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
const express = require('express');
|
| 2 |
const WebSocket = require('ws');
|
| 3 |
const http = require('http');
|
|
|
|
| 409 |
|
| 410 |
this.logger.info('==================================================');
|
| 411 |
this.logger.info(`🔄 [Auth] 开始账号切换流程`);
|
| 412 |
+
this.logger.info(` • 失败次数: ${this.failureCount}/${this.config.failureThreshold > 0 ? this.config.failureThreshold : 'N/A'}`);
|
| 413 |
this.logger.info(` • 当前账号索引: ${this.currentAuthIndex}`);
|
| 414 |
this.logger.info(` • 目标账号索引: ${nextAuthIndex}`);
|
| 415 |
this.logger.info(` • 可用账号总数: ${maxAuthIndex}`);
|
|
|
|
| 431 |
this.isAuthSwitching = false;
|
| 432 |
}
|
| 433 |
}
|
| 434 |
+
|
| 435 |
+
async _handleRequestFailureAndSwitch(errorDetails, res) {
|
| 436 |
+
const isImmediateSwitch = this.config.immediateSwitchStatusCodes.includes(errorDetails.status);
|
| 437 |
+
|
| 438 |
+
if (isImmediateSwitch) {
|
| 439 |
+
this.logger.warn(`🔴 [Auth] 收到状态码 ${errorDetails.status},触发立即切换账号...`);
|
| 440 |
+
if (res) this._sendErrorChunkToClient(res, `收到状态码 ${errorDetails.status},正在尝试切换账号...`);
|
| 441 |
+
try {
|
| 442 |
+
await this._switchToNextAuth();
|
| 443 |
+
if (res) this._sendErrorChunkToClient(res, `已切换到账号索引 ${this.currentAuthIndex},请重试`);
|
| 444 |
+
} catch (switchError) {
|
| 445 |
+
this.logger.error(`🔴 [Auth] 账号切换失败: ${switchError.message}`);
|
| 446 |
+
if (res) this._sendErrorChunkToClient(res, `切换账号失败: ${switchError.message}`);
|
| 447 |
+
}
|
| 448 |
+
return; // End here after immediate switch attempt
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
if (this.config.failureThreshold > 0) {
|
| 452 |
+
this.failureCount++;
|
| 453 |
+
this.logger.warn(`⚠️ [Auth] 请求失败 - 失败计数: ${this.failureCount}/${this.config.failureThreshold} (当前账号索引: ${this.currentAuthIndex})`);
|
| 454 |
+
if (this.failureCount >= this.config.failureThreshold) {
|
| 455 |
+
this.logger.warn(`🔴 [Auth] 达到失败阈值!准备切换账号...`);
|
| 456 |
+
if (res) this._sendErrorChunkToClient(res, `连续失败${this.failureCount}次,正在尝试切换账号...`);
|
| 457 |
+
try {
|
| 458 |
+
await this._switchToNextAuth();
|
| 459 |
+
if (res) this._sendErrorChunkToClient(res, `已切换到账号索引 ${this.currentAuthIndex},请重试`);
|
| 460 |
+
} catch (switchError) {
|
| 461 |
+
this.logger.error(`🔴 [Auth] 账号切换失败: ${switchError.message}`);
|
| 462 |
+
if (res) this._sendErrorChunkToClient(res, `切换账号失败: ${switchError.message}`);
|
| 463 |
+
}
|
| 464 |
+
}
|
| 465 |
+
} else {
|
| 466 |
+
this.logger.warn(`[Auth] 请求失败 (状态码: ${errorDetails.status})。基于计数的自动切换已禁用 (failureThreshold=0)`);
|
| 467 |
+
}
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
|
| 471 |
async processRequest(req, res) {
|
| 472 |
this.logger.info(`[Request] 处理请求: ${req.method} ${req.path}`);
|
|
|
|
| 530 |
this._forwardRequest(proxyRequest);
|
| 531 |
lastMessage = await messageQueue.dequeue();
|
| 532 |
if (lastMessage.event_type === 'error' && lastMessage.status >= 400 && lastMessage.status <= 599) {
|
| 533 |
+
await this._handleRequestFailureAndSwitch(lastMessage, res);
|
| 534 |
const errorText = `收到 ${lastMessage.status} 错误。${attempt < this.maxRetries ? `将在 ${this.retryDelay / 1000}秒后重试...` : '已达到最大重试次数。'}`;
|
| 535 |
this._sendErrorChunkToClient(res, errorText);
|
| 536 |
if (attempt < this.maxRetries) {
|
|
|
|
| 542 |
break;
|
| 543 |
}
|
| 544 |
if (lastMessage.event_type === 'error' || requestFailed) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
throw new Error(lastMessage.message || '请求失败');
|
| 546 |
}
|
| 547 |
if (this.failureCount > 0) {
|
|
|
|
| 568 |
this._forwardRequest(proxyRequest);
|
| 569 |
headerMessage = await messageQueue.dequeue();
|
| 570 |
if (headerMessage.event_type === 'error' && headerMessage.status >= 400 && headerMessage.status <= 599) {
|
| 571 |
+
await this._handleRequestFailureAndSwitch(headerMessage, null); // `res` is not available for streaming chunks here
|
| 572 |
this.logger.warn(`[Request] 收到 ${headerMessage.status} 错误,将在 ${this.retryDelay / 1000}秒后重试...`);
|
| 573 |
if (attempt < this.maxRetries) {
|
| 574 |
await new Promise(resolve => setTimeout(resolve, this.retryDelay));
|
|
|
|
| 579 |
break;
|
| 580 |
}
|
| 581 |
if (headerMessage.event_type === 'error' || requestFailed) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 582 |
return this._sendErrorResponse(res, headerMessage.status, headerMessage.message);
|
| 583 |
}
|
| 584 |
if (this.failureCount > 0) {
|
|
|
|
| 654 |
_loadConfiguration() {
|
| 655 |
let config = {
|
| 656 |
httpPort: 7860, host: '0.0.0.0', wsPort: 9998, streamingMode: 'real',
|
| 657 |
+
failureThreshold: 0,
|
| 658 |
+
maxRetries: 3, retryDelay: 2000, browserExecutablePath: null,
|
| 659 |
apiKeys: [],
|
| 660 |
+
immediateSwitchStatusCodes: [],
|
| 661 |
};
|
| 662 |
|
| 663 |
const configPath = path.join(__dirname, 'config.json');
|
|
|
|
| 681 |
if (process.env.API_KEYS) {
|
| 682 |
config.apiKeys = process.env.API_KEYS.split(',');
|
| 683 |
}
|
| 684 |
+
|
| 685 |
+
// NEW: 统一处理 immediateSwitchStatusCodes,环境变量优先于 config.json
|
| 686 |
+
let rawCodes = process.env.IMMEDIATE_SWITCH_STATUS_CODES;
|
| 687 |
+
let codesSource = '环境变量';
|
| 688 |
+
|
| 689 |
+
if (!rawCodes && config.immediateSwitchStatusCodes && Array.isArray(config.immediateSwitchStatusCodes)) {
|
| 690 |
+
rawCodes = config.immediateSwitchStatusCodes.join(',');
|
| 691 |
+
codesSource = 'config.json 文件';
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
if (rawCodes && typeof rawCodes === 'string') {
|
| 695 |
+
config.immediateSwitchStatusCodes = rawCodes
|
| 696 |
+
.split(',')
|
| 697 |
+
.map(code => parseInt(String(code).trim(), 10))
|
| 698 |
+
.filter(code => !isNaN(code) && code >= 400 && code <= 599);
|
| 699 |
+
if (config.immediateSwitchStatusCodes.length > 0) {
|
| 700 |
+
this.logger.info(`[System] 已从 ${codesSource} 加载“立即切换状态码”。`);
|
| 701 |
+
}
|
| 702 |
+
} else {
|
| 703 |
+
config.immediateSwitchStatusCodes = [];
|
| 704 |
+
}
|
| 705 |
|
|
|
|
| 706 |
if (Array.isArray(config.apiKeys)) {
|
| 707 |
config.apiKeys = config.apiKeys.map(k => String(k).trim()).filter(k => k);
|
| 708 |
} else {
|
| 709 |
+
config.apiKeys = [];
|
| 710 |
}
|
| 711 |
|
| 712 |
this.config = config;
|
| 713 |
+
this.logger.info('================ [ 生效配置 ] ================');
|
| 714 |
+
this.logger.info(` HTTP 服务端口: ${this.config.httpPort}`);
|
| 715 |
+
this.logger.info(` 监听地址: ${this.config.host}`);
|
| 716 |
+
this.logger.info(` 流式模式: ${this.config.streamingMode}`);
|
| 717 |
+
// MODIFIED: 日志输出已汉化
|
| 718 |
+
this.logger.info(` 失败计数切换: ${this.config.failureThreshold > 0 ? `连续 ${this.config.failureThreshold} 次失败后切换` : '已禁用'}`);
|
| 719 |
+
this.logger.info(` 立即切换状态码: ${this.config.immediateSwitchStatusCodes.length > 0 ? this.config.immediateSwitchStatusCodes.join(', ') : '已禁用'}`);
|
| 720 |
+
this.logger.info(` 单次请求最大重试: ${this.config.maxRetries}次`);
|
| 721 |
+
this.logger.info(` 重试间隔: ${this.config.retryDelay}ms`);
|
| 722 |
if (this.config.apiKeys && this.config.apiKeys.length > 0) {
|
| 723 |
+
this.logger.info(` API 密钥认证: 已启用 (${this.config.apiKeys.length} 个密钥)`);
|
| 724 |
} else {
|
| 725 |
+
this.logger.info(` API 密钥认证: 已禁用`);
|
| 726 |
}
|
| 727 |
this.logger.info('=============================================================');
|
| 728 |
}
|
|
|
|
| 771 |
if (serverApiKeys.includes(clientKey)) {
|
| 772 |
this.logger.info(`[Auth] API Key 在 '${keySource}' 中找到,验证通过。`);
|
| 773 |
|
|
|
|
| 774 |
if (keySource === 'Query Parameter') {
|
| 775 |
delete req.query.key;
|
| 776 |
this.logger.debug(`[Auth-Cleanup] 已从 req.query 中移除 API Key,以确保请求纯净。`);
|
|
|
|
| 825 |
config: {
|
| 826 |
streamingMode: this.streamingMode,
|
| 827 |
failureThreshold: this.config.failureThreshold,
|
| 828 |
+
immediateSwitchStatusCodes: this.config.immediateSwitchStatusCodes,
|
| 829 |
maxRetries: this.config.maxRetries,
|
| 830 |
authMode: this.authSource.authMode,
|
| 831 |
apiKeyAuth: (this.config.apiKeys && this.config.apiKeys.length > 0) ? 'Enabled' : 'Disabled',
|