Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
926 lines (796 loc) · 30.5 KB
/
Copy pathapp.js
File metadata and controls
926 lines (796 loc) · 30.5 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
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const fs = require('fs').promises;
const path = require('path');
const app = express();
const os = require('os');
const crypto = require('crypto');
const basicAuth = require('basic-auth');
const { execSync } = require('child_process');
const USERNAME = process.env.USERNAME || 'admin';
const PASSWORD = process.env.PASSWORD || 'admin';
const API_URL = process.env.API_URL || 'https://sublink.eooce.com'; // 订阅转换地址
const PORT = process.env.SERVER_PORT || process.env.PORT || 3000;
const SUB_TOKEN = process.env.SUB_TOKEN || generateRandomString();
let subscriptions = [];
let nodes = '';
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const DATA_FILE = path.join(DATA_DIR, 'data.json');
const CREDENTIALS_FILE = path.join(DATA_DIR, 'credentials.json');
// 检查数据目录
async function ensureDataDir() {
try {
await fs.access(DATA_DIR);
} catch {
await fs.mkdir(DATA_DIR, { recursive: true });
}
}
// 初始化数据
const initialData = {
subscriptions: [],
nodes: ''
};
// 初始化凭证变量
let credentials = {
username: USERNAME,
password: PASSWORD
};
// 身份验证中间件
const auth = async (req, res, next) => {
const user = basicAuth(req);
if (!user || user.name !== credentials.username || user.pass !== credentials.password) {
res.set('WWW-Authenticate', 'Basic realm="Node"');
return res.status(401).send('认证失败');
}
next();
};
// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
// 中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 获取 SUB_TOKEN 的路由
app.get('/get-sub-token', auth, (req, res) => {
res.json({ token: SUB_TOKEN });
});
// 获取 API_URL
app.get('/get-apiurl', auth, (req, res) => {
res.json({ ApiUrl: API_URL });
});
// 生成随机20位字符的函数
function generateRandomString() {
const user = getSystemUsername();
const hostname = os.hostname();
// 结合主机名和用户名生成唯一token
const uniqueString = `${hostname}-${user}`;
const hash = crypto.createHash('md5').update(uniqueString).digest('hex');
return hash.slice(0, 20); // 截取前20位
}
// 获取系统用户名
function getSystemUsername() {
try {
return execSync('whoami').toString().trim().toLowerCase();
} catch (error) {
console.error('Error getting system username:', error);
return 'admin';
}
}
// 初始化凭证文件
async function initializeCredentialsFile() {
try {
// 检查文件是否存在
try {
await fs.access(CREDENTIALS_FILE);
console.log('Credentials file already exists');
return true;
} catch {
// 文件不存在,创建新文件
const initialCredentials = {
username: USERNAME,
password: PASSWORD
};
await fs.writeFile(
CREDENTIALS_FILE,
JSON.stringify(initialCredentials, null, 2),
'utf8'
);
console.log('Created new credentials file with environment variables or default admin credentials');
return true;
}
} catch (error) {
console.error('Error initializing credentials file:', error);
return false;
}
}
// 加载凭证
async function loadCredentials() {
try {
await initializeCredentialsFile();
const data = await fs.readFile(CREDENTIALS_FILE, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Error loading credentials:', error);
return {
username: USERNAME,
password: PASSWORD
};
}
}
// 保存凭证
async function saveCredentials(newCredentials) {
try {
await fs.writeFile(
CREDENTIALS_FILE,
JSON.stringify(newCredentials, null, 2),
'utf8'
);
return true;
} catch (error) {
console.error('Error saving credentials:', error);
return false;
}
}
// 凭证更新路由
app.post('/admin/update-credentials', auth, async (req, res) => {
try {
console.log('Received update request:', req.body);
const { username, password, currentPassword } = req.body;
// 验证请求数据是否存在
if (!req.body || typeof req.body !== 'object') {
return res.status(400).json({ error: '无效的请求数据' });
}
// 验证所有必需字段
if (!username || !password || !currentPassword) {
return res.status(400).json({ error: '所有字段都必须填写' });
}
// 验证当前密码
const currentCredentials = await loadCredentials();
if (currentPassword !== currentCredentials.password) {
console.log('Current password verification failed');
return res.status(400).json({ error: '当前密码错误' });
}
const newCredentials = {
username: username,
password: password
};
const saved = await saveCredentials(newCredentials);
if (!saved) {
return res.status(500).json({ error: '保存密码失败' });
}
credentials = newCredentials;
console.log('Credentials updated successfully');
res.json({ message: '密码修改成功' });
} catch (error) {
console.error('Error updating credentials:', error);
res.status(500).json({ error: '修改失败: ' + error.message });
}
});
// 管理页面和管理验证
app.use(['/admin', '/'], (req, res, next) => {
// 排除订阅链接路径
if (req.path === `/${SUB_TOKEN}`) {
return next();
}
// 排除首页
if (req.path === '/' && req.method === 'GET') {
return next();
}
// 排除 API 路径
if (req.path.startsWith('/api/')) {
return next();
}
// 其他路径应用验证
return auth(req, res, next);
});
// 初始化数据文件
async function initializeDataFile() {
try {
let data;
try {
// 尝试读取现有文件
data = await fs.readFile(DATA_FILE, 'utf8');
console.log('Existing data file found');
} catch {
// 文件不存在,创建新文件
console.log('Creating new data file with initial data...');
data = JSON.stringify(initialData, null, 2);
await fs.writeFile(DATA_FILE, data);
console.log('Data file created successfully');
}
const parsedData = JSON.parse(data);
subscriptions = parsedData.subscriptions || [];
nodes = parsedData.nodes || '';
console.log('Data loaded into memory:', { subscriptions, nodes });
} catch (error) {
console.error('Error during initialization:', error);
// 如果出错,使用初始数据
subscriptions = initialData.subscriptions;
nodes = initialData.nodes;
}
}
// 读取数据
async function loadData() {
try {
const data = await fs.readFile(DATA_FILE, 'utf8');
const parsedData = JSON.parse(data);
subscriptions = Array.isArray(parsedData.subscriptions)
? parsedData.subscriptions
: [];
nodes = typeof parsedData.nodes === 'string'
? parsedData.nodes
: '';
console.log('Data loaded successfully:', { subscriptions, nodes });
} catch (error) {
console.error('Error loading data:', error);
// 如果出错,初始化为空数据
subscriptions = [];
nodes = '';
}
}
// 添加订阅路由
app.post('/admin/add-subscription', async (req, res) => {
try {
const newSubscriptionInput = req.body.subscription?.trim();
console.log('Attempting to add subscription(s):', newSubscriptionInput);
if (!newSubscriptionInput) {
return res.status(400).json({ error: 'Subscription URL is required' });
}
if (!Array.isArray(subscriptions)) {
subscriptions = [];
}
// 分割多行输入
const newSubscriptions = newSubscriptionInput.split('\n')
.map(sub => sub.trim())
.filter(sub => sub); // 过滤空行
// 检查每个订阅是否已存在
const addedSubs = [];
const existingSubs = [];
for (const sub of newSubscriptions) {
if (subscriptions.some(existingSub => existingSub.trim() === sub)) {
existingSubs.push(sub);
} else {
addedSubs.push(sub);
subscriptions.push(sub);
}
}
if (addedSubs.length > 0) {
await saveData(subscriptions, nodes);
console.log('Subscriptions added successfully. Current subscriptions:', subscriptions);
const message = addedSubs.length === newSubscriptions.length
? '订阅添加成功'
: `成功添加 ${addedSubs.length} 个订阅,${existingSubs.length} 个订阅已存在`;
res.status(200).json({ message });
} else {
res.status(400).json({ error: '所有订阅已存在' });
}
} catch (error) {
console.error('Error adding subscription:', error);
res.status(500).json({ error: 'Failed to add subscription' });
}
});
// 检查并解码 base64
function tryDecodeBase64(str) {
const base64Regex = /^[A-Za-z0-9+/=]+$/;
try {
if (base64Regex.test(str)) {
const decoded = Buffer.from(str, 'base64').toString('utf-8');
if (decoded.startsWith('vmess://') ||
decoded.startsWith('vless://') ||
decoded.startsWith('trojan://') ||
decoded.startsWith('ss://') ||
decoded.startsWith('ssr://') ||
decoded.startsWith('snell://') ||
decoded.startsWith('juicity://') ||
decoded.startsWith('hysteria://') ||
decoded.startsWith('hysteria2://') ||
decoded.startsWith('tuic://') ||
decoded.startsWith('anytls://') ||
decoded.startsWith('wireguard://') ||
decoded.startsWith('socks5://') ||
decoded.startsWith('http://') ||
decoded.startsWith('https://')) {
return decoded;
}
}
// 如果不是 base64 或解码后不是有效节点,返回原始字符串
return str;
} catch (error) {
console.log('Not a valid base64 string, using original input');
return str;
}
}
// 添加节点路由
app.post('/admin/add-node', async (req, res) => {
try {
const newNode = req.body.node?.trim();
console.log('Attempting to add node:', newNode);
if (!newNode) {
return res.status(400).json({ error: 'Node is required' });
}
let nodesList = typeof nodes === 'string'
? nodes.split('\n').map(n => n.trim()).filter(n => n)
: [];
const newNodes = newNode.split('\n')
.map(n => n.trim())
.filter(n => n)
.map(n => tryDecodeBase64(n));
const addedNodes = [];
const existingNodes = [];
// 处理每个新节点
for (const node of newNodes) {
if (nodesList.some(existingNode => existingNode === node)) {
existingNodes.push(node);
} else {
addedNodes.push(node);
nodesList.push(node);
}
}
if (addedNodes.length > 0) {
nodes = nodesList.join('\n');
await saveData(subscriptions, nodes);
console.log('Node(s) added successfully');
const message = addedNodes.length === newNodes.length
? '节点添加成功'
: `成功添加 ${addedNodes.length} 个节点,${existingNodes.length} 个节点已存在`;
res.status(200).json({ message });
} else {
res.status(400).json({ error: '所有节点已存在' });
}
} catch (error) {
console.error('Error adding node:', error);
res.status(500).json({ error: 'Failed to add node' });
}
});
// 移除特殊字符
function cleanNodeString(str) {
return str
.replace(/^["'`]+|["'`]+$/g, '') // 移除首尾的引号
.replace(/,+$/g, '') // 移除末尾的逗号
.replace(/\s+/g, '') // 移除所有空白字符
.trim();
}
// 删除订阅路由
app.post('/admin/delete-subscription', async (req, res) => {
try {
const subsToDelete = req.body.subscription?.trim();
console.log('Attempting to delete subscription(s):', subsToDelete);
if (!subsToDelete) {
return res.status(400).json({ error: 'Subscription URL is required' });
}
if (!Array.isArray(subscriptions)) {
subscriptions = [];
return res.status(404).json({ error: 'No subscriptions found' });
}
// 分割多行输入
const deleteList = subsToDelete.split('\n')
.map(sub => sub.trim())
.filter(sub => sub);
// 记录删除结果
const deletedSubs = [];
const notFoundSubs = [];
// 处理每个要删除的订阅
deleteList.forEach(subToDelete => {
const index = subscriptions.findIndex(sub =>
sub.trim() === subToDelete.trim()
);
if (index !== -1) {
deletedSubs.push(subToDelete);
subscriptions.splice(index, 1);
} else {
notFoundSubs.push(subToDelete);
}
});
if (deletedSubs.length > 0) {
await saveData(subscriptions, nodes);
console.log('Subscriptions deleted. Remaining subscriptions:', subscriptions);
const message = deletedSubs.length === deleteList.length
? '订阅删除成功'
: `成功删除 ${deletedSubs.length} 个订阅,${notFoundSubs.length} 个订阅不存在`;
res.status(200).json({ message });
} else {
res.status(404).json({ error: '未找到要删除的订阅' });
}
} catch (error) {
console.error('Error deleting subscription:', error);
res.status(500).json({ error: 'Failed to delete subscription' });
}
});
// 删除节点路由
app.post('/admin/delete-node', async (req, res) => {
try {
const nodesToDelete = req.body.node?.trim();
console.log('Attempting to delete node(s):', nodesToDelete);
if (!nodesToDelete) {
return res.status(400).json({ error: 'Node is required' });
}
// 分割多行输入并清理每个节点字符串
const deleteList = nodesToDelete.split('\n')
.map(node => cleanNodeString(node))
.filter(node => node); // 过滤空行
// 获取当前节点列表并清理
let nodesList = nodes.split('\n')
.map(node => cleanNodeString(node))
.filter(node => node);
// 记录删除结果
const deletedNodes = [];
const notFoundNodes = [];
// 处理每个要删除的节点
deleteList.forEach(nodeToDelete => {
const index = nodesList.findIndex(node => {
// 使用清理后的字符串进行比较
return cleanNodeString(node) === cleanNodeString(nodeToDelete);
});
if (index !== -1) {
deletedNodes.push(nodeToDelete);
nodesList.splice(index, 1);
} else {
notFoundNodes.push(nodeToDelete);
}
});
if (deletedNodes.length > 0) {
// 更新节点列表
nodes = nodesList.join('\n');
await saveData(subscriptions, nodes);
console.log('Nodes deleted. Remaining nodes:', nodes);
const message = deletedNodes.length === deleteList.length
? '节点删除成功'
: `成功删除 ${deletedNodes.length} 个节点,${notFoundNodes.length} 个节点不存在`;
res.status(200).json({ message });
} else {
res.status(404).json({ error: '未找到要删除的节点' });
}
} catch (error) {
console.error('Error deleting node:', error);
res.status(500).json({ error: 'Failed to delete node' });
}
});
// API路由 - 添加订阅(无需验证)
app.post('/api/add-subscriptions', async (req, res) => {
try {
const newSubscriptions = req.body.subscription;
console.log('API - Attempting to add subscription(s):', newSubscriptions);
if (!newSubscriptions) {
return res.status(400).json({ error: 'Subscription URL is required' });
}
if (!Array.isArray(subscriptions)) {
subscriptions = [];
}
// 处理输入数据
const processedSubs = Array.isArray(newSubscriptions)
? newSubscriptions.map(sub => sub.trim()).filter(sub => sub)
: [newSubscriptions.trim()].filter(sub => sub);
// 检查每个订阅是否已存在
const addedSubs = [];
const existingSubs = [];
for (const sub of processedSubs) {
if (subscriptions.some(existingSub => existingSub.trim() === sub)) {
existingSubs.push(sub);
} else {
addedSubs.push(sub);
subscriptions.push(sub);
}
}
if (addedSubs.length > 0) {
await saveData(subscriptions, nodes);
res.status(200).json({
success: true,
added: addedSubs,
existing: existingSubs
});
} else {
res.status(400).json({
success: false,
error: 'All subscriptions already exist'
});
}
} catch (error) {
console.error('API Error adding subscription:', error);
res.status(500).json({ error: 'Failed to add subscription' });
}
});
// API路由 - 添加节点(无需验证)
app.post('/api/add-nodes', async (req, res) => {
try {
const newNodes = req.body.nodes;
if (!newNodes) {
return res.status(400).json({ error: 'Nodes are required' });
}
let nodesList = typeof nodes === 'string'
? nodes.split('\n').map(n => n.trim()).filter(n => n)
: [];
const processedNodes = Array.isArray(newNodes)
? newNodes
: newNodes.split('\n');
const nodesToAdd = processedNodes
.map(n => n.trim())
.filter(n => n)
.map(n => tryDecodeBase64(n));
const addedNodes = [];
const existingNodes = [];
for (const node of nodesToAdd) {
if (nodesList.some(existingNode => existingNode === node)) {
existingNodes.push(node);
} else {
addedNodes.push(node);
nodesList.push(node);
}
}
if (addedNodes.length > 0) {
nodes = nodesList.join('\n');
await saveData(subscriptions, nodes);
res.status(200).json({
success: true,
added: addedNodes,
existing: existingNodes
});
} else {
res.status(400).json({
success: false,
error: 'All nodes already exist'
});
}
} catch (error) {
console.error('API Error adding nodes:', error);
res.status(500).json({ error: 'Failed to add nodes' });
}
});
// API路由 - 删除订阅(无需验证)
app.delete('/api/delete-subscriptions', async (req, res) => {
try {
const subsToDelete = req.body.subscription;
if (!subsToDelete) {
return res.status(400).json({ error: 'Subscription URL is required' });
}
if (!Array.isArray(subscriptions)) {
subscriptions = [];
return res.status(404).json({ error: 'No subscriptions found' });
}
const deleteList = Array.isArray(subsToDelete)
? subsToDelete
: subsToDelete.split('\n');
const processedSubs = deleteList
.map(sub => cleanNodeString(sub))
.filter(sub => sub);
const deletedSubs = [];
const notFoundSubs = [];
processedSubs.forEach(subToDelete => {
const index = subscriptions.findIndex(sub =>
cleanNodeString(sub) === subToDelete
);
if (index !== -1) {
deletedSubs.push(subToDelete);
subscriptions.splice(index, 1);
} else {
notFoundSubs.push(subToDelete);
}
});
if (deletedSubs.length > 0) {
await saveData(subscriptions, nodes);
res.status(200).json({
success: true,
deleted: deletedSubs,
notFound: notFoundSubs
});
} else {
res.status(404).json({
success: false,
error: 'No subscriptions found to delete'
});
}
} catch (error) {
console.error('API Error deleting subscription:', error);
res.status(500).json({ error: 'Failed to delete subscription' });
}
});
// API路由 - 删除节点(无需验证)
app.delete('/api/delete-nodes', async (req, res) => {
try {
const nodesToDelete = req.body.nodes;
if (!nodesToDelete) {
return res.status(400).json({ error: 'Nodes are required' });
}
const deleteList = Array.isArray(nodesToDelete)
? nodesToDelete
: nodesToDelete.split('\n');
const processedNodes = deleteList
.map(node => cleanNodeString(node))
.filter(node => node);
let nodesList = nodes.split('\n')
.map(node => cleanNodeString(node))
.filter(node => node);
const deletedNodes = [];
const notFoundNodes = [];
processedNodes.forEach(nodeToDelete => {
const index = nodesList.findIndex(node =>
cleanNodeString(node) === cleanNodeString(nodeToDelete)
);
if (index !== -1) {
deletedNodes.push(nodeToDelete);
nodesList.splice(index, 1);
} else {
notFoundNodes.push(nodeToDelete);
}
});
if (deletedNodes.length > 0) {
nodes = nodesList.join('\n');
await saveData(subscriptions, nodes);
res.status(200).json({
success: true,
deleted: deletedNodes,
notFound: notFoundNodes
});
} else {
res.status(404).json({
success: false,
error: 'No nodes found to delete'
});
}
} catch (error) {
console.error('API Error deleting nodes:', error);
res.status(500).json({ error: 'Failed to delete nodes' });
}
});
// 获取数据
app.get('/admin/data', async (req, res) => {
try {
const nodesList = typeof nodes === 'string'
? nodes.split('\n').map(n => n.trim()).filter(n => n)
: [];
const response = {
subscriptions: Array.isArray(subscriptions) ? subscriptions : [],
nodes: nodesList
};
console.log('Sending data to client:', response);
res.status(200).json(response);
} catch (error) {
console.error('Error fetching data:', error);
res.status(500).json({ error: 'Failed to fetch data' });
}
});
// 保存数据
async function saveData(subs, nds) {
try {
const data = {
subscriptions: Array.isArray(subs) ? subs : [],
nodes: typeof nds === 'string' ? nds : ''
};
await fs.writeFile(DATA_FILE, JSON.stringify(data, null, 2));
console.log('Data saved successfully:', data);
subscriptions = data.subscriptions;
nodes = data.nodes;
} catch (error) {
console.error('Error saving data:', error);
throw error;
}
}
// 订阅路由
app.get(`/${SUB_TOKEN}`, async (req, res) => {
try {
const queryCFIP = req.query.CFIP;
const queryCFPORT = req.query.CFPORT;
// 从文件重新读取最新数据
await loadData();
const mergedSubscription = await generateMergedSubscription(queryCFIP, queryCFPORT);
const base64Content = Buffer.from(mergedSubscription).toString('base64');
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.send(`${base64Content}`);
} catch (error) {
console.error(`Error handling /${SUB_TOKEN} route: ${error}`);
res.status(500).send('Internal Server Error');
}
});
// 首页
app.get('/', function (req, res) {
res.send('Hello world!');
});
// 生成合并订阅
async function generateMergedSubscription(targetCFIP, targetCFPORT) {
try {
const promises = subscriptions.map(async (subscription) => {
try {
const subscriptionContent = await fetchSubscriptionContent(subscription);
if (subscriptionContent) {
const decodedContent = decodeBase64Content(subscriptionContent);
const updatedContent = replaceAddressAndPort(decodedContent, targetCFIP, targetCFPORT);
return updatedContent;
}
} catch (error) {
console.error(`Error fetching subscription content: ${error}`);
}
return null;
});
const mergedContentArray = await Promise.all(promises);
const mergedContent = mergedContentArray.filter(content => content !== null).join('\n');
const updatedNodes = replaceAddressAndPort(nodes, targetCFIP, targetCFPORT);
return `${mergedContent}\n${updatedNodes}`;
} catch (error) {
console.error(`Error generating merged subscription: ${error}`);
throw error;
}
}
function decodeBase64Content(base64Content) {
const decodedContent = Buffer.from(base64Content, 'base64').toString('utf-8');
return decodedContent;
}
async function fetchSubscriptionContent(subscription) {
try {
const response = await axios.get(subscription, { timeout: 10000 }); // 无效获取订阅10秒超时
return response.data;
} catch (error) {
console.error(`Error fetching subscription content: ${error}`);
return null;
}
}
function replaceAddressAndPort(content, targetCFIP, targetCFPORT) {
if (!targetCFIP || !targetCFPORT) {
return content;
}
return content.split('\n').map(line => {
line = line.trim();
if (!line) return line;
if (line.startsWith('vmess://')) {
try {
const base64Part = line.substring(8); // 去掉 'vmess://'
const decoded = Buffer.from(base64Part, 'base64').toString('utf-8');
const nodeObj = JSON.parse(decoded);
// 检查是否为 ws 协议且带 TLS
if ((nodeObj.net === 'ws' || nodeObj.net === 'xhttp') && nodeObj.tls === 'tls') {
// 只有当 host 不存在或与 address 不同时才替换
if (!nodeObj.host || nodeObj.host !== nodeObj.add) {
nodeObj.add = targetCFIP;
nodeObj.port = parseInt(targetCFPORT, 10);
}
return 'vmess://' + Buffer.from(JSON.stringify(nodeObj)).toString('base64');
}
} catch (error) {
console.error('Error processing VMess node:', error);
}
}
// 处理 VLESS 和 Trojan 节点
else if (line.startsWith('vless://') || line.startsWith('trojan://')) {
try {
// 检查是否包含 ws 和 tls
if ((line.includes('type=ws') || line.includes('type=xhttp')) && line.includes('security=tls')) {
const url = new URL(line);
const address = url.hostname;
const params = new URLSearchParams(url.search);
const host = params.get('host');
// 只有当 host 存在且与 address 不同时才替换(即不替换直连节点)
if (!host || host !== address) {
return line.replace(/@([\w.-]+):(\d+)/, (match, host) => {
return `@${targetCFIP}:${targetCFPORT}`;
});
}
}
} catch (error) {
console.error('Error processing VLESS/Trojan node:', error);
}
}
// 其他协议(如 tcp、hysteria、hysteria2、tuic snell等)返回原始行
return line;
}).join('\n');
}
// 先初始化数据再启动http服务
async function startServer() {
try {
// 初始化并加载凭证
await ensureDataDir();
await initializeCredentialsFile();
credentials = await loadCredentials();
console.log('Credentials initialized and loaded successfully');
await initializeDataFile();
// 启动服务器
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log(`Subscription route is /${SUB_TOKEN}`);
console.log(`Admin page is available at /`);
console.log(`Initial credentials: username=${credentials.username} password=${credentials.password}`);
});
} catch (error) {
console.error('Error starting server:', error);
process.exit(1);
}
}
startServer();