Skip to content

Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.

21.2 KB
Raw Blame
/**
 * Snitch — world map view.
 *
 * EN: D3 + TopoJSON natural-earth map. The user's position (browser
 *     geolocation, Paris fallback) sits at the origin; geolocated remote
 *     hosts are drawn as pulsing dots with animated dashed arcs flowing from
 *     the user. Node coordinates get a small deterministic jitter so hosts
 *     sharing a datacenter don't stack on one pixel.
 *     Labels use a collision pass (`applyLabelCollision`) — highest-traffic
 *     nodes win — and everything is counter-scaled by the zoom factor `k`
 *     so stroke widths and fonts stay constant on screen.
 *
 * FR: Carte natural-earth D3 + TopoJSON. La position de l'utilisateur
 *     (géolocalisation navigateur, repli par fuseau horaire) est l'origine ; les hôtes
 *     distants géolocalisés sont des points pulsants avec des arcs animés en
 *     pointillés partant de l'utilisateur. Les coordonnées reçoivent un
 *     jitter déterministe pour que les hôtes d'un même datacenter ne se
 *     superposent pas.
 *     Les étiquettes passent par une détection de collision
 *     (`applyLabelCollision`) — les nœuds au plus fort trafic gagnent — et
 *     tout est contre-dimensionné par le facteur de zoom `k` pour que les
 *     épaisseurs et polices restent constantes à l'écran.
 */
import { useEffect, useRef, useState } from 'react'
import * as d3 from 'd3'
import * as topojson from 'topojson-client'
import { useT } from '../i18n'
// EN: The world map is bundled, not fetched — fetch() of a local file is
//     blocked for file:// pages in Electron (opaque origin), so the map
//     stayed blank in the packaged app.
// FR: La carte du monde est embarquée dans le bundle, pas fetchée —
//     fetch() d'un fichier local est bloqué pour les pages file:// sous
//     Electron (origine opaque), donc la carte restait vide dans l'app.
import worldTopoJson from './countries-110m.json'

const STYLE = `
  @keyframes arcFlow {
    from { stroke-dashoffset: 1; }
    to   { stroke-dashoffset: 0; }
  }
  .arc-flow { animation: arcFlow linear infinite; }
`

/** EN: Stable per-id hash. / FR: Hash stable par id. */
function hashId(id) {
  let h = 0
  for (const c of String(id)) h = (h * 31 + c.charCodeAt(0)) & 0xffff
  return h
}

/**
 * EN: Deterministic offset so co-located hosts don't overlap.
 * FR: Décalage déterministe pour éviter la superposition des hôtes co-localisés.
 */
function jitter(id) {
  const h = hashId(id)
  const angle = (h / 0x8000) * Math.PI * 2
  const r = 0.3 + (h & 0xff) / 255 * 1.2
  return [Math.cos(angle) * r, Math.sin(angle) * r]
}

/** EN: Per-arc animation duration (varied for organic feel). / FR: Durée d'animation par arc (variée pour un effet organique). */
function animDur(id) {
  return (1.8 + (hashId(id) / 0xffff) * 2).toFixed(2) + 's'
}

