forked from thinhhoangpham/tcp_timearcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattack_timearcs.js.backup
More file actions
3424 lines (3027 loc) · 132 KB
/
attack_timearcs.js.backup
File metadata and controls
3424 lines (3027 loc) · 132 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
// Network TimeArcs visualization
// Input CSV schema: timestamp,length,src_ip,dst_ip,protocol,count
// - timestamp: integer absolute minutes. If very large (>1e6), treated as minutes since Unix epoch.
// Otherwise treated as relative minutes and displayed as t=.. labels.
(function () {
const fileInput = document.getElementById('fileInput');
const ipMapInput = document.getElementById('ipMapInput');
const eventMapInput = document.getElementById('eventMapInput');
const statusEl = document.getElementById('status');
const svg = d3.select('#chart');
const container = document.getElementById('chart-container');
const legendEl = document.getElementById('legend');
const tooltip = document.getElementById('tooltip');
const labelModeRadios = document.querySelectorAll('input[name="labelMode"]');
const lensingMulSlider = document.getElementById('lensingMulSlider');
const lensingMulValue = document.getElementById('lensingMulValue');
const lensingToggleBtn = document.getElementById('lensingToggle');
// User-selected labeling mode: 'attack' or 'attack_group'
let labelMode = 'attack';
labelModeRadios.forEach(r => r.addEventListener('change', () => {
const sel = Array.from(labelModeRadios).find(r=>r.checked);
labelMode = sel ? sel.value : 'attack';
if (lastRawCsvRows) {
render(rebuildDataFromRawRows(lastRawCsvRows));
}
}));
// Handle lens magnification slider
if (lensingMulSlider && lensingMulValue) {
lensingMulSlider.addEventListener('input', (e) => {
lensingMul = parseFloat(e.target.value);
fisheyeDistortion = lensingMul; // Sync fisheye distortion with slider
lensingMulValue.textContent = `${lensingMul}x`;
// Update vertical fisheye scale distortion if it exists
if (fisheyeScale && typeof fisheyeScale.distortion === 'function') {
fisheyeScale.distortion(fisheyeDistortion);
}
// Update horizontal fisheye scale distortion if it exists
if (horizontalFisheyeScale && typeof horizontalFisheyeScale.distortion === 'function') {
horizontalFisheyeScale.distortion(fisheyeDistortion);
}
// If lensing is active, update visualization immediately
if (isLensing && updateLensVisualizationFn) {
updateLensVisualizationFn();
}
});
}
// Handle lens toggle button
function updateLensingButtonState() {
if (!lensingToggleBtn) return;
if (fisheyeEnabled) {
lensingToggleBtn.style.background = '#0d6efd';
lensingToggleBtn.style.color = '#fff';
lensingToggleBtn.style.borderColor = '#0d6efd';
} else {
lensingToggleBtn.style.background = '#fff';
lensingToggleBtn.style.color = '#000';
lensingToggleBtn.style.borderColor = '#dee2e6';
}
}
// Store reference to resetFisheye function so it can be called from button handler
let resetFisheyeFn = null;
if (lensingToggleBtn) {
lensingToggleBtn.addEventListener('click', () => {
fisheyeEnabled = !fisheyeEnabled;
console.log('Fisheye toggled:', fisheyeEnabled);
// Reset to original positions when disabled
if (!fisheyeEnabled && resetFisheyeFn) {
resetFisheyeFn();
}
// Update cursor on SVG
const svgEl = d3.select('#chart');
svgEl.style('cursor', fisheyeEnabled ? 'crosshair' : 'default');
updateLensingButtonState();
});
}
// Handle keyboard shortcut: Shift + L to toggle lensing
document.addEventListener('keydown', (e) => {
// Check for Shift + L (case insensitive)
if (e.shiftKey && (e.key === 'L' || e.key === 'l')) {
e.preventDefault(); // Prevent default browser behavior
fisheyeEnabled = !fisheyeEnabled;
console.log('Fisheye toggled (keyboard):', fisheyeEnabled);
// Reset to original positions when disabled
if (!fisheyeEnabled && resetFisheyeFn) {
resetFisheyeFn();
}
// Update cursor on SVG
const svgEl = d3.select('#chart');
svgEl.style('cursor', fisheyeEnabled ? 'crosshair' : 'default');
updateLensingButtonState();
}
});
const margin = { top: 40, right: 20, bottom: 30, left: 110 };
let width = 1200; // updated on render
let height = 600; // updated on render
// Lens magnification state (horizontal time only, matching main.js)
let isLensing = false;
let lensingMul = 5; // Magnification factor (5x)
let lensCenter = 0; // Focused timestamp position (horizontal)
let XGAP_BASE = null; // Base X-scale gap for lens calculations
let labelsCompressedMode = false; // When true, hide baseline labels and only show magnified ones
// Fisheye state (vertical row distortion)
let fisheyeEnabled = false;
let fisheyeScale = null;
let fisheyeDistortion = 5; // Initial distortion amount (linked to lensingMul slider)
let originalRowPositions = new Map(); // Store original Y positions for each IP
// Horizontal fisheye state (timeline distortion)
let horizontalFisheyeScale = null;
let currentMouseX = null; // Current mouse X position for horizontal fisheye
// Default protocol colors
const protocolColors = new Map([
['TCP', '#1f77b4'],
['UDP', '#2ca02c'],
['ICMP', '#ff7f0e'],
['GRE', '#9467bd'],
['ARP', '#8c564b'],
['DNS', '#17becf'],
]);
const defaultColor = '#6c757d';
// IP map state (id -> dotted string)
let ipIdToAddr = null; // Map<number, string>
let ipMapLoaded = false;
// Attack/event mapping: id -> name, and color mapping: name -> color
let attackIdToName = null; // Map<number, string>
let colorByAttack = null; // Map<string, string> by canonicalized name
let rawColorByAttack = null; // original keys
// Attack group mapping/color
let attackGroupIdToName = null; // Map<number,string>
let colorByAttackGroup = null; // canonical map
let rawColorByAttackGroup = null;
// Track visible attacks for legend filtering
let visibleAttacks = new Set(); // Set of attack names that are currently visible
let currentArcPaths = null; // Reference to arc paths selection for visibility updates
let currentLabelMode = 'attack'; // Track current label mode for filtering
// Reference to updateLensVisualization function so slider can trigger updates
let updateLensVisualizationFn = null;
// Reference to toggleLensing function so button can trigger it
let toggleLensingFn = null;
// Initialize mappings, then try a default CSV load
(async function init() {
try {
await Promise.all([
loadIpMap(),
loadEventTypeMap(),
loadColorMapping(),
loadAttackGroupMap(),
loadAttackGroupColorMapping(),
]);
} catch (_) { /* non-fatal */ }
// After maps are ready (or failed gracefully), try default CSV
tryLoadDefaultCsv();
})();
// Stream-parse a CSV file incrementally to avoid loading entire file into memory
// Pushes transformed rows directly into combinedData, returns {totalRows, validRows}
async function processCsvFile(file, combinedData, options = { hasHeader: true, delimiter: ',' }) {
const hasHeader = options.hasHeader !== false;
const delimiter = options.delimiter || ',';
let header = null;
let totalRows = 0;
let validRows = 0;
// Incremental line splitter handling CR/CRLF/LF boundaries
let carry = '';
const decoder = new TextDecoder();
const reader = file.stream().getReader();
function emitLinesFromChunk(txt, onLine) {
carry += txt;
let idx;
while ((idx = findNextBreak(carry)) >= 0) {
const line = carry.slice(0, idx);
onLine(line);
carry = stripBreakPrefix(carry.slice(idx));
}
}
function findNextBreak(s) {
const n = s.indexOf('\n');
const r = s.indexOf('\r');
if (n === -1 && r === -1) return -1;
if (n === -1) return r;
if (r === -1) return n;
return Math.min(n, r);
}
function stripBreakPrefix(s) {
if (s.startsWith('\r\n')) return s.slice(2);
if (s.startsWith('\n') || s.startsWith('\r')) return s.slice(1);
return s;
}
function parseCsvLine(line) {
const out = [];
let i = 0;
const n = line.length;
while (i < n) {
if (line[i] === '"') {
i++;
let start = i;
let val = '';
while (i < n) {
const ch = line[i];
if (ch === '"') {
if (i + 1 < n && line[i + 1] === '"') { val += line.slice(start, i) + '"'; i += 2; start = i; continue; }
val += line.slice(start, i); i++; break;
}
i++;
}
if (i < n && line[i] === delimiter) i++;
out.push(val);
} else {
let start = i;
while (i < n && line[i] !== delimiter) i++;
out.push(line.slice(start, i));
if (i < n && line[i] === delimiter) i++;
}
}
return out;
}
function toNum(v) { const n = +v; return isFinite(n) ? n : NaN; }
function handleRow(cols) {
if (!cols || cols.length === 0) return;
totalRows++;
const obj = header ? Object.fromEntries(header.map((h, i) => [h, cols[i]]))
: Object.fromEntries(cols.map((v, i) => [String(i), v]));
const attackName = decodeAttack(obj.attack);
const attackGroupName = decodeAttackGroup(obj.attack_group, obj.attack);
const rec = {
idx: combinedData.length,
timestamp: toNum(obj.timestamp),
length: toNum(obj.length),
src_ip: decodeIp(obj.src_ip),
dst_ip: decodeIp(obj.dst_ip),
protocol: (obj.protocol || '').toUpperCase() || 'OTHER',
count: toNum(obj.count) || 1,
attack: attackName,
attack_group: attackGroupName,
};
const hasValidTimestamp = isFinite(rec.timestamp);
const hasValidSrcIp = rec.src_ip && rec.src_ip !== 'N/A' && !String(rec.src_ip).startsWith('IP_');
const hasValidDstIp = rec.dst_ip && rec.dst_ip !== 'N/A' && !String(rec.dst_ip).startsWith('IP_');
if (hasValidTimestamp && hasValidSrcIp && hasValidDstIp) {
combinedData.push(rec);
validRows++;
}
}
// Read stream in chunks
while (true) {
const { value, done } = await reader.read();
if (done) break;
const txt = decoder.decode(value, { stream: true });
emitLinesFromChunk(txt, (line) => {
const s = line.trim();
if (!s) return;
if (!header && hasHeader) { header = parseCsvLine(s); return; }
const cols = parseCsvLine(s);
handleRow(cols);
});
}
// flush remainder
if (carry.trim()) {
const s = carry.trim();
if (!header && hasHeader) header = parseCsvLine(s); else handleRow(parseCsvLine(s));
}
return { fileName: file.name, totalRows, validRows };
}
// Transform raw CSV rows to processed data
function transformRows(rows, startIdx = 0) {
return rows.map((d, i) => {
const attackName = decodeAttack(d.attack);
const attackGroupName = decodeAttackGroup(d.attack_group, d.attack);
const srcIp = decodeIp(d.src_ip);
const dstIp = decodeIp(d.dst_ip);
return {
idx: startIdx + i,
timestamp: toNumber(d.timestamp),
length: toNumber(d.length),
src_ip: srcIp,
dst_ip: dstIp,
protocol: (d.protocol || '').toUpperCase() || 'OTHER',
count: toNumber(d.count) || 1,
attack: attackName,
attack_group: attackGroupName,
};
}).filter(d => {
// Filter out records with invalid data
const hasValidTimestamp = isFinite(d.timestamp);
const hasValidSrcIp = d.src_ip && d.src_ip !== 'N/A' && !d.src_ip.startsWith('IP_');
const hasValidDstIp = d.dst_ip && d.dst_ip !== 'N/A' && !d.dst_ip.startsWith('IP_');
// Debug logging for filtered records
if (!hasValidSrcIp || !hasValidDstIp) {
console.log('Filtering out record:', {
src_ip: d.src_ip,
dst_ip: d.dst_ip,
hasValidSrcIp,
hasValidDstIp,
ipMapLoaded,
ipMapSize: ipIdToAddr ? ipIdToAddr.size : 0
});
}
return hasValidTimestamp && hasValidSrcIp && hasValidDstIp;
});
}
// Handle CSV upload - supports multiple files
fileInput?.addEventListener('change', async (e) => {
const files = Array.from(e.target.files || []);
if (files.length === 0) return;
// Show loading status
if (files.length === 1) {
status(`Loading ${files[0].name} …`);
} else {
status(`Loading ${files.length} files…`);
}
try {
console.log('Processing CSV files with IP map status:', {
fileCount: files.length,
ipMapLoaded,
ipMapSize: ipIdToAddr ? ipIdToAddr.size : 0
});
// Warn if IP map is not loaded
if (!ipMapLoaded || !ipIdToAddr || ipIdToAddr.size === 0) {
console.warn('IP map not loaded or empty. Some IP IDs may not be mapped correctly.');
status('Warning: IP map not loaded. Some data may be filtered out.');
}
// Process files sequentially to bound memory; stream-parse to avoid full-file buffers
const combinedData = [];
const fileStats = [];
const errors = [];
for (const file of files) {
try {
const res = await processCsvFile(file, combinedData, { hasHeader: true, delimiter: ',' });
const filteredRows = res.totalRows - res.validRows;
fileStats.push({ fileName: file.name, totalRows: res.totalRows, validRows: res.validRows, filteredRows });
} catch (err) {
errors.push({ fileName: file.name, error: err });
console.error(`Failed to load ${file.name}:`, err);
}
}
// Disable rebuild cache for huge datasets to avoid memory spikes
lastRawCsvRows = null;
if (combinedData.length === 0) {
if (errors.length > 0) {
status(`Failed to load files. ${errors.length} error(s) occurred.`);
} else {
status('No valid rows found. Ensure CSV files have required columns and IP mappings are available.');
}
clearChart();
return;
}
// Build status message with summary
const successfulFiles = fileStats.length;
const totalValidRows = combinedData.length;
const totalFilteredRows = fileStats.reduce((sum, stat) => sum + stat.filteredRows, 0);
let statusMsg = '';
if (files.length === 1) {
// Single file: show simple message
if (totalFilteredRows > 0) {
statusMsg = `Loaded ${totalValidRows} valid rows (${totalFilteredRows} rows filtered due to missing IP mappings)`;
} else {
statusMsg = `Loaded ${totalValidRows} records`;
}
} else {
// Multiple files: show detailed summary
const fileSummary = fileStats.map(stat =>
`${stat.fileName} (${stat.validRows} valid${stat.filteredRows > 0 ? `, ${stat.filteredRows} filtered` : ''})`
).join('; ');
statusMsg = `Loaded ${successfulFiles} file(s): ${fileSummary}. Total: ${totalValidRows} records`;
if (errors.length > 0) {
statusMsg += `. ${errors.length} file(s) failed to load.`;
}
}
status(statusMsg);
render(combinedData);
} catch (err) {
console.error(err);
status('Failed to read CSV file(s).');
clearChart();
}
});
// Allow user to upload a custom ip_map JSON (expected format: { "1.2.3.4": 123, ... } OR reverse { "123": "1.2.3.4" })
ipMapInput?.addEventListener('change', async (e) => {
const file = e.target.files?.[0];
if (!file) return;
status(`Loading IP map ${file.name} …`);
try {
const text = await file.text();
const obj = JSON.parse(text);
const rev = new Map();
const entries = Object.entries(obj);
// Detect orientation: sample if keys look like IPs
let ipKeyMode = 0, numericKeyMode = 0;
for (const [k,v] of entries.slice(0,20)) {
if (/^\d+\.\d+\.\d+\.\d+$/.test(k) && Number.isFinite(Number(v))) ipKeyMode++;
if (!isNaN(+k) && typeof v === 'string' && /^\d+\.\d+\.\d+\.\d+$/.test(v)) numericKeyMode++;
}
if (ipKeyMode >= numericKeyMode) {
// ipString -> idNumber
for (const [ip,id] of entries) {
const num = Number(id);
if (Number.isFinite(num) && /^\d+\.\d+\.\d+\.\d+$/.test(ip)) rev.set(num, ip);
}
} else {
// idNumber -> ipString
for (const [idStr, ip] of entries) {
const num = Number(idStr);
if (Number.isFinite(num) && /^\d+\.\d+\.\d+\.\d+$/.test(ip)) rev.set(num, ip);
}
}
ipIdToAddr = rev;
ipMapLoaded = true;
console.log(`Custom IP map loaded with ${rev.size} entries`);
console.log('Sample entries:', Array.from(rev.entries()).slice(0, 5));
status(`Custom IP map loaded (${rev.size} entries). Re-rendering…`);
if (lastRawCsvRows) {
// rebuild to decode IP ids again
render(rebuildDataFromRawRows(lastRawCsvRows));
}
} catch (err) {
console.error(err);
status('Failed to parse IP map JSON.');
}
});
// Allow user to upload a custom event_type_mapping JSON (expected format: { "attack_name": 123, ... } OR reverse { "123": "attack_name" })
eventMapInput?.addEventListener('change', async (e) => {
const file = e.target.files?.[0];
if (!file) return;
status(`Loading event type map ${file.name} …`);
try {
const text = await file.text();
const obj = JSON.parse(text);
const rev = new Map();
const entries = Object.entries(obj);
// Detect orientation: sample if keys look like numbers (IDs) or strings (names)
let nameKeyMode = 0, idKeyMode = 0;
for (const [k, v] of entries.slice(0, 20)) {
if (typeof k === 'string' && !isNaN(+v) && Number.isFinite(Number(v))) nameKeyMode++;
if (!isNaN(+k) && typeof v === 'string') idKeyMode++;
}
if (nameKeyMode >= idKeyMode) {
// name -> id format: { "attack_name": 123 }
for (const [name, id] of entries) {
const num = Number(id);
if (Number.isFinite(num)) rev.set(num, name);
}
} else {
// id -> name format: { "123": "attack_name" }
for (const [idStr, name] of entries) {
const num = Number(idStr);
if (Number.isFinite(num) && typeof name === 'string') rev.set(num, name);
}
}
attackIdToName = rev;
console.log(`Custom event type map loaded with ${rev.size} entries`);
console.log('Sample entries:', Array.from(rev.entries()).slice(0, 5));
status(`Custom event type map loaded (${rev.size} entries). Re-rendering…`);
if (lastRawCsvRows) {
// rebuild to decode attack IDs again
render(rebuildDataFromRawRows(lastRawCsvRows));
}
} catch (err) {
console.error(err);
status('Failed to parse event type map JSON.');
}
});
// Keep last raw CSV rows so we can rebuild when mappings change
let lastRawCsvRows = null; // array of raw objects from csvParse
function rebuildDataFromRawRows(rows){
return rows.map((d, i) => {
const attackName = decodeAttack(d.attack);
const attackGroupName = decodeAttackGroup(d.attack_group, d.attack);
return {
idx: i,
timestamp: toNumber(d.timestamp),
length: toNumber(d.length),
src_ip: decodeIp(d.src_ip),
dst_ip: decodeIp(d.dst_ip),
protocol: (d.protocol || '').toUpperCase() || 'OTHER',
count: toNumber(d.count) || 1,
attack: attackName,
attack_group: attackGroupName,
};
}).filter(d => {
// Filter out records with invalid data
const hasValidTimestamp = isFinite(d.timestamp);
const hasValidSrcIp = d.src_ip && d.src_ip !== 'N/A' && !d.src_ip.startsWith('IP_');
const hasValidDstIp = d.dst_ip && d.dst_ip !== 'N/A' && !d.dst_ip.startsWith('IP_');
return hasValidTimestamp && hasValidSrcIp && hasValidDstIp;
});
}
async function tryLoadDefaultCsv() {
const defaultPath = './set1_first90_minutes.csv';
try {
const res = await fetch(defaultPath, { cache: 'no-store' });
if (!res.ok) return; // quietly exit if not found
const text = await res.text();
const rows = d3.csvParse((text || '').trim());
lastRawCsvRows = rows; // cache raw rows
const data = rows.map((d, i) => {
const attackName = decodeAttack(d.attack);
const attackGroupName = decodeAttackGroup(d.attack_group, d.attack);
return {
idx: i,
timestamp: toNumber(d.timestamp),
length: toNumber(d.length),
src_ip: decodeIp(d.src_ip),
dst_ip: decodeIp(d.dst_ip),
protocol: (d.protocol || '').toUpperCase() || 'OTHER',
count: toNumber(d.count) || 1,
attack: attackName,
attack_group: attackGroupName,
};
}).filter(d => {
// Filter out records with invalid data
const hasValidTimestamp = isFinite(d.timestamp);
const hasValidSrcIp = d.src_ip && d.src_ip !== 'N/A' && !d.src_ip.startsWith('IP_');
const hasValidDstIp = d.dst_ip && d.dst_ip !== 'N/A' && !d.dst_ip.startsWith('IP_');
return hasValidTimestamp && hasValidSrcIp && hasValidDstIp;
});
if (!data.length) {
status('Default CSV loaded but no valid rows found. Check IP mappings.');
return;
}
// Report how many rows were filtered out
const totalRows = rows.length;
const filteredRows = totalRows - data.length;
if (filteredRows > 0) {
status(`Loaded default: set1_first90_minutes.csv (${data.length} valid rows, ${filteredRows} filtered due to missing IP mappings)`);
} else {
status(`Loaded default: set1_first90_minutes.csv (${data.length} rows)`);
}
render(data);
} catch (err) {
// ignore if file isn't present; keep waiting for upload
}
}
function toNumber(v) {
const n = +v; return isFinite(n) ? n : 0;
}
function status(msg) { if (statusEl) statusEl.textContent = msg; }
function clearChart() {
svg.selectAll('*').remove();
legendEl.innerHTML = '';
}
// Use d3 formatters consistently; we prefer UTC to match axis
// Function to update arc visibility based on visible attacks
function updateArcVisibility() {
if (!currentArcPaths) return;
currentArcPaths.style('display', d => {
const attackName = (currentLabelMode === 'attack_group' ? d.attack_group : d.attack) || 'normal';
return visibleAttacks.has(attackName) ? 'block' : 'none';
});
}
// Function to update all legend items' visual state
function updateLegendVisualState() {
const legendItems = legendEl.querySelectorAll('.legend-item');
legendItems.forEach(item => {
const attackName = item.getAttribute('data-attack');
const isVisible = visibleAttacks.has(attackName);
if (isVisible) {
item.style.opacity = '1';
item.style.textDecoration = 'none';
} else {
item.style.opacity = '0.3';
item.style.textDecoration = 'line-through';
}
});
}
// Function to isolate a single attack (hide all others)
// If the attack is already isolated (only one visible), show all attacks instead
function isolateAttack(attackName) {
// Check if this attack is already isolated (only one visible and it's this one)
if (visibleAttacks.size === 1 && visibleAttacks.has(attackName)) {
// Show all attacks (toggle back to showing all)
const legendItems = legendEl.querySelectorAll('.legend-item');
visibleAttacks.clear();
legendItems.forEach(item => {
visibleAttacks.add(item.getAttribute('data-attack'));
});
} else {
// Clear all visible attacks
visibleAttacks.clear();
// Add only the isolated attack
visibleAttacks.add(attackName);
}
// Update arc visibility
updateArcVisibility();
// Update all legend items' visual state
updateLegendVisualState();
}
function buildLegend(items, colorFn) {
legendEl.innerHTML = '';
const frag = document.createDocumentFragment();
// Initialize all attacks as visible if set is empty
if (visibleAttacks.size === 0) {
items.forEach(item => visibleAttacks.add(item));
}
items.forEach(p => {
const item = document.createElement('div');
item.className = 'legend-item';
item.style.cursor = 'pointer';
item.style.userSelect = 'none';
item.setAttribute('data-attack', p);
// Add visual indicator for hidden items
const isVisible = visibleAttacks.has(p);
if (!isVisible) {
item.style.opacity = '0.3';
item.style.textDecoration = 'line-through';
}
const sw = document.createElement('div');
sw.className = 'swatch';
sw.style.background = colorFn(p);
const label = document.createElement('span');
label.textContent = p;
item.appendChild(sw);
item.appendChild(label);
// Handle click vs double-click timing
let lastClickTime = 0;
let clickTimeout = null;
// Add click handler to toggle visibility (delayed to allow double-click detection)
item.addEventListener('click', function(e) {
const attackName = this.getAttribute('data-attack');
const now = Date.now();
// If this click happened very recently (within 300ms), it's likely part of a double-click
// Wait a bit to see if dblclick fires
if (now - lastClickTime < 300) {
// Likely part of a double-click, ignore this click
if (clickTimeout) {
clearTimeout(clickTimeout);
clickTimeout = null;
}
lastClickTime = now;
return;
}
lastClickTime = now;
// Clear any pending single-click action
if (clickTimeout) {
clearTimeout(clickTimeout);
}
// Delay single-click action to detect double-click
clickTimeout = setTimeout(() => {
clickTimeout = null;
if (visibleAttacks.has(attackName)) {
visibleAttacks.delete(attackName);
} else {
visibleAttacks.add(attackName);
}
updateArcVisibility();
updateLegendVisualState();
}, 300); // 300ms delay to detect double-click
});
// Add double-click handler to isolate attack
item.addEventListener('dblclick', function(e) {
e.preventDefault();
// Clear pending single-click action
if (clickTimeout) {
clearTimeout(clickTimeout);
clickTimeout = null;
}
const attackName = this.getAttribute('data-attack');
isolateAttack(attackName);
lastClickTime = Date.now();
});
// Add hover effect
item.addEventListener('mouseenter', function() {
if (visibleAttacks.has(this.getAttribute('data-attack'))) {
this.style.backgroundColor = 'rgba(0, 0, 0, 0.05)';
}
});
item.addEventListener('mouseleave', function() {
this.style.backgroundColor = '';
});
frag.appendChild(item);
});
legendEl.appendChild(frag);
}
function render(data) {
// Determine timestamp handling
const tsMin = d3.min(data, d => d.timestamp);
const tsMax = d3.max(data, d => d.timestamp);
// Heuristic timestamp unit detection by magnitude:
// - Microseconds: > 1e15
// - Milliseconds: > 1e12 and <= 1e15
// - Seconds: > 1e9 and <= 1e12
// - Minutes: > 1e7 and <= 1e9
// - Hours: > 1e5 and <= 1e7
// Otherwise: treat as relative values (default unit minutes to preserve legacy)
const looksLikeMicroseconds = tsMin > 1e15;
const looksLikeMilliseconds = tsMin > 1e12 && tsMin <= 1e15;
const looksLikeSeconds = tsMin > 1e9 && tsMin <= 1e12;
const looksLikeMinutesAbs = tsMin > 1e7 && tsMin <= 1e9;
const looksLikeHoursAbs = tsMin > 1e5 && tsMin <= 1e7;
const looksAbsolute = looksLikeMicroseconds || looksLikeMilliseconds || looksLikeSeconds || looksLikeMinutesAbs || looksLikeHoursAbs;
let unit = 'minutes'; // one of: microseconds|milliseconds|seconds|minutes|hours
if (looksLikeMicroseconds) unit = 'microseconds';
else if (looksLikeMilliseconds) unit = 'milliseconds';
else if (looksLikeSeconds) unit = 'seconds';
else if (looksLikeMinutesAbs) unit = 'minutes';
else if (looksLikeHoursAbs) unit = 'hours';
const base = looksAbsolute ? 0 : tsMin; // normalize relative timelines to start at 0
const unitMs = unit === 'microseconds' ? 0.001
: unit === 'milliseconds' ? 1
: unit === 'seconds' ? 1000
: unit === 'minutes' ? 60_000
: 3_600_000; // hours
const unitSuffix = unit === 'seconds' ? 's' : unit === 'hours' ? 'h' : 'm';
console.log('Timestamp debug:', {
tsMin,
tsMax,
looksLikeMicroseconds,
looksLikeMilliseconds,
looksAbsolute,
inferredUnit: unit,
base,
sampleTimestamps: data.slice(0, 5).map(d => d.timestamp)
});
const toDate = (m) => {
if (m === undefined || m === null || !isFinite(m)) {
console.warn('Invalid timestamp in toDate:', m);
return new Date(0); // Return epoch as fallback
}
// Convert using detected unit; for absolute series use m as-is, otherwise offset by base
const val = looksAbsolute ? m : (m - base);
const ms = unit === 'microseconds' ? (val / 1000)
: unit === 'milliseconds' ? (val)
: (val * unitMs);
const result = new Date(ms);
if (!isFinite(result.getTime())) {
console.warn('Invalid date result in toDate:', { m, looksAbsolute, unit, base, computedMs: ms });
return new Date(0); // Return epoch as fallback
}
return result;
};
// Aggregate links; then order IPs using the React component's approach:
// primary-attack grouping, groups ordered by earliest time, nodes within group by force-simulated y
const links = computeLinks(data); // aggregated per pair per minute
// Collect ALL IPs from links (not just from nodes) to ensure scale includes all referenced IPs
const allIpsFromLinks = new Set();
links.forEach(l => {
allIpsFromLinks.add(l.source);
allIpsFromLinks.add(l.target);
});
const nodeData = computeNodesByAttackGrouping(links);
const nodes = nodeData.nodes;
const ips = nodes.map(n => n.name);
const simulation = nodeData.simulation;
const simNodes = nodeData.simNodes;
const yMap = nodeData.yMap;
// Ensure all IPs from links are included in the initial IP list
// This prevents misalignment when arcs reference IPs not in the nodes list
const allIps = Array.from(new Set([...ips, ...allIpsFromLinks]));
console.log('Render debug:', {
dataLength: data.length,
linksLength: links.length,
nodesLength: nodes.length,
ipsLength: ips.length,
allIpsLength: allIps.length,
sampleIps: ips.slice(0, 5),
sampleLinks: links.slice(0, 3)
});
// Determine which label dimension we use (attack vs group) for legend and coloring
const activeLabelKey = labelMode === 'attack_group' ? 'attack_group' : 'attack';
const attacks = Array.from(new Set(links.map(l => l[activeLabelKey] || 'normal'))).sort();
// Always enable ALL attacks on each fresh render (e.g., new data loaded)
// This ensures the legend starts fully enabled regardless of previous toggles
visibleAttacks = new Set(attacks);
currentLabelMode = labelMode;
// Sizing based on fixed height (matching main.js: height = 780)
// main.js uses: height = 780 - margin.top - margin.bottom = 780 (since margin.top=0, margin.bottom=5)
// Match main.js: use fixed height instead of scaling with number of IPs
const innerHeight = 780;
// Fit width to container - like main.js: width accounts for margins
const availableWidth = container.clientWidth || 1200;
const viewportWidth = Math.max(availableWidth, 800);
// Calculate width accounting for margins (like main.js: width = clientWidth - margin.left - margin.right)
width = viewportWidth - margin.left - margin.right;
height = margin.top + innerHeight + margin.bottom;
// Initial SVG size - will be updated after calculating actual arc extents
svg.attr('width', width + margin.left + margin.right).attr('height', height);
const xMinDate = toDate(tsMin);
const xMaxDate = toDate(tsMax);
console.log('X-scale debug:', {
tsMin,
tsMax,
xMinDate,
xMaxDate,
xMinValid: isFinite(xMinDate.getTime()),
xMaxValid: isFinite(xMaxDate.getTime())
});
// Timeline width is the available width after accounting for left margin offset
// Like main.js, we use the full width (after margins) for the timeline
const timelineWidth = width;
console.log('Timeline fitting:', {
containerWidth: container.clientWidth,
viewportWidth,
timelineWidth,
marginLeft: margin.left,
marginRight: margin.right
});
// X scale for timeline that fits in container
// Calculate max arc radius to reserve space for arc curves
const ipIndexMap = new Map(allIps.map((ip, idx) => [ip, idx]));
let maxIpIndexDist = 0;
links.forEach(l => {
const srcIdx = ipIndexMap.get(l.source);
const tgtIdx = ipIndexMap.get(l.target);
if (srcIdx !== undefined && tgtIdx !== undefined) {
const dist = Math.abs(srcIdx - tgtIdx);
if (dist > maxIpIndexDist) maxIpIndexDist = dist;
}
});
// Estimate final spacing after auto-fit (scalePoint with padding 0.5)
const estimatedStep = allIps.length > 1 ? innerHeight / allIps.length : innerHeight;
const maxArcRadius = (maxIpIndexDist * estimatedStep) / 2;
const svgWidth = width + margin.left + margin.right;
const xStart = margin.left;
const xEnd = svgWidth - margin.right - maxArcRadius;
const x = d3.scaleTime()
.domain([xMinDate, xMaxDate])
.range([xStart, xEnd]);
// Calculate base gap for lens calculations
XGAP_BASE = timelineWidth / (tsMax - tsMin);
// Initialize lens center to middle of data range
if (lensCenter === 0 || lensCenter < tsMin || lensCenter > tsMax) {
lensCenter = (tsMin + tsMax) / 2;
}
// Generic 1D lens transform that:
// - expands a band around lensCenterNorm by lensingMul
// - compresses everything outside that band
// - keeps the overall [0,1] interval fixed (0 -> 0, 1 -> 1)
function applyLens1D(normalized, lensCenterNorm, bandRadiusNorm, magnification) {
const n = Math.min(1, Math.max(0, normalized));
const c = Math.min(1, Math.max(0, lensCenterNorm));
const r = Math.max(0, bandRadiusNorm);
if (magnification <= 1 || r === 0) return n;
const a = Math.max(0, c - r);
const b = Math.min(1, c + r);
const insideLength = Math.max(0, b - a);
const outsideLength = a + (1 - b);
if (insideLength === 0 || outsideLength < 0) return n;
const scale = 1 / (outsideLength + insideLength * magnification);
if (n < a) {
// Before lens band: compressed towards 0
return n * scale;
} else if (n > b) {
// After lens band: compressed towards 1
const base = scale * (a + insideLength * magnification);
return base + (n - b) * scale;
} else {
// Inside lens band: expanded around center
const base = scale * a;
return base + (n - a) * magnification * scale;
}
}
// Lens-aware x scale function
function xScaleLens(timestamp) {
const minX = xStart;
const maxX = xEnd;
// Use horizontal fisheye if enabled
if (fisheyeEnabled && horizontalFisheyeScale) {
const fisheyeX = horizontalFisheyeScale.apply(timestamp);
return Math.max(minX, Math.min(fisheyeX, maxX));
}
if (!isLensing) {
// Even when lensing is off, clamp to ensure arcs don't go out of bounds
const rawX = x(toDate(timestamp));
return Math.max(minX, Math.min(rawX, maxX));
}
// Safety check for zero range
if (tsMax === tsMin) {
const rawX = x(toDate(timestamp));
return Math.max(minX, Math.min(rawX, maxX));
}
// Convert timestamp to normalized position (0 to 1)
const normalized = (timestamp - tsMin) / (tsMax - tsMin);
const totalWidth = xEnd - xStart;
// Lens parameters (matching main.js: numLens = 5 months on each side)
// For continuous time, approximate 5 months out of ~108 months = ~4.6% on each side
const lensCenterNorm = (lensCenter - tsMin) / (tsMax - tsMin);
const bandRadiusNorm = 0.045; // ~4.5% on each side (matching main.js's 5 months out of ~108)
const position = applyLens1D(normalized, lensCenterNorm, bandRadiusNorm, lensingMul);
// Map into screen coordinates and clamp to visible timeline so arcs
// never extend beyond the right edge of the chart.
const rawX = minX + position * totalWidth;
return Math.max(minX, Math.min(rawX, maxX));
}