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.

Surface fatal capture failures instead of failing silently

MoneyLisa4439357f63e0
diff --git a/backend/api/main.py b/backend/api/main.py
index 34959e3..262b759 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -1865,6 +1865,43 @@ def _cleanup_loop() -> None:
# ── Capture lifecycle / Cycle de vie de la capture ───────────────────────────
+def _capture_error() -> str | None:
+ """EN: Last fatal capture error reported by the sniffer (None = healthy
+ or demo mode, which has no error path).
+ FR: Dernière erreur fatale de capture remontée par le sniffer (None =
+ sain, ou mode démo qui n'a pas de chemin d'erreur)."""
+ return getattr(_sniffer, "last_error", None) if _sniffer else None
+
+
+def _sniffer_failed(msg: str) -> None:
+ """EN: Called from the capture thread when pcap dies (no privileges,
+ missing Npcap, unplugged interface…). Without this the UI showed
+ "capturing" forever while the sniffer thread was dead — the ARP scan
+ kept feeding the device list and users saw "devices but no traffic"
+ with no explanation. Flag the real state via capture_status.
+ FR: Appelé depuis le thread de capture quand pcap meurt (droits
+ manquants, Npcap absent, interface débranchée…). Sans ça l'UI
+ affichait « capture en cours » indéfiniment alors que le thread était
+ mort — le scan ARP continuait de remplir la liste d'appareils et
+ l'utilisateur voyait « des appareils mais pas de trafic » sans
+ explication. On signale l'état réel via capture_status."""
+ global _capturing
+ _capturing = False
+ if _loop is None:
+ return
+ try:
+ asyncio.run_coroutine_threadsafe(broadcast({
+ "type": "capture_status",
+ "capturing": False,
+ "capture_error": msg,
+ "ports": _port_filter,
+ "excluded_processes": sorted(_excluded_processes),
+ "whitelisted_ips": sorted(_whitelisted_ips),
+ }), _loop)
+ except Exception: # noqa: BLE001
+ pass
+
+
def _start_capture() -> None:
"""EN: (Re)start sniffer + ARP-table scanner in daemon threads.
With SNITCH_DEMO=1 the sniffer is replaced by the synthetic demo
@@ -1879,6 +1916,7 @@ def _start_capture() -> None:
else:
_sniffer = PacketSniffer(callback=on_packet, ports=_port_filter,
iface=db.get_setting("interface"))
+ _sniffer.on_error = _sniffer_failed
# EN: eBPF attribution probe — kernel sees every connect() even
# from processes that die before the next socket-table refresh.
# Opt-in-able via settings, silently no-ops without bcc/root.
@@ -2366,6 +2404,7 @@ async def get_capture_status() -> dict:
"""EN: Capture state + all active filters. / FR: État de capture + filtres actifs."""
return {
"capturing": _capturing,
+ "capture_error": _capture_error(),
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
@@ -2382,6 +2421,7 @@ async def stop_capture() -> dict:
await broadcast({
"type": "capture_status",
"capturing": False,
+ "capture_error": _capture_error(),
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
@@ -2436,6 +2476,7 @@ async def start_capture() -> dict:
await broadcast({
"type": "capture_status",
"capturing": True,
+ "capture_error": None,
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
@@ -2453,6 +2494,7 @@ async def set_process_filter(body: ProcessFilterBody) -> dict:
await broadcast({
"type": "capture_status",
"capturing": _capturing,
+ "capture_error": _capture_error(),
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
@@ -2499,6 +2541,7 @@ async def set_ip_whitelist(body: WhitelistBody) -> dict:
await broadcast({
"type": "capture_status",
"capturing": _capturing,
+ "capture_error": _capture_error(),
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
@@ -2741,6 +2784,7 @@ async def get_diagnostics() -> dict:
"platform": platform.platform(),
"capture": {
"capturing": _capturing,
+ "capture_error": _capture_error(),
"interface": db.get_setting("interface"),
"ports": _port_filter,
},
@@ -4250,6 +4294,7 @@ async def websocket_endpoint(websocket: WebSocket) -> None:
"alerts": detector.history[-50:],
"media": _media_state,
"capturing": _capturing,
+ "capture_error": _capture_error(),
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.py
index 090aebc..f1d3d67 100644
--- a/backend/capture/sniffer.py
+++ b/backend/capture/sniffer.py
@@ -243,6 +243,40 @@ class PacketSniffer:
# qui comptait.
self.stats = {"frames": 0, "delivered": 0, "parse_failed": 0,
"not_for_us": 0}
+ # EN: Fatal capture failure surfaced to the API/UI — pcap_open_live
+ # dying (no privileges, missing Npcap) used to fail silently in
+ # this thread while the ARP scan kept feeding the device list:
+ # "devices but no traffic" with zero explanation. `on_error` is
+ # called from the capture thread, like `callback`.
+ # FR: Échec fatal de capture remonté à l'API/UI — un pcap_open_live
+ # mourant (droits manquants, Npcap absent) échouait silencieusement
+ # dans ce thread pendant que le scan ARP remplissait la liste
+ # d'appareils : « appareils mais pas de trafic » sans explication.
+ # `on_error` est appelé depuis le thread de capture, comme
+ # `callback`.
+ self.last_error: Optional[str] = None
+ self.on_error: Optional[Callable[[str], None]] = None
+
+ def _fail(self, msg: str) -> None:
+ """EN: Record a fatal capture failure and notify the API layer.
+ FR: Enregistrer un échec fatal de capture et notifier la couche API."""
+ self.last_error = msg
+ logger.error("capture failed: %s", msg)
+ if self.on_error:
+ try:
+ self.on_error(msg)
+ except Exception: # noqa: BLE001
+ logger.debug("capture error callback failed", exc_info=True)
+
+ @property
+ def running(self) -> bool:
+ """EN: True while the capture thread is actually alive — the honest
+ answer to "are we capturing", unlike the intent flag.
+ FR: Vrai tant que le thread de capture est réellement vivant — la
+ réponse honnête à « est-ce qu'on capture », contrairement au
+ drapeau d'intention."""
+ return (self._running and self._thread is not None
+ and self._thread.is_alive())
def set_attribution_probe(self, probe) -> None:
"""EN: Register an object exposing lookup(ip, port) → (pid, name)
@@ -438,11 +472,13 @@ class PacketSniffer:
def start(self) -> None:
"""EN: Launch the capture thread. / FR: Lancer le thread de capture."""
if not PCAP_AVAILABLE:
- logger.warning("libpcap unavailable — packet capture disabled")
+ self._fail("libpcap unavailable — install Npcap (Windows) or "
+ "libpcap (Linux); on macOS it is built in")
return
if not self.iface:
- logger.warning("no capture interface found — packet capture disabled")
+ self._fail("no capture interface found — packet capture disabled")
return
+ self.last_error = None
self._running = True
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
@@ -469,7 +505,13 @@ class PacketSniffer:
try:
pkt = self._session.next_packet()
except PcapError as exc:
- logger.error("capture error: %s", exc)
+ # EN: A pcap error racing a user stop() is benign — only
+ # report failures while capture is meant to run.
+ # FR: Une erreur pcap concurrente d'un stop() utilisateur
+ # est bénigne — ne remonter que les échecs survenant
+ # pendant que la capture doit tourner.
+ if self._running:
+ self._fail(f"capture error: {exc}")
break
if time.monotonic() - last_ip_refresh > 30:
self.local_ips = get_local_ips()
@@ -477,7 +519,9 @@ class PacketSniffer:
if pkt is not None:
self._handle_frame(*pkt)
except PcapError as exc:
- logger.error("sniffer failed to start: %s", exc)
+ self._fail(f"sniffer failed to start: {exc}")
+ except Exception as exc: # noqa: BLE001
+ self._fail(f"sniffer crashed: {exc}")
finally:
if self._session:
self._session.close()
diff --git a/backend/tests/test_capture_iface.py b/backend/tests/test_capture_iface.py
index 809b5c4..c1320f6 100644
--- a/backend/tests/test_capture_iface.py
+++ b/backend/tests/test_capture_iface.py
@@ -75,3 +75,39 @@ def test_default_iface_falls_back_without_route(monkeypatch):
monkeypatch.setattr(sniffer, "_default_route_ip", lambda: None)
monkeypatch.setattr(sniffer.psutil, "net_if_addrs", lambda: {})
assert sniffer.PacketSniffer._default_iface() == "en0"
+
+
+def test_pcap_open_failure_is_reported(monkeypatch):
+ """EN: pcap_open_live failing (no privileges / missing Npcap) must set
+ last_error and fire on_error — the old code logged and died silently,
+ which is how users got "devices but no traffic" with no explanation.
+ FR: Un échec de pcap_open_live (droits manquants / Npcap absent) doit
+ remplir last_error et déclencher on_error — l'ancien code logguait
+ puis mourrait silencieusement, d'où le « appareils mais pas de
+ trafic » sans explication vu par les utilisateurs."""
+ monkeypatch.setattr(sniffer, "PCAP_AVAILABLE", True)
+
+ def boom(*_a, **_k):
+ raise sniffer.PcapError("you don't have permission to capture")
+ monkeypatch.setattr(sniffer, "PcapSession", boom)
+
+ s = sniffer.PacketSniffer(callback=lambda p: None, iface="en0")
+ errors = []
+ s.on_error = errors.append
+ s._running = True
+ s._run()
+ assert s.last_error and "permission" in s.last_error
+ assert errors == [s.last_error]
+
+
+def test_missing_libpcap_is_reported(monkeypatch):
+ """EN: No libpcap at all must also surface via last_error + on_error.
+ FR: L'absence totale de libpcap doit aussi remonter via last_error +
+ on_error."""
+ monkeypatch.setattr(sniffer, "PCAP_AVAILABLE", False)
+ s = sniffer.PacketSniffer(callback=lambda p: None, iface="en0")
+ errors = []
+ s.on_error = errors.append
+ s.start()
+ assert s.last_error
+ assert errors == [s.last_error]
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 933af3e..a682d95 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -34,7 +34,7 @@ import { computePrivacyScore } from './scoring/privacy'
import { useT, LANGS, LANG_NAMES } from './i18n'
export default function App() {
- const { nodes, edges, lanDevices, packets, alerts, unread, clearUnread, status, bandwidth, capturing, toggleCapture, portFilter, updatePortFilter, excludedProcesses, updateProcessFilter, whitelistedIps, updateIpWhitelist, media, ssid, iface, watchlist, updateWatchlist } = useWebSocket(null) // EN: null → resolves the dynamic port/scheme via wsBase()
+ const { nodes, edges, lanDevices, packets, alerts, unread, clearUnread, status, bandwidth, capturing, captureError, toggleCapture, portFilter, updatePortFilter, excludedProcesses, updateProcessFilter, whitelistedIps, updateIpWhitelist, media, ssid, iface, watchlist, updateWatchlist } = useWebSocket(null) // EN: null → resolves the dynamic port/scheme via wsBase()
// FR: null → résout port/schéma dynamiques via wsBase()
const [selected, setSelected] = useState(null)
const [view, setView] = useState('graph')
@@ -209,6 +209,13 @@ export default function App() {
<StatusBadge status={status} />
</div>
+ {/* EN: Fatal capture failure banner — without it a dead pcap
+ session showed "devices but no traffic" with no hint why.
+ FR: Bannière d'échec fatal de capture — sans elle une session
+ pcap morte affichait « des appareils mais pas de trafic »
+ sans aucune indication. */}
+ {captureError && <CaptureErrorBanner error={captureError} />}
+
{showAlerts && (
<AlertPanel alerts={alerts} onClose={() => setShowAlerts(false)} onIgnore={handleIgnoreAlert} />
)}
@@ -836,6 +843,34 @@ function NetworkBadge({ ssid, iface }) {
)
}
+/** EN: Fatal capture failure banner — pcap died (no privileges, missing
+ * Npcap, unplugged interface) while the UI kept saying "capturing".
+ * Shows the raw libpcap message plus the fix hint.
+ * FR: Bannière d'échec fatal de capture — pcap est mort (droits manquants,
+ * Npcap absent, interface débranchée) alors que l'UI continuait
+ * d'afficher « capture en cours ». Affiche le message libpcap brut plus
+ * l'indice de résolution. */
+function CaptureErrorBanner({ error }) {
+ const { t } = useT()
+ return (
+ <div role="alert" style={{
+ position: 'absolute', top: 16, left: '50%', transform: 'translateX(-50%)',
+ zIndex: 60, maxWidth: 620,
+ background: 'var(--surface)', border: '1px solid #ef4444',
+ borderRadius: 10, padding: '10px 16px',
+ display: 'flex', alignItems: 'flex-start', gap: 10,
+ boxShadow: '0 4px 24px rgba(0,0,0,0.35)',
+ }}>
+ <AlertTriangle size={16} color="#ef4444" style={{ flexShrink: 0, marginTop: 2 }} />
+ <div>
+ <div style={{ fontSize: 12, fontWeight: 600, color: '#ef4444' }}>{t('capture_error_title')}</div>
+ <div style={{ fontSize: 11, color: 'var(--text)', marginTop: 2, wordBreak: 'break-word' }}>{error}</div>
+ <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>{t('capture_error_hint')}</div>
+ </div>
+ </div>
+ )
+}
+
/** EN: WebSocket status badge.
* FR: Badge de statut WebSocket. */
function StatusBadge({ status }) {
diff --git a/frontend/src/hooks/useWebSocket.js b/frontend/src/hooks/useWebSocket.js
index b7a625b..01e7a7d 100644
--- a/frontend/src/hooks/useWebSocket.js
+++ b/frontend/src/hooks/useWebSocket.js
@@ -54,6 +54,7 @@ export function useWebSocket(url) {
const [status, setStatus] = useState('connecting')
const [bandwidth, setBandwidth] = useState([])
const [capturing, setCapturing] = useState(true)
+ const [captureError, setCaptureError] = useState(null)
const [portFilter, setPortFilter] = useState([])
const [excludedProcesses, setExcludedProcesses] = useState([])
const [whitelistedIps, setWhitelistedIps] = useState([])
@@ -148,6 +149,7 @@ export function useWebSocket(url) {
if (msg.type === 'init') {
if (msg.media) setMedia(msg.media)
if (msg.capturing !== undefined) setCapturing(msg.capturing)
+ if ('capture_error' in msg) setCaptureError(msg.capture_error)
if (msg.ports !== undefined) setPortFilter(msg.ports)
if (msg.excluded_processes !== undefined) setExcludedProcesses(msg.excluded_processes)
if (msg.whitelisted_ips !== undefined) setWhitelistedIps(msg.whitelisted_ips)
@@ -247,6 +249,7 @@ export function useWebSocket(url) {
// FR: Le statut capture/filtres a changé (action locale ou distante).
if (msg.type === 'capture_status') {
setCapturing(msg.capturing)
+ if ('capture_error' in msg) setCaptureError(msg.capture_error)
if (msg.ports !== undefined) setPortFilter(msg.ports)
if (msg.excluded_processes !== undefined) setExcludedProcesses(msg.excluded_processes)
if (msg.whitelisted_ips !== undefined) setWhitelistedIps(msg.whitelisted_ips)
@@ -367,5 +370,5 @@ export function useWebSocket(url) {
setWatchlist(data.items)
}
- return { nodes, edges, lanDevices, packets, alerts, unread, clearUnread, status, bandwidth, capturing, toggleCapture, portFilter, updatePortFilter, excludedProcesses, updateProcessFilter, whitelistedIps, updateIpWhitelist, media, ssid, iface, watchlist, updateWatchlist }
+ return { nodes, edges, lanDevices, packets, alerts, unread, clearUnread, status, bandwidth, capturing, captureError, toggleCapture, portFilter, updatePortFilter, excludedProcesses, updateProcessFilter, whitelistedIps, updateIpWhitelist, media, ssid, iface, watchlist, updateWatchlist }
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index f81979b..53bfeb2 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -154,6 +154,8 @@ export default {
capture_start: 'Start',
capture_stopping: 'Stoppe…',
capture_starting: 'Starte…',
+ capture_error_title: 'Aufzeichnung fehlgeschlagen — es wird kein Traffic angezeigt',
+ capture_error_hint: 'Snitch mit Aufzeichnungsrechten neu starten (Admin unter Windows — Npcap erforderlich, sudo unter macOS/Linux) oder zum Wiederholen Start drücken.',
// Port filter / Port-Filter
port_filter: 'Ports',
diff --git a/frontend/src/locales/en.js b/frontend/src/locales/en.js
index db954d3..b02d4d3 100644
--- a/frontend/src/locales/en.js
+++ b/frontend/src/locales/en.js
@@ -158,6 +158,8 @@ export default { // Navigation
capture_start: 'Start',
capture_stopping: 'Stopping…',
capture_starting: 'Starting…',
+ capture_error_title: 'Capture failed — no traffic will show',
+ capture_error_hint: 'Restart Snitch with capture privileges (admin on Windows — Npcap required, sudo on macOS/Linux) or press Start to retry.',
// Port filter / Filtre de ports
port_filter: 'Ports',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 784dc04..1140717 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -152,6 +152,8 @@ export default { // Navegación
capture_start: 'Iniciar',
capture_stopping: 'Deteniendo…',
capture_starting: 'Iniciando…',
+ capture_error_title: 'Error de captura: no se mostrará tráfico',
+ capture_error_hint: 'Reinicia Snitch con privilegios de captura (administrador en Windows — Npcap requerido, sudo en macOS/Linux) o pulsa Iniciar para reintentar.',
// Filtro de puertos
port_filter: 'Puertos',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 8ebb49c..8b4331a 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -154,6 +154,8 @@ export default { // Navigation
capture_start: 'Démarrer',
capture_stopping: 'Arrêt…',
capture_starting: 'Démarrage…',
+ capture_error_title: "Échec de la capture — aucun trafic ne s'affichera",
+ capture_error_hint: "Relancez Snitch avec les droits de capture (admin sous Windows — Npcap requis, sudo sous macOS/Linux) ou appuyez sur Démarrer pour réessayer.",
// Filtre de ports / Port filter
port_filter: 'Ports',
diff --git a/frontend/src/locales/ja.js b/frontend/src/locales/ja.js
index e24c049..fa2be74 100644
--- a/frontend/src/locales/ja.js
+++ b/frontend/src/locales/ja.js
@@ -154,6 +154,8 @@ export default {
capture_start: '開始',
capture_stopping: '停止中…',
capture_starting: '開始中…',
+ capture_error_title: 'キャプチャに失敗しました — トラフィックは表示されません',
+ capture_error_hint: 'キャプチャ権限で Snitch を再起動してください(Windows では管理者+Npcap 必須、macOS/Linux では sudo)、または「開始」で再試行。',
// ポートフィルター
port_filter: 'ポート',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 625f625..4417eeb 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -154,6 +154,8 @@ export default {
capture_start: 'Iniciar',
capture_stopping: 'Parando…',
capture_starting: 'Iniciando…',
+ capture_error_title: 'Falha na captura — nenhum tráfego será exibido',
+ capture_error_hint: 'Reinicie o Snitch com privilégios de captura (admin no Windows — Npcap obrigatório, sudo no macOS/Linux) ou pressione Iniciar para tentar de novo.',
// Filtro de portas
port_filter: 'Portas',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 7b59ff3..ffa26ac 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -154,6 +154,8 @@ export default {
capture_start: 'Старт',
capture_stopping: 'Остановка…',
capture_starting: 'Запуск…',
+ capture_error_title: 'Ошибка захвата — трафик не будет отображаться',
+ capture_error_hint: 'Перезапустите Snitch с правами захвата (администратор в Windows — требуется Npcap, sudo в macOS/Linux) или нажмите «Старт» для повтора.',
// Фильтр портов
port_filter: 'Порты',
diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.js
index ea92c69..fa10a55 100644
--- a/frontend/src/locales/zh-CN.js
+++ b/frontend/src/locales/zh-CN.js
@@ -154,6 +154,8 @@ export default {
capture_start: '开始',
capture_stopping: '停止中…',
capture_starting: '启动中…',
+ capture_error_title: '抓包失败 — 将不会显示任何流量',
+ capture_error_hint: '请以抓包权限重启 Snitch(Windows 需管理员权限并安装 Npcap,macOS/Linux 需 sudo),或点击“开始”重试。',
// 端口过滤
port_filter: '端口',