forked from thinhhoangpham/tcp_timearcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattack_timearcs.js
More file actions
2469 lines (2147 loc) · 96.9 KB
/
attack_timearcs.js
File metadata and controls
2469 lines (2147 loc) · 96.9 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
import { MARGIN, DEFAULT_WIDTH, DEFAULT_HEIGHT, INNER_HEIGHT, PROTOCOL_COLORS, DEFAULT_COLOR, NEUTRAL_GREY, LENS_DEFAULTS, FISHEYE_DEFAULTS } from './src/config/constants.js';
import { toNumber, sanitizeId, canonicalizeName, showTooltip, hideTooltip, setStatus } from './src/utils/helpers.js';
import { decodeIp, decodeAttack, decodeAttackGroup, lookupAttackColor, lookupAttackGroupColor } from './src/mappings/decoders.js';
import { buildRelationships, computeConnectivityFromRelationships, computeLinks, findConnectedComponents } from './src/data/aggregation.js';
import { linkArc, gradientIdForLink } from './src/rendering/arcPath.js';
import { buildLegend as createLegend, updateLegendVisualState as updateLegendUI, isolateAttack as isolateLegendAttack } from './src/ui/legend.js';
import { parseCSVStream, parseCSVLine } from './src/data/csvParser.js';
import { detectTimestampUnit, createToDateConverter, createTimeScale, createIpScale, createWidthScale, calculateMaxArcRadius } from './src/scales/scaleFactory.js';
import { createForceSimulation, runUntilConverged, createComponentSeparationForce, createWeakComponentSeparationForce, createComponentCohesionForce, createHubCenteringForce, createComponentYForce, initializeNodePositions, calculateComponentCenters, findComponentHubIps, calculateIpDegrees, calculateConnectionStrength, createMutualHubAttractionForce } from './src/layout/forceSimulation.js';
import { applyLens1D, createLensXScale, createFisheyeScale, createHorizontalFisheyeScale, fisheyeDistort, createD3CartesianFisheye, createD3FisheyeXScale, createD3FisheyeYScale } from './src/scales/distortion.js';
import { computeIpSpans, createSpanData, renderRowLines, renderIpLabels, createLabelHoverHandler, createLabelMoveHandler, createLabelLeaveHandler, attachLabelHoverHandlers } from './src/rendering/rows.js';
import { createArcHoverHandler, createArcMoveHandler, createArcLeaveHandler, attachArcHandlers } from './src/rendering/arcInteractions.js';
import { loadAllMappings } from './src/mappings/loaders.js';
import { setupWindowResizeHandler as setupWindowResizeHandlerFromModule } from './src/interaction/resize.js';
// 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) {
// Reset to show all data when switching label modes
originalData = null; // Force re-storing of original data
visibleAttacks.clear(); // Clear visible attacks so render() re-initializes
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);
// Don't reset when disabled - keep the current fisheye effect
// User can use reset button to restore original positions
// 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);
// Don't reset when disabled - keep the current fisheye effect
// User can use reset button to restore original positions
// Update cursor on SVG
const svgEl = d3.select('#chart');
svgEl.style('cursor', fisheyeEnabled ? 'crosshair' : 'default');
updateLensingButtonState();
}
});
// Add reset button handler - set up after DOM is ready
// This will be called after the page loads
function setupResetButton() {
const resetFisheyeBtn = document.getElementById('resetFisheyeBtn');
if (resetFisheyeBtn) {
resetFisheyeBtn.addEventListener('click', () => {
console.log('Resetting fisheye to original positions');
if (resetFisheyeFn) {
resetFisheyeFn();
} else {
console.warn('Reset function not yet available. Please wait for visualization to load.');
}
// Also disable fisheye when resetting
fisheyeEnabled = false;
const svgEl = d3.select('#chart');
svgEl.style('cursor', 'default');
updateLensingButtonState();
});
}
}
// Set up reset button when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', setupResetButton);
} else {
setupResetButton();
}
let width = DEFAULT_WIDTH; // updated on render
let height = DEFAULT_HEIGHT; // 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
// 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;
// State for last rendered data (for resize re-render)
let lastRenderedData = null;
// Store original unfiltered data for legend filtering
let originalData = null;
// Flag to track if we're rendering filtered data (to prevent overwriting originalData)
let isRenderingFilteredData = false;
// Cleanup function for resize handler
let resizeCleanup = null;
// Initialize mappings, then try a default CSV load
(async function init() {
try {
const mappings = await loadAllMappings(canonicalizeName);
ipIdToAddr = mappings.ipIdToAddr;
ipMapLoaded = ipIdToAddr !== null && ipIdToAddr.size > 0;
attackIdToName = mappings.attackIdToName;
colorByAttack = mappings.colorByAttack;
rawColorByAttack = mappings.rawColorByAttack;
attackGroupIdToName = mappings.attackGroupIdToName;
colorByAttackGroup = mappings.colorByAttackGroup;
rawColorByAttackGroup = mappings.rawColorByAttackGroup;
if (ipMapLoaded) {
setStatus(statusEl, `IP map loaded (${ipIdToAddr.size} entries). Upload CSV to render.`);
}
} catch (err) {
console.warn('Mapping load failed:', err);
}
// Setup window resize handler
resizeCleanup = setupWindowResizeHandler();
// After maps are ready (or failed gracefully), try default CSV
tryLoadDefaultCsv();
})();
// Window resize handler for responsive visualization
function setupWindowResizeHandler() {
const handleResizeLogic = () => {
try {
// Only proceed if we have data to re-render
if (!lastRenderedData || lastRenderedData.length === 0) {
return;
}
console.log('Handling window resize, updating visualization dimensions');
// Store old dimensions for comparison
const oldWidth = width;
const oldHeight = height;
const containerEl = document.getElementById('chart-container');
if (!containerEl) return;
// Calculate new dimensions
const containerRect = containerEl.getBoundingClientRect();
const availableWidth = containerRect.width || 1200;
const viewportWidth = Math.max(availableWidth, 800);
const newWidth = viewportWidth - MARGIN.left - MARGIN.right;
// Skip if dimensions haven't changed significantly
if (Math.abs(newWidth - oldWidth) < 10) {
return;
}
console.log(`Resize: ${oldWidth}x${oldHeight} -> ${newWidth}x${height}`);
// Re-render with the new dimensions
// The render function will recalculate all scales and positions
render(lastRenderedData);
console.log('Window resize handling complete');
} catch (e) {
console.warn('Error during window resize:', e);
}
};
// Use module's resize handler with our custom logic
return setupWindowResizeHandlerFromModule({
debounceMs: 200,
onResize: handleResizeLogic
});
}
// 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 result = await parseCSVStream(file, (obj, idx) => {
const attackName = _decodeAttack(obj.attack);
const attackGroupName = _decodeAttackGroup(obj.attack_group, obj.attack);
const rec = {
idx: combinedData.length,
timestamp: toNumber(obj.timestamp),
length: toNumber(obj.length),
src_ip: _decodeIp(obj.src_ip),
dst_ip: _decodeIp(obj.dst_ip),
protocol: (obj.protocol || '').toUpperCase() || 'OTHER',
count: toNumber(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);
return true;
}
return false;
}, options);
return {
fileName: result.fileName,
totalRows: result.totalRows,
validRows: result.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) {
setStatus(statusEl,`Loading ${files[0].name} …`);
} else {
setStatus(statusEl,`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.');
setStatus(statusEl,'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) {
setStatus(statusEl,`Failed to load files. ${errors.length} error(s) occurred.`);
} else {
setStatus(statusEl,'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.`;
}
}
setStatus(statusEl,statusMsg);
// Reset legend state for new data to ensure proper filtering
originalData = null;
visibleAttacks.clear();
render(combinedData);
} catch (err) {
console.error(err);
setStatus(statusEl,'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;
setStatus(statusEl,`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));
setStatus(statusEl,`Custom IP map loaded (${rev.size} entries). Re-rendering…`);
if (lastRawCsvRows) {
// Reset legend state for updated mappings
originalData = null;
visibleAttacks.clear();
// rebuild to decode IP ids again
render(rebuildDataFromRawRows(lastRawCsvRows));
}
} catch (err) {
console.error(err);
setStatus(statusEl,'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;
setStatus(statusEl,`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));
setStatus(statusEl,`Custom event type map loaded (${rev.size} entries). Re-rendering…`);
if (lastRawCsvRows) {
// Reset legend state for updated mappings
originalData = null;
visibleAttacks.clear();
// rebuild to decode attack IDs again
render(rebuildDataFromRawRows(lastRawCsvRows));
}
} catch (err) {
console.error(err);
setStatus(statusEl,'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) {
setStatus(statusEl,'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) {
setStatus(statusEl,`Loaded default: set1_first90_minutes.csv (${data.length} valid rows, ${filteredRows} filtered due to missing IP mappings)`);
} else {
setStatus(statusEl,`Loaded default: set1_first90_minutes.csv (${data.length} rows)`);
}
render(data);
} catch (err) {
// ignore if file isn't present; keep waiting for upload
}
}
function clearChart() {
svg.selectAll('*').remove();
legendEl.innerHTML = '';
}
// Use d3 formatters consistently; we prefer UTC to match axis
// Function to filter data based on visible attacks and re-render
function applyAttackFilter() {
if (!originalData || originalData.length === 0) return;
// Filter data to only include visible attacks
const activeLabelKey = labelMode === 'attack_group' ? 'attack_group' : 'attack';
const filteredData = originalData.filter(d => {
const attackName = (d[activeLabelKey] || 'normal');
return visibleAttacks.has(attackName);
});
console.log(`Filtered data: ${filteredData.length} of ${originalData.length} records (${visibleAttacks.size} visible attacks)`);
// Set flag to prevent overwriting originalData during filtered render
isRenderingFilteredData = true;
// Re-render with filtered data (this will recompute the entire layout)
render(filteredData);
// Reset flag after render completes
isRenderingFilteredData = false;
}
function buildLegend(items, colorFn) {
createLegend(legendEl, items, colorFn, visibleAttacks, {
onToggle: (attackName) => {
if (visibleAttacks.has(attackName)) {
visibleAttacks.delete(attackName);
} else {
visibleAttacks.add(attackName);
}
updateLegendUI(legendEl, visibleAttacks);
applyAttackFilter(); // Recompute layout with filtered data
},
onIsolate: (attackName) => {
isolateLegendAttack(attackName, visibleAttacks, legendEl);
updateLegendUI(legendEl, visibleAttacks);
applyAttackFilter(); // Recompute layout with filtered data
}
});
}
function render(data) {
// Store data for resize re-render
lastRenderedData = data;
// Store original data for filtering (only if this is truly new data, not filtered data)
// Don't overwrite originalData if we're rendering filtered data
if (!isRenderingFilteredData && (!originalData || visibleAttacks.size === 0)) {
originalData = data;
console.log('Stored original data:', originalData.length, 'records');
}
// 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:
// Detect timestamp unit and create converter using factory
const timeInfo = detectTimestampUnit(tsMin, tsMax);
const { unit, looksAbsolute, unitMs, unitSuffix, base } = timeInfo;
const toDate = createToDateConverter(timeInfo);
console.log('Timestamp debug:', {
tsMin,
tsMax,
looksAbsolute,
inferredUnit: unit,
base,
sampleTimestamps: data.slice(0, 5).map(d => d.timestamp)
});
// 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 { simNodes, simLinks, yMap, components, ipToComponent } = nodeData;
// Create simulation using the factory function
const simulation = createForceSimulation(d3, simNodes, simLinks);
simulation._components = components;
simulation._ipToComponent = ipToComponent;
// 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';
// Build attacks list from ORIGINAL data (not filtered) so legend always shows all attacks
const originalLinks = originalData ? computeLinks(originalData) : links;
const attacks = Array.from(new Set(originalLinks.map(l => l[activeLabelKey] || 'normal'))).sort();
// Only initialize visibleAttacks on first render or when switching label modes
// This preserves the user's filter selections across re-renders
if (visibleAttacks.size === 0 || currentLabelMode !== labelMode) {
visibleAttacks = new Set(attacks);
console.log('Initialized visibleAttacks with', attacks.length, '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
// 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 + INNER_HEIGHT + 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 ? INNER_HEIGHT / allIps.length : INNER_HEIGHT;
const maxArcRadius = (maxIpIndexDist * estimatedStep) / 2;
const svgWidth = width + MARGIN.left + MARGIN.right;
const xStart = MARGIN.left;
const xEnd = svgWidth - MARGIN.right - maxArcRadius;
const x = createTimeScale(d3, xMinDate, xMaxDate, 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;
}
// Track the current xEnd value (will be updated after arc radius calculation)
let currentXEnd = xEnd;
// Lens-aware x scale function using imported factory
const xScaleLens = createLensXScale({
xScale: x,
tsMin,
tsMax,
xStart,
xEnd: xEnd, // Use initial xEnd, will be updated via getter
toDate,
getIsLensing: () => isLensing,
getLensCenter: () => lensCenter,
getLensingMul: () => lensingMul,
getHorizontalFisheyeScale: () => horizontalFisheyeScale,
getFisheyeEnabled: () => fisheyeEnabled,
getXEnd: () => currentXEnd // Dynamic getter for updated xEnd
});
// Use allIps for the y scale to ensure all IPs referenced in arcs are included
const y = createIpScale(d3, allIps, MARGIN.top, MARGIN.top + INNER_HEIGHT, 0.5);
console.log('Y-scale debug:', {
domain: allIps,
domainLength: allIps.length,
sampleYValues: allIps.slice(0, 5).map(ip => ({ ip, y: y(ip) }))
});
// Store evenly distributed positions after auto-fit animation
let evenlyDistributedYPositions = null;
// Y scale function (matching main.js: no vertical lensing, just return y position)
function yScaleLens(ip) {
// If we have evenly distributed positions (after animation), use those
if (evenlyDistributedYPositions && evenlyDistributedYPositions.has(ip)) {
return evenlyDistributedYPositions.get(ip);
}
// Otherwise use the base y scale (matching main.js: no vertical lensing)
return y(ip);
}
// Width scale by aggregated link count (log scale like the React version)
const minLinkCount = d3.min(links, d => Math.max(1, d.count)) || 1;
const maxLinkCount = d3.max(links, d => Math.max(1, d.count)) || 1;
const widthScale = createWidthScale(d3, minLinkCount, maxLinkCount);
// Keep lengthScale (unused) for completeness
const maxLen = d3.max(data, d => d.length || 0) || 0;
const lengthScale = d3.scaleLinear().domain([0, Math.max(1, maxLen)]).range([0.6, 2.2]);
const colorForAttack = (name) => {
if (labelMode === 'attack_group') return _lookupAttackGroupColor(name) || _lookupAttackColor(name) || DEFAULT_COLOR;
return _lookupAttackColor(name) || _lookupAttackGroupColor(name) || DEFAULT_COLOR;
};
// Clear
svg.selectAll('*').remove();
// Axes — render to sticky top SVG
const axisScale = d3.scaleTime()
.domain([xMinDate, xMaxDate])
.range([0, xEnd - xStart]);
const utcTick = d3.utcFormat('%Y-%m-%d %H:%M');
const xAxis = d3.axisTop(axisScale).ticks(looksAbsolute ? 7 : 7).tickFormat(d => {
if (looksAbsolute) return utcTick(d);
const relUnits = Math.round((d.getTime()) / unitMs);
return `t=${relUnits}${unitSuffix}`;
});
// Create axis SVG that matches the viewport width
const axisSvg = d3.select('#axis-top')
.attr('width', width + MARGIN.left + MARGIN.right)
.attr('height', 36);
axisSvg.selectAll('*').remove();
// Create axis group
const axisGroup = axisSvg.append('g')
.attr('transform', `translate(${xStart}, 28)`)
.call(xAxis);
// Utility for safe gradient IDs per link
// Use original IP strings (sourceIp/targetIp) for gradient IDs
const gradIdForLink = (d) => gradientIdForLink(d, sanitizeId);
// Row labels and span lines: draw per-IP line only from first to last activity
const rows = svg.append('g');
// compute first/last minute per IP based on aggregated links
const ipSpans = computeIpSpans(links);
// Use allIps to ensure all IPs have row lines, matching the labels and arcs
const spanData = createSpanData(allIps, ipSpans);
renderRowLines(rows, spanData, MARGIN.left, yScaleLens);
// Build legend (attack types)
buildLegend(attacks, colorForAttack);
// Create node objects for each IP with x/y properties (matching main.js structure)
// This allows links to reference node objects with x/y coordinates
const ipToNode = new Map();
allIps.forEach(ip => {
const node = { name: ip, x: 0, y: 0 };
ipToNode.set(ip, node);
});
// Transform links to have source/target as node objects (matching main.js)
// Keep original IP strings for gradient/display purposes
const linksWithNodes = links.map(link => {
const sourceNode = ipToNode.get(link.source);
const targetNode = ipToNode.get(link.target);
if (!sourceNode || !targetNode) {
console.warn('Missing node for link:', link);
return null;
}
return {
...link,
// Preserve original IP strings for gradient IDs and other uses
sourceIp: link.source,
targetIp: link.target,
// Store node objects separately
sourceNode: sourceNode,
targetNode: targetNode,
// For linkArc function, use source/target as node objects (will be set per-arc)
source: sourceNode,
target: targetNode
};
}).filter(l => l !== null);
// Function to update node positions from scales (called during render/update)
// Match main.js: nodes maintain their x/y positions and xConnected
function updateNodePositions() {
// X position for all labels: first time tick in the timeline
const firstTimeTickX = xScaleLens(tsMin);
allIps.forEach(ip => {
const node = ipToNode.get(ip);
if (node) {
// Y position comes from the scale (matching main.js n.y)
node.y = yScaleLens(ip);
// X position: first time tick in the timeline (keep current y position logic)
node.xConnected = firstTimeTickX;
}
});
}
// Initialize node positions (matching main.js where nodes have n.y and xConnected)
updateNodePositions();
// Create labels for all IPs to ensure alignment with arcs
// Match main.js: labels positioned at first arc time (xConnected) initially
// Must be created after nodes are set up and positions are calculated
const ipLabels = renderIpLabels(rows, allIps, ipToNode, MARGIN.left, yScaleLens);
// Create per-link gradients from grey (source) to attack color (destination)
const defs = svg.append('defs');
const gradients = defs.selectAll('linearGradient')
.data(linksWithNodes)
.join('linearGradient')
.attr('id', d => gradIdForLink(d))
.attr('gradientUnits', 'userSpaceOnUse')
.attr('x1', d => xScaleLens(d.minute))
.attr('x2', d => xScaleLens(d.minute))
.attr('y1', d => yScaleLens(d.sourceNode.name))
.attr('y2', d => yScaleLens(d.targetNode.name));
gradients.each(function(d) {
const g = d3.select(this);
// Reset stops to avoid duplicates on re-renders
g.selectAll('stop').remove();
g.append('stop')
.attr('offset', '0%')
.attr('stop-color', NEUTRAL_GREY);
g.append('stop')
.attr('offset', '100%')
.attr('stop-color', colorForAttack((labelMode==='attack_group'? d.attack_group : d.attack) || 'normal'));
});
// Draw arcs using linkArc function (matching main.js)
const arcs = svg.append('g');
const arcPaths = arcs.selectAll('path')
.data(linksWithNodes)
.join('path')
.attr('class', 'arc')
.attr('data-attack', d => (labelMode === 'attack_group' ? d.attack_group : d.attack) || 'normal')
.attr('stroke', d => `url(#${gradIdForLink(d)})`)
.attr('stroke-width', d => widthScale(Math.max(1, d.count)))
.attr('d', d => {
// Update node positions for this link (matching main.js pattern)
// In main.js, nodes have x/y from force layout; here we compute from scales