-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.mjs
More file actions
2449 lines (2229 loc) · 86.3 KB
/
server.mjs
File metadata and controls
2449 lines (2229 loc) · 86.3 KB
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* codex2api 反代服务入口
*
* 将免费 ChatGPT 账号的 Codex/Chat API 能力对外暴露为标准 API 格式。
*
* 启动流程:
* 1. 加载 config-server.json
* 2. 加载 i18n/zh.json
* 3. 初始化 modelMapper
* 4. AccountPool.loadFromRepository()
* 5. 设置调度器
* 6. TokenRefresher.start()
* 7. 注册路由(openai, codex, anthropic, gemini)
* 8. 监听端口
* 9. Ctrl+C 优雅退出
*
* 零依赖: 全用 Node.js 22 内置 http, fs, fetch
*/
import http from 'node:http';
import crypto from 'node:crypto';
import { readFileSync, existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { resolve, normalize, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { log, C } from './lib/utils.mjs';
import {
readBody,
extractBearerToken,
derivePromptCacheSessionId,
resolveRetryPolicy,
isRetryableError,
pickRetryAccount,
isTimeoutError,
isNetworkError,
createTimeoutError,
} from './lib/http-utils.mjs';
import { AccountPool } from './lib/account-pool.mjs';
import { createScheduler } from './lib/scheduler.mjs';
import { TokenRefresher } from './lib/token-refresher.mjs';
import { AutoRelogin } from './lib/auto-relogin.mjs';
import PoolHealthMonitor from './lib/pool-health-monitor.mjs';
import AccountHealthChecker from './lib/account-health-checker.mjs';
import * as modelMapper from './lib/converter/model-mapper.mjs';
import { createOpenAIRoutes } from './routes/openai.mjs';
import { createCodexRoutes } from './routes/codex.mjs';
import { createAnthropicRoutes } from './routes/anthropic.mjs';
import { createGeminiRoutes } from './routes/gemini.mjs';
import {
createAdminRoutes,
logCollector,
initLogPersistence,
handleCredentialsImportGpaApi,
handleCredentialsExportGpaApi,
} from './routes/admin.mjs';
import { StatsCollector } from './lib/stats-collector.mjs';
import * as codexResponses from './lib/converter/openai-responses.mjs';
import { normalizeCollectedUsage } from './lib/converter/openai-responses.mjs';
import { parseSSEStream } from './lib/converter/stream/sse-parser.mjs';
import { authenticateApiKey, setDiscordApiKeyUserStore } from './lib/api-key-auth.mjs';
import { getRealClientIp } from './lib/ip-utils.mjs';
import { initAuthSchema } from './lib/storage/auth-schema.mjs';
import { migrateDiscordUsers } from './lib/storage/migrate-discord-to-unified.mjs';
import { migrateLegacyJsonToSqlite } from './lib/storage/migrate-legacy-json-to-sqlite.mjs';
import { BehaviorAggregator } from './lib/abuse/behavior-aggregator.mjs';
import { RiskLogger } from './lib/abuse/risk-logger.mjs';
import { RuleEngine } from './lib/abuse/rule-engine.mjs';
import { RateLimiter } from './lib/rate-limiter.mjs';
// ============ 路径常量 ============
var __filename = fileURLToPath(import.meta.url);
var __dirname = resolve(__filename, '..');
var CONFIG_PATH = resolve(__dirname, 'config-server.json');
var I18N_PATH = resolve(__dirname, 'i18n/zh.json');
// ============ 加载配置 ============
var config = {};
var i18n = {};
try {
config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
log('✅', C.green, '配置已加载: ' + CONFIG_PATH);
} catch (e) {
log('❌', C.red, '配置加载失败: ' + e.message);
process.exit(1);
}
try {
i18n = JSON.parse(readFileSync(I18N_PATH, 'utf8'));
} catch (e) {
log('⚠️', C.yellow, 'i18n 加载失败,使用空字典: ' + e.message);
}
/**
* i18n 模板替换
* t('account.loaded', { count: 5, active: 3 }) → "已加载 5 个账号(3 可用)"
*/
function t(key, params) {
var parts = key.split('.');
var val = i18n;
for (var i = 0; i < parts.length; i++) {
val = val && val[parts[i]];
}
if (typeof val !== 'string') return key;
if (params) {
var keys = Object.keys(params);
for (var j = 0; j < keys.length; j++) {
val = val.split('{' + keys[j] + '}').join(String(params[keys[j]]));
}
}
return val;
}
function normalizeStorageMode(storage) {
var raw = storage && typeof storage.mode === 'string' ? storage.mode.trim().toLowerCase() : '';
if (raw === 'db' || raw === 'dual' || raw === 'file') return raw;
return 'file';
}
function normalizeStoragePathInConfig(configObj) {
if (!configObj || typeof configObj !== 'object') return;
if (!configObj.storage || typeof configObj.storage !== 'object') return;
if (!configObj.storage.sqlite || typeof configObj.storage.sqlite !== 'object') return;
var rawPath = String(configObj.storage.sqlite.path || '').trim();
if (!rawPath) return;
configObj.storage.sqlite.path = resolve(__dirname, rawPath);
}
function resolveSqliteDbPathFromConfig(configObj) {
var rawPath = '';
if (
configObj
&& configObj.storage
&& configObj.storage.sqlite
&& typeof configObj.storage.sqlite.path === 'string'
) {
rawPath = String(configObj.storage.sqlite.path || '').trim();
}
if (!rawPath) {
return resolve(__dirname, 'data/accounts.db');
}
return resolve(__dirname, rawPath);
}
// ============ 启动时安全检查 ============
var adminPassword = (config.server && config.server.admin_password) || '';
var apiPassword = (config.server && config.server.password) || '';
if (adminPassword && adminPassword.length < 6) {
log('⚠️', C.yellow, t('admin.weak_password'));
}
if (!apiPassword) {
log('⚠️', C.yellow, t('admin.no_api_password'));
}
// ============ 初始化组件 ============
// 模型映射器
modelMapper.init(config.models);
normalizeStoragePathInConfig(config);
// 账号池
var pool = new AccountPool(config, i18n.account);
var loadResult = { loaded: 0, active: 0 };
try {
await pool.initRepository(config.storage);
if (config && config.storage) {
var modeForLog = normalizeStorageMode(config && config.storage);
log('🗄️', C.cyan, '账号仓储已初始化: mode=' + modeForLog + ', driver=' + ((config.storage && config.storage.driver) || 'sqlite'));
}
try {
var legacyMigrationSummary = migrateLegacyJsonToSqlite({
dataDir: resolve(__dirname, 'data'),
dbPath: resolveSqliteDbPathFromConfig(config),
logger: function (message) {
log('🗃️', C.cyan, message);
},
});
if (legacyMigrationSummary && legacyMigrationSummary.errors && legacyMigrationSummary.errors.length > 0) {
log('⚠️', C.yellow, 'legacy JSON 迁移出现错误: ' + legacyMigrationSummary.errors.join(' | '));
}
if (legacyMigrationSummary) {
log(
'🗃️',
C.cyan,
'legacy JSON 迁移完成: inserted=' + legacyMigrationSummary.total_inserted
+ ', processed=' + legacyMigrationSummary.total_processed
+ ', skipped_by_signature=' + legacyMigrationSummary.skipped_by_signature
+ ', skipped_by_missing=' + legacyMigrationSummary.skipped_by_missing
);
}
} catch (e) {
log('⚠️', C.yellow, 'legacy JSON 迁移失败(已跳过,不影响服务启动): ' + (e && e.message ? e.message : String(e)));
}
if (typeof pool.loadFromRepository === 'function') {
var repositoryLoadResult = await pool.loadFromRepository();
loadResult = repositoryLoadResult || loadResult;
log('🗄️', C.cyan, '从数据库加载: ' + repositoryLoadResult.loaded + ' 个账号');
}
} catch (e) {
log('❌', C.red, '账号仓储初始化失败: ' + (e && e.message ? e.message : String(e)));
process.exit(1);
}
// wasted 账号不再自动恢复 — 由 auto-relogin 确认封禁后标记,重启不复活
// 总账号数检查
var totalActive = pool.getActiveCount ? pool.getActiveCount() : loadResult.active;
log('📋', C.cyan, t('account.loaded', { count: pool.getTotalCount(), active: totalActive }));
if (pool.getTotalCount() === 0) {
log('⚠️', C.yellow, t('server.no_accounts'));
}
var accountRepository = typeof pool.getRepository === 'function' ? pool.getRepository() : null;
var accountDb = accountRepository && typeof accountRepository.getDb === 'function'
? accountRepository.getDb()
: null;
if (accountDb) {
try {
initAuthSchema(accountDb);
log('✅', C.green, '认证 schema 已初始化');
} catch (e) {
log('⚠️', C.yellow, '认证 schema 初始化失败(已跳过,不影响现有服务): ' + e.message);
}
try {
var migrationSummary = migrateDiscordUsers(accountDb);
if (migrationSummary && migrationSummary.missing_source_table) {
log('ℹ️', C.cyan, 'Discord→Unified 迁移跳过:未发现 discord_users 表');
} else if (migrationSummary) {
log(
'✅',
C.green,
'Discord→Unified 迁移完成: scanned=' + migrationSummary.scanned
+ ', created_users=' + migrationSummary.created_users
+ ', created_identities=' + migrationSummary.created_identities
+ ', repaired_missing_users=' + migrationSummary.repaired_missing_users
);
}
} catch (e) {
log('⚠️', C.yellow, 'Discord→Unified 迁移失败(已跳过,不影响现有服务): ' + e.message);
}
}
// 调度器
var schedulerMode = (config.scheduler && config.scheduler.mode) || 'round_robin';
var scheduler = createScheduler(schedulerMode);
pool.setScheduler(scheduler);
log('🔄', C.cyan, t('scheduler.' + schedulerMode) || schedulerMode);
// 自动重登器(已废弃,保留初始化避免 import 断链)
var autoRelogin = new AutoRelogin(pool, config, function (level, message, meta) {
logCollector.add(level, message, meta || {});
});
function isAutoReloginEnabled() {
return false;
}
// Token 刷新器
var tokenRefresher = new TokenRefresher(pool, config.credentials, i18n.account, function (level, message, meta) {
logCollector.add(level, message, meta || {});
});
var poolHealthMonitor = new PoolHealthMonitor(pool, config, logCollector);
var accountHealthChecker = new AccountHealthChecker(pool, config, logCollector);
// 统计收集器
var statsCollector = new StatsCollector({
config: config,
dataDir: resolve(__dirname, 'data'),
});
var ABUSE_CONFIG = (config && config.abuse_detection) || {};
var ABUSE_PERSISTED_STATS_CACHE_TTL_MS = 15000;
var _abusePersistedStatsCache = {
loaded_at: 0,
data: new Map(),
};
function normalizeUserIdentity(value) {
var identity = String(value || '').trim();
if (!identity || identity === 'unknown') return '';
return identity;
}
function appendConfiguredIdentity(set, value) {
var identity = normalizeUserIdentity(value);
if (!identity) return;
if (identity.indexOf('discord:') === 0) return;
set.add(identity);
}
function buildDiscordAvatarUrl(discordUserId, avatarHash, size) {
var userId = String(discordUserId || '').trim();
var avatar = String(avatarHash || '').trim();
var iconSize = Math.max(16, Math.floor(toPositiveInt(size, 32)));
if (!userId || !avatar) return '';
if (/^https?:\/\//i.test(avatar)) return avatar;
return 'https://cdn.discordapp.com/avatars/' + userId + '/' + avatar + '.png?size=' + iconSize;
}
function collectConfiguredNonDiscordIdentities() {
var serverCfg = (config && config.server) || {};
var identitySet = new Set();
appendConfiguredIdentity(identitySet, serverCfg.default_identity);
appendConfiguredIdentity(identitySet, serverCfg.admin_username);
var arrayFields = [
serverCfg.whitelist,
serverCfg.whitelist_identities,
serverCfg.admin_users,
serverCfg.admin_identities,
];
for (var i = 0; i < arrayFields.length; i++) {
var identities = arrayFields[i];
if (!Array.isArray(identities)) continue;
for (var j = 0; j < identities.length; j++) {
appendConfiguredIdentity(identitySet, identities[j]);
}
}
var apiKeys = Array.isArray(serverCfg.api_keys) ? serverCfg.api_keys : [];
for (var k = 0; k < apiKeys.length; k++) {
var apiKey = apiKeys[k] || {};
if (apiKey.enabled === false) continue;
appendConfiguredIdentity(identitySet, apiKey.identity);
}
return Array.from(identitySet);
}
function getDiscordUserStoreForAbuse() {
if (
discordAuthRoutes
&& discordAuthRoutes.userStore
&& typeof discordAuthRoutes.userStore.listUsers === 'function'
) {
return discordAuthRoutes.userStore;
}
if (ruleEngine && ruleEngine._userStore && typeof ruleEngine._userStore.listUsers === 'function') {
return ruleEngine._userStore;
}
return null;
}
function getDiscordRegisteredUsersFromStore() {
var userStore = getDiscordUserStoreForAbuse();
if (!userStore || typeof userStore.listUsers !== 'function') return [];
try {
var users = userStore.listUsers();
if (!Array.isArray(users)) return [];
var rows = [];
for (var i = 0; i < users.length; i++) {
var user = users[i] && typeof users[i] === 'object' ? users[i] : {};
var discordUserId = String(user.discord_user_id || '').trim();
if (!discordUserId) continue;
var username = String(user.username || '').trim();
var globalName = String(user.global_name || '').trim();
var avatar = String(user.avatar || '').trim();
var seqId = String(user.seq_id || '').trim();
rows.push({
identity: 'discord:' + discordUserId,
discord_user_id: discordUserId,
username: username,
global_name: globalName,
display_name: globalName || username || seqId || discordUserId,
seq_id: seqId,
avatar: avatar,
avatar_url: buildDiscordAvatarUrl(discordUserId, avatar, 32),
created_at: String(user.created_at || '').trim(),
});
}
return rows;
} catch (_) {
return [];
}
}
function getDiscordRegisteredUserCount() {
return getDiscordRegisteredUsersFromStore().length;
}
function getAbuseRegisteredUsers() {
var rows = [];
var seen = new Set();
var discordRows = getDiscordRegisteredUsersFromStore();
for (var i = 0; i < discordRows.length; i++) {
var row = discordRows[i] && typeof discordRows[i] === 'object' ? discordRows[i] : {};
var discordIdentity = String(row.identity || '').trim();
if (!discordIdentity || seen.has(discordIdentity)) continue;
seen.add(discordIdentity);
rows.push(row);
}
var nonDiscordIdentities = collectConfiguredNonDiscordIdentities();
for (var j = 0; j < nonDiscordIdentities.length; j++) {
var adminIdentity = String(nonDiscordIdentities[j] || '').trim();
if (!adminIdentity || seen.has(adminIdentity)) continue;
seen.add(adminIdentity);
rows.push({
identity: adminIdentity,
discord_user_id: '',
username: adminIdentity,
global_name: '',
display_name: adminIdentity,
seq_id: 'admin_' + String(j + 1),
avatar: '',
avatar_url: '',
created_at: '',
});
}
return rows;
}
function getAbuseOverviewUserCount() {
var registeredUsers = getAbuseRegisteredUsers();
return Array.isArray(registeredUsers) ? registeredUsers.length : 0;
}
function normalizeAbuseStatsIdentity(value) {
var identity = String(value || '').trim();
if (!identity || identity === 'unknown') return '';
return identity;
}
function toNonNegativeInt(value) {
var n = Number(value);
if (!isFinite(n) || n <= 0) return 0;
return Math.floor(n);
}
function getPersistedAbuseIdentityStats() {
var now = Date.now();
if (
_abusePersistedStatsCache
&& _abusePersistedStatsCache.data instanceof Map
&& (now - Number(_abusePersistedStatsCache.loaded_at || 0) < ABUSE_PERSISTED_STATS_CACHE_TTL_MS)
) {
return _abusePersistedStatsCache.data;
}
var out = new Map();
if (!statsCollector || typeof statsCollector.getCallerStatsTotal !== 'function') {
_abusePersistedStatsCache = { loaded_at: now, data: out };
return out;
}
try {
var rows = statsCollector.getCallerStatsTotal();
rows = Array.isArray(rows) ? rows : [];
for (var i = 0; i < rows.length; i++) {
var row = rows[i] && typeof rows[i] === 'object' ? rows[i] : {};
var identity = normalizeAbuseStatsIdentity(row.identity || row.caller_identity || '');
if (!identity) continue;
out.set(identity, {
requests: toNonNegativeInt(row.requests),
input_tokens: toNonNegativeInt(row.input_tokens !== undefined ? row.input_tokens : row.input),
output_tokens: toNonNegativeInt(row.output_tokens !== undefined ? row.output_tokens : row.output),
cached_tokens: toNonNegativeInt(row.cached_tokens !== undefined ? row.cached_tokens : row.cached),
first_seen: 0,
last_seen: 0,
});
}
} catch (_) {
_abusePersistedStatsCache = { loaded_at: now, data: out };
return out;
}
_abusePersistedStatsCache = { loaded_at: now, data: out };
return out;
}
var behaviorAggregator = new BehaviorAggregator({
config: ABUSE_CONFIG,
});
var riskLogger = new RiskLogger({
dataDir: resolve(__dirname, 'data'),
config: ABUSE_CONFIG,
dbPath: (config && config.storage && config.storage.sqlite && config.storage.sqlite.path)
? String(config.storage.sqlite.path)
: resolve(__dirname, 'data/accounts.db'),
});
var ruleEngine = new RuleEngine({
config: ABUSE_CONFIG,
aggregator: behaviorAggregator,
riskLogger: riskLogger,
getUserCount: getAbuseOverviewUserCount,
getRegisteredUsers: getAbuseRegisteredUsers,
getPersistedIdentityStats: getPersistedAbuseIdentityStats,
});
var rateLimiter = new RateLimiter((config && config.rate_limits) || {});
// 日志持久化初始化
initLogPersistence(resolve(__dirname, 'data'));
var MODEL_DISCOVERY_DEFAULT_INTERVAL_MS = 60 * 60 * 1000; // 1h
var MODEL_DISCOVERY_DEFAULT_TIMEOUT_MS = 20000;
var MODEL_DISCOVERY_DEFAULT_CLIENT_VERSION = '0.99.0';
var modelDiscoveryTimer = null;
function toPositiveInt(value, fallback) {
var n = parseInt(value, 10);
if (!isFinite(n) || n <= 0) return fallback;
return n;
}
function getModelDiscoveryConfig() {
var models = (config && config.models) || {};
if (models.discovery && typeof models.discovery === 'object') {
return models.discovery;
}
return {};
}
function isModelDiscoveryEnabled() {
var discovery = getModelDiscoveryConfig();
return discovery.enabled !== false;
}
function getModelDiscoveryIntervalMs() {
var discovery = getModelDiscoveryConfig();
return toPositiveInt(discovery.interval_ms, MODEL_DISCOVERY_DEFAULT_INTERVAL_MS);
}
function buildModelDiscoveryTokenContext() {
var account = pool.getAccount();
if (!account || !account.accessToken) return null;
return {
accessToken: account.accessToken,
sessionToken: account.sessionToken || '',
cookies: account.cookies || {},
email: account.email || '',
};
}
async function refreshUpstreamModels(force) {
if (!isModelDiscoveryEnabled()) {
return {
success: false,
disabled: true,
error: 'model_discovery_disabled',
};
}
var discovery = getModelDiscoveryConfig();
var result = await modelMapper.fetchUpstreamModels(buildModelDiscoveryTokenContext, {
force: force === true,
cacheTtlMs: toPositiveInt(discovery.cache_ttl_ms, MODEL_DISCOVERY_DEFAULT_INTERVAL_MS),
timeoutMs: toPositiveInt(discovery.timeout_ms, MODEL_DISCOVERY_DEFAULT_TIMEOUT_MS),
clientVersion: String(discovery.client_version || MODEL_DISCOVERY_DEFAULT_CLIENT_VERSION),
});
if (result && result.success) {
var models = (result.models && Array.isArray(result.models)) ? result.models : [];
log('🧩', C.green, '上游模型同步成功: ' + models.length + ' 个 [' + models.join(', ') + ']');
} else if (result && !result.disabled) {
var errText = (result && (result.error || (result.cache && result.cache.last_error))) || 'unknown';
log('⚠️', C.yellow, '上游模型同步失败,回退本地配置: ' + errText);
}
return result;
}
// ============ 路由上下文 ============
var ctx = {
pool: pool,
config: config,
i18n: i18n,
t: t,
configPath: CONFIG_PATH,
autoRelogin: autoRelogin,
stats: statsCollector,
poolHealthMonitor: poolHealthMonitor,
accountHealthChecker: accountHealthChecker,
abuse: {
aggregator: behaviorAggregator,
riskLogger: riskLogger,
ruleEngine: ruleEngine,
},
rateLimiter: rateLimiter,
refreshUpstreamModels: function (force) {
return refreshUpstreamModels(force);
},
getUpstreamModelsSnapshot: function () {
if (typeof modelMapper.getUpstreamModelsSnapshot === 'function') {
return modelMapper.getUpstreamModelsSnapshot();
}
return null;
},
};
// 路由处理器
var openaiRoutes = createOpenAIRoutes(ctx);
var codexRoutes = createCodexRoutes(ctx);
var anthropicRoutes = createAnthropicRoutes(ctx);
var geminiRoutes = createGeminiRoutes(ctx);
var adminRoutes = createAdminRoutes(ctx);
var discordAuthRoutes = null;
var userApiRoutes = null;
var emailAuthRoutes = null;
function normalizeHostHeader(hostHeader) {
var host = String(hostHeader || '').trim().toLowerCase();
if (!host) return '';
if (host.indexOf('[') === 0) {
var closingIndex = host.indexOf(']');
if (closingIndex > 0) {
return host.slice(1, closingIndex);
}
return host;
}
var colonIndex = host.indexOf(':');
if (colonIndex >= 0) {
return host.slice(0, colonIndex);
}
return host;
}
var DISCORD_AUTH_ENABLED = !!(config.discord_auth && config.discord_auth.enabled === true);
var DISCORD_PUBLIC_DOMAIN = normalizeHostHeader(config.discord_auth && config.discord_auth.public_domain);
var EMAIL_AUTH_ENABLED = !!(config.auth && config.auth.email && config.auth.email.enabled === true);
if (!accountDb) {
EMAIL_AUTH_ENABLED = false;
log('⚠️', C.yellow, '邮箱登录路由未加载:缺少可用数据库连接');
} else {
try {
var emailAuthModule = await import('./routes/email-auth.mjs');
if (emailAuthModule && typeof emailAuthModule.createEmailAuthRoutes === 'function') {
emailAuthRoutes = await emailAuthModule.createEmailAuthRoutes({
config: config,
db: accountDb,
});
}
if (EMAIL_AUTH_ENABLED) {
log('✅', C.green, '邮箱登录路由已启用');
} else {
log('ℹ️', C.cyan, '邮箱登录路由已注册(当前配置为 disabled)');
}
} catch (err) {
EMAIL_AUTH_ENABLED = false;
emailAuthRoutes = null;
log('⚠️', C.yellow, '邮箱登录路由加载失败,已自动跳过: ' + err.message);
}
}
if (DISCORD_AUTH_ENABLED) {
try {
var discordAuthModule = await import('./routes/discord-auth.mjs');
var userApiModule = await import('./routes/user-api.mjs');
if (discordAuthModule && typeof discordAuthModule.createDiscordAuthRoutes === 'function') {
discordAuthRoutes = await discordAuthModule.createDiscordAuthRoutes({
config: config,
stats: statsCollector,
});
}
ctx.discordUserStore = discordAuthRoutes && discordAuthRoutes.userStore ? discordAuthRoutes.userStore : null;
ctx.discordSessionStore = discordAuthRoutes && discordAuthRoutes.sessionStore ? discordAuthRoutes.sessionStore : null;
ctx.stores = {
userStore: ctx.discordUserStore,
sessionStore: ctx.discordSessionStore,
};
if (userApiModule && typeof userApiModule.createUserApiRoutes === 'function') {
userApiRoutes = await userApiModule.createUserApiRoutes({
config: config,
stats: statsCollector,
ruleEngine: ruleEngine,
stores: ctx.stores,
});
}
if (discordAuthRoutes && discordAuthRoutes.userStore) {
setDiscordApiKeyUserStore(discordAuthRoutes.userStore);
if (ruleEngine && typeof ruleEngine.setUserStore === 'function') {
ruleEngine.setUserStore(discordAuthRoutes.userStore);
}
} else if (ruleEngine && typeof ruleEngine.setUserStore === 'function') {
ruleEngine.setUserStore(null);
}
log('✅', C.green, 'Discord 认证路由已启用 | public_domain=' + (DISCORD_PUBLIC_DOMAIN || '(empty)'));
} catch (err) {
DISCORD_AUTH_ENABLED = false;
discordAuthRoutes = null;
userApiRoutes = null;
ctx.discordUserStore = null;
ctx.discordSessionStore = null;
ctx.stores = { userStore: null, sessionStore: null };
setDiscordApiKeyUserStore(null);
if (ruleEngine && typeof ruleEngine.setUserStore === 'function') {
ruleEngine.setUserStore(null);
}
log('⚠️', C.yellow, 'Discord 路由加载失败,已自动禁用: ' + err.message);
}
} else {
ctx.discordUserStore = null;
ctx.discordSessionStore = null;
ctx.stores = { userStore: null, sessionStore: null };
setDiscordApiKeyUserStore(null);
if (ruleEngine && typeof ruleEngine.setUserStore === 'function') {
ruleEngine.setUserStore(null);
}
}
// ============ 静态文件服务 ============
var PUBLIC_DIR = resolve(__dirname, 'public');
var PUBLIC_USER_DIR = resolve(PUBLIC_DIR, 'user');
var MIME_TYPES = {
html: 'text/html',
css: 'text/css',
js: 'application/javascript',
mjs: 'application/javascript',
json: 'application/json',
txt: 'text/plain',
svg: 'image/svg+xml',
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
webp: 'image/webp',
mp3: 'audio/mpeg',
m4a: 'audio/mp4',
avif: 'image/avif',
ico: 'image/x-icon',
map: 'application/json',
woff: 'font/woff',
woff2: 'font/woff2',
};
var STATIC_CACHE_MAX_BYTES = 2 * 1024 * 1024;
var staticFileCache = new Map();
function getMimeTypeByPath(filePath) {
var idx = String(filePath || '').lastIndexOf('.');
if (idx < 0) return 'application/octet-stream';
var ext = String(filePath).slice(idx + 1).toLowerCase();
return MIME_TYPES[ext] || 'application/octet-stream';
}
function buildStaticContentTypeHeader(mime) {
var baseMime = String(mime || '');
var needsCharset = baseMime.indexOf('text/') === 0
|| baseMime.indexOf('application/json') === 0
|| baseMime.indexOf('application/javascript') === 0;
return needsCharset ? (baseMime + '; charset=utf-8') : baseMime;
}
function resolveStaticPath(rootDir, filePath) {
var decoded = decodeURIComponent(String(filePath || ''));
var fullPath = resolve(rootDir, normalize(decoded));
var rootPrefix = rootDir + sep;
if (fullPath !== rootDir && !fullPath.startsWith(rootPrefix)) {
return '';
}
return fullPath;
}
function staticFileExists(rootDir, filePath) {
var fullPath = '';
try {
fullPath = resolveStaticPath(rootDir, filePath);
} catch (_) {
return false;
}
if (!fullPath) return false;
return existsSync(fullPath);
}
async function serveStaticFromDir(res, rootDir, filePath, contentType) {
var fullPath;
try {
fullPath = resolveStaticPath(rootDir, filePath);
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Bad request' }));
return;
}
if (!fullPath) {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Forbidden' }));
return;
}
var mime = contentType || getMimeTypeByPath(filePath);
var header = buildStaticContentTypeHeader(mime);
var cached = staticFileCache.get(fullPath);
if (cached && cached.header === header) {
res.writeHead(200, { 'Content-Type': cached.header });
res.end(cached.content);
return;
}
var readStart = Date.now();
try {
var content = await readFile(fullPath);
if (content.length <= STATIC_CACHE_MAX_BYTES) {
staticFileCache.set(fullPath, {
content: content,
header: header,
});
}
res.writeHead(200, { 'Content-Type': header });
res.end(content);
var readCost = Date.now() - readStart;
if (readCost > 200) {
log('⏱️', C.yellow, '静态文件读取偏慢: ' + String(filePath || '') + ' | ' + readCost + 'ms');
}
} catch (e) {
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
return;
}
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Internal server error' }));
}
}
function serveStatic(res, filePath, contentType) {
return serveStaticFromDir(res, PUBLIC_DIR, filePath, contentType);
}
async function serveFirstExistingUserHtml(res, candidates) {
for (var i = 0; i < candidates.length; i++) {
var candidate = String(candidates[i] || '');
if (!candidate) continue;
if (!staticFileExists(PUBLIC_USER_DIR, candidate)) continue;
await serveStaticFromDir(res, PUBLIC_USER_DIR, candidate, 'text/html');
return;
}
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
function hasFileExtension(pathname) {
var path = String(pathname || '');
var slashIndex = path.lastIndexOf('/');
var dotIndex = path.lastIndexOf('.');
return dotIndex > slashIndex;
}
async function servePublicUserRoute(res, pathname) {
var path = String(pathname || '');
if (path === '/login' || path === '/login/') {
await serveFirstExistingUserHtml(res, ['login.html', 'login/index.html']);
return true;
}
if (path.startsWith('/login/')) {
var loginFile = path.substring('/login/'.length);
if (!loginFile || !hasFileExtension(loginFile)) {
await serveFirstExistingUserHtml(res, ['login/index.html', 'login.html']);
return true;
}
await serveStaticFromDir(res, PUBLIC_USER_DIR, 'login/' + loginFile);
return true;
}
if (path === '/portal' || path === '/portal/' || path === '/portal/index.html') {
await serveFirstExistingUserHtml(res, ['portal.html', 'portal/index.html']);
return true;
}
if (path.startsWith('/portal/')) {
var portalFile = path.substring('/portal/'.length);
if (!portalFile || !hasFileExtension(portalFile)) {
await serveFirstExistingUserHtml(res, ['portal.html', 'portal/index.html']);
return true;
}
await serveStaticFromDir(res, PUBLIC_USER_DIR, 'portal/' + portalFile);
return true;
}
if (path === '/error' || path === '/error/' || path === '/error/index.html') {
await serveFirstExistingUserHtml(res, ['error.html', 'error/index.html']);
return true;
}
if (path.startsWith('/error/')) {
var errorFile = path.substring('/error/'.length);
if (!errorFile || !hasFileExtension(errorFile)) {
await serveFirstExistingUserHtml(res, ['error.html', 'error/index.html']);
return true;
}
await serveStaticFromDir(res, PUBLIC_USER_DIR, 'error/' + errorFile);
return true;
}
if (path === '/terms' || path === '/terms/' || path === '/terms/index.html') {
await serveFirstExistingUserHtml(res, ['terms.html', 'terms/index.html']);
return true;
}
if (path.startsWith('/terms/')) {
var termsFile = path.substring('/terms/'.length);
if (!termsFile || !hasFileExtension(termsFile)) {
await serveFirstExistingUserHtml(res, ['terms.html', 'terms/index.html']);
return true;
}
await serveStaticFromDir(res, PUBLIC_USER_DIR, 'terms/' + termsFile);
return true;
}
if (path === '/user/terms' || path === '/user/terms/') {
await serveFirstExistingUserHtml(res, ['terms.html', 'terms/index.html']);
return true;
}
if (path === '/user/terms.html') {
await serveFirstExistingUserHtml(res, ['terms.html']);
return true;
}
return false;
}
function normalizePublicStaticPath(pathname) {
var path = String(pathname || '');
if (!path || path === '/' || !path.startsWith('/')) return '';
if (!hasFileExtension(path)) return '';
var relativePath = path.replace(/^\/+/, '');
if (!relativePath) return '';
if (relativePath.startsWith('admin/')) return '';
return relativePath;
}
async function servePublicStaticRoute(res, pathname) {
var staticPath = normalizePublicStaticPath(pathname);
if (!staticPath) return false;
if (!staticFileExists(PUBLIC_DIR, staticPath)) return false;
await serveStatic(res, staticPath);
return true;
}
async function primeStaticCache() {
var candidates = [
'index.html',
'style.css',
'js/main.js',
'js/dashboard.js',
'js/auth.js',
'js/utils.js',
'user/login.html',
'user/portal.html',
'user/error.html',
'user/terms.html',
];
var startAt = Date.now();
var warmed = 0;
await Promise.all(candidates.map(async function (candidate) {
var fullPath = '';
try {
fullPath = resolveStaticPath(PUBLIC_DIR, candidate);
} catch (_) {
return;
}
if (!fullPath || staticFileCache.has(fullPath)) return;
try {
var content = await readFile(fullPath);
if (content.length > STATIC_CACHE_MAX_BYTES) return;
staticFileCache.set(fullPath, {
content: content,
header: buildStaticContentTypeHeader(getMimeTypeByPath(candidate)),
});
warmed++;
} catch (_) {}
}));
var cost = Date.now() - startAt;
log('⚡', C.cyan, '静态缓存预热完成: ' + warmed + ' 个文件 | ' + cost + 'ms');
}
await primeStaticCache();
// ============ 认证辅助 — 用于健康检查详细信息 ============
/**
* 检查请求是否携带有效的管理认证
*/
function hasAdminAuth(req) {
var password = config.server && config.server.admin_password;
if (!password) return false;
var token = extractBearerToken(req.headers['authorization'] || '');
if (!token) return false;
// 复用 admin 的 session 判断(简单检查 token 非空且在 sessions 中)
// 此处直接引用 createAdminRoutes 内部不可访问,所以用 API 密码做备用
var apiPw = config.server && config.server.password;
if (apiPw && token === apiPw) return true;
// 对于 session token 无法在这里验证(sessions 在 admin.mjs 内部),
// 所以也接受 admin_password 本身作为认证(仅健康检查详情)
if (password && token === password) return true;
return false;