holyterra commited on
Commit
25a48a2
·
verified ·
1 Parent(s): 62fa002

Upload 2 files

Browse files
Files changed (2) hide show
  1. Dockerfile +13 -0
  2. unified-server.js +821 -0
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM holyterra/build-server:0623
2
+
3
+ # 切换到user用户
4
+ USER user
5
+ WORKDIR /home/user
6
+
7
+ COPY ./unified-server.js /home/user/unified-server.js
8
+
9
+ # 暴露端口
10
+ EXPOSE 7860
11
+
12
+ # 启动命令
13
+ CMD ["node", "unified-server.js"]
unified-server.js ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // unified-server.js (v6 - API Key Authentication)
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;
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: 8889, host: '0.0.0.0', wsPort: 9998, streamingMode: 'real',
645
+ failureThreshold: 3, maxRetries: 3, retryDelay: 2000, browserExecutablePath: null,
646
+ apiKeys: [], // <-- MODIFICATION: Add apiKeys default
647
+ };
648
+ const configPath = path.join(__dirname, 'config.json');
649
+ try {
650
+ if (fs.existsSync(configPath)) {
651
+ config = { ...config, ...JSON.parse(fs.readFileSync(configPath, 'utf-8')) };
652
+ this.logger.info('[System] 已从 config.json 加载配置。');
653
+ }
654
+ } catch (error) {
655
+ this.logger.warn(`[System] 无法读取或解析 config.json: ${error.message}`);
656
+ }
657
+
658
+ if (process.env.PORT) config.httpPort = parseInt(process.env.PORT, 10) || config.httpPort;
659
+ if (process.env.HOST) config.host = process.env.HOST;
660
+ if (process.env.STREAMING_MODE) config.streamingMode = process.env.STREAMING_MODE;
661
+ if (process.env.FAILURE_THRESHOLD) config.failureThreshold = parseInt(process.env.FAILURE_THRESHOLD, 10) || config.failureThreshold;
662
+ if (process.env.MAX_RETRIES) config.maxRetries = parseInt(process.env.MAX_RETRIES, 10) || config.maxRetries;
663
+ if (process.env.RETRY_DELAY) config.retryDelay = parseInt(process.env.RETRY_DELAY, 10) || config.retryDelay;
664
+ if (process.env.CAMOUFOX_EXECUTABLE_PATH) config.browserExecutablePath = process.env.CAMOUFOX_EXECUTABLE_PATH;
665
+
666
+ // --- MODIFICATION: Load API_KEYS from environment variable ---
667
+ if (process.env.API_KEYS) {
668
+ config.apiKeys = process.env.API_KEYS.split(',').map(key => key.trim()).filter(key => key);
669
+ }
670
+
671
+ this.config = config;
672
+ this.logger.info('================ [ EFFECTIVE CONFIGURATION ] ================');
673
+ this.logger.info(` HTTP Port: ${this.config.httpPort}`);
674
+ this.logger.info(` Host: ${this.config.host}`);
675
+ this.logger.info(` Streaming Mode: ${this.config.streamingMode}`);
676
+ this.logger.info(` Failure Threshold: ${this.config.failureThreshold}`);
677
+ this.logger.info(` Max Retries: ${this.config.maxRetries}`);
678
+ this.logger.info(` Retry Delay: ${this.config.retryDelay}ms`);
679
+ if (this.config.apiKeys.length > 0) {
680
+ this.logger.info(` API Key Auth: ENABLED (${this.config.apiKeys.length} keys loaded)`);
681
+ } else {
682
+ this.logger.info(` API Key Auth: DISABLED`);
683
+ }
684
+ this.logger.info('=============================================================');
685
+ }
686
+
687
+ async start(initialAuthIndex = 1) {
688
+ try {
689
+ await this.browserManager.launchBrowser(initialAuthIndex);
690
+ await this._startHttpServer();
691
+ await this._startWebSocketServer();
692
+ this.logger.info(`[System] 代理服务器系统启动完成。`);
693
+ this.emit('started');
694
+ } catch (error) {
695
+ this.logger.error(`[System] 启动失败: ${error.message}`);
696
+ this.emit('error', error);
697
+ throw error;
698
+ }
699
+ }
700
+
701
+ async _startHttpServer() {
702
+ const app = this._createExpressApp();
703
+ this.httpServer = http.createServer(app);
704
+ return new Promise((resolve) => {
705
+ this.httpServer.listen(this.config.httpPort, this.config.host, () => {
706
+ this.logger.info(`[System] HTTP服务器已在 http://${this.config.host}:${this.config.httpPort} 上监听`);
707
+ resolve();
708
+ });
709
+ });
710
+ }
711
+
712
+ _createExpressApp() {
713
+ const app = express();
714
+ app.use(express.json({ limit: '100mb' }));
715
+ app.use(express.raw({ type: '*/*', limit: '100mb' }));
716
+
717
+ app.get('/admin/set-mode', (req, res) => { /* ... unchanged ... */ });
718
+
719
+ app.get('/health', (req, res) => { /* ... unchanged ... */ });
720
+
721
+ // --- MODIFICATION: Main request handler with authentication middleware ---
722
+ app.all(/(.*)/, (req, res, next) => {
723
+ // Public endpoints that do not require authentication
724
+ if (req.path.startsWith('/admin/') || req.path === '/health') {
725
+ return next();
726
+ }
727
+ if (req.path === '/favicon.ico') {
728
+ return res.status(204).send();
729
+ }
730
+
731
+ // API Key Authentication Middleware
732
+ const apiKeys = this.config.apiKeys;
733
+ if (apiKeys && apiKeys.length > 0) {
734
+ const authHeader = req.headers.authorization;
735
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
736
+ this.logger.warn(`[Auth] Blocked request: Missing or invalid Authorization header from ${req.ip}`);
737
+ return res.status(401).json({ error: { message: 'Authorization header is missing or invalid. Format: "Bearer <YOUR_API_KEY>".', type: 'authentication_error' } });
738
+ }
739
+
740
+ const providedKey = authHeader.substring(7); // "Bearer ".length is 7
741
+
742
+ if (!apiKeys.includes(providedKey)) {
743
+ this.logger.warn(`[Auth] Blocked request: Invalid API Key provided from ${req.ip}`);
744
+ return res.status(401).json({ error: { message: 'Invalid API Key provided.', type: 'authentication_error' } });
745
+ }
746
+
747
+ this.logger.debug(`[Auth] Request from ${req.ip} authenticated successfully.`);
748
+ }
749
+
750
+ // If authentication passes (or is disabled), process the request
751
+ this.requestHandler.processRequest(req, res);
752
+ });
753
+
754
+ // Move admin handlers to be processed by the main app.all router
755
+ app.get('/admin/set-mode', (req, res) => {
756
+ const newMode = req.query.mode;
757
+ if (newMode === 'fake' || newMode === 'real') {
758
+ this.streamingMode = newMode;
759
+ res.status(200).send(`流式模式已切换为: ${this.streamingMode}`);
760
+ } else {
761
+ res.status(400).send('无效模式. 请用 "fake" 或 "real".');
762
+ }
763
+ });
764
+
765
+ app.get('/health', (req, res) => {
766
+ res.status(200).json({
767
+ status: 'healthy',
768
+ uptime: process.uptime(),
769
+ config: {
770
+ streamingMode: this.streamingMode,
771
+ failureThreshold: this.config.failureThreshold,
772
+ maxRetries: this.config.maxRetries,
773
+ authMode: this.authSource.authMode,
774
+ },
775
+ auth: {
776
+ currentAuthIndex: this.requestHandler.currentAuthIndex,
777
+ maxAuthIndex: this.authSource.getMaxIndex(),
778
+ failureCount: this.requestHandler.failureCount,
779
+ isAuthSwitching: this.requestHandler.isAuthSwitching,
780
+ apiKeyAuthEnabled: this.config.apiKeys.length > 0,
781
+ },
782
+ browser: {
783
+ connected: !!this.browserManager.browser,
784
+ },
785
+ websocket: {
786
+ internalClients: this.connectionRegistry.connections.size
787
+ }
788
+ });
789
+ });
790
+
791
+ return app;
792
+ }
793
+
794
+ async _startWebSocketServer() {
795
+ this.wsServer = new WebSocket.Server({ port: this.config.wsPort, host: this.config.host });
796
+ this.wsServer.on('connection', (ws, req) => {
797
+ this.connectionRegistry.addConnection(ws, { address: req.socket.remoteAddress });
798
+ });
799
+ }
800
+ }
801
+
802
+ // ===================================================================================
803
+ // MAIN INITIALIZATION
804
+ // ===================================================================================
805
+
806
+ async function initializeServer() {
807
+ const initialAuthIndex = parseInt(process.env.INITIAL_AUTH_INDEX, 10) || 1;
808
+ try {
809
+ const serverSystem = new ProxyServerSystem();
810
+ await serverSystem.start(initialAuthIndex);
811
+ } catch (error) {
812
+ console.error('❌ 服务器启动失败:', error.message);
813
+ process.exit(1);
814
+ }
815
+ }
816
+
817
+ if (require.main === module) {
818
+ initializeServer();
819
+ }
820
+
821
+ module.exports = { ProxyServerSystem, BrowserManager, initializeServer };