holyterra commited on
Commit
df525af
·
verified ·
1 Parent(s): ef0fe37

Delete unified-server.js

Browse files
Files changed (1) hide show
  1. unified-server.js +0 -849
unified-server.js DELETED
@@ -1,849 +0,0 @@
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');
7
- const { EventEmitter } = require('events');
8
- const fs = require('fs');
9
- const path = require('path');
10
- const { firefox } = require('playwright');
11
- const os = require('os');
12
-
13
-
14
- // ===================================================================================
15
- // AUTH SOURCE MANAGEMENT MODULE
16
- // ===================================================================================
17
-
18
- class AuthSource {
19
- constructor(logger) {
20
- this.logger = logger;
21
- this.authMode = 'file'; // Default mode
22
- this.maxIndex = 0;
23
-
24
- if (process.env.AUTH_JSON_1) {
25
- this.authMode = 'env';
26
- this.logger.info('[Auth] 检测到 AUTH_JSON_1 环境变量,切换到环境变量认证模式。');
27
- } else {
28
- this.logger.info('[Auth] 未检测到环境变量认证,将使用 "auth/" 目录下的文件。');
29
- }
30
-
31
- this._calculateMaxIndex();
32
-
33
- if (this.maxIndex === 0) {
34
- this.logger.error(`[Auth] 致命错误:在 '${this.authMode}' 模式下未找到任何有效的认证源。`);
35
- throw new Error("No valid authentication sources found.");
36
- }
37
- }
38
-
39
- _calculateMaxIndex() {
40
- if (this.authMode === 'env') {
41
- let i = 1;
42
- while (process.env[`AUTH_JSON_${i}`]) {
43
- i++;
44
- }
45
- this.maxIndex = i - 1;
46
- } else { // 'file' mode
47
- const authDir = path.join(__dirname, 'auth');
48
- if (!fs.existsSync(authDir)) {
49
- this.logger.warn('[Auth] "auth/" 目录不存在。');
50
- this.maxIndex = 0;
51
- return;
52
- }
53
- try {
54
- const files = fs.readdirSync(authDir);
55
- const authFiles = files.filter(file => /^auth-\d+\.json$/.test(file));
56
- const indices = authFiles.map(file => parseInt(file.match(/^auth-(\d+)\.json$/)[1], 10));
57
- this.maxIndex = indices.length > 0 ? Math.max(...indices) : 0;
58
- } catch (error) {
59
- this.logger.error(`[Auth] 扫描 "auth/" 目录失败: ${error.message}`);
60
- this.maxIndex = 0;
61
- }
62
- }
63
- this.logger.info(`[Auth] 在 '${this.authMode}' 模式下,检测到 ${this.maxIndex} 个认证源。`);
64
- }
65
-
66
- getMaxIndex() {
67
- return this.maxIndex;
68
- }
69
-
70
- getAuth(index) {
71
- if (index > this.maxIndex || index < 1) {
72
- this.logger.error(`[Auth] 请求了无效的认证索引: ${index}`);
73
- return null;
74
- }
75
-
76
- let jsonString;
77
- let sourceDescription;
78
-
79
- if (this.authMode === 'env') {
80
- jsonString = process.env[`AUTH_JSON_${index}`];
81
- sourceDescription = `环境变量 AUTH_JSON_${index}`;
82
- } else { // 'file' mode
83
- const authFilePath = path.join(__dirname, 'auth', `auth-${index}.json`);
84
- sourceDescription = `文件 ${authFilePath}`;
85
- if (!fs.existsSync(authFilePath)) {
86
- this.logger.error(`[Auth] ${sourceDescription} 不存在。`);
87
- return null;
88
- }
89
- try {
90
- jsonString = fs.readFileSync(authFilePath, 'utf-8');
91
- } catch (e) {
92
- this.logger.error(`[Auth] 读取 ${sourceDescription} 失败: ${e.message}`);
93
- return null;
94
- }
95
- }
96
-
97
- try {
98
- return JSON.parse(jsonString);
99
- } catch (e) {
100
- this.logger.error(`[Auth] 解析来自 ${sourceDescription} 的JSON内容失败: ${e.message}`);
101
- return null;
102
- }
103
- }
104
- }
105
-
106
-
107
- // ===================================================================================
108
- // BROWSER MANAGEMENT MODULE
109
- // ===================================================================================
110
-
111
- class BrowserManager {
112
- constructor(logger, config, authSource) {
113
- this.logger = logger;
114
- this.config = config;
115
- this.authSource = authSource;
116
- this.browser = null;
117
- this.context = null;
118
- this.page = null;
119
- this.currentAuthIndex = 0;
120
- this.scriptFileName = 'dark-browser.js';
121
-
122
- if (this.config.browserExecutablePath) {
123
- this.browserExecutablePath = this.config.browserExecutablePath;
124
- this.logger.info(`[System] 使用环境变量 CAMOUFOX_EXECUTABLE_PATH 指定的浏览器路径。`);
125
- } else {
126
- const platform = os.platform();
127
- if (platform === 'win32') {
128
- this.browserExecutablePath = path.join(__dirname, 'camoufox', 'camoufox.exe');
129
- this.logger.info(`[System] 检测到操作系统: Windows. 将使用 'camoufox' 目录下的浏览器。`);
130
- } else if (platform === 'linux') {
131
- this.browserExecutablePath = path.join(__dirname, 'camoufox-linux', 'camoufox');
132
- this.logger.info(`[System] 检测到操作系统: Linux. 将使用 'camoufox-linux' 目录下的浏览器。`);
133
- } else {
134
- this.logger.error(`[System] 不支持的操作系统: ${platform}.`);
135
- throw new Error(`Unsupported operating system: ${platform}`);
136
- }
137
- }
138
- }
139
-
140
- async launchBrowser(authIndex) {
141
- if (this.browser) {
142
- this.logger.warn('尝试启动一个已在运行的浏览器实例,���作已取消。');
143
- return;
144
- }
145
-
146
- const sourceDescription = this.authSource.authMode === 'env' ? `环境变量 AUTH_JSON_${authIndex}` : `文件 auth-${authIndex}.json`;
147
- this.logger.info('==================================================');
148
- this.logger.info(`🚀 [Browser] 准备启动浏览器`);
149
- this.logger.info(` • 认证源: ${sourceDescription}`);
150
- this.logger.info(` • 浏览器路径: ${this.browserExecutablePath}`);
151
- this.logger.info('==================================================');
152
-
153
- if (!fs.existsSync(this.browserExecutablePath)) {
154
- this.logger.error(`❌ [Browser] 找不到浏览器可执行文件: ${this.browserExecutablePath}`);
155
- throw new Error(`Browser executable not found at path: ${this.browserExecutablePath}`);
156
- }
157
-
158
- const storageStateObject = this.authSource.getAuth(authIndex);
159
- if (!storageStateObject) {
160
- this.logger.error(`❌ [Browser] 无法获取或解析索引为 ${authIndex} 的认证信息。`);
161
- throw new Error(`Failed to get or parse auth source for index ${authIndex}.`);
162
- }
163
-
164
- let buildScriptContent;
165
- try {
166
- const scriptFilePath = path.join(__dirname, this.scriptFileName);
167
- buildScriptContent = fs.readFileSync(scriptFilePath, 'utf-8');
168
- this.logger.info(`✅ [Browser] 成功读取注入脚本 "${this.scriptFileName}"`);
169
- } catch (error) {
170
- this.logger.error(`❌ [Browser] 无法读取注入脚本 "${this.scriptFileName}"!`);
171
- throw error;
172
- }
173
-
174
- try {
175
- this.browser = await firefox.launch({
176
- headless: true,
177
- executablePath: this.browserExecutablePath,
178
- });
179
- this.browser.on('disconnected', () => {
180
- this.logger.error('❌ [Browser] 浏览器意外断开连接!服务器可能需要重启。');
181
- this.browser = null; this.context = null; this.page = null;
182
- });
183
- this.context = await this.browser.newContext({
184
- storageState: storageStateObject,
185
- viewport: { width: 1920, height: 1080 },
186
- });
187
- this.page = await this.context.newPage();
188
- this.logger.info(`[Browser] 正在加载账户 ${authIndex} 并访问目标网页...`);
189
- const targetUrl = 'https://aistudio.google.com/u/0/apps/bundled/blank?showPreview=true&showCode=true&showAssistant=true';
190
- await this.page.goto(targetUrl, { timeout: 60000, waitUntil: 'networkidle' });
191
- this.logger.info('[Browser] 网页加载完成,正在注入客户端脚本...');
192
-
193
- const editorContainerLocator = this.page.locator('div.monaco-editor').first();
194
-
195
- this.logger.info('[Browser] 等待编辑器出现,最长60秒...');
196
- await editorContainerLocator.waitFor({ state: 'visible', timeout: 60000 });
197
- this.logger.info('[Browser] 编辑器已出现,准备粘贴脚本。');
198
-
199
- await editorContainerLocator.click();
200
- await this.page.evaluate(text => navigator.clipboard.writeText(text), buildScriptContent);
201
- const isMac = os.platform() === 'darwin';
202
- const pasteKey = isMac ? 'Meta+V' : 'Control+V';
203
- await this.page.keyboard.press(pasteKey);
204
- this.logger.info('[Browser] 脚本已粘贴。浏览器端初始化完成。');
205
-
206
-
207
- this.currentAuthIndex = authIndex;
208
- this.logger.info('==================================================');
209
- this.logger.info(`✅ [Browser] 账户 ${authIndex} 初始化成功!`);
210
- this.logger.info('✅ [Browser] 浏览器客户端已准备就绪。');
211
- this.logger.info('==================================================');
212
- } catch (error) {
213
- this.logger.error(`❌ [Browser] 账户 ${authIndex} 初始化失败: ${error.message}`);
214
- if (this.browser) {
215
- await this.browser.close();
216
- this.browser = null;
217
- }
218
- throw error;
219
- }
220
- }
221
-
222
- async closeBrowser() {
223
- if (this.browser) {
224
- this.logger.info('[Browser] 正在关闭当前浏览器实例...');
225
- await this.browser.close();
226
- this.browser = null; this.context = null; this.page = null;
227
- this.logger.info('[Browser] 浏览器已关闭。');
228
- }
229
- }
230
-
231
- async switchAccount(newAuthIndex) {
232
- this.logger.info(`🔄 [Browser] 开始账号切换: 从 ${this.currentAuthIndex} 到 ${newAuthIndex}`);
233
- await this.closeBrowser();
234
- await this.launchBrowser(newAuthIndex);
235
- this.logger.info(`✅ [Browser] 账号切换完成,当前账号: ${this.currentAuthIndex}`);
236
- }
237
- }
238
-
239
- // ===================================================================================
240
- // PROXY SERVER MODULE
241
- // ===================================================================================
242
-
243
- class LoggingService {
244
- constructor(serviceName = 'ProxyServer') {
245
- this.serviceName = serviceName;
246
- }
247
- _formatMessage(level, message) {
248
- const timestamp = new Date().toISOString();
249
- return `[${level}] ${timestamp} [${this.serviceName}] - ${message}`;
250
- }
251
- info(message) { console.log(this._formatMessage('INFO', message)); }
252
- error(message) { console.error(this._formatMessage('ERROR', message)); }
253
- warn(message) { console.warn(this._formatMessage('WARN', message)); }
254
- debug(message) { console.debug(this._formatMessage('DEBUG', message)); }
255
- }
256
-
257
- class MessageQueue extends EventEmitter {
258
- constructor(timeoutMs = 600000) {
259
- super();
260
- this.messages = [];
261
- this.waitingResolvers = [];
262
- this.defaultTimeout = timeoutMs;
263
- this.closed = false;
264
- }
265
- enqueue(message) {
266
- if (this.closed) return;
267
- if (this.waitingResolvers.length > 0) {
268
- const resolver = this.waitingResolvers.shift();
269
- resolver.resolve(message);
270
- } else {
271
- this.messages.push(message);
272
- }
273
- }
274
- async dequeue(timeoutMs = this.defaultTimeout) {
275
- if (this.closed) {
276
- throw new Error('Queue is closed');
277
- }
278
- return new Promise((resolve, reject) => {
279
- if (this.messages.length > 0) {
280
- resolve(this.messages.shift());
281
- return;
282
- }
283
- const resolver = { resolve, reject };
284
- this.waitingResolvers.push(resolver);
285
- const timeoutId = setTimeout(() => {
286
- const index = this.waitingResolvers.indexOf(resolver);
287
- if (index !== -1) {
288
- this.waitingResolvers.splice(index, 1);
289
- reject(new Error('Queue timeout'));
290
- }
291
- }, timeoutMs);
292
- resolver.timeoutId = timeoutId;
293
- });
294
- }
295
- close() {
296
- this.closed = true;
297
- this.waitingResolvers.forEach(resolver => {
298
- clearTimeout(resolver.timeoutId);
299
- resolver.reject(new Error('Queue closed'));
300
- });
301
- this.waitingResolvers = [];
302
- this.messages = [];
303
- }
304
- }
305
-
306
- class ConnectionRegistry extends EventEmitter {
307
- constructor(logger) {
308
- super();
309
- this.logger = logger;
310
- this.connections = new Set();
311
- this.messageQueues = new Map();
312
- }
313
- addConnection(websocket, clientInfo) {
314
- this.connections.add(websocket);
315
- this.logger.info(`[Server] 内部WebSocket客户端已连接 (来自: ${clientInfo.address})`);
316
- websocket.on('message', (data) => this._handleIncomingMessage(data.toString()));
317
- websocket.on('close', () => this._removeConnection(websocket));
318
- websocket.on('error', (error) => this.logger.error(`[Server] 内部WebSocket连接错误: ${error.message}`));
319
- this.emit('connectionAdded', websocket);
320
- }
321
- _removeConnection(websocket) {
322
- this.connections.delete(websocket);
323
- this.logger.warn('[Server] 内部WebSocket客户端连接断开');
324
- this.messageQueues.forEach(queue => queue.close());
325
- this.messageQueues.clear();
326
- this.emit('connectionRemoved', websocket);
327
- }
328
- _handleIncomingMessage(messageData) {
329
- try {
330
- const parsedMessage = JSON.parse(messageData);
331
- const requestId = parsedMessage.request_id;
332
- if (!requestId) {
333
- this.logger.warn('[Server] 收到无效消息:缺少request_id');
334
- return;
335
- }
336
- const queue = this.messageQueues.get(requestId);
337
- if (queue) {
338
- this._routeMessage(parsedMessage, queue);
339
- } else {
340
- this.logger.warn(`[Server] 收到未知请求ID的消息: ${requestId}`);
341
- }
342
- } catch (error) {
343
- this.logger.error('[Server] 解析内部WebSocket消息失败');
344
- }
345
- }
346
- _routeMessage(message, queue) {
347
- const { event_type } = message;
348
- switch (event_type) {
349
- case 'response_headers': case 'chunk': case 'error':
350
- queue.enqueue(message);
351
- break;
352
- case 'stream_close':
353
- queue.enqueue({ type: 'STREAM_END' });
354
- break;
355
- default:
356
- this.logger.warn(`[Server] 未知的内部事件类型: ${event_type}`);
357
- }
358
- }
359
- hasActiveConnections() { return this.connections.size > 0; }
360
- getFirstConnection() { return this.connections.values().next().value; }
361
- createMessageQueue(requestId) {
362
- const queue = new MessageQueue();
363
- this.messageQueues.set(requestId, queue);
364
- return queue;
365
- }
366
- removeMessageQueue(requestId) {
367
- const queue = this.messageQueues.get(requestId);
368
- if (queue) {
369
- queue.close();
370
- this.messageQueues.delete(requestId);
371
- }
372
- }
373
- }
374
-
375
- class RequestHandler {
376
- constructor(serverSystem, connectionRegistry, logger, browserManager, config, authSource) {
377
- this.serverSystem = serverSystem;
378
- this.connectionRegistry = connectionRegistry;
379
- this.logger = logger;
380
- this.browserManager = browserManager;
381
- this.config = config;
382
- this.authSource = authSource;
383
- this.maxRetries = this.config.maxRetries;
384
- this.retryDelay = this.config.retryDelay;
385
- this.failureCount = 0;
386
- this.isAuthSwitching = false;
387
- }
388
-
389
- get currentAuthIndex() {
390
- return this.browserManager.currentAuthIndex;
391
- }
392
-
393
- _getMaxAuthIndex() {
394
- return this.authSource.getMaxIndex();
395
- }
396
-
397
- _getNextAuthIndex() {
398
- const maxIndex = this._getMaxAuthIndex();
399
- if (maxIndex === 0) return 0; // Should not happen if initial check passes
400
- return this.currentAuthIndex >= maxIndex ? 1 : this.currentAuthIndex + 1;
401
- }
402
-
403
- async _switchToNextAuth() {
404
- if (this.isAuthSwitching) {
405
- this.logger.info('�� [Auth] 正在切换auth文件,跳过重复切换');
406
- return;
407
- }
408
-
409
- this.isAuthSwitching = true;
410
- const nextAuthIndex = this._getNextAuthIndex();
411
- const maxAuthIndex = this._getMaxAuthIndex();
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}`);
419
- this.logger.info('==================================================');
420
-
421
- try {
422
- await this.browserManager.switchAccount(nextAuthIndex);
423
- this.failureCount = 0;
424
- this.logger.info('==================================================');
425
- this.logger.info(`✅ [Auth] 成功切换到账号索引 ${this.currentAuthIndex}`);
426
- this.logger.info(`✅ [Auth] 失败计数已重置为0`);
427
- this.logger.info('==================================================');
428
- } catch (error) {
429
- this.logger.error('==================================================');
430
- this.logger.error(`❌ [Auth] 切换账号失败: ${error.message}`);
431
- this.logger.error('==================================================');
432
- throw error;
433
- } finally {
434
- this.isAuthSwitching = false;
435
- }
436
- }
437
-
438
- async processRequest(req, res) {
439
- this.logger.info(`[Request] 处理请求: ${req.method} ${req.path}`);
440
- if (!this.connectionRegistry.hasActiveConnections()) {
441
- return this._sendErrorResponse(res, 503, '没有可用的浏览器连接');
442
- }
443
- const requestId = this._generateRequestId();
444
- const proxyRequest = this._buildProxyRequest(req, requestId);
445
- const messageQueue = this.connectionRegistry.createMessageQueue(requestId);
446
- try {
447
- if (this.serverSystem.streamingMode === 'fake') {
448
- await this._handlePseudoStreamResponse(proxyRequest, messageQueue, req, res);
449
- } else {
450
- await this._handleRealStreamResponse(proxyRequest, messageQueue, res);
451
- }
452
- } catch (error) {
453
- this._handleRequestError(error, res);
454
- } finally {
455
- this.connectionRegistry.removeMessageQueue(requestId);
456
- }
457
- }
458
- _generateRequestId() { return `${Date.now()}_${Math.random().toString(36).substring(2, 11)}`; }
459
- _buildProxyRequest(req, requestId) {
460
- let requestBody = '';
461
- if (Buffer.isBuffer(req.body)) requestBody = req.body.toString('utf-8');
462
- else if (typeof req.body === 'string') requestBody = req.body;
463
- else if (req.body) requestBody = JSON.stringify(req.body);
464
- return {
465
- path: req.path, method: req.method, headers: req.headers, query_params: req.query,
466
- body: requestBody, request_id: requestId, streaming_mode: this.serverSystem.streamingMode
467
- };
468
- }
469
- _forwardRequest(proxyRequest) {
470
- const connection = this.connectionRegistry.getFirstConnection();
471
- if (connection) {
472
- connection.send(JSON.stringify(proxyRequest));
473
- } else {
474
- throw new Error("无法转发请求:没有可用的WebSocket连接。");
475
- }
476
- }
477
- _sendErrorChunkToClient(res, errorMessage) {
478
- const errorPayload = {
479
- error: { message: `[代理系统提示] ${errorMessage}`, type: 'proxy_error', code: 'proxy_error' }
480
- };
481
- const chunk = `data: ${JSON.stringify(errorPayload)}\n\n`;
482
- if (res && !res.writableEnded) {
483
- res.write(chunk);
484
- this.logger.info(`[Request] 已向客户端发送标准错误信号: ${errorMessage}`);
485
- }
486
- }
487
- async _handlePseudoStreamResponse(proxyRequest, messageQueue, req, res) {
488
- res.status(200).set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' });
489
- this.logger.info('[Request] 已向客户端发送初始响应头,假流式计时器已启动。');
490
- let connectionMaintainer = null;
491
- try {
492
- const keepAliveChunk = this._getKeepAliveChunk(req);
493
- connectionMaintainer = setInterval(() => { if (!res.writableEnded) { res.write(keepAliveChunk); } }, 1000);
494
- let lastMessage, requestFailed = false;
495
- for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
496
- this.logger.info(`[Request] 请求尝试 #${attempt}/${this.maxRetries}...`);
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) {
503
- await new Promise(resolve => setTimeout(resolve, this.retryDelay));
504
- continue;
505
- }
506
- requestFailed = true;
507
- }
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) {
527
- this.logger.info(`✅ [Auth] 请求成功 - 失败计数已从 ${this.failureCount} 重置为 0`);
528
- }
529
- this.failureCount = 0;
530
- const dataMessage = await messageQueue.dequeue();
531
- const endMessage = await messageQueue.dequeue();
532
- if (dataMessage.data) {
533
- res.write(`data: ${dataMessage.data}\n\n`);
534
- this.logger.info('[Request] 已将完整响应体作为SSE事件发送。');
535
- }
536
- if (endMessage.type !== 'STREAM_END') this.logger.warn('[Request] 未收到预期的流结束信号。');
537
- } finally {
538
- if (connectionMaintainer) clearInterval(connectionMaintainer);
539
- if (!res.writableEnded) res.end();
540
- this.logger.info('[Request] 假流式响应处理结束。');
541
- }
542
- }
543
- async _handleRealStreamResponse(proxyRequest, messageQueue, res) {
544
- let headerMessage, requestFailed = false;
545
- for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
546
- this.logger.info(`[Request] 请求尝试 #${attempt}/${this.maxRetries}...`);
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));
553
- continue;
554
- }
555
- requestFailed = true;
556
- }
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) {
573
- this.logger.info(`✅ [Auth] 请求成功 - 失败计数已从 ${this.failureCount} 重置为 0`);
574
- }
575
- this.failureCount = 0;
576
- this._setResponseHeaders(res, headerMessage);
577
- this.logger.info('[Request] 已向客户端发送真实响应头,开始流式传输...');
578
- try {
579
- while (true) {
580
- const dataMessage = await messageQueue.dequeue(30000);
581
- if (dataMessage.type === 'STREAM_END') { this.logger.info('[Request] 收到流结束信号。'); break; }
582
- if (dataMessage.data) res.write(dataMessage.data);
583
- }
584
- } catch (error) {
585
- if (error.message !== 'Queue timeout') throw error;
586
- this.logger.warn('[Request] 真流式响应超时,可能流已正常结束。');
587
- } finally {
588
- if (!res.writableEnded) res.end();
589
- this.logger.info('[Request] 真流式响应连接已关闭。');
590
- }
591
- }
592
- _getKeepAliveChunk(req) {
593
- if (req.path.includes('chat/completions')) {
594
- const payload = { id: `chatcmpl-${this._generateRequestId()}`, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model: "gpt-4", choices: [{ index: 0, delta: {}, finish_reason: null }] };
595
- return `data: ${JSON.stringify(payload)}\n\n`;
596
- }
597
- if (req.path.includes('generateContent') || req.path.includes('streamGenerateContent')) {
598
- const payload = { candidates: [{ content: { parts: [{ text: "" }], role: "model" }, finishReason: null, index: 0, safetyRatings: [] }] };
599
- return `data: ${JSON.stringify(payload)}\n\n`;
600
- }
601
- return 'data: {}\n\n';
602
- }
603
- _setResponseHeaders(res, headerMessage) {
604
- res.status(headerMessage.status || 200);
605
- const headers = headerMessage.headers || {};
606
- Object.entries(headers).forEach(([name, value]) => {
607
- if (name.toLowerCase() !== 'content-length') res.set(name, value);
608
- });
609
- }
610
- _handleRequestError(error, res) {
611
- if (res.headersSent) {
612
- this.logger.error(`[Request] 请求处理错误 (头已发送): ${error.message}`);
613
- if (this.serverSystem.streamingMode === 'fake') this._sendErrorChunkToClient(res, `处理失败: ${error.message}`);
614
- if (!res.writableEnded) res.end();
615
- } else {
616
- this.logger.error(`[Request] 请求处理错误: ${error.message}`);
617
- const status = error.message.includes('超时') ? 504 : 500;
618
- this._sendErrorResponse(res, status, `代理错误: ${error.message}`);
619
- }
620
- }
621
- _sendErrorResponse(res, status, message) {
622
- if (!res.headersSent) res.status(status || 500).type('text/plain').send(message);
623
- }
624
- }
625
-
626
- class ProxyServerSystem extends EventEmitter {
627
- constructor() {
628
- super();
629
- this.logger = new LoggingService('ProxySystem');
630
- this._loadConfiguration();
631
- this.streamingMode = this.config.streamingMode;
632
-
633
- this.authSource = new AuthSource(this.logger);
634
- this.browserManager = new BrowserManager(this.logger, this.config, this.authSource);
635
- this.connectionRegistry = new ConnectionRegistry(this.logger);
636
- this.requestHandler = new RequestHandler(this, this.connectionRegistry, this.logger, this.browserManager, this.config, this.authSource);
637
-
638
- this.httpServer = null;
639
- this.wsServer = null;
640
- }
641
-
642
- _loadConfiguration() {
643
- let config = {
644
- httpPort: 7860, host: '0.0.0.0', wsPort: 9998, streamingMode: 'real',
645
- failureThreshold: 3, maxRetries: 3, retryDelay: 2000, browserExecutablePath: null,
646
- apiKeys: [],
647
- };
648
-
649
- const configPath = path.join(__dirname, 'config.json');
650
- try {
651
- if (fs.existsSync(configPath)) {
652
- const fileConfig = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
653
- config = { ...config, ...fileConfig };
654
- this.logger.info('[System] 已从 config.json 加载配置。');
655
- }
656
- } catch (error) {
657
- this.logger.warn(`[System] 无法读取或解析 config.json: ${error.message}`);
658
- }
659
-
660
- if (process.env.PORT) config.httpPort = parseInt(process.env.PORT, 10) || config.httpPort;
661
- if (process.env.HOST) config.host = process.env.HOST;
662
- if (process.env.STREAMING_MODE) config.streamingMode = process.env.STREAMING_MODE;
663
- if (process.env.FAILURE_THRESHOLD) config.failureThreshold = parseInt(process.env.FAILURE_THRESHOLD, 10) || config.failureThreshold;
664
- if (process.env.MAX_RETRIES) config.maxRetries = parseInt(process.env.MAX_RETRIES, 10) || config.maxRetries;
665
- if (process.env.RETRY_DELAY) config.retryDelay = parseInt(process.env.RETRY_DELAY, 10) || config.retryDelay;
666
- if (process.env.CAMOUFOX_EXECUTABLE_PATH) config.browserExecutablePath = process.env.CAMOUFOX_EXECUTABLE_PATH;
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 = []; // Ensure it's always an array
676
- }
677
-
678
- this.config = config;
679
- this.logger.info('================ [ EFFECTIVE CONFIGURATION ] ================');
680
- this.logger.info(` HTTP Port: ${this.config.httpPort}`);
681
- this.logger.info(` Host: ${this.config.host}`);
682
- this.logger.info(` Streaming Mode: ${this.config.streamingMode}`);
683
- this.logger.info(` Failure Threshold: ${this.config.failureThreshold}`);
684
- this.logger.info(` Max Retries: ${this.config.maxRetries}`);
685
- this.logger.info(` Retry Delay: ${this.config.retryDelay}ms`);
686
- if (this.config.apiKeys && this.config.apiKeys.length > 0) {
687
- this.logger.info(` API Key Auth: Enabled (${this.config.apiKeys.length} keys loaded)`);
688
- } else {
689
- this.logger.info(` API Key Auth: Disabled`);
690
- }
691
- this.logger.info('=============================================================');
692
- }
693
-
694
- async start(initialAuthIndex = 1) {
695
- try {
696
- await this.browserManager.launchBrowser(initialAuthIndex);
697
- await this._startHttpServer();
698
- await this._startWebSocketServer();
699
- this.logger.info(`[System] 代理服务器系统启动完成。`);
700
- this.emit('started');
701
- } catch (error) {
702
- this.logger.error(`[System] 启动失败: ${error.message}`);
703
- this.emit('error', error);
704
- throw error;
705
- }
706
- }
707
-
708
- _createAuthMiddleware() {
709
- return (req, res, next) => {
710
- const serverApiKeys = this.config.apiKeys;
711
- if (!serverApiKeys || serverApiKeys.length === 0) {
712
- return next();
713
- }
714
-
715
- let clientKey = null;
716
- let keySource = null;
717
-
718
- const headers = req.headers;
719
-
720
- if (headers['x-goog-api-key']) {
721
- clientKey = headers['x-goog-api-key'];
722
- keySource = 'x-goog-api-key Header';
723
- } else if (headers.authorization && headers.authorization.startsWith('Bearer ')) {
724
- clientKey = headers.authorization.substring(7);
725
- keySource = 'Authorization Header';
726
- } else if (headers['x-api-key']) {
727
- clientKey = headers['x-api-key'];
728
- keySource = 'X-API-Key Header';
729
- } else if (req.query.key) {
730
- clientKey = req.query.key;
731
- keySource = 'Query Parameter';
732
- }
733
-
734
- if (clientKey) {
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,以确保请求纯净。`);
742
- }
743
- return next();
744
- } else {
745
- this.logger.warn(`[Auth] 拒绝请求: 无效的 API Key。IP: ${req.ip}, Source: ${keySource}, Key: '${clientKey}'`);
746
- return res.status(401).json({ error: { message: "Invalid API key provided." } });
747
- }
748
- }
749
-
750
- this.logger.warn(`[Auth] 拒绝受保护的请求: 缺少 API Key。IP: ${req.ip}, Path: ${req.path}`);
751
- this.logger.debug(`[Auth-Debug] 未在任何标准位置找到API Key。`);
752
- this.logger.debug(`[Auth-Debug] 搜索的Headers: ${JSON.stringify(headers)}`);
753
- this.logger.debug(`[Auth-Debug] 搜索的Query: ${JSON.stringify(req.query)}`);
754
- this.logger.debug(`[Auth-Debug] 已加载的API Keys: [${serverApiKeys.join(', ')}]`);
755
-
756
- return res.status(401).json({ error: { message: "Access denied. A valid API key was not found in headers or query parameters." } });
757
- };
758
- }
759
-
760
- async _startHttpServer() {
761
- const app = this._createExpressApp();
762
- this.httpServer = http.createServer(app);
763
- return new Promise((resolve) => {
764
- this.httpServer.listen(this.config.httpPort, this.config.host, () => {
765
- this.logger.info(`[System] HTTP服务器已在 http://${this.config.host}:${this.config.httpPort} 上监听`);
766
- resolve();
767
- });
768
- });
769
- }
770
-
771
- _createExpressApp() {
772
- const app = express();
773
- app.use(express.json({ limit: '100mb' }));
774
- app.use(express.raw({ type: '*/*', limit: '100mb' }));
775
-
776
- app.get('/admin/set-mode', (req, res) => {
777
- const newMode = req.query.mode;
778
- if (newMode === 'fake' || newMode === 'real') {
779
- this.streamingMode = newMode;
780
- res.status(200).send(`流式模式已切换为: ${this.streamingMode}`);
781
- } else {
782
- res.status(400).send('无效模式. 请用 "fake" 或 "real".');
783
- }
784
- });
785
-
786
- app.get('/health', (req, res) => {
787
- res.status(200).json({
788
- status: 'healthy',
789
- uptime: process.uptime(),
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',
796
- },
797
- auth: {
798
- currentAuthIndex: this.requestHandler.currentAuthIndex,
799
- maxAuthIndex: this.authSource.getMaxIndex(),
800
- failureCount: this.requestHandler.failureCount,
801
- isAuthSwitching: this.requestHandler.isAuthSwitching,
802
- },
803
- browser: {
804
- connected: !!this.browserManager.browser,
805
- },
806
- websocket: {
807
- internalClients: this.connectionRegistry.connections.size
808
- }
809
- });
810
- });
811
-
812
- app.use(this._createAuthMiddleware());
813
-
814
- app.all(/(.*)/, (req, res) => {
815
- if (req.path === '/favicon.ico') return res.status(204).send();
816
- this.requestHandler.processRequest(req, res);
817
- });
818
-
819
- return app;
820
- }
821
-
822
- async _startWebSocketServer() {
823
- this.wsServer = new WebSocket.Server({ port: this.config.wsPort, host: this.config.host });
824
- this.wsServer.on('connection', (ws, req) => {
825
- this.connectionRegistry.addConnection(ws, { address: req.socket.remoteAddress });
826
- });
827
- }
828
- }
829
-
830
- // ===================================================================================
831
- // MAIN INITIALIZATION
832
- // ===================================================================================
833
-
834
- async function initializeServer() {
835
- const initialAuthIndex = parseInt(process.env.INITIAL_AUTH_INDEX, 10) || 1;
836
- try {
837
- const serverSystem = new ProxyServerSystem();
838
- await serverSystem.start(initialAuthIndex);
839
- } catch (error) {
840
- console.error('❌ 服务器启动失败:', error.message);
841
- process.exit(1);
842
- }
843
- }
844
-
845
- if (require.main === module) {
846
- initializeServer();
847
- }
848
-
849
- module.exports = { ProxyServerSystem, BrowserManager, initializeServer };