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.

20.3 KB
Raw Blame
/**
 * Snitch — alert UI components.
 *
 * EN: Three exports:
 *       AlertBell   — toolbar bell with an unread counter
 *       AlertPanel  — dropdown listing all alerts, grouped visually by severity
 *       AlertToasts — transient bottom-left popups for warning/critical alerts
 *     Alert `type` values map to translated labels via the `alert_*` i18n keys.
 * FR: Trois exports :
 *       AlertBell   — cloche de la barre d'outils avec compteur de non-lus
 *       AlertPanel  — panneau listant toutes les alertes, groupées par sévérité
 *       AlertToasts — popups transitoires en bas à gauche pour les alertes
 *                     warning/critiques
 *     Les `type` d'alerte correspondent aux libellés traduits via les clés
 *     i18n `alert_*`.
 */
import { useState, useEffect, useRef } from 'react'
import {
  Bell, Info, AlertTriangle, AlertCircle, X,
  Globe, WifiOff, Wifi, ScanLine,
  Activity, Unlock, TrendingUp, Camera, ShieldAlert,
  FileWarning, Fingerprint, Cpu, HelpCircle,
  Pickaxe, Magnet, Syringe, Package, ListFilter,
  Ban, Skull, Pause, ShieldCheck, ShieldX, Brain, Waves,
} from 'lucide-react'
import { useT } from '../i18n'
import { apiBase, authHeaders } from '../api'

// EN: Visual style per severity. / FR: Style visuel par sévérité.
const SEVERITY_STYLES = {
  info:     { color: '#38bdf8', Icon: Info,          bg: 'var(--info-bg)' },
  warning:  { color: '#f59e0b', Icon: AlertTriangle, bg: 'var(--warn-bg)' },
  critical: { color: '#ef4444', Icon: AlertCircle,   bg: 'var(--danger-bg)' },
}

// EN: Per-alert-type icon. / FR: Icône par type d'alerte.
const TYPE_ICONS = {
  NEW_HOST:           Globe,
  SUSPICIOUS_PROCESS: AlertTriangle,
  SUSPICIOUS_PORT:    Unlock,
  BEACON:             Activity,
  VOLUME_SPIKE:       TrendingUp,
  NEW_LAN_DEVICE:     Wifi,
  DEVICE_OFFLINE:     WifiOff,
  MEDIA_EXFIL:        Camera,
  PORT_SCAN:          ScanLine,
  UPLOAD_SPIKE:       TrendingUp,
  WATCHLIST_HIT:      ShieldAlert,
  BLOCKED_ATTEMPT:    ShieldAlert,
  THREAT_HIT:         ShieldAlert,
  DNS_TUNNEL:         ScanLine,
  CLEARTEXT:          Unlock,
  BASELINE_DEVIATION: Activity,
  LOCKDOWN:           AlertTriangle,
  BINARY_CHANGED:     FileWarning,
  NAME_MISMATCH:      Fingerprint,
  MEM_RWX:            Cpu,
  MODULE_SUSPECT:     Package,
  MODULE_CHANGED:     FileWarning,
  MINING_STRATUM:     Pickaxe,
  MINING_SUSPECT:     Pickaxe,
  SINKHOLE_HIT:       Magnet,
  INJECT_SUSPECT:     Syringe,
  CUSTOM_RULE:        ListFilter,
  TLS_CERT:           Fingerprint,
  HIGH_ENTROPY:       Waves,
  ICMP_TUNNEL:        Activity,
  ML_ANOMALY:         Brain,
  ASK_VERDICT:        HelpCircle,
}

/**
 * EN: One-click incident response on an alert — real API calls, tiny
 *     inline buttons under the alert body. `block` creates a real OS
 *     firewall rule on the remote IP; `kill`/`suspend` act on the
 *     reported pid; ASK_VERDICT alerts get allow/deny that resolves the
 *     held NFQUEUE packet. Errors stay silent — the action is best-effort
 *     remediation, the alert itself is the durable record.
 * FR: Réponse à incident en un clic sur une alerte — vrais appels API.
 *     `block` crée une vraie règle pare-feu OS sur l'IP distante ;
 *     `kill`/`suspend` agissent sur le pid rapporté ; les alertes
 *     ASK_VERDICT ont autoriser/refuser qui résout le paquet NFQUEUE
 *     gelé. Échecs silencieux — remédiation au mieux.
 */
