/** * Graph visualization module for DNSRecon * Handles network graph rendering using vis.js */ class GraphManager { constructor(containerId) { this.container = document.getElementById(containerId); this.network = null; this.nodes = new vis.DataSet(); this.edges = new vis.DataSet(); this.isInitialized = false; this.currentLayout = 'physics'; this.nodeInfoPopup = null; this.options = { nodes: { shape: 'dot', size: 15, font: { size: 12, color: '#c7c7c7', face: 'Roboto Mono, monospace', background: 'rgba(26, 26, 26, 0.9)', strokeWidth: 2, strokeColor: '#000000' }, borderWidth: 2, borderColor: '#444', scaling: { min: 10, max: 30, label: { enabled: true, min: 8, max: 16 } }, chosen: { node: (values, id, selected, hovering) => { values.borderColor = '#00ff41'; values.borderWidth = 3; } } }, edges: { width: 2, color: { color: '#555', highlight: '#00ff41', hover: '#ff9900', inherit: false }, font: { size: 10, color: '#999', face: 'Roboto Mono, monospace', background: 'rgba(26, 26, 26, 0.8)', strokeWidth: 1, strokeColor: '#000000' }, arrows: { to: { enabled: true, scaleFactor: 1, type: 'arrow' } }, smooth: { enabled: true, type: 'dynamic', roundness: 0.6 }, chosen: { edge: (values, id, selected, hovering) => { values.color = '#00ff41'; values.width = 4; } } }, physics: { enabled: true, stabilization: { enabled: true, iterations: 150, updateInterval: 50 }, barnesHut: { gravitationalConstant: -3000, centralGravity: 0.4, springLength: 120, springConstant: 0.05, damping: 0.1, avoidOverlap: 0.2 }, maxVelocity: 30, minVelocity: 0.1, solver: 'barnesHut', timestep: 0.4, adaptiveTimestep: true }, interaction: { hover: true, hoverConnectedEdges: true, selectConnectedEdges: true, tooltipDelay: 300, hideEdgesOnDrag: false, hideNodesOnDrag: false, zoomView: true, dragView: true, multiselect: true }, layout: { improvedLayout: true, randomSeed: 2 } }; this.createNodeInfoPopup(); } /** * Create floating node info popup */ createNodeInfoPopup() { this.nodeInfoPopup = document.createElement('div'); this.nodeInfoPopup.className = 'node-info-popup'; this.nodeInfoPopup.style.display = 'none'; document.body.appendChild(this.nodeInfoPopup); } /** * Initialize the network graph */ initialize() { if (this.isInitialized) { return; } try { const data = { nodes: this.nodes, edges: this.edges }; this.network = new vis.Network(this.container, data, this.options); this.setupNetworkEvents(); this.isInitialized = true; // Hide placeholder const placeholder = this.container.querySelector('.graph-placeholder'); if (placeholder) { placeholder.style.display = 'none'; } // Add graph controls this.addGraphControls(); console.log('Graph initialized successfully'); } catch (error) { console.error('Failed to initialize graph:', error); this.showError('Failed to initialize visualization'); } } /** * Add interactive graph controls */ addGraphControls() { const controlsContainer = document.createElement('div'); controlsContainer.className = 'graph-controls'; controlsContainer.innerHTML = ` `; this.container.appendChild(controlsContainer); // Add control event listeners document.getElementById('graph-fit').addEventListener('click', () => this.fitView()); document.getElementById('graph-physics').addEventListener('click', () => this.togglePhysics()); document.getElementById('graph-cluster').addEventListener('click', () => this.toggleClustering()); } /** * Setup network event handlers */ setupNetworkEvents() { if (!this.network) return; // Node click event with details this.network.on('click', (params) => { if (params.nodes.length > 0) { const nodeId = params.nodes[0]; if (this.network.isCluster(nodeId)) { this.network.openCluster(nodeId); } else { const node = this.nodes.get(nodeId); if (node) { this.showNodeDetails(node); this.highlightNodeConnections(nodeId); } } } else { this.clearHighlights(); } }); // Hover events this.network.on('hoverNode', (params) => { const nodeId = params.node; const node = this.nodes.get(nodeId); if (node) { this.highlightConnectedNodes(nodeId, true); } }); // FIX: Comment out the problematic context menu handler this.network.on('oncontext', (params) => { params.event.preventDefault(); // if (params.nodes.length > 0) { // this.showNodeContextMenu(params.pointer.DOM, params.nodes[0]); // } }); // Stabilization events with progress this.network.on('stabilizationProgress', (params) => { const progress = params.iterations / params.total; this.updateStabilizationProgress(progress); }); this.network.on('stabilizationIterationsDone', () => { this.onStabilizationComplete(); }); // Selection events this.network.on('select', (params) => { console.log('Selected nodes:', params.nodes); console.log('Selected edges:', params.edges); }); } /** * @param {Object} graphData - Graph data from backend */ updateGraph(graphData) { if (!graphData || !graphData.nodes || !graphData.edges) { console.warn('Invalid graph data received'); return; } try { // Initialize if not already done if (!this.isInitialized) { this.initialize(); } const largeEntityMap = new Map(); graphData.nodes.forEach(node => { if (node.type === 'large_entity' && node.attributes && Array.isArray(node.attributes.nodes)) { node.attributes.nodes.forEach(nodeId => { largeEntityMap.set(nodeId, node.id); }); } }); const processedNodes = graphData.nodes.map(node => { const processed = this.processNode(node); if (largeEntityMap.has(node.id)) { processed.hidden = true; } return processed; }); const mergedEdges = {}; graphData.edges.forEach(edge => { const fromNode = largeEntityMap.has(edge.from) ? largeEntityMap.get(edge.from) : edge.from; const toNode = largeEntityMap.has(edge.to) ? largeEntityMap.get(edge.to) : edge.to; const mergeKey = `${fromNode}-${toNode}-${edge.label}`; if (!mergedEdges[mergeKey]) { mergedEdges[mergeKey] = { ...edge, from: fromNode, to: toNode, count: 0, confidence_score: 0 }; } mergedEdges[mergeKey].count++; if (edge.confidence_score > mergedEdges[mergeKey].confidence_score) { mergedEdges[mergeKey].confidence_score = edge.confidence_score; } }); const processedEdges = Object.values(mergedEdges).map(edge => { const processed = this.processEdge(edge); if (edge.count > 1) { processed.label = `${edge.label} (${edge.count})`; } return processed; }); // Update datasets with animation const existingNodeIds = this.nodes.getIds(); const existingEdgeIds = this.edges.getIds(); // Add new nodes with fade-in animation const newNodes = processedNodes.filter(node => !existingNodeIds.includes(node.id)); const newEdges = processedEdges.filter(edge => !existingEdgeIds.includes(edge.id)); // Update existing data this.nodes.update(processedNodes); this.edges.update(processedEdges); // Highlight new additions briefly if (newNodes.length > 0 || newEdges.length > 0) { setTimeout(() => this.highlightNewElements(newNodes, newEdges), 100); } // Auto-fit view for small graphs or first update if (processedNodes.length <= 10 || existingNodeIds.length === 0) { setTimeout(() => this.fitView(), 800); } console.log(`Graph updated: ${processedNodes.length} nodes, ${processedEdges.length} edges (${newNodes.length} new nodes, ${newEdges.length} new edges)`); } catch (error) { console.error('Failed to update graph:', error); this.showError('Failed to update visualization'); } } /** * Process node data with styling and metadata * @param {Object} node - Raw node data * @returns {Object} Processed node data */ processNode(node) { const processedNode = { id: node.id, label: this.formatNodeLabel(node.id, node.type), color: this.getNodeColor(node.type), size: this.getNodeSize(node.type), borderColor: this.getNodeBorderColor(node.type), shape: this.getNodeShape(node.type), attributes: node.attributes || {}, description: node.description || '', metadata: node.metadata || {}, type: node.type, incoming_edges: node.incoming_edges || [], outgoing_edges: node.outgoing_edges || [] }; // Add confidence-based styling if (node.confidence) { processedNode.borderWidth = Math.max(2, Math.floor(node.confidence * 5)); } // Style based on certificate validity if (node.type === 'domain') { if (node.attributes && node.attributes.certificates && node.attributes.certificates.has_valid_cert === false) { processedNode.color = { background: '#888888', border: '#666666' }; } } // Handle merged correlation objects (similar to large entities) if (node.type === 'correlation_object') { const metadata = node.metadata || {}; const values = metadata.values || []; const mergeCount = metadata.merge_count || 1; if (mergeCount > 1) { // Display as merged correlation container processedNode.label = `Correlations (${mergeCount})`; processedNode.title = `Merged correlation container with ${mergeCount} values: ${values.slice(0, 3).join(', ')}${values.length > 3 ? '...' : ''}`; processedNode.borderWidth = 3; // Thicker border for merged nodes } else { // Single correlation value const value = Array.isArray(values) && values.length > 0 ? values[0] : (metadata.value || 'Unknown'); const displayValue = typeof value === 'string' && value.length > 20 ? value.substring(0, 17) + '...' : value; processedNode.label = `Corr: ${displayValue}`; processedNode.title = `Correlation: ${value}`; } } return processedNode; } /** * Process edge data with styling and metadata * @param {Object} edge - Raw edge data * @returns {Object} Processed edge data */ processEdge(edge) { const confidence = edge.confidence_score || 0; const processedEdge = { id: `${edge.from}-${edge.to}`, from: edge.from, to: edge.to, label: this.formatEdgeLabel(edge.label, confidence), title: this.createEdgeTooltip(edge), width: this.getEdgeWidth(confidence), color: this.getEdgeColor(confidence), dashes: confidence < 0.6 ? [5, 5] : false, metadata: { relationship_type: edge.label, confidence_score: confidence, source_provider: edge.source_provider, discovery_timestamp: edge.discovery_timestamp } }; return processedEdge; } /** * Format node label for display * @param {string} nodeId - Node identifier * @param {string} nodeType - Node type * @returns {string} Formatted label */ formatNodeLabel(nodeId, nodeType) { if (typeof nodeId !== 'string') return ''; if (nodeId.length > 20) { return nodeId.substring(0, 17) + '...'; } return nodeId; } /** * Format edge label for display * @param {string} relationshipType - Type of relationship * @param {number} confidence - Confidence score * @returns {string} Formatted label */ formatEdgeLabel(relationshipType, confidence) { if (!relationshipType) return ''; const confidenceText = confidence >= 0.8 ? '●' : confidence >= 0.6 ? '◐' : '○'; return `${relationshipType} ${confidenceText}`; } /** * Get node color based on type * @param {string} nodeType - Node type * @returns {string} Color value */ getNodeColor(nodeType) { const colors = { 'domain': '#00ff41', // Green 'ip': '#ff9900', // Amber 'asn': '#00aaff', // Blue 'large_entity': '#ff6b6b', // Red for large entities 'correlation_object': '#9620c0ff' }; return colors[nodeType] || '#ffffff'; } /** * Get node border color based on type * @param {string} nodeType - Node type * @returns {string} Border color value */ getNodeBorderColor(nodeType) { const borderColors = { 'domain': '#00aa2e', 'ip': '#cc7700', 'asn': '#0088cc', 'correlation_object': '#c235c9ff' }; return borderColors[nodeType] || '#666666'; } /** * Get node size based on type * @param {string} nodeType - Node type * @returns {number} Node size */ getNodeSize(nodeType) { const sizes = { 'domain': 12, 'ip': 14, 'asn': 16, 'correlation_object': 8, 'large_entity': 5 }; return sizes[nodeType] || 12; } /** * Get node shape based on type * @param {string} nodeType - Node type * @returns {string} Shape name */ getNodeShape(nodeType) { const shapes = { 'domain': 'dot', 'ip': 'square', 'asn': 'triangle', 'correlation_object': 'hexagon', 'large_entity': 'database' }; return shapes[nodeType] || 'dot'; } /** * Get edge color based on confidence * @param {number} confidence - Confidence score * @returns {string} Edge color */ getEdgeColor(confidence) { if (confidence >= 0.8) { return '#00ff41'; // High confidence - green } else if (confidence >= 0.6) { return '#ff9900'; // Medium confidence - amber } else { return '#666666'; // Low confidence - gray } } /** * Get edge width based on confidence * @param {number} confidence - Confidence score * @returns {number} Edge width */ getEdgeWidth(confidence) { if (confidence >= 0.8) { return 3; } else if (confidence >= 0.6) { return 2; } else { return 1; } } /** * Create edge tooltip with correct provider information * @param {Object} edge - Edge data * @returns {string} HTML tooltip content */ createEdgeTooltip(edge) { let tooltip = `