-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
6191 lines (5676 loc) · 243 KB
/
server.js
File metadata and controls
6191 lines (5676 loc) · 243 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
'use strict';
const express = require('express');
const fs = require('fs');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const { spawn } = require('child_process');
const { AsyncLocalStorage } = require('node:async_hooks');
const QRCode = require('qrcode');
const mcpManager = require('./mcp-manager');
const multer = require('multer');
const mammoth = require('mammoth');
const pdfParse = require('pdf-parse');
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 20 * 1024 * 1024 } });
const app = express();
const HOST = process.env.HOST || (process.env.SHARE_MODE === '1' ? '0.0.0.0' : '127.0.0.1');
const PORT = Number(process.env.PORT || 5173);
const SHARE_MODE = HOST === '0.0.0.0' || process.env.SHARE_MODE === '1';
const ACCESS_TOKEN = process.env.ACCESS_TOKEN || '';
const OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'qwen3:8b';
const OLLAMA_BASE_URL = 'http://127.0.0.1:11434';
const RATE_LIMIT_WINDOW_MS = Math.max(1000, Number(process.env.RATE_LIMIT_WINDOW_MS || 60 * 1000));
const RATE_LIMIT_PER_MIN = Number(process.env.RATE_LIMIT_PER_MIN || (SHARE_MODE ? 60 : 240));
const RATE_LIMIT_TRANSLATE_PER_MIN = Number(process.env.RATE_LIMIT_TRANSLATE_PER_MIN || (SHARE_MODE ? 180 : 600));
const RATE_LIMIT_TRUST_CLIENT_ID = process.env.RATE_LIMIT_TRUST_CLIENT_ID !== '0';
const MIN_CN_CHARS = Number(process.env.MIN_CN_CHARS || 800);
const MAX_INPUT_CHARS = Number(process.env.MAX_INPUT_CHARS || 60000);
const OLLAMA_TIMEOUT_MS = Number(process.env.OLLAMA_TIMEOUT_MS || 8 * 60 * 1000);
const OLLAMA_CHAT_TIMEOUT_MS = Number(process.env.OLLAMA_CHAT_TIMEOUT_MS || 12 * 60 * 1000);
const TRANSLATE_TIMEOUT_MS = Number(process.env.TRANSLATE_TIMEOUT_MS || 120 * 1000);
const TRANSLATE_CACHE_TTL_MS = Math.max(0, Number(process.env.TRANSLATE_CACHE_TTL_MS || 30 * 60 * 1000));
const TRANSLATE_CACHE_MAX_ITEMS = Math.max(0, Number(process.env.TRANSLATE_CACHE_MAX_ITEMS || 500));
const KB_EMBED_QUERY_CACHE_TTL_MS = Math.max(0, Number(process.env.KB_EMBED_QUERY_CACHE_TTL_MS || 5 * 60 * 1000));
const KB_EMBED_QUERY_CACHE_MAX_ITEMS = Math.max(0, Number(process.env.KB_EMBED_QUERY_CACHE_MAX_ITEMS || 200));
const KB_EMBED_VECTOR_WEIGHT = Math.max(0, Number(process.env.KB_EMBED_VECTOR_WEIGHT || 2.2));
const KB_EMBED_VECTOR_MIN_SCORE = Math.max(-1, Math.min(1, Number(process.env.KB_EMBED_VECTOR_MIN_SCORE || 0.15)));
const KB_EMBED_BATCH_SIZE = Math.max(1, Math.min(64, Number(process.env.KB_EMBED_BATCH_SIZE || 16)));
const LOREBOOK_MAX_INJECT_CHARS = Math.max(200, Number(process.env.LOREBOOK_MAX_INJECT_CHARS || 2800));
const LOREBOOK_MAX_HITS = Math.max(1, Math.min(24, Number(process.env.LOREBOOK_MAX_HITS || 8)));
const TEAM_SHARING_MEMBER_RATE_PER_MIN_DEFAULT = Math.max(10, Number(process.env.TEAM_SHARING_MEMBER_RATE_PER_MIN_DEFAULT || 120));
const CHAT_THINK = process.env.CHAT_THINK !== '0';
const CHAT_CTX_LIMIT = Number(process.env.CHAT_CTX_LIMIT || 3000);
const CHAT_HISTORY_LIMIT = Number(process.env.CHAT_HISTORY_LIMIT || 8);
const CHAT_USER_MAX_CHARS = Number(process.env.CHAT_USER_MAX_CHARS || 1000);
const CHAT_ASSISTANT_MAX_CHARS = Number(process.env.CHAT_ASSISTANT_MAX_CHARS || 400);
const ALLOW_PUBLIC = process.env.ALLOW_PUBLIC === '1';
const ELECTRON_DESKTOP = process.env.ELECTRON_DESKTOP === '1';
const CONFIG_DIR = path.join(os.homedir(), '.reviewpack');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
let appConfig = loadAppConfig();
let desktopSetupOllamaServeProc = null;
function defaultOllamaProvider() {
return {
id: 'ollama-default',
name: 'Ollama 本地',
type: 'ollama',
baseUrl: '',
apiKey: '',
models: [OLLAMA_MODEL],
availableModels: [],
temperature: null,
maxTokens: null,
enabled: true
};
}
const PRESET_PROVIDERS = [
{ key: 'openai', name: 'OpenAI', type: 'openai_compatible', baseUrl: 'https://api.openai.com/v1', defaultModels: ['gpt-4o', 'gpt-4o-mini', 'o3-mini'], icon: '🟢' },
{ key: 'deepseek', name: 'DeepSeek', type: 'openai_compatible', baseUrl: 'https://api.deepseek.com/v1', defaultModels: ['deepseek-chat', 'deepseek-reasoner'], icon: '🐋' },
{ key: 'kimi', name: 'Kimi (Moonshot)', type: 'openai_compatible', baseUrl: 'https://api.moonshot.cn/v1', defaultModels: ['moonshot-v1-auto', 'kimi-k2.5'], icon: '🌙' },
{ key: 'siliconflow', name: '硅基流动', type: 'openai_compatible', baseUrl: 'https://api.siliconflow.cn/v1', defaultModels: ['Qwen/Qwen3-8B', 'deepseek-ai/DeepSeek-V3'], icon: '🔷' },
{ key: 'zhipu', name: '智谱 AI', type: 'openai_compatible', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', defaultModels: ['glm-4-flash', 'glm-4-plus'], icon: '🧠' },
{ key: 'baichuan', name: '百川 AI', type: 'openai_compatible', baseUrl: 'https://api.baichuan-ai.com/v1', defaultModels: ['Baichuan4'], icon: '🌊' },
{ key: 'anthropic', name: 'Claude (Anthropic)', type: 'anthropic', baseUrl: 'https://api.anthropic.com', defaultModels: ['claude-sonnet-4-20250514', 'claude-haiku-4-20250414'], icon: '🟠' }
];
const PRESET_MCP_SERVERS = [
{ key: 'mcp-time', name: '时间日历', command: 'npx', args: ['-y', '@modelcontextprotocol/server-everything'], icon: '🕐', desc: '获取当前时间、时区转换' },
{ key: 'mcp-fetch', name: '网页读取', command: 'npx', args: ['-y', '@modelcontextprotocol/server-fetch'], icon: '🌐', desc: '抓取网页内容辅助研究' },
{ key: 'mcp-memory', name: '记忆笔记', command: 'npx', args: ['-y', '@modelcontextprotocol/server-memory'], icon: '🧠', desc: '持久化知识图谱笔记' },
{ key: 'mcp-sequentialthinking', name: '深度推理', command: 'npx', args: ['-y', '@modelcontextprotocol/server-sequential-thinking'], icon: '🔗', desc: '分步推理复杂问题' }
];
const TEAM_SHARING_DEFAULTS = Object.freeze({
enabled: false,
publicBaseUrl: '',
memberDefaultRatePerMin: TEAM_SHARING_MEMBER_RATE_PER_MIN_DEFAULT,
members: []
});
const DESKTOP_SETUP_DEFAULTS = Object.freeze({
firstRunCompleted: false,
runtimeMode: 'api',
localModels: [],
wizardVersion: 1,
completedAt: 0
});
function normalizeDesktopSetupConfig(raw) {
const src = raw && typeof raw === 'object' ? raw : {};
const mode = String(src.runtimeMode || 'api').trim().toLowerCase();
const runtimeMode = ['api', 'local', 'hybrid'].includes(mode) ? mode : 'api';
const localModels = Array.isArray(src.localModels) ? src.localModels : [];
return {
firstRunCompleted: Boolean(src.firstRunCompleted),
runtimeMode,
localModels: localModels
.filter((m) => m && typeof m === 'object')
.map((m) => ({
model: String(m.model || '').trim(),
flashEnabled: m.flashEnabled !== false,
thinkingEnabled: Boolean(m.thinkingEnabled)
}))
.filter((m) => m.model)
.slice(0, 24),
wizardVersion: Math.max(1, Number(src.wizardVersion || 1) || 1),
completedAt: Number(src.completedAt) || 0
};
}
function migrateProvider(p) {
if (typeof p.model === 'string' && !Array.isArray(p.models)) {
p.models = p.model ? [p.model] : [];
p.availableModels = p.availableModels || [];
delete p.model;
}
if (!Array.isArray(p.models)) p.models = [];
if (!Array.isArray(p.availableModels)) p.availableModels = [];
return p;
}
function loadAppConfig() {
try {
const raw = fs.readFileSync(CONFIG_FILE, 'utf8');
const parsed = JSON.parse(raw);
if (parsed && Array.isArray(parsed.providers)) {
parsed.providers.forEach(migrateProvider);
return {
providers: parsed.providers,
activeProviderId: parsed.activeProviderId || parsed.providers[0]?.id || 'ollama-default',
mcpServers: Array.isArray(parsed.mcpServers) ? parsed.mcpServers : [],
knowledgeBases: Array.isArray(parsed.knowledgeBases) ? parsed.knowledgeBases : [],
lorebooks: Array.isArray(parsed.lorebooks) ? parsed.lorebooks : [],
teamSharing: normalizeTeamSharingConfig(parsed.teamSharing || {}),
desktopSetup: normalizeDesktopSetupConfig(parsed.desktopSetup || {})
};
}
// migrate old single-provider config
if (parsed && parsed.provider) {
const old = parsed.provider;
const migrated = migrateProvider({
...defaultOllamaProvider(),
...old,
id: old.type === 'openai_compatible' ? 'openai-migrated' : 'ollama-default',
name: old.type === 'openai_compatible' ? 'API (迁移)' : 'Ollama 本地'
});
const providers = [defaultOllamaProvider()];
if (old.type === 'openai_compatible') providers.push(migrated);
return {
providers,
activeProviderId: migrated.id,
mcpServers: [],
knowledgeBases: [],
lorebooks: [],
teamSharing: normalizeTeamSharingConfig({}),
desktopSetup: normalizeDesktopSetupConfig({})
};
}
} catch {}
return {
providers: [defaultOllamaProvider()],
activeProviderId: 'ollama-default',
mcpServers: [],
knowledgeBases: [],
lorebooks: [],
teamSharing: normalizeTeamSharingConfig({}),
desktopSetup: normalizeDesktopSetupConfig({})
};
}
function saveAppConfig() {
try {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.writeFileSync(CONFIG_FILE, JSON.stringify(appConfig, null, 2), 'utf8');
return true;
} catch (error) {
console.error('[config] save failed:', error.message);
return false;
}
}
function getProvider(id) {
return appConfig.providers.find((p) => p.id === id);
}
function getActiveProvider() {
return getProvider(appConfig.activeProviderId) || appConfig.providers[0] || defaultOllamaProvider();
}
function getActiveModel() {
const p = getActiveProvider();
return (p.models && p.models[0]) || OLLAMA_MODEL;
}
function isOpenAI(provider) {
const p = provider || getActiveProvider();
return p.type === 'openai_compatible';
}
function isAnthropic(provider) {
const p = provider || getActiveProvider();
return p.type === 'anthropic';
}
const publicDir = path.join(__dirname, 'public');
const promptsDir = path.join(__dirname, 'prompts');
const reviewPromptTemplate = readPromptOrExit(path.join(promptsDir, 'review_pack_prompt.txt'));
const reviewRepairPromptTemplate = readPromptOrExit(path.join(promptsDir, 'json_repair_prompt.txt'));
const paperPromptTemplate = readPromptOrExit(path.join(promptsDir, 'paper_report_prompt.txt'));
const paperRepairPromptTemplate = readPromptOrExit(path.join(promptsDir, 'paper_report_repair_prompt.txt'));
const rateStore = new Map();
const translateRateStore = new Map();
const translateResultCache = new Map();
const translateInFlight = new Map();
const kbEmbedQueryCache = new Map();
const kbEmbedQueryInFlight = new Map();
const teamShareMemberRateStore = new Map();
const teamShareUsageStore = new Map();
const requestContextStore = new AsyncLocalStorage();
const proxyDispatcherCache = new Map();
let undiciProxyAgentCtor = undefined;
function loadUndiciProxyAgentCtor() {
if (undiciProxyAgentCtor !== undefined) return undiciProxyAgentCtor;
try {
({ ProxyAgent: undiciProxyAgentCtor } = require('undici'));
} catch (_) {
undiciProxyAgentCtor = null;
}
return undiciProxyAgentCtor;
}
function clampTeamShareMemberRate(v, fallback = TEAM_SHARING_MEMBER_RATE_PER_MIN_DEFAULT) {
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return Math.max(10, Math.min(5000, Math.round(n)));
}
function normalizeTeamSharingMember(raw) {
const src = raw && typeof raw === 'object' ? raw : {};
const id = String(src.id || '').trim();
const tokenHash = String(src.tokenHash || '').trim();
if (!id || !tokenHash) return null;
return {
id: id.slice(0, 64),
name: String(src.name || 'Member').trim().slice(0, 80) || 'Member',
tokenHash: tokenHash.slice(0, 200),
tokenPreview: String(src.tokenPreview || '').trim().slice(0, 24),
enabled: src.enabled !== false,
rateLimitPerMin: clampTeamShareMemberRate(src.rateLimitPerMin, TEAM_SHARING_MEMBER_RATE_PER_MIN_DEFAULT),
createdAt: Number(src.createdAt) || Date.now(),
updatedAt: Number(src.updatedAt) || Date.now(),
lastUsedAt: Number(src.lastUsedAt) || 0
};
}
function normalizeTeamSharingConfig(raw) {
const src = raw && typeof raw === 'object' ? raw : {};
const members = Array.isArray(src.members)
? src.members.map(normalizeTeamSharingMember).filter(Boolean)
: [];
return {
enabled: Boolean(src.enabled),
publicBaseUrl: String(src.publicBaseUrl || '').trim().slice(0, 500),
memberDefaultRatePerMin: clampTeamShareMemberRate(src.memberDefaultRatePerMin, TEAM_SHARING_MEMBER_RATE_PER_MIN_DEFAULT),
members
};
}
function ensureTeamSharingConfig() {
appConfig.teamSharing = normalizeTeamSharingConfig(appConfig.teamSharing || {});
return appConfig.teamSharing;
}
function safeJsonParse(text) {
try {
return { ok: true, data: JSON.parse(text) };
} catch (error) {
return { ok: false, error };
}
}
function parseClientProxyHeader(rawHeader) {
if (!rawHeader) return { ok: true, proxy: null };
if (rawHeader.length > 2048) return { ok: false, message: '代理配置头过长。' };
const parsed = safeJsonParse(rawHeader);
if (!parsed.ok || !parsed.data || typeof parsed.data !== 'object') {
return { ok: false, message: '代理配置格式无效。' };
}
const data = parsed.data;
const enabled = Boolean(data.enabled);
if (!enabled) return { ok: true, proxy: null };
const type = String(data.type || '').toLowerCase();
if (!['http', 'https', 'socks5'].includes(type)) {
return { ok: false, message: '代理类型仅支持 http / https / socks5。' };
}
const host = String(data.host || '').trim();
const port = Number(data.port);
if (!host) return { ok: false, message: '代理主机不能为空。' };
if (!Number.isInteger(port) || port < 1 || port > 65535) {
return { ok: false, message: '代理端口无效。' };
}
return {
ok: true,
proxy: {
enabled: true,
type,
host,
port,
user: String(data.user || '').trim(),
pass: String(data.pass || '')
}
};
}
function getRequestProxyConfig() {
return requestContextStore.getStore()?.proxy || null;
}
function isLoopbackHost(hostname) {
const host = String(hostname || '').toLowerCase();
return host === '127.0.0.1' || host === 'localhost' || host === '::1';
}
function shouldBypassProxy(url) {
try {
const u = new URL(url);
return isLoopbackHost(u.hostname);
} catch (_) {
return true;
}
}
function buildProxyUrl(proxy) {
const protocol = proxy.type === 'https' ? 'https' : (proxy.type === 'http' ? 'http' : 'socks5');
const auth = proxy.user
? `${encodeURIComponent(proxy.user)}${proxy.pass ? `:${encodeURIComponent(proxy.pass)}` : ''}@`
: '';
return `${protocol}://${auth}${proxy.host}:${proxy.port}`;
}
function getProxyDispatcher(proxy) {
if (!proxy || !proxy.enabled) return null;
if (proxy.type === 'socks5') {
throw new Error('当前服务端暂不支持 SOCKS5 出站代理,请改用 HTTP/HTTPS 代理端口(如 Clash 的 HTTP/Mixed 端口)。');
}
const ProxyAgentCtor = loadUndiciProxyAgentCtor();
if (!ProxyAgentCtor) {
throw new Error('未安装 undici,无法启用出站代理。请执行 npm install。');
}
const proxyUrl = buildProxyUrl(proxy);
let dispatcher = proxyDispatcherCache.get(proxyUrl);
if (!dispatcher) {
dispatcher = new ProxyAgentCtor(proxyUrl);
proxyDispatcherCache.set(proxyUrl, dispatcher);
}
return dispatcher;
}
async function fetchRuntime(url, options) {
const reqOptions = options || {};
if (shouldBypassProxy(url)) return fetch(url, reqOptions);
const proxy = getRequestProxyConfig();
if (!proxy || !proxy.enabled) return fetch(url, reqOptions);
const dispatcher = getProxyDispatcher(proxy);
return fetch(url, { ...reqOptions, dispatcher });
}
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, x-access-token, Authorization, x-client-id, x-client-proxy-config');
if (req.method === 'OPTIONS') return res.status(204).end();
next();
});
app.use(express.json({ limit: '10mb' }));
app.use('/vendor/katex', express.static(path.join(__dirname, 'node_modules', 'katex', 'dist')));
app.use('/api', (req, res, next) => {
const parsed = parseClientProxyHeader(req.get('x-client-proxy-config') || '');
if (!parsed.ok) {
return res.status(400).json({ error: 'BadProxyConfig', message: parsed.message });
}
requestContextStore.run({ proxy: parsed.proxy }, () => next());
});
if (SHARE_MODE && !ALLOW_PUBLIC) {
app.use((req, res, next) => {
const ip = getClientIp(req);
if (!isPrivateOrLanIp(ip)) {
return res.status(403).json({
error: 'Forbidden',
message: 'share 模式默认仅允许局域网或本机访问。'
});
}
next();
});
}
app.use('/api', (req, res, next) => {
const ip = getClientIp(req) || 'unknown';
const now = Date.now();
const isTranslateApi = req.path === '/translate';
const activeStore = isTranslateApi ? translateRateStore : rateStore;
const activeLimit = isTranslateApi ? RATE_LIMIT_TRANSLATE_PER_MIN : RATE_LIMIT_PER_MIN;
if (!(activeLimit > 0)) return next();
const key = getRateLimitBucketKey(req, ip);
const item = activeStore.get(key) || { windowStart: now, count: 0 };
if (now - item.windowStart >= RATE_LIMIT_WINDOW_MS) {
item.windowStart = now;
item.count = 0;
}
item.count += 1;
activeStore.set(key, item);
res.setHeader('X-RateLimit-Limit', String(activeLimit));
res.setHeader('X-RateLimit-Remaining', String(Math.max(0, activeLimit - item.count)));
if (item.count > activeLimit) {
const retryAfterMs = Math.max(250, item.windowStart + RATE_LIMIT_WINDOW_MS - now);
res.setHeader('Retry-After', String(Math.ceil(retryAfterMs / 1000)));
return res.status(429).json({
error: 'Too Many Requests',
message: `\u8bf7\u6c42\u8fc7\u4e8e\u9891\u7e41\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5\uff08${Math.round(RATE_LIMIT_WINDOW_MS / 1000)} \u79d2\u5185\u6700\u591a ${activeLimit} \u6b21\uff09\u3002`,
retryAfterMs,
windowMs: RATE_LIMIT_WINDOW_MS,
limit: activeLimit
});
}
if (activeStore.size > 5000) {
for (const [staleKey, value] of activeStore.entries()) {
if (now - value.windowStart > Math.max(2 * RATE_LIMIT_WINDOW_MS, 2 * 60 * 1000)) activeStore.delete(staleKey);
}
}
next();
});
app.use('/api', (req, res, next) => {
const headerToken = req.get('x-access-token');
const bearer = req.get('authorization');
const bearerToken = bearer && bearer.toLowerCase().startsWith('bearer ')
? bearer.slice(7).trim()
: '';
const token = headerToken || bearerToken;
req.authRole = 'anonymous';
req.teamSharingMemberId = '';
req.teamSharingMemberName = '';
if (ACCESS_TOKEN && token === ACCESS_TOKEN) {
req.authRole = 'admin';
return next();
}
const teamMember = findTeamSharingMemberByToken(token);
if (teamMember) {
if (!isTeamSharingAllowedApiRoute(req)) {
return res.status(403).json({
error: 'Forbidden',
message: 'This team sharing token is not allowed to access this API route.'
});
}
if (!enforceTeamSharingMemberRateLimit(req, res, teamMember)) return;
req.authRole = 'team_member';
req.teamSharingMemberId = teamMember.id;
req.teamSharingMemberName = teamMember.name;
touchTeamSharingMemberUsage(teamMember, req);
return next();
}
if (!ACCESS_TOKEN) return next();
return res.status(401).json({
error: 'Unauthorized',
message: 'Unauthorized: invalid or missing access token.'
});
});
app.get('/api/info', async (req, res) => {
let liveOllamaAvailableModels = null;
try {
const tags = await ollamaTags(1200);
liveOllamaAvailableModels = (Array.isArray(tags && tags.models) ? tags.models : [])
.map((m) => {
const id = String(m && (m.name || m.model) || '').trim();
return id ? { id, name: id } : null;
})
.filter(Boolean)
.slice(0, 500);
} catch (_) { }
res.json({
host: HOST,
port: PORT,
shareMode: SHARE_MODE,
localIPs: getLocalIpv4s(),
authRequired: Boolean(ACCESS_TOKEN),
tokenRecommended: Boolean(SHARE_MODE && !ACCESS_TOKEN),
warning: SHARE_MODE && !ACCESS_TOKEN ? '当前是 share 模式,建议设置 ACCESS_TOKEN。' : '',
model: getActiveModel(),
providerType: getActiveProvider().type,
providers: appConfig.providers.map((p) => ({
id: p.id,
name: p.name,
type: p.type,
models: p.models || [],
availableModels: p.type === 'ollama' && Array.isArray(liveOllamaAvailableModels)
? liveOllamaAvailableModels
: (p.availableModels || []),
enabled: p.enabled
})),
activeProviderId: appConfig.activeProviderId,
rateLimitPerMin: RATE_LIMIT_PER_MIN,
translateRateLimitPerMin: RATE_LIMIT_TRANSLATE_PER_MIN,
rateLimitWindowMs: RATE_LIMIT_WINDOW_MS,
rateLimitUsesClientId: RATE_LIMIT_TRUST_CLIENT_ID,
teamSharingEnabled: Boolean(ensureTeamSharingConfig().enabled),
teamSharingMemberCount: Array.isArray(ensureTeamSharingConfig().members) ? ensureTeamSharingConfig().members.length : 0,
minChineseChars: MIN_CN_CHARS,
desktopSetup: normalizeDesktopSetupConfig(appConfig.desktopSetup || {})
});
});
function getDesktopSetupVendorOllamaExePath() {
return path.join(__dirname, 'vendor', 'ollama', 'ollama.exe');
}
function getDesktopSetupEnvironmentSnapshot() {
const apiProviders = Array.isArray(appConfig.providers)
? appConfig.providers.filter((p) => p && p.enabled !== false && p.type !== 'ollama')
: [];
const active = getActiveProvider();
return {
isDesktop: ELECTRON_DESKTOP,
apiProvidersConfigured: apiProviders.length > 0,
activeProviderType: active.type,
activeProviderId: active.id,
activeModel: getActiveModel(),
vendorOllamaBundled: fs.existsSync(getDesktopSetupVendorOllamaExePath()),
localOllamaReachable: false,
localOllamaModels: []
};
}
function getDesktopSetupRecommendedMode(env) {
if (env.localOllamaReachable && env.apiProvidersConfigured) return 'hybrid';
if (env.apiProvidersConfigured) return 'api';
if (env.localOllamaReachable) return 'local';
return 'api';
}
function getDesktopSetupVendorOllamaModelsDir() {
return path.join(__dirname, 'vendor', 'ollama', 'models');
}
function normalizeDesktopSetupLocalModelSelectionList(rawList) {
return (Array.isArray(rawList) ? rawList : [])
.filter((m) => m && typeof m === 'object')
.map((m) => ({
model: String(m.model || '').trim(),
flashEnabled: m.flashEnabled !== false,
thinkingEnabled: Boolean(m.thinkingEnabled)
}))
.filter((m) => m.model)
.slice(0, 48);
}
function syncDesktopSetupLocalModelsToOllamaProvider(localModels, runtimeMode) {
const mode = String(runtimeMode || '').trim().toLowerCase();
const selectedModels = normalizeDesktopSetupLocalModelSelectionList(localModels).map((m) => m.model);
if (!selectedModels.length) return;
let ollamaProvider = getProvider('ollama-default');
if (!ollamaProvider) {
ollamaProvider = appConfig.providers.find((p) => p && p.type === 'ollama');
}
if (!ollamaProvider) return;
ollamaProvider.enabled = true;
ollamaProvider.models = Array.from(new Set(selectedModels));
// Keep availableModels as "actually detected" local models only.
// Selected-but-not-installed models belong in desktopSetup.localModels / provider.models,
// and should not be exposed as already available in the runtime model selector.
if (!Array.isArray(ollamaProvider.availableModels)) {
ollamaProvider.availableModels = [];
}
if (mode === 'local') {
appConfig.activeProviderId = ollamaProvider.id || 'ollama-default';
}
}
function estimateOllamaPullTimeoutMs(modelName) {
const text = String(modelName || '').toLowerCase();
if (text.includes('70b') || text.includes('72b') || text.includes('8x22b')) return 3 * 60 * 60 * 1000;
if (text.includes('34b') || text.includes('32b') || text.includes('27b') || text.includes('24b') || text.includes('14b') || text.includes('13b') || text.includes('12b') || text.includes('8x7b')) {
return 2 * 60 * 60 * 1000;
}
return 90 * 60 * 1000;
}
async function waitForOllamaReady(timeoutMs = 25000) {
const deadline = Date.now() + Math.max(5000, Number(timeoutMs) || 25000);
let lastError = null;
while (Date.now() < deadline) {
try {
await ollamaTags();
return true;
} catch (error) {
lastError = error;
await new Promise((r) => setTimeout(r, 700));
}
}
throw lastError || new Error('Ollama not ready');
}
function startBundledOllamaForDesktopSetup() {
const exePath = getDesktopSetupVendorOllamaExePath();
if (!fs.existsSync(exePath)) {
throw new Error('Bundled Ollama runtime not found. Please install/start Ollama first.');
}
if (desktopSetupOllamaServeProc && desktopSetupOllamaServeProc.exitCode == null) {
return { started: false, pid: desktopSetupOllamaServeProc.pid || 0, reused: true };
}
const modelsDir = getDesktopSetupVendorOllamaModelsDir();
try { fs.mkdirSync(modelsDir, { recursive: true }); } catch (_) {}
const env = {
...process.env,
OLLAMA_MODELS: process.env.OLLAMA_MODELS || modelsDir,
OLLAMA_HOST: process.env.OLLAMA_HOST || '127.0.0.1:11434'
};
const child = spawn(exePath, ['serve'], {
cwd: path.dirname(exePath),
stdio: 'ignore',
windowsHide: true,
detached: false,
env
});
child.on('error', () => {});
child.on('exit', () => {
if (desktopSetupOllamaServeProc === child) desktopSetupOllamaServeProc = null;
});
desktopSetupOllamaServeProc = child;
return { started: true, pid: child.pid || 0, reused: false };
}
async function ensureDesktopSetupLocalOllamaReady() {
try {
await waitForOllamaReady(2500);
return { ok: true, startedBundledRuntime: false, source: 'existing' };
} catch (_) {}
let launchInfo = null;
try {
launchInfo = startBundledOllamaForDesktopSetup();
} catch (error) {
return {
ok: false,
startedBundledRuntime: false,
source: 'none',
message: String(error && error.message ? error.message : error)
};
}
try {
await waitForOllamaReady(30000);
return {
ok: true,
startedBundledRuntime: Boolean(launchInfo && launchInfo.started),
source: 'bundled',
pid: launchInfo && launchInfo.pid ? launchInfo.pid : 0
};
} catch (error) {
return {
ok: false,
startedBundledRuntime: Boolean(launchInfo && launchInfo.started),
source: 'bundled',
message: `Bundled Ollama started but did not become ready: ${error && error.message ? error.message : error}`
};
}
}
async function ollamaPullModel(modelName) {
const model = String(modelName || '').trim();
if (!model) throw new Error('Model name required');
const response = await fetchWithTimeout(`${OLLAMA_BASE_URL}/api/pull`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: model, stream: false })
}, estimateOllamaPullTimeoutMs(model));
const raw = await response.text();
if (!response.ok) {
throw new Error(`Ollama pull failed: HTTP ${response.status} ${safeSnippet(raw)}`);
}
let payload = {};
if (raw) {
try {
payload = JSON.parse(raw);
} catch (_) {
payload = { status: raw.slice(0, 200) };
}
}
return payload;
}
app.get('/api/setup/wizard-status', async (req, res) => {
if (!requireAdminManagementRequest(req, res)) return;
const env = getDesktopSetupEnvironmentSnapshot();
try {
const tags = await ollamaTags();
env.localOllamaReachable = true;
env.localOllamaModels = Array.isArray(tags && tags.models)
? tags.models.map((m) => String(m && (m.name || m.model) || '')).filter(Boolean).slice(0, 100)
: [];
} catch (_) {
env.localOllamaReachable = false;
}
res.json({
ok: true,
desktop: ELECTRON_DESKTOP,
setup: normalizeDesktopSetupConfig(appConfig.desktopSetup || {}),
environment: env,
recommendation: {
mode: getDesktopSetupRecommendedMode(env),
reason: env.apiProvidersConfigured
? (env.localOllamaReachable ? 'Detected both API provider and local Ollama.' : 'Detected API provider, local Ollama not reachable.')
: (env.localOllamaReachable ? 'Detected local Ollama, no API provider configured yet.' : 'No local runtime or API provider detected; API mode is simplest to start.')
}
});
});
app.post('/api/setup/wizard-complete', (req, res) => {
if (!requireAdminManagementRequest(req, res)) return;
const body = req.body && typeof req.body === 'object' ? req.body : {};
const runtimeMode = String(body.runtimeMode || '').trim().toLowerCase();
const mode = ['api', 'local', 'hybrid'].includes(runtimeMode) ? runtimeMode : '';
if (!mode) {
return res.status(400).json({
error: 'InvalidRuntimeMode',
message: 'runtimeMode must be one of: api, local, hybrid'
});
}
const localModels = Array.isArray(body.localModels) ? body.localModels : [];
appConfig.desktopSetup = normalizeDesktopSetupConfig({
...(appConfig.desktopSetup || {}),
firstRunCompleted: true,
runtimeMode: mode,
localModels,
wizardVersion: Number(body.wizardVersion || 1) || 1,
completedAt: Date.now()
});
try {
syncDesktopSetupLocalModelsToOllamaProvider(appConfig.desktopSetup.localModels, mode);
} catch (_) {}
if (!saveAppConfig()) {
return res.status(500).json({ error: 'ConfigSaveFailed', message: 'Failed to save setup wizard config.' });
}
res.json({ ok: true, setup: normalizeDesktopSetupConfig(appConfig.desktopSetup || {}) });
});
app.post('/api/setup/wizard-reset', (req, res) => {
if (!requireAdminManagementRequest(req, res)) return;
appConfig.desktopSetup = normalizeDesktopSetupConfig({ firstRunCompleted: false, runtimeMode: 'api', localModels: [] });
if (!saveAppConfig()) {
return res.status(500).json({ error: 'ConfigSaveFailed', message: 'Failed to reset setup wizard config.' });
}
res.json({ ok: true, setup: normalizeDesktopSetupConfig(appConfig.desktopSetup || {}) });
});
app.post('/api/setup/wizard-install-local-models', async (req, res) => {
if (!requireAdminManagementRequest(req, res)) return;
const body = req.body && typeof req.body === 'object' ? req.body : {};
const requestedModels = normalizeDesktopSetupLocalModelSelectionList(
Array.isArray(body.localModels) ? body.localModels : (appConfig.desktopSetup && appConfig.desktopSetup.localModels)
);
if (!requestedModels.length) {
return res.json({
ok: true,
skipped: true,
message: 'No local models selected.',
results: [],
environment: getDesktopSetupEnvironmentSnapshot()
});
}
const runtimeReady = await ensureDesktopSetupLocalOllamaReady();
if (!runtimeReady.ok) {
return res.status(502).json({
error: 'LocalOllamaUnavailable',
message: runtimeReady.message || 'Local Ollama is not available.',
startedBundledRuntime: Boolean(runtimeReady.startedBundledRuntime)
});
}
let currentTags = null;
try {
currentTags = await ollamaTags();
} catch (error) {
return res.status(502).json({
error: 'OllamaTagsFailed',
message: `Connected to local Ollama but failed to query models: ${error.message || error}`
});
}
const installedSet = new Set(
(Array.isArray(currentTags && currentTags.models) ? currentTags.models : [])
.map((m) => String(m && (m.name || m.model) || '').trim())
.filter(Boolean)
);
const results = [];
for (const item of requestedModels) {
const model = item.model;
if (installedSet.has(model)) {
results.push({ model, status: 'already-installed' });
continue;
}
try {
const payload = await ollamaPullModel(model);
results.push({
model,
status: 'installed',
detail: String(payload && (payload.status || payload.message) || 'ok')
});
installedSet.add(model);
} catch (error) {
results.push({
model,
status: 'failed',
error: String(error && (error.message || error) || 'pull failed')
});
}
}
try {
const afterTags = await ollamaTags();
const ollamaProvider = getProvider('ollama-default') || appConfig.providers.find((p) => p && p.type === 'ollama');
if (ollamaProvider) {
const available = Array.isArray(afterTags && afterTags.models) ? afterTags.models : [];
ollamaProvider.availableModels = available
.map((m) => {
const id = String(m && (m.name || m.model) || '').trim();
return id ? { id, name: id } : null;
})
.filter(Boolean)
.slice(0, 500);
syncDesktopSetupLocalModelsToOllamaProvider(requestedModels, (appConfig.desktopSetup && appConfig.desktopSetup.runtimeMode) || 'local');
saveAppConfig();
}
} catch (_) {
// Ignore follow-up sync failure; install results are still useful.
}
const failed = results.filter((r) => r.status === 'failed');
res.status(failed.length ? 207 : 200).json({
ok: failed.length === 0,
partial: failed.length > 0,
startedBundledRuntime: Boolean(runtimeReady.startedBundledRuntime),
results,
summary: {
requested: requestedModels.length,
installed: results.filter((r) => r.status === 'installed').length,
alreadyInstalled: results.filter((r) => r.status === 'already-installed').length,
failed: failed.length
}
});
});
app.get('/api/health', async (req, res) => {
// Try active provider first, then fall back to any enabled provider
const enabledProviders = appConfig.providers.filter((p) => p.enabled);
const active = getActiveProvider();
const ordered = [active, ...enabledProviders.filter((p) => p.id !== active.id)];
for (const provider of ordered) {
try {
const result = await llmTestConnectionFor(provider);
return res.json({
ok: true,
model: (provider.models && provider.models[0]) || OLLAMA_MODEL,
model_available: true,
providerType: provider.type,
message: result.message
});
} catch (_) { /* try next */ }
}
res.status(503).json({
ok: false,
model: getActiveModel(),
model_available: false,
providerType: active.type,
message: '所有 Provider 均无法连接'
});
});
// ── Multi-provider CRUD ──
app.get('/api/team-sharing/status', (req, res) => {
if (!requireAdminManagementRequest(req, res)) return;
res.json(buildTeamSharingStatusPayload());
});
app.post('/api/team-sharing/config', (req, res) => {
if (!requireAdminManagementRequest(req, res)) return;
const body = req.body || {};
const cfg = ensureTeamSharingConfig();
if (Object.prototype.hasOwnProperty.call(body, 'enabled')) {
const nextEnabled = Boolean(body.enabled);
if (nextEnabled && !ACCESS_TOKEN) {
return res.status(400).json({
error: 'AccessTokenRequired',
message: '启用 Team Sharing 前请先配置 ACCESS_TOKEN(避免管理接口暴露)。'
});
}
cfg.enabled = nextEnabled;
}
if (Object.prototype.hasOwnProperty.call(body, 'publicBaseUrl')) {
const raw = String(body.publicBaseUrl || '').trim();
if (raw && !/^https?:\/\/.+/i.test(raw)) {
return res.status(400).json({
error: 'BadRequest',
message: 'publicBaseUrl 必须以 http:// 或 https:// 开头。'
});
}
cfg.publicBaseUrl = raw.replace(/\/+$/, '').slice(0, 500);
}
if (Object.prototype.hasOwnProperty.call(body, 'memberDefaultRatePerMin')) {
cfg.memberDefaultRatePerMin = clampTeamShareMemberRate(body.memberDefaultRatePerMin, cfg.memberDefaultRatePerMin);
}
if (!saveAppConfig()) {
return res.status(500).json({ error: 'SaveFailed', message: '保存 Team Sharing 配置失败。' });
}
res.json({ ok: true, status: buildTeamSharingStatusPayload() });
});
app.post('/api/team-sharing/members', (req, res) => {
if (!requireAdminManagementRequest(req, res)) return;
const cfg = ensureTeamSharingConfig();
const body = req.body || {};
const name = String(body.name || '').trim() || `Member ${cfg.members.length + 1}`;
const token = generateTeamSharingToken();
const now = Date.now();
const member = normalizeTeamSharingMember({
id: `tm_${now.toString(36)}_${crypto.randomBytes(4).toString('hex')}`,
name: name.slice(0, 80),
tokenHash: stableSha256(token),
tokenPreview: tokenPreview(token),
enabled: body.enabled !== false,
rateLimitPerMin: clampTeamShareMemberRate(body.rateLimitPerMin, cfg.memberDefaultRatePerMin || TEAM_SHARING_MEMBER_RATE_PER_MIN_DEFAULT),
createdAt: now,
updatedAt: now,
lastUsedAt: 0
});
if (!member) {
return res.status(500).json({ error: 'CreateFailed', message: '创建 Team Sharing 成员失败。' });
}
cfg.members.push(member);
if (!saveAppConfig()) {
return res.status(500).json({ error: 'SaveFailed', message: '保存 Team Sharing 成员失败。' });
}
res.json({
ok: true,
member: sanitizeTeamSharingMember(member),
token,