// ── Label collision detection in map-coordinate space ────────────────────────
// EN: Nodes with more traffic take priority; losers hide their labels.
// FR: Les nœuds au plus fort trafic sont prioritaires ; les perdants cachent leurs étiquettes.
function applyLabelCollision(g, k) {
  const SHOW_AT = 2.5
  if (k < SHOW_AT) {
    g.selectAll('g.dest .dot-label').attr('display', 'none')
    return
  }

  const items = []
  g.selectAll('g.dest').each(function (d) {
    const t = d3.select(this).attr('transform') || ''
    const m = t.match(/translate\(([^,]+),([^)]+)\)/)
    if (!m) return
    items.push({ el: this, d, mx: +m[1], my: +m[2] })
  })

  items.sort((a, b) => (b.d?.bytes || 0) - (a.d?.bytes || 0))

  const placed = []  // EN: accepted bounding boxes (map coords) / FR: boîtes acceptées (coords carte)

  for (const { el, d, mx, my } of items) {
    const labelSel = d3.select(el).select('.dot-label')
    const text = labelSel.text()
    if (!text) { labelSel.attr('display', 'none'); continue }

    const fs  = Math.max(9 / k, 5)
    const lw  = text.length * fs * 0.58
    const lh  = fs + 2
    const r   = Math.min(3 + Math.log1p((d?.packets || 0) * 0.4), 9) / k
    const ly  = my + r + 10 / k  // EN: label center-y (below dot) / FR: y du centre de l'étiquette (sous le point)
    const pad = 4 / k

    const box = { x: mx - lw / 2 - pad, y: ly - lh / 2 - pad, w: lw + pad * 2, h: lh + pad * 2 }

    const hit = placed.some(b =>
      box.x < b.x + b.w && box.x + box.w > b.x &&
      box.y < b.y + b.h && box.y + box.h > b.y
    )

    if (hit) {
      labelSel.attr('display', 'none')
    } else {
      labelSel.attr('display', null)
      placed.push(box)
    }
  }
}

// EN: Coarse self-location fallback anchors keyed by IANA timezone — honest
//     approximation (region anchor city) when no geolocation is available.
//     Much better than silently pinning every user to Paris.
// FR: Points de repli grossiers par fuseau horaire IANA — approximation
//     honnête quand aucune géolocalisation n'est disponible. Mieux que de
//     clouer tout le monde sur Paris en silence.
const TZ_ANCHORS = {
  'America/New_York':[-74,40.7],'America/Chicago':[-87.6,41.9],'America/Denver':[-105,39.7],
  'America/Los_Angeles':[-118.2,34],'America/Toronto':[-79.4,43.7],'America/Vancouver':[-123.1,49.3],
  'America/Mexico_City':[-99.1,19.4],'America/Sao_Paulo':[-46.6,-23.5],'America/Buenos_Aires':[-58.4,-34.6],
  'Europe/London':[-0.1,51.5],'Europe/Paris':[2.35,48.85],'Europe/Berlin':[13.4,52.5],
  'Europe/Madrid':[-3.7,40.4],'Europe/Moscow':[37.6,55.8],'Europe/Kyiv':[30.5,50.4],
  'Africa/Casablanca':[-7.6,33.6],'Africa/Cairo':[31.2,30],'Asia/Dubai':[55.3,25.2],
  'Asia/Kolkata':[77.2,28.6],'Asia/Shanghai':[121.5,31.2],'Asia/Tokyo':[139.7,35.7],
  'Asia/Singapore':[103.8,1.35],'Asia/Seoul':[127,37.6],
  'Australia/Sydney':[151.2,-33.9],'Pacific/Auckland':[174.8,-36.8]
}
const TZ_REGION = [['America/',[-95,40]],['Europe/',[10,50]],['Asia/',[100,35]],
  ['Australia/',[134,-25]],['Africa/',[20,10]],['Pacific/',[-160,0]]]
function tzGuess() {
  try {
    const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''
    if (TZ_ANCHORS[tz]) return TZ_ANCHORS[tz]
    for (const [pfx, ll] of TZ_REGION) if (tz.startsWith(pfx)) return ll
  } catch { /* no Intl */ }
  return [10, 35] // EN: mid-Atlantic-ish neutral point / FR: point neutre
}

