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.
Python cybersecurityd3jsebpfedrelectronfastapifirewallfleet-managementlinuxlittle-snitch-alternativemacosnetwork-monitornetwork-securitypacket-captureprivacyreactrustself-hostedsiemwindows
Corriger le démarrage et la capture de l'app Windows (#14)
aiXis13cadda77a1a
diff --git a/CITATION.cff b/CITATION.cffindex 1687d80..83fa96d 100644--- a/CITATION.cff+++ b/CITATION.cff@@ -17,5 +17,5 @@ keywords:- privacy- traffic visualization- cybersecurity-version: "1.1.0"+version: "1.0.4"date-released: "2026-10-01"diff --git a/README.md b/README.mdindex fc8e8d8..cc90a60 100644--- a/README.md+++ b/README.md@@ -169,16 +169,19 @@ cd frontend && npm test```bash# 1 — Compile backend (PyInstaller)cd backend-pip install pyinstaller+pip install -r requirements.txt pyinstallerpyinstaller backend.spec --distpath ../dist/backend# 2 — Build frontend-cd frontend+cd ../frontend+npm cinpm run build-# 3 — Build Electron installer-cd electron-npm run build:dir+# 3 — Build Electron installer (the icon is generated automatically)+cd ../electron+npm ci+npm run build # NSIS installer -> dist/installer/Snitch Setup <version>.exe+# npm run build:dir # unpacked app only -> dist/installer/win-unpacked/```### Project structurediff --git a/backend/api/main.py b/backend/api/main.pyindex 2ff23d2..e301d68 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -89,6 +89,7 @@ from scanner.arp_scanner import ARPScanner, Device, default_gateway as _default_from scanner.arp_scanner import READ_STATS as _arp_statsfrom detection.anomaly import AnomalyDetectorimport storage.db as db+from version import __version__logger = logging.getLogger("snitch.api")@@ -1400,7 +1401,7 @@ async def get_diagnostics() -> dict:db_file = data_dir() / "snitch.db"return {- "version": "1.1.0",+ "version": __version__,"python": platform.python_version(),"platform": platform.platform(),"capture": {diff --git a/backend/capture/pcap.py b/backend/capture/pcap.pyindex 77cf934..c4f2908 100644--- a/backend/capture/pcap.py+++ b/backend/capture/pcap.py@@ -31,6 +31,7 @@ FR: Liaison ctypes minimale et sans dépendance vers la bibliothèque système dimport ctypesimport ctypes.utilimport logging+import socketimport sysfrom dataclasses import dataclassfrom typing import Optional@@ -226,6 +227,34 @@ class PcapDevice:name: strdescription: strloopback: bool = False+ # EN: IPv4/IPv6 addresses owned by the device, as reported by libpcap.+ # Needed on Windows, where Npcap names (\Device\NPF_{GUID}) never+ # match psutil's friendly names ("Ethernet 2").+ # FR: Adresses IPv4/IPv6 du périphérique, telles que rapportées par+ # libpcap. Indispensable sous Windows, où les noms Npcap+ # (\Device\NPF_{GUID}) ne correspondent jamais aux noms+ # conviviaux de psutil (« Ethernet 2 »).+ addresses: tuple[str, ...] = ()+++def _sockaddr_ip(ptr: Optional[int]) -> Optional[str]:+ """+ EN: Decode a `struct sockaddr *` into an IP string (IPv4/IPv6 only).+ BSD/macOS start with a 1-byte sa_len then a 1-byte family; Windows+ and Linux use a 2-byte little-endian family.+ FR: Décoder un `struct sockaddr *` en chaîne IP (IPv4/IPv6 seulement).+ BSD/macOS commencent par sa_len sur 1 octet puis la famille sur 1+ octet ; Windows et Linux utilisent une famille sur 2 octets LE.+ """+ if not ptr:+ return None+ raw = ctypes.string_at(ptr, 24)+ family = raw[1] if sys.platform == "darwin" else int.from_bytes(raw[0:2], "little")+ if family == socket.AF_INET:+ return socket.inet_ntop(socket.AF_INET, raw[4:8])+ if family == socket.AF_INET6:+ return socket.inet_ntop(socket.AF_INET6, raw[8:24])+ return Nonedef list_devices() -> list[PcapDevice]:@@ -245,8 +274,16 @@ def list_devices() -> list[PcapDevice]:d = cur.contentsname = d.name.decode(errors="replace") if d.name else ""desc = d.description.decode(errors="replace") if d.description else ""+ addrs = []+ a = d.addresses+ while a:+ ip = _sockaddr_ip(a.contents.addr)+ if ip:+ addrs.append(ip)+ a = a.contents.nextout.append(PcapDevice(name=name, description=desc,- loopback=bool(d.flags & 0x1)))+ loopback=bool(d.flags & 0x1),+ addresses=tuple(addrs)))cur = d.nextreturn outfinally:diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.pyindex 8cb0318..deaf7fe 100644--- a/backend/capture/sniffer.py+++ b/backend/capture/sniffer.py@@ -47,6 +47,26 @@ logger = logging.getLogger("snitch.capture.sniffer")PCAP_AVAILABLE = is_available()+def _default_route_ip() -> Optional[str]:+ """+ EN: Local IP the OS would use for outbound traffic. A UDP connect() only+ asks the routing table — no packet is ever sent (zero outbound+ calls, as promised).+ FR: IP locale que l'OS utiliserait pour le trafic sortant. Un connect()+ UDP interroge seulement la table de routage — aucun paquet n'est+ envoyé (zéro appel sortant, comme promis).+ """+ for family, target in ((socket.AF_INET, "192.0.2.1"),+ (socket.AF_INET6, "2001:db8::1")):+ try:+ with socket.socket(family, socket.SOCK_DGRAM) as s:+ s.connect((target, 9))+ return s.getsockname()[0].split("%")[0]+ except OSError:+ continue+ return None++@dataclassclass Packet:"""@@ -205,18 +225,32 @@ class PacketSniffer:a non-loopback local IP (macOS's "ap1" AWDL device is listedbefore the real Wi-Fi "en1": picking blindly by order capturedAirDrop chatter and missed every real packet — frames: 0).- Order: device owning a local IP → default-route iface → first- non-loopback.+ Order: device owning the default-route source IP → device owning+ a local IP → first non-loopback. The default-route step matters+ on Windows, where WSL/Hyper-V virtual adapters are listed first+ and also own private IPs.FR: L'interface qui porte réellement NOTRE trafic — celle quipossède une IP locale non-loopback (« ap1 » AWDL de macOS estlistée avant le vrai Wi-Fi « en1 » : choisir à l'aveuglecapturait le bavardage AirDrop et ratait chaque vrai paquet —frames : 0). Ordre : périphérique possédant une IP locale →- interface de la route par défaut → premier non-loopback.+ interface de la route par défaut → premier non-loopback. L'étape+ route par défaut compte sous Windows, où les cartes virtuelles+ WSL/Hyper-V sont listées en premier et possèdent aussi des IP+ privées."""try:devs = list_devices()names = {d.name for d in devs}+ # EN: Match on libpcap's own addresses first (works on Windows,+ # where Npcap names differ from psutil's friendly names).+ # FR: Correspondance d'abord sur les adresses de libpcap (marche+ # sous Windows, où les noms Npcap diffèrent de ceux de psutil).+ route_ip = _default_route_ip()+ if route_ip:+ for d in devs:+ if route_ip in d.addresses:+ return d.name# EN: iface → its IPv4/IPv6 addresses via psutil (same source as# self.local_ips, so the match is consistent).# FR: interface → ses adresses IPv4/IPv6 via psutil (même sourcediff --git a/backend/run_backend.py b/backend/run_backend.pyindex 81db7d5..f29f994 100644--- a/backend/run_backend.py+++ b/backend/run_backend.py@@ -31,6 +31,15 @@ if getattr(sys, 'frozen', False):if bundle_dir not in sys.path:sys.path.insert(0, bundle_dir)+# EN: console=False PyInstaller builds on Windows have no stdout/stderr (None),+# which crashes uvicorn's log formatter (isatty) at startup.+# FR: Les builds PyInstaller console=False sous Windows n'ont pas de+# stdout/stderr (None), ce qui fait planter le formateur de uvicorn (isatty).+if sys.stdout is None:+ sys.stdout = open(os.devnull, 'w', encoding='utf-8')+if sys.stderr is None:+ sys.stderr = open(os.devnull, 'w', encoding='utf-8')+# EN: Configure logging BEFORE importing app modules so they inherit handlers.# FR: Configurer les logs AVANT d'importer les modules pour qu'ils héritent des handlers.from logging_config import setup_logging # noqa: E402diff --git a/backend/tests/test_capture_iface.py b/backend/tests/test_capture_iface.pynew file mode 100644index 0000000..809b5c4--- /dev/null+++ b/backend/tests/test_capture_iface.py@@ -0,0 +1,77 @@+"""+Snitch — capture interface selection tests (no libpcap, no real traffic).++EN: Covers sockaddr decoding of libpcap device addresses and the default+ interface choice: the device owning the default-route IP must win over+ virtual adapters listed first (WSL/Hyper-V on Windows).+FR: Couvre le décodage sockaddr des adresses de périphériques libpcap et le+ choix de l'interface par défaut : le périphérique qui possède l'IP de la+ route par défaut doit l'emporter sur les cartes virtuelles listées en+ premier (WSL/Hyper-V sous Windows).+"""++import ctypes+import socket+import struct+import sys++import capture.pcap as pcap+import capture.sniffer as sniffer+from capture.pcap import PcapDevice+++def _sockaddr_in(ip: str) -> ctypes.Array:+ """EN: Platform-shaped sockaddr_in buffer. / FR: Buffer sockaddr_in au format de la plateforme."""+ if sys.platform == "darwin":+ head = bytes([16, socket.AF_INET])+ else:+ head = struct.pack("<H", socket.AF_INET)+ raw = head + bytes(2) + socket.inet_aton(ip) + bytes(16)+ return ctypes.create_string_buffer(raw, len(raw))+++def _sockaddr_in6(ip: str) -> ctypes.Array:+ """EN: Platform-shaped sockaddr_in6 buffer. / FR: Buffer sockaddr_in6 au format de la plateforme."""+ if sys.platform == "darwin":+ head = bytes([28, socket.AF_INET6])+ else:+ head = struct.pack("<H", socket.AF_INET6)+ raw = head + bytes(6) + socket.inet_pton(socket.AF_INET6, ip) + bytes(4)+ return ctypes.create_string_buffer(raw, len(raw))+++def test_sockaddr_ipv4():+ buf = _sockaddr_in("192.168.1.42")+ assert pcap._sockaddr_ip(ctypes.addressof(buf)) == "192.168.1.42"+++def test_sockaddr_ipv6():+ buf = _sockaddr_in6("2001:db8::7")+ assert pcap._sockaddr_ip(ctypes.addressof(buf)) == "2001:db8::7"+++def test_sockaddr_null():+ assert pcap._sockaddr_ip(None) is None+++def test_default_iface_prefers_default_route(monkeypatch):+ devs = [+ PcapDevice(r"\Device\NPF_{WSL}", "vEthernet (WSL)", addresses=("172.20.0.1",)),+ PcapDevice(r"\Device\NPF_{ETH}", "Ethernet 2", addresses=("10.0.0.5",)),+ PcapDevice(r"\Device\NPF_Loopback", "Loopback", loopback=True,+ addresses=("127.0.0.1",)),+ ]+ monkeypatch.setattr(sniffer, "list_devices", lambda: devs)+ monkeypatch.setattr(sniffer, "_default_route_ip", lambda: "10.0.0.5")+ assert sniffer.PacketSniffer._default_iface() == r"\Device\NPF_{ETH}"+++def test_default_iface_falls_back_without_route(monkeypatch):+ devs = [+ PcapDevice("lo0", "", loopback=True),+ PcapDevice("en0", "", addresses=("192.168.1.2",)),+ ]+ monkeypatch.setattr(sniffer, "list_devices", lambda: devs)+ monkeypatch.setattr(sniffer, "_default_route_ip", lambda: None)+ monkeypatch.setattr(sniffer.psutil, "net_if_addrs", lambda: {})+ assert sniffer.PacketSniffer._default_iface() == "en0"diff --git a/backend/version.py b/backend/version.pynew file mode 100644index 0000000..d00d92f--- /dev/null+++ b/backend/version.py@@ -0,0 +1,8 @@+"""+EN: Single source of truth for the backend version (shown in /diagnostics).+ Keep in sync with electron/package.json and frontend/package.json.+FR: Source unique de la version du backend (affichée dans /diagnostics).+ À garder alignée avec electron/package.json et frontend/package.json.+"""++__version__ = "1.0.4"diff --git a/electron/main.js b/electron/main.jsindex a165b8e..62fcdfb 100644--- a/electron/main.js+++ b/electron/main.js@@ -204,6 +204,28 @@ async function offerNpcapDownload() {}// ── Windows / Fenêtres ───────────────────────────────────────────────────────+/**+ * EN: The splash is always-on-top — drop it below dialogs, otherwise it hides+ * the very error the user needs to read.+ * FR: Le splash est toujours au premier plan — le passer sous les dialogues,+ * sinon il masque justement l'erreur que l'utilisateur doit lire.+ */+function lowerSplash() {+ if (splashWindow && !splashWindow.isDestroyed()) {+ splashWindow.setAlwaysOnTop(false)+ splashWindow.hide()+ }+}++/** EN: Bring the splash back after a dialog (retry path).+ * FR: Réafficher le splash après un dialogue (chemin « réessayer »). */+function raiseSplash() {+ if (splashWindow && !splashWindow.isDestroyed()) {+ splashWindow.setAlwaysOnTop(true)+ splashWindow.show()+ }+}+function createSplash() {/** EN: Frameless transparent splash shown while the backend boots.* FR: Splash sans cadre et transparent affiché pendant le démarrage du backend. */@@ -575,15 +597,21 @@ app.whenReady().then(async () => {await waitForBackend(backendElevated ? 90 : 40)booted = true} catch (e) {+ lowerSplash()if (!backendElevated) {dialog.showErrorBox('Snitch', `Backend unavailable / Backend indisponible :\n${e.message}`)app.quit(); return}const choice = await dialog.showMessageBox({type: 'warning', title: 'Snitch',- message: 'The admin prompt was declined or timed out. Capture needs it to watch traffic.\n' +- 'L\'invite administrateur a été refusée ou a expiré. La capture en a besoin pour observer le trafic.',- detail: `Backend unavailable / Backend indisponible : ${e.message}`,+ // EN: Don't guess the cause — a crashing backend looks exactly like a+ // declined prompt from here. Point to the log that tells which.+ // FR: Ne pas deviner la cause — un backend qui plante ressemble ici+ // exactement à une invite refusée. Pointer vers le log qui le dit.+ message: 'The capture backend did not start (admin prompt declined or timed out, or backend error).\n' ++ 'Le backend de capture n\'a pas démarré (invite administrateur refusée ou expirée, ou erreur du backend).',+ detail: `Backend unavailable / Backend indisponible : ${e.message}\n` ++ `Logs / Journaux : ${logDir}`,buttons: ['Retry / Réessayer','Continue without capture / Continuer sans capture',@@ -603,6 +631,7 @@ app.whenReady().then(async () => {app.quit(); return}}+ raiseSplash()// EN: response 0 loops back to launchBackend() → fresh admin prompt.// FR: la réponse 0 reboucle vers launchBackend() → nouvelle invite admin.}diff --git a/electron/package.json b/electron/package.jsonindex 58dddda..ec46bc7 100644--- a/electron/package.json+++ b/electron/package.json@@ -6,7 +6,10 @@"license": "AGPL-3.0-or-later","scripts": {"start": "electron .",+ "icon": "node generate-icon.js",+ "prebuild": "npm run icon","build": "electron-builder --win --x64",+ "prebuild:dir": "npm run icon","build:dir": "electron-builder --win --x64 --dir"},"devDependencies": {@@ -42,7 +45,8 @@],"win": {"target": "nsis",- "requestedExecutionLevel": "asInvoker"+ "requestedExecutionLevel": "asInvoker",+ "icon": "icon.png"},"nsis": {"oneClick": false,diff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsxindex 47b90ed..b7636b5 100644--- a/frontend/src/components/AlertPanel.jsx+++ b/frontend/src/components/AlertPanel.jsx@@ -89,7 +89,7 @@ export function AlertPanel({ alerts, onClose, onIgnore }) {_grouped: true,})}- rows.sort((a, b) => new Date(b.timestamp + 'Z') - new Date(a.timestamp + 'Z'))+ rows.sort((a, b) => parseTs(b.timestamp) - parseTs(a.timestamp))return (<div style={{@@ -197,9 +197,22 @@ function AlertRow({ alert, onIgnore }) {)}+/**+ * 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. */-function timeAgo(iso, t) {- const diff = Math.floor((Date.now() - new Date(iso + 'Z')) / 1000)+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))diff --git a/frontend/src/components/AlertPanel.test.js b/frontend/src/components/AlertPanel.test.jsnew file mode 100644index 0000000..d1f52a3--- /dev/null+++ b/frontend/src/components/AlertPanel.test.js@@ -0,0 +1,31 @@+/**+ * Snitch — alert timestamp tests (Vitest).+ *+ * EN: Backend alerts carry ISO 8601 timestamps WITH an offset ("+00:00");+ * the relative time must never render as "NaNh ago".+ * FR: Les alertes du backend portent des horodatages ISO 8601 AVEC décalage+ * (« +00:00 ») ; le temps relatif ne doit jamais afficher « NaNh ago ».+ */+import { describe, it, expect } from 'vitest'+import { parseTs, timeAgo } from './AlertPanel'++const t = (key, n) => `${key}:${n ?? ''}`+const NOW = Date.parse('2026-10-05T12:00:00Z')++describe('parseTs', () => {+ it('parses offset, Z and naive timestamps as UTC', () => {+ expect(parseTs('2026-10-05T11:00:00+00:00').getTime()).toBe(NOW - 3600e3)+ expect(parseTs('2026-10-05T11:00:00Z').getTime()).toBe(NOW - 3600e3)+ expect(parseTs('2026-10-05T11:00:00').getTime()).toBe(NOW - 3600e3)+ })+})++describe('timeAgo', () => {+ it('formats backend offset timestamps', () => {+ expect(timeAgo('2026-10-05T11:59:30.123456+00:00', t, NOW)).toBe('time_seconds:29')+ expect(timeAgo('2026-10-05T10:00:00+00:00', t, NOW)).toBe('time_hours:2')+ })+ it('never returns NaN', () => {+ expect(timeAgo('garbage', t, NOW)).toBe('')+ })+})diff --git a/pyproject.toml b/pyproject.tomlindex 943388d..dc2fc37 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -15,7 +15,7 @@ build-backend = "setuptools.build_meta"[project]name = "snitch"-version = "1.1.0"+version = "1.0.4"description = "Real-time network traffic visualizer — EN/FR, privacy-first, local-only"readme = "README.md"license = { text = "AGPL-3.0-or-later" }@@ -38,7 +38,7 @@ packages = ["api", "capture", "classifier", "detection", "resolver", "scanner","storage",]-py-modules = ["cli", "paths", "logging_config", "run_backend"]+py-modules = ["cli", "paths", "logging_config", "run_backend", "version"]# EN: The built frontend ships inside the wheel — `npm run build` output is# expected at frontend/dist and gets copied to backend/frontend_dist by