-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2655 lines (2344 loc) · 104 KB
/
app.js
File metadata and controls
2655 lines (2344 loc) · 104 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
// API Base URL - Auto-detect from current location (works with 0.0.0.0)
const API_BASE = window.location.origin + '/api';
// Configure fetch to include credentials for OIDC
const fetchOptions = {
credentials: 'include'
};
// Authentication state
let isAuthenticated = false;
let currentUser = null;
// Show/hide AbuseIPDB categories when checkbox is toggled
document.addEventListener('DOMContentLoaded', function() {
const reportCheckbox = document.getElementById('report-to-abuseipdb');
const categoriesDiv = document.getElementById('abuseipdb-categories');
if (reportCheckbox && categoriesDiv) {
reportCheckbox.addEventListener('change', function() {
categoriesDiv.style.display = this.checked ? 'block' : 'none';
});
}
});
// AbuseIPDB Queue Functions
async function loadAbuseIPDBStatus() {
try {
const response = await fetch(`${API_BASE}/abuseipdb/status`, fetchOptions);
if (response.ok) {
const status = await response.json();
const queueCard = document.getElementById('abuseipdb-queue-card');
// Show queue card only if mode is log_and_hold
if (queueCard && status.mode === 'log_and_hold' && status.enabled) {
queueCard.style.display = 'block';
document.getElementById('queue-count').textContent = `${status.queue_count || 0} pending`;
if (status.queue_count > 0) {
loadAbuseIPDBQueue();
}
} else if (queueCard) {
queueCard.style.display = 'none';
}
}
} catch (error) {
console.error('Error loading AbuseIPDB status:', error);
}
}
async function loadAbuseIPDBQueue() {
try {
const response = await fetch(`${API_BASE}/abuseipdb/queue?status=pending`, fetchOptions);
if (response.ok) {
const reports = await response.json();
const tbody = document.getElementById('abuseipdb-queue-table');
if (reports.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No pending reports</td></tr>';
return;
}
tbody.innerHTML = reports.map(report => {
let categories = 'N/A';
if (Array.isArray(report.categories)) {
categories = report.categories.join(', ');
} else if (typeof report.categories === 'string') {
try {
const parsed = JSON.parse(report.categories);
categories = Array.isArray(parsed) ? parsed.join(', ') : parsed;
} catch {
categories = report.categories;
}
}
return `
<tr>
<td><input type="checkbox" class="queue-checkbox" value="${report.id}"></td>
<td><code>${report.ip_address}</code></td>
<td><small>${categories}</small></td>
<td><small>${report.comment || '-'}</small></td>
<td><span class="badge bg-${report.source === 'auto' ? 'primary' : 'secondary'}">${report.source || 'manual'}</span></td>
<td><small>${new Date(report.created_at).toLocaleString()}</small></td>
</tr>
`;
}).join('');
}
} catch (error) {
console.error('Error loading AbuseIPDB queue:', error);
}
}
function toggleSelectAllQueue() {
const selectAll = document.getElementById('select-all-checkbox') || document.getElementById('select-all-queue');
const checkboxes = document.querySelectorAll('.queue-checkbox');
checkboxes.forEach(cb => cb.checked = selectAll.checked);
}
async function submitSelectedReports() {
const selected = Array.from(document.querySelectorAll('.queue-checkbox:checked')).map(cb => parseInt(cb.value));
if (selected.length === 0) {
showAlert('Please select at least one report to submit', 'warning');
return;
}
if (!confirm(`Submit ${selected.length} report(s) to AbuseIPDB?`)) {
return;
}
try {
const response = await fetch(`${API_BASE}/abuseipdb/queue/submit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: selected }),
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert(result.message, 'success');
loadAbuseIPDBQueue();
loadAbuseIPDBStatus();
} else {
showAlert(result.error || 'Error submitting reports', 'danger');
}
} catch (error) {
console.error('Error submitting reports:', error);
showAlert('Error submitting reports', 'danger');
}
}
async function deleteSelectedReports() {
const selected = Array.from(document.querySelectorAll('.queue-checkbox:checked')).map(cb => parseInt(cb.value));
if (selected.length === 0) {
showAlert('Please select at least one report to delete', 'warning');
return;
}
if (!confirm(`Delete ${selected.length} report(s)?`)) {
return;
}
try {
const response = await fetch(`${API_BASE}/abuseipdb/queue/delete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: selected }),
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert(result.message, 'success');
loadAbuseIPDBQueue();
loadAbuseIPDBStatus();
} else {
showAlert(result.error || 'Error deleting reports', 'danger');
}
} catch (error) {
console.error('Error deleting reports:', error);
showAlert('Error deleting reports', 'danger');
}
}
// Reports Functions
function showReport(reportType) {
// Hide all report sections
document.querySelectorAll('.report-section').forEach(section => {
section.style.display = 'none';
});
// Remove active class from all buttons
document.querySelectorAll('.btn-group .btn').forEach(btn => {
btn.classList.remove('active');
});
// Show selected report
const reportSection = document.getElementById(`report-${reportType}`);
if (reportSection) {
reportSection.style.display = 'block';
}
// Add active class to clicked button (if event exists)
if (event && event.target) {
event.target.classList.add('active');
} else {
// Find button by onclick attribute
const buttons = document.querySelectorAll('.btn-group .btn');
buttons.forEach(btn => {
if (btn.getAttribute('onclick') && btn.getAttribute('onclick').includes(reportType)) {
btn.classList.add('active');
}
});
}
// Load report data
switch(reportType) {
case 'top-offenders':
loadTopOffenders();
break;
case 'packet-stats':
loadPacketStats();
break;
case 'chain-stats':
loadChainStats();
break;
case 'activity-timeline':
loadActivityTimeline();
break;
case 'block-summary':
loadBlockSummary();
break;
}
}
async function loadReports() {
// Load default report (top offenders)
showReport('top-offenders');
loadTopOffenders();
}
async function refreshReports() {
const activeReport = document.querySelector('.report-section[style*="block"]') || document.getElementById('report-top-offenders');
if (activeReport) {
const reportId = activeReport.id.replace('report-', '');
showReport(reportId);
}
}
async function loadTopOffenders() {
const period = document.getElementById('top-offenders-period')?.value || 168;
try {
const response = await fetch(`${API_BASE}/reports/top-offenders?period=${period}`, fetchOptions);
if (response.ok) {
const data = await response.json();
const tbody = document.getElementById('top-offenders-table');
if (data.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No data available</td></tr>';
return;
}
tbody.innerHTML = data.map((item, index) => `
<tr>
<td><span class="badge bg-${index < 3 ? 'danger' : 'secondary'}">#${index + 1}</span></td>
<td><code>${item.ip_address}</code></td>
<td><strong>${item.block_count || 0}</strong></td>
<td>${item.first_blocked ? new Date(item.first_blocked).toLocaleString() : 'N/A'}</td>
<td>${item.last_blocked ? new Date(item.last_blocked).toLocaleString() : 'N/A'}</td>
<td>${item.description || '-'}</td>
</tr>
`).join('');
}
} catch (error) {
console.error('Error loading top offenders:', error);
document.getElementById('top-offenders-table').innerHTML =
'<tr><td colspan="6" class="text-center text-danger">Error loading data</td></tr>';
}
}
async function loadPacketStats() {
try {
const response = await fetch(`${API_BASE}/reports/packet-stats`, fetchOptions);
if (response.ok) {
const data = await response.json();
// Chain packet stats
const chainTbody = document.getElementById('chain-packet-stats-table');
if (data.chains && data.chains.length > 0) {
chainTbody.innerHTML = data.chains.map(chain => `
<tr>
<td><code>${chain.name}</code></td>
<td>${chain.packets.toLocaleString()}</td>
<td>${formatBytes(chain.bytes)}</td>
</tr>
`).join('');
} else {
chainTbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted">No data available</td></tr>';
}
// IP packet stats
const ipTbody = document.getElementById('ip-packet-stats-table');
if (data.top_ips && data.top_ips.length > 0) {
ipTbody.innerHTML = data.top_ips.map(ip => `
<tr>
<td><code>${ip.ip_address}</code></td>
<td>${ip.packets.toLocaleString()}</td>
<td>${formatBytes(ip.bytes)}</td>
<td><span class="badge bg-info">${ip.chain}</span></td>
</tr>
`).join('');
} else {
ipTbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">No data available</td></tr>';
}
}
} catch (error) {
console.error('Error loading packet stats:', error);
}
}
async function loadChainStats() {
try {
const response = await fetch(`${API_BASE}/reports/chain-stats`, fetchOptions);
if (response.ok) {
const data = await response.json();
// Update summary cards
document.getElementById('whitelist-chain-rules').textContent = data.whitelist_rules || 0;
document.getElementById('blacklist-chain-rules').textContent = data.blacklist_rules || 0;
document.getElementById('rules-chain-rules').textContent = data.rules_count || 0;
// Chain details table
const tbody = document.getElementById('chain-stats-table');
if (data.chains && data.chains.length > 0) {
tbody.innerHTML = data.chains.map(chain => `
<tr>
<td><code>${chain.name}</code></td>
<td><span class="badge bg-${chain.policy === 'ACCEPT' ? 'success' : chain.policy === 'DROP' ? 'danger' : 'secondary'}">${chain.policy}</span></td>
<td>${chain.packets.toLocaleString()}</td>
<td>${formatBytes(chain.bytes)}</td>
<td>${chain.rule_count}</td>
</tr>
`).join('');
} else {
tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">No data available</td></tr>';
}
}
} catch (error) {
console.error('Error loading chain stats:', error);
}
}
async function loadActivityTimeline() {
const period = document.getElementById('activity-period')?.value || 168;
try {
const response = await fetch(`${API_BASE}/reports/activity-timeline?period=${period}`, fetchOptions);
if (response.ok) {
const data = await response.json();
const tbody = document.getElementById('activity-timeline-table');
if (data.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">No activity in selected period</td></tr>';
return;
}
tbody.innerHTML = data.map(activity => `
<tr>
<td>${new Date(activity.timestamp).toLocaleString()}</td>
<td><span class="badge bg-info">${activity.action}</span></td>
<td>${activity.type || '-'}</td>
<td><code>${activity.entry || '-'}</code></td>
<td><span class="badge bg-${activity.status === 'success' ? 'success' : activity.status === 'error' ? 'danger' : 'warning'}">${activity.status}</span></td>
</tr>
`).join('');
}
} catch (error) {
console.error('Error loading activity timeline:', error);
}
}
async function loadBlockSummary() {
try {
const response = await fetch(`${API_BASE}/reports/block-summary`, fetchOptions);
if (response.ok) {
const data = await response.json();
// Update summary stats
document.getElementById('total-blocks').textContent = data.total_blocks || 0;
document.getElementById('auto-blocks').textContent = data.auto_blocks || 0;
document.getElementById('manual-blocks').textContent = data.manual_blocks || 0;
document.getElementById('blocks-today').textContent = data.blocks_today || 0;
document.getElementById('blocks-week').textContent = data.blocks_week || 0;
// Block sources table
const tbody = document.getElementById('block-sources-table');
if (data.sources && data.sources.length > 0) {
const total = data.sources.reduce((sum, s) => sum + s.count, 0);
tbody.innerHTML = data.sources.map(source => {
const percentage = total > 0 ? ((source.count / total) * 100).toFixed(1) : 0;
return `
<tr>
<td>${source.source}</td>
<td>${source.count}</td>
<td>
<div class="progress" style="height: 20px;">
<div class="progress-bar" role="progressbar" style="width: ${percentage}%">${percentage}%</div>
</div>
</td>
</tr>
`;
}).join('');
} else {
tbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted">No data available</td></tr>';
}
}
} catch (error) {
console.error('Error loading block summary:', error);
}
}
function formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Crowdsource Lists Functions
document.addEventListener('DOMContentLoaded', function() {
const autoSyncCheckbox = document.getElementById('crowdsource-auto-sync');
const syncIntervalGroup = document.getElementById('crowdsource-sync-interval-group');
if (autoSyncCheckbox && syncIntervalGroup) {
autoSyncCheckbox.addEventListener('change', function() {
syncIntervalGroup.style.display = this.checked ? 'block' : 'none';
});
}
});
function load3FIFTYnetList() {
document.getElementById('crowdsource-name').value = '3FIFTYnet Abusive Subnets';
document.getElementById('crowdsource-url').value = 'https://raw.githubusercontent.com/3FIFTYnet/dbl/refs/heads/main/abusive_subnet_24_blacklist.txt';
document.getElementById('crowdsource-type').value = 'blacklist';
document.getElementById('crowdsource-desc').value = 'Community-maintained list of abusive /24 subnets from 3FIFTYnet. Based on known and verifiable abusive and excessive network traffic.';
document.getElementById('crowdsource-auto-sync').checked = true;
document.getElementById('crowdsource-sync-interval-group').style.display = 'block';
showAlert('3FIFTYnet list loaded. Review settings and click "Add List" to import.', 'info');
}
async function loadCrowdsourceLists() {
try {
const response = await fetch(`${API_BASE}/url-lists`, fetchOptions);
if (response.ok) {
const lists = await response.json();
const tbody = document.getElementById('crowdsource-table');
if (lists.length === 0) {
tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">No crowdsource lists configured. Click "Add Crowdsource List" to get started.</td></tr>';
return;
}
tbody.innerHTML = lists.map(list => {
const statusBadge = list.enabled
? '<span class="badge bg-success">Enabled</span>'
: '<span class="badge bg-secondary">Disabled</span>';
const autoSyncBadge = list.auto_sync
? `<span class="badge bg-info">Every ${formatInterval(list.sync_interval)}</span>`
: '<span class="badge bg-secondary">Manual</span>';
const lastSync = list.last_sync
? new Date(list.last_sync).toLocaleString()
: 'Never';
const urlDisplay = list.url.length > 50
? list.url.substring(0, 50) + '...'
: list.url;
return `
<tr>
<td><strong>${list.name}</strong></td>
<td><a href="${list.url}" target="_blank" title="${list.url}">${urlDisplay}</a></td>
<td><span class="badge bg-${list.list_type === 'whitelist' ? 'success' : 'danger'}">${list.list_type}</span></td>
<td>${statusBadge}</td>
<td><strong>${list.entry_count || 0}</strong></td>
<td><small>${lastSync}</small></td>
<td>${autoSyncBadge}</td>
<td>
<button class="btn btn-sm btn-primary" onclick="syncCrowdsourceList(${list.id})" title="Sync Now">
<i class="bi bi-arrow-clockwise"></i>
</button>
<button class="btn btn-sm btn-warning" onclick="toggleCrowdsourceList(${list.id}, ${!list.enabled})" title="${list.enabled ? 'Disable' : 'Enable'}">
<i class="bi bi-${list.enabled ? 'pause' : 'play'}-fill"></i>
</button>
<button class="btn btn-sm btn-danger" onclick="deleteCrowdsourceList(${list.id})" title="Delete">
<i class="bi bi-trash"></i>
</button>
</td>
</tr>
`;
}).join('');
}
} catch (error) {
console.error('Error loading crowdsource lists:', error);
document.getElementById('crowdsource-table').innerHTML =
'<tr><td colspan="8" class="text-center text-danger">Error loading crowdsource lists</td></tr>';
}
}
async function addCrowdsourceList() {
const name = document.getElementById('crowdsource-name').value.trim();
const url = document.getElementById('crowdsource-url').value.trim();
const listType = document.getElementById('crowdsource-type').value;
const description = document.getElementById('crowdsource-desc').value.trim();
const enabled = document.getElementById('crowdsource-enabled').checked;
const autoSync = document.getElementById('crowdsource-auto-sync').checked;
const syncInterval = parseInt(document.getElementById('crowdsource-sync-interval').value) || 3600;
if (!name || !url) {
showAlert('Name and URL are required', 'warning');
return;
}
if (autoSync && syncInterval < 60) {
showAlert('Sync interval must be at least 60 seconds', 'warning');
return;
}
try {
const response = await fetch(`${API_BASE}/url-lists`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
url,
list_type: listType,
description,
enabled,
auto_sync: autoSync,
sync_interval: syncInterval
}),
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert('Crowdsource list added successfully. Syncing now...', 'success');
bootstrap.Modal.getInstance(document.getElementById('addCrowdsourceModal')).hide();
document.getElementById('crowdsource-form').reset();
document.getElementById('crowdsource-sync-interval-group').style.display = 'none';
// Auto-sync after adding
if (result.id) {
setTimeout(() => {
syncCrowdsourceList(result.id);
loadCrowdsourceLists();
}, 500);
}
} else {
showAlert(result.error || 'Error adding crowdsource list', 'danger');
}
} catch (error) {
console.error('Error adding crowdsource list:', error);
showAlert('Error adding crowdsource list', 'danger');
}
}
async function syncCrowdsourceList(id) {
try {
const response = await fetch(`${API_BASE}/url-lists/${id}/sync`, {
method: 'POST',
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert(`Sync completed: ${result.entries_added || 0} entries added`, 'success');
loadCrowdsourceLists();
refreshStats();
if (result.list_type === 'whitelist') loadWhitelist();
if (result.list_type === 'blacklist') loadBlacklist();
} else {
showAlert(result.error || 'Error syncing crowdsource list', 'danger');
}
} catch (error) {
console.error('Error syncing crowdsource list:', error);
showAlert('Error syncing crowdsource list', 'danger');
}
}
async function toggleCrowdsourceList(id, enabled) {
try {
const response = await fetch(`${API_BASE}/url-lists/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled }),
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert(`Crowdsource list ${enabled ? 'enabled' : 'disabled'}`, 'success');
loadCrowdsourceLists();
} else {
showAlert(result.error || 'Error updating crowdsource list', 'danger');
}
} catch (error) {
console.error('Error toggling crowdsource list:', error);
showAlert('Error updating crowdsource list', 'danger');
}
}
async function deleteCrowdsourceList(id) {
if (!confirm('Are you sure you want to delete this crowdsource list? This will not remove the imported IPs.')) {
return;
}
try {
const response = await fetch(`${API_BASE}/url-lists/${id}`, {
method: 'DELETE',
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert('Crowdsource list deleted successfully', 'success');
loadCrowdsourceLists();
} else {
showAlert(result.error || 'Error deleting crowdsource list', 'danger');
}
} catch (error) {
console.error('Error deleting crowdsource list:', error);
showAlert('Error deleting crowdsource list', 'danger');
}
}
function formatInterval(seconds) {
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
return `${Math.floor(seconds / 86400)}d`;
}
// AbuseIPDB Settings Functions
async function loadAbuseIPDBSettings() {
try {
const response = await fetch(`${API_BASE}/abuseipdb/status`, fetchOptions);
if (response.ok) {
const status = await response.json();
// Update form fields (don't show full API key for security)
const apiKeyInput = document.getElementById('abuseipdb-api-key');
if (apiKeyInput) {
if (status.api_key_configured) {
apiKeyInput.placeholder = 'API key is configured (enter new key to change)';
apiKeyInput.value = '';
} else {
apiKeyInput.placeholder = 'Enter your AbuseIPDB API key';
}
}
const modeSelect = document.getElementById('abuseipdb-mode');
if (modeSelect) {
modeSelect.value = status.mode || 'automatic';
}
const enabledCheckbox = document.getElementById('abuseipdb-enabled');
if (enabledCheckbox) {
enabledCheckbox.checked = status.enabled || false;
}
// Update status display
const statusDisplay = document.getElementById('abuseipdb-status-display');
if (statusDisplay) {
const statusBadge = status.enabled
? '<span class="badge bg-success">Enabled</span>'
: '<span class="badge bg-secondary">Disabled</span>';
const apiKeyStatus = status.api_key_configured
? '<span class="badge bg-success">Configured</span>'
: '<span class="badge bg-warning">Not Configured</span>';
statusDisplay.innerHTML = `
<div class="mb-2">
<strong>Status:</strong> ${statusBadge}
</div>
<div class="mb-2">
<strong>API Key:</strong> ${apiKeyStatus}
</div>
<div class="mb-2">
<strong>Mode:</strong> <span class="badge bg-info">${status.mode || 'automatic'}</span>
</div>
<div class="mb-2">
<strong>Queue Count:</strong> ${status.queue_count || 0} pending reports
</div>
`;
}
}
} catch (error) {
console.error('Error loading AbuseIPDB settings:', error);
}
}
async function saveAbuseIPDBSettings() {
const apiKey = document.getElementById('abuseipdb-api-key').value.trim();
const mode = document.getElementById('abuseipdb-mode').value;
const enabled = document.getElementById('abuseipdb-enabled').checked;
try {
const response = await fetch(`${API_BASE}/settings/abuseipdb`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
api_key: apiKey || null,
mode: mode,
enabled: enabled
}),
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert('AbuseIPDB settings saved successfully. Restart the server for changes to take full effect.', 'success');
loadAbuseIPDBSettings();
} else {
showAlert(result.error || 'Error saving AbuseIPDB settings', 'danger');
}
} catch (error) {
console.error('Error saving AbuseIPDB settings:', error);
showAlert('Error saving AbuseIPDB settings', 'danger');
}
}
async function testAbuseIPDBConnection() {
try {
const response = await fetch(`${API_BASE}/abuseipdb/status`, fetchOptions);
if (response.ok) {
const status = await response.json();
if (status.enabled && status.api_key_configured) {
showAlert('AbuseIPDB connection test successful', 'success');
} else {
showAlert('AbuseIPDB is not configured. Please enter an API key.', 'warning');
}
} else {
showAlert('Error testing AbuseIPDB connection', 'danger');
}
} catch (error) {
console.error('Error testing AbuseIPDB connection:', error);
showAlert('Error testing AbuseIPDB connection', 'danger');
}
}
function toggleApiKeyVisibility() {
const apiKeyInput = document.getElementById('abuseipdb-api-key');
const eyeIcon = document.getElementById('api-key-eye-icon');
if (apiKeyInput.type === 'password') {
apiKeyInput.type = 'text';
eyeIcon.className = 'bi bi-eye-slash';
} else {
apiKeyInput.type = 'password';
eyeIcon.className = 'bi bi-eye';
}
}
// System Settings Functions
async function loadSystemSettings() {
try {
const response = await fetch(`${API_BASE}/settings`, fetchOptions);
if (response.ok) {
const settings = await response.json();
// Server settings
if (settings.server) {
document.getElementById('server-host').value = settings.server.host || '';
document.getElementById('server-port').value = settings.server.port || '';
document.getElementById('secret-key').value = settings.server.secret_key || '';
}
// Database settings
if (settings.database) {
document.getElementById('db-host').value = settings.database.host || '';
document.getElementById('db-name').value = settings.database.name || '';
document.getElementById('db-user').value = settings.database.user || '';
// Don't load password for security
}
// OIDC settings
if (settings.oidc) {
document.getElementById('oidc-issuer').value = settings.oidc.issuer || '';
document.getElementById('oidc-client-id').value = settings.oidc.client_id || '';
document.getElementById('oidc-client-secret').value = settings.oidc.client_secret || '';
document.getElementById('oidc-redirect-uri').value = settings.oidc.redirect_uri || '';
document.getElementById('oidc-post-logout-uri').value = settings.oidc.post_logout_uri || '';
}
}
// Load appearance, proxy, and monitoring settings
await loadAppearanceSettings();
await loadProxySettings();
await loadMonitoringSettings();
} catch (error) {
console.error('Error loading system settings:', error);
}
}
async function saveServerSettings() {
const host = document.getElementById('server-host').value.trim();
const port = document.getElementById('server-port').value.trim();
const secretKey = document.getElementById('secret-key').value.trim();
try {
const response = await fetch(`${API_BASE}/settings/server`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
host: host,
port: port,
secret_key: secretKey || null
}),
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert('Server settings saved. Restart the server for changes to take effect.', 'success');
} else {
showAlert(result.error || 'Error saving server settings', 'danger');
}
} catch (error) {
console.error('Error saving server settings:', error);
showAlert('Error saving server settings', 'danger');
}
}
async function saveDatabaseSettings() {
const host = document.getElementById('db-host').value.trim();
const name = document.getElementById('db-name').value.trim();
const user = document.getElementById('db-user').value.trim();
const password = document.getElementById('db-password').value.trim();
try {
const response = await fetch(`${API_BASE}/settings/database`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
host: host,
name: name,
user: user,
password: password || null
}),
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert('Database settings saved. Restart the server for changes to take effect.', 'success');
document.getElementById('db-password').value = '';
} else {
showAlert(result.error || 'Error saving database settings', 'danger');
}
} catch (error) {
console.error('Error saving database settings:', error);
showAlert('Error saving database settings', 'danger');
}
}
async function testDatabaseConnection() {
const host = document.getElementById('db-host').value.trim();
const name = document.getElementById('db-name').value.trim();
const user = document.getElementById('db-user').value.trim();
const password = document.getElementById('db-password').value.trim();
try {
const response = await fetch(`${API_BASE}/settings/database/test`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
host: host,
name: name,
user: user,
password: password || null
}),
credentials: 'include'
});
const result = await response.json();
if (response.ok && result.success) {
showAlert('Database connection test successful', 'success');
} else {
showAlert(result.error || 'Database connection test failed', 'danger');
}
} catch (error) {
console.error('Error testing database connection:', error);
showAlert('Error testing database connection', 'danger');
}
}
async function saveOIDCSettings() {
const issuer = document.getElementById('oidc-issuer').value.trim();
const clientId = document.getElementById('oidc-client-id').value.trim();
const clientSecret = document.getElementById('oidc-client-secret').value.trim();
const redirectUri = document.getElementById('oidc-redirect-uri').value.trim();
const postLogoutUri = document.getElementById('oidc-post-logout-uri').value.trim();
try {
const response = await fetch(`${API_BASE}/settings/oidc`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
issuer: issuer,
client_id: clientId,
client_secret: clientSecret || null,
redirect_uri: redirectUri,
post_logout_uri: postLogoutUri
}),
credentials: 'include'
});
const result = await response.json();
if (response.ok) {
showAlert('OIDC settings saved. Restart the server for changes to take effect.', 'success');
} else {
showAlert(result.error || 'Error saving OIDC settings', 'danger');
}
} catch (error) {
console.error('Error saving OIDC settings:', error);
showAlert('Error saving OIDC settings', 'danger');
}
}
async function loadMonitoringSettings() {
try {
// Load monitoring settings
const settingsResponse = await fetch(`${API_BASE}/monitoring/settings`, fetchOptions);
if (settingsResponse.ok) {
const settings = await settingsResponse.json();
document.getElementById('enable-log-monitoring').checked = settings.enabled || false;
document.getElementById('monitor-threshold').value = settings.threshold || 5;
document.getElementById('monitor-duration').value = settings.duration || 60;
document.getElementById('history-retention').value = settings.history_retention || 90;
document.getElementById('enable-permaban').checked = settings.permaban_enabled || false;
document.getElementById('permaban-threshold').value = settings.permaban_threshold || 10;
// Show/hide permaban settings
const permabanSettings = document.getElementById('permaban-settings');
if (permabanSettings) {
permabanSettings.style.display = settings.permaban_enabled ? 'block' : 'none';
}
}
// Load monitored services
const servicesResponse = await fetch(`${API_BASE}/monitoring/services`, fetchOptions);
if (servicesResponse.ok) {
const services = await servicesResponse.json();
const servicesList = document.getElementById('monitored-services-list');
if (servicesList && services.length > 0) {
servicesList.innerHTML = services.map(service => `
<div class="card mb-2">
<div class="card-body p-2">
<div class="row align-items-center">
<div class="col-md-4">
<div class="form-check">
<input class="form-check-input service-toggle" type="checkbox"
id="service-${service.service_name}"
data-service="${service.service_name}"
${service.enabled ? 'checked' : ''}>
<label class="form-check-label" for="service-${service.service_name}">
<strong>${service.service_name}</strong>
</label>
</div>
</div>
<div class="col-md-3">
<label class="form-label small">Threshold</label>
<input type="number" class="form-control form-control-sm service-threshold"
data-service="${service.service_name}"
value="${service.threshold || 5}" min="1" max="100">
</div>
<div class="col-md-3">
<label class="form-label small">Duration (min)</label>
<input type="number" class="form-control form-control-sm service-duration"
data-service="${service.service_name}"
value="${service.duration_minutes || 60}" min="1" max="1440">
</div>
</div>
</div>
</div>
`).join('');
}
}
} catch (error) {
console.error('Error loading monitoring settings:', error);
}
}
async function saveMonitoringSettings() {
const enabled = document.getElementById('enable-log-monitoring').checked;
const threshold = parseInt(document.getElementById('monitor-threshold').value) || 5;
const duration = parseInt(document.getElementById('monitor-duration').value) || 60;
const historyRetention = parseInt(document.getElementById('history-retention').value) || 90;
const permabanEnabled = document.getElementById('enable-permaban').checked;
const permabanThreshold = parseInt(document.getElementById('permaban-threshold').value) || 10;
// Collect service configurations
const services = [];
document.querySelectorAll('.service-toggle').forEach(checkbox => {
const serviceName = checkbox.dataset.service;
const thresholdInput = document.querySelector(`.service-threshold[data-service="${serviceName}"]`);
const durationInput = document.querySelector(`.service-duration[data-service="${serviceName}"]`);
services.push({
service_name: serviceName,
enabled: checkbox.checked,
threshold: parseInt(thresholdInput?.value) || 5,
duration_minutes: parseInt(durationInput?.value) || 60