export default function MapView({ nodes, onNodeClick }) {
  const { t, lang } = useT()
  const svgRef    = useRef(null)
  const gRef      = useRef(null)
  const projRef   = useRef(null)
  const kRef      = useRef(1)
  const userPosRef = useRef(null)

  const [worldTopo, setWorldTopo] = useState(null)
  const [userPos,   setUserPos]   = useState(null)
  // EN: true when the position is a timezone-based guess rather than a real
  //     fix — the label then reads "You (approx.)".
  // FR: vrai quand la position est une estimation de fuseau horaire — le
  //     label affiche alors « Vous (approx.) ».
  const [posApprox, setPosApprox] = useState(false)
  // EN: Position is session-only on purpose — a privacy tool must not
  //     keep the user's location on disk, even in localStorage.
  // FR: Position volontairement limitée à la session — un outil de
  //     confidentialité ne garde pas la localisation sur disque.
  const setPos = (ll, approx = false) => { setUserPos(ll); setPosApprox(approx) }
  const [tooltip,   setTooltip]   = useState(null)

  // EN: Load the world TopoJSON + resolve the user's position once.
  // FR: Charger le TopoJSON du monde + résoudre la position utilisateur une fois.
  useEffect(() => {
    // EN: Bundled import — no network, works identically under file://
    //     (Electron) and http(s) (browser/Docker).
    // FR: Import embarqué — aucun réseau, fonctionne pareil sous file://
    //     (Electron) et http(s) (navigateur/Docker).
    setWorldTopo(worldTopoJson)
    navigator.geolocation?.getCurrentPosition(
      p => setPos([p.coords.longitude, p.coords.latitude]),
      () => setPos(tzGuess(), true),  // EN: timezone guess / FR: estimation par fuseau
      { timeout: 4000, maximumAge: 3600000 }
    )
    // EN: Electron has no location provider — getCurrentPosition can hang
    //     forever without ever calling back, leaving userPos null and the
    //     map blank. Belt-and-braces: force the fallback after 5 s either way.
    // FR: Electron n'a pas de fournisseur de localisation — getCurrentPosition
    //     peut rester muet indéfiniment sans jamais rappeler, laissant userPos
    //     null et la carte vide. Double sécurité : forcer le repli après 5 s.
    setTimeout(() => setUserPos(pos => { if (pos == null) { setPos(tzGuess(), true) } return pos ?? tzGuess() }), 5000)
  }, [])

  useEffect(() => {
    if (!worldTopo || !userPos || !svgRef.current) return
    userPosRef.current = userPos
    drawBase(worldTopo, userPos, posApprox ? t('map_you_approx') : t('map_you'))
  }, [worldTopo, userPos, posApprox, lang])

  useEffect(() => {
    if (!gRef.current || !projRef.current) return
    drawConnections(projRef.current)
  }, [nodes])

  /**
   * EN: Counter-scale all fixed-screen-size elements after a zoom so text and
   *     strokes stay readable at any zoom level.
   * FR: Contre-dimensionner tous les éléments à taille écran fixe après un
   *     zoom pour que texte et traits restent lisibles à tout niveau.
   */
  function rescaleAll(k) {
    const g = gRef.current
    if (!g) return

    g.select('.graticule').style('stroke-width', 0.3 / k)
    g.select('.borders').style('stroke-width', 0.3 / k)
    g.selectAll('.countries path').style('stroke-width', 0.5 / k)

    g.selectAll('path.arc-flow').each(function (d) {
      const base = 0.8 + Math.log1p((d?.bytes || 0) / 512)
      d3.select(this).style('stroke-width', Math.min(base, 3.5) / k)
    })

    g.selectAll('g.dest').each(function (d) {
      const r  = Math.min(3 + Math.log1p((d?.packets || 0) * 0.4), 9)
      const vr = r / k
      d3.select(this).select('.dot').attr('r', vr).style('stroke-width', 1 / k)
      d3.select(this).select('.dot-label')
        .attr('font-size', Math.max(9 / k, 5))
        .attr('y', vr + 10 / k)
    })

    g.select('.user-dot').attr('r', 7 / k).style('stroke-width', 1.5 / k)
    g.select('.user-label').attr('font-size', 11 / k).attr('x', function () {
      return +d3.select(this).attr('data-ux') + 10 / k
    })

    // EN: Recompute collision at the new zoom level.
    // FR: Recalculer les collisions au nouveau niveau de zoom.
    applyLabelCollision(g, k)
  }

  /**
   * EN: Draw the static map layers: ocean, graticule, countries, borders,
   *     the user's pulsing location, and the (empty) arc/dot groups.
   * FR: Dessiner les couches statiques : océan, graticule, pays, frontières,
   *     la position pulsante de l'utilisateur et les groupes arcs/points
   *     (initialement vides).
   */
  function drawBase(topo, pos, youLabel) {
    const el  = svgRef.current
    const svg = d3.select(el)
    svg.selectAll('*').remove()
    svg.append('defs').append('style').text(STYLE)

    const W = el.clientWidth
    const H = el.clientHeight

    const projection = d3.geoNaturalEarth1()
      .scale(W / 6.3)
      .translate([W / 2, H / 2])
    projRef.current = projection

    const geoPath = d3.geoPath().projection(projection)

    const zoom = d3.zoom()
      .scaleExtent([0.7, 20])
      .on('zoom', e => {
        g.attr('transform', e.transform)
        kRef.current = e.transform.k
        rescaleAll(e.transform.k)
      })
    svg.call(zoom)

    // EN: Click anywhere on the map to set your own location — the honest
    //     fallback when no geolocation provider exists (Electron). Kept in
    //     memory for this session only — nothing is stored or sent.
    // FR: Un clic sur la carte définit votre position — le repli honnête
    //     quand aucun fournisseur de géolocalisation n'existe (Electron).
    //     Conservée en mémoire pour la session — rien de stocké ni envoyé.
    svg.on('click.maploc', e => {
      if (e.target.closest('.dots')) return
      const t2 = d3.zoomTransform(el)
      const [x, y] = t2.invert(d3.pointer(e))
      const ll = projection.invert([x, y])
      if (ll) setPos(ll)
    })

    const g = svg.append('g')
    gRef.current = g

    // EN: Ocean background (oversized for pan headroom) — translucent
    //     black so the aurora backdrop glows faintly through the map.
    // FR: Fond océan (surdimensionné pour la marge de déplacement) —
    //     noir translucide pour laisser l'aurore luire sous la carte.
    g.append('rect')
      .attr('width', W * 4).attr('height', H * 4)
      .attr('x', -W).attr('y', -H)
      .style('fill', 'var(--bg)')
      .style('fill-opacity', 0.55)

    g.append('path')
      .attr('class', 'graticule')
      .datum(d3.geoGraticule()())
      .attr('d', geoPath)
      .style('fill', 'none')
      .style('stroke', 'var(--surface-2)')
      .style('stroke-width', 0.3)

    const countries = topojson.feature(topo, topo.objects.countries)
    g.append('g').attr('class', 'countries')
      .selectAll('path')
      .data(countries.features)
      .join('path')
      .attr('d', geoPath)
      .style('fill', 'var(--surface)')
      .style('stroke', 'var(--map-border)')
      .style('stroke-width', 0.5)

    g.append('path')
      .attr('class', 'borders')
      .datum(topojson.mesh(topo, topo.objects.countries, (a, b) => a !== b))
      .attr('d', geoPath)
      .style('fill', 'none')
      .style('stroke', 'var(--border)')
      .style('stroke-width', 0.3)

    // EN: Layer order matters: arcs below dots.
    // FR: L'ordre des couches compte : arcs sous les points.
    g.append('g').attr('class', 'arcs')
    g.append('g').attr('class', 'dots')

    // EN: User's position — pulsing rings + blue dot + "You/Vous" label.
    // FR: Position de l'utilisateur — anneaux pulsants + point bleu + label.
    const up = projection(pos)
    if (up) {
      const [ux, uy] = up
      const userG = g.append('g').attr('class', 'user-loc')

      for (let i = 0; i < 2; i++) {
        const base = 10 + i * 8
        userG.append('circle')
          .attr('cx', ux).attr('cy', uy).attr('r', base)
          .style('fill', 'none').style('stroke', '#3b82f6')
          .style('stroke-opacity', 0.3 - i * 0.1)
          .append('animate').attr('attributeName', 'r')
          .attr('values', `${base};${base + 18};${base}`)
          .attr('dur', `${2.5 + i * 0.8}s`).attr('repeatCount', 'indefinite')
      }

      userG.append('circle')
        .attr('class', 'user-dot')
        .attr('cx', ux).attr('cy', uy).attr('r', 7)
        .style('fill', '#3b82f6').style('fill-opacity', 0.9)
        .style('stroke', 'var(--blue-text)').style('stroke-width', 1.5)

      userG.append('text')
        .attr('class', 'user-label')
        .attr('data-ux', ux)
        .attr('x', ux + 10).attr('y', uy + 4)
        .style('fill', 'var(--blue-text)').attr('font-size', 11).attr('font-weight', '700')
        .text(youLabel)
    }

    drawConnections(projection)
  }

  /**
   * EN: Join/update/exit arcs + destination dots for geolocated nodes.
   *     Called on every `nodes` prop change — D3's data join makes updates
   *     cheap (only diffs are touched).
   * FR: Entrée/mise à jour/sortie des arcs + points de destination pour les
   *     nœuds géolocalisés. Appelé à chaque changement de `nodes` — le data
   *     join de D3 rend les mises à jour légères (seuls les diffs bougent).
   */
  function drawConnections(projection) {
    const g = gRef.current
    if (!g) return
    const geoPath = d3.geoPath().projection(projection)
    const pos     = userPosRef.current || tzGuess()
    const k       = kRef.current

    const geoNodes = Object.values(nodes)
      .filter(n => n.id !== 'local' && n.lat != null && n.lon != null)

    // ── Arcs ────────────────────────────────────────────────────────────────
    const arcs = g.select('.arcs').selectAll('path.arc-flow')
      .data(geoNodes, d => d.id)

    const arcsEnter = arcs.enter().append('path')
      .attr('class', 'arc-flow')
      .style('fill', 'none')
      .attr('pointer-events', 'none')
      .style('animation-duration', d => animDur(d.id))

    arcsEnter.merge(arcs)
      .attr('d', d => {
        const [jx, jy] = jitter(d.id)
        return geoPath({ type: 'LineString', coordinates: [pos, [d.lon + jx, d.lat + jy]] })
      })
      .style('stroke', d => d.color || 'var(--text-dim)')
      .style('stroke-opacity', 0.4)
      .style('stroke-width', d => Math.min(0.8 + Math.log1p((d.bytes || 0) / 512), 3.5) / k)
      .each(function () {
        // EN: pathLength normalizes the dash cycle so CSS animation works
        //     on any arc length.
        // FR: pathLength normalise le cycle de pointillés pour que l'animation
        //     CSS fonctionne quelle que soit la longueur d'arc.
        const len = this.getTotalLength() || 500
        d3.select(this)
          .attr('stroke-dasharray', `${len * 0.1} ${len * 0.9}`)
          .attr('pathLength', 1)
      })

    arcs.exit().remove()

    // ── Destination dots / Points de destination ────────────────────────────
    const dotGroups = g.select('.dots').selectAll('g.dest')
      .data(geoNodes, d => d.id)

    const enter = dotGroups.enter().append('g').attr('class', 'dest')
    enter.append('circle').attr('class', 'pulse').style('fill', 'none').style('stroke-opacity', 0)
    enter.append('circle').attr('class', 'dot').style('stroke', 'var(--dot-stroke)')
    enter.append('text').attr('class', 'dot-label').style('fill', 'var(--text-2)').attr('text-anchor', 'middle').attr('pointer-events', 'none')

    const all = enter.merge(dotGroups)

    all.each(function (d) {
      const [jx, jy] = jitter(d.id)
      const pt = projection([d.lon + jx, d.lat + jy])
      if (!pt) return
      const [x, y] = pt
      const r  = Math.min(3 + Math.log1p(d.packets || 0) * 0.4, 9)
      const vr = r / k

      d3.select(this).attr('transform', `translate(${x},${y})`)

      const pulse = d3.select(this).select('.pulse')
      pulse.attr('r', (r + 3) / k).style('stroke', d.color || 'var(--text-dim)')
      pulse.selectAll('animate').remove()
      pulse.append('animate').attr('attributeName', 'stroke-opacity')
        .attr('values', '0.5;0;0.5').attr('dur', '3s').attr('repeatCount', 'indefinite')

      d3.select(this).select('.dot')
        .attr('r', vr)
        .style('fill', d.color || 'var(--text-dim)')
        .style('stroke-width', 1 / k)
        .attr('cursor', 'pointer')

      d3.select(this).select('.dot-label')
        .attr('display', 'none')  // EN: collision pass decides visibility
                                  // FR: la passe de collision décide de la visibilité
        .attr('font-size', Math.max(9 / k, 5))
        .attr('y', vr + 10 / k)
        .text(() => {
          const lbl = d.label || (d.label_key ? t(d.label_key) : null) || d.ip || ''
          return lbl.length > 18 ? lbl.slice(0, 16) + '…' : lbl
        })
    })

    all
      .on('mouseover', (e, d) => setTooltip({ x: e.clientX, y: e.clientY, node: d }))
      .on('mouseout',  () => setTooltip(null))
      .on('click',     (_, d) => onNodeClick?.(d))

    dotGroups.exit().remove()

    applyLabelCollision(g, k)
  }

  const geoCount   = Object.values(nodes).filter(n => n.id !== 'local' && n.lat).length
  const noGeoCount = Object.values(nodes).filter(n => n.id !== 'local' && !n.lat).length

  return (
    <div style={{ width: '100%', height: '100%', position: 'relative' }}>
      <svg ref={svgRef} style={{ width: '100%', height: '100%' }} />

      {/* EN: Geolocated-host counter badge — sits below the floating toolbar.
          FR: Badge compteur d'hôtes géolocalisés — sous la barre d'outils flottante. */}
      <div style={{
        position: 'absolute', top: 64, left: 16,
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 8, padding: '8px 14px', fontSize: 10, color: 'var(--text-muted)',
      }}>
        <span style={{ color: '#22c55e', fontWeight: 700 }}>{t('map_located', geoCount)}</span>
        {noGeoCount > 0 && <span> · <span style={{ color: '#f59e0b' }}>{noGeoCount}</span> {t('map_no_geo')}</span>}
      </div>

      {/* EN: Hover tooltip / FR: Infobulle au survol */}
      {tooltip && (
        <div style={{
          position: 'fixed', left: tooltip.x + 14, top: tooltip.y - 10, zIndex: 100,
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 8, padding: '8px 12px', pointerEvents: 'none',
          boxShadow: '0 4px 20px rgba(0,0,0,0.5)',
        }}>
          <div style={{ fontWeight: 700, fontSize: 12, color: 'var(--text)', marginBottom: 3 }}>
            {tooltip.node.label || (tooltip.node.label_key ? t(tooltip.node.label_key) : null) || tooltip.node.ip}
          </div>
          {tooltip.node.country && (
            <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>
              {[tooltip.node.city, tooltip.node.country].filter(Boolean).join(', ')}
            </div>
          )}
          {tooltip.node.org && (
            <div style={{ fontSize: 10, color: 'var(--text-muted)' }}>{tooltip.node.org}</div>
          )}
          <div style={{ marginTop: 5, fontSize: 10, display: 'flex', gap: 10 }}>
            <span style={{ color: tooltip.node.color }}>{tooltip.node.category}</span>
            <span style={{ color: 'var(--text-faint)' }}>{tooltip.node.packets} pkt</span>
          </div>
        </div>
      )}
    </div>
  )
}