-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1370 lines (1273 loc) · 55.6 KB
/
index.js
File metadata and controls
1370 lines (1273 loc) · 55.6 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
require('dotenv').config();
const express = require('express');
const fs = require('fs');
const path = require('path');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const app = express();
const PORT = process.env.PORT || 3000;
const TOKEN = process.env.TOKEN;
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
const adminSesList = {};
app.use(cookieParser());
app.get(['/.env', '/config.json', '/history.json', '/settings.json'], (req, res) => {
res.status(403).send('扫你🐎呢');
});
const adminSes = new Set();
function createSession() {
const sid = crypto.randomBytes(16).toString('hex');
adminSes.add(sid);
return sid;
}
function getSession(req, res) {
let sid = req.cookies && req.cookies.captcha_sid;
if (!sid || !adminSesList[sid]) {
sid = crypto.randomBytes(12).toString('hex');
adminSesList[sid] = {};
res.cookie('captcha_sid', sid, { httpOnly: true });
}
return adminSesList[sid];
}
let configCache = null;
let cacheMtime = 0;
const configPath = path.join(__dirname, 'config.json');
function initConfig() {
return {
groups: [{ id: 'default', name: '默认分组' }],
variables: []
};
}
function loadConfig() {
try {
const stat = fs.statSync(configPath);
if (!configCache || stat.mtimeMs !== cacheMtime) {
const data = fs.readFileSync(configPath, 'utf-8');
configCache = JSON.parse(data);
// 兼容旧数据
if (!configCache.groups) {
configCache.groups = [{ id: 'default', name: '默认分组' }];
configCache.variables.forEach(v => v.groupId = 'default');
}
cacheMtime = stat.mtimeMs;
}
return configCache;
} catch (err) {
console.error('读取 config.json 失败:', err);
configCache = initConfig();
return configCache;
}
}
function saveConfig(config) {
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
configCache = config;
cacheMtime = fs.statSync(configPath).mtimeMs;
return true;
} catch (err) {
console.error('保存配置失败:', err);
return false;
}
}
// 读取config.json
function getSettings() { return loadConfig().variables; }
function log(level, message) {
const now = new Date();
const pad = n => n.toString().padStart(2, '0');
const timeStr = `${now.getFullYear()}/${pad(now.getMonth() + 1)}/${pad(now.getDate())}/${pad(now.getHours())}:${pad(now.getMinutes())}`;
console.log(`[${level}][${timeStr}] ${message}`);
}
function logInfo(message) {
log('INFO', message);
}
function logError(message) {
log('ERROR', message);
}
function ckToken(req, res, next) {
const token = req.query.token;
const settings = loadSystemSettings();
if (settings.tokens.some(t => t.token === token)) return next();
logError(`身份验证失败,IP: ${req.ip}`);
return res.status(401).json({ error: 'Invalid or missing token' });
}
function ckAuth(req, res, next) {
const sid = req.cookies && req.cookies.adminsid;
if (sid && adminSes.has(sid)) return next();
return res.redirect('/admin/login');
}
function apiResponse(success, data = null, message = '') {
return {
success,
data,
message,
timestamp: Date.now()
};
}
const historyPath = path.join(__dirname, 'history.json');
function loadHistory() {
try {
const data = fs.readFileSync(historyPath, 'utf-8');
return JSON.parse(data);
} catch (err) {
return [];
}
}
function saveHistory(history) {
try {
fs.writeFileSync(historyPath, JSON.stringify(history, null, 2), 'utf-8');
return true;
} catch (err) {
console.error('保存历史记录失败:', err);
return false;
}
}
function addHistory(name, oldValue, newValue, action, ip) {
const history = loadHistory();
history.unshift({
name,
oldValue,
newValue,
action,
ip,
timestamp: Date.now()
});
// 只保留最近1000条记录
if (history.length > 1000) history.length = 1000;
saveHistory(history);
}
// 删除旧的 /get 和 /set 路由,完全使用新的 RESTful API
app.get('/api/v1/variables/:name', ckToken, (req, res) => {
const name = req.params.name;
const variable = getSettings().find(v => v.name === name);
if (!variable) {
logError(`查询变量失败:${name} 不存在`);
return res.status(404).json(apiResponse(false, null, 'Variable not found'));
}
logInfo(`查询变量:${name},值:${variable.value},IP: ${req.ip}`);
res.json(apiResponse(true, { name: variable.name, value: variable.value }));
});
app.get('/api/v1/variables', ckToken, (req, res) => {
const variables = getSettings();
res.json(apiResponse(true, variables));
});
app.get('/api/v1/groups', ckToken, (req, res) => {
const config = loadConfig();
res.json(apiResponse(true, config.groups));
});
app.post('/api/v1/groups', ckToken, express.json(), (req, res) => {
const { name } = req.body;
if (!name) {
return res.status(400).json(apiResponse(false, null, 'Missing group name'));
}
const config = loadConfig();
const groupId = crypto.randomBytes(4).toString('hex');
config.groups.push({ id: groupId, name });
if (!saveConfig(config)) {
return res.status(500).json(apiResponse(false, null, 'Save failed'));
}
logInfo(`新增分组:${name},IP: ${req.ip}`);
res.status(201).json(apiResponse(true, { id: groupId, name }));
});
app.post('/api/v1/variables', ckToken, express.json(), (req, res) => {
const { name, value, groupId = 'default' } = req.body;
if (!name || typeof value === 'undefined') {
logError('新增变量失败:缺少 name 或 value');
return res.status(400).json(apiResponse(false, null, 'Missing name or value'));
}
const config = loadConfig();
if (config.variables.find(v => v.name === name)) {
logError(`新增变量失败:${name} 已存在`);
return res.status(409).json(apiResponse(false, null, 'Variable already exists'));
}
if (!config.groups.find(g => g.id === groupId)) {
return res.status(400).json(apiResponse(false, null, 'Invalid group'));
}
config.variables.push({ name, value: String(value), groupId });
if (!saveConfig(config)) {
return res.status(500).json(apiResponse(false, null, 'Save failed'));
}
// 添加历史记录
addHistory(name, null, value, 'create', req.ip);
logInfo(`新增变量:${name},值:${value},IP: ${req.ip}`);
res.status(201).json(apiResponse(true, { name, value }));
});
app.get('/api/v1/variables/:name/history', ckToken, (req, res) => {
const name = req.params.name;
const history = loadHistory().filter(h => h.name === name);
res.json(apiResponse(true, history));
});
app.put('/api/v1/variables/:name', ckToken, express.json(), (req, res) => {
const name = req.params.name;
const { value } = req.body;
if (typeof value === 'undefined') {
return res.status(400).json(apiResponse(false, null, 'Missing value'));
}
const config = loadConfig();
const variable = config.variables.find(v => v.name === name);
if (!variable) {
return res.status(404).json(apiResponse(false, null, 'Variable not found'));
}
const oldValue = variable.value;
variable.value = String(value);
if (!saveConfig(config)) {
return res.status(500).json(apiResponse(false, null, 'Save failed'));
}
// 添加历史记录
addHistory(name, oldValue, value, 'update', req.ip);
logInfo(`修改变量:${name},原值:${oldValue},新值:${value},IP: ${req.ip}`);
res.json(apiResponse(true, variable));
});
app.delete('/api/v1/variables/:name', ckToken, (req, res) => {
const name = req.params.name;
const config = loadConfig();
const variable = config.variables.find(v => v.name === name);
if (!variable) {
return res.status(404).json(apiResponse(false, null, 'Variable not found'));
}
const idx = config.variables.findIndex(v => v.name === name);
config.variables.splice(idx, 1);
if (!saveConfig(config)) {
return res.status(500).json(apiResponse(false, null, 'Save failed'));
}
// 添加历史记录
addHistory(name, variable.value, null, 'delete', req.ip);
logInfo(`删除变量:${name},IP: ${req.ip}`);
res.json(apiResponse(true));
});
app.get('/admin/login', (req, res) => {
res.send(`
<html><head><title>ValueAPI - 管理面板登录</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>body{background:#f7f7f7;} .login-panel{max-width:340px;margin:80px auto;padding:32px 24px;background:#fff;border-radius:8px;box-shadow:0 2px 8px #0001;}</style>
</head><body>
<div class="login-panel">
<h4 class="mb-4">管理面板登录</h4>
<form method="POST" action="/admin/login">
<div class="mb-3"><input type="password" class="form-control" name="password" placeholder="密码" required /></div>
<button type="submit" class="btn btn-primary w-100">登录</button>
</form>
</div>
</body></html>
`);
});
app.post('/admin/login', express.urlencoded({ extended: false }), (req, res) => {
const { password } = req.body;
if (password === ADMIN_PASSWORD) {
const sid = createSession();
res.cookie('adminsid', sid, { httpOnly: true });
logInfo(`管理登录成功,IP: ${req.ip}`);
return res.redirect('/admin');
}
logError(`管理登录失败,IP: ${req.ip}`);
return res.send('<script>alert("密码错误");location.href="/admin/login"</script>');
});
app.post('/admin/group/delete', ckAuth, express.urlencoded({ extended: false }), (req, res) => {
const { id } = req.body;
if (id === 'default') {
return res.send('默认分组不能删除');
}
const config = loadConfig();
const groupIdx = config.groups.findIndex(g => g.id === id);
if (groupIdx === -1) return res.send('分组不存在');
// 将该分组下的变量转移到默认分组
config.variables.forEach(v => {
if (v.groupId === id) v.groupId = 'default';
});
config.groups.splice(groupIdx, 1);
if (!saveConfig(config)) return res.send('保存失败');
res.redirect('/admin');
});
app.post('/admin/group/edit', ckAuth, express.urlencoded({ extended: false }), (req, res) => {
const { id, name } = req.body;
if (id === 'default' && name !== '默认分组') {
return res.send('默认分组名称不能修改');
}
const config = loadConfig();
const group = config.groups.find(g => g.id === id);
if (!group) return res.send('分组不存在');
group.name = name;
if (!saveConfig(config)) return res.send('保存失败');
res.redirect('/admin');
});
app.get('/admin', ckAuth, (req, res) => {
logInfo(`访问管理面板,IP: ${req.ip}`);
const config = loadConfig();
const groups = config.groups;
const variables = config.variables;
const search = req.query.search || '';
const groupId = req.query.group || '';
// 生成分组选项
const groupOptions = groups.map(g =>
`<option value="${g.id}" ${groupId === g.id ? 'selected' : ''}>${g.name}</option>`
).join('');
// 过滤变量
const filteredVars = variables.filter(v =>
(!search || v.name.includes(search)) &&
(!groupId || v.groupId === groupId)
);
// 按分组组织变量
const groupedRows = groups.map(group => {
const groupVars = filteredVars.filter(v => v.groupId === group.id);
if (groupVars.length === 0 && groupId && groupId !== group.id) return '';
return `
<tr class="group-header">
<td colspan="3" class="table-light">
<div class="d-flex justify-content-between align-items-center">
<div>
<strong>${group.name}</strong>
<span class="badge bg-secondary ms-2">${groupVars.length}</span>
</div>
${group.id !== 'default' ? `
<div class="btn-group btn-group-sm">
<button type="button" class="btn btn-outline-primary"
onclick="editGroup('${group.id}', '${group.name}')">编辑</button>
<button type="button" class="btn btn-outline-danger"
onclick="deleteGroup('${group.id}', '${group.name}')">删除</button>
</div>
` : ''}
</div>
</td>
</tr>
${groupVars.map(v => `
<tr>
<td>${v.name}</td>
<td>
<form method="POST" action="/admin/edit" class="d-inline-flex align-items-center">
<input type="hidden" name="name" value="${v.name}" />
<input name="value" value="${v.value}" class="form-control form-control-sm me-2" style="width:120px;" />
<button type="submit" class="btn btn-sm btn-outline-primary">修改</button>
</form>
</td>
<td>
<div class="btn-group btn-group-sm">
<a href="/admin/history/${v.name}" class="btn btn-outline-secondary">历史</a>
<button type="button" class="btn btn-outline-danger"
onclick="deleteVar('${v.name}')">删除</button>
</div>
</td>
</tr>
`).join('')}
`;
}).join('');
res.send(`
<html><head><title>ValueAPI - 管理面板</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<style>
body { background: #f7f7f7; }
.sidebar {
width: 240px;
position: fixed;
left: 0;
top: 0;
bottom: 0;
background: #fff;
border-right: 1px solid #eee;
padding: 20px 0;
}
.main-content {
margin-left: 240px;
padding: 20px 30px;
}
.sidebar-brand {
padding: 0 20px 20px;
border-bottom: 1px solid #eee;
margin-bottom: 20px;
}
.sidebar-nav .nav-link {
padding: 8px 20px;
color: #666;
font-weight: 500;
}
.sidebar-nav .nav-link:hover {
background: #f8f9fa;
color: #333;
}
.sidebar-nav .nav-link.active {
background: #f0f7ff;
color: #0d6efd;
}
.sidebar-nav .nav-link i {
margin-right: 8px;
}
.top-bar {
background: #fff;
border-bottom: 1px solid #eee;
padding: 15px 0;
margin: -20px -30px 20px;
}
.panel {
background: #fff;
border-radius: 8px;
box-shadow: 0 1px 3px #0001;
}
.table > :not(caption) > * > * {
padding: 1rem;
}
.group-header {
background: #f8f9fa;
}
.group-header td {
padding: 12px 1rem !important;
}
.btn-icon {
padding: 0.375rem;
line-height: 1;
}
.btn-icon i {
font-size: 1.1rem;
}
</style>
</head><body>
<div class="sidebar">
<div class="sidebar-brand">
<h5 class="mb-0">ValueAPI</h5>
<small class="text-muted">变量管理系统</small>
</div>
<div class="sidebar-nav">
<a href="/admin" class="nav-link active">
<i class="bi bi-gear"></i> 变量管理
</a>
<a href="/admin/settings" class="nav-link">
<i class="bi bi-sliders"></i> 系统设置
</a>
</div>
</div>
<div class="main-content">
<div class="top-bar">
<div class="container-fluid">
<div class="row g-3 align-items-center">
<div class="col-auto">
<div class="input-group">
<span class="input-group-text bg-white">
<i class="bi bi-search text-muted"></i>
</span>
<input type="text" class="form-control border-start-0" id="searchInput"
placeholder="搜索变量" value="${search}">
</div>
</div>
<div class="col-auto">
<select class="form-select" id="groupFilter">
<option value="">所有分组</option>
${groupOptions}
</select>
</div>
<div class="col-auto ms-auto">
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addGroupModal">
<i class="bi bi-plus-lg me-1"></i>新增分组
</button>
</div>
</div>
</div>
</div>
<div class="panel">
<table class="table table-bordered align-middle mb-0">
<thead class="bg-light">
<tr>
<th style="width:30%">变量名</th>
<th>值</th>
<th style="width:180px" class="text-end">操作</th>
</tr>
</thead>
<tbody>
${groups.map(group => {
const groupVars = filteredVars.filter(v => v.groupId === group.id);
if (groupVars.length === 0 && groupId && groupId !== group.id) return '';
return `
<tr class="group-header">
<td colspan="3">
<div class="d-flex justify-content-between align-items-center">
<div>
<strong>${group.name}</strong>
<span class="badge bg-secondary bg-opacity-75 ms-2">${groupVars.length}</span>
</div>
${group.id !== 'default' ? `
<div class="btn-group btn-group-sm">
<button type="button" class="btn btn-icon btn-outline-secondary"
onclick="editGroup('${group.id}', '${group.name}')" title="编辑分组">
<i class="bi bi-pencil"></i>
</button>
<button type="button" class="btn btn-icon btn-outline-danger"
onclick="deleteGroup('${group.id}', '${group.name}')" title="删除分组">
<i class="bi bi-trash"></i>
</button>
</div>
` : ''}
</div>
</td>
</tr>
${groupVars.map(v => `
<tr>
<td class="text-break">${v.name}</td>
<td>
<form method="POST" action="/admin/edit" class="d-flex align-items-center">
<input type="hidden" name="name" value="${v.name}">
<input name="value" value="${v.value}" class="form-control form-control-sm me-2">
<button type="submit" class="btn btn-sm btn-primary px-3">保存</button>
</form>
</td>
<td class="text-end">
<div class="btn-group btn-group-sm">
<a href="/admin/history/${v.name}" class="btn btn-icon btn-outline-secondary" title="历史记录">
<i class="bi bi-clock-history"></i>
</a>
<button type="button" class="btn btn-icon btn-outline-danger"
onclick="deleteVar('${v.name}')" title="删除">
<i class="bi bi-trash"></i>
</button>
</div>
</td>
</tr>
`).join('')}
`;
}).join('')}
</tbody>
</table>
</div>
<div class="mt-4">
<div class="panel p-4">
<h5 class="mb-3">添加变量</h5>
<form method="POST" action="/admin/add" class="row g-3">
<div class="col-4">
<label class="form-label">变量名</label>
<input name="name" class="form-control" required>
</div>
<div class="col-4">
<label class="form-label">值</label>
<input name="value" class="form-control" required>
</div>
<div class="col-2">
<label class="form-label">分组</label>
<select name="groupId" class="form-select">
${groupOptions}
</select>
</div>
<div class="col-2">
<label class="form-label"> </label>
<button type="submit" class="btn btn-primary w-100">添加</button>
</div>
</form>
</div>
</div>
</div>
<!-- 新增分组模态框 -->
<div class="modal fade" id="addGroupModal">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" action="/admin/group/add">
<div class="modal-header">
<h5 class="modal-title">新增分组</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<input name="name" class="form-control" placeholder="分组名称" required />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
<button type="submit" class="btn btn-primary">确定</button>
</div>
</form>
</div>
</div>
</div>
<!-- 编辑分组模态框 -->
<div class="modal fade" id="editGroupModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" action="/admin/group/edit">
<input type="hidden" name="id" id="editGroupId">
<div class="modal-header">
<h5 class="modal-title">编辑分组</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<input name="name" id="editGroupName" class="form-control" placeholder="分组名称" required />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
<button type="submit" class="btn btn-primary">保存</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
let editModal;
window.onload = () => {
editModal = new bootstrap.Modal(document.getElementById('editGroupModal'));
};
function updateSearch() {
const search = document.getElementById('searchInput').value.trim();
const group = document.getElementById('groupFilter').value;
const params = new URLSearchParams(window.location.search);
if (search) params.set('search', search);
else params.delete('search');
if (group) params.set('group', group);
else params.delete('group');
window.location.search = params.toString();
}
// 添加搜索延迟
let searchTimeout;
document.getElementById('searchInput').addEventListener('input', () => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(updateSearch, 300);
});
document.getElementById('groupFilter').addEventListener('change', updateSearch);
function editGroup(id, name) {
document.getElementById('editGroupId').value = id;
document.getElementById('editGroupName').value = name;
editModal.show();
}
function deleteGroup(id, name) {
if (!confirm(\`确定要删除分组【\${name}】吗?该分组下的变量将被移动到默认分组。\`)) return;
const form = document.createElement('form');
form.method = 'POST';
form.action = '/admin/group/delete';
const input = document.createElement('input');
input.name = 'id';
input.value = id;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
function deleteVar(name) {
if (!confirm(\`确定要删除变量【\${name}】吗?\`)) return;
const form = document.createElement('form');
form.method = 'POST';
form.action = '/admin/delete';
const input = document.createElement('input');
input.name = 'name';
input.value = name;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
</script>
</body></html>
`);
});
app.get('/admin/history/:name', ckAuth, (req, res) => {
const name = req.params.name;
const history = loadHistory().filter(h => h.name === name);
const variable = getSettings().find(v => v.name === name);
if (!variable) return res.redirect('/admin');
const rows = history.map(h => {
const time = new Date(h.timestamp).toLocaleString();
const actionMap = { create: '创建', update: '修改', delete: '删除' };
const actionClass = {
create: 'bg-success',
update: 'bg-primary',
delete: 'bg-danger'
};
return `
<tr>
<td class="text-nowrap">${time}</td>
<td><span class="badge ${actionClass[h.action]} bg-opacity-75">${actionMap[h.action] || h.action}</span></td>
<td><code>${h.oldValue === null ? '-' : h.oldValue}</code></td>
<td><code>${h.newValue === null ? '-' : h.newValue}</code></td>
<td class="text-nowrap">${h.ip}</td>
<td class="text-end">
${h.action === 'update' ? `
<button type="button" class="btn btn-sm btn-outline-primary"
onclick="rollback('${name}', '${h.oldValue}')">恢复此版本</button>
` : ''}
</td>
</tr>
`;
}).join('');
res.send(`
<html><head><title>变量历史 - ValueAPI</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background: #f7f7f7; }
.panel { background: #fff; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px #0001; max-width: 1000px; margin: 40px auto; }
code { background: #f5f5f5; padding: 2px 6px; border-radius: 4px; }
</style>
</head><body>
<div class="panel">
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h4 class="m-0">变量历史记录</h4>
<div class="text-muted mt-1">
<strong>${name}</strong>
<span class="mx-2">•</span>
当前值:<code>${variable.value}</code>
</div>
</div>
<a href="/admin" class="btn btn-outline-secondary">返回</a>
</div>
<table class="table table-bordered align-middle">
<thead class="table-light">
<tr>
<th>时间</th>
<th>操作</th>
<th>原值</th>
<th>新值</th>
<th>IP</th>
<th></th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
${history.length === 0 ? '<div class="text-center text-muted py-4">暂无历史记录</div>' : ''}
</div>
<script>
function rollback(name, value) {
if (!confirm('确定要恢复到这个版本吗?')) return;
const form = document.createElement('form');
form.method = 'POST';
form.action = '/admin/edit';
const nameInput = document.createElement('input');
nameInput.name = 'name';
nameInput.value = name;
const valueInput = document.createElement('input');
valueInput.name = 'value';
valueInput.value = value;
form.appendChild(nameInput);
form.appendChild(valueInput);
document.body.appendChild(form);
form.submit();
}
</script>
</body></html>
`);
});
// 更新首页文档
app.get('/', (req, res) => {
res.send(`
<html>
<head>
<title>首页 - ValueAPI</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background: #f7f7f7; }
.main-panel { max-width: 700px; margin: 60px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px #0001; padding: 32px 28px; }
code { background: #f5f5f5; padding: 2px 6px; border-radius: 4px; }
</style>
</head>
<body>
<div class="main-panel">
<h2 class="mb-3">ValueAPI</h2>
<p class="text-muted">一个轻量级的变量存储与管理接口,支持通过API接口进行变量的查询和修改,并通过一个简单的后台进行可视化修改</p>
<hr>
<h5>REST API 接口说明</h5>
<p class="text-muted small">所有请求需要在URL参数中携带 token</p>
<ul>
<li><b>查询所有变量:</b> <code>GET /api/v1/variables</code></li>
<li><b>查询单个变量:</b> <code>GET /api/v1/variables/:name</code></li>
<li><b>新增变量:</b> <code>POST /api/v1/variables</code></li>
<li><b>修改变量:</b> <code>PUT /api/v1/variables/:name</code></li>
<li><b>删除变量:</b> <code>DELETE /api/v1/variables/:name</code></li>
</ul>
<h6 class="mt-4">请求示例</h6>
<div class="mb-2">
<p class="mb-1 small text-muted">查询变量</p>
<pre class="bg-light p-2 rounded"><code>curl "http://localhost:${PORT}/api/v1/variables/foo?token=你的Token"</code></pre>
</div>
<div class="mb-2">
<p class="mb-1 small text-muted">添加变量</p>
<pre class="bg-light p-2 rounded"><code>curl -X POST "http://localhost:${PORT}/api/v1/variables?token=你的Token" \\
-H "Content-Type: application/json" \\
-d '{"name":"foo","value":"bar"}'</code></pre>
</div>
<div class="mb-2">
<p class="mb-1 small text-muted">修改变量</p>
<pre class="bg-light p-2 rounded"><code>curl -X PUT "http://localhost:${PORT}/api/v1/variables/foo?token=你的Token" \\
-H "Content-Type: application/json" \\
-d '{"value":"newbar"}'</code></pre>
</div>
<div class="mb-2">
<p class="mb-1 small text-muted">删除变量</p>
<pre class="bg-light p-2 rounded"><code>curl -X DELETE "http://localhost:${PORT}/api/v1/variables/foo?token=你的Token"</code></pre>
</div>
<hr>
<div class="text-muted small">Powered by ValueAPI & Made By Zatursure</div>
<div class="text-muted small">Star this Project on Github (zatursure/ValueAPI)</div>
</div>
</body>
</html>
`);
});
// ValueAPI, 启动!
app.listen(PORT, () => {
let version = '';
try {
const pkg = require('./package.json');
version = pkg.version ? ` v${pkg.version}` : '';
} catch (e) {
version = '';
}
console.log(`|----------------------------------------------------------|`);
console.log(`|---------------ValueAPI - Made By Zatursure---------------|`);
console.log(`|-----Star this project on Github (zatursure/ValueAPI)-----|`);
console.log(`|------------------Version: ${version}------------------------|`);
console.log(`|----------------------------------------------------------|`);
logInfo(`ValueAPI运行在 http://localhost:${PORT}${version}`);
});
// 在 const TOKEN = process.env.TOKEN; 后添加系统设置相关代码
const systemSettingsPath = path.join(__dirname, 'settings.json');
function loadSystemSettings() {
try {
const data = fs.readFileSync(systemSettingsPath, 'utf-8');
const settings = JSON.parse(data);
// 确保默认令牌存在
const defaultToken = settings.tokens.find(t => t.name === 'Default');
if (!defaultToken) {
settings.tokens.unshift({
name: 'Default',
token: TOKEN,
remark: '默认令牌',
createdAt: Date.now(),
isDefault: true
});
} else {
// 不更新默认令牌的值,保持用户设置的值
defaultToken.isDefault = true;
}
return settings;
} catch (err) {
const defaultSettings = {
tokens: [{
name: 'Default',
token: TOKEN,
remark: '默认令牌',
createdAt: Date.now(),
isDefault: true
}],
settings: {
historyLimit: 1000,
pageSize: 50,
allowNewToken: true
}
};
fs.writeFileSync(systemSettingsPath, JSON.stringify(defaultSettings, null, 2));
return defaultSettings;
}
}
function saveSystemSettings(settings) {
try {
fs.writeFileSync(systemSettingsPath, JSON.stringify(settings, null, 2), 'utf-8');
return true;
} catch (err) {
console.error('保存系统设置失败:', err);
return false;
}
}
// 修改 ckToken 中间件支持多令牌验证
function ckToken(req, res, next) {
const token = req.query.token;
const settings = loadSystemSettings();
if (settings.tokens.some(t => t.token === token)) return next();
logError(`身份验证失败,IP: ${req.ip}`);
return res.status(401).json({ error: 'Invalid or missing token' });
}
// 修改令牌管理API路由
app.post('/admin/settings/token/add', ckAuth, express.json(), (req, res) => {
const { name, remark } = req.body;
if (!name) return res.json({ error: '请输入令牌名称' });
const settings = loadSystemSettings();
if (settings.tokens.find(t => t.name === name)) {
return res.json({ error: '令牌名称已存在' });
}
const token = crypto.randomBytes(16).toString('hex');
settings.tokens.push({
name,
token,
remark: remark || '',
createdAt: Date.now()
});
if (!saveSystemSettings(settings)) {
return res.json({ error: '保存失败' });
}
res.json({
success: true,
token,
message: '创建成功!新令牌:' + token
});
});
app.post('/admin/settings/token/delete', ckAuth, express.json(), (req, res) => {
const { name } = req.body;
if (name === 'Default') {
return res.json({ error: '默认令牌不能删除' });
}
const settings = loadSystemSettings();
const idx = settings.tokens.findIndex(t => t.name === name);
if (idx === -1) {
return res.json({ error: '令牌不存在' });
}
settings.tokens.splice(idx, 1);
if (!saveSystemSettings(settings)) {
return res.json({ error: '保存失败' });
}
res.json({ success: true, message: '删除成功' });
});
// 修改系统设置页面中的令牌管理部分
app.get('/admin/settings', ckAuth, (req, res) => {
const settings = loadSystemSettings();
res.send(`
<html><head><title>系统设置 - ValueAPI</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<style>
body { background: #f7f7f7; }
.sidebar {
width: 240px;
position: fixed;
left: 0;
top: 0;
bottom: 0;
background: #fff;
border-right: 1px solid #eee;
padding: 20px 0;
}
.main-content {
margin-left: 240px;
padding: 20px 30px;
}
.sidebar-brand {
padding: 0 20px 20px;
border-bottom: 1px solid #eee;
margin-bottom: 20px;
}
.sidebar-nav .nav-link {