admin / Synapse-Sonar
publicAttack Surface Simulation
Synapse-Sonar / synapse-sonar / components / NetworkGraph.tsx
23288 B · main
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 | "use client"; import { useCallback, useEffect, useMemo, useRef, useState, } from "react"; import dynamic from "next/dynamic"; // react-force-graph touches `window`, so load it client-side only. const ForceGraph2D = dynamic(() => import("react-force-graph-2d"), { ssr: false, }); // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- type Severity = "LOW" | "MEDIUM" | "HIGH" | "CRITICAL"; interface Vulnerability { cveId: string; cvssScore: number; severity: Severity; title?: string | null; } interface GraphNode { id: string; hostname: string; ipAddress: string; relatedIps: string[]; assetType: string; criticality: string; isRogue: boolean; offline: boolean; openPorts: number[]; vulnerabilities: Vulnerability[]; criticalCount: number; // injected by force engine x?: number; y?: number; } interface GraphLink { id: string; source: string | GraphNode; target: string | GraphNode; protocol?: string | null; port?: number | null; volume: number; lastSeenAt: string; } interface GraphData { nodes: GraphNode[]; links: GraphLink[]; netscanEnabled: boolean; canEdit: boolean; } // Synapse IronNode palette const COLORS = { bg: "#05080f", iron: "#94a3b8", ironLight: "#f8fafc", cyan: "#06b6d4", blue: "#3b82f6", violet: "#8b5cf6", rogue: "#f43f5e", crit: "#ef4444", offline: "#64748b", }; const CRITICALITY_LABEL: Record<string, string> = { TIER_0_CROWN_JEWEL: "Tier 0 · Crown Jewel", TIER_1_CRITICAL: "Tier 1 · Critical", TIER_2_STANDARD: "Tier 2 · Standard", TIER_3_LOW: "Tier 3 · Low", }; // --------------------------------------------------------------------------- // Component // --------------------------------------------------------------------------- export default function NetworkGraph() { const fgRef = useRef<any>(null); const containerRef = useRef<HTMLDivElement>(null); const [data, setData] = useState<GraphData>({ nodes: [], links: [], netscanEnabled: false, canEdit: false, }); const [dims, setDims] = useState({ width: 800, height: 600 }); const [hoverNode, setHoverNode] = useState<GraphNode | null>(null); const [pointer, setPointer] = useState({ x: 0, y: 0 }); const [selected, setSelected] = useState<GraphNode | null>(null); // Blast radius highlight state const [blastNodes, setBlastNodes] = useState<Set<string>>(new Set()); const [blastEdges, setBlastEdges] = useState<Set<string>>(new Set()); const [simulating, setSimulating] = useState(false); // --- Load + periodically refresh tenant-scoped topology --- // Existing nodes keep their (pinned) positions; only genuinely new nodes are // added so the layout places them. We skip state updates when nothing changed // so the graph stays static and doesn't reheat needlessly. const sigRef = useRef(""); const loadGraph = useCallback(async () => { try { const res = await fetch("/api/graph"); if (!res.ok) return; const incoming: GraphData = await res.json(); const sig = JSON.stringify({ n: incoming.nodes.map((n) => [ n.id, n.offline, n.criticalCount, n.isRogue, n.hostname, (n.relatedIps || []).length, (n.openPorts || []).length, ]), l: incoming.links.map((l: any) => [l.id, l.volume]), ne: incoming.netscanEnabled, ce: incoming.canEdit, }); if (sig === sigRef.current) return; // nothing changed — keep it static sigRef.current = sig; setData((prev) => { const prevNodes = new Map(prev.nodes.map((n) => [n.id, n as any])); const nodes = incoming.nodes.map((inc) => { const ex = prevNodes.get(inc.id); if (ex) { // Refresh data fields in place; the server never sends coordinates, // so x/y/fx/fy (position + pin) are preserved. Object.assign(ex, inc); return ex; } return inc; // new node — unpinned; the engine lays it out, then pins }); const prevLinks = new Map(prev.links.map((l: any) => [l.id, l])); const links = incoming.links.map((inc: any) => { const ex = prevLinks.get(inc.id); if (ex) { // Keep the resolved source/target objects; refresh mutable fields. ex.volume = inc.volume; ex.lastSeenAt = inc.lastSeenAt; ex.protocol = inc.protocol; ex.port = inc.port; return ex; } return inc; }); return { ...incoming, nodes, links }; }); } catch { /* transient fetch error — try again next tick */ } }, []); useEffect(() => { loadGraph(); const t = setInterval(loadGraph, 20000); return () => clearInterval(t); }, [loadGraph]); // --- Responsive canvas sizing --- useEffect(() => { if (!containerRef.current) return; const ro = new ResizeObserver((entries) => { const { width, height } = entries[0].contentRect; setDims({ width, height }); }); ro.observe(containerRef.current); return () => ro.disconnect(); }, []); const clearBlast = useCallback(() => { setBlastNodes(new Set()); setBlastEdges(new Set()); }, []); // --- Blast radius simulation --- const runBlastRadius = useCallback(async (assetId: string) => { setSimulating(true); try { const res = await fetch(`/api/assets/${assetId}/blast-radius?hops=2`); if (!res.ok) throw new Error("simulation failed"); const json = await res.json(); setBlastNodes(new Set([assetId, ...json.reachable.map((r: any) => r.assetId)])); setBlastEdges(new Set(json.pathEdgeIds)); } catch { clearBlast(); } finally { setSimulating(false); } }, [clearBlast]); // ---- Manually toggle a node online/offline ---- const [toggling, setToggling] = useState(false); const toggleOffline = useCallback(async (assetId: string, next: boolean) => { setToggling(true); try { const res = await fetch(`/api/assets/${assetId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ offline: next }), }); if (!res.ok) return; setData((prev) => ({ ...prev, nodes: prev.nodes.map((n) => (n.id === assetId ? { ...n, offline: next } : n)), })); setSelected((prev) => (prev && prev.id === assetId ? { ...prev, offline: next } : prev)); } finally { setToggling(false); } }, []); // ---- Node painting ---- const paintNode = useCallback( (node: GraphNode, ctx: CanvasRenderingContext2D, scale: number) => { const r = 5; const inBlast = blastNodes.has(node.id); const isCompromised = selected?.id === node.id && blastNodes.size > 0; const isOffline = node.offline; // glow + body ctx.save(); if (isOffline) { // Manually offline: dimmed, no glow, dashed grey outline. ctx.globalAlpha = 0.45; ctx.beginPath(); ctx.arc(node.x!, node.y!, r, 0, 2 * Math.PI); ctx.fillStyle = "#1e293b"; ctx.fill(); ctx.setLineDash([2 / scale, 2 / scale]); ctx.lineWidth = 1.2 / scale; ctx.strokeStyle = COLORS.offline; ctx.stroke(); ctx.setLineDash([]); } else { ctx.shadowBlur = inBlast ? 22 : 12; ctx.shadowColor = node.isRogue ? COLORS.rogue : inBlast ? COLORS.violet : node.criticalCount > 0 ? COLORS.crit : COLORS.cyan; ctx.beginPath(); ctx.arc(node.x!, node.y!, r, 0, 2 * Math.PI); ctx.fillStyle = isCompromised ? COLORS.crit : inBlast ? COLORS.violet : node.isRogue ? COLORS.rogue : "#0f172a"; ctx.fill(); ctx.lineWidth = 1.5 / scale; ctx.strokeStyle = inBlast ? COLORS.violet : COLORS.iron; ctx.stroke(); } ctx.restore(); // critical CVE ring (hidden while offline) if (node.criticalCount > 0 && !isOffline) { ctx.beginPath(); ctx.arc(node.x!, node.y!, r + 2.5, 0, 2 * Math.PI); ctx.strokeStyle = COLORS.crit; ctx.lineWidth = 1 / scale; ctx.stroke(); } // hostname label when zoomed in if (scale > 1.6) { ctx.font = `${3.2}px Inter, sans-serif`; ctx.fillStyle = isOffline ? COLORS.offline : COLORS.iron; ctx.textAlign = "center"; ctx.fillText(node.hostname + (isOffline ? " (offline)" : ""), node.x!, node.y! + r + 4); } }, [blastNodes, selected] ); // IDs of nodes currently marked offline (for edge styling). const offlineIds = useMemo( () => new Set(data.nodes.filter((n) => n.offline).map((n) => n.id)), [data.nodes] ); const linkTouchesOffline = useCallback( (link: GraphLink) => { const src = typeof link.source === "object" ? link.source.id : link.source; const tgt = typeof link.target === "object" ? link.target.id : link.target; return offlineIds.has(src) || offlineIds.has(tgt); }, [offlineIds] ); // ---- Link styling: offline = dim red; blast path = violet; else cyan ---- const linkColor = useCallback( (link: GraphLink) => { if (linkTouchesOffline(link)) return "rgba(239,68,68,0.30)"; // dim red return blastEdges.has(link.id) ? COLORS.violet : "rgba(6,182,212,0.35)"; }, [blastEdges, linkTouchesOffline] ); const linkWidth = useCallback( (link: GraphLink) => { const base = Math.min(1 + Math.log10(Math.max(link.volume, 1)) / 2, 4); if (linkTouchesOffline(link)) return Math.max(base * 0.6, 0.6); return blastEdges.has(link.id) ? base + 1.5 : base; }, [blastEdges, linkTouchesOffline] ); // Directional moving particles — none on offline edges (no live traffic). const linkParticles = useCallback( (link: GraphLink) => linkTouchesOffline(link) ? 0 : Math.min(1 + Math.floor(Math.log10(Math.max(link.volume, 1))), 4), [linkTouchesOffline] ); const linkParticleSpeed = useCallback( (link: GraphLink) => 0.004 + Math.min(Math.log10(Math.max(link.volume, 1)) / 1000, 0.01), [] ); const graphData = useMemo(() => data, [data]); return ( <div ref={containerRef} className="relative h-full w-full overflow-hidden bg-[#05080f]"> {/* Blast-radius control banner */} {blastNodes.size > 0 && ( <div className="absolute left-4 top-4 z-20 flex items-center gap-3 rounded-lg border border-violet-500/40 bg-[#1e293b]/80 px-4 py-2 backdrop-blur"> <span className="h-2 w-2 animate-pulse rounded-full bg-violet-500 shadow-[0_0_10px_#8b5cf6]" /> <span className="font-mono text-xs text-violet-200"> Blast radius: {blastNodes.size - 1} downstream assets · 2 hops </span> <button onClick={clearBlast} className="text-xs text-slate-400 hover:text-slate-100" > Clear </button> </div> )} <ForceGraph2D ref={fgRef} width={dims.width} height={dims.height} graphData={graphData as any} backgroundColor={COLORS.bg} nodeRelSize={5} // Keep redrawing after the layout cools so edge particles keep flowing // even though the nodes are frozen in place. autoPauseRedraw={false} // Once the initial layout settles, pin every node so it stays static. onEngineStop={() => { for (const n of data.nodes as any[]) { if (n.x != null) { n.fx = n.x; n.fy = n.y; } } }} // Dragging repositions a node; keep it pinned where the user drops it. onNodeDragEnd={(node: any) => { node.fx = node.x; node.fy = node.y; }} nodeCanvasObject={paintNode as any} nodePointerAreaPaint={(node: any, color: string, ctx: CanvasRenderingContext2D) => { ctx.fillStyle = color; ctx.beginPath(); ctx.arc(node.x, node.y, 7, 0, 2 * Math.PI); ctx.fill(); }} linkColor={linkColor as any} linkWidth={linkWidth as any} linkDirectionalParticles={linkParticles as any} linkDirectionalParticleSpeed={linkParticleSpeed as any} linkDirectionalParticleWidth={2} linkDirectionalParticleColor={() => COLORS.blue} onNodeHover={(node: any) => { setHoverNode(node ?? null); if (containerRef.current) containerRef.current.style.cursor = node ? "pointer" : "grab"; }} onNodeClick={(node: any) => { setSelected(node); clearBlast(); }} onBackgroundClick={() => { setSelected(null); clearBlast(); }} onRenderFramePre={(ctx: CanvasRenderingContext2D) => { // track pointer in screen space for the tooltip // (handled via DOM event below) }} /> {/* DOM mouse tracker for tooltip positioning */} <div className="pointer-events-none absolute inset-0" onMouseMove={(e) => { const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect(); setPointer({ x: e.clientX - rect.left, y: e.clientY - rect.top }); }} /> {/* ---- Hover micro-tooltip (basic info only, destroyed on mouse-out) ---- */} {hoverNode && ( <div className="pointer-events-none absolute z-30 w-64 rounded-lg border border-slate-600/60 bg-[#0f172a]/90 p-3 shadow-2xl backdrop-blur-sm" style={{ left: Math.min(pointer.x + 14, dims.width - 270), top: Math.min(pointer.y + 14, dims.height - 150), }} > <div className="flex items-center justify-between"> <span className="truncate text-sm font-semibold text-slate-100"> {hoverNode.hostname} </span> {hoverNode.offline ? ( <span className="rounded bg-slate-500/20 px-1.5 py-0.5 text-[10px] font-bold text-slate-300"> OFFLINE </span> ) : ( hoverNode.isRogue && ( <span className="rounded bg-rose-500/20 px-1.5 py-0.5 text-[10px] font-bold text-rose-300"> ROGUE </span> ) )} </div> <div className="mt-1 font-mono text-xs text-cyan-300">{hoverNode.ipAddress}</div> {hoverNode.relatedIps?.length > 0 && ( <div className="mt-1 text-[10px] leading-snug text-slate-500"> <span className="text-slate-400">Docker / related:</span>{" "} <span className="font-mono text-slate-300"> {hoverNode.relatedIps.join(", ")} </span> </div> )} <div className="mt-1.5 text-[11px] text-slate-400"> {CRITICALITY_LABEL[hoverNode.criticality] ?? hoverNode.criticality} </div> {hoverNode.criticalCount > 0 ? ( <div className="mt-2 inline-flex items-center gap-1 rounded bg-red-500/15 px-2 py-1 text-[11px] font-medium text-red-300"> ⚠️ {hoverNode.criticalCount} Critical CVE {hoverNode.criticalCount > 1 ? "s" : ""} </div> ) : ( <div className="mt-2 inline-flex items-center gap-1 rounded bg-emerald-500/10 px-2 py-1 text-[11px] text-emerald-300"> ✓ No critical findings </div> )} </div> )} {/* ---- Deep-dive slide-out sidebar (click) ---- */} <DeepDiveSidebar node={selected} netscanEnabled={data.netscanEnabled} simulating={simulating} canEdit={data.canEdit} toggling={toggling} onToggleOffline={(next) => selected && toggleOffline(selected.id, next)} onClose={() => { setSelected(null); clearBlast(); }} onSimulate={() => selected && runBlastRadius(selected.id)} /> </div> ); } // --------------------------------------------------------------------------- // Deep-Dive Sidebar // --------------------------------------------------------------------------- function DeepDiveSidebar({ node, netscanEnabled, simulating, canEdit, toggling, onToggleOffline, onClose, onSimulate, }: { node: GraphNode | null; netscanEnabled: boolean; simulating: boolean; canEdit: boolean; toggling: boolean; onToggleOffline: (next: boolean) => void; onClose: () => void; onSimulate: () => void; }) { const open = Boolean(node); return ( <div className={`absolute right-0 top-0 z-40 h-full w-[380px] transform border-l border-slate-700/60 bg-[#0f172a]/95 backdrop-blur-md transition-transform duration-300 ease-out ${ open ? "translate-x-0" : "translate-x-full" }`} > {node && ( <div className="flex h-full flex-col"> {/* header */} <div className="flex items-start justify-between border-b border-slate-700/60 p-5"> <div> <div className="flex items-center gap-2"> <h2 className="text-lg font-semibold text-slate-100">{node.hostname}</h2> {node.offline && ( <span className="rounded bg-slate-500/20 px-2 py-0.5 text-[10px] font-bold text-slate-300"> OFFLINE </span> )} {node.isRogue && ( <span className="rounded bg-rose-500/20 px-2 py-0.5 text-[10px] font-bold text-rose-300"> ROGUE / SHADOW IT </span> )} </div> <p className="mt-1 font-mono text-sm text-cyan-300">{node.ipAddress}</p> {node.relatedIps?.length > 0 && ( <p className="mt-1 text-[11px] text-slate-500"> <span className="text-slate-400">Docker / related IPs:</span>{" "} <span className="font-mono text-slate-300">{node.relatedIps.join(", ")}</span> </p> )} <p className="mt-1 text-xs text-slate-400"> {CRITICALITY_LABEL[node.criticality] ?? node.criticality} · {node.assetType} </p> </div> <button onClick={onClose} className="rounded p-1 text-slate-400 hover:bg-slate-700/40 hover:text-slate-100" aria-label="Close" > ✕ </button> </div> {/* body */} <div className="flex-1 space-y-6 overflow-y-auto p-5"> {/* open ports */} <section> <h3 className="mb-2 text-xs font-semibold uppercase tracking-wider text-slate-500"> Open Ports </h3> <div className="flex flex-wrap gap-1.5"> {node.openPorts.length === 0 && ( <span className="text-sm text-slate-500">None observed</span> )} {node.openPorts.map((p) => ( <span key={p} className="rounded border border-slate-600/60 bg-slate-800/60 px-2 py-0.5 font-mono text-xs text-slate-200" > {p} </span> ))} </div> </section> {/* vulnerabilities */} <section> <h3 className="mb-2 text-xs font-semibold uppercase tracking-wider text-slate-500"> Vulnerabilities (NetscanXi) </h3> {!netscanEnabled ? ( <p className="rounded border border-slate-700/60 bg-slate-800/40 p-3 text-xs text-slate-400"> NetscanXi integration is disabled. Enable it on the Integrations page to overlay vulnerability data. </p> ) : node.vulnerabilities.length === 0 ? ( <p className="text-sm text-emerald-300">✓ No known vulnerabilities</p> ) : ( <ul className="space-y-2"> {node.vulnerabilities.map((v) => ( <li key={v.cveId} className="rounded border border-slate-700/60 bg-slate-800/50 p-2.5" > <div className="flex items-center justify-between"> <span className="font-mono text-xs text-slate-200">{v.cveId}</span> <SeverityBadge severity={v.severity} score={v.cvssScore} /> </div> {v.title && ( <p className="mt-1 text-xs text-slate-400">{v.title}</p> )} </li> ))} </ul> )} </section> </div> {/* footer action */} <div className="space-y-3 border-t border-slate-700/60 p-5"> {canEdit && ( <button onClick={() => onToggleOffline(!node.offline)} disabled={toggling} className={`w-full rounded-lg border px-4 py-2.5 text-sm font-semibold transition disabled:opacity-50 ${ node.offline ? "border-emerald-500/50 bg-emerald-600/15 text-emerald-200 hover:bg-emerald-600/25" : "border-slate-500/50 bg-slate-600/15 text-slate-200 hover:bg-slate-600/25" }`} > {toggling ? "Updating…" : node.offline ? "● Mark as online" : "○ Mark as offline"} </button> )} <div> <button onClick={onSimulate} disabled={simulating} className="group relative w-full overflow-hidden rounded-lg border border-violet-500/50 bg-gradient-to-r from-violet-600/30 to-violet-500/10 px-4 py-3 text-sm font-semibold text-violet-100 transition hover:from-violet-600/50 hover:to-violet-500/20 disabled:opacity-50" > <span className="relative z-10"> {simulating ? "Simulating…" : "⚡ Simulate Blast Radius"} </span> </button> <p className="mt-2 text-center text-[10px] text-slate-500"> Highlights all assets reachable within 2 hops </p> </div> </div> </div> )} </div> ); } function SeverityBadge({ severity, score }: { severity: Severity; score: number }) { const styles: Record<Severity, string> = { CRITICAL: "bg-red-500/20 text-red-300", HIGH: "bg-orange-500/20 text-orange-300", MEDIUM: "bg-amber-500/20 text-amber-300", LOW: "bg-slate-500/20 text-slate-300", }; return ( <span className={`rounded px-1.5 py-0.5 text-[10px] font-bold ${styles[severity]}`}> {severity} {score.toFixed(1)} </span> ); } |