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.

v1.1 features: auto-update, QUIC, watchlist, interface selector, ES UI

MoneyLisa931430244273
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 66eb3e8..774a7e5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -159,6 +159,45 @@ jobs:
choco install innosetup --no-progress -y
$v = "${{ github.ref_name }}" -replace '^v',''
& "C:\Program Files (x86)\Inno Setup 6\iscc.exe" "/DMyAppVersion=$v" "installer\snitch.iss"
+ # EN: FREE Authenticode signing via the SignPath Foundation OSS
+ # program (https://signpath.org) — the only legal no-cost path to
+ # publicly-trusted Windows code signing. Completely inert until the
+ # maintainer is accepted and configures:
+ # vars.SIGNPATH_ORGANIZATION_ID / SIGNPATH_PROJECT_SLUG /
+ # SIGNPATH_POLICY_SLUG + secret SIGNPATH_API_TOKEN.
+ # See docs/SIGNING.md for the full setup walkthrough.
+ # FR: Signature Authenticode GRATUITE via le programme OSS de la
+ # Fondation SignPath (https://signpath.org) — la seule voie légale
+ # sans frais vers une signature Windows publiquement reconnue.
+ # Totalement inerte tant que le mainteneur n'est pas accepté et
+ # n'a pas configuré :
+ # vars.SIGNPATH_ORGANIZATION_ID / SIGNPATH_PROJECT_SLUG /
+ # SIGNPATH_POLICY_SLUG + secret SIGNPATH_API_TOKEN.
+ # Voir docs/SIGNING.md pour la procédure complète.
+ - name: Upload unsigned Windows installer (SignPath input)
+ if: ${{ matrix.os == 'windows-latest' && vars.SIGNPATH_ORGANIZATION_ID != '' }}
+ id: upload-unsigned-exe
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ with:
+ name: snitch-unsigned-exe
+ path: dist/installer/*.exe
+ - name: SignPath — submit signing request
+ if: ${{ matrix.os == 'windows-latest' && vars.SIGNPATH_ORGANIZATION_ID != '' }}
+ uses: signpath/github-action-submit-signing-request@f6d04783b4569d051e0c80105fe66e82819d0092 # v3
+ with:
+ api-token: ${{ secrets.SIGNPATH_API_TOKEN }}
+ organization-id: ${{ vars.SIGNPATH_ORGANIZATION_ID }}
+ project-slug: ${{ vars.SIGNPATH_PROJECT_SLUG }}
+ signing-policy-slug: ${{ vars.SIGNPATH_POLICY_SLUG }}
+ github-artifact-id: ${{ steps.upload-unsigned-exe.outputs.artifact-id }}
+ wait-for-completion: true
+ wait-for-completion-timeout-in-seconds: 600
+ output-artifact-directory: dist/installer/signed
+ - name: Replace unsigned installer with signed copy
+ if: ${{ matrix.os == 'windows-latest' && vars.SIGNPATH_ORGANIZATION_ID != '' }}
+ shell: pwsh
+ run: Copy-Item -Force "dist/installer/signed/*" "dist/installer/"
+
# EN: Upload only the final installable files — unpacked dirs and
# blockmaps bloat artifacts to ~900 MB and break the release
# download. / FR: N'envoyer que les fichiers installables finaux —
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b4a7806..b182bbd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,20 @@ All notable changes to Snitch. / Toutes les modifications notables de Snitch.
The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
+## [Unreleased] / [Non publié]
+
+### Added / Ajouté
+
+- **Auto-update / Mise à jour automatique** — the desktop app checks GitHub Releases at launch and every 6 h via electron-updater (the `latest-*.yml` feeds were already published). Downloads install on restart; tray menu and Settings show live status. Opt-out in Settings or via `SNITCH_NO_UPDATE=1`. / L'app bureau vérifie les releases GitHub au lancement puis toutes les 6 h via electron-updater. Installation au redémarrage ; statut en direct dans le tray et les Réglages. Désactivation dans Réglages ou via `SNITCH_NO_UPDATE=1`.
+- **QUIC / HTTP/3 visibility / visibilité QUIC/HTTP3** — UDP/443 flows are labelled `QUIC/HTTP3` instead of being lumped into HTTPS or unknown. The QUIC Initial's SNI is encrypted and is never read — the label is honest about what is observable. / Les flux UDP/443 sont étiquetés `QUIC/HTTP3` au lieu d'être rangés en HTTPS ou inconnu. Le SNI du paquet Initial QUIC est chiffré et jamais lu — l'étiquette reste honnête.
+- **Watchlist** — pin IPs or domain suffixes (`example.com` also matches `api.example.com`); a dedicated `WATCHLIST_HIT` alert fires on first contact, rate-limited per (entry, host). Persisted, managed in Settings. / Épinglez des IP ou suffixes de domaine ; l'alerte dédiée `WATCHLIST_HIT` tire au premier contact, limitée par (entrée, hôte). Persistée, gérée dans Réglages.
+- **Per-process upload alert / Alerte d'envoi par processus** — `UPLOAD_SPIKE` warns when one process exceeds a configurable MB/min ceiling (default 50, 0 = off) — covers exfiltration that the baseline-relative `VOLUME_SPIKE` misses on cold-start processes. / `UPLOAD_SPIKE` alerte quand un processus dépasse un plafond Mo/min réglable (50 par défaut, 0 = off) — couvre l'exfiltration que le `VOLUME_SPIKE` relatif rate sur les processus frais.
+- **Capture interface selector / Sélecteur d'interface de capture** — `GET/POST /capture/interfaces` + a Settings dropdown listing libpcap devices; switching restarts capture instantly. Replaces the `SNITCH_IFACE` env var for desktop users. / `GET/POST /capture/interfaces` + liste déroulante dans Réglages ; le changement redémarre la capture aussitôt. Remplace la variable `SNITCH_IFACE`.
+- **Wi-Fi context / Contexte Wi-Fi** — the toolbar shows the current SSID (or the capture interface when not on Wi-Fi). Best-effort per OS, 60 s cache. / La barre d'outils affiche le SSID courant (ou l'interface hors Wi-Fi). Au mieux par OS, cache 60 s.
+- **Spanish UI / UI espagnole** — full `es` dictionary (194 keys, parity-checked); the language toggle is now EN/FR/ES. / Dictionnaire `es` complet (194 clés, parité vérifiée) ; le sélecteur devient EN/FR/ES.
+- **Snap package / Paquet snap** — electron-builder now emits a strict-confinement `.snap` (with the `network-observe` plug for AF_PACKET capture). Flatpak is deliberately not shipped — the sandbox cannot expose raw packet capture (documented in `docs/PACKAGING.md`). / electron-builder émet un `.snap` en confinement strict (plug `network-observe` pour la capture AF_PACKET). Pas de Flatpak — la sandbox ne peut pas exposer la capture brute (documenté dans `docs/PACKAGING.md`).
+- **Free code signing path / Signature de code gratuite** — optional SignPath Foundation OSS integration in CI (`vars.SIGNPATH_*` + `secrets.SIGNPATH_API_TOKEN`): the Windows installer is Authenticode-signed automatically once the project is accepted. Fully documented in `docs/SIGNING.md` including the honest macOS story (no free notarization exists). / Intégration optionnelle de SignPath Foundation OSS dans la CI : l'installeur Windows est signé Authenticode automatiquement une fois le projet accepté. Documenté dans `docs/SIGNING.md`, y compris la situation macOS (pas de notarisation gratuite).
+
## [1.0.8] — 2026-10-22
### Changed / Modifié
diff --git a/PRIVACY.md b/PRIVACY.md
index 16f45ae..3dbdd8f 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -5,9 +5,10 @@
Snitch is a privacy tool — it must never leak the very data it helps you monitor.
**Telemetry: none.** Snitch contains no analytics, no crash reporting, no
-update checks, no phone-home of any kind.
+phone-home of any kind.
-**Outbound network calls made by Snitch itself: none.** The application only:
+**Outbound network calls made by Snitch: two, both optional.** Everything
+below is passive observation or user-triggered — there is no silent traffic:
- captures packets on your local interfaces (passive observation),
- reads your system ARP/neighbour table (no active scanning),
@@ -16,11 +17,20 @@ update checks, no phone-home of any kind.
`SNITCH_DISABLE_PTR=1` to disable them entirely),
- serves a web UI on `127.0.0.1` for your own browser.
-**Geolocation is offline-only.** If you place a DB-IP Lite or MaxMind
-GeoLite2 `.mmdb` file in `<data_dir>/geo/`, lookups happen locally against
-that file. Without it, IPs simply show no location. There is no HTTP
-geolocation service — ip-api.com was removed precisely because it sent
-visited IPs to a third party in plaintext.
+The **desktop app checks github.com for new releases** at launch and every
+6 h (electron-updater, reads the public `latest-*.yml` files). This is the
+only periodic outbound call. Disable it in *Settings → Updates → Check
+automatically* (persisted) or with `SNITCH_NO_UPDATE=1`. The Docker build
+and the backend itself never check for updates.
+
+The **GeoIP database download** (`Settings → Geolocation`) fetches ~50 MB
+from db-ip.com — only when you click it, with an explicit consent flag.
+
+**Geolocation is offline-only.** Once a DB-IP Lite or MaxMind GeoLite2
+`.mmdb` file sits in `<data_dir>/geo/`, lookups happen locally against that
+file. Without it, IPs simply show no location. There is no HTTP geolocation
+service — ip-api.com was removed precisely because it sent visited IPs to a
+third party in plaintext.
**What is stored locally:**
@@ -41,10 +51,11 @@ Linux when running installed.
Snitch est un outil de confidentialité — il ne doit jamais divulguer les
données qu'il vous aide à surveiller.
-**Télémétrie : aucune.** Pas d'analytics, pas de rapports de crash, pas de
-vérification de mise à jour, aucun appel sortant.
+**Télémétrie : aucune.** Pas d'analytics, pas de rapports de crash, aucun
+appel « maison » d'aucune sorte.
-**Appels réseau émis par Snitch : aucun.** L'application se contente de :
+**Appels réseau émis par Snitch : deux, tous deux optionnels.** Tout le
+reste est observation passive ou déclenché par vous — aucun trafic silencieux :
- capturer les paquets sur vos interfaces locales (observation passive),
- lire la table ARP/voisinage système (pas de scan actif),
@@ -53,8 +64,18 @@ vérification de mise à jour, aucun appel sortant.
(`SNITCH_DISABLE_PTR=1` pour les désactiver complètement),
- servir une UI web sur `127.0.0.1` pour votre propre navigateur.
-**La géolocalisation est 100 % hors ligne.** Si vous placez un fichier
-`.mmdb` DB-IP Lite ou MaxMind GeoLite2 dans `<data_dir>/geo/`, les recherches
-se font localement. Sans base, les IP n'affichent simplement pas de position.
+**L'app bureau vérifie les nouvelles versions sur github.com** au lancement
+puis toutes les 6 h (electron-updater, lecture des fichiers publics
+`latest-*.yml`). C'est le seul appel sortant périodique. Désactivation dans
+*Réglages → Mises à jour → Vérifier automatiquement* (persisté) ou via
+`SNITCH_NO_UPDATE=1`. Le build Docker et le backend ne vérifient jamais.
+
+**Le téléchargement de la base GeoIP** (*Réglages → Géolocalisation*)
+récupère ~50 Mo depuis db-ip.com — uniquement à votre clic, avec un
+consentement explicite.
+
+**La géolocalisation est 100 % hors ligne.** Une fois un fichier `.mmdb`
+DB-IP Lite ou MaxMind GeoLite2 dans `<data_dir>/geo/`, les recherches se
+font localement. Sans base, les IP n'affichent simplement pas de position.
Il n'y a aucun service de géolocalisation HTTP — ip-api.com a été supprimé
précisément parce qu'il envoyait les IP visitées à un tiers en clair.
diff --git a/README.md b/README.md
index 83bc92d..e6dab98 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@
**Snitch** is a real-time network traffic visualizer.
See every connection your computer makes — who it talks to, where they are, and which app is responsible.
-The entire interface is available in **English and French**: use the `EN / FR` toggle in the top-right toolbar.
+The entire interface is available in **English, French and Spanish**: use the `EN / FR / ES` toggle in the top-right toolbar.
### Why Snitch?
@@ -56,15 +56,22 @@ The entire interface is available in **English and French**: use the `EN / FR` t
| Settings Panel | Language, retention, filters, consent-gated GeoIP download, diagnostics |
| Tracker Detection | Suffix-matched domain lists shipped as editable data files (`backend/classifier/lists/`) |
| Bandwidth Monitor | Live MB/s sparkline |
-| EN / FR UI | Full bilingual interface, one click to switch |
+| EN / FR / ES UI | Full trilingual interface, one click to switch |
| Light / Dark Theme | Follows your OS preference by default, manual toggle persists |
+| Auto-Update | Desktop app checks GitHub Releases (opt-out in Settings; `SNITCH_NO_UPDATE=1`) |
+| QUIC / HTTP/3 | UDP/443 flows labeled honestly — QUIC SNI is encrypted and never read |
+| Watchlist | Pin IPs/domains — dedicated alert the moment traffic touches them |
+| Upload Spike Alert | Per-process MB/min ceiling with adjustable threshold |
+| Interface Selector | Pick which adapter is sniffed — no env var needed |
+| Wi-Fi Context | Current SSID shown in the toolbar |
+| Export | Graph + alerts to JSON/CSV, one click |
### Download
| Platform | Package |
|---|---|
| **macOS (Apple Silicon)** | `brew install --cask aixisstudio/tap/snitch` — or **Snitch.app** zip/dmg from [latest release](https://github.com/aixisstudio/Snitch/releases/latest) |
-| **Linux** | **Snitch AppImage / .deb** from [latest release](https://github.com/aixisstudio/Snitch/releases/latest) — or `sudo docker compose up --build`, see [Docker (Linux)](#docker-linux) |
+| **Linux** | **Snitch AppImage / .deb / .snap** from [latest release](https://github.com/aixisstudio/Snitch/releases/latest) — or `sudo docker compose up --build`, see [Docker (Linux)](#docker-linux) |
| **Windows** | **Snitch Setup** `.exe` — one-click NSIS installer (native app, UAC prompt at launch, Npcap check built in) from [latest release](https://github.com/aixisstudio/Snitch/releases/latest). Lite alternative: `Snitch-Lite-Setup` (backend + browser UI). Requires [Npcap](https://npcap.com/) |
| **All (1-click)** | [Pinokio](https://pinokio.co/apps/github-com-aixisstudio-snitch) — installs deps, runs the backend, opens the UI / installe tout, lance le backend, ouvre l'UI |
@@ -220,7 +227,7 @@ snitch/
**Snitch** est un visualiseur de trafic réseau en temps réel.
Voyez chaque connexion que votre ordinateur établit — à qui il parle, où se trouvent les serveurs, et quelle application est responsable.
-Toute l'interface est disponible en **français et en anglais** : utilisez le sélecteur `EN / FR` dans la barre d'outils en haut à droite.
+Toute l'interface est disponible en **français, anglais et espagnol** : utilisez le sélecteur `EN / FR / ES` dans la barre d'outils en haut à droite.
### Pourquoi Snitch ?
@@ -245,15 +252,22 @@ Toute l'interface est disponible en **français et en anglais** : utilisez le s
| Panneau Réglages | Langue, rétention, filtres, téléchargement GeoIP sous consentement, diagnostic |
| Détection de trackers | Listes de domaines par suffixe, livrées en fichiers de données éditables (`backend/classifier/lists/`) |
| Moniteur de débit | Sparkline MB/s en direct |
-| UI FR / EN | Interface entièrement bilingue, bascule en un clic |
+| UI FR / EN / ES | Interface entièrement trilingue, bascule en un clic |
| Thème clair / sombre | Suit la préférence système par défaut, bascule manuelle persistée |
+| Mise à jour auto | L'app bureau vérifie les releases GitHub (désactivable dans Réglages ; `SNITCH_NO_UPDATE=1`) |
+| QUIC / HTTP/3 | Flux UDP/443 étiquetés honnêtement — le SNI QUIC est chiffré, jamais lu |
+| Watchlist | Épinglez IP/domaines — alerte dédiée dès qu'un trafic les touche |
+| Alerte pic d'envoi | Plafond Mo/min par processus, seuil réglable |
+| Sélecteur d'interface | Choisissez la carte écoutée — plus besoin de variable d'env |
+| Contexte Wi-Fi | SSID courant affiché dans la barre d'outils |
+| Export | Graphe + alertes en JSON/CSV, en un clic |
### Téléchargement
| Plateforme | Paquet |
|---|---|
| **macOS (Apple Silicon)** | `brew install --cask aixisstudio/tap/snitch` — ou **Snitch.app** zip/dmg depuis la [dernière release](https://github.com/aixisstudio/Snitch/releases/latest) |
-| **Linux** | **Snitch AppImage / .deb** depuis la [dernière release](https://github.com/aixisstudio/Snitch/releases/latest) — ou `sudo docker compose up --build`, voir [Docker (Linux)](#docker-linux-1) |
+| **Linux** | **Snitch AppImage / .deb / .snap** depuis la [dernière release](https://github.com/aixisstudio/Snitch/releases/latest) — ou `sudo docker compose up --build`, voir [Docker (Linux)](#docker-linux-1) |
| **Windows** | **Snitch Setup** `.exe` — installeur NSIS en un clic (app native, prompt UAC au lancement, détection Npcap intégrée) depuis la [dernière release](https://github.com/aixisstudio/Snitch/releases/latest). Alternative lite : `Snitch-Lite-Setup` (backend + UI navigateur). Nécessite [Npcap](https://npcap.com/) |
Ou récupérez la dernière release : **[github.com/aixisstudio/Snitch/releases](https://github.com/aixisstudio/Snitch/releases)**
diff --git a/ROADMAP.md b/ROADMAP.md
index f97fcdf..4b1b841 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -15,20 +15,23 @@ Also live / également en place : Docker image on GHCR, Homebrew tap (`brew inst
## 🚧 v1.x — in progress / en cours
-- [ ] **Signed & notarized macOS build** — needs an Apple Developer account ($99/yr). Until then the [tap](https://github.com/aixisstudio/homebrew-tap) strips quarantine for you / build macOS signée et notarisée — nécessite un compte Apple Developer. En attendant, le tap retire la quarantaine automatiquement
+- [x] **Signed Windows installer** — CI wired for [SignPath](https://signpath.org) OSS (free Authenticode for approved projects); activates once the application is accepted — see `docs/SIGNING.md` / CI branchée sur SignPath OSS (signature Authenticode gratuite pour projets acceptés) ; s'active dès l'acceptation — voir `docs/SIGNING.md`
+- [ ] **Signed & notarized macOS build** — needs an Apple Developer account ($99/yr), no free path exists. Until then the [tap](https://github.com/aixisstudio/homebrew-tap) strips quarantine for you / build macOS signée et notarisée — nécessite un compte Apple Developer, aucune voie gratuite. En attendant, le tap retire la quarantaine automatiquement
- [ ] **Homebrew upstream** (`brew install --cask snitch`) — blocked: the `snitch` formula name is already taken by an unrelated project; revisit once we have Developer ID signing / bloqué : le nom `snitch` est déjà pris par un autre projet ; à revoir une fois la signature en place
- [ ] **winget publishing** — [PR #455520](https://github.com/microsoft/winget-pkgs/pull/455520) open, awaiting Microsoft review / en attente de validation Microsoft
-- [ ] **Windows 1-click installers** — Electron NSIS (`Snitch Setup.exe`, native app + tray) and Inno Lite (`Snitch-Lite-Setup.exe`, backend + browser UI) now build in CI on tags; first shipping release v1.0.6 / installeurs Windows en un clic — NSIS Electron + Inno Lite, construits en CI aux tags ; première release v1.0.6
-- [ ] **Linux packages** — .deb / .rpm / AppImage alongside Docker / paquets Linux en plus de Docker
-- [ ] **Export formats** — per-host/session CSV & PCAP slices / exports CSV et PCAP par hôte ou session
+- [x] **Windows 1-click installers** — Electron NSIS (`Snitch Setup.exe`, native app + tray) and Inno Lite (`Snitch-Lite-Setup.exe`, backend + browser UI) build in CI on tags; shipping since v1.0.6 / installeurs Windows en un clic — NSIS Electron + Inno Lite, construits en CI aux tags ; livré depuis v1.0.6
+- [x] **Linux packages** — .deb / AppImage / **snap** alongside Docker (no Flatpak: the sandbox cannot expose packet capture) / paquets Linux en plus de Docker — deb / AppImage / **snap** (pas de Flatpak : la sandbox ne peut pas exposer la capture)
+- [x] **Auto-update** — electron-updater on the published `latest-*.yml` feeds, opt-out in Settings / auto-mise à jour — electron-updater sur les flux `latest-*.yml`, désactivable dans Réglages
+- [x] **Export formats** — graph + alerts to JSON/CSV in the UI / export graphe + alertes en JSON/CSV dans l'UI
- [ ] **Deeper tracker coverage** — community-editable lists live in `backend/classifier/lists/` / couverture trackers élargie — listes éditables par la communauté
+- [ ] **PCAP export** — capture slices per host/session / export PCAP par hôte ou session
## 💭 Under consideration / à l'étude
-- Per-process bandwidth history / historique de débit par processus
+- ~~Per-process bandwidth alert~~ — shipped as `UPLOAD_SPIKE` / livré via `UPLOAD_SPIKE`
- Custom alert rules in the UI / règles d'alerte personnalisées dans l'UI
- ~~Light theme / thème clair~~ — shipped in v1.0.7 / livré en v1.0.7
-- More languages — the i18n layer is ready / autres langues — l'i18n est prête
+- ~~More languages~~ — Spanish shipped; more welcome via `frontend/src/i18n.jsx` / espagnol livré ; d'autres bienvenues via `frontend/src/i18n.jsx`
- Optional remote pairing for headless hosts — consent-gated, token-protected / appairage optionnel d'hôtes sans écran — avec consentement et jeton
- Map layers: ASN / organisation view / couches de carte : vue ASN / organisation
diff --git a/backend/api/main.py b/backend/api/main.py
index 0e0df91..909cfc5 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -113,6 +113,7 @@ _capturing: bool = True
_port_filter: list[int] = []
_excluded_processes: set[str] = set()
_whitelisted_ips: set[str] = set()
+_watchlist: list[str] = [] # EN: user-pinned IPs/domains / FR: IP/domaines épinglés
_media_state: dict = {"mic": [], "camera": [], "supported": True}
_shutdown = False
@@ -189,6 +190,18 @@ class GeoDownloadBody(BaseModel):
consent: bool = False
+class InterfaceBody(BaseModel):
+ """EN: /capture/interface payload — None/empty means "auto-pick".
+ FR: Charge utile de /capture/interface — None/vide = choix automatique."""
+ name: Optional[str] = None
+
+
+class WatchlistBody(BaseModel):
+ """EN: /watchlist payload — IPs and/or domain suffixes to watch.
+ FR: Charge utile de /watchlist — IP et/ou suffixes de domaine à surveiller."""
+ items: list[str] = Field(default_factory=list)
+
+
# ── Broadcast / Diffusion ────────────────────────────────────────────────────
async def broadcast(message: dict) -> None:
@@ -979,6 +992,54 @@ def _stop_capture() -> None:
logger.info("capture stopped")
+# ── Wi-Fi SSID / SSID Wi-Fi ──────────────────────────────────────────────────
+# EN: Current wireless network name — displayed in the status bar so the user
+# can tell "home" from "hotel wifi" at a glance. Best-effort per platform,
+# cached 60 s, empty string on Ethernet/unsupported.
+# FR: Nom du réseau sans fil courant — affiché dans la barre de statut pour
+# distinguer « maison » et « wifi d'hôtel » d'un coup d'œil. Au mieux par
+# plateforme, en cache 60 s, chaîne vide sur Ethernet/non géré.
+_ssid_cache: dict = {"ssid": "", "ts": 0.0}
+
+
+def _current_ssid() -> str:
+ """EN: Active Wi-Fi SSID (60 s cache), "" when not on Wi-Fi or unknown.
+ FR: SSID Wi-Fi actif (cache 60 s), « » hors Wi-Fi ou inconnu."""
+ now = time.time()
+ if now - _ssid_cache["ts"] < 60:
+ return _ssid_cache["ssid"]
+ ssid = ""
+ try:
+ if sys.platform == "darwin":
+ iface = (_sniffer.iface if _sniffer else None) or "en0"
+ out = subprocess.run(
+ ["ipconfig", "getsummary", iface],
+ capture_output=True, text=True, timeout=3).stdout
+ for line in out.splitlines():
+ if "SSID :" in line:
+ ssid = line.split("SSID :", 1)[1].strip()
+ break
+ elif sys.platform.startswith("linux"):
+ out = subprocess.run(
+ ["iwgetid", "-r"], capture_output=True, text=True, timeout=3
+ ).stdout.strip()
+ if out:
+ ssid = out
+ elif sys.platform == "win32":
+ out = subprocess.run(
+ ["netsh", "wlan", "show", "interfaces"],
+ capture_output=True, text=True, timeout=3).stdout
+ for line in out.splitlines():
+ if line.strip().startswith("SSID"):
+ ssid = line.split(":", 1)[1].strip()
+ break
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ _ssid_cache["ssid"] = ssid
+ _ssid_cache["ts"] = now
+ return ssid
+
+
def _load_settings() -> None:
"""
EN: Restore persisted settings from SQLite at startup — filters, whitelist
@@ -986,11 +1047,15 @@ def _load_settings() -> None:
FR: Restaurer les réglages persistés depuis SQLite au démarrage — filtres,
whitelist et exclusions de processus survivent aux redémarrages.
"""
- global _port_filter, _excluded_processes, _whitelisted_ips
+ global _port_filter, _excluded_processes, _whitelisted_ips, _watchlist
_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 [])
+ _watchlist = list(db.get_setting("watchlist", []) or [])
detector.load_suppressions(db.get_setting("suppressions", []) or [])
+ detector.set_watchlist(_watchlist)
+ detector.set_upload_threshold_mb(
+ float(db.get_setting("upload_threshold_mb", 50)))
if _port_filter:
logger.info("restored port filter: %s", _port_filter)
@@ -1143,6 +1208,15 @@ async def post_settings(body: SettingsBody) -> dict:
loop = asyncio.get_running_loop()
for key, value in body.settings.items():
await loop.run_in_executor(None, db.set_setting, key, value)
+ # EN: Live-apply settings the detector reads dynamically — no restart
+ # needed for the upload threshold to take effect.
+ # FR: Appliquer à chaud les réglages que le détecteur lit
+ # dynamiquement — pas besoin de redémarrer pour le seuil d'envoi.
+ if key == "upload_threshold_mb":
+ try:
+ detector.set_upload_threshold_mb(float(value))
+ except (TypeError, ValueError):
+ pass
return {"ok": True}
@app.get("/capture/status", dependencies=_AUTH)
@@ -1153,6 +1227,9 @@ async def get_capture_status() -> dict:
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
+ "watchlist": list(_watchlist),
+ "interface": _sniffer.iface if _sniffer else None,
+ "ssid": _current_ssid(),
}
@app.post("/capture/stop", dependencies=_AUTH)
@@ -1166,6 +1243,8 @@ async def stop_capture() -> dict:
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
+ "watchlist": list(_watchlist),
+ "interface": _sniffer.iface if _sniffer else None,
})
return {"capturing": False}
@@ -1273,6 +1352,77 @@ async def set_ip_whitelist(body: WhitelistBody) -> dict:
await broadcast({"type": "nodes_removed", "ids": removed_ids})
return {"whitelisted_ips": sorted(_whitelisted_ips)}
+
+# ── Capture interface + watchlist / Interface de capture + watchlist ────────
+
[email protected]("/capture/interfaces", dependencies=_AUTH)
+async def list_interfaces() -> dict:
+ """
+ EN: Capture-capable interfaces from libpcap + the one currently in use
+ (None = auto-picked). Runs in the executor — pcap_findalldevs can be
+ slow on Windows.
+ FR: Interfaces capturables via libpcap + celle en cours (None = choix
+ automatique). Dans l'executor — pcap_findalldevs peut être lent sous
+ Windows.
+ """
+ from capture.pcap import PcapError, list_devices
+ loop = asyncio.get_running_loop()
+ try:
+ devs = await loop.run_in_executor(None, list_devices)
+ except PcapError as exc:
+ return {"interfaces": [], "current": None, "error": str(exc)}
+ return {
+ "interfaces": [
+ {"name": d.name, "description": d.description,
+ "loopback": d.loopback, "addresses": list(d.addresses)}
+ for d in devs
+ ],
+ "current": _sniffer.iface if _sniffer else None,
+ "configured": db.get_setting("interface"),
+ }
+
+
[email protected]("/capture/interface", dependencies=_AUTH)
+async def set_interface(body: InterfaceBody) -> dict:
+ """
+ EN: Pin the capture interface (empty body = back to auto). Persisted, and
+ the capture restarts immediately on the new interface.
+ FR: Épingler l'interface de capture (corps vide = retour à l'auto).
+ Persisté, et la capture redémarre aussitôt sur la nouvelle interface.
+ """
+ name = (body.name or "").strip() or None
+ db.set_setting("interface", name)
+ if _capturing:
+ _stop_capture()
+ _start_capture()
+ return {"interface": name,
+ "current": _sniffer.iface if _sniffer else None}
+
+
[email protected]("/watchlist", dependencies=_AUTH)
+async def get_watchlist() -> dict:
+ """EN: Pinned IPs/domains the detector alerts on.
+ FR: IP/domaines épinglés sur lesquels le détecteur alerte."""
+ return {"items": list(_watchlist)}
+
+
[email protected]("/watchlist", dependencies=_AUTH)
+async def set_watchlist(body: WatchlistBody) -> dict:
+ """
+ EN: Replace the watchlist — entries are IPs (exact match) or domain
+ suffixes ("example.com" catches "api.example.com"). Persisted and
+ pushed live into the detector.
+ FR: Remplacer la watchlist — les entrées sont des IP (correspondance
+ exacte) ou des suffixes de domaine (« example.com » attrape
+ « api.example.com »). Persisté et poussé à chaud dans le détecteur.
+ """
+ global _watchlist
+ _watchlist = [str(i).strip() for i in body.items if str(i).strip()][:500]
+ db.set_setting("watchlist", _watchlist)
+ detector.set_watchlist(_watchlist)
+ return {"items": _watchlist}
+
+
# EN: Upper bound for `minutes` query params — a week. Prevents absurd
# values (minutes=1e9) from scanning the whole history table; the
# retention cleanup makes anything older empty anyway.
@@ -1572,6 +1722,9 @@ async def websocket_endpoint(websocket: WebSocket) -> None:
"ports": _port_filter,
"excluded_processes": sorted(_excluded_processes),
"whitelisted_ips": sorted(_whitelisted_ips),
+ "watchlist": list(_watchlist),
+ "interface": _sniffer.iface if _sniffer else None,
+ "ssid": _current_ssid(),
}))
connected_clients.append(websocket)
diff --git a/backend/classifier/traffic.py b/backend/classifier/traffic.py
index 1f8fdef..95c765a 100644
--- a/backend/classifier/traffic.py
+++ b/backend/classifier/traffic.py
@@ -142,7 +142,14 @@ def classify(
3. port de destination bien connu -> safe/dns/admin
4. repli -> unknown
"""
- label = PORT_LABELS.get(dst_port or 0, protocol)
+ # EN: UDP/443 = QUIC (HTTP/3) — SNI lives inside the encrypted QUIC
+ # Initial, so we cannot read it; labelling the flow is the honest
+ # middle ground between pretending it is HTTPS and ignoring it.
+ # FR: UDP/443 = QUIC (HTTP/3) — le SNI vit dans le paquet Initial QUIC
+ # chiffré, illisible ; étiqueter le flux est l'honnête compromis
+ # entre faire croire à du HTTPS et l'ignorer.
+ is_quic = dst_port == 443 and protocol == "UDP"
+ label = "QUIC/HTTP3" if is_quic else PORT_LABELS.get(dst_port or 0, protocol)
if hostname:
if _domain_match(hostname, KNOWN_TRACKERS):
diff --git a/backend/detection/anomaly.py b/backend/detection/anomaly.py
index 2526cbe..74d7885 100644
--- a/backend/detection/anomaly.py
+++ b/backend/detection/anomaly.py
@@ -16,6 +16,12 @@ EN: Stateful, rule-based detector fed with every captured packet and every
- PORT_SCAN many distinct remote ports from one origin in a
short window (both directions)
- VOLUME_SPIKE bytes-per-window far above the rolling baseline
+ - UPLOAD_SPIKE a single process uploads more than the configured
+ threshold in a 60 s window — "who is sending big
+ data right now" catches exfil that VOLUME_SPIKE's
+ baseline-relative test misses
+ - WATCHLIST_HIT contact with a user-pinned IP or domain — the
+ "tell me when X shows up" feature
- MEDIA_EXFIL mic/camera-using process (not whitelisted) sending out
- NEW_LAN_DEVICE device appears on the local network
- DEVICE_OFFLINE device disappears from the local network
@@ -44,6 +50,13 @@ FR: Détecteur à état basé sur des règles, alimenté par chaque paquet captu
- PORT_SCAN beaucoup de ports distants distincts depuis une
origine sur une courte fenêtre (deux sens)
- VOLUME_SPIKE octets par fenêtre bien au-dessus de la base roulante
+ - UPLOAD_SPIKE un processus émet plus que le seuil configuré sur
+ une fenêtre de 60 s — « qui envoie beaucoup de
+ données en ce moment » attrape l'exfil que le test
+ relatif à la base de VOLUME_SPIKE rate
+ - WATCHLIST_HIT contact avec une IP ou un domaine épinglé par
+ l'utilisateur — la fonction « dis-moi quand X
+ apparaît »
- MEDIA_EXFIL processus micro/caméra (non whitelisté) qui émet
- NEW_LAN_DEVICE un appareil apparaît sur le réseau local
- DEVICE_OFFLINE un appareil disparaît du réseau local
@@ -128,6 +141,19 @@ VOLUME_MIN_BYTES = 5 * 1024 * 1024 # EN: windows under 5 MB never alert
# FR: les fenêtres sous 5 Mo n'alertent pas
VOLUME_MULTIPLIER = 5.0
+# ── Upload threshold / Seuil d'émission ──────────────────────────────────────
+# EN: Absolute per-process outbound threshold — unlike VOLUME_SPIKE (which
+# needs a baseline to compare against), this fires the moment a process
+# crosses a hard ceiling, so a brand-new uploader is caught too. Tunable
+# through the `upload_threshold_mb` setting.
+# FR: Seuil sortant absolu par processus — contrairement à VOLUME_SPIKE
+# (qui exige une base de comparaison), il déclenche dès qu'un processus
+# franchit un plafond strict : un nouvel émetteur est attrapé aussi.
+# Réglable via le paramètre `upload_threshold_mb`.
+UPLOAD_WINDOW_S = 60
+UPLOAD_DEFAULT_MB = 50
+MAX_TRACKED_PROCS = 5_000
+
# ── Port scan / Scan de ports ────────────────────────────────────────────────
SCAN_WINDOW_S = 60
SCAN_THRESHOLD = 20 # EN: distinct remote ports / FR: ports distants
@@ -271,6 +297,15 @@ 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: (ts, bytes) outbound events per PROCESS NAME for UPLOAD_SPIKE,
+ # plus the user watchlist (ips/domains) and its threshold.
+ # FR: Événements (ts, octets) sortants par NOM DE PROCESSUS pour
+ # UPLOAD_SPIKE, plus la watchlist utilisateur (ip/domaines) et
+ # son seuil.
+ self._proc_upload: dict[str, deque] = defaultdict(lambda: deque(maxlen=500))
+ self._upload_threshold_b = UPLOAD_DEFAULT_MB * 1024 * 1024
+ self._watch_ips: set[str] = set()
+ self._watch_domains: set[str] = set()
# EN: User suppressions — persisted in the settings table, loaded at
# startup. An entry is {"type": "BEACON"|None, "ip": "1.2.3.4"|None};
@@ -310,6 +345,34 @@ class AnomalyDetector:
self._mic_procs = {p.lower() for p in mic}
self._cam_procs = {p.lower() for p in camera}
+ def set_upload_threshold_mb(self, mb: float) -> None:
+ """EN: Configure the per-process upload ceiling (megabytes/minute);
+ <= 0 disables the rule entirely.
+ FR: Configurer le plafond d'émission par processus (Mo/minute) ;
+ <= 0 désactive entièrement la règle."""
+ with self._lock:
+ self._upload_threshold_b = max(0, int(mb)) * 1024 * 1024
+
+ def set_watchlist(self, items: list[str]) -> None:
+ """
+ EN: Replace the user watchlist — entries are IPs or domain suffixes
+ ("example.com" also catches "api.example.com").
+ FR: Remplacer la watchlist utilisateur — les entrées sont des IP ou
+ suffixes de domaine (« example.com » attrape aussi
+ « api.example.com »).
+ """
+ with self._lock:
+ self._watch_ips, self._watch_domains = set(), set()
+ for item in items:
+ s = str(item).strip().lower().rstrip(".")
+ if not s:
+ continue
+ try:
+ ipaddress.ip_address(s)
+ self._watch_ips.add(s)
+ except ValueError:
+ self._watch_domains.add(s)
+
def forget(self, ip: str) -> None:
"""
EN: Drop all runtime state for an IP (e.g. after it is whitelisted).
@@ -374,6 +437,8 @@ 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)
+ alerts += self._check_upload_spike(pkt, remote_ip, geo)
+ alerts += self._check_watchlist(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 —
@@ -689,6 +754,87 @@ class AnomalyDetector:
details={"process": pkt.process_name, "device": device, "ip": remote_ip, "host": label, "org": geo.get("org", "")},
)]
+ def _check_upload_spike(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:
+ """
+ EN: Per-process absolute upload ceiling — VOLUME_SPIKE only fires
+ against a learned baseline, so a process that was quiet since
+ boot has none and can exfiltrate freely. This rule tracks each
+ process's outbound bytes over the last UPLOAD_WINDOW_S seconds
+ and warns past `upload_threshold_mb` (default 50 MB/min).
+ FR: Plafond d'émission absolu par processus — VOLUME_SPIKE ne tire
+ que par rapport à une base apprise, donc un processus silencieux
+ depuis le boot n'en a pas et peut exfiltrer librement. Cette
+ règle suit les octets sortants de chaque processus sur les
+ dernières UPLOAD_WINDOW_S secondes et alerte au-delà de
+ `upload_threshold_mb` (50 Mo/min par défaut).
+ """
+ if (pkt.direction != "out" or not pkt.process_name
+ or self._upload_threshold_b <= 0):
+ return []
+ now = time.time()
+ dq = self._proc_upload[pkt.process_name]
+ if len(self._proc_upload) > MAX_TRACKED_PROCS:
+ # EN: Bound long-term memory — drop the coldest process windows.
+ # FR: Borner la mémoire longue durée — jeter les fenêtres de
+ # processus les plus froides.
+ for k in [k for k, d in self._proc_upload.items()
+ if not d or now - d[-1][0] > 3600]:
+ self._proc_upload.pop(k, None)
+ if len(self._proc_upload) > MAX_TRACKED_PROCS:
+ self._proc_upload.clear()
+ dq = self._proc_upload[pkt.process_name]
+ dq.append((now, pkt.size))
+ cutoff = now - UPLOAD_WINDOW_S
+ while dq and dq[0][0] < cutoff:
+ dq.popleft()
+ total = sum(b for _, b in dq)
+ if total < self._upload_threshold_b:
+ return []
+ if not self._cooldown_ok(f"upload_spike:{pkt.process_name}", cooldown=300):
+ return []
+ label = geo.get("hostname") or remote_ip
+ mb = round(total / (1024 * 1024), 1)
+ return [Alert(
+ type="UPLOAD_SPIKE",
+ severity="warning",
+ message=f"Upload spike: {pkt.process_name} sent {mb} MB in {UPLOAD_WINDOW_S}s",
+ node_id=remote_ip,
+ details={"process": pkt.process_name, "bytes": total,
+ "mb": mb, "window_s": UPLOAD_WINDOW_S,
+ "ip": remote_ip, "host": label},
+ )]
+
+ def _check_watchlist(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:
+ """
+ EN: User-pinned IP / domain suffix hit — fires once per (entry, ip)
+ per 5 min so a busy watched host does not spam. Severity
+ "warning": the user asked to be told.
+ FR: Atteinte d'une IP / d'un suffixe de domaine épinglé par
+ l'utilisateur — tire une fois par (entrée, ip) par 5 min pour ne
+ pas spammer un hôte surveillé bavard. Sévérité « warning » :
+ l'utilisateur a demandé à être prévenu.
+ """
+ if not self._watch_ips and not self._watch_domains:
+ return []
+ host = (geo.get("hostname") or pkt.sni or "").lower().rstrip(".")
+ matched = remote_ip if remote_ip in self._watch_ips else None
+ if not matched and host:
+ matched = next((d for d in self._watch_domains
+ if host == d or host.endswith("." + d)), None)
+ if not matched:
+ return []
+ if not self._cooldown_ok(f"watchlist:{matched}:{remote_ip}", cooldown=300):
+ return []
+ return [Alert(
+ type="WATCHLIST_HIT",
+ severity="warning",
+ message=f"Watchlist hit: {matched} ({host or remote_ip})",
+ node_id=remote_ip,
+ details={"match": matched, "ip": remote_ip,
+ "host": host or remote_ip,
+ "process": pkt.process_name},
+ )]
+
# ── Helpers / Utilitaires ────────────────────────────────────────────────
def _cooldown_ok(self, key: str, cooldown: int = COOLDOWN) -> bool:
diff --git a/backend/tests/test_anomaly.py b/backend/tests/test_anomaly.py
index 0844ab5..04e7b9f 100644
--- a/backend/tests/test_anomaly.py
+++ b/backend/tests/test_anomaly.py
@@ -170,3 +170,83 @@ def test_reset_runtime_clears_state():
det.reset_runtime()
alerts = det.analyze_packet(pkt(), {})
assert any(a.type == "NEW_HOST" for a in alerts)
+
+
+def test_upload_spike_alerts_past_threshold():
+ """EN: One process exceeding the MB/min upload ceiling alerts once.
+ FR: Un processus dépassant le plafond Mo/min alerte une fois."""
+ det = AnomalyDetector()
+ det.set_upload_threshold_mb(1) # EN: 1 MB/min / FR: 1 Mo/min
+ alerts = []
+ for _ in range(12):
+ alerts += det.analyze_packet(
+ pkt(size=100_000, process="backupd"), {"hostname": "x.io"})
+ types = [a.type for a in alerts]
+ assert "UPLOAD_SPIKE" in types
+ # EN: Cooldown — feeding more traffic must NOT re-alert immediately.
+ # FR: Cooldown — plus de trafic ne doit PAS re-alerter aussitôt.
+ n_before = len(alerts)
+ for _ in range(12):
+ alerts += det.analyze_packet(
+ pkt(size=100_000, process="backupd"), {"hostname": "x.io"})
+ assert [a.type for a in alerts[n_before:]].count("UPLOAD_SPIKE") == 0
+
+
+def test_upload_spike_disabled_with_zero():
+ """EN: upload_threshold_mb <= 0 disables the rule entirely.
+ FR: upload_threshold_mb <= 0 désactive la règle."""
+ det = AnomalyDetector()
+ det.set_upload_threshold_mb(0)
+ alerts = []
+ for _ in range(30):
+ alerts += det.analyze_packet(
+ pkt(size=200_000, process="backupd"), {"hostname": "x.io"})
+ assert "UPLOAD_SPIKE" not in [a.type for a in alerts]
+
+
+def test_upload_spike_ignores_inbound_and_no_process():
+ """EN: Inbound packets and unattributed traffic never count.
+ FR: Paquets entrants et trafic non attribué ne comptent jamais."""
+ det = AnomalyDetector()
+ det.set_upload_threshold_mb(1)
+ alerts = []
+ for _ in range(20):
+ alerts += det.analyze_packet(
+ pkt(size=100_000, direction="in", process="backupd"), {})
+ alerts += det.analyze_packet(pkt(size=100_000), {})
+ assert "UPLOAD_SPIKE" not in [a.type for a in alerts]
+
+
+def test_watchlist_hit_by_ip():
+ """EN: A packet to a watched IP raises WATCHLIST_HIT once per 5 min.
+ FR: Un paquet vers une IP surveillée déclenche WATCHLIST_HIT."""
+ det = AnomalyDetector()
+ det.set_watchlist(["91.198.174.192"])
+ alerts = det.analyze_packet(pkt(), {})
+ assert any(a.type == "WATCHLIST_HIT" for a in alerts)
+
+
+def test_watchlist_hit_by_domain_suffix():
+ """EN: A watched suffix matches subdomains via the resolved hostname.
+ FR: Un suffixe surveillé matche les sous-domaines via le nom résolu."""
+ det = AnomalyDetector()
+ det.set_watchlist(["evil.example"])
+ alerts = det.analyze_packet(pkt(), {"hostname": "cdn.evil.example"})
+ assert any(a.type == "WATCHLIST_HIT" for a in alerts)
+
+
+def test_watchlist_no_match_no_alert():
+ """EN: Unrelated traffic stays quiet. / FR: Le trafic étranger reste muet."""
+ det = AnomalyDetector()
+ det.set_watchlist(["8.8.8.8", "evil.example"])
+ alerts = det.analyze_packet(pkt(), {"hostname": "wikipedia.org"})
+ assert "WATCHLIST_HIT" not in [a.type for a in alerts]
+
+
+def test_watchlist_rejects_domain_lookalike():
+ """EN: "notexample.com" must NOT match suffix "example.com".
+ FR: « notexample.com » ne doit PAS matcher le suffixe « example.com »."""
+ det = AnomalyDetector()
+ det.set_watchlist(["example.com"])
+ alerts = det.analyze_packet(pkt(), {"hostname": "notexample.com"})
+ assert "WATCHLIST_HIT" not in [a.type for a in alerts]
diff --git a/backend/tests/test_classifier.py b/backend/tests/test_classifier.py
index eaa2309..112ac56 100644
--- a/backend/tests/test_classifier.py
+++ b/backend/tests/test_classifier.py
@@ -59,3 +59,20 @@ def test_suffix_match_accepts_deep_subdomain():
FR: a.b.c.doubleclick.net correspond toujours à doubleclick.net."""
r = classify("a.b.c.doubleclick.net", 443, "TCP")
assert r.category == "tracking"
+
+
+def test_udp_443_is_quic_http3():
+ """EN: UDP/443 = QUIC (HTTP/3) — labeled honestly since SNI is encrypted.
+ FR: UDP/443 = QUIC (HTTP/3) — étiqueté honnêtement, le SNI est chiffré."""
+ from classifier.traffic import classify
+ c = classify(None, 443, "UDP")
+ assert c.label == "QUIC/HTTP3"
+ assert c.category == "safe" # EN: port-443 bucket / FR: famille port 443
+
+
+def test_tcp_443_stays_https():
+ """EN: TCP/443 keeps the HTTPS label — QUIC detection must not leak.
+ FR: TCP/443 garde l'étiquette HTTPS — la détection QUIC ne doit pas fuiter."""
+ from classifier.traffic import classify
+ c = classify(None, 443, "TCP")
+ assert c.label != "QUIC/HTTP3"
diff --git a/docs/PACKAGING.md b/docs/PACKAGING.md
new file mode 100644
index 0000000..f3ae5d0
--- /dev/null
+++ b/docs/PACKAGING.md
@@ -0,0 +1,74 @@
+# Linux packaging / Empaquetage Linux
+
+English · [Français](#français)
+
+## Formats shipped
+
+| Format | File | Notes |
+|---|---|---|
+| AppImage | `Snitch-x86_64.AppImage` | portable, needs `libfuse2`; update info via `latest-linux.yml` |
+| deb | `snitch-linux-amd64.deb` | standard Debian/Ubuntu install |
+| snap | `Snitch-amd64.snap` | strict confinement — see below |
+
+## Snap — packet capture under confinement
+
+The snap is built by electron-builder (`linux.target` includes `"snap"`) in
+strict confinement. Packet capture uses `AF_PACKET` sockets, which the
+`network-observe` interface grants (the same model the `tcpdump` snap
+uses). After installing a local `.snap`:
+
+```bash
+sudo snap install --dangerous Snitch-amd64.snap
+sudo snap connect snitch:network-observe # grants AF_PACKET read access
+```
+
+Without the `network-observe` connection the UI still runs but capture
+stays empty. Store publication would auto-connect that interface once
+human-reviewed; until then the manual connect is required.
+
+## Flatpak — deliberately not shipped
+
+Flatpak's sandbox cannot grant `AF_PACKET` access: there is no portal or
+`finish-args` combination that exposes raw packet capture, and process
+attribution via `psutil` needs host `/proc` visibility the sandbox denies.
+Shipping a Flatpak would produce a pretty UI that can never see a packet —
+we'd rather not publish a broken app than fake it. If flathub ever grows a
+capture-capable permission, revisit.
+
+---
+
+## Français
+
+### Formats publiés
+
+| Format | Fichier | Notes |
+|---|---|---|
+| AppImage | `Snitch-x86_64.AppImage` | portable, requiert `libfuse2` ; info de mise à jour via `latest-linux.yml` |
+| deb | `snitch-linux-amd64.deb` | installation Debian/Ubuntu standard |
+| snap | `Snitch-amd64.snap` | confinement strict — voir ci-dessous |
+
+### Snap — capture de paquets sous confinement
+
+Le snap est construit par electron-builder (`linux.target` inclut
+`"snap"`) en confinement strict. La capture utilise des sockets
+`AF_PACKET`, que l'interface `network-observe` autorise (le même modèle
+que le snap `tcpdump`). Après installation d'un `.snap` local :
+
+```bash
+sudo snap install --dangerous Snitch-amd64.snap
+sudo snap connect snitch:network-observe # autorise la lecture AF_PACKET
+```
+
+Sans cette connexion, l'UI tourne mais la capture reste vide. Une
+publication sur le Store connecterait l'interface automatiquement après
+revue ; en attendant, la connexion manuelle est requise.
+
+### Flatpak — volontairement non publié
+
+La sandbox Flatpak ne peut pas accorder l'accès `AF_PACKET` : aucun portal
+ni combinaison de `finish-args` n'expose la capture de paquets brute, et
+l'attribution par processus via `psutil` exige une visibilité `/proc` de
+l'hôte que la sandbox refuse. Publier un Flatpak produirait une jolie UI
+incapable de voir le moindre paquet — mieux vaut ne pas publier une app
+cassée que de simuler. À revoir si flathub ajoute une permission de
+capture.
diff --git a/docs/SIGNING.md b/docs/SIGNING.md
new file mode 100644
index 0000000..079355b
--- /dev/null
+++ b/docs/SIGNING.md
@@ -0,0 +1,111 @@
+# Code signing / Signature de code
+
+English · [Français](#français)
+
+## Current state / État actuel
+
+Snitch builds are **unsigned** on Windows and macOS. This is honest and
+deliberate: we will not ship self-signed certificates that defeat the point
+of signing, and we will not buy a certificate while a legitimate free path
+exists for open-source projects.
+
+Les builds Snitch sont **non signés** sous Windows et macOS. C'est honnête et
+volontaire : pas de certificat auto-signé qui viderait la signature de son
+sens, et pas d'achat de certificat tant qu'une voie gratuite légitime existe
+pour l'open source.
+
+## Windows — SignPath Foundation (free for OSS)
+
+[SignPath](https://signpath.org) offers **free Authenticode signing** to
+qualifying open-source projects. Approved projects get a `release-signing`
+policy that produces publicly trusted signatures — SmartScreen stops
+warning once reputation builds.
+
+### Setup (one-time, maintainer only)
+
+1. Apply at <https://signpath.org> → *Open Source* — describe the project
+ and link this repository. Approval is manual (days).
+2. Create the SignPath organization, a **project** (slug, e.g. `Snitch`),
+ link the *GitHub.com* trusted build system to it, and install the
+ SignPath GitHub App on this repository (required for origin verification).
+3. Create a **release-signing policy** restricted to tag builds, with an
+ artifact configuration matching `*.exe` in a ZIP (the standard template
+ works).
+4. In GitHub → repo *Settings → Secrets and variables → Actions*:
+ - Variables: `SIGNPATH_ORGANIZATION_ID`, `SIGNPATH_PROJECT_SLUG`,
+ `SIGNPATH_POLICY_SLUG`
+ - Secret: `SIGNPATH_API_TOKEN`
+5. Done — the CI job `SignPath — submit signing request` in
+ `.github/workflows/ci.yml` activates automatically on the next tag: it
+ uploads the unsigned installer, waits for the signed copy, and replaces
+ the artifact before release upload. **Everything is inert until step 4.**
+
+## macOS — no free path exists
+
+Apple requires a paid **Developer Program** membership ($99/yr) for a
+Developer ID certificate + notarization. There is no legal free
+alternative. Until/unless the project funds one:
+
+- the `.zip`/`.dmg` builds stay unsigned — first launch needs
+ **right-click → Open**, or `xattr -d com.apple.quarantine Snitch.app`
+- SHA256 checksums are published on every release for integrity checking
+- public CI build logs provide provenance (reproducible pipeline)
+
+If `APPLE_ID` / `APPLE_TEAM_ID` / `APPLE_APP_PASSWORD` / `MACOS_CERT_P12`
+secrets are ever configured, the `ENABLE_CODESIGNING` placeholder steps in
+CI are the hook.
+
+## Alternatives evaluated and rejected
+
+| Option | Why not |
+|---|---|
+| Azure Trusted Signing | ~$10/mo — not free; free/trial/sponsored Azure subs are explicitly unsupported |
+| Microsoft Store (MSIX) | Microsoft re-signs for free after certification — but only for Store distribution; kept as a future channel |
+| Self-signed cert | Defeats SmartScreen/Gatekeeper trust — worse than unsigned |
+| Community/shared certs | Illegal under CA terms — never |
+
+---
+
+## Français
+
+### Windows — Fondation SignPath (gratuit pour l'open source)
+
+[SignPath](https://signpath.org) offre la **signature Authenticode gratuite**
+aux projets open source éligibles. Les projets acceptés obtiennent une
+politique `release-signing` produisant des signatures publiquement
+reconnues — SmartScreen cesse d'avertir une fois la réputation établie.
+
+#### Installation (une fois, mainteneur)
+
+1. Postuler sur <https://signpath.org> → *Open Source*. Approbation manuelle.
+2. Créer l'organisation SignPath, un **projet** (slug ex. `Snitch`), lier le
+ build system de confiance *GitHub.com* et installer l'app GitHub SignPath
+ sur ce dépôt (requis pour la vérification d'origine).
+3. Créer une **politique release-signing** restreinte aux builds de tag, avec
+ une configuration d'artefact couvrant `*.exe` dans un ZIP.
+4. Dans GitHub → *Settings → Secrets and variables → Actions* :
+ - Variables : `SIGNPATH_ORGANIZATION_ID`, `SIGNPATH_PROJECT_SLUG`,
+ `SIGNPATH_POLICY_SLUG`
+ - Secret : `SIGNPATH_API_TOKEN`
+5. Terminé — le job CI `SignPath — submit signing request` s'active tout
+ seul au prochain tag. **Tout reste inerte tant que l'étape 4 n'est pas faite.**
+
+### macOS — aucune voie gratuite
+
+Apple exige un compte **Developer Program** payant (99 $/an) pour un
+certificat Developer ID + notarisation. Pas d'alternative gratuite légale.
+En attendant :
+
+- les builds `.zip`/`.dmg` restent non signés — premier lancement via
+ **clic droit → Ouvrir**, ou `xattr -d com.apple.quarantine Snitch.app`
+- les SHA256 de chaque release permettent de vérifier l'intégrité
+- les logs CI publics fournissent la provenance (pipeline reproductible)
+
+### Alternatives évaluées et rejetées
+
+| Option | Pourquoi non |
+|---|---|
+| Azure Trusted Signing | ~10 $/mois — pas gratuit ; abonnements Azure gratuits/sponsorisés explicitement non supportés |
+| Microsoft Store (MSIX) | Microsoft re-signe gratuitement après certification — distribution Store seulement ; piste future |
+| Certificat auto-signé | Neutralise la confiance SmartScreen/Gatekeeper — pire que non signé |
+| Certificats partagés/communautaires | Illégal selon les termes des CA — jamais |
diff --git a/electron/main.js b/electron/main.js
index 1916f92..4d3093b 100644
--- a/electron/main.js
+++ b/electron/main.js
@@ -93,6 +93,19 @@ const iconPath = isDev
const logDir = path.join(backendDataDir(), 'logs')
const logFile = path.join(logDir, 'backend.log')
+// EN: Tiny main-process logger — appends to backend.log next to the backend's
+// own output so update errors land where "Open logs" points.
+// FR: Mini-logger du processus principal — ajoute dans backend.log à côté de
+// la sortie du backend, pour que les erreurs de mise à jour arrivent là
+// où « Ouvrir les logs » pointe.
+const log = {
+ warn: (...args) => {
+ const line = `[main] ${args.join(' ')}`
+ try { fs.appendFileSync(logFile, `${new Date().toISOString()} ${line}\n`) } catch { /* log dir not writable yet */ }
+ console.warn(line)
+ },
+}
+
let mainWindow = null
let splashWindow = null
let backendProc = null
@@ -141,6 +154,91 @@ ipcMain.handle('snitch:set-auto-launch', (_evt, enabled) => {
return app.getLoginItemSettings().openAtLogin
})
+// ── Auto-update / Mise à jour automatique ────────────────────────────────────
+// EN: electron-updater against the public GitHub Releases feed
+// (latest.yml / latest-mac.yml / latest-linux.yml are already published
+// by CI). Privacy note: checking for updates is an OUTBOUND call to
+// github.com — it is on by default but can be disabled in Settings,
+// persisted in userData/update-prefs.json, or killed wholesale via
+// SNITCH_NO_UPDATE=1. Never runs in unpackaged dev builds.
+// FR: electron-updater sur le flux GitHub Releases public
+// (latest.yml / latest-mac.yml / latest-linux.yml déjà publiés par la
+// CI). Note vie privée : la vérification de mise à jour est un appel
+// SORTANT vers github.com — activée par défaut mais désactivable dans
+// les Réglages, persistée dans userData/update-prefs.json, ou coupée
+// entièrement via SNITCH_NO_UPDATE=1. Jamais en dev non empaqueté.
+let autoUpdater = null
+let updateStatus = { state: 'idle' } // EN: idle|checking|available|downloading|downloaded|none|error|dev
+const updatePrefsPath = path.join(app.getPath('userData'), 'update-prefs.json')
+
+function updateCheckEnabled() {
+ if (process.env.SNITCH_NO_UPDATE) return false
+ try {
+ return JSON.parse(fs.readFileSync(updatePrefsPath, 'utf8')).enabled !== false
+ } catch { return true } // EN: default on / FR: activé par défaut
+}
+
+function setUpdateCheckEnabled(enabled) {
+ try {
+ fs.writeFileSync(updatePrefsPath, JSON.stringify({ enabled: !!enabled }))
+ } catch (e) { log.warn('update prefs write failed:', e.message) }
+ rebuildTrayMenu()
+}
+
+function reportUpdate(state, extra = {}) {
+ updateStatus = { state, ...extra }
+ // EN: Forward to the renderer (Settings panel shows it) — guarded, the
+ // window may not exist yet when the first check fires.
+ // FR: Relayer au renderer (le panneau Réglages l'affiche) — protégé, la
+ // fenêtre peut ne pas encore exister au premier contrôle.
+ if (mainWindow && !mainWindow.isDestroyed()) {
+ mainWindow.webContents.send('snitch:update-status', updateStatus)
+ }
+ rebuildTrayMenu()
+}
+
+function initAutoUpdater() {
+ try {
+ ({ autoUpdater } = require('electron-updater'))
+ } catch {
+ log.warn('electron-updater not bundled — update checks disabled')
+ return
+ }
+ autoUpdater.autoDownload = true // EN: download in background / FR: télécharger en tâche de fond
+ autoUpdater.autoInstallOnAppQuit = true
+ autoUpdater.on('checking-for-update', () => reportUpdate('checking'))
+ autoUpdater.on('update-available', (info) => reportUpdate('available', { version: info.version }))
+ autoUpdater.on('update-not-available', () => reportUpdate('none'))
+ autoUpdater.on('download-progress', (p) => reportUpdate('downloading', { percent: Math.round(p.percent) }))
+ autoUpdater.on('update-downloaded', (info) => reportUpdate('downloaded', { version: info.version }))
+ autoUpdater.on('error', (err) => {
+ log.warn('auto-update error:', err.message)
+ reportUpdate('error', { message: err.message })
+ })
+}
+
+function checkForUpdates(manual = false) {
+ if (!autoUpdater || !app.isPackaged) {
+ // EN: Dev builds have no update feed — don't pretend to check.
+ // FR: Les builds dev n'ont pas de flux de mise à jour — ne pas faire semblant.
+ if (manual) reportUpdate('dev')
+ return
+ }
+ if (!manual && !updateCheckEnabled()) return
+ autoUpdater.checkForUpdates().catch(err => {
+ log.warn('update check failed:', err.message)
+ reportUpdate('error', { message: err.message })
+ })
+}
+
+ipcMain.handle('snitch:get-update-status', () => updateStatus)
+ipcMain.handle('snitch:get-update-check', () => updateCheckEnabled())
+ipcMain.handle('snitch:set-update-check', (_e, on) => { setUpdateCheckEnabled(on); return on })
+ipcMain.handle('snitch:check-updates', () => { checkForUpdates(true); return updateStatus })
+ipcMain.handle('snitch:install-update', () => {
+ if (autoUpdater && updateStatus.state === 'downloaded') autoUpdater.quitAndInstall()
+})
+
/**
* EN: Find a free loopback port by binding :0 and releasing — the backend
* then binds the same number. A tiny race window remains (another
@@ -288,14 +386,32 @@ function createMain() {
* Quitter. L'icône est le PNG 512 px généré ; Electron l'adapte selon
* la plateforme.
*/
-function createTray() {
- tray = new Tray(iconPath)
- tray.setToolTip('Snitch')
- const menu = Menu.buildFromTemplate([
+function rebuildTrayMenu() {
+ if (!tray) return
+ const items = [
{
label: 'Show Snitch / Afficher Snitch',
click: () => { if (mainWindow) { mainWindow.show(); mainWindow.focus() } },
},
+ ]
+ // EN: Update entries reflect live state — "restart to update" once the
+ // new version is staged, "check now" otherwise.
+ // FR: Les entrées de mise à jour reflètent l'état courant — « redémarrer
+ // pour mettre à jour » une fois la version prête, « vérifier » sinon.
+ if (updateStatus.state === 'downloaded') {
+ items.push({
+ label: `Restart to update to v${updateStatus.version} / Redémarrer pour v${updateStatus.version}`,
+ click: () => autoUpdater && autoUpdater.quitAndInstall(),
+ })
+ } else if (updateStatus.state === 'downloading') {
+ items.push({ label: `Downloading update… ${updateStatus.percent ?? 0}% / Téléchargement…`, enabled: false })
+ } else if (app.isPackaged) {
+ items.push({
+ label: 'Check for updates / Vérifier les mises à jour',
+ click: () => checkForUpdates(true),
+ })
+ }
+ items.push(
{
label: 'Open logs / Ouvrir les logs',
click: () => shell.openPath(logDir),
@@ -305,8 +421,14 @@ function createTray() {
label: 'Quit / Quitter',
click: () => { isQuitting = true; app.quit() },
},
- ])
- tray.setContextMenu(menu)
+ )
+ tray.setContextMenu(Menu.buildFromTemplate(items))
+}
+
+function createTray() {
+ tray = new Tray(iconPath)
+ tray.setToolTip('Snitch')
+ rebuildTrayMenu()
// EN: A plain click (Windows/Linux) or double-click restores the window.
// FR: Un simple clic (Windows/Linux) ou double-clic restaure la fenêtre.
tray.on('click', () => { if (mainWindow) { mainWindow.show(); mainWindow.focus() } })
@@ -648,6 +770,14 @@ app.whenReady().then(async () => {
createMain()
createTray()
+
+ // EN: Kick the updater once the UI is up — first check now, then every
+ // 6 h while running. Honors the user opt-out (see updateCheckEnabled).
+ // FR: Lancer l'updater une fois l'UI prête — premier contrôle maintenant,
+ // puis toutes les 6 h. Respecte l'opt-out (voir updateCheckEnabled).
+ initAutoUpdater()
+ checkForUpdates()
+ setInterval(() => checkForUpdates(), 6 * 3600 * 1000).unref()
})
app.on('window-all-closed', () => {
diff --git a/electron/package-lock.json b/electron/package-lock.json
index ee25fd3..d6ec40b 100644
--- a/electron/package-lock.json
+++ b/electron/package-lock.json
@@ -1,13 +1,16 @@
{
"name": "snitch",
- "version": "1.0.4",
+ "version": "1.0.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "snitch",
- "version": "1.0.4",
+ "version": "1.0.8",
"license": "AGPL-3.0-or-later",
+ "dependencies": {
+ "electron-updater": "^6.8.9"
+ },
"devDependencies": {
"electron": "^44.7.0",
"electron-builder": "^26.15.3"
@@ -796,7 +799,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
- "dev": true,
"license": "Python-2.0"
},
"node_modules/asn1js": {
@@ -952,7 +954,6 @@
"version": "9.7.0",
"resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",
"integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.3.4",
@@ -1211,7 +1212,6 @@
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -1521,6 +1521,34 @@
"mime": "^2.5.2"
}
},
+ "node_modules/electron-updater": {
+ "version": "6.8.9",
+ "resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.9.tgz",
+ "integrity": "sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==",
+ "license": "MIT",
+ "dependencies": {
+ "builder-util-runtime": "9.7.0",
+ "fs-extra": "^10.1.0",
+ "js-yaml": "^4.1.0",
+ "lazy-val": "^1.0.5",
+ "lodash.escaperegexp": "^4.1.2",
+ "lodash.isequal": "^4.5.0",
+ "semver": "~7.7.3",
+ "tiny-typed-emitter": "^2.1.0"
+ }
+ },
+ "node_modules/electron-updater/node_modules/semver": {
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/electron-winstaller": {
"version": "5.4.0",
"resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz",
@@ -1809,7 +1837,6 @@
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.0",
@@ -2035,7 +2062,6 @@
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
- "dev": true,
"license": "ISC"
},
"node_modules/has-flag": {
@@ -2257,7 +2283,6 @@
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
"integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
- "dev": true,
"funding": [
{
"type": "github",
@@ -2315,7 +2340,6 @@
"version": "6.2.1",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
"integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
"license": "MIT",
"dependencies": {
"universalify": "^2.0.0"
@@ -2338,7 +2362,6 @@
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz",
"integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==",
- "dev": true,
"license": "MIT"
},
"node_modules/lodash": {
@@ -2348,6 +2371,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/lodash.escaperegexp": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz",
+ "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isequal": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
+ "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
+ "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",
+ "license": "MIT"
+ },
"node_modules/lowercase-keys": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",
@@ -2508,7 +2544,6 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "dev": true,
"license": "MIT"
},
"node_modules/node-abi": {
@@ -3058,7 +3093,6 @@
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
- "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
@@ -3321,6 +3355,12 @@
"semver": "bin/semver"
}
},
+ "node_modules/tiny-typed-emitter": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/tiny-typed-emitter/-/tiny-typed-emitter-2.1.0.tgz",
+ "integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==",
+ "license": "MIT"
+ },
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -3411,7 +3451,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 10.0.0"
diff --git a/electron/package.json b/electron/package.json
index 0ce569e..32be0f3 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -66,7 +66,8 @@
"linux": {
"target": [
"AppImage",
- "deb"
+ "deb",
+ "snap"
],
"category": "Utility",
"icon": "icon.png",
@@ -76,6 +77,11 @@
"syncDesktopName": true,
"artifactName": "${productName}-${arch}.${ext}"
},
+ "snap": {
+ "confinement": "strict",
+ "grade": "stable",
+ "plugs": ["network", "network-bind", "network-observe", "desktop", "desktop-legacy", "x11", "wayland", "opengl", "removable-media"]
+ },
"publish": [
{
"provider": "github",
@@ -86,5 +92,8 @@
},
"homepage": "https://github.com/aixisstudio/Snitch",
"desktopName": "Snitch",
- "author": "aiXis Studio"
+ "author": "aiXis Studio",
+ "dependencies": {
+ "electron-updater": "^6.8.9"
+ }
}
diff --git a/electron/preload.js b/electron/preload.js
index 675561a..f113e5b 100644
--- a/electron/preload.js
+++ b/electron/preload.js
@@ -40,4 +40,19 @@ contextBridge.exposeInMainWorld('snitch', {
// false sous Linux).
getAutoLaunch: () => ipcRenderer.invoke('snitch:get-auto-launch'),
setAutoLaunch: (enabled) => ipcRenderer.invoke('snitch:set-auto-launch', enabled),
+ // EN: Auto-update bridge — status push channel plus the four controls the
+ // Settings panel needs. `onUpdateStatus` returns an unsubscribe fn.
+ // FR: Pont de mise à jour — canal de statut poussé + les quatre contrôles
+ // du panneau Réglages. `onUpdateStatus` renvoie une fonction de
+ // désabonnement.
+ getUpdateStatus: () => ipcRenderer.invoke('snitch:get-update-status'),
+ getUpdateCheck: () => ipcRenderer.invoke('snitch:get-update-check'),
+ setUpdateCheck: (on) => ipcRenderer.invoke('snitch:set-update-check', on),
+ checkUpdates: () => ipcRenderer.invoke('snitch:check-updates'),
+ installUpdate: () => ipcRenderer.invoke('snitch:install-update'),
+ onUpdateStatus: (cb) => {
+ const handler = (_e, s) => cb(s)
+ ipcRenderer.on('snitch:update-status', handler)
+ return () => ipcRenderer.removeListener('snitch:update-status', handler)
+ },
})
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 91a8f16..1fdcafb 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -33,7 +33,7 @@ import { computePrivacyScore } from './scoring/privacy'
import { useT } 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 } = useWebSocket(null) // EN: null → resolves the dynamic port/scheme via wsBase()
+ 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()
// FR: null → résout port/schéma dynamiques via wsBase()
const [selected, setSelected] = useState(null)
const [view, setView] = useState('graph')
@@ -191,6 +191,7 @@ export default function App() {
display: 'flex', alignItems: 'center', gap: 8,
}}>
<MediaBadge media={media} />
+ <NetworkBadge ssid={ssid} iface={iface} />
<ThemeToggle />
<LangToggle />
<ViewToggle view={view} onChange={setView} />
@@ -209,7 +210,8 @@ export default function App() {
)}
{showSettings && (
- <SettingsPanel onClose={() => setShowSettings(false)} lang={lang} setLang={setLang} />
+ <SettingsPanel onClose={() => setShowSettings(false)} lang={lang} setLang={setLang}
+ watchlist={watchlist} onWatchlist={updateWatchlist} iface={iface} />
)}
{showOnboarding && <Onboarding onDone={() => setShowOnboarding(false)} />}
@@ -750,8 +752,8 @@ function ThemeToggle() {
)
}
-/** EN: EN/FR language toggle — the headline feature.
- * FR: Bascule de langue EN/FR — la fonctionnalité vedette. */
+/** EN: EN/FR/ES language toggle — the headline feature.
+ * FR: Bascule de langue EN/FR/ES — la fonctionnalité vedette. */
function LangToggle() {
const { lang, setLang } = useT()
return (
@@ -759,7 +761,7 @@ function LangToggle() {
display: 'flex', background: 'var(--surface)',
border: '1px solid var(--border)', borderRadius: 20, overflow: 'hidden',
}}>
- {['en', 'fr'].map(l => (
+ {['en', 'fr', 'es'].map(l => (
<button key={l} onClick={() => setLang(l)} style={{
background: lang === l ? '#3b82f6' : 'transparent',
border: 'none', cursor: 'pointer',
@@ -804,6 +806,33 @@ function ViewToggle({ view, onChange }) {
)
}
+/** EN: Network-context chip — current Wi-Fi SSID when known, otherwise the
+ * capture interface name. Lets the user see "hotel wifi" vs "home" and
+ * which adapter is sniffed, at a glance. Renders nothing when neither
+ * is known.
+ * FR: Pastille de contexte réseau — SSID Wi-Fi courant quand il est connu,
+ * sinon le nom de l'interface de capture. Permet de voir « wifi hôtel »
+ * vs « maison » et quelle carte est écoutée, d'un coup d'œil. Ne rend
+ * rien quand ni l'un ni l'autre n'est connu. */
+function NetworkBadge({ ssid, iface }) {
+ const label = ssid || iface
+ if (!label) return null
+ return (
+ <div title={ssid ? `${iface || ''} · ${ssid}` : iface} style={{
+ display: 'flex', alignItems: 'center', gap: 6,
+ background: 'var(--surface)', border: '1px solid var(--border)',
+ borderRadius: 20, padding: '5px 12px', cursor: 'default',
+ maxWidth: 180, overflow: 'hidden',
+ }}>
+ <Wifi size={11} color="var(--text-muted)" />
+ <span style={{
+ fontSize: 10, color: 'var(--text-muted)', fontWeight: 600,
+ whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden',
+ }}>{label}</span>
+ </div>
+ )
+}
+
/** EN: WebSocket status badge.
* FR: Badge de statut WebSocket. */
function StatusBadge({ status }) {
diff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsx
index 6341fc8..56e9aae 100644
--- a/frontend/src/components/AlertPanel.jsx
+++ b/frontend/src/components/AlertPanel.jsx
@@ -18,7 +18,7 @@ import { useState, useEffect, useRef } from 'react'
import {
Bell, Info, AlertTriangle, AlertCircle, X,
Globe, WifiOff, Wifi, ScanLine,
- Activity, Unlock, TrendingUp, Camera,
+ Activity, Unlock, TrendingUp, Camera, ShieldAlert,
} from 'lucide-react'
import { useT } from '../i18n'
@@ -40,6 +40,8 @@ const TYPE_ICONS = {
DEVICE_OFFLINE: WifiOff,
MEDIA_EXFIL: Camera,
PORT_SCAN: ScanLine,
+ UPLOAD_SPIKE: TrendingUp,
+ WATCHLIST_HIT: ShieldAlert,
}
export function AlertBell({ unread, onClick }) {
diff --git a/frontend/src/components/Settings.jsx b/frontend/src/components/Settings.jsx
index 5f0a59b..c7c91a5 100644
--- a/frontend/src/components/Settings.jsx
+++ b/frontend/src/components/Settings.jsx
@@ -31,34 +31,69 @@ export function SettingsButton({ onClick }) {
)
}
-export function SettingsPanel({ onClose, lang, setLang }) {
+export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchlist, iface }) {
const { t } = useT()
const [settings, setSettings] = useState(null)
const [retention, setRetention] = useState(24)
+ const [uploadMb, setUploadMb] = useState(50)
const [geoStatus, setGeoStatus] = useState(null)
const [geoMsg, setGeoMsg] = useState('')
const [saved, setSaved] = useState(false)
const [autoLaunch, setAutoLaunch] = useState(false)
+ const [ifaces, setIfaces] = useState(null)
+ const [watchInput, setWatchInput] = useState('')
+ const [updStatus, setUpdStatus] = useState(null)
+ const [updCheck, setUpdCheck] = useState(true)
useEffect(() => {
;(async () => {
const base = await apiBase()
const headers = await authHeaders()
try {
- const [s, g] = await Promise.all([
+ const [s, g, i] = await Promise.all([
fetch(`${base}/settings`, { headers }).then(r => r.json()),
fetch(`${base}/geo/status`, { headers }).then(r => r.json()),
+ fetch(`${base}/capture/interfaces`, { headers }).then(r => r.json()),
])
setSettings(s.settings || {})
setRetention(s.settings?.retention_hours ?? 24)
+ setUploadMb(s.settings?.upload_threshold_mb ?? 50)
setGeoStatus(g)
+ setIfaces(i.interfaces || [])
} catch { setSettings({}) }
if (window.snitch?.getAutoLaunch) {
setAutoLaunch(await window.snitch.getAutoLaunch())
}
+ if (window.snitch?.getUpdateStatus) {
+ setUpdStatus(await window.snitch.getUpdateStatus())
+ setUpdCheck(await window.snitch.getUpdateCheck())
+ }
})()
+ // EN: Live update progress pushed by the main process.
+ // FR: Progression des mises à jour poussée par le processus principal.
+ const off = window.snitch?.onUpdateStatus?.(setUpdStatus)
+ return () => off?.()
}, [])
+ async function setInterface(name) {
+ const base = await apiBase()
+ await fetch(`${base}/capture/interface`, {
+ method: 'POST',
+ headers: await authHeaders({ 'Content-Type': 'application/json' }),
+ body: JSON.stringify({ name }),
+ })
+ setSaved(true)
+ setTimeout(() => setSaved(false), 1500)
+ }
+
+ function addWatch(e) {
+ e.preventDefault()
+ const item = watchInput.trim()
+ if (!item || watchlist.includes(item)) { setWatchInput(''); return }
+ onWatchlist?.([...watchlist, item])
+ setWatchInput('')
+ }
+
async function save(key, value) {
const base = await apiBase()
await fetch(`${base}/settings`, {
@@ -134,7 +169,7 @@ export function SettingsPanel({ onClose, lang, setLang }) {
<div style={row}>
<div><div style={label}>{t('settings_language')}</div></div>
<div style={{ display: 'flex', gap: 4 }}>
- {['en', 'fr'].map(l => (
+ {['en', 'fr', 'es'].map(l => (
<button key={l} onClick={() => { setLang(l); save('language', l) }} style={{
background: lang === l ? '#3b82f6' : 'var(--bg)',
border: '1px solid var(--border)', borderRadius: 6,
@@ -185,6 +220,128 @@ export function SettingsPanel({ onClose, lang, setLang }) {
</div>
)}
+ {/* Capture interface / Interface de capture */}
+ <div style={row}>
+ <div>
+ <div style={label}>{t('settings_interface')}</div>
+ <div style={hint}>{t('settings_interface_hint')}</div>
+ </div>
+ <select
+ value={settings?.interface ?? ''}
+ onChange={e => {
+ const v = e.target.value || null
+ setSettings(s => ({ ...s, interface: v }))
+ setInterface(v)
+ }}
+ style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 6, color: 'var(--text)', padding: '4px 8px',
+ fontSize: 11, maxWidth: 180,
+ }}
+ >
+ <option value="">{t('settings_interface_auto')}</option>
+ {(ifaces || []).map(d => (
+ <option key={d.name} value={d.name}>
+ {d.name}{d.description ? ` — ${d.description}` : ''}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Upload alert threshold / Seuil d'alerte d'envoi */}
+ <div style={row}>
+ <div>
+ <div style={label}>{t('settings_upload')}</div>
+ <div style={hint}>{t('settings_upload_hint')}</div>
+ </div>
+ <select
+ value={uploadMb}
+ onChange={e => { const v = +e.target.value; setUploadMb(v); save('upload_threshold_mb', v) }}
+ style={{ background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '4px 8px', fontSize: 11 }}
+ >
+ {[10, 25, 50, 100, 250, 500, 0].map(v => (
+ <option key={v} value={v}>{v === 0 ? t('settings_off') : `${v} MB/min`}</option>
+ ))}
+ </select>
+ </div>
+
+ {/* Watchlist / Liste de surveillance */}
+ <div style={{ ...row, display: 'block' }}>
+ <div style={label}>{t('watchlist_title')}</div>
+ <div style={hint}>{t('watchlist_hint')}</div>
+ <form onSubmit={addWatch} style={{ display: 'flex', gap: 6, marginTop: 8 }}>
+ <input
+ value={watchInput}
+ onChange={e => setWatchInput(e.target.value)}
+ placeholder={t('watchlist_placeholder')}
+ aria-label={t('watchlist_title')}
+ style={{
+ flex: 1, background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 6, color: 'var(--text)', padding: '6px 10px',
+ fontSize: 11, outline: 'none',
+ }}
+ />
+ <button type="submit" style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 6, color: 'var(--text-dim)', padding: '6px 12px',
+ fontSize: 11, cursor: 'pointer',
+ }}>{t('watchlist_add')}</button>
+ </form>
+ {watchlist.length > 0 && (
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 8 }}>
+ {watchlist.map(item => (
+ <button key={item} title={t('watchlist_remove')}
+ onClick={() => onWatchlist?.(watchlist.filter(i => i !== item))}
+ style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 10, color: 'var(--text)', padding: '3px 9px',
+ fontSize: 10, cursor: 'pointer', display: 'flex', gap: 5,
+ alignItems: 'center',
+ }}>
+ {item} <X size={9} />
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Updates (Electron only) / Mises à jour (Electron seul) */}
+ {window.snitch?.getUpdateStatus && (
+ <div style={{ ...row, display: 'block' }}>
+ <div style={label}>{t('update_title')}</div>
+ <div style={hint}>
+ {updStatus?.state === 'checking' && t('update_checking')}
+ {updStatus?.state === 'available' && t('update_available', updStatus.version)}
+ {updStatus?.state === 'downloading' && t('update_downloading', updStatus.percent ?? 0)}
+ {updStatus?.state === 'downloaded' && t('update_ready', updStatus.version)}
+ {updStatus?.state === 'none' && t('update_none')}
+ {updStatus?.state === 'error' && t('update_error')}
+ {(!updStatus || updStatus.state === 'idle' || updStatus.state === 'dev') && t('update_idle')}
+ </div>
+ <div style={{ display: 'flex', gap: 6, marginTop: 8, alignItems: 'center' }}>
+ {updStatus?.state === 'downloaded' ? (
+ <button onClick={() => window.snitch.installUpdate()} style={{
+ background: '#3b82f6', border: 'none', borderRadius: 6,
+ color: '#fff', padding: '6px 12px', fontSize: 11,
+ cursor: 'pointer', fontWeight: 600,
+ }}>{t('update_restart')}</button>
+ ) : (
+ <button onClick={() => window.snitch.checkUpdates()} style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 6, color: 'var(--text-dim)',
+ padding: '6px 12px', fontSize: 11, cursor: 'pointer',
+ }}>{t('update_check_btn')}</button>
+ )}
+ <label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 10, color: 'var(--text-muted)', cursor: 'pointer' }}>
+ <input type="checkbox" checked={updCheck}
+ onChange={async e => setUpdCheck(await window.snitch.setUpdateCheck(e.target.checked))} />
+ {t('update_auto')}
+ </label>
+ </div>
+ <div style={{ ...hint, marginTop: 4 }}>{t('update_privacy')}</div>
+ </div>
+ )}
+
{/* GeoIP / GeoIP */}
<div style={{ ...row, display: 'block' }}>
<div style={label}>{t('geo_title')}</div>
diff --git a/frontend/src/components/Timeline.jsx b/frontend/src/components/Timeline.jsx
index 6de88e2..9961b50 100644
--- a/frontend/src/components/Timeline.jsx
+++ b/frontend/src/components/Timeline.jsx
@@ -37,7 +37,7 @@ export default function Timeline() {
*/
function fmtMinute(iso) {
const d = new Date(iso + ':00Z')
- return d.toLocaleTimeString(lang === 'fr' ? 'fr-FR' : 'en-US', { hour: '2-digit', minute: '2-digit' })
+ return d.toLocaleTimeString({ en: 'en-US', fr: 'fr-FR', es: 'es-ES' }[lang] || 'en-US', { hour: '2-digit', minute: '2-digit' })
}
const fetchTimeline = useCallback(() => {
diff --git a/frontend/src/hooks/useWebSocket.js b/frontend/src/hooks/useWebSocket.js
index 206247a..b7a625b 100644
--- a/frontend/src/hooks/useWebSocket.js
+++ b/frontend/src/hooks/useWebSocket.js
@@ -58,6 +58,13 @@ export function useWebSocket(url) {
const [excludedProcesses, setExcludedProcesses] = useState([])
const [whitelistedIps, setWhitelistedIps] = useState([])
const [media, setMedia] = useState({ mic: [], camera: [] })
+ // EN: Network context surfaced by the backend — Wi-Fi SSID ("" on
+ // Ethernet), active capture interface, user watchlist.
+ // FR: Contexte réseau remonté par le backend — SSID Wi-Fi (« » sur
+ // Ethernet), interface de capture active, watchlist utilisateur.
+ const [ssid, setSsid] = useState('')
+ const [iface, setIface] = useState(null)
+ const [watchlist, setWatchlist] = useState([])
// EN: { secondTimestamp: bytesReceivedThatSecond } — rolled into `bandwidth`.
// FR: { timestampSeconde: octetsReçusCetteSeconde } — agrégé dans `bandwidth`.
const bwRef = useRef({})
@@ -144,6 +151,9 @@ export function useWebSocket(url) {
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)
+ if (msg.watchlist !== undefined) setWatchlist(msg.watchlist)
+ if (msg.ssid !== undefined) setSsid(msg.ssid)
+ if (msg.interface !== undefined) setIface(msg.interface)
const nodeMap = {}, edgeMap = {}, deviceMap = {}
msg.nodes.forEach(n => {
if (n.category === 'lan_device') deviceMap[n.id] = n
@@ -240,6 +250,8 @@ export function useWebSocket(url) {
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)
+ if (msg.watchlist !== undefined) setWatchlist(msg.watchlist)
+ if (msg.interface !== undefined) setIface(msg.interface)
}
// EN: Whitelisted nodes were removed server-side — mirror the removal.
@@ -345,5 +357,15 @@ export function useWebSocket(url) {
setWhitelistedIps(data.whitelisted_ips)
}
- return { nodes, edges, lanDevices, packets, alerts, unread, clearUnread, status, bandwidth, capturing, toggleCapture, portFilter, updatePortFilter, excludedProcesses, updateProcessFilter, whitelistedIps, updateIpWhitelist, media }
+ async function updateWatchlist(items) {
+ const res = await fetch(`${await apiBase()}/watchlist`, {
+ method: 'POST',
+ headers: await authHeaders({ 'Content-Type': 'application/json' }),
+ body: JSON.stringify({ items }),
+ })
+ const data = await res.json()
+ 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 }
}
diff --git a/frontend/src/i18n.jsx b/frontend/src/i18n.jsx
index 87f17fb..48c428b 100644
--- a/frontend/src/i18n.jsx
+++ b/frontend/src/i18n.jsx
@@ -120,6 +120,8 @@ const en = {
alert_DEVICE_OFFLINE: 'Device offline',
alert_MEDIA_EXFIL: 'Media exfiltration',
alert_PORT_SCAN: 'Port scan',
+ alert_UPLOAD_SPIKE: 'Upload spike',
+ alert_WATCHLIST_HIT: 'Watchlist hit',
// EN: Full alert messages built from backend codes + details — the backend
// only sends type + params, never prose.
// FR: Messages d'alerte complets construits depuis les codes + détails du
@@ -133,6 +135,8 @@ const en = {
alertmsg_NEW_LAN_DEVICE: d => `New device on the network: ${d.host || d.ip}`,
alertmsg_DEVICE_OFFLINE: d => `Device went offline: ${d.host || d.ip}`,
alertmsg_PORT_SCAN: d => `Port scan: ${d.source || d.ip} touched ${d.ports}+ ports in ${d.window_s}s`,
+ alertmsg_UPLOAD_SPIKE: d => `Upload spike: ${d.process} sent ${d.mb} MB in ${d.window_s}s`,
+ alertmsg_WATCHLIST_HIT: d => `Watchlist hit: ${d.match} (${d.host || d.ip}) — ${d.process || 'unknown process'}`,
time_just_now: 'just now',
time_seconds: n => `${n}s ago`,
time_minutes: n => `${n}min ago`,
@@ -213,6 +217,29 @@ const en = {
theme_toggle: 'Light / dark theme',
settings_retention: 'History retention',
settings_retention_hint: 'How long traffic & alert history is kept',
+ settings_interface: 'Capture interface',
+ settings_interface_hint: 'Which network adapter is sniffed (restart capture to apply)',
+ settings_interface_auto: 'Auto (first non-loopback)',
+ settings_upload: 'Upload alert threshold',
+ settings_upload_hint: 'Warn when one process uploads more than this per minute',
+ settings_off: 'Off',
+ watchlist_title: 'Watchlist',
+ watchlist_hint: 'Get alerted whenever traffic touches these IPs or domains',
+ watchlist_placeholder: '203.0.113.7 or example.com',
+ watchlist_add: 'Add',
+ watchlist_remove: 'Remove',
+ update_title: 'Updates',
+ update_checking: 'Checking for updates…',
+ update_available: v => `Update available: v${v} — downloading`,
+ update_downloading: p => `Downloading update… ${p}%`,
+ update_ready: v => `v${v} downloaded — restart to install`,
+ update_none: 'Snitch is up to date',
+ update_error: 'Update check failed',
+ update_idle: 'No check yet',
+ update_restart: 'Restart & install',
+ update_check_btn: 'Check now',
+ update_auto: 'Check automatically',
+ update_privacy: 'Checks github.com for new releases — the only outbound call besides the GeoIP download.',
geo_title: 'Geolocation database',
geo_present: dbs => `Installed: ${dbs}`,
geo_none: 'Not installed — IPs are not geolocated',
@@ -361,6 +388,8 @@ const fr = {
alert_DEVICE_OFFLINE: 'Appareil hors ligne',
alert_MEDIA_EXFIL: 'Exfiltration média',
alert_PORT_SCAN: 'Scan de ports',
+ alert_UPLOAD_SPIKE: 'Pic d\'envoi',
+ alert_WATCHLIST_HIT: 'Correspondance watchlist',
alertmsg_NEW_HOST: d => `Nouvel hôte contacté : ${d.host || d.ip}`,
alertmsg_SUSPICIOUS_PROCESS: d => `Processus suspect : ${d.process} → ${d.host || d.ip}`,
alertmsg_SUSPICIOUS_PORT: d => `Port suspect ${d.port} (${d.reason}) → ${d.host || d.ip}`,
@@ -370,6 +399,8 @@ const fr = {
alertmsg_MEDIA_EXFIL: d => `Exfiltration ${d.device === 'camera' ? 'caméra' : 'micro'} suspectée : ${d.process} → ${d.host || d.ip}`,
alertmsg_NEW_LAN_DEVICE: d => `Nouvel appareil sur le réseau : ${d.host || d.ip}`,
alertmsg_DEVICE_OFFLINE: d => `Appareil hors ligne : ${d.host || d.ip}`,
+ alertmsg_UPLOAD_SPIKE: d => `Pic d\'envoi : ${d.process} a envoyé ${d.mb} Mo en ${d.window_s}s`,
+ alertmsg_WATCHLIST_HIT: d => `Watchlist : ${d.match} (${d.host || d.ip}) — ${d.process || 'processus inconnu'}`,
time_just_now: "à l'instant",
time_seconds: n => `il y a ${n}s`,
time_minutes: n => `il y a ${n}min`,
@@ -450,6 +481,29 @@ const fr = {
theme_toggle: 'Thème clair / sombre',
settings_retention: 'Rétention de l\'historique',
settings_retention_hint: 'Durée de conservation du trafic et des alertes',
+ settings_interface: 'Interface de capture',
+ settings_interface_hint: 'Carte réseau écoutée (redémarre la capture)',
+ settings_interface_auto: 'Auto (première non-loopback)',
+ settings_upload: 'Seuil d\'alerte d\'envoi',
+ settings_upload_hint: 'Alerter quand un processus envoie plus que ceci par minute',
+ settings_off: 'Désactivé',
+ watchlist_title: 'Liste de surveillance',
+ watchlist_hint: 'Alerter dès qu\'un trafic touche ces IP ou domaines',
+ watchlist_placeholder: '203.0.113.7 ou example.com',
+ watchlist_add: 'Ajouter',
+ watchlist_remove: 'Retirer',
+ update_title: 'Mises à jour',
+ update_checking: 'Vérification des mises à jour…',
+ update_available: v => `Mise à jour disponible : v${v} — téléchargement`,
+ update_downloading: p => `Téléchargement de la mise à jour… ${p}%`,
+ update_ready: v => `v${v} téléchargée — redémarrer pour installer`,
+ update_none: 'Snitch est à jour',
+ update_error: 'Échec de la vérification',
+ update_idle: 'Pas encore de vérification',
+ update_restart: 'Redémarrer et installer',
+ update_check_btn: 'Vérifier',
+ update_auto: 'Vérifier automatiquement',
+ update_privacy: 'Vérifie github.com pour les nouvelles versions — le seul appel sortant avec le téléchargement GeoIP.',
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',
@@ -490,6 +544,272 @@ const fr = {
onboard_go: 'Compris',
}
+// ── Diccionario español / Spanish dictionary ─────────────────────────────────
+// EN: Third UI language — kept structurally identical to `en` so every key
+// resolves; missing keys would fall back to the raw key name.
+// FR: Troisième langue d'UI — structure identique à `en` pour que chaque clé
+// se résolve ; une clé absente retomberait sur le nom de clé brut.
+const es = {
+ // Navegación
+ nav_graph: 'Grafo',
+ nav_map: 'Mapa',
+
+ // Badge de estado
+ status_connected: 'En directo',
+ status_connecting: 'Conectando…',
+ status_disconnected: 'Desconectado',
+ status_error: 'Error',
+ lan_devices: n => `${n} dispositivo${n > 1 ? 's' : ''} LAN`,
+
+ // Leyenda
+ legend_alert: 'Alerta',
+ legend_unknown: 'Desconocido',
+ legend_router: 'Router',
+ legend_phone: 'Teléfono',
+ legend_pc: 'PC',
+ legend_iot: 'IoT',
+ legend_https: 'HTTPS',
+ legend_tracking: 'Rastreo',
+ legend_cdn: 'CDN',
+ legend_dns: 'DNS',
+
+ // Cabecera + estadísticas de la barra lateral
+ app_name: 'SNITCH',
+ tagline: 'Vigila cada flujo oculto.',
+ footer_credit: 'Desarrollado por aiXis',
+ stat_lan: 'Dispositivos LAN',
+ stat_ext: 'Hosts ext.',
+ stat_traffic: 'Tráfico',
+
+ // Secciones de la barra lateral
+ section_lan: n => `Dispositivos LAN (${n})`,
+ section_ext: (n, total) => total ? `Hosts externos (${n}/${total})` : `Hosts externos (${n})`,
+ section_packets: 'Tráfico reciente',
+
+ // Etiquetas de los campos de detalle de nodo
+ field_ip: 'IP',
+ field_mac: 'MAC',
+ field_hostname: 'Nombre de host',
+ field_vendor: 'Fabricante',
+ field_type: 'Tipo',
+ field_country: 'País',
+ field_city: 'Ciudad',
+ field_org: 'Org',
+ field_category: 'Categoría',
+ field_traffic: 'Tráfico',
+ field_packets: 'Paquetes',
+ processes: 'Procesos',
+ online: 'en línea',
+ offline: 'fuera de línea',
+
+ // Búsqueda
+ search_placeholder: 'Buscar host, IP, país…',
+ cat_all: 'Todo',
+ cat_unknown: 'Desconocido',
+ cat_alerted: 'Alertas',
+ cat_safe: 'Seguro',
+ cat_tracking: 'Rastreo',
+ cat_cdn: 'CDN',
+ cat_dns: 'DNS',
+ cat_admin: 'Admin',
+ cat_local: 'Local',
+ cat_lan_device: 'Dispositivo LAN',
+ cat_other: 'Otro',
+
+ node_local: 'Este dispositivo',
+ hint_local: 'Esta es ESTA máquina — la que ejecuta Snitch. Todo lo que envía o recibe irradia desde el centro del grafo.',
+ unidentified: 'sin identificar',
+ devtype_router: 'Router',
+ devtype_phone: 'Teléfono',
+ devtype_pc: 'Ordenador',
+ devtype_tv: 'TV',
+ devtype_iot: 'Dispositivo IoT',
+ devtype_unknown: 'Tipo desconocido',
+ hint_unidentified: 'Aún no identificado — su nombre aparece cuando se anuncia (DNS/mDNS) o se conoce el fabricante de su MAC. Si no lo reconoces, revisa la lista de clientes de tu router.',
+ hint_unresolved: 'Aún sin nombre — el dominio aparece cuando una respuesta DNS o un handshake TLS lo revela.',
+ hint_private_mac: 'Dirección MAC privada (aleatorizada) — iOS/Android/Windows ocultan la real, así que el fabricante no se puede identificar. Es un comportamiento de privacidad normal.',
+ hint_gateway: 'Esta es tu caja/router de internet — TODO tu tráfico pasa físicamente por él, así que verlo comunicar es normal y esperado.',
+ hint_lan_idle: 'Visto en tu red vía la tabla de vecinos — sin datos intercambiados. Una arista discontinua significa « presente », no « hablando ».',
+ hint_lan_active: b => `${b} intercambiados — normalmente anuncios automáticos (Bonjour/mDNS, compartición de archivos). Vigílalo si el volumen sube.`,
+ ext_empty: 'Sin conexiones externas todavía — todo lo que hable tu máquina aparecerá aquí.',
+ legend_edge_solid: 'línea sólida = tráfico',
+ legend_edge_dashed: 'discontinua = visto, sin datos',
+ legend_ring_safe: 'anillo verde = identificado, seguro',
+ legend_ring_warn: 'anillo ámbar = sospechoso',
+ legend_ring_crit: 'anillo rojo = alerta',
+ legend_ring_none: 'sin anillo = no identificado, neutro',
+ legend_perimeter: 'Perímetro LAN',
+ perim_lan: 'RED LOCAL',
+
+ // Panel de alertas
+ alerts_title: 'Alertas',
+ alerts_total: 'total',
+ alerts_empty: 'Sin alertas por ahora',
+ alert_NEW_HOST: 'Host nuevo',
+ alert_SUSPICIOUS_PROCESS: 'Proceso sospechoso',
+ alert_SUSPICIOUS_PORT: 'Puerto sospechoso',
+ alert_BEACON: 'Beacon C2',
+ alert_VOLUME_SPIKE: 'Pico de tráfico',
+ alert_NEW_LAN_DEVICE: 'Dispositivo nuevo',
+ alert_DEVICE_OFFLINE: 'Dispositivo fuera de línea',
+ alert_MEDIA_EXFIL: 'Exfiltración de medios',
+ alert_PORT_SCAN: 'Escaneo de puertos',
+ alert_UPLOAD_SPIKE: 'Pico de subida',
+ alert_WATCHLIST_HIT: 'Coincidencia watchlist',
+ alertmsg_NEW_HOST: d => `Host nuevo contactado: ${d.host || d.ip}`,
+ alertmsg_SUSPICIOUS_PROCESS: d => `Proceso sospechoso: ${d.process} → ${d.host || d.ip}`,
+ alertmsg_SUSPICIOUS_PORT: d => `Puerto sospechoso ${d.port} (${d.reason}) → ${d.host || d.ip}`,
+ alertmsg_BEACON: d => `Regularidad tipo beacon: intervalo ~${d.interval_s}s hacia ${d.host || d.ip}`,
+ alertmsg_VOLUME_SPIKE: d => `Pico de datos hacia ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} KB en ${d.window_s}s`,
+ alertmsg_MEDIA_EXFIL: d => `Posible exfiltración de ${d.device === 'camera' ? 'cámara' : 'micrófono'}: ${d.process} → ${d.host || d.ip}`,
+ alertmsg_NEW_LAN_DEVICE: d => `Nuevo dispositivo en la red: ${d.host || d.ip}`,
+ alertmsg_DEVICE_OFFLINE: d => `Dispositivo desconectado: ${d.host || d.ip}`,
+ alertmsg_PORT_SCAN: d => `Escaneo de puertos: ${d.source || d.ip} tocó ${d.ports}+ puertos en ${d.window_s}s`,
+ alertmsg_UPLOAD_SPIKE: d => `Pico de subida: ${d.process} envió ${d.mb} MB en ${d.window_s}s`,
+ alertmsg_WATCHLIST_HIT: d => `Watchlist: ${d.match} (${d.host || d.ip}) — ${d.process || 'proceso desconocido'}`,
+ time_just_now: 'ahora mismo',
+ time_seconds: n => `hace ${n}s`,
+ time_minutes: n => `hace ${n}min`,
+ time_hours: n => `hace ${n}h`,
+
+ // Puntuación de privacidad
+ privacy_title: 'Puntuación de privacidad',
+ privacy_critical_label: 'Crítica',
+ privacy_excellent_label: 'Excelente',
+ privacy_risk_factors: n => `${n} factor${n !== 1 ? 'es' : ''} de riesgo`,
+ privacy_more_factors: n => `+${n} factor${n > 1 ? 'es' : ''} más`,
+ privacy_label_excellent: 'Excelente',
+ privacy_label_good: 'Buena',
+ privacy_label_average: 'Media',
+ privacy_label_weak: 'Débil',
+ privacy_label_critical: 'Crítica',
+
+ // Timeline
+ timeline_packets: n => `${n.toLocaleString()} paquetes`,
+ timeline_alerts: n => `${n} alerta${n > 1 ? 's' : ''}`,
+ timeline_live: 'En directo',
+
+ // Botón de captura
+ capture_stop: 'Detener',
+ capture_start: 'Iniciar',
+ capture_stopping: 'Deteniendo…',
+ capture_starting: 'Iniciando…',
+
+ // Filtro de puertos
+ port_filter: 'Puertos',
+ port_all: 'Todos los puertos',
+ port_placeholder: 'Añadir puerto (ej. 443)',
+ port_invalid: 'Puerto inválido',
+
+ // Exportar
+ export_btn: 'Exportar',
+ export_graph_json: 'Grafo (JSON)',
+ export_graph_csv: 'Grafo (CSV)',
+ export_alerts_json: 'Alertas (JSON)',
+ export_alerts_csv: 'Alertas (CSV)',
+
+ // Filtro de procesos
+ process_filter: 'Apps',
+ process_filter_hint: 'Clic para ocultar la app del grafo',
+ process_none: 'Sin procesos detectados aún',
+ process_clear: 'Mostrar todas las apps',
+
+ // Lista blanca de IP
+ ip_whitelist: 'De confianza',
+ ip_whitelist_hint: 'Las IP de confianza ya no se capturan ni se muestran',
+ ip_placeholder: 'Añadir IP (ej. 1.1.1.1)',
+ ip_invalid: 'Dirección IP inválida',
+ ip_clear: 'Vaciar la lista',
+ whitelist_action: 'Marcar como de confianza',
+
+ // Mapa
+ map_you: 'Tú',
+ map_located: n => `${n} host${n !== 1 ? 's' : ''} localizado${n !== 1 ? 's' : ''}`,
+ map_no_geo: 'sin geo',
+
+ // Factores de la puntuación
+ score_trackers: n => `${n} rastreador${n > 1 ? 'es' : ''} contactado${n > 1 ? 's' : ''}`,
+ score_tracker_traffic: pct => `${pct}% del tráfico hacia rastreadores`,
+ score_ad_networks: n => `${n} red${n > 1 ? 'es' : ''} publicitaria${n > 1 ? 's' : ''}`,
+ score_beacons: n => `${n} comportamiento${n > 1 ? 's' : ''} tipo beacon`,
+ score_susp_proc: n => `${n} proceso${n > 1 ? 's' : ''} sospechoso${n > 1 ? 's' : ''}`,
+ score_susp_ports: n => `${n} puerto${n > 1 ? 's' : ''} peligroso${n > 1 ? 's' : ''}`,
+ score_critical_alerts: n => `${n} alerta${n > 1 ? 's' : ''} crítica${n > 1 ? 's' : ''}`,
+ score_warnings: n => `${n} avisos`,
+ score_https_ratio: pct => `${pct}% de tráfico HTTPS`,
+ score_no_trackers: 'Sin rastreadores detectados',
+
+ // Ajustes
+ settings_title: 'Ajustes',
+ settings_saved: 'Guardado',
+ close: 'Cerrar',
+ settings_language: 'Idioma / Language',
+ theme_toggle: 'Tema claro / oscuro',
+ settings_retention: 'Retención del historial',
+ settings_retention_hint: 'Cuánto tiempo se conserva el tráfico y las alertas',
+ settings_interface: 'Interfaz de captura',
+ settings_interface_hint: 'Qué adaptador de red se escucha (reinicia la captura)',
+ settings_interface_auto: 'Auto (primera no-loopback)',
+ settings_upload: 'Umbral de alerta de subida',
+ settings_upload_hint: 'Avisar cuando un proceso suba más de esto por minuto',
+ settings_off: 'Desactivado',
+ watchlist_title: 'Lista de vigilancia',
+ watchlist_hint: 'Alertar en cuanto el tráfico toque estas IP o dominios',
+ watchlist_placeholder: '203.0.113.7 o example.com',
+ watchlist_add: 'Añadir',
+ watchlist_remove: 'Quitar',
+ update_title: 'Actualizaciones',
+ update_checking: 'Buscando actualizaciones…',
+ update_available: v => `Actualización disponible: v${v} — descargando`,
+ update_downloading: p => `Descargando actualización… ${p}%`,
+ update_ready: v => `v${v} descargada — reiniciar para instalar`,
+ update_none: 'Snitch está al día',
+ update_error: 'Falló la comprobación',
+ update_idle: 'Sin comprobación todavía',
+ update_restart: 'Reiniciar e instalar',
+ update_check_btn: 'Comprobar ahora',
+ update_auto: 'Comprobar automáticamente',
+ update_privacy: 'Consulta github.com para nuevas versiones — la única llamada saliente junto a la descarga GeoIP.',
+ geo_title: 'Base de geolocalización',
+ geo_present: dbs => `Instalada: ${dbs}`,
+ geo_none: 'No instalada — las IP no se geolocalizan',
+ geo_download_btn: 'Descargar DB-IP Lite (gratis)',
+ geo_consent: 'Descarga ~50 MB de db-ip.com (CC BY 4.0). Es la única llamada saliente posible de Snitch.',
+ geo_downloading: 'Descargando…',
+ geo_done: n => `${n} base(s) descargada(s)`,
+ geo_failed: 'Descarga fallida — revisa tu conexión',
+ diag_title: 'Diagnóstico',
+ diag_hint: 'Logs e info del sistema para informes de error',
+ diag_open_logs: 'Logs',
+ diag_export: 'Exportar',
+ settings_note: 'Todos los ajustes se guardan localmente. Snitch no envía nada a terceros.',
+ nav_apps: 'Aplicaciones',
+ ignore_alert: 'Ignorar este tipo/este host',
+
+ // Vista de aplicaciones
+ apps_empty: 'Sin procesos atribuidos todavía',
+ apps_process: 'Proceso',
+ apps_destinations: 'Hosts',
+ apps_packets: 'Paquetes',
+ apps_volume: 'Volumen',
+ apps_top_dest: 'Destinos principales',
+ apps_history_60m: 'Última hora (bytes/min)',
+ alertmsg_NEW_HOSTS: n => `${n} host${n > 1 ? 's' : ''} nuevo${n > 1 ? 's' : ''} contactado${n > 1 ? 's' : ''}`,
+ settings_autolaunch: 'Iniciar al arrancar',
+ settings_autolaunch_hint: 'Arrancar Snitch automáticamente al iniciar sesión',
+
+ // Onboarding
+ onboard_title: 'Bienvenido a Snitch',
+ onboard_sub: 'Visualizador de tráfico de red en tiempo real — privado por diseño.',
+ onboard_priv_title: 'Todo se queda en esta máquina',
+ onboard_priv_body: 'Metadatos de tráfico, alertas e historial se guardan en una base SQLite local. Sin cuenta, sin nube, sin telemetría.',
+ onboard_capture_title: 'Qué se captura',
+ onboard_capture_body: 'Solo cabeceras de paquetes: IP de destino, puertos, volúmenes, nombres de proceso, nombres DNS y SNI TLS. Los contenidos nunca se leen.',
+ onboard_out_title: 'Qué sale de la máquina',
+ onboard_out_body: 'Nada por defecto. La única llamada saliente posible es la descarga de la base de geolocalización, que tú mismo lanzas en Ajustes.',
+ onboard_go: 'Entendido',
+}
+
// ── Context / Contexte ───────────────────────────────────────────────────────
const I18nContext = createContext(null)
@@ -510,7 +830,7 @@ export function I18nProvider({ children }) {
localStorage.setItem('snitch_lang', l)
setLangState(l)
}
- const dict = lang === 'fr' ? fr : en
+ const dict = { en, fr, es }[lang] || en
function t(key, ...args) {
// EN: Own-property check — without it, keys like "constructor" would