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
feat: persisted alert suppression, traffic history, settings & apps views
MoneyLisa8c7a26ab694d
diff --git a/README.md b/README.mdindex 429df13..fe51ca4 100644--- a/README.md+++ b/README.md@@ -51,10 +51,14 @@ The entire interface is available in **English and French**: use the `EN / FR` t- **API token** — every REST endpoint and the WebSocket require a token. Electron generates it per launch; in Docker/browser it's printed once in the backend logs and stored in `data/api_token.txt`. Open the UI with `http://localhost:8000/?token=<TOKEN>` (or enter it when prompted).- **Loopback-only by default** — the API binds `127.0.0.1` in every mode. Set `SNITCH_BIND=0.0.0.0` only if you explicitly want LAN access (token auth still applies).- **CORS/WebSocket origin allowlist** — only `localhost:5173`, the backend's own origin and Electron `file://` pages may connect.-- **Geolocation is offline-only** — there is *no* online lookup. Drop `dbip-city-lite.mmdb` + `dbip-asn-lite.mmdb` ([DB-IP Lite](https://db-ip.com/db/lite.php), CC BY 4.0) or `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) into `<data_dir>/geo/` for local lookups. Without a DB, IPs simply show no geo — nothing is ever sent to a third party.-- **All data stays local** — `snitch.db` (24 h sliding window, configurable via `retention_hours` setting) and `data/logs/snitch.log` never leave the machine. No telemetry, no outbound calls.-- **Settings persist** — port filters, excluded processes and the IP whitelist are stored in SQLite and restored on restart.+- **Geolocation is offline-only** — there is *no* online lookup. Drop `dbip-city-lite.mmdb` + `dbip-asn-lite.mmdb` ([DB-IP Lite](https://db-ip.com/db/lite.php), CC BY 4.0) or `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) into `<data_dir>/geo/` for local lookups — or download DB-IP Lite from the Settings panel (explicit consent, the only possible outbound call). Without a DB, IPs simply show no geo.+- **All data stays local** — `snitch.db` (24 h sliding window, configurable via `retention_hours` setting) and `data/logs/snitch.log` never leave the machine. No telemetry. The **only** possible outbound call is the opt-in DB-IP Lite download (Settings → "Download DB-IP Lite"), which requires an explicit click.+- **Settings persist** — port filters, excluded processes, the IP whitelist, language and retention are stored in SQLite and restored on restart.+- **Alert suppression** — each alert has an "Ignore this type/host" action; suppression rules are persisted (`alert_suppressions` table), applied before alerts are emitted or logged, and survivable across restarts via `POST /alerts/ignore` / `DELETE /alerts/ignore` / `GET /alerts/ignore`.+- **History** — per-minute per-host and per-process byte/packet aggregates are kept in SQLite (`host_history`, `process_history`) for the retention window, powering the per-application view and `GET /history/host/{ip}` / `GET /history/process/{name}`.+- **Diagnostics** — `GET /diagnostics` returns a JSON snapshot of the runtime (capture state, geo DB status, interface, versions, paths) with no secrets; the Settings panel can export it or open the log directory (Electron).- **LAN devices** are discovered passively from the system ARP table — no active broadcast scanning.+- See [docs/threat-model.md](docs/threat-model.md) for the full threat model.### Docker (Linux)@@ -185,10 +189,14 @@ Toute l'interface est disponible en **français et en anglais** : utilisez le s- **Jeton API** — chaque endpoint REST et le WebSocket exigent un jeton. Electron le génère à chaque lancement ; sous Docker/navigateur il est affiché une fois dans les logs du backend et stocké dans `data/api_token.txt`. Ouvrez l'UI via `http://localhost:8000/?token=<JETON>` (ou saisissez-le à l'invite).- **Loopback uniquement par défaut** — l'API écoute sur `127.0.0.1` dans tous les modes. Ne mettez `SNITCH_BIND=0.0.0.0` que pour un accès LAN explicite (le jeton reste exigé).- **Liste blanche CORS/Origin WebSocket** — seuls `localhost:5173`, l'origine propre du backend et les pages `file://` d'Electron peuvent se connecter.-- **Géolocalisation 100 % hors ligne** — il n'y a *aucune* recherche en ligne. Déposez `dbip-city-lite.mmdb` + `dbip-asn-lite.mmdb` ([DB-IP Lite](https://db-ip.com/db/lite.php), CC BY 4.0) ou `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) dans `<data_dir>/geo/`. Sans base, les IP n'ont simplement pas de géo — rien n'est jamais envoyé à un tiers.-- **Toutes les données restent locales** — `snitch.db` (fenêtre glissante de 24 h, configurable via le réglage `retention_hours`) et `data/logs/snitch.log` ne quittent jamais la machine. Pas de télémétrie, aucun appel sortant.-- **Réglages persistés** — filtres de ports, processus exclus et whitelist IP sont stockés dans SQLite et restaurés au redémarrage.+- **Géolocalisation 100 % hors ligne** — il n'y a *aucune* recherche en ligne. Déposez `dbip-city-lite.mmdb` + `dbip-asn-lite.mmdb` ([DB-IP Lite](https://db-ip.com/db/lite.php), CC BY 4.0) ou `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) dans `<data_dir>/geo/` — ou téléchargez DB-IP Lite depuis le panneau Réglages (consentement explicite, seul appel sortant possible). Sans base, les IP n'ont simplement pas de géo.+- **Toutes les données restent locales** — `snitch.db` (fenêtre glissante de 24 h, configurable via le réglage `retention_hours`) et `data/logs/snitch.log` ne quittent jamais la machine. Pas de télémétrie. Le **seul** appel sortant possible est le téléchargement opt-in de DB-IP Lite (Réglages → « Télécharger DB-IP Lite »), qui exige un clic explicite.+- **Réglages persistés** — filtres de ports, processus exclus, whitelist IP, langue et rétention sont stockés dans SQLite et restaurés au redémarrage.+- **Suppression d'alertes** — chaque alerte offre « Ignorer ce type/cet hôte » ; les règles sont persistées (`alert_suppressions`), appliquées avant émission, et gérables via `POST /alerts/ignore`, `DELETE /alerts/ignore`, `GET /alerts/ignore`.+- **Historique** — les agrégats octets/paquets par minute, par hôte et par processus sont conservés dans SQLite (`host_history`, `process_history`) sur la fenêtre de rétention, et alimentent la vue par application ainsi que `GET /history/host/{ip}` et `GET /history/process/{nom}`.+- **Diagnostic** — `GET /diagnostics` renvoie un instantané JSON du runtime (état de capture, géo, interface, versions, chemins) sans secrets ; le panneau Réglages peut l'exporter ou ouvrir le dossier des logs (Electron).- **Appareils LAN** découverts passivement via la table ARP système — aucun scan broadcast actif.+- Voir [docs/threat-model.md](docs/threat-model.md) pour le modèle de menace complet.### Docker (Linux)diff --git a/backend/api/main.py b/backend/api/main.pyindex e819af5..f84b219 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -67,6 +67,7 @@ import timefrom contextlib import asynccontextmanagerfrom datetime import datetime, timezonefrom pathlib import Path+from typing import Optionalfrom fastapi import Depends, FastAPI, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddleware@@ -148,6 +149,20 @@ class SettingsBody(BaseModel):settings: dict = Field(default_factory=dict)+class IgnoreBody(BaseModel):+ """EN: /alerts/ignore payload — suppress a host, a type, or both.+ FR: Charge utile de /alerts/ignore — supprimer un hôte, un type, ou les deux."""+ type: Optional[str] = None+ ip: Optional[str] = None+++class GeoDownloadBody(BaseModel):+ """EN: /geo/download payload — explicit consent is REQUIRED, this is the+ only outbound call in the whole app. / FR: Charge utile de /geo/download —+ consentement explicite OBLIGATOIRE, c'est le seul appel sortant de l'app."""+ consent: bool = False++# ── Broadcast / Diffusion ────────────────────────────────────────────────────async def broadcast(message: dict) -> None:@@ -396,8 +411,13 @@ def _process_batch(packets: list[Packet]) -> None:edge["bytes"] += pkt.sizeedge["packets"] += 1- db.accumulate(datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M"),- category.category, pkt.size)+ minute = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M")+ db.accumulate(minute, category.category, pkt.size)+ # EN: Per-entity history — feeds the per-host and per-app views.+ # FR: Historique par entité — alimente les vues par hôte et par app.+ db.accumulate_history(minute, "host", remote_ip, pkt.size)+ if pkt.process_name:+ db.accumulate_history(minute, "process", pkt.process_name, pkt.size)# EN: Detection runs in the event loop — analyze_packet is# lock-guarded internally, no executor hop needed.@@ -587,7 +607,8 @@ def _start_capture() -> None:"""EN: (Re)start sniffer + ARP-table scanner in daemon threads.FR: (Re)démarrer sniffer + scanner de table ARP dans des threads daemon."""global _sniffer, _scanner, _capturing- _sniffer = PacketSniffer(callback=on_packet, ports=_port_filter)+ _sniffer = PacketSniffer(callback=on_packet, ports=_port_filter,+ iface=db.get_setting("interface"))threading.Thread(target=_sniffer.start, daemon=True).start()_scanner = ARPScanner(callback=on_device, interval=30)threading.Thread(target=_scanner.start, daemon=True).start()@@ -617,6 +638,7 @@ def _load_settings() -> None:_port_filter = db.get_setting("ports", []) or []_excluded_processes = set(db.get_setting("excluded_processes", []) or [])_whitelisted_ips = set(db.get_setting("whitelisted_ips", []) or [])+ detector.load_suppressions(db.get_setting("suppressions", []) or [])if _port_filter:logger.info("restored port filter: %s", _port_filter)@@ -900,6 +922,185 @@ async def get_timeline(minutes: int = 60) -> dict:return {"timeline": data}+# ── Alert suppression / Suppression d'alertes ────────────────────────────────+[email protected]("/alerts/ignore", dependencies=_AUTH)+async def ignore_alert(body: IgnoreBody) -> dict:+ """+ EN: Persisted "ignore this host / this type" — the rule is stored in the+ settings table AND pushed live into the detector so it takes effect+ immediately.+ FR: « Ignorer cet hôte / ce type » persisté — la règle est stockée dans+ settings ET poussée au détecteur pour prise d'effet immédiate.+ """+ suppressions = db.get_setting("suppressions", []) or []+ entry = {"type": body.type, "ip": body.ip}+ if entry not in suppressions and (body.type or body.ip):+ suppressions.append(entry)+ db.set_setting("suppressions", suppressions)+ detector.load_suppressions(suppressions)+ return {"suppressions": suppressions}++[email protected]("/alerts/ignore", dependencies=_AUTH)+async def list_ignored() -> dict:+ """EN: List active suppression rules.+ FR: Lister les règles de suppression actives."""+ return {"suppressions": db.get_setting("suppressions", []) or []}++[email protected]("/alerts/ignore", dependencies=_AUTH)+async def unignore_alert(body: IgnoreBody) -> dict:+ """EN: Remove a suppression rule — {type, ip} must match exactly.+ FR: Retirer une règle de suppression — {type, ip} doit correspondre."""+ suppressions = db.get_setting("suppressions", []) or []+ entry = {"type": body.type, "ip": body.ip}+ suppressions = [s for s in suppressions if s != entry]+ db.set_setting("suppressions", suppressions)+ detector.load_suppressions(suppressions)+ return {"suppressions": suppressions}+++# ── History / Historique ─────────────────────────────────────────────────────+[email protected]("/history/host/{ip}", dependencies=_AUTH)+async def get_host_history(ip: str, minutes: int = 60) -> dict:+ """EN: Per-host byte/packet history. / FR: Historique par hôte."""+ loop = asyncio.get_running_loop()+ return {"history": await loop.run_in_executor(+ None, db.get_history, "host", ip, minutes)}++[email protected]("/history/process/{name}", dependencies=_AUTH)+async def get_process_history(name: str, minutes: int = 60) -> dict:+ """EN: Per-process byte/packet history. / FR: Historique par processus."""+ loop = asyncio.get_running_loop()+ return {"history": await loop.run_in_executor(+ None, db.get_history, "process", name, minutes)}++[email protected]("/history/top_processes", dependencies=_AUTH)+async def get_top_processes(minutes: int = 60) -> dict:+ """EN: Top talkers by process — the Apps view data source.+ FR: Plus gros émetteurs par processus — la source de la vue Apps."""+ loop = asyncio.get_running_loop()+ return {"processes": await loop.run_in_executor(+ None, db.get_top_processes, minutes)}+++# ── Diagnostics / Diagnostic ────────────────────────────────────────────────+[email protected]("/diagnostics", dependencies=_AUTH)+async def get_diagnostics() -> dict:+ """+ EN: Sanitized support bundle: versions, capture status, settings, last+ 200 log lines, DB sizes. IPs/hostnames stay local — this is served+ only to the authenticated local user.+ FR: Paquet de support assaini : versions, état de capture, réglages, 200+ dernières lignes de log, tailles de la BDD. Les IP/noms d'hôtes+ restent locaux — servi uniquement à l'utilisateur local authentifié.+ """+ import platform+ from paths import data_dir++ log_tail = []+ log_file = data_dir() / "logs" / "snitch.log"+ try:+ if log_file.exists():+ log_tail = log_file.read_text(errors="replace").splitlines()[-200:]+ except OSError as exc:+ log_tail = [f"<log read failed: {exc}>"]++ db_file = data_dir() / "snitch.db"+ return {+ "version": "1.1.0",+ "python": platform.python_version(),+ "platform": platform.platform(),+ "capture": {+ "capturing": _capturing,+ "interface": db.get_setting("interface"),+ "ports": _port_filter,+ },+ "settings": db.all_settings(),+ "counts": {"nodes": len(nodes), "edges": len(edges),+ "lan_devices": len(lan_devices),+ "alerts_memory": len(detector.history)},+ "db_bytes": db_file.stat().st_size if db_file.exists() else 0,+ "log_tail": log_tail,+ }+++# ── GeoIP database download (consent-gated) / Téléchargement base GeoIP ─────++def _download_dbip() -> dict:+ """+ EN: Download DB-IP Lite City + ASN into <data_dir>/geo/. This is the ONE+ opt-in outbound call in the entire app — reached only via an explicit+ user action and the `consent` flag. HTTPS, 60 s timeout, gzip decompress.+ FR: Télécharger DB-IP Lite City + ASN dans <data_dir>/geo/. C'est le SEUL+ appel sortant opt-in de toute l'app — atteint uniquement via une+ action explicite et le drapeau `consent`. HTTPS, timeout 60 s,+ décompression gzip.+ """+ import gzip+ import urllib.request+ from paths import data_dir+ import resolver.dns_geo as dg++ month = datetime.now(timezone.utc).strftime("%Y-%m")+ files = {+ f"dbip-city-lite-{month}.mmdb.gz": "dbip-city-lite.mmdb",+ f"dbip-asn-lite-{month}.mmdb.gz": "dbip-asn-lite.mmdb",+ }+ geo_dir = data_dir() / "geo"+ geo_dir.mkdir(parents=True, exist_ok=True)++ downloaded = []+ errors = []+ for remote, local in files.items():+ url = f"https://download.db-ip.com/free/{remote}"+ try:+ req = urllib.request.Request(url, headers={"User-Agent": "Snitch/1.1"})+ with urllib.request.urlopen(req, timeout=60) as resp:+ data = gzip.decompress(resp.read())+ (geo_dir / local).write_bytes(data)+ downloaded.append(local)+ except Exception as exc:+ errors.append(f"{local}: {exc}")+ logger.error("geo download failed for %s: %s", url, exc)++ # EN: Force reader reload on next lookup.+ # FR: Forcer le rechargement des lecteurs à la prochaine recherche.+ dg.reset_readers()+ return {"downloaded": downloaded, "errors": errors, "dir": str(geo_dir)}++[email protected]("/geo/download", dependencies=_AUTH)+async def geo_download(body: GeoDownloadBody) -> dict:+ """+ EN: Consent-gated GeoIP DB download. Without consent=true the endpoint+ refuses — the default state of Snitch makes ZERO outbound calls.+ FR: Téléchargement de base GeoIP sous consentement. Sans consent=true le+ endpoint refuse — l'état par défaut de Snitch n'émet AUCUN appel+ sortant.+ """+ if not body.consent:+ return {"ok": False, "reason": "consent_required"}+ loop = asyncio.get_running_loop()+ result = await loop.run_in_executor(None, _download_dbip)+ result["ok"] = not result["errors"]+ return result++[email protected]("/geo/status", dependencies=_AUTH)+async def geo_status() -> dict:+ """EN: Which .mmdb files are present. / FR: Quels .mmdb sont présents."""+ from paths import data_dir+ geo_dir = data_dir() / "geo"+ present = sorted(p.name for p in geo_dir.glob("*.mmdb")) if geo_dir.exists() else []+ return {"databases": present, "dir": str(geo_dir)}++# ── WebSocket ────────────────────────────────────────────────────────────────@app.websocket("/ws")diff --git a/backend/capture/parser.py b/backend/capture/parser.pyindex e46a1ab..d3b7b20 100644--- a/backend/capture/parser.py+++ b/backend/capture/parser.py@@ -381,12 +381,16 @@ def parse_tls_sni(payload: bytes) -> Optional[str]:if len(body) < 34:return Noneoff = 2 + 32 # EN: version + random / FR: version + aléa- sid_len = body[off]; off += 1 + sid_len- cs_len = struct.unpack("!H", body[off:off + 2])[0]; off += 2 + cs_len- cm_len = body[off]; off += 1 + cm_len+ sid_len = body[off]+ off += 1 + sid_len+ cs_len = struct.unpack("!H", body[off:off + 2])[0]+ off += 2 + cs_len+ cm_len = body[off]+ off += 1 + cm_lenif off + 2 > len(body):return None- ext_total = struct.unpack("!H", body[off:off + 2])[0]; off += 2+ ext_total = struct.unpack("!H", body[off:off + 2])[0]+ off += 2ext_end = min(off + ext_total, len(body))while off + 4 <= ext_end:diff --git a/backend/detection/anomaly.py b/backend/detection/anomaly.pyindex 901f72e..832a458 100644--- a/backend/detection/anomaly.py+++ b/backend/detection/anomaly.py@@ -271,11 +271,38 @@ class AnomalyDetector:self._byte_window: dict[str, deque] = defaultdict(lambda: deque(maxlen=5000))self._byte_baseline: dict[str, deque] = defaultdict(lambda: deque(maxlen=10))self._byte_last_fold: dict[str, float] = {}++ # EN: User suppressions — persisted in the settings table, loaded at+ # startup. An entry is {"type": "BEACON"|None, "ip": "1.2.3.4"|None};+ # a packet is suppressed when BOTH non-None fields match.+ # FR: Suppressions utilisateur — persistées dans la table settings,+ # chargées au démarrage. Une entrée vaut+ # {"type": "BEACON"|None, "ip": "1.2.3.4"|None} ; un paquet est+ # supprimé quand les DEUX champs non-None correspondent.+ self._suppressions: list[dict] = []self._cooldowns: dict[str, float] = {}self.history: list[dict] = []self._mic_procs: set[str] = set()self._cam_procs: set[str] = set()+ def load_suppressions(self, items: list[dict]) -> None:+ """EN: Replace the suppression list (from persisted settings).+ FR: Remplacer la liste de suppression (depuis les réglages persistés)."""+ with self._lock:+ self._suppressions = [+ {"type": s.get("type"), "ip": s.get("ip")}+ for s in items if isinstance(s, dict)+ ]++ def _suppressed(self, alert_type: str, ip: str) -> bool:+ """EN: True when a suppression rule covers (type, ip) — either field+ may be None (=match all). / FR: True quand une règle de suppression+ couvre (type, ip) — chaque champ peut être None (= tout)."""+ for s in self._suppressions:+ if s["type"] in (None, alert_type) and s["ip"] in (None, ip):+ return True+ return False+def update_media_state(self, mic: list[str], camera: list[str]) -> None:"""EN: Sync mic/camera process sets from the media monitor.FR: Synchroniser les ensembles micro/caméra depuis le moniteur média."""@@ -338,6 +365,11 @@ class AnomalyDetector:alerts += self._check_beacon(remote_ip, geo)alerts += self._check_volume_spike(remote_ip, pkt, geo)alerts += self._check_media_exfil(pkt, remote_ip, geo)+ # EN: Drop suppressed alerts before recording — persisted+ # "ignore this host/type" rules from the UI.+ # FR: Écarter les alertes supprimées avant l'enregistrement —+ # règles « ignorer cet hôte/ce type » persistées depuis l'UI.+ alerts = [a for a in alerts if not self._suppressed(a.type, remote_ip)]self._record(alerts)return alerts@@ -370,6 +402,10 @@ class AnomalyDetector:details={"ip": device.ip, "host": label},))+ # EN: Device alerts honour suppressions too (keyed on the LAN ip).+ # FR: Les alertes d'appareil respectent aussi les suppressions+ # (clés sur l'IP LAN).+ alerts = [a for a in alerts if not self._suppressed(a.type, device.ip)]self._record(alerts)return alertsdiff --git a/backend/resolver/dns_geo.py b/backend/resolver/dns_geo.pyindex 060564d..eee8f35 100644--- a/backend/resolver/dns_geo.py+++ b/backend/resolver/dns_geo.py@@ -164,6 +164,21 @@ def resolve_hostname(ip: str) -> Optional[str]:# ── Geolocation / Géolocalisation ────────────────────────────────────────────+def reset_readers() -> None:+ """EN: Drop open .mmdb readers so a newly downloaded DB is picked up.+ FR: Refermer les lecteurs .mmdb pour prendre en compte une base fraîche."""+ global _readers+ with _readers_lock:+ for r in _readers.values():+ try:+ if r is not None:+ r.close()+ except Exception:+ pass+ _readers = {}+ resolve_geo.cache_clear()++def _get_reader(kind: str):"""EN: Lazy-open one .mmdb reader ('city' or 'asn'). Prefers DB-IP Litediff --git a/backend/storage/db.py b/backend/storage/db.pyindex 245656c..490a1a3 100644--- a/backend/storage/db.py+++ b/backend/storage/db.py@@ -49,6 +49,7 @@ _conn_lock = threading.Lock()# EN: In-memory write accumulator — (minute, category) -> [packets, bytes].# FR: Accumulateur d'écriture en mémoire — (minute, catégorie) -> [paquets, octets]._pending: dict[tuple, list] = defaultdict(lambda: [0, 0])+_pending_hist: dict[tuple, list] = defaultdict(lambda: [0, 0])_pending_lock = threading.Lock()@@ -115,6 +116,21 @@ def _init_schema(conn: sqlite3.Connection) -> None:key TEXT PRIMARY KEY,value TEXT NOT NULL);++ -- EN: Per-host and per-process byte/packet history, per minute.+ -- dim is 'host' or 'process'; key is the IP or process name.+ -- FR: Historique par hôte et par processus, en octets/paquets par+ -- minute. dim vaut 'host' ou 'process' ; key est l'IP ou le nom+ -- de processus.+ CREATE TABLE IF NOT EXISTS history (+ minute TEXT NOT NULL,+ dim TEXT NOT NULL,+ key TEXT NOT NULL,+ packets INTEGER DEFAULT 0,+ bytes INTEGER DEFAULT 0,+ PRIMARY KEY (minute, dim, key)+ );+ CREATE INDEX IF NOT EXISTS idx_history_lookup ON history(dim, key, minute);""")conn.commit()@@ -171,6 +187,18 @@ def accumulate(minute: str, category: str, size: int) -> None:_pending[(minute, category)][1] += size+def accumulate_history(minute: str, dim: str, key: str, size: int) -> None:+ """+ EN: Same zero-block pattern as accumulate(), but into the per-entity+ `history` table — one call per (remote host, owning process) pair.+ FR: Même schéma non-bloquant qu'accumulate(), vers la table `history` —+ un appel par couple (hôte distant, processus).+ """+ with _pending_lock:+ _pending_hist[(minute, dim, key)][0] += 1+ _pending_hist[(minute, dim, key)][1] += size++def flush() -> None:"""EN: Batch-write the accumulator to SQLite using UPSERT semantics.@@ -179,12 +207,15 @@ def flush() -> None:Appelé par le thread de flush toutes les ~10 s."""with _pending_lock:- if not _pending:+ if not _pending and not _pending_hist:returnbatch = dict(_pending)_pending.clear()+ hist_batch = dict(_pending_hist)+ _pending_hist.clear()rows = [(m, c, v[0], v[1]) for (m, c), v in batch.items()]+ hist_rows = [(m, d, k, v[0], v[1]) for (m, d, k), v in hist_batch.items()]try:with _conn_lock:conn = get_conn()@@ -195,6 +226,13 @@ def flush() -> None:packets = packets + excluded.packets,bytes = bytes + excluded.bytes""", rows)+ conn.executemany("""+ INSERT INTO history (minute, dim, key, packets, bytes)+ VALUES (?, ?, ?, ?, ?)+ ON CONFLICT(minute, dim, key) DO UPDATE SET+ packets = packets + excluded.packets,+ bytes = bytes + excluded.bytes+ """, hist_rows)conn.commit()except sqlite3.Error as exc:logger.error("flush failed: %s", exc)@@ -264,6 +302,38 @@ def get_timeline(minutes: int = 60) -> list[dict]:]+def get_history(dim: str, key: str, minutes: int = 60) -> list[dict]:+ """+ EN: Per-entity history — bytes/packets per minute for one host or process.+ Used by the per-application view and node detail panel.+ FR: Historique par entité — octets/paquets par minute pour un hôte ou un+ processus. Utilisé par la vue par application et le panneau de détail.+ """+ cutoff = (datetime.now(timezone.utc) - timedelta(minutes=minutes)).strftime("%Y-%m-%dT%H:%M")+ with _conn_lock:+ rows = get_conn().execute("""+ SELECT minute, packets, bytes FROM history+ WHERE dim = ? AND key = ? AND minute >= ?+ ORDER BY minute ASC+ """, (dim, key, cutoff)).fetchall()+ return [{"minute": r[0], "packets": r[1], "bytes": r[2]} for r in rows]+++def get_top_processes(minutes: int = 60, limit: int = 50) -> list[dict]:+ """+ EN: Top talkers by process over the window — feeds the Apps view.+ FR: Plus gros émetteurs par processus sur la fenêtre — alimente la vue Apps.+ """+ cutoff = (datetime.now(timezone.utc) - timedelta(minutes=minutes)).strftime("%Y-%m-%dT%H:%M")+ with _conn_lock:+ rows = get_conn().execute("""+ SELECT key, SUM(packets), SUM(bytes) FROM history+ WHERE dim = 'process' AND minute >= ?+ GROUP BY key ORDER BY SUM(bytes) DESC LIMIT ?+ """, (cutoff, limit)).fetchall()+ return [{"process": r[0], "packets": r[1], "bytes": r[2]} for r in rows]++def get_alerts(limit: int = 100) -> list[dict]:"""EN: Most recent persisted alerts, newest first — the /alerts endpoint now@@ -303,6 +373,7 @@ def cleanup_old_data(hours: int = 24) -> None:conn = get_conn()conn.execute("DELETE FROM traffic WHERE minute < ?", (cutoff,))conn.execute("DELETE FROM alerts_log WHERE ts < ?", (cutoff,))+ conn.execute("DELETE FROM history WHERE minute < ?", (cutoff,))conn.commit()except sqlite3.Error as exc:logger.error("cleanup failed: %s", exc)diff --git a/docs/threat-model.md b/docs/threat-model.mdnew file mode 100644index 0000000..82c3058--- /dev/null+++ b/docs/threat-model.md@@ -0,0 +1,91 @@+# Threat Model / Modèle de menace++*EN first, FR below — both describe the same system.*++## English++### What Snitch is++A local-first network traffic visualizer. It captures packets on the host,+attributes them to processes, enriches them **offline** (local `.mmdb`+geolocation, local DNS/SNI maps), and renders them in a web UI served by the+same process. There is **no cloud component** and **no telemetry**.++### Assets++- Your traffic metadata (destination IPs, ports, volumes, process names).+- The API token (per-launch in Electron, per-install in CLI/Docker mode).+- The local SQLite history DB (`traffic`, `alerts_log`, histories, settings).+- Integrity of the machine itself (a compromised Snitch could lie to you).++### Trust boundaries++| Boundary | Threat | Mitigation |+|---|---|---|+| Browser/remote client → REST `/`, `/settings`, `/alerts`, `/history/*`, `/geo/*`, `/capture/*` | An attacker on the LAN or a malicious web page reads/controls your traffic view | Token required on **every** endpoint (`Authorization: Bearer`). Bind is `127.0.0.1` by default. In Docker, `0.0.0.0` requires `SNITCH_TOKEN` to be explicitly set. |+| Web page → `/ws` | Cross-site WebSocket hijacking (CSWSH) | Token **and** `Origin` allowlist (loopback + Electron `null` origin only). |+| Host → third parties | Privacy leak | Zero outbound calls by default. The **only** possible outbound call is the DB-IP Lite download, gated behind `/geo/download` with `consent: true` — a deliberate user click. |+| Capture driver → parser | Malformed frames crash the process | The parser bounds-checks every offset; malformed packets return `None`, never raise into the capture loop. |+| Renderer ↔ main process (Electron) | Token exfiltration from the page | `contextIsolation` + `sandbox`; the token only crosses via `ipcRenderer.invoke`, never lands in the DOM or a URL string. |+| Local attacker with FS access | Token/history theft | Token file `0600`; data dir under the platform user dir; DB is not encrypted — full-disk encryption is the OS's job. |++### Known limitations++- **Root/Admin required for capture.** In Electron v1 the whole app runs+ elevated on Windows (`requireAdministrator`) — a privileged split is on the+ roadmap, see `docs/architecture.md`.+- The API token protects HTTP/WS but **not** against another local process+ running as you that can read `data/api_token.txt` or the Electron IPC.+- SQLite data at rest is unencrypted.+- Alert suppression is local and silent — an attacker who can write to the DB+ can mute alerts (defense: FS permissions).++### Out-of-scope++Malicious packet payloads (we parse headers only), kernel/driver compromise,+a rogue administrator.++---++## Français++### Ce qu'est Snitch++Un visualiseur de trafic réseau local d'abord. Il capture les paquets sur+l'hôte, les attribue aux processus, les enrichit **hors ligne** (base `.mmdb`+locale, tables DNS/SNI locales) et les rend dans une interface web servie par+le même processus. **Aucun composant cloud, aucune télémétrie.**++### Actifs++- Vos métadonnées de trafic (IP de destination, ports, volumes, processus).+- Le jeton API (par lancement sous Electron, par installation en CLI/Docker).+- La base SQLite locale (`traffic`, `alerts_log`, historiques, réglages).+- L'intégrité de la machine (un Snitch compromis pourrait vous mentir).++### Frontières de confiance++| Frontière | Menace | Atténuation |+|---|---|---|+| Navigateur/client distant → REST | Un attaquant LAN ou une page web malveillante lit/contrôle votre vue du trafic | Jeton exigé sur **chaque** endpoint (`Authorization: Bearer`). Bind `127.0.0.1` par défaut. En Docker, `0.0.0.0` exige `SNITCH_TOKEN` explicite. |+| Page web → `/ws` | Détournement de WebSocket cross-site (CSWSH) | Jeton **et** liste blanche d'`Origin` (loopback + origine `null` d'Electron). |+| Hôte → tiers | Fuite de vie privée | Zéro appel sortant par défaut. Le **seul** appel possible est le téléchargement DB-IP Lite, conditionné à `/geo/download` avec `consent: true` — un clic délibéré. |+| Driver de capture → parseur | Des trames malformées plantent le processus | Le parseur borne chaque offset ; les paquets malformés renvoient `None`, jamais d'exception dans la boucle. |+| Renderer ↔ main (Electron) | Exfiltration du jeton depuis la page | `contextIsolation` + `sandbox` ; le jeton ne transite que par `ipcRenderer.invoke`, jamais dans le DOM ni une URL. |+| Attaquant local avec accès FS | Vol du jeton/de l'historique | Fichier jeton `0600` ; dossier de données dans le répertoire utilisateur ; base non chiffrée — le chiffrement disque relève de l'OS. |++### Limites connues++- **Capture = privilèges admin/root.** Sous Electron v1, toute l'app tourne+ élevée sur Windows (`requireAdministrator`) — séparation privilégiée en+ feuille de route, voir `docs/architecture.md`.+- Le jeton protège HTTP/WS mais **pas** contre un autre processus local+ tournant sous votre compte qui lit `data/api_token.txt` ou l'IPC Electron.+- Les données SQLite au repos ne sont pas chiffrées.+- La suppression d'alertes est locale et silencieuse — un attaquant qui écrit+ dans la base peut masquer des alertes (défense : permissions FS).++### Hors périmètre++Charges utiles malveillantes (seuls les en-têtes sont parsés), compromission+noyau/driver, administrateur malveillant.diff --git a/electron/main.js b/electron/main.jsindex ba74ffd..a7a756e 100644--- a/electron/main.js+++ b/electron/main.js@@ -105,6 +105,12 @@ const API_TOKEN = crypto.randomBytes(24).toString('hex')ipcMain.handle('snitch:get-token', () => API_TOKEN)ipcMain.handle('snitch:get-port', () => backendPort)ipcMain.handle('snitch:get-version', () => app.getVersion())+// EN: "Open logs" — opens the platform log dir in the file manager. Returns+// a non-empty error string on failure (shell.openPath contract).+// FR: « Ouvrir les logs » — ouvre le dossier de logs dans le gestionnaire de+// fichiers. Renvoie une chaîne d'erreur non vide en cas d'échec+// (contrat de shell.openPath).+ipcMain.handle('snitch:open-logs', () => shell.openPath(logDir))/*** EN: Find a free loopback port by binding :0 and releasing — the backenddiff --git a/electron/preload.js b/electron/preload.jsindex bc50b44..77fe4f1 100644--- a/electron/preload.js+++ b/electron/preload.js@@ -30,4 +30,9 @@ contextBridge.exposeInMainWorld('snitch', {// EN: Async — real app version (package.json via app.getVersion()).// FR: Asynchrone — vraie version de l'app (package.json via app.getVersion()).getVersion: () => ipcRenderer.invoke('snitch:get-version'),+ // EN: Async — asks the main process to open the log directory in the OS+ // file manager (shell.openPath — cross-platform, no shelling out).+ // FR: Asynchrone — demande au processus principal d'ouvrir le dossier des+ // logs dans le gestionnaire de fichiers (shell.openPath — multi-OS).+ openLogs: () => ipcRenderer.invoke('snitch:open-logs'),})diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 9f2ff80..5700961 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -13,13 +13,16 @@* vue, panneaux) vit ici.*/import { useState, useMemo } from 'react'-import { Hexagon, Globe, Wifi, Smartphone, Monitor, Cpu, ShieldCheck, Radio, Zap, HelpCircle, AlertTriangle, Square, Play, Filter, Mic, Camera, Download, ShieldOff } from 'lucide-react'+import { Hexagon, Globe, Wifi, Smartphone, Monitor, Cpu, ShieldCheck, Radio, Zap, HelpCircle, AlertTriangle, Square, Play, Filter, Mic, Camera, Download, ShieldOff, AppWindow } from 'lucide-react'import ForceGraph from './graph/ForceGraph'import MapView from './map/MapView'+import AppsView from './components/AppsView'import Sidebar from './components/Sidebar'import { AlertBell, AlertPanel, AlertToasts } from './components/AlertPanel'+import { SettingsButton, SettingsPanel } from './components/Settings'import Timeline from './components/Timeline'import Dropdown from './components/Dropdown'+import { apiBase, authHeaders } from './api'import { useWebSocket } from './hooks/useWebSocket'import { computePrivacyScore } from './scoring/privacy'// EN: WS URL is resolved dynamically (port + ws/wss) via api.js wsBase().@@ -32,7 +35,9 @@ export default function App() {const [selected, setSelected] = useState(null)const [view, setView] = useState('graph')const [showAlerts, setShowAlerts] = useState(false)+ const [showSettings, setShowSettings] = useState(false)const [filter, setFilter] = useState({ text: '', category: 'all' })+ const { lang, setLang } = useT()// EN: Node ids that currently have at least one alert — drives the red glow.// FR: Ids des nœuds ayant au moins une alerte — pilote le halo rouge.@@ -90,6 +95,17 @@ export default function App() {setSelected(null)}+ // EN: Persisted "ignore this host/type" — POST /alerts/ignore.+ // FR: « Ignorer cet hôte/ce type » persisté — POST /alerts/ignore.+ async function handleIgnoreAlert(alert) {+ const base = await apiBase()+ await fetch(`${base}/alerts/ignore`, {+ method: 'POST',+ headers: await authHeaders({ 'Content-Type': 'application/json' }),+ body: JSON.stringify({ type: alert.type, ip: alert.details?.ip }),+ })+ }+return (<div style={{ display: 'flex', height: '100vh', width: '100vw', overflow: 'hidden' }}><Sidebar@@ -120,6 +136,7 @@ export default function App() {{view === 'map' && (<MapView nodes={filteredNodes} onNodeClick={setSelected} />)}+ {view === 'apps' && <AppsView nodes={filteredNodes} />}{/* EN: Top-right toolbar / FR: Barre d'outils en haut à droite */}<div style={{@@ -135,11 +152,16 @@ export default function App() {<IPWhitelist ips={whitelistedIps} onUpdate={updateIpWhitelist} /><CaptureToggle capturing={capturing} onToggle={toggleCapture} /><AlertBell unread={unread} onClick={handleBell} />+ <SettingsButton onClick={() => setShowSettings(v => !v)} /><StatusBadge status={status} lanCount={Object.keys(lanDevices).length} /></div>{showAlerts && (- <AlertPanel alerts={alerts} onClose={() => setShowAlerts(false)} />+ <AlertPanel alerts={alerts} onClose={() => setShowAlerts(false)} onIgnore={handleIgnoreAlert} />+ )}++ {showSettings && (+ <SettingsPanel onClose={() => setShowSettings(false)} lang={lang} setLang={setLang} />)}{/* EN: Floating toasts for warning/critical alerts.@@ -253,6 +275,11 @@ function ExportButton({ nodes, edges, lanDevices, alerts }) {/** EN: Red badge shown while a process holds the mic or camera.* FR: Badge rouge affiché quand un processus utilise le micro ou la caméra. */function MediaBadge({ media }) {+ // EN: supported === false means the platform has no backend (macOS) —+ // hide the badge entirely rather than lie with empty lists.+ // FR: supported === false signifie que la plateforme n'a pas de backend+ // (macOS) — masquer le badge plutôt que de mentir avec des listes vides.+ if (media.supported === false) return nullconst micActive = media.mic.length > 0const camActive = media.camera.length > 0if (!micActive && !camActive) return null@@ -650,8 +677,9 @@ function LangToggle() {function ViewToggle({ view, onChange }) {const { t } = useT()const items = [- { id: 'graph', Icon: Hexagon, label: t('nav_graph') },- { id: 'map', Icon: Globe, label: t('nav_map') },+ { id: 'graph', Icon: Hexagon, label: t('nav_graph') },+ { id: 'map', Icon: Globe, label: t('nav_map') },+ { id: 'apps', Icon: AppWindow, label: t('nav_apps') },]return (<div style={{diff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsxindex 38c9604..9a20b1d 100644--- a/frontend/src/components/AlertPanel.jsx+++ b/frontend/src/components/AlertPanel.jsx@@ -65,12 +65,32 @@ export function AlertBell({ unread, onClick }) {)}-export function AlertPanel({ alerts, onClose }) {+export function AlertPanel({ alerts, onClose, onIgnore }) {const { t } = useT()const warningCount = alerts.filter(a => a.severity === 'warning').lengthconst criticalCount = alerts.filter(a => a.severity === 'critical').lengthconst 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) => new Date(b.timestamp + 'Z') - new Date(a.timestamp + 'Z'))+return (<div style={{position: 'absolute', top: 56, right: 16, zIndex: 200,@@ -87,7 +107,7 @@ export function AlertPanel({ alerts, onClose }) {}}><div><span style={{ fontWeight: 700, fontSize: 13, color: '#f1f5f9' }}>{t('alerts_title')}</span>- <span style={{ fontSize: 11, color: '#64748b', marginLeft: 8 }}>{alerts.length} {t('alerts_total')}</span>+ <span style={{ fontSize: 11, color: '#64748b', marginLeft: 8 }}>{rows.length} {t('alerts_total')}</span></div><div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>{criticalCount > 0 && <Badge count={criticalCount} color="#ef4444" />}@@ -100,12 +120,12 @@ export function AlertPanel({ alerts, onClose }) {</div><div style={{ overflowY: 'auto', flex: 1 }}>- {alerts.length === 0 && (+ {rows.length === 0 && (<div style={{ padding: 32, textAlign: 'center', color: '#64748b', fontSize: 12 }}>{t('alerts_empty')}</div>)}- {alerts.map(alert => <AlertRow key={alert.id} alert={alert} />)}+ {rows.map(alert => <AlertRow key={alert.id} alert={alert} onIgnore={onIgnore} />)}</div></div>)@@ -122,12 +142,13 @@ export function AlertPanel({ alerts, onClose }) {* 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 }) {+function AlertRow({ alert, onIgnore }) {const { t } = useT()const sev = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.infoconst TypeIcon = TYPE_ICONS[alert.type] || Info@@ -154,9 +175,18 @@ function AlertRow({ alert }) {<div style={{ fontSize: 11, color: '#e2e8f0', lineHeight: 1.4 }}>{alertMessage(t, alert)}</div>{alert.details && Object.keys(alert.details).length > 0 && (<div style={{ marginTop: 3, fontSize: 9, color: '#64748b', fontFamily: 'monospace' }}>- {Object.entries(alert.details).filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`).join(' · ')}+ {Object.entries(alert.details).filter(([, v]) => v).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(', ') : v}`).join(' · ')}</div>)}+ {!alert._grouped && onIgnore && (+ <button onClick={() => onIgnore(alert)} style={{+ marginTop: 5, background: 'none', border: '1px solid #334155',+ borderRadius: 4, padding: '2px 8px', fontSize: 9,+ color: '#64748b', cursor: 'pointer',+ }}>+ {t('ignore_alert')}+ </button>+ )}</div></div><span style={{ fontSize: 9, color: '#475569', flexShrink: 0, marginTop: 2 }}>diff --git a/frontend/src/components/AppsView.jsx b/frontend/src/components/AppsView.jsxnew file mode 100644index 0000000..8dca9cb--- /dev/null+++ b/frontend/src/components/AppsView.jsx@@ -0,0 +1,126 @@+/**+ * Snitch — per-application view.+ *+ * EN: Aggregates live node "processes" maps into a per-process table:+ * destinations reached, volumes, and a click-through to per-process+ * history (bytes/minute from the /history/process endpoint).+ * FR: Agrège les tables « processes » des nœuds en un tableau par processus :+ * destinations jointes, volumes, et historique par processus au clic+ * (octets/minute depuis l'endpoint /history/process).+ */+import { useState, useEffect, useMemo, Fragment } from 'react'+import { useT } from '../i18n'+import { apiBase, authHeaders } from '../api'++function fmtBytes(b) {+ if (b >= 1e9) return (b / 1e9).toFixed(1) + ' GB'+ if (b >= 1e6) return (b / 1e6).toFixed(1) + ' MB'+ if (b >= 1e3) return (b / 1e3).toFixed(1) + ' KB'+ return b + ' B'+}++export default function AppsView({ nodes }) {+ const { t } = useT()+ const [expanded, setExpanded] = useState(null)+ const [history, setHistory] = useState([])++ // EN: Per-process rollup across all nodes.+ // FR: Agrégat par processus sur tous les nœuds.+ const apps = useMemo(() => {+ const map = {}+ for (const node of Object.values(nodes)) {+ if (!node.processes) continue+ for (const [proc, stats] of Object.entries(node.processes)) {+ const a = map[proc] ||= { name: proc, bytes: 0, packets: 0, destinations: [] }+ a.bytes += stats.bytes+ a.packets += stats.packets+ a.destinations.push({ ip: node.ip, label: node.label, bytes: stats.bytes })+ }+ }+ for (const a of Object.values(map)) {+ a.destinations.sort((x, y) => y.bytes - x.bytes)+ }+ return Object.values(map).sort((x, y) => y.bytes - x.bytes)+ }, [nodes])++ useEffect(() => {+ if (!expanded) { setHistory([]); return }+ ;(async () => {+ try {+ const base = await apiBase()+ const res = await fetch(+ `${base}/history/process/${encodeURIComponent(expanded)}?minutes=60`,+ { headers: await authHeaders() }).then(r => r.json())+ setHistory(res.history || [])+ } catch { setHistory([]) }+ })()+ }, [expanded])++ if (apps.length === 0) {+ return <div style={{ padding: 40, textAlign: 'center', color: '#64748b', fontSize: 12 }}>{t('apps_empty')}</div>+ }++ const maxBytes = apps[0].bytes || 1+ const maxHist = Math.max(...history.map(h => h.bytes), 1)++ return (+ <div style={{ height: '100%', overflowY: 'auto', padding: '16px 24px' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>+ <thead>+ <tr style={{ color: '#64748b', fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5 }}>+ <th style={{ textAlign: 'left', padding: '6px 8px' }}>{t('apps_process')}</th>+ <th style={{ textAlign: 'right', padding: '6px 8px' }}>{t('apps_destinations')}</th>+ <th style={{ textAlign: 'right', padding: '6px 8px' }}>{t('apps_packets')}</th>+ <th style={{ textAlign: 'left', padding: '6px 8px', width: '40%' }}>{t('apps_volume')}</th>+ </tr>+ </thead>+ <tbody>+ {apps.map(app => (+ <Fragment key={app.name}>+ <tr+ onClick={() => setExpanded(expanded === app.name ? null : app.name)}+ style={{ cursor: 'pointer', borderTop: '1px solid #1e293b' }}+ >+ <td style={{ padding: '8px', color: '#e2e8f0', fontFamily: 'monospace' }}>{app.name}</td>+ <td style={{ padding: '8px', textAlign: 'right', color: '#94a3b8' }}>{app.destinations.length}</td>+ <td style={{ padding: '8px', textAlign: 'right', color: '#94a3b8' }}>{app.packets}</td>+ <td style={{ padding: '8px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>+ <div style={{ flex: 1, height: 6, background: '#0f172a', borderRadius: 3, overflow: 'hidden' }}>+ <div style={{ width: `${(app.bytes / maxBytes) * 100}%`, height: '100%', background: '#3b82f6' }} />+ </div>+ <span style={{ color: '#94a3b8', minWidth: 60, textAlign: 'right' }}>{fmtBytes(app.bytes)}</span>+ </div>+ </td>+ </tr>+ {expanded === app.name && (+ <tr>+ <td colSpan={4} style={{ padding: '8px 8px 16px 24px', background: '#0f172a' }}>+ <div style={{ fontSize: 10, color: '#64748b', marginBottom: 6 }}>{t('apps_top_dest')}</div>+ {app.destinations.slice(0, 5).map(d => (+ <div key={d.ip} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#94a3b8', padding: '2px 0' }}>+ <span style={{ fontFamily: 'monospace' }}>{d.label || d.ip}</span>+ <span>{fmtBytes(d.bytes)}</span>+ </div>+ ))}+ {history.length > 0 && (+ <>+ <div style={{ fontSize: 10, color: '#64748b', margin: '10px 0 6px' }}>{t('apps_history_60m')}</div>+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2, height: 40 }}>+ {history.slice(-30).map((h, i) => (+ <div key={i} title={`${h.minute} — ${fmtBytes(h.bytes)}`}+ style={{ flex: 1, background: '#3b82f6', height: `${(h.bytes / maxHist) * 100}%`, minHeight: 1, borderRadius: 1 }} />+ ))}+ </div>+ </>+ )}+ </td>+ </tr>+ )}+ </Fragment>+ ))}+ </tbody>+ </table>+ </div>+ )+}diff --git a/frontend/src/components/Settings.jsx b/frontend/src/components/Settings.jsxnew file mode 100644index 0000000..c893d05--- /dev/null+++ b/frontend/src/components/Settings.jsx@@ -0,0 +1,210 @@+/**+ * Snitch — settings panel.+ *+ * EN: A slide-over panel for persisted settings: language, port filter,+ * excluded processes, IP whitelist, retention hours, and the opt-in+ * GeoIP database download (the app's ONLY outbound call — requires an+ * explicit click + consent flag). Under Electron, an "Open logs" action+ * reaches the preload bridge.+ * FR: Panneau latéral pour les réglages persistés : langue, filtre de ports,+ * processus exclus, whitelist IP, durée de rétention, et le téléchargement+ * opt-in de la base GeoIP (le SEUL appel sortant de l'app — exige un clic+ * explicite + le drapeau consent). Sous Electron, « Ouvrir les logs »+ * passe par le pont preload.+ */+import { useState, useEffect } from 'react'+import { Settings as SettingsIcon, X, FolderOpen, Download, ShieldCheck } from 'lucide-react'+import { useT } from '../i18n'+import { apiBase, authHeaders } from '../api'++export function SettingsButton({ onClick }) {+ return (+ <button onClick={onClick} aria-label="Settings / Réglages" style={{+ display: 'flex', alignItems: 'center', gap: 6,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 20, padding: '5px 14px',+ cursor: 'pointer', color: '#64748b',+ fontSize: 11, fontWeight: 600,+ }}>+ <SettingsIcon size={11} />+ </button>+ )+}++export function SettingsPanel({ onClose, lang, setLang }) {+ const { t } = useT()+ const [settings, setSettings] = useState(null)+ const [retention, setRetention] = useState(24)+ const [geoStatus, setGeoStatus] = useState(null)+ const [geoMsg, setGeoMsg] = useState('')+ const [saved, setSaved] = useState(false)++ useEffect(() => {+ ;(async () => {+ const base = await apiBase()+ const headers = await authHeaders()+ try {+ const [s, g] = await Promise.all([+ fetch(`${base}/settings`, { headers }).then(r => r.json()),+ fetch(`${base}/geo/status`, { headers }).then(r => r.json()),+ ])+ setSettings(s.settings || {})+ setRetention(s.settings?.retention_hours ?? 24)+ setGeoStatus(g)+ } catch { setSettings({}) }+ })()+ }, [])++ async function save(key, value) {+ const base = await apiBase()+ await fetch(`${base}/settings`, {+ method: 'POST',+ headers: await authHeaders({ 'Content-Type': 'application/json' }),+ body: JSON.stringify({ settings: { [key]: value } }),+ })+ setSaved(true)+ setTimeout(() => setSaved(false), 1500)+ }++ async function downloadGeo() {+ setGeoMsg(t('geo_downloading'))+ const base = await apiBase()+ try {+ const res = await fetch(`${base}/geo/download`, {+ method: 'POST',+ headers: await authHeaders({ 'Content-Type': 'application/json' }),+ body: JSON.stringify({ consent: true }),+ }).then(r => r.json())+ setGeoMsg(res.ok ? t('geo_done', res.downloaded.length) : t('geo_failed'))+ const g = await fetch(`${base}/geo/status`, { headers: await authHeaders() }).then(r => r.json())+ setGeoStatus(g)+ } catch {+ setGeoMsg(t('geo_failed'))+ }+ }++ async function openLogs() {+ // EN: Electron only — via preload bridge. / FR: Electron seulement — via le pont preload.+ if (window.snitch?.openLogs) await window.snitch.openLogs()+ }++ async function exportDiagnostics() {+ const base = await apiBase()+ const data = await fetch(`${base}/diagnostics`, { headers: await authHeaders() }).then(r => r.json())+ const a = document.createElement('a')+ a.href = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }))+ a.download = `snitch-diagnostics-${Date.now()}.json`+ a.click()+ URL.revokeObjectURL(a.href)+ }++ const row = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid #0f172a' }+ const label = { fontSize: 12, color: '#e2e8f0', fontWeight: 600 }+ const hint = { fontSize: 10, color: '#64748b', marginTop: 2 }++ return (+ <div role="dialog" aria-label="Settings / Réglages" style={{+ position: 'absolute', top: 56, right: 16, zIndex: 200,+ width: 380, maxHeight: 'calc(100vh - 80px)',+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 12, overflow: 'hidden auto',+ boxShadow: '0 8px 40px rgba(0,0,0,0.6)',+ display: 'flex', flexDirection: 'column',+ }}>+ <div style={{+ padding: '14px 18px', borderBottom: '1px solid #334155',+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',+ position: 'sticky', top: 0, background: '#1e293b', zIndex: 1,+ }}>+ <span style={{ fontWeight: 700, fontSize: 13, color: '#f1f5f9' }}>{t('settings_title')}</span>+ <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>+ {saved && <span style={{ fontSize: 10, color: '#4ade80' }}>{t('settings_saved')}</span>}+ <button onClick={onClose} aria-label={t('close')} style={{ background: 'none', border: 'none', color: '#64748b', cursor: 'pointer' }}>+ <X size={16} />+ </button>+ </div>+ </div>++ <div style={{ padding: '4px 18px 16px' }}>+ {/* Language / Langue */}+ <div style={row}>+ <div><div style={label}>{t('settings_language')}</div></div>+ <div style={{ display: 'flex', gap: 4 }}>+ {['en', 'fr'].map(l => (+ <button key={l} onClick={() => { setLang(l); save('language', l) }} style={{+ background: lang === l ? '#3b82f6' : '#0f172a',+ border: '1px solid #334155', borderRadius: 6,+ color: lang === l ? '#fff' : '#64748b',+ padding: '4px 12px', fontSize: 11, cursor: 'pointer',+ textTransform: 'uppercase', fontWeight: 600,+ }}>{l}</button>+ ))}+ </div>+ </div>++ {/* Retention / Rétention */}+ <div style={row}>+ <div>+ <div style={label}>{t('settings_retention')}</div>+ <div style={hint}>{t('settings_retention_hint')}</div>+ </div>+ <select+ value={retention}+ onChange={e => { const v = +e.target.value; setRetention(v); save('retention_hours', v) }}+ style={{ background: '#0f172a', border: '1px solid #334155', borderRadius: 6, color: '#e2e8f0', padding: '4px 8px', fontSize: 11 }}+ >+ {[6, 12, 24, 48, 72, 168].map(h => <option key={h} value={h}>{h}h</option>)}+ </select>+ </div>++ {/* GeoIP / GeoIP */}+ <div style={{ ...row, display: 'block' }}>+ <div style={label}>{t('geo_title')}</div>+ <div style={hint}>+ {geoStatus?.databases?.length+ ? t('geo_present', geoStatus.databases.join(', '))+ : t('geo_none')}+ </div>+ <button onClick={downloadGeo} style={{+ marginTop: 8, display: 'flex', alignItems: 'center', gap: 6,+ background: '#0f172a', border: '1px solid #3b82f6', borderRadius: 6,+ color: '#93c5fd', padding: '6px 12px', fontSize: 11, cursor: 'pointer',+ }}>+ <Download size={11} /> {t('geo_download_btn')}+ </button>+ <div style={{ ...hint, marginTop: 4 }}>{t('geo_consent')}</div>+ {geoMsg && <div style={{ fontSize: 10, color: '#93c5fd', marginTop: 4 }}>{geoMsg}</div>}+ </div>++ {/* Diagnostics / Diagnostic */}+ <div style={row}>+ <div>+ <div style={label}>{t('diag_title')}</div>+ <div style={hint}>{t('diag_hint')}</div>+ </div>+ <div style={{ display: 'flex', gap: 6 }}>+ {window.snitch?.openLogs && (+ <button onClick={openLogs} aria-label={t('diag_open_logs')} style={{+ background: '#0f172a', border: '1px solid #334155', borderRadius: 6,+ color: '#94a3b8', padding: '5px 10px', fontSize: 11, cursor: 'pointer',+ display: 'flex', alignItems: 'center', gap: 4,+ }}>+ <FolderOpen size={11} /> {t('diag_open_logs')}+ </button>+ )}+ <button onClick={exportDiagnostics} style={{+ background: '#0f172a', border: '1px solid #334155', borderRadius: 6,+ color: '#94a3b8', padding: '5px 10px', fontSize: 11, cursor: 'pointer',+ }}>+ {t('diag_export')}+ </button>+ </div>+ </div>++ <div style={{ fontSize: 10, color: '#475569', marginTop: 12, display: 'flex', alignItems: 'center', gap: 4 }}>+ <ShieldCheck size={11} /> {t('settings_note')}+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/hooks/useWebSocket.js b/frontend/src/hooks/useWebSocket.jsindex d16fe85..6fda3e4 100644--- a/frontend/src/hooks/useWebSocket.js+++ b/frontend/src/hooks/useWebSocket.js@@ -65,6 +65,7 @@ export function useWebSocket(url) {let stopped = falselet attempts = 0let timer = null+ let heartbeat = null // EN: 20 s app-level keepalive / FR: keepalive applicatif de 20 sasync function connect() {// EN: Resolve the token BEFORE opening the socket.@@ -77,8 +78,16 @@ export function useWebSocket(url) {ws.current.onopen = () => {attempts = 0setStatus('connected')+ // EN: send a cheap JSON ping every 20 s so idle sockets aren't dropped+ // by proxies or OS timeouts (the backend just ignores them).+ // FR: envoyer un ping JSON toutes les 20 s pour que les sockets inactifs+ // ne soient pas coupés par les proxies ou les timeouts OS.+ heartbeat = setInterval(() => {+ if (ws.current?.readyState === WebSocket.OPEN) ws.current.send('{}')+ }, 20000)}ws.current.onclose = () => {+ clearInterval(heartbeat)if (stopped) returnsetStatus('disconnected')// EN: Exponential backoff — 1s, 2s, 4s … max 30s.@@ -249,6 +258,7 @@ export function useWebSocket(url) {// FR: Arrêter les reconnexions et libérer le timer en attente au démontage.stopped = trueif (timer) clearTimeout(timer)+ clearInterval(heartbeat)ws.current?.close()}}, [url])diff --git a/frontend/src/i18n.jsx b/frontend/src/i18n.jsxindex 7cab2f3..82dcd9d 100644--- a/frontend/src/i18n.jsx+++ b/frontend/src/i18n.jsx@@ -167,6 +167,39 @@ const en = {score_warnings: n => `${n} warnings`,score_https_ratio: pct => `${pct}% HTTPS traffic`,score_no_trackers: 'No trackers detected',++ // Settings / Réglages+ settings_title: 'Settings',+ settings_saved: 'Saved',+ close: 'Close',+ settings_language: 'Language / Langue',+ settings_retention: 'History retention',+ settings_retention_hint: 'How long traffic & alert history is kept',+ geo_title: 'Geolocation database',+ geo_present: dbs => `Installed: ${dbs}`,+ geo_none: 'Not installed — IPs are not geolocated',+ geo_download_btn: 'Download DB-IP Lite (free)',+ geo_consent: 'Downloads ~50 MB from db-ip.com (CC BY 4.0). This is the only outbound call Snitch can make.',+ geo_downloading: 'Downloading…',+ geo_done: n => `Downloaded ${n} database(s)`,+ geo_failed: 'Download failed — check your connection',+ diag_title: 'Diagnostics',+ diag_hint: 'Logs and system info for bug reports',+ diag_open_logs: 'Logs',+ diag_export: 'Export',+ settings_note: 'All settings are stored locally. Snitch never sends data to third parties.',+ nav_apps: 'Apps',+ ignore_alert: 'Ignore this alert type/host',++ // Apps view / Vue applications+ apps_empty: 'No process attributed yet',+ apps_process: 'Process',+ apps_destinations: 'Hosts',+ apps_packets: 'Packets',+ apps_volume: 'Volume',+ apps_top_dest: 'Top destinations',+ apps_history_60m: 'Last hour (bytes/min)',+ alertmsg_NEW_HOSTS: n => `${n} new host${n > 1 ? 's' : ''} contacted`,}// ── Dictionnaire français / French dictionary ────────────────────────────────@@ -320,6 +353,39 @@ const fr = {score_warnings: n => `${n} alertes`,score_https_ratio: pct => `${pct}% de trafic HTTPS`,score_no_trackers: 'Aucun tracker détecté',++ // Réglages / Settings+ settings_title: 'Réglages',+ settings_saved: 'Enregistré',+ close: 'Fermer',+ settings_language: 'Langue / Language',+ settings_retention: 'Rétention de l\'historique',+ settings_retention_hint: 'Durée de conservation du trafic et des alertes',+ geo_title: 'Base de géolocalisation',+ geo_present: dbs => `Installée : ${dbs}`,+ geo_none: 'Non installée — les IP ne sont pas géolocalisées',+ geo_download_btn: 'Télécharger DB-IP Lite (gratuit)',+ geo_consent: 'Télécharge ~50 Mo depuis db-ip.com (CC BY 4.0). C\'est le seul appel sortant possible de Snitch.',+ geo_downloading: 'Téléchargement…',+ geo_done: n => `${n} base(s) téléchargée(s)`,+ geo_failed: 'Échec du téléchargement — vérifiez la connexion',+ diag_title: 'Diagnostic',+ diag_hint: 'Logs et infos système pour les rapports de bug',+ diag_open_logs: 'Logs',+ diag_export: 'Exporter',+ settings_note: 'Tous les réglages sont stockés localement. Snitch n\'envoie rien à des tiers.',+ nav_apps: 'Apps',+ ignore_alert: 'Ignorer ce type/cet hôte',++ // Vue applications / Apps view+ apps_empty: 'Aucun processus attribué pour l\'instant',+ apps_process: 'Processus',+ apps_destinations: 'Hôtes',+ apps_packets: 'Paquets',+ apps_volume: 'Volume',+ apps_top_dest: 'Destinations principales',+ apps_history_60m: 'Dernière heure (octets/min)',+ alertmsg_NEW_HOSTS: n => `${n} nouvel${n > 1 ? 'x' : ''} hôte${n > 1 ? 's' : ''} contacté${n > 1 ? 's' : ''}`,}// ── Context / Contexte ───────────────────────────────────────────────────────