function AlertActions({ alert }) {
  const { t } = useT()
  const [done, setDone] = useState('')
  const d = alert.details || {}
  const post = async (path, body, tag) => {
    try {
      const base = await apiBase()
      const headers = { ...(await authHeaders()), 'Content-Type': 'application/json' }
      const r = await fetch(`${base}${path}`, {
        method: 'POST', headers, body: JSON.stringify(body),
      })
      if (r.ok) setDone(tag)
    } catch { /* best-effort remediation */ }
  }
  const btn = {
    background: 'none', border: '1px solid var(--border)', borderRadius: 4,
    padding: '2px 6px', fontSize: 9, color: 'var(--text-muted)',
    cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 3,
  }
  return (
    <>
      {alert.type === 'ASK_VERDICT' && d.remote_ip && (
        <>
          <button onClick={() => post('/security/ask/verdict',
            { remote_ip: d.remote_ip, remote_port: d.remote_port,
              proto: d.proto, allow: true }, 'allow')}
            style={{ ...btn, color: '#4ade80', borderColor: '#4ade8044' }}>
            <ShieldCheck size={10} /> {t('alert_act_allow')}
          </button>
          <button onClick={() => post('/security/ask/verdict',
            { remote_ip: d.remote_ip, remote_port: d.remote_port,
              proto: d.proto, allow: false }, 'deny')}
            style={{ ...btn, color: '#ef4444', borderColor: '#ef444444' }}>
            <ShieldX size={10} /> {t('alert_act_deny')}
          </button>
          <button onClick={() => post('/security/ask/verdict',
            { remote_ip: d.remote_ip, remote_port: d.remote_port,
              proto: d.proto, allow: true, permanent: true }, 'allow+')}
            title={t('alert_act_allow_perm')}
            style={{ ...btn, color: '#4ade80', borderColor: '#4ade8044' }}>
            {t('alert_act_allow_perm')}
          </button>
          <button onClick={() => post('/security/ask/verdict',
            { remote_ip: d.remote_ip, remote_port: d.remote_port,
              proto: d.proto, allow: false, permanent: true }, 'deny+')}
            title={t('alert_act_deny_perm')}
            style={{ ...btn, color: '#ef4444', borderColor: '#ef444444' }}>
            {t('alert_act_deny_perm')}
          </button>
        </>
      )}
      {d.ip && !alert._grouped && done !== 'block' && (
        <button onClick={() => post('/firewall/rules',
          { kind: 'ip', value: d.ip, action: 'block' }, 'block')}
          title={t('alert_act_block')} style={btn}>
          <Ban size={10} /> {t('alert_act_block')}
        </button>
      )}
      {d.pid && !alert._grouped && (
        <>
          <button onClick={() => post('/processes/kill', { pid: d.pid }, 'kill')}
            title={t('alert_act_kill')} style={{ ...btn, color: '#ef4444' }}>
            <Skull size={10} /> {t('alert_act_kill')}
          </button>
          <button onClick={() => post('/processes/suspend', { pid: d.pid }, 'suspend')}
            title={t('alert_act_suspend')} style={btn}>
            <Pause size={10} /> {t('alert_act_suspend')}
          </button>
        </>
      )}
      {done && <span style={{ fontSize: 9, color: '#4ade80' }}>✓ {done}</span>}
    </>
  )
}

/**
 * EN: On-demand bilingual explanation for one alert type — fetched from
 *     GET /security/explain (deterministic templates, offline-capable).
 *     Picks the <field>_<lang> variant, English fallback.
 * FR: Explication bilingue à la demande pour un type d'alerte — récupérée
 *     depuis GET /security/explain (gabarits déterministes, hors-ligne).
 *     Choisit la variante <champ>_<lang>, retombe sur l'anglais.
 */
function useExplanation(type, open) {
  const { lang } = useT()
  const [rec, setRec] = useState(null)
  useEffect(() => {
    if (!open || rec) return
    let cancelled = false
    ;(async () => {
      try {
        const base = await apiBase()
        const headers = await authHeaders()
        const r = await fetch(`${base}/security/explain?type=${encodeURIComponent(type)}`, { headers })
        if (r.ok && !cancelled) setRec(await r.json())
      } catch { /* explanation is a nicety — failure stays silent */ }
    })()
    return () => { cancelled = true }
  }, [open, type]) // eslint-disable-line react-hooks/exhaustive-deps
  if (!rec) return null
  const pick = (k) => rec[`${k}_${lang}`] || rec[`${k}_en`]
  const actions = rec[`actions_${lang}`] || rec.actions_en || []
  return { title: pick('title'), what: pick('what'), why: pick('why'), actions }
}

export function AlertBell({ unread, onClick }) {
  return (
    <button onClick={onClick} style={{
      position: 'relative', background: 'var(--surface)',
      border: '1px solid var(--border)', borderRadius: 20,
      padding: '5px 14px', cursor: 'pointer',
      display: 'flex', alignItems: 'center', gap: 6,
      color: unread > 0 ? '#f59e0b' : 'var(--text-muted)',
    }}>
      <Bell size={14} />
      {unread > 0 && (
        <span style={{
          background: '#ef4444', color: '#fff',
          borderRadius: 10, fontSize: 9, fontWeight: 700,
          padding: '1px 5px', minWidth: 16, textAlign: 'center',
        }}>
          {unread > 99 ? '99+' : unread}
        </span>
      )}
    </button>
  )
}

export function AlertPanel({ alerts, onClose, onIgnore }) {
  const { t } = useT()
  const warningCount  = alerts.filter(a => a.severity === 'warning').length
  const criticalCount = alerts.filter(a => a.severity === 'critical').length
  const infoCount     = alerts.filter(a => a.severity === 'info').length

  // EN: NEW_HOST alerts are collapsed into ONE synthetic row ("N new hosts")
  //     — they flood the list otherwise. All other types stay individual.
  // FR: Les alertes NEW_HOST sont réduites en UNE ligne synthétique
  //     (« N nouveaux hôtes ») — elles noient la liste sinon. Les autres
  //     types restent individuels.
  const newHostAlerts = alerts.filter(a => a.type === 'NEW_HOST')
  const otherAlerts   = alerts.filter(a => a.type !== 'NEW_HOST')
  const rows = [...otherAlerts]
  if (newHostAlerts.length > 0) {
    rows.unshift({
      id: 'new-hosts-group',
      type: 'NEW_HOST',
      severity: 'info',
      timestamp: newHostAlerts[0].timestamp,
      details: { count: newHostAlerts.length, hosts: newHostAlerts.map(a => a.details?.ip || a.message).slice(0, 20) },
      _grouped: true,
    })
  }
  rows.sort((a, b) => parseTs(b.timestamp) - parseTs(a.timestamp))

  return (
    <div style={{
      position: 'absolute', top: 56, right: 16, zIndex: 200,
      width: 380, maxHeight: 'calc(100vh - 80px)',
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 12, overflow: 'hidden',
      boxShadow: '0 8px 40px rgba(0,0,0,0.6)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* EN: Header with severity counters / FR: En-tête avec compteurs de sévérité */}
      <div style={{
        padding: '14px 18px', borderBottom: '1px solid var(--border)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <div>
          <span style={{ fontWeight: 700, fontSize: 13, color: 'var(--text)' }}>{t('alerts_title')}</span>
          <span style={{ fontSize: 11, color: 'var(--text-muted)', marginLeft: 8 }}>{rows.length} {t('alerts_total')}</span>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {criticalCount > 0 && <Badge count={criticalCount} color="#ef4444" />}
          {warningCount  > 0 && <Badge count={warningCount}  color="#f59e0b" />}
          {infoCount     > 0 && <Badge count={infoCount}     color="#38bdf8" />}
          <button onClick={onClose} aria-label="Close alerts / Fermer les alertes" style={{ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer' }}>
            <X size={16} />
          </button>
        </div>
      </div>

      <div style={{ overflowY: 'auto', flex: 1 }}>
        {rows.length === 0 && (
          <div style={{ padding: 32, textAlign: 'center', color: 'var(--text-muted)', fontSize: 12 }}>
            {t('alerts_empty')}
          </div>
        )}
        {rows.map(alert => <AlertRow key={alert.id} alert={alert} onIgnore={onIgnore} />)}
      </div>
    </div>
  )
}

/**
 * EN: Translated alert message — the backend ships a code (alert.type) plus
 *     structured params (alert.details); the `alertmsg_*` i18n functions
 *     build the prose locally. Falls back to the backend's English `message`
 *     if no key exists.
 * FR: Message d'alerte traduit — le backend envoie un code (alert.type) plus
 *     des paramètres structurés (alert.details) ; les fonctions i18n
 *     `alertmsg_*` construisent le texte localement. Retombe sur le `message`
 *     anglais du backend si aucune clé n'existe.
 */
function alertMessage(t, alert) {
  if (alert._grouped) return t('alertmsg_NEW_HOSTS', alert.details.count)
  const key = `alertmsg_${alert.type}`
  const translated = t(key, alert.details || {})
  return translated !== key ? translated : alert.message
}

function AlertRow({ alert, onIgnore }) {
  const { t } = useT()
  const sev      = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.info
  const TypeIcon = TYPE_ICONS[alert.type] || Info
  const SevIcon  = sev.Icon
  const [showWhy, setShowWhy] = useState(false)
  const expl = useExplanation(alert.type, showWhy)
  // EN: Translate the type if a key exists, else show the raw type.
  // FR: Traduire le type si une clé existe, sinon afficher le type brut.
  const typeLabel = t(`alert_${alert.type}`) !== `alert_${alert.type}` ? t(`alert_${alert.type}`) : alert.type

  return (
    <div style={{
      padding: '10px 18px', borderBottom: '1px solid var(--surface)',
      borderLeft: `3px solid ${sev.color}`, background: sev.bg,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
          <SevIcon size={14} color={sev.color} style={{ flexShrink: 0, marginTop: 1 }} />
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 2 }}>
              <TypeIcon size={11} color={sev.color} />
              <span style={{ fontSize: 10, color: sev.color, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                {typeLabel}
              </span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--text)', lineHeight: 1.4 }}>{alertMessage(t, alert)}</div>
            {alert.details && Object.keys(alert.details).length > 0 && (
              <div style={{ marginTop: 3, fontSize: 9, color: 'var(--text-muted)', fontFamily: 'monospace' }}>
                {Object.entries(alert.details).filter(([, v]) => v).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(', ') : v}`).join(' · ')}
              </div>
            )}
            {showWhy && expl && (
              <div style={{
                marginTop: 5, padding: '6px 8px', fontSize: 10, lineHeight: 1.5,
                background: 'var(--bg)', border: '1px solid var(--border)',
                borderRadius: 6, color: 'var(--text-muted)',
              }}>
                <div style={{ fontWeight: 700, color: 'var(--text)', marginBottom: 2 }}>{expl.title}</div>
                <div>{expl.what}</div>
                <div style={{ marginTop: 3 }}>{expl.why}</div>
                {expl.actions.length > 0 && (
                  <ul style={{ margin: '4px 0 0', paddingLeft: 14 }}>
                    {expl.actions.map((a, i) => <li key={i}>{a}</li>)}
                  </ul>
                )}
              </div>
            )}
            <div style={{ display: 'flex', gap: 6, marginTop: 5 }}>
              {!alert._grouped && (
                <button onClick={() => setShowWhy(v => !v)} title={t('alert_why')} style={{
                  background: 'none', border: '1px solid var(--border)',
                  borderRadius: 4, padding: '2px 6px', fontSize: 9,
                  color: 'var(--text-muted)', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', gap: 3,
                }}>
                  <HelpCircle size={10} /> {t('alert_why')}
                </button>
              )}
              {!alert._grouped && onIgnore && (
                <button onClick={() => onIgnore(alert)} style={{
                  background: 'none', border: '1px solid var(--border)',
                  borderRadius: 4, padding: '2px 8px', fontSize: 9,
                  color: 'var(--text-muted)', cursor: 'pointer',
                }}>
                  {t('ignore_alert')}
                </button>
              )}
              <AlertActions alert={alert} />
            </div>
          </div>
        </div>
        <span style={{ fontSize: 9, color: 'var(--text-faint)', flexShrink: 0, marginTop: 2 }}>
          {timeAgo(alert.timestamp, t)}
        </span>
      </div>
    </div>
  )
}

/**
 * EN: Parse a backend timestamp. They are ISO 8601 with an offset
 *     ("+00:00"); only naive ones get a "Z" — "…+00:00Z" is NaN
 *     ("NaNh ago").
 * FR: Analyser un horodatage du backend. Ils sont en ISO 8601 avec
 *     décalage (« +00:00 ») ; seuls les naïfs reçoivent un « Z » —
 *     « …+00:00Z » donne NaN (« NaNh ago »).
 */
export function parseTs(iso) {
  return new Date(/(Z|[+-]\d{2}:?\d{2})$/.test(iso) ? iso : iso + 'Z')
}

/** EN: Relative timestamp via i18n keys. / FR: Horodatage relatif via les clés i18n. */
export function timeAgo(iso, t, now = Date.now()) {
  const diff = Math.max(0, Math.floor((now - parseTs(iso)) / 1000))
  if (Number.isNaN(diff)) return ''
  if (diff < 5)    return t('time_just_now')
  if (diff < 60)   return t('time_seconds', diff)
  if (diff < 3600) return t('time_minutes', Math.floor(diff / 60))
  return t('time_hours', Math.floor(diff / 3600))
}

function Badge({ count, color }) {
  return (
    <span style={{
      background: color + '22', color, border: `1px solid ${color}44`,
      borderRadius: 10, fontSize: 10, fontWeight: 700, padding: '1px 7px',
    }}>
      {count}
    </span>
  )
}

const TOAST_DURATION = 5000  // EN: ms before fade starts / FR: ms avant le début du fondu
const TOAST_FADE     = 800   // EN: fade duration in ms / FR: durée du fondu en ms

/**
 * EN: Stacked transient notifications. New alerts appear for TOAST_DURATION,
 *     then fade out over TOAST_FADE and unmount.
 * FR: Notifications empilées transitoires. Les nouvelles alertes restent
 *     TOAST_DURATION puis fondent en TOAST_FADE avant démontage.
 */
export function AlertToasts({ alerts }) {
  const [visible, setVisible] = useState([])  // [{ alert, dying }]
  const timers = useRef({})
  const prevIds = useRef(new Set())

  useEffect(() => {
    const incoming = alerts.filter(a => a.severity !== 'info').slice(0, 10)
    const newOnes = incoming.filter(a => !prevIds.current.has(a.id))
    if (!newOnes.length) return

    newOnes.forEach(a => prevIds.current.add(a.id))

    setVisible(prev => {
      const next = [...newOnes.map(a => ({ alert: a, dying: false })), ...prev].slice(0, 5)
      return next
    })

    newOnes.forEach(a => {
      timers.current[a.id] = setTimeout(() => {
        setVisible(prev => prev.map(t => t.alert.id === a.id ? { ...t, dying: true } : t))
        setTimeout(() => {
          setVisible(prev => prev.filter(t => t.alert.id !== a.id))
          delete timers.current[a.id]
        }, TOAST_FADE)
      }, TOAST_DURATION)
    })
  }, [alerts])

  useEffect(() => () => Object.values(timers.current).forEach(clearTimeout), [])

  return (
    <div style={{
      position: 'absolute', bottom: 16, left: 16,
      display: 'flex', flexDirection: 'column-reverse', gap: 4,
      pointerEvents: 'none', zIndex: 300, maxWidth: 260,
    }}>
      {visible.map(({ alert, dying }, i) => (
        <Toast key={alert.id} alert={alert} index={i} dying={dying} />
      ))}
    </div>
  )
}

function Toast({ alert, index, dying }) {
  const { t } = useT()
  const sev      = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.info
  const TypeIcon = TYPE_ICONS[alert.type] || Info
  const typeLabel = t(`alert_${alert.type}`) !== `alert_${alert.type}` ? t(`alert_${alert.type}`) : alert.type

  // EN: Older toasts fade progressively in the stack.
  // FR: Les toasts plus anciens s'estompent progressivement dans la pile.
  const baseOpacity = Math.max(0, 1 - index * 0.2)

  return (
    <div style={{
      background: 'var(--surface)', border: `1px solid ${sev.color}44`,
      borderLeft: `3px solid ${sev.color}`,
      borderRadius: 6, padding: '5px 10px',
      display: 'flex', alignItems: 'center', gap: 8,
      opacity: dying ? 0 : baseOpacity,
      transform: `scale(${1 - index * 0.02})`,
      transition: dying ? `opacity ${TOAST_FADE}ms ease` : 'opacity 0.3s ease',
      transformOrigin: 'bottom left',
    }}>
      <TypeIcon size={12} color={sev.color} style={{ flexShrink: 0 }} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 9, color: sev.color, fontWeight: 700, textTransform: 'uppercase' }}>{typeLabel}</div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{alertMessage(t, alert)}</div>
      </div>
    </div>
  )
}