Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.
Python cybersecurityd3jsebpfedrelectronfastapifirewallfleet-managementlinuxlittle-snitch-alternativemacosnetwork-monitornetwork-securitypacket-captureprivacyreactrustself-hostedsiemwindows
feat: Scapy-free capture engine + correctness/privacy hardening
MoneyLisa7f626a4916b9
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.mdnew file mode 100644index 0000000..c8f3f58--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.md@@ -0,0 +1,21 @@+---+name: Bug report / Rapport de bug+about: Something is broken / Quelque chose est cassé+labels: bug+---++**OS / Système** : (Windows 11 / Ubuntu 24.04 / macOS 15…)++**Snitch version / Version Snitch** :++**How you run it / Comment vous le lancez** : (Electron installer / `snitch` CLI / Docker / dev)++**What happened / Ce qui s'est passé** :++**What you expected / Ce que vous attendiez** :++**Logs** (from `logs/snitch.log` or backend console — **remove any IPs/hostnames you consider private** / retirez les IP/noms d'hôtes privés) :++```+paste here / collez ici+```diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.mdnew file mode 100644index 0000000..64e52f1--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.md@@ -0,0 +1,11 @@+---+name: Feature request / Demande de fonctionnalité+about: Suggest an idea / Proposer une idée+labels: enhancement+---++**The problem it solves / Le problème résolu** :++**The feature / La fonctionnalité** :++**Privacy impact / Impact vie privée** : (Snitch makes zero outbound calls — does this feature need one? / Snitch n'émet aucun appel sortant — cette fonctionnalité en nécessite-t-elle un ?)diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 0000000..222d1d7--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,17 @@+## What / Quoi++<!-- One sentence + linked issue / Une phrase + issue liée -->++## Checklist++- [ ] Tests pass / Les tests passent (`pytest backend/tests`, `npm test`)+- [ ] New dependencies are AGPL-3.0-compatible (no GPL-2.0-only)+- [ ] No new outbound network call (or it is explicitly opt-in)+- [ ] UI strings exist in EN and FR / Chaînes UI en EN et FR+- [ ] README updated if behavior changed / README mis à jour si le comportement change++## Verified / Vérifié++- [ ] Windows+- [ ] Linux+- [ ] macOSdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex dbebf74..d563ef6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1,19 +1,26 @@# Snitch — continuous integration.-# EN: Python lint (ruff, critical rules only) + pytest, and the frontend-# vitest suite + production build on every push/PR.-# FR: Lint Python (ruff, règles critiques seulement) + pytest, et la suite-# vitest frontend + build de production à chaque push/PR.+# EN: Python lint (ruff, critical rules only) + pytest on all three OSes,+# frontend vitest + production build on every push/PR.+# Release job (tags only): per-OS PyInstaller build + SHA256 checksums.+# FR: Lint Python (ruff, règles critiques) + pytest sur les trois OS, vitest+# frontend + build de production à chaque push/PR.+# Job release (tags seulement) : build PyInstaller par OS + checksums SHA256.name: CIon:push:branches: [main]+ tags: ['v*']pull_request:jobs:backend:- runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, windows-latest, macos-latest]+ runs-on: ${{ matrix.os }}steps:- uses: actions/checkout@v4- uses: actions/setup-python@v5@@ -25,6 +32,7 @@ jobs:run: ruff check backend --select E9,F- name: Pytestrun: cd backend && python -m pytest tests/ -v+ shell: bashfrontend:runs-on: ubuntu-latest@@ -36,6 +44,50 @@ jobs:- name: Install + test + buildrun: |cd frontend- npm install+ npm cinpm testnpm run build++ # EN: Per-OS PyInstaller build — runs on tags; verifies the spec compiles+ # everywhere and produces checksums for the release.+ # FR: Build PyInstaller par OS — sur tags ; vérifie que le spec compile+ # partout et produit les checksums pour la release.+ package:+ if: startsWith(github.ref, 'refs/tags/')+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, windows-latest, macos-latest]+ runs-on: ${{ matrix.os }}+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: '3.11'+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ - name: Build frontend+ run: cd frontend && npm ci && npm run build+ - name: Install backend deps + PyInstaller+ run: pip install -r backend/requirements.txt pyinstaller+ - name: PyInstaller build (onedir)+ run: cd backend && pyinstaller backend.spec --distpath ../dist/backend+ - name: SHA256 checksums+ shell: bash+ run: |+ cd dist/backend+ tar czf snitch-backend-${{ matrix.os }}.tar.gz snitch-backend+ sha256sum snitch-backend-${{ matrix.os }}.tar.gz > snitch-backend-${{ matrix.os }}.sha256+ - uses: actions/upload-artifact@v4+ with:+ name: snitch-backend-${{ matrix.os }}+ path: dist/backend/*.tar.gz*+ # EN: Code signing/notarization placeholders — wire your secrets here:+ # Windows: signtool + Azure Trusted Signing / cert in secrets+ # macOS: codesign + notarytool (APPLE_ID/TEAM_ID secrets)+ # They are intentionally disabled until secrets are configured.+ # FR: Placeholders signature/notarisation — branchez vos secrets ici :+ # Windows : signtool + Azure Trusted Signing / cert dans secrets+ # macOS : codesign + notarytool (secrets APPLE_ID/TEAM_ID)+ # Volontairement désactivés tant que les secrets ne sont pas configurés.diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 0000000..c3b2e1b--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,20 @@+# Code of Conduct / Code de conduite++## English++This project follows the [Contributor Covenant v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).++Be kind. Assume good faith. No harassment, no personal attacks, no+publishing others' private information. Maintainers may remove content and+ban contributors who violate these rules.++Report unacceptable behavior via the repository's Security tab or maintainer+contact listed in the profile.++## Français++Ce projet suit le [Contributor Covenant v2.1](https://www.contributor-covenant.org/fr/version/2/1/code_of_conduct/).++Soyez bienveillants. Présumez la bonne foi. Pas de harcèlement, pas+d'attaques personnelles, pas de publication d'informations privées. Les+mainteneurs peuvent retirer du contenu et exclure les contrevenants.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..0e55eb9--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,45 @@+# Contributing / Contribuer++## English++Thanks for your interest! Snitch is a bilingual (EN/FR) project — code+comments and user-facing text should exist in both languages where practical.++**Ground rules**++- **License compatibility**: new dependencies must be AGPL-3.0-compatible+ (MIT, BSD, ISC, Apache-2.0, LGPL). GPL-2.0-only is a hard no.+- **No outbound calls**: never add code that contacts a third-party service+ without explicit, opt-in user consent.+- **Bilingual**: docstrings and UI strings in English AND French.+- **Tests**: every bug fix ships a test. `pytest backend/tests` and+ `npm test` in `frontend/` must pass.+- **Keep diffs focused** — one concern per PR.++**Dev setup**++```bash+cd backend && pip install -r requirements.txt -r requirements-dev.txt+cd frontend && npm install+```++Backend: `python run_backend.py` (needs capture privileges).+Frontend: `npm run dev` → http://localhost:5173/?token=<token from backend output>.++## Français++Merci de votre intérêt ! Snitch est un projet bilingue (EN/FR) — les+commentaires de code et les textes utilisateur doivent exister dans les deux+langues autant que possible.++**Règles de base**++- **Compatibilité de licence** : les nouvelles dépendances doivent être+ compatibles AGPL-3.0 (MIT, BSD, ISC, Apache-2.0, LGPL). GPL-2.0-only est+ exclu.+- **Aucun appel sortant** : jamais de code contactant un service tiers sans+ consentement explicite et opt-in de l'utilisateur.+- **Bilingue** : docstrings et chaînes UI en anglais ET en français.+- **Tests** : chaque correction s'accompagne d'un test. `pytest+ backend/tests` et `npm test` dans `frontend/` doivent passer.+- **Diffs ciblées** — un sujet par PR.diff --git a/Dockerfile b/Dockerfileindex f531ffc..bcc40c9 100644--- a/Dockerfile+++ b/Dockerfile@@ -9,13 +9,15 @@ COPY frontend/ ./RUN npm run build# ── Stage 2: Python runtime ───────────────────────────────────────────────────-# EN: Slim Python image + libpcap (required by Scapy for raw packet capture).-# FR: Image Python légère + libpcap (requise par Scapy pour la capture brute).+# EN: Slim Python image + libpcap — the capture engine is a ctypes binding+# (capture/pcap.py), so libpcap0.8 is the only native dependency needed.+# FR: Image Python légère + libpcap — le moteur de capture est une liaison+# ctypes (capture/pcap.py), donc libpcap0.8 est la seule dépendance native.FROM python:3.11-slim-bookwormWORKDIR /appRUN apt-get update \- && apt-get install -y --no-install-recommends libpcap-dev \+ && apt-get install -y --no-install-recommends libpcap0.8 \&& rm -rf /var/lib/apt/lists/*# EN: Install Python dependencies first to leverage Docker layer caching.diff --git a/PRIVACY.md b/PRIVACY.mdnew file mode 100644index 0000000..be9c7ad--- /dev/null+++ b/PRIVACY.md@@ -0,0 +1,58 @@+# Privacy / Confidentialité++## English++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.++**Outbound network calls made by Snitch itself: none.** The application only:++- captures packets on your local interfaces (passive observation),+- reads your system ARP/neighbour table (no active scanning),+- resolves reverse DNS via your OS resolver — standard PTR lookups that+ already happen implicitly with any network activity,+- 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.++**What is stored locally:**++| Data | Location | Retention |+|---|---|---|+| Per-minute traffic aggregates | `snitch.db` | 24 h (configurable: `retention_hours` setting) |+| Alert history | `snitch.db` | same retention window |+| Settings (filters, whitelist, language…) | `snitch.db` | until you change them |+| API token | `api_token.txt` (0600) | regenerated per launch under Electron |+| Logs | `logs/snitch.log` (rotating) | ~5 MB max |++Data directory: `data/` in dev/Docker, `%LOCALAPPDATA%\Snitch` on Windows,+`~/Library/Application Support/Snitch` on macOS, `~/.local/share/snitch` on+Linux when running installed.++## Français++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.++**Appels réseau émis par Snitch : aucun.** L'application se contente de :++- capturer les paquets sur vos interfaces locales (observation passive),+- lire la table ARP/voisinage système (pas de scan actif),+- résoudre le DNS inverse via le résolveur de votre OS — des requêtes PTR+ standard qui ont déjà lieu implicitement avec toute activité réseau,+- 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.+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.mdindex 93a0f11..429df13 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@ The entire interface is available in **English and French**: use the `EN / FR` t| 15/30/60-min Timeline | Sliding history stored locally in SQLite (24 h retention) || Anomaly Detection | Flags port scans, beaconing, potential exfiltration || Process Attribution | Know which app generates which traffic (top 5 per connection) |-| LAN Scanner | ARP discovery of all devices on your local network |+| LAN Scanner | Passive discovery via the system ARP table (no broadcast scans) || Privacy Score | Real-time score of your outgoing traffic exposure || Bandwidth Monitor | Live MB/s sparkline || EN / FR UI | Full bilingual interface, one click to switch |@@ -40,19 +40,21 @@ The entire interface is available in **English and French**: use the `EN / FR` t| Layer | Technology ||---|---|-| Packet capture | Python — Scapy — Npcap (Windows) / libpcap (Linux) |+| Packet capture | ctypes → libpcap — Npcap (Windows) / libpcap (Linux/macOS) — own parser (IPv4/IPv6/TCP/UDP/DNS/TLS-SNI) || Backend API | FastAPI — WebSockets — SQLite || Frontend | React 18 — Vite — D3.js v7 — TopoJSON |-| Desktop wrapper | Electron 28 |-| Geolocation | MaxMind GeoLite2 (offline; ip-api.com fallback is **opt-in**) |+| Desktop wrapper | Electron 33 |+| Geolocation | **Offline only** — DB-IP Lite (CC BY 4.0) or MaxMind GeoLite2 `.mmdb` in the user data dir |### Security & privacy- **API token** — every REST endpoint and the WebSocket require a token. Electron generates it per launch; in Docker/browser it's printed once in the backend logs and stored in `data/api_token.txt`. Open the UI with `http://localhost:8000/?token=<TOKEN>` (or enter it when prompted).- **Loopback-only by default** — the API binds `127.0.0.1` in every mode. Set `SNITCH_BIND=0.0.0.0` only if you explicitly want LAN access (token auth still applies).- **CORS/WebSocket origin allowlist** — only `localhost:5173`, the backend's own origin and Electron `file://` pages may connect.-- **Geolocation is offline-first** — drop `GeoLite2-City.mmdb` into `data/` for fully local lookups (free MaxMind account required to download the DB). The ip-api.com fallback is **disabled by default** because it sends contacted IPs to a third party over plaintext HTTP; enable it only deliberately with `SNITCH_ONLINE_GEO=1`.-- **All data stays local** — `snitch.db` (24 h sliding window) and `data/logs/snitch.log` never leave the machine.+- **Geolocation is offline-only** — there is *no* online lookup. Drop `dbip-city-lite.mmdb` + `dbip-asn-lite.mmdb` ([DB-IP Lite](https://db-ip.com/db/lite.php), CC BY 4.0) or `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) into `<data_dir>/geo/` for local lookups. Without a DB, IPs simply show no geo — nothing is ever sent to a third party.+- **All data stays local** — `snitch.db` (24 h sliding window, configurable via `retention_hours` setting) and `data/logs/snitch.log` never leave the machine. No telemetry, no outbound calls.+- **Settings persist** — port filters, excluded processes and the IP whitelist are stored in SQLite and restored on restart.+- **LAN devices** are discovered passively from the system ARP table — no active broadcast scanning.### Docker (Linux)@@ -138,10 +140,10 @@ npm run build:dir```snitch/-├── backend/ Python FastAPI + Scapy capture engine+├── backend/ Python FastAPI + libpcap capture engine (ctypes, own parser)├── frontend/ React + D3.js UI (EN/FR)├── electron/ Electron wrapper (main, splash, preload)-├── data/ Runtime data (SQLite DB, GeoLite2 DB)+├── data/ Runtime data (SQLite DB, .mmdb geo DBs in geo/)└── dist/ Compiled output (backend exe, installer)```@@ -163,7 +165,7 @@ Toute l'interface est disponible en **français et en anglais** : utilisez le s| Timeline 15/30/60 min | Historique glissant stocké localement dans SQLite (rétention 24 h) || Détection d'anomalies | Signale scans de ports, beaconing, exfiltration potentielle || Attribution processus | Sachez quelle app génère quel trafic (top 5 par connexion) |-| Scanner LAN | Découverte ARP de tous les appareils du réseau local |+| Scanner LAN | Découverte passive via la table ARP système (aucun scan broadcast) || Score de confidentialité | Score en temps réel de l'exposition de votre trafic sortant || Moniteur de débit | Sparkline MB/s en direct || UI FR / EN | Interface entièrement bilingue, bascule en un clic |@@ -172,19 +174,21 @@ Toute l'interface est disponible en **français et en anglais** : utilisez le s| Couche | Technologie ||---|---|-| Capture de paquets | Python — Scapy — Npcap (Windows) / libpcap (Linux) |+| Capture de paquets | ctypes → libpcap — Npcap (Windows) / libpcap (Linux/macOS) — parseur maison (IPv4/IPv6/TCP/UDP/DNS/SNI-TLS) || API backend | FastAPI — WebSockets — SQLite || Frontend | React 18 — Vite — D3.js v7 — TopoJSON |-| Conteneur bureau | Electron 28 |-| Géolocalisation | MaxMind GeoLite2 (hors ligne ; repli ip-api.com **opt-in**) |+| Conteneur bureau | Electron 33 |+| Géolocalisation | **Hors ligne uniquement** — DB-IP Lite (CC BY 4.0) ou MaxMind GeoLite2 `.mmdb` dans le dossier de données |### Sécurité & confidentialité- **Jeton API** — chaque endpoint REST et le WebSocket exigent un jeton. Electron le génère à chaque lancement ; sous Docker/navigateur il est affiché une fois dans les logs du backend et stocké dans `data/api_token.txt`. Ouvrez l'UI via `http://localhost:8000/?token=<JETON>` (ou saisissez-le à l'invite).- **Loopback uniquement par défaut** — l'API écoute sur `127.0.0.1` dans tous les modes. Ne mettez `SNITCH_BIND=0.0.0.0` que pour un accès LAN explicite (le jeton reste exigé).- **Liste blanche CORS/Origin WebSocket** — seuls `localhost:5173`, l'origine propre du backend et les pages `file://` d'Electron peuvent se connecter.-- **Géolocalisation hors ligne d'abord** — déposez `GeoLite2-City.mmdb` dans `data/` pour des recherches 100 % locales (compte MaxMind gratuit requis pour télécharger la base). Le repli ip-api.com est **désactivé par défaut** car il envoie les IP contactées à un tiers en HTTP clair ; ne l'activez que volontairement avec `SNITCH_ONLINE_GEO=1`.-- **Toutes les données restent locales** — `snitch.db` (fenêtre glissante de 24 h) et `data/logs/snitch.log` ne quittent jamais la machine.+- **Géolocalisation 100 % hors ligne** — il n'y a *aucune* recherche en ligne. Déposez `dbip-city-lite.mmdb` + `dbip-asn-lite.mmdb` ([DB-IP Lite](https://db-ip.com/db/lite.php), CC BY 4.0) ou `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) dans `<data_dir>/geo/`. Sans base, les IP n'ont simplement pas de géo — rien n'est jamais envoyé à un tiers.+- **Toutes les données restent locales** — `snitch.db` (fenêtre glissante de 24 h, configurable via le réglage `retention_hours`) et `data/logs/snitch.log` ne quittent jamais la machine. Pas de télémétrie, aucun appel sortant.+- **Réglages persistés** — filtres de ports, processus exclus et whitelist IP sont stockés dans SQLite et restaurés au redémarrage.+- **Appareils LAN** découverts passivement via la table ARP système — aucun scan broadcast actif.### Docker (Linux)@@ -239,10 +243,10 @@ cd frontend && npm test```snitch/-├── backend/ Moteur de capture Python FastAPI + Scapy+├── backend/ Moteur de capture Python FastAPI + libpcap (ctypes, parseur maison)├── frontend/ Interface React + D3.js (FR/EN)├── electron/ Conteneur Electron (main, splash, preload)-├── data/ Données d'exécution (SQLite, GeoLite2)+├── data/ Données d'exécution (SQLite, bases .mmdb dans geo/)└── dist/ Sortie compilée (exe backend, installateur)```diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..e6bc682--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,40 @@+# Security Policy / Politique de sécurité++## Reporting / Signalement++**EN:** Please report vulnerabilities privately via GitHub's "Report a+vulnerability" feature (Security tab) or by emailing the maintainers listed+in the repository profile. Do not open public issues for security problems.++**FR :** Signalez les vulnérabilités en privé via la fonction « Report a+vulnerability » de GitHub (onglet Security) ou par email aux mainteneurs.+N'ouvrez pas d'issue publique pour les problèmes de sécurité.++## Local attack surface / Surface d'attaque locale++The API exposes your full traffic graph — it is protected by design:++- **Token auth** on every REST endpoint and the WebSocket+ (`X-Snitch-Token` or `?token=`). Generated per launch under Electron,+ persisted 0600 otherwise.+- **Loopback bind** (`127.0.0.1`) in all modes by default.+- **Origin allowlist** on the WebSocket handshake (loopback hosts + `null`)+ to block cross-site WebSocket hijacking.+- **Restricted CORS** — loopback origins only, no credentials.++## Privileges / Privilèges++Packet capture requires elevated privileges. Current limitation: under+Electron the **whole app** (Chromium UI included) runs elevated on Windows+(`requireAdministrator`). A privileged-daemon split (unprivileged UI ++elevated capture backend) is a known roadmap item — see issues.++- Windows: Administrator + Npcap (installed by you from npcap.com)+- Linux: `setcap cap_net_raw,cap_net_admin` on the binary, or root+- macOS: read access to `/dev/bpf*` (experimental support)++## Dependencies / Dépendances++Scapy was removed (GPL-2.0-only + large attack surface). Capture is a minimal+ctypes binding to libpcap plus our own bounded parser. Dependencies are+pinned and scanned by Dependabot.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..17c7fd7--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,51 @@+# Third-Party Notices / Mentions de tiers++**EN:** Snitch is licensed AGPL-3.0-or-later. Below are the third-party+components and data sources it uses, with their licenses. We deliberately+removed GPL-2.0-only code (Scapy) to keep the dependency set AGPL-compatible.++**FR :** Snitch est sous licence AGPL-3.0-or-later. Voici les composants tiers+et sources de données utilisés, avec leurs licences. Nous avons retiré+volontairement le code GPL-2.0-only (Scapy) pour garder des dépendances+compatibles AGPL.++## Runtime dependencies / Dépendances d'exécution++| Component / Composant | License / Licence |+|---|---|+| FastAPI | MIT |+| Uvicorn | BSD-3-Clause |+| Starlette | BSD-3-Clause |+| Pydantic / pydantic-core | MIT |+| websockets | BSD-3-Clause |+| maxminddb | Apache-2.0 |+| psutil | BSD-3-Clause |+| python-dotenv | BSD-3-Clause |+| aiofiles | Apache-2.0 |+| React | MIT |+| Vite | MIT |+| D3.js | ISC |+| TopoJSON | ISC |+| lucide-react | ISC |+| Electron | MIT |+| electron-builder | MIT |++## System libraries / Bibliothèques système++| Component / Composant | License / Licence | Notes |+|---|---|---|+| libpcap | BSD-3-Clause | Linux/macOS packet capture — loaded via ctypes, not bundled |+| Npcap | Npcap License | Windows capture driver — **NOT bundled**; user installs from [npcap.com](https://npcap.com). The free version is not redistributable; Snitch only links to the official site. |++## Data sources / Sources de données++| Data / Données | License / Licence | Attribution |+|---|---|---|+| DB-IP Lite (City + ASN) | CC BY 4.0 | "IP Geolocation by [DB-IP](https://db-ip.com)" — recommended default |+| MaxMind GeoLite2 | GeoLite2 EULA | Optional alternative — requires a free MaxMind account; review the EULA before use |++Both `.mmdb` databases are placed manually by the user in `<data_dir>/geo/`.+No database is downloaded or contacted automatically.++Les deux bases `.mmdb` sont placées manuellement par l'utilisateur dans+`<data_dir>/geo/`. Aucune base n'est téléchargée ni contactée automatiquement.diff --git a/backend/api/main.py b/backend/api/main.pyindex 47f7506..e819af5 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -2,10 +2,24 @@Snitch — FastAPI application.EN: Heart of the backend. Owns the in-memory graph state (nodes / edges /- LAN devices), receives packets from the Scapy sniffer thread, enriches- them (DNS + geolocation + classification), feeds the anomaly detector,- persists aggregates to SQLite and pushes realtime updates over the- WebSocket.+ LAN devices), receives packets from the libpcap sniffer thread, enriches+ them (observed DNS/SNI + offline geolocation + classification), feeds the+ anomaly detector, persists aggregates to SQLite and pushes realtime+ updates over the WebSocket.++ Pipeline (post-review redesign):+ capture thread → bounded queue.Queue → ONE asyncio drain task every+ 250 ms → per-packet: filter + detector (lock-guarded) + graph aggregates+ → ONE "batch" broadcast per tick. No per-packet coroutine storm, no+ per-packet broadcast — json.dumps runs once per 250 ms window.++ Enrichment is fire-and-forget: packets create/update nodes immediately+ with a stub, a deduplicated background task fills in geo/hostname when it+ resolves, then broadcasts a node patch. In-flight lookups are deduplicated+ per IP and failures are never cached permanently.++ Settings (port filter, excluded processes, whitelist) persist in SQLite+ and are restored at startup.Security model (see api/security.py):- every REST endpoint requires the API token (X-Snitch-Token header or@@ -14,10 +28,27 @@ EN: Heart of the backend. Owns the in-memory graph state (nodes / edges /- CORS is restricted to the dev server / self-origin / file:// (Electron)FR: Cœur du backend. Détenir l'état du graphe en mémoire (nœuds / arêtes /- appareils LAN), recevoir les paquets du thread du sniffer Scapy, les- enrichir (DNS + géolocalisation + classification), alimenter le détecteur- d'anomalies, persister les agrégats dans SQLite et pousser les mises à- jour temps réel via le WebSocket.+ appareils LAN), recevoir les paquets du thread du sniffer libpcap, les+ enrichir (DNS/SNI observés + géolocalisation hors ligne ++ classification), alimenter le détecteur d'anomalies, persister les+ agrégats dans SQLite et pousser les mises à jour temps réel via le+ WebSocket.++ Pipeline (refonte post-revue) :+ thread de capture → queue.Queue bornée → UNE tâche asyncio de vidage+ toutes les 250 ms → par paquet : filtre + détecteur (sous verrou) ++ agrégats du graphe → UNE diffusion « batch » par tick. Plus de tempête+ de coroutines ni de broadcast par paquet — json.dumps tourne une fois+ par fenêtre de 250 ms.++ L'enrichissement est en tâche de fond : les paquets créent/mettent à jour+ les nœuds immédiatement avec un stub, une tâche dédupliquée remplit+ géo/nom d'hôte quand la résolution aboutit, puis diffuse un patch de+ nœud. Les recherches en vol sont dédupliquées par IP et les échecs ne sont+ jamais cachés définitivement.++ Les réglages (filtre de ports, processus exclus, whitelist) persistent+ dans SQLite et sont restaurés au démarrage.Modèle de sécurité (voir api/security.py) :- chaque endpoint REST exige le jeton API (en-tête X-Snitch-Token ou@@ -27,22 +58,27 @@ FR: Cœur du backend. Détenir l'état du graphe en mémoire (nœuds / arêtes /"""import asyncio+import ipaddressimport jsonimport logging+import queueimport threadingimport timefrom contextlib import asynccontextmanagerfrom datetime import datetime, timezone+from pathlib import Pathfrom fastapi import Depends, FastAPI, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddleware+from fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel, Field-from api.security import ALLOWED_ORIGINS_LIST, require_token, ws_authorized+from api.security import ALLOWED_ORIGIN_REGEX, require_token, ws_authorizedfrom capture.sniffer import Packet, PacketSnifferfrom capture.media_monitor import MediaMonitor, MediaStatefrom classifier.traffic import classify-from resolver.dns_geo import enrich_ip+from resolver.dns_geo import (enrich_ip, is_private, learn_dns_answers,+ learn_sni, lookup_domain)from scanner.arp_scanner import ARPScanner, Devicefrom detection.anomaly import AnomalyDetectorimport storage.db as db@@ -58,20 +94,33 @@ lan_devices: dict[str, dict] = {}connected_clients: list[WebSocket] = []enrichment_cache: dict[str, dict] = {} # EN: remote_ip -> geo/hostname result# FR: remote_ip -> résultat geo/hostname+_inflight_geo: set[str] = set() # EN: IPs with a running enrich task+ # FR: IP avec une tâche d'enrichissement en coursdetector = AnomalyDetector()_loop: asyncio.AbstractEventLoop | None = None_sniffer: PacketSniffer | None = None_scanner: ARPScanner | None = None+_media_monitor: MediaMonitor | None = None_capturing: bool = True_port_filter: list[int] = []_excluded_processes: set[str] = set()_whitelisted_ips: set[str] = set()-_media_state: dict = {"mic": [], "camera": []}+_media_state: dict = {"mic": [], "camera": [], "supported": True}+_shutdown = False++# EN: Bounded packet queue between the capture thread and the event loop.+# Full → drop oldest: a stale burst is less useful than fresh traffic.+# FR: File de paquets bornée entre le thread de capture et la boucle.+# Pleine → on jette le plus ancien : une rafale périmée vaut moins que+# le trafic frais.+_pkt_queue: queue.Queue = queue.Queue(maxsize=20_000)# EN: Hard caps so a long-running instance can't leak memory.# FR: Plafonds stricts pour qu'une instance longue durée ne fuie pas de mémoire.MAX_GRAPH_NODES = 800MAX_ENRICHMENT_CACHE = 4096+DRAIN_INTERVAL_S = 0.25 # EN: ~4 Hz batch broadcasts / FR: ~4 lots par seconde+DRAIN_MAX_PACKETS = 2_000 # EN: per tick / FR: par tick# ── Pydantic request models / Modèles de requête Pydantic ────────────────────@@ -93,201 +142,344 @@ class WhitelistBody(BaseModel):ips: list[str] = Field(default_factory=list)+class SettingsBody(BaseModel):+ """EN: /settings payload — generic key/value settings persisted to SQLite.+ FR: Charge utile de /settings — réglages clé/valeur persistés dans SQLite."""+ settings: dict = Field(default_factory=dict)++# ── Broadcast / Diffusion ────────────────────────────────────────────────────async def broadcast(message: dict) -> None:"""EN: Send a JSON message to every connected WebSocket client; drop the- dead ones.+ dead ones. Serialized ONCE for all clients.FR: Envoyer un message JSON à tous les clients WebSocket connectés ;- retirer les morts.+ retirer les morts. Sérialisé UNE fois pour tous les clients."""+ if not connected_clients:+ return+ payload = json.dumps(message)dead = []for ws in connected_clients:try:- await ws.send_text(json.dumps(message))+ await ws.send_text(payload)except Exception:dead.append(ws)for ws in dead:connected_clients.remove(ws)-# ── Packet handling / Traitement des paquets ─────────────────────────────────+# ── Noise filtering / Filtrage du bruit ──────────────────────────────────────-def on_packet(pkt: Packet) -> None:+def _is_noise_ip(ip: str) -> bool:"""- EN: Called from the Scapy sniffer THREAD — schedule the async handler on- the event loop.- FR: Appelé depuis le THREAD du sniffer Scapy — planifier le handler async- sur la boucle d'événements.+ EN: True for traffic that must never become a node: multicast, broadcast,+ loopback, link-local, unspecified. These used to spawn duplicate+ "external" nodes before the ARP scan populated lan_devices.+ FR: True pour le trafic qui ne doit jamais devenir un nœud : multicast,+ broadcast, loopback, link-local, non spécifié. Ce trafic créait des+ nœuds « externes » doublons avant que le scan ARP ne remplisse+ lan_devices."""- if _loop is None:- return- asyncio.run_coroutine_threadsafe(_handle_packet(pkt), _loop)+ try:+ a = ipaddress.ip_address(ip)+ return (a.is_multicast or a.is_loopback or a.is_link_local+ or a.is_unspecified or a.is_reserved)+ except ValueError:+ return ip == "255.255.255.255"-async def _handle_packet(pkt: Packet) -> None:+def _ensure_lan_device(ip: str) -> dict:"""- EN: Per-packet pipeline — filter, enrich, update graph, persist, detect.- LAN-destined traffic is accounted on the device node instead of being- dropped, so LAN devices show real byte counters.- FR: Pipeline par paquet — filtrer, enrichir, mettre à jour le graphe,- persister, détecter. Le trafic vers le LAN est comptabilisé sur le nœud- de l'appareil au lieu d'être ignoré, pour que les appareils LAN- affichent de vrais compteurs d'octets.+ EN: Guarantee a lan_devices entry for a private peer — even before the+ ARP table yields it (router, DHCP guests). Real discoveries later+ overwrite these stub fields with vendor/hostname info.+ FR: Garantir une entrée lan_devices pour un pair privé — même avant que+ la table ARP ne le livre (routeur, invités DHCP). Les vraies+ découvertes écrasent ensuite ces champs stub avec fabricant/nom d'hôte."""- if pkt.process_name and pkt.process_name in _excluded_processes:- return+ key = f"lan:{ip}"+ dev = lan_devices.get(key)+ if dev is None:+ dev = {+ "id": key, "ip": ip, "mac": None,+ "label": ip, "hostname": None, "vendor": "",+ "category": "lan_device", "device_type": "unknown",+ "online": True, "bytes": 0, "packets": 0,+ "color": "#64748b", "alerted": False,+ }+ lan_devices[key] = dev+ edges[f"lan-edge-{ip}"] = {+ "id": f"lan-edge-{ip}", "source": "local", "target": key,+ "protocol": "LAN", "label": "LAN", "color": "#64748b",+ "bytes": 0, "packets": 0, "dashed": True,+ }+ return dev- remote_ip = pkt.dst_ip if pkt.direction == "out" else pkt.src_ip- if remote_ip in _whitelisted_ips:- return+# ── Packet handling / Traitement des paquets ─────────────────────────────────- # ── LAN traffic accounting / Comptabilisation du trafic LAN ─────────────- lan_key = f"lan:{remote_ip}"- if lan_key in lan_devices:- lan_devices[lan_key]["bytes"] = lan_devices[lan_key].get("bytes", 0) + pkt.size- lan_devices[lan_key]["packets"] = lan_devices[lan_key].get("packets", 0) + 1- edge = edges.get(f"lan-edge-{remote_ip}")- if edge:- edge["bytes"] += pkt.size- edge["packets"] += 1- await broadcast({- "type": "device_update",- "device": lan_devices[lan_key],- "edge": edge,- "is_new": False,- })+def on_packet(pkt: Packet) -> None:+ """+ EN: Called from the capture THREAD — drop into the bounded queue. The+ event loop drains it in batches; no coroutine is created per packet.+ FR: Appelé depuis le THREAD de capture — déposer dans la file bornée. La+ boucle d'événements la vide par lots ; aucune coroutine n'est créée+ par paquet.+ """+ try:+ _pkt_queue.put_nowait(pkt)+ except queue.Full:+ try:+ _pkt_queue.get_nowait() # EN: drop oldest / FR: jeter le plus ancien+ _pkt_queue.put_nowait(pkt)+ except (queue.Empty, queue.Full):+ pass+++def _request_enrichment(ip: str) -> None:+ """+ EN: Kick off a deduplicated background enrichment for `ip`. The node is+ patched + broadcast when the lookup resolves. Failures cache a stub+ for 5 min only — never permanently.+ FR: Lancer un enrichissement de fond dédupliqué pour `ip`. Le nœud est+ patché + rediffusé quand la résolution aboutit. Les échecs sont cachés+ 5 min seulement — jamais définitivement.+ """+ if ip in _inflight_geo or ip in enrichment_cache:return+ _inflight_geo.add(ip)- # EN: Enrich once per IP (reverse DNS + geolocation), then cache it.- # The cache is bounded — evict the oldest half when full.- # FR: Enrichir une fois par IP (DNS inverse + géolocalisation), puis cacher.- # Le cache est borné — évincer la moitié la plus ancienne quand plein.- if remote_ip not in enrichment_cache:- if len(enrichment_cache) > MAX_ENRICHMENT_CACHE:- for stale in list(enrichment_cache.keys())[: MAX_ENRICHMENT_CACHE // 2]:- enrichment_cache.pop(stale, None)+ async def _enrich() -> None:try:- enrichment_cache[remote_ip] = await enrich_ip(remote_ip)+ geo = await enrich_ip(ip)+ if len(enrichment_cache) > MAX_ENRICHMENT_CACHE:+ for stale in list(enrichment_cache.keys())[: MAX_ENRICHMENT_CACHE // 2]:+ enrichment_cache.pop(stale, None)+ enrichment_cache[ip] = geo+ node = nodes.get(ip)+ if node:+ node.update({+ "label": geo.get("hostname") or node["label"],+ "country": geo.get("country"),+ "country_code": geo.get("country_code"),+ "city": geo.get("city"),+ "lat": geo.get("lat"),+ "lon": geo.get("lon"),+ "org": geo.get("org"),+ })+ await broadcast({"type": "node_update", "node": node})except Exception as exc:- logger.debug("enrich_ip failed for %s: %s", remote_ip, exc)- enrichment_cache[remote_ip] = {"ip": remote_ip, "hostname": None, "private": False}- geo = enrichment_cache[remote_ip]-- category = classify(geo.get("hostname"), pkt.dst_port, pkt.protocol)-- # ── Graph node update / Mise à jour du nœud ─────────────────────────────- node_id = remote_ip- if node_id not in nodes:- # EN: Bound the graph — evict the lowest-traffic non-alerted node.- # FR: Borner le graphe — évincer le nœud au plus faible trafic non alerté.- if len(nodes) >= MAX_GRAPH_NODES:- _evict_weakest_node()- nodes[node_id] = {- "id": node_id,- "label": geo.get("hostname") or remote_ip,- "ip": remote_ip,- "country": geo.get("country"),- "country_code": geo.get("country_code"),- "city": geo.get("city"),- "lat": geo.get("lat"),- "lon": geo.get("lon"),- "org": geo.get("org"),- "category": category.category,- "color": category.color,- "bytes": 0,- "packets": 0,- "alerted": False,- }+ logger.debug("enrich_ip failed for %s: %s", ip, exc)+ enrichment_cache[ip] = {"ip": ip, "hostname": None, "private": False,+ "_expires": time.time() + 300}+ finally:+ _inflight_geo.discard(ip)- nodes[node_id]["bytes"] += pkt.size- nodes[node_id]["packets"] += 1-- # EN: Track per-process traffic on this node (top talkers in the UI).- # FR: Suivre le trafic par processus sur ce nœud (top parleurs dans l'UI).- if pkt.process_name:- procs = nodes[node_id].setdefault("processes", {})- if pkt.process_name not in procs:- procs[pkt.process_name] = {"bytes": 0, "packets": 0}- procs[pkt.process_name]["bytes"] += pkt.size- procs[pkt.process_name]["packets"] += 1-- # ── Graph edge update / Mise à jour de l'arête ──────────────────────────- edge_id = f"local-{node_id}-{pkt.protocol}"- if edge_id not in edges:- edges[edge_id] = {- "id": edge_id,- "source": "local",- "target": node_id,- "protocol": pkt.protocol,- "label": category.label,- "color": category.color,- "bytes": 0,- "packets": 0,- }- edges[edge_id]["bytes"] += pkt.size- edges[edge_id]["packets"] += 1+ asyncio.get_running_loop().create_task(_enrich())- # EN: Persist per-minute aggregates — batched, non-blocking.- # FR: Persister les agrégats par minute — par lots, sans blocage.- minute = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M")- db.accumulate(minute, category.category, pkt.size)- # ── Anomaly detection / Détection d'anomalies ───────────────────────────- loop = asyncio.get_running_loop()- alerts = await loop.run_in_executor(None, detector.analyze_packet, pkt, geo)- for alert in alerts:- if alert.node_id and alert.node_id in nodes:- nodes[alert.node_id]["alerted"] = True- alert_dict = alert.to_dict()- await loop.run_in_executor(None, db.log_alert, alert_dict)- await broadcast({"type": "alert", "alert": alert_dict})+def _geo_for(ip: str) -> dict:+ """+ EN: Best geo info available RIGHT NOW — cached result or a stub with the+ observed DNS/SNI domain. Kicks off background enrichment on a miss.+ FR: Meilleure info géo disponible IMMÉDIATEMENT — résultat en cache ou+ stub avec le domaine DNS/SNI observé. Lance un enrichissement de fond+ en cas d'échec.+ """+ cached = enrichment_cache.get(ip)+ if cached and cached.get("_expires", float("inf")) > time.time():+ return cached+ _request_enrichment(ip)+ return {"ip": ip, "hostname": lookup_domain(ip), "private": is_private(ip)}- await broadcast({- "type": "update",- "node": nodes[node_id],- "edge": edges[edge_id],- "packet": {- "src": pkt.src_ip,- "dst": pkt.dst_ip,- "protocol": pkt.protocol,- "size": pkt.size,- "direction": pkt.direction,- "process": pkt.process_name,++def _process_batch(packets: list[Packet]) -> None:+ """+ EN: One drain tick — runs on the event-loop thread. Per packet: filters,+ LAN accounting, graph aggregation, detection (lock-guarded inside).+ Returns the coalesced broadcast payload pieces.+ FR: Un tick de vidage — tourne sur le thread de la boucle. Par paquet :+ filtres, comptabilisation LAN, agrégation du graphe, détection (sous+ verrou à l'intérieur). Renvoie les morceaux du lot à diffuser.+ """+ touched_nodes: dict[str, dict] = {}+ touched_edges: dict[str, dict] = {}+ touched_devices: dict[str, dict] = {}+ out_packets: list[dict] = []+ out_alerts: list[dict] = []++ for pkt in packets:+ if pkt.process_name and pkt.process_name in _excluded_processes:+ continue++ remote_ip = pkt.dst_ip if pkt.direction == "out" else pkt.src_ip+ if remote_ip in _whitelisted_ips or _is_noise_ip(remote_ip):+ continue++ # EN: Feed the observed-domain map first — DNS answers map many IPs,+ # SNI names the destination of this very packet.+ # FR: Alimenter d'abord la table des domaines observés — les réponses+ # DNS mappent beaucoup d'IP, le SNI nomme la destination de ce+ # paquet même.+ if pkt.dns:+ learn_dns_answers(pkt.dns)+ if pkt.sni:+ learn_sni(remote_ip, pkt.sni)++ # ── LAN accounting / Comptabilisation LAN ───────────────────────────+ if is_private(remote_ip):+ dev = _ensure_lan_device(remote_ip)+ dev["bytes"] += pkt.size+ dev["packets"] += 1+ edge = edges[f"lan-edge-{remote_ip}"]+ edge["bytes"] += pkt.size+ edge["packets"] += 1+ touched_devices[dev["id"]] = dev+ touched_edges[edge["id"]] = edge+ continue++ geo = _geo_for(remote_ip)++ # EN: remote_port — the fix for the inbound classification bug.+ # Category is recomputed and updatable (not frozen at creation).+ # FR: remote_port — la correction du bug de classification entrant.+ # La catégorie est recalculée et modifiable (pas figée à la+ # création).+ category = classify(geo.get("hostname") or pkt.sni,+ pkt.remote_port, pkt.protocol)++ node_id = remote_ip+ node = nodes.get(node_id)+ if node is None:+ if len(nodes) >= MAX_GRAPH_NODES:+ _evict_weakest_node()+ node = {+ "id": node_id,+ "label": geo.get("hostname") or remote_ip,+ "ip": remote_ip,+ "country": geo.get("country"),+ "country_code": geo.get("country_code"),+ "city": geo.get("city"),+ "lat": geo.get("lat"),+ "lon": geo.get("lon"),+ "org": geo.get("org"),+ "category": category.category,+ "color": category.color,+ "bytes": 0, "packets": 0, "alerted": False,+ }+ nodes[node_id] = node+ elif node["category"] == "other" and category.category != "other":+ # EN: Upgrade a placeholder category once DNS/SNI gives a real name.+ # FR: Améliorer une catégorie générique quand DNS/SNI donne un vrai nom.+ node["category"] = category.category+ node["color"] = category.color+ elif node["label"] == remote_ip and geo.get("hostname"):+ node["label"] = geo["hostname"]++ node["bytes"] += pkt.size+ node["packets"] += 1++ if pkt.process_name:+ procs = node.setdefault("processes", {})+ proc = procs.setdefault(pkt.process_name, {"bytes": 0, "packets": 0})+ proc["bytes"] += pkt.size+ proc["packets"] += 1++ edge_id = f"local-{node_id}-{pkt.protocol}"+ edge = edges.setdefault(edge_id, {+ "id": edge_id, "source": "local", "target": node_id,+ "protocol": pkt.protocol, "label": category.label,+ "color": category.color, "bytes": 0, "packets": 0,+ })+ edge["bytes"] += pkt.size+ edge["packets"] += 1++ db.accumulate(datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M"),+ category.category, pkt.size)++ # EN: Detection runs in the event loop — analyze_packet is+ # lock-guarded internally, no executor hop needed.+ # FR: La détection tourne dans la boucle — analyze_packet est+ # protégée par verrou, pas besoin de saut d'executor.+ for alert in detector.analyze_packet(pkt, geo):+ if alert.node_id and alert.node_id in nodes:+ nodes[alert.node_id]["alerted"] = True+ alert_dict = alert.to_dict()+ db.log_alert(alert_dict)+ out_alerts.append(alert_dict)++ touched_nodes[node_id] = node+ touched_edges[edge_id] = edge+ out_packets.append({+ "src": pkt.src_ip, "dst": pkt.dst_ip,+ "protocol": pkt.protocol, "size": pkt.size,+ "direction": pkt.direction, "process": pkt.process_name,+ "remote_port": pkt.remote_port, "sni": pkt.sni,"timestamp": pkt.timestamp,- },- })+ })++ return {+ "type": "batch",+ "nodes": list(touched_nodes.values()),+ "edges": list(touched_edges.values()),+ "devices": list(touched_devices.values()),+ "packets": out_packets,+ "alerts": out_alerts,+ }+++async def _drain_loop() -> None:+ """+ EN: THE consumer of _pkt_queue — one task, ~4 Hz. Each tick drains up to+ DRAIN_MAX_PACKETS, aggregates them, and broadcasts a single "batch"+ message. Replaces the old per-packet coroutine+broadcast storm.+ FR: LE consommateur de _pkt_queue — une tâche, ~4 Hz. Chaque tick vide+ jusqu'à DRAIN_MAX_PACKETS paquets, les agrège et diffuse un unique+ message « batch ». Remplace l'ancienne tempête coroutine+broadcast+ par paquet.+ """+ while not _shutdown:+ batch: list[Packet] = []+ for _ in range(DRAIN_MAX_PACKETS):+ try:+ batch.append(_pkt_queue.get_nowait())+ except queue.Empty:+ break+ if batch:+ try:+ await broadcast(_process_batch(batch))+ except Exception as exc:+ logger.exception("packet batch failed: %s", exc)+ await asyncio.sleep(DRAIN_INTERVAL_S)def _evict_weakest_node() -> None:"""EN: Remove the lowest-byte, non-alerted, non-local node (and its edges)- when the graph hits MAX_GRAPH_NODES. Called from _handle_packet.+ when the graph hits MAX_GRAPH_NODES.FR: Retirer le nœud au plus faible trafic, non alerté et non « local »- (et ses arêtes) quand le graphe atteint MAX_GRAPH_NODES. Appelé depuis- _handle_packet.+ (et ses arêtes) quand le graphe atteint MAX_GRAPH_NODES."""- candidates = [- n for n in nodes.values()- if n["id"] != "local" and not n.get("alerted")- ]+ candidates = [n for n in nodes.values()+ if n["id"] != "local" and not n.get("alerted")]if not candidates:returnweakest = min(candidates, key=lambda n: n.get("bytes", 0))wid = weakest["id"]nodes.pop(wid, None)enrichment_cache.pop(wid, None)- for eid in [eid for eid, e in edges.items() if e["target"] == wid or e["source"] == wid]:+ for eid in [eid for eid, e in edges.items()+ if e["target"] == wid or e["source"] == wid]:edges.pop(eid, None)# ── LAN device handling / Gestion des appareils LAN ──────────────────────────def on_device(device: Device, is_new: bool) -> None:- """EN: ARP scanner callback — schedules async handling.- FR: Callback du scanner ARP — planifie le traitement async."""+ """EN: ARP-table scanner callback — schedules async handling.+ FR: Callback du scanner de table ARP — planifie le traitement async."""if _loop is None:returnasyncio.run_coroutine_threadsafe(_handle_device(device, is_new), _loop)@@ -301,8 +493,8 @@ async def _handle_device(device: Device, is_new: bool) -> None:arête pointillée vers « local », lancer les règles niveau appareil."""node = device.to_dict()- # EN: Preserve accumulated byte counters across rediscovery.- # FR: Préserver les compteurs d'octets accumulés à travers les redécouvertes.+ # EN: Preserve accumulated counters + merge any stub the packet path made.+ # FR: Préserver les compteurs + fusionner l'éventuel stub du chemin paquets.prev = lan_devices.get(node["id"])if prev:node["bytes"] = prev.get("bytes", 0)@@ -332,7 +524,7 @@ async def _handle_device(device: Device, is_new: bool) -> None:if alert.node_id and alert.node_id in lan_devices:lan_devices[alert.node_id]["alerted"] = Truealert_dict = alert.to_dict()- await loop.run_in_executor(None, db.log_alert, alert_dict)+ db.log_alert(alert_dict)await broadcast({"type": "alert", "alert": alert_dict})await broadcast({@@ -348,23 +540,24 @@ async def _handle_device(device: Device, is_new: bool) -> None:def _on_media_change(state: MediaState) -> None:"""EN: MediaMonitor callback — sync the detector's media sets and notify UI.+ `supported=False` (macOS) is forwarded so the badge can hide.FR: Callback MediaMonitor — synchroniser les ensembles média du détecteur- et notifier l'UI.+ et notifier l'UI. `supported=False` (macOS) est transmis pour que le+ badge se masque."""global _media_state- _media_state = {"mic": state.mic, "camera": state.camera}+ _media_state = {"mic": state.mic, "camera": state.camera,+ "supported": state.supported}detector.update_media_state(state.mic, state.camera)if _loop:asyncio.run_coroutine_threadsafe(- broadcast({"type": "media", "mic": state.mic, "camera": state.camera}),- _loop,- )+ broadcast({"type": "media", **_media_state}), _loop)def _flush_loop() -> None:"""EN: Periodically flush the traffic accumulator to SQLite.FR: Vider périodiquement l'accumulateur de trafic vers SQLite."""- while True:+ while not _shutdown:time.sleep(10)try:db.flush()@@ -374,15 +567,16 @@ def _flush_loop() -> None:def _cleanup_loop() -> None:"""- EN: Drop rows older than 24h — the timeline is a sliding window, the DB- must not grow forever.- FR: Supprimer les lignes de plus de 24 h — la timeline est une fenêtre- glissante, la BDD ne doit pas grossir indéfiniment.+ EN: Drop rows older than the configured retention — the DB must not grow+ forever. Retention is a persisted setting (hours, default 24).+ FR: Supprimer les lignes plus anciennes que la rétention configurée — la+ BDD ne doit pas grossir indéfiniment. La rétention est un réglage+ persisté (heures, défaut 24)."""- while True:+ while not _shutdown:time.sleep(3600)try:- db.cleanup_old_data(hours=24)+ db.cleanup_old_data(hours=int(db.get_setting("retention_hours", 24)))except Exception as exc:logger.error("db cleanup failed: %s", exc)@@ -390,8 +584,8 @@ def _cleanup_loop() -> None:# ── Capture lifecycle / Cycle de vie de la capture ───────────────────────────def _start_capture() -> None:- """EN: (Re)start sniffer + ARP scanner in daemon threads.- FR: (Re)démarrer sniffer + scanner ARP dans des threads daemon."""+ """EN: (Re)start sniffer + ARP-table scanner in daemon threads.+ FR: (Re)démarrer sniffer + scanner de table ARP dans des threads daemon."""global _sniffer, _scanner, _capturing_sniffer = PacketSniffer(callback=on_packet, ports=_port_filter)threading.Thread(target=_sniffer.start, daemon=True).start()@@ -412,10 +606,27 @@ def _stop_capture() -> None:logger.info("capture stopped")+def _load_settings() -> None:+ """+ EN: Restore persisted settings from SQLite at startup — filters, whitelist+ and process exclusions survive restarts now.+ 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+ _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 [])+ if _port_filter:+ logger.info("restored port filter: %s", _port_filter)++async def _startup() -> None:- """EN: Startup — create the "local" node, start capture + background threads.- FR: Démarrage — créer le nœud « local », lancer capture + threads d'arrière-plan."""- global _loop+ """EN: Startup — create the "local" node, load settings, start capture ++ drain task + background threads.+ FR: Démarrage — créer le nœud « local », charger les réglages, lancer+ capture + tâche de vidage + threads d'arrière-plan."""+ global _loop, _media_monitor_loop = asyncio.get_running_loop()nodes["local"] = {@@ -424,20 +635,57 @@ async def _startup() -> None:"bytes": 0, "packets": 0, "alerted": False,}+ _load_settings()_start_capture()+ asyncio.get_running_loop().create_task(_drain_loop())threading.Thread(target=_flush_loop, daemon=True).start()threading.Thread(target=_cleanup_loop, daemon=True).start()- media = MediaMonitor(callback=_on_media_change, interval=3)- threading.Thread(target=media.start, daemon=True).start()+ _media_monitor = MediaMonitor(callback=_on_media_change, interval=3)+ threading.Thread(target=_media_monitor.start, daemon=True).start()+++async def _shutdown_all() -> None:+ """+ EN: Ordered shutdown — stop capture sources, drain pending packets, flush+ the DB. Threads are daemons so nothing blocks process exit.+ FR: Arrêt ordonné — stopper les sources de capture, vider les paquets en+ attente, flusher la BDD. Les threads sont daemon donc rien ne bloque+ la sortie du processus.+ """+ global _shutdown+ _shutdown = True+ _stop_capture()+ if _media_monitor:+ _media_monitor.stop()+ # EN: Final drain + flush so nothing in flight is lost.+ # FR: Dernier vidage + flush pour ne rien perdre en vol.+ remaining: list[Packet] = []+ while True:+ try:+ remaining.append(_pkt_queue.get_nowait())+ except queue.Empty:+ break+ if remaining:+ try:+ _process_batch(remaining)+ except Exception as exc:+ logger.error("shutdown drain failed: %s", exc)+ try:+ db.flush()+ except Exception as exc:+ logger.error("final db flush failed: %s", exc)@asynccontextmanagerasync def lifespan(app: FastAPI):- """EN: FastAPI lifespan — startup logic, then yield for the app's life.- FR: Lifespan FastAPI — logique de démarrage, puis yield pour la vie de l'app."""+ """EN: FastAPI lifespan — startup, yield, then clean shutdown.+ FR: Lifespan FastAPI — démarrage, yield, puis arrêt propre."""await _startup()- yield+ try:+ yield+ finally:+ await _shutdown_all()app = FastAPI(title="Snitch API", lifespan=lifespan)@@ -450,7 +698,9 @@ app = FastAPI(title="Snitch API", lifespan=lifespan)# l'attaque « n'importe quelle page ouverte pilote mon API ».app.add_middleware(CORSMiddleware,- allow_origins=ALLOWED_ORIGINS_LIST,+ allow_origin_regex=ALLOWED_ORIGIN_REGEX,+ allow_origins=["null"], # EN: file:// pages (Electron renderer)+ # FR: pages file:// (renderer Electron)allow_methods=["GET", "POST"],allow_headers=["X-Snitch-Token", "Content-Type"],)@@ -479,14 +729,40 @@ async def get_devices() -> dict:@app.get("/alerts", dependencies=_AUTH)async def get_alerts() -> dict:- """EN: Last 100 in-memory alerts. / FR: Les 100 dernières alertes en mémoire."""+ """EN: Alert history — SQLite-backed so it survives restarts; falls back+ to the in-memory tail if the DB read fails.+ FR: Historique des alertes — adossé à SQLite donc survit aux+ redémarrages ; repli sur la queue en mémoire si la lecture échoue."""+ loop = asyncio.get_running_loop()+ try:+ rows = await loop.run_in_executor(None, db.get_alerts, 100)+ if rows:+ return {"alerts": rows}+ except Exception as exc:+ logger.debug("get_alerts db read failed: %s", exc)return {"alerts": detector.history[-100:]}@app.get("/media", dependencies=_AUTH)async def get_media() -> dict:- """EN: Current mic/camera usage. / FR: Usage actuel micro/caméra."""+ """EN: Current mic/camera usage (+ supported flag).+ FR: Usage actuel micro/caméra (+ drapeau supported)."""return _media_state[email protected]("/settings", dependencies=_AUTH)+async def get_settings() -> dict:+ """EN: All persisted settings. / FR: Tous les réglages persistés."""+ loop = asyncio.get_running_loop()+ return {"settings": await loop.run_in_executor(None, db.all_settings)}+[email protected]("/settings", dependencies=_AUTH)+async def post_settings(body: SettingsBody) -> dict:+ """EN: Persist arbitrary settings keys (language, thresholds…).+ FR: Persister des clés de réglage arbitraires (langue, seuils…)."""+ loop = asyncio.get_running_loop()+ for key, value in body.settings.items():+ await loop.run_in_executor(None, db.set_setting, key, value)+ return {"ok": True}+@app.get("/capture/status", dependencies=_AUTH)async def get_capture_status() -> dict:"""EN: Capture state + all active filters. / FR: État de capture + filtres actifs."""@@ -501,6 +777,7 @@ async def get_capture_status() -> dict:async def stop_capture() -> dict:"""EN: Stop sniffing + ARP scan. / FR: Arrêter le sniffing + le scan ARP."""_stop_capture()+ db.set_setting("ports", _port_filter)await broadcast({"type": "capture_status","capturing": False,@@ -515,12 +792,14 @@ async def set_port_filter(body: PortFilterBody) -> dict:"""EN: Restrict capture to a list of ports (empty = all). Graph and detectorruntime state are both reset so the UI only shows matching traffic.+ Persisted — the filter survives restarts.FR: Restreindre la capture à une liste de ports (vide = tous). Le graphe etl'état du détecteur sont réinitialisés pour que l'UI n'affiche que le- trafic correspondant.+ trafic correspondant. Persisté — le filtre survit aux redémarrages."""global _port_filter_port_filter = [p for p in body.ports if 1 <= p <= 65535]+ db.set_setting("ports", _port_filter)# EN: Clear graph + detector state — keep only the "local" node.# FR: Vider graphe + état du détecteur — ne garder que le nœud « local ».@@ -560,9 +839,11 @@ async def start_capture() -> dict:@app.post("/capture/processes", dependencies=_AUTH)async def set_process_filter(body: ProcessFilterBody) -> dict:- """EN: Hide traffic from named processes. / FR: Masquer le trafic de processus nommés."""+ """EN: Hide traffic from named processes (persisted).+ FR: Masquer le trafic de processus nommés (persisté)."""global _excluded_processes_excluded_processes = {str(p) for p in body.excluded}+ db.set_setting("excluded_processes", sorted(_excluded_processes))await broadcast({"type": "capture_status",@@ -576,26 +857,28 @@ async def set_process_filter(body: ProcessFilterBody) -> dict:@app.post("/capture/whitelist", dependencies=_AUTH)async def set_ip_whitelist(body: WhitelistBody) -> dict:"""- EN: Mark IPs as trusted — dropped from capture and display. Removed nodes- also get forgotten by the detector and the enrichment cache, so- un-whitelisting works correctly afterwards.+ EN: Mark IPs as trusted — dropped from capture and display (persisted).+ Removed nodes also get forgotten by the detector and the enrichment+ cache, so un-whitelisting works correctly afterwards.FR: Marquer des IP comme fiables — ignorées de la capture et de- l'affichage. Les nœuds retirés sont aussi oubliés par le détecteur et- le cache d'enrichissement, pour qu'un retrait de la whitelist- fonctionne ensuite correctement.+ l'affichage (persisté). Les nœuds retirés sont aussi oubliés par le+ détecteur et le cache d'enrichissement, pour qu'un retrait de la+ whitelist fonctionne ensuite correctement."""global _whitelisted_ips_whitelisted_ips = {str(ip) for ip in body.ips}+ db.set_setting("whitelisted_ips", sorted(_whitelisted_ips))- removed_ids = [ip for ip in _whitelisted_ips if ip != "local" and nodes.pop(ip, None) is not None]+ removed_ids = [ip for ip in _whitelisted_ips+ if ip != "local" and nodes.pop(ip, None) is not None]if removed_ids:removed_set = set(removed_ids)- for edge_id in [eid for eid, e in edges.items() if e["source"] in removed_set or e["target"] in removed_set]:+ for edge_id in [eid for eid, e in edges.items()+ if e["source"] in removed_set or e["target"] in removed_set]:edges.pop(edge_id, None)for ip in removed_ids:enrichment_cache.pop(ip, None)- detector.forget(ip) # EN: clear seen/beacon/spike state too- # FR: vider aussi l'état seen/beacon/spike+ detector.forget(ip)await broadcast({"type": "capture_status",@@ -624,10 +907,10 @@ async def websocket_endpoint(websocket: WebSocket) -> None:"""EN: Realtime channel. Handshake is gated by ws_authorized() — Originallowlist + token. On success we send the `init` snapshot BEFORE- registering the client so no `update` can reference unknown nodes.+ registering the client so no `batch` can reference unknown nodes.FR: Canal temps réel. Le handshake est filtré par ws_authorized() — listeblanche d'Origin + jeton. En cas de succès on envoie l'instantané- `init` AVANT d'enregistrer le client pour qu'aucun `update` ne+ `init` AVANT d'enregistrer le client pour qu'aucun « batch » neréférence de nœud inconnu."""if not await ws_authorized(websocket):@@ -667,9 +950,6 @@ async def websocket_endpoint(websocket: WebSocket) -> None:# FR: En mode Docker / hors Electron, FastAPI sert le frontend compilé en# fichiers statiques. Monté sur "/", il intercepte toutes les routes non# correspondantes — donc enregistré en DERNIER.-from pathlib import Path-from fastapi.staticfiles import StaticFiles-_frontend_dist = Path(__file__).parent.parent.parent / 'frontend_dist'if _frontend_dist.exists():app.mount('/', StaticFiles(directory=str(_frontend_dist), html=True), name='frontend')diff --git a/backend/api/security.py b/backend/api/security.pyindex 1f1a567..c79edf2 100644--- a/backend/api/security.py+++ b/backend/api/security.py@@ -27,11 +27,11 @@ FR: Trois protections complémentaires :import loggingimport osimport secrets-import sys-from pathlib import Pathfrom fastapi import HTTPException, Request, WebSocket, status+from paths import data_dir+logger = logging.getLogger("snitch.api.security")# EN: Origins allowed to reach the API. `null` covers file:// pages (Electron@@ -39,35 +39,45 @@ logger = logging.getLogger("snitch.api.security")# FR: Origines autorisées à joindre l'API. `null` couvre les pages file://# (renderer Electron) — les navigateurs envoient Origin: null pour les# fichiers locaux.-ALLOWED_ORIGINS = {- "http://localhost:5173", # EN: Vite dev / FR: dev Vite- "http://127.0.0.1:5173",- "http://localhost:8000", # EN: backend serving its own frontend- "http://127.0.0.1:8000", # FR: le backend servant son propre frontend- "null", # EN: file:// (Electron) / FR: file:// (Electron)-}--ALLOWED_ORIGINS_LIST = sorted(ALLOWED_ORIGINS)+# EN: The port is dynamic now (free-port selection), so the allowlist is a+# RULE, not a literal set: loopback hosts on any port + `null` (file://+# Electron). A loopback origin can only come from a local process/page —+# remote origins always fail. Token auth applies on top regardless.+# FR: Le port est désormais dynamique (choix de port libre), donc la liste+# blanche est une RÈGLE, pas un ensemble littéral : hôtes loopback sur tout+# port + `null` (file:// Electron). Une origine loopback ne peut venir que+# d'une page/processus local — les origines distantes échouent toujours.+# L'authentification par jeton s'applique de toute façon par-dessus.+_LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1", "[::1]"}++def _is_loopback_origin(origin: str) -> bool:+ """EN: True when the origin's hostname is loopback (any scheme/port).+ FR: True quand le nom d'hôte de l'origine est loopback (schéma/port quelconques)."""+ try:+ from urllib.parse import urlparse+ host = urlparse(origin).hostname or ""+ return host.lower() in _LOOPBACK_HOSTS+ except Exception:+ return False-def _data_dir() -> Path:+def origin_allowed(origin: str | None) -> bool:"""- EN: Resolve the writable data directory — same rules as storage.db:- SNITCH_DATA_DIR env override, LOCALAPPDATA\\Snitch when frozen by- PyInstaller, otherwise <repo>/data.- FR: Résoudre le dossier de données inscriptible — mêmes règles que- storage.db : SNITCH_DATA_DIR en priorité, LOCALAPPDATA\\Snitch quand- figé par PyInstaller, sinon <dépôt>/data.+ EN: An absent Origin header means a non-browser client (curl, Electron's+ main process) — allowed. Present origins must be loopback or `null`.+ FR: Un en-tête Origin absent signifie un client non-navigateur (curl,+ processus principal d'Electron) — autorisé. Les origines présentes+ doivent être loopback ou `null`."""- env_dir = os.environ.get("SNITCH_DATA_DIR")- if env_dir:- d = Path(env_dir)- elif getattr(sys, "frozen", False):- d = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "Snitch"- else:- d = Path(__file__).parent.parent.parent / "data"- d.mkdir(parents=True, exist_ok=True)- return d+ if origin is None:+ return True+ return origin == "null" or _is_loopback_origin(origin)+++# EN: CORS needs literal strings/regex — a loopback regex mirrors the rule.+# FR: CORS exige des chaînes/regex littérales — une regex loopback reflète la règle.+ALLOWED_ORIGIN_REGEX = r"^https?://(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$"+ALLOWED_ORIGINS_LIST = ["null"]def _load_or_create_token() -> str:@@ -89,7 +99,7 @@ def _load_or_create_token() -> str:if token:return token- token_file = _data_dir() / "api_token.txt"+ token_file = data_dir() / "api_token.txt"try:if token_file.exists():existing = token_file.read_text().strip()@@ -120,6 +130,12 @@ def _load_or_create_token() -> str:API_TOKEN = _load_or_create_token()+def get_token() -> str:+ """EN: Public accessor — the CLI needs the token to build the open-URL.+ FR: Accesseur public — la CLI a besoin du jeton pour construire l'URL."""+ return API_TOKEN++def _extract_token(request: Request) -> str | None:"""EN: Accept `X-Snitch-Token` header (preferred) or `?token=` query param@@ -144,17 +160,6 @@ def require_token(request: Request) -> None:raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API token")-def origin_allowed(origin: str | None) -> bool:- """- EN: An absent Origin header means a non-browser client (curl, Electron's- main process) — allowed. Present origins must be in the allowlist.- FR: Un en-tête Origin absent signifie un client non-navigateur (curl,- processus principal d'Electron) — autorisé. Les origines présentes- doivent figurer dans la liste blanche.- """- return origin is None or origin in ALLOWED_ORIGINS--async def ws_authorized(websocket: WebSocket) -> bool:"""EN: WebSocket gate — validates Origin (anti-CSWSH) and the ?token= param.diff --git a/backend/backend.spec b/backend/backend.specindex 974ee17..ed503ce 100644--- a/backend/backend.spec+++ b/backend/backend.spec@@ -2,22 +2,25 @@## EN: Run from the backend/ directory:# pyinstaller backend.spec --distpath ../dist/backend-# Produces a single-file `snitch-backend` executable that the Electron-# wrapper spawns as a child process.+# Produces a `snitch-backend/` ONEDIR bundle the Electron wrapper spawns+# as a child process. ONEDIR (not onefile) is deliberate: fewer AV false+# positives, faster startup, no temp-dir self-extraction of a+# network-sniffing binary.+#+# UPX is DISABLED — UPX-packed executables that touch the network are a+# well-known antivirus false-positive trigger.## FR: À lancer depuis le dossier backend/ :# pyinstaller backend.spec --distpath ../dist/backend-# Produit un exécutable unique `snitch-backend` que le conteneur Electron-# lance comme processus enfant.--from PyInstaller.utils.hooks import collect_all, collect_submodules+# Produit un bundle ONEDIR `snitch-backend/` que le conteneur Electron+# lance comme processus enfant. ONEDIR (pas onefile) est voulu : moins de+# faux positifs antivirus, démarrage plus rapide, pas d'auto-extraction+# en temp d'un binaire qui sniffe le réseau.+#+# UPX est DÉSACTIVÉ — les exécutables UPX qui touchent au réseau sont un+# déclencheur connu de faux positifs antivirus.-# EN: Pull in ALL of scapy — layers, arch backends, libs and data files.-# Scapy does a lot of dynamic imports, so a plain Analysis misses them.-# FR: On embarque TOUT scapy — couches, backends arch, libs et fichiers de-# données. Scapy fait beaucoup d'imports dynamiques, donc une Analysis-# simple les raterait.-scapy_datas, scapy_binaries, scapy_hiddenimports = collect_all('scapy')+from PyInstaller.utils.hooks import collect_submodulesblock_cipher = None@@ -25,13 +28,11 @@ a = Analysis(['run_backend.py'],pathex=['.'], # EN: backend/ — so api.*, capture.*, etc. resolve# FR: backend/ — pour que api.*, capture.*, etc. se résolvent- binaries=scapy_binaries,- datas=scapy_datas,+ binaries=[],+ datas=[],hiddenimports=(- scapy_hiddenimports-# ── uvicorn internals / éléments internes d'uvicorn ─────────────- + collect_submodules('uvicorn')+ collect_submodules('uvicorn')# ── FastAPI / Starlette / Pydantic ──────────────────────────────+ collect_submodules('starlette')@@ -49,8 +50,8 @@ a = Analysis('aiofiles',]- # ── DNS / networking / réseau ───────────────────────────────────- + collect_submodules('dns')+ # ── mmdb / psutil internals ─────────────────────────────────────+ + collect_submodules('maxminddb')+ ['psutil','psutil._pswindows',@@ -71,8 +72,8 @@ a = Analysis(hookspath=[],hooksconfig={},runtime_hooks=[],- # EN: Exclude heavy unused packages to keep the binary small.- # FR: Exclure les gros paquets inutilisés pour garder un binaire léger.+ # EN: Exclude heavy unused packages to keep the bundle small.+ # FR: Exclure les gros paquets inutilisés pour garder un bundle léger.excludes=['tkinter', 'matplotlib', 'numpy', 'PIL', 'PyQt5', 'wx'],win_no_prefer_redirects=False,win_private_assemblies=False,@@ -85,26 +86,36 @@ pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)exe = EXE(pyz,a.scripts,- a.binaries,- a.zipfiles,- a.datas,[],+ exclude_binaries=True, # EN: ONEDIR mode — binaries go into COLLECT+ # FR: mode ONEDIR — les binaires vont dans COLLECTname='snitch-backend',debug=False,bootloader_ignore_signals=False,strip=False,- upx=True,- upx_exclude=[],- runtime_tmpdir=None,- # EN: Keep a console for debugging; set to False for release builds.- # FR: Garder une console pour le débogage ; passer à False en release.- console=True,+ upx=False, # EN: UPX off — AV false-positive trigger+ # FR: UPX désactivé — faux positifs antivirus+ console=False, # EN: no console window under Electron+ # FR: pas de fenêtre console sous Electrondisable_windowed_traceback=False,argv_emulation=False,target_arch=None,codesign_identity=None,entitlements_file=None,- # EN: Elevation is handled by the Electron wrapper (NSIS requireAdministrator).- # FR: L'élévation est gérée par le conteneur Electron (NSIS requireAdministrator).+ # EN: Elevation is handled by the Electron wrapper (NSIS+ # requireAdministrator) — the backend does not self-elevate.+ # FR: L'élévation est gérée par le conteneur Electron (NSIS+ # requireAdministrator) — le backend ne s'élève pas tout seul.uac_admin=False,)++coll = COLLECT(+ exe,+ a.binaries,+ a.zipfiles,+ a.datas,+ strip=False,+ upx=False,+ upx_exclude=[],+ name='snitch-backend',+)diff --git a/backend/capture/__init__.py b/backend/capture/__init__.pyindex 21fa94f..0de2d3b 100644--- a/backend/capture/__init__.py+++ b/backend/capture/__init__.py@@ -1,2 +1,4 @@-# EN: Packet capture package — Scapy sniffer and microphone/camera monitor.-# FR: Paquet de capture — sniffer Scapy et moniteur microphone/caméra.+# EN: Packet capture package — libpcap sniffer (ctypes + own parser) and+# microphone/camera monitor.+# FR: Paquet de capture — sniffer libpcap (ctypes + parseur maison) et+# moniteur microphone/caméra.diff --git a/backend/capture/media_monitor.py b/backend/capture/media_monitor.pyindex e22fa2b..99e242f 100644--- a/backend/capture/media_monitor.py+++ b/backend/capture/media_monitor.py@@ -38,9 +38,15 @@ logger = logging.getLogger("snitch.capture.media")@dataclassclass MediaState:"""EN: Snapshot of which process names are using mic/camera.- FR: Instantané des noms de processus utilisant micro/caméra."""+ `supported=False` means the platform has no detection backend+ (macOS) — the UI hides the badge entirely rather than lying.+ FR: Instantané des noms de processus utilisant micro/caméra.+ `supported=False` signifie que la plateforme n'a pas de backend de+ détection (macOS) — l'UI masque complètement le badge plutôt que de+ mentir."""mic: list[str] = field(default_factory=list)camera: list[str] = field(default_factory=list)+ supported: bool = Truedef _detect_windows() -> MediaState:@@ -69,41 +75,44 @@ def _detect_windows() -> MediaState:procs = []key_path = rf"SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\{device}"try:- key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path)+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path) as key:+ i = 0+ while True:+ try:+ sub = winreg.EnumKey(key, i)+ i += 1+ except OSError:+ break++ try:+ if sub == "NonPackaged":+ # EN: Desktop apps — one sub-key per exe path.+ # FR: Apps bureau — une sous-clé par chemin d'exe.+ with winreg.OpenKey(key, sub) as np_key:+ j = 0+ while True:+ try:+ app = winreg.EnumKey(np_key, j)+ j += 1+ with winreg.OpenKey(np_key, app) as app_key:+ if _key_in_use(app_key):+ procs.append(app.split("#")[-1])+ except OSError:+ break+ else:+ # EN: Packaged (Store/UWP) apps sit directly under+ # the capability key.+ # FR: Les apps packagées (Store/UWP) sont+ # directement sous la clé de capacité.+ with winreg.OpenKey(key, sub) as app_key:+ if _key_in_use(app_key):+ procs.append(sub)+ except OSError:+ # EN: One broken key must not abort the whole walk.+ # FR: Une clé cassée ne doit pas interrompre le parcours.+ continueexcept OSError:- return procs-- i = 0- while True:- try:- sub = winreg.EnumKey(key, i)- i += 1- except OSError:- break-- try:- if sub == "NonPackaged":- # EN: Desktop apps — one sub-key per exe path.- # FR: Apps bureau — une sous-clé par chemin d'exe.- np_key = winreg.OpenKey(key, sub)- j = 0- while True:- try:- app = winreg.EnumKey(np_key, j)- j += 1- app_key = winreg.OpenKey(np_key, app)- if _key_in_use(app_key):- procs.append(app.split("#")[-1])- except OSError:- break- else:- # EN: Packaged (Store/UWP) apps sit directly under the key.- # FR: Les apps packagées (Store/UWP) sont directement sous la clé.- app_key = winreg.OpenKey(key, sub)- if _key_in_use(app_key):- procs.append(sub)- except OSError:- continue+ passreturn procsstate.mic = _read_consent("microphone")@@ -138,9 +147,18 @@ def _detect_linux() -> MediaState:def detect_media_usage() -> MediaState:- """EN: Platform dispatch. / FR: Répartition selon la plateforme."""+ """+ EN: Platform dispatch. macOS has no straightforward API for this — the+ Linux branch would be wrong there, so we report "unsupported" and let+ the UI hide the feature.+ FR: Répartition selon la plateforme. macOS n'offre pas d'API simple pour+ cela — la branche Linux y serait fausse, donc on rapporte+ « non supporté » et l'UI masque la fonctionnalité.+ """if sys.platform == "win32":return _detect_windows()+ if sys.platform == "darwin":+ return MediaState(supported=False)return _detect_linux()diff --git a/backend/capture/parser.py b/backend/capture/parser.pynew file mode 100644index 0000000..e46a1ab--- /dev/null+++ b/backend/capture/parser.py@@ -0,0 +1,412 @@+"""+Snitch — packet parser (pure Python, no Scapy).++EN: Decodes raw link-layer frames into a normalized `ParsedPacket`. This is+ what frees Snitch from Scapy's GPL-2.0-only license and gives us IPv6,+ DNS answers and TLS SNI — all of which Scapy imports never actually used.++ Supported link types : Ethernet, BSD loopback (NULL), raw IP, Linux SLL+ and SLL2.+ Network layers : IPv4 (with fragment skip), IPv6 (walks extension+ headers), TCP, UDP, ICMP.+ Payload extraction : DNS responses (A / AAAA / CNAME → ip↔name with+ TTL), TLS ClientHello SNI (single-segment case).++FR: Décode les trames de couche liaison brutes en `ParsedPacket` normalisé.+ C'est ce qui affranchit Snitch de la licence GPL-2.0-only de Scapy et nous+ donne IPv6, les réponses DNS et le SNI TLS — que les imports Scapy+ n'utilisaient jamais vraiment.++ Types de lien gérés : Ethernet, loopback BSD (NULL), IP brut, SLL et+ SLL2 Linux.+ Couches réseau : IPv4 (fragments sautés), IPv6 (parcours des+ extensions), TCP, UDP, ICMP.+ Extraction de charge : réponses DNS (A / AAAA / CNAME → ip↔nom avec TTL),+ SNI du ClientHello TLS (cas d'un seul segment).+"""++import socket+import struct+from dataclasses import dataclass, field+from typing import Optional++# ── Link-layer types / Types de liaison ──────────────────────────────────────+DLT_NULL = 0 # EN: BSD loopback / FR: loopback BSD+DLT_EN10MB = 1 # EN: Ethernet / FR: Ethernet+DLT_RAW = 12 # EN: raw IP, most platforms / FR: IP brut, plupart des plateformes+DLT_RAW_ALT = 101 # EN: raw IP, OpenBSD numbering / FR: IP brut, numérotation OpenBSD+DLT_LINUX_SLL = 113 # EN: Linux cooked v1 / FR: cooked v1 Linux+DLT_LINUX_SLL2 = 276 # EN: Linux cooked v2 / FR: cooked v2 Linux++# ── EtherTypes / EtherTypes ──────────────────────────────────────────────────+ETHERTYPE_IPV4 = 0x0800+ETHERTYPE_IPV6 = 0x86DD+ETHERTYPE_VLAN = 0x8100 # EN: 802.1Q tag — skip 4 bytes and re-read+ # FR: tag 802.1Q — sauter 4 octets et relire++# ── IP protocol numbers / Numéros de protocole IP ────────────────────────────+IPPROTO_TCP = 6+IPPROTO_UDP = 17+IPPROTO_ICMP = 1+IPPROTO_ICMPV6 = 58+# EN: IPv6 extension headers that carry a length we can walk past.+# FR: En-têtes d'extension IPv6 dont la longueur permet de les sauter.+IPV6_EXT_HOPOPT = 0+IPV6_EXT_ROUTE = 43+IPV6_EXT_FRAG = 44+IPV6_EXT_AH = 51+IPV6_EXT_DSTOPTS = 60+IPV6_EXT_NO_NEXT = 59+IPV6_EXT_CHAIN = {IPV6_EXT_HOPOPT, IPV6_EXT_ROUTE, IPV6_EXT_FRAG, IPV6_EXT_DSTOPTS}+++@dataclass+class ParsedPacket:+ """+ EN: Normalized view of one frame — the single object the sniffer produces.+ `dns` holds answer tuples (name, ip, ttl) from DNS responses; `sni`+ holds the TLS ClientHello server name when observed.+ FR: Vue normalisée d'une trame — l'objet unique produit par le sniffer.+ `dns` contient des tuples de réponse (nom, ip, ttl) des réponses DNS ;+ `sni` contient le nom de serveur du ClientHello TLS quand observé.+ """+ src_ip: str+ dst_ip: str+ protocol: str # "TCP" | "UDP" | "ICMP" | "OTHER"+ size: int # EN: bytes on the wire / FR: octets sur le fil+ src_port: Optional[int] = None+ dst_port: Optional[int] = None+ tcp_flags: int = 0+ dns: list[tuple[str, str, int]] = field(default_factory=list)+ sni: Optional[str] = None+++def parse_frame(linktype: int, buf: bytes) -> Optional[ParsedPacket]:+ """+ EN: Entry point — decode one captured frame. Returns None for frames we+ can't or don't care to decode (non-IP, truncated, malformed).+ Never raises: a corrupt packet must not kill the capture loop.+ FR: Point d'entrée — décoder une trame capturée. Renvoie None pour les+ trames non décodables ou sans intérêt (non-IP, tronquées, malformées).+ Ne lève jamais d'exception : un paquet corrompu ne doit pas tuer la+ boucle de capture.+ """+ try:+ return _parse_frame(linktype, buf)+ except (IndexError, struct.error, ValueError):+ return None+++def _parse_frame(linktype: int, buf: bytes) -> Optional[ParsedPacket]:+ """EN: Internal — may raise on malformed input; parse_frame guards it.+ FR: Interne — peut lever des exceptions sur entrée malformée ; parse_frame la protège."""+ total_len = len(buf)++ # ── Strip the link-layer header / Dépouiller l'en-tête de liaison ───────+ if linktype == DLT_EN10MB:+ if total_len < 14:+ return None+ ethertype = struct.unpack("!H", buf[12:14])[0]+ off = 14+ while ethertype == ETHERTYPE_VLAN: # EN: stacked VLAN tags+ ethertype = struct.unpack("!H", buf[off + 2:off + 4])[0]+ off += 4+ if ethertype == ETHERTYPE_IPV4:+ return _parse_ipv4(buf[off:], total_len)+ if ethertype == ETHERTYPE_IPV6:+ return _parse_ipv6(buf[off:], total_len)+ return None++ if linktype == DLT_NULL:+ if total_len < 4:+ return None+ # EN: 4-byte family in HOST byte order: 2=IPv4, 24/28/30=IPv6.+ # FR: Famille sur 4 octets en ordre HÔTE : 2=IPv4, 24/28/30=IPv6.+ family = struct.unpack("=I", buf[:4])[0]+ if family == 2:+ return _parse_ipv4(buf[4:], total_len)+ if family in (24, 28, 30):+ return _parse_ipv6(buf[4:], total_len)+ return None++ if linktype in (DLT_RAW, DLT_RAW_ALT):+ # EN: First nibble is the IP version. / FR: Le premier quartet est la version IP.+ if total_len < 1:+ return None+ version = buf[0] >> 4+ if version == 4:+ return _parse_ipv4(buf, total_len)+ if version == 6:+ return _parse_ipv6(buf, total_len)+ return None++ if linktype == DLT_LINUX_SLL:+ # EN: 16-byte header, protocol at offset 14 (network byte order).+ # FR: En-tête de 16 octets, protocole à l'offset 14 (ordre réseau).+ if total_len < 16:+ return None+ proto = struct.unpack("!H", buf[14:16])[0]+ if proto == ETHERTYPE_IPV4:+ return _parse_ipv4(buf[16:], total_len)+ if proto == ETHERTYPE_IPV6:+ return _parse_ipv6(buf[16:], total_len)+ return None++ if linktype == DLT_LINUX_SLL2:+ # EN: 20-byte header, protocol at offset 0.+ # FR: En-tête de 20 octets, protocole à l'offset 0.+ if total_len < 20:+ return None+ proto = struct.unpack("!H", buf[0:2])[0]+ if proto == ETHERTYPE_IPV4:+ return _parse_ipv4(buf[20:], total_len)+ if proto == ETHERTYPE_IPV6:+ return _parse_ipv6(buf[20:], total_len)+ return None++ return None+++# ── IPv4 / IPv6 ──────────────────────────────────────────────────────────────++def _parse_ipv4(buf: bytes, wire_len: int) -> Optional[ParsedPacket]:+ """+ EN: IPv4 header — variable IHL, fragment-aware (non-first fragments are+ dropped since their ports aren't present).+ FR: En-tête IPv4 — IHL variable, gestion des fragments (les fragments non+ premiers sont ignorés car leurs ports ne sont pas présents).+ """+ if len(buf) < 20:+ return None+ ihl = (buf[0] & 0x0F) * 4+ if ihl < 20 or len(buf) < ihl:+ return None+ proto = buf[9]+ frag = struct.unpack("!H", buf[6:8])[0]+ # EN: Fragment offset in low 13 bits — non-zero means a later fragment.+ # FR: Offset de fragment sur 13 bits bas — non nul = fragment ultérieur.+ if frag & 0x1FFF:+ return None+ src = socket.inet_ntop(socket.AF_INET, buf[12:16])+ dst = socket.inet_ntop(socket.AF_INET, buf[16:20])+ return _parse_transport(buf[ihl:], proto, src, dst, wire_len)+++def _parse_ipv6(buf: bytes, wire_len: int) -> Optional[ParsedPacket]:+ """+ EN: IPv6 — fixed 40-byte header, then walk the extension-header chain+ (hop-by-hop / routing / dest-opts have a len field; fragment header is+ fixed 8 bytes; non-first fragments are dropped).+ FR: IPv6 — en-tête fixe de 40 octets, puis parcours de la chaîne+ d'extensions (hop-by-hop / routing / dest-opts ont un champ de+ longueur ; l'en-tête fragment fait 8 octets ; les fragments non+ premiers sont ignorés).+ """+ if len(buf) < 40:+ return None+ nxt = buf[6]+ src = socket.inet_ntop(socket.AF_INET6, buf[8:24])+ dst = socket.inet_ntop(socket.AF_INET6, buf[24:40])+ off = 40++ while nxt in IPV6_EXT_CHAIN:+ if nxt == IPV6_EXT_FRAG:+ if off + 8 > len(buf):+ return None+ frag_field = struct.unpack("!H", buf[off + 2:off + 4])[0]+ if (frag_field >> 3) != 0: # EN: non-first fragment+ return None # FR: fragment non premier+ nxt = buf[off]+ off += 8+ continue+ if off + 2 > len(buf):+ return None+ hdr_len = (buf[off + 1] + 1) * 8+ nxt = buf[off]+ off += hdr_len++ if nxt == IPV6_EXT_NO_NEXT:+ return None+ return _parse_transport(buf[off:], nxt, src, dst, wire_len)+++def _parse_transport(payload: bytes, proto: int, src: str, dst: str,+ wire_len: int) -> Optional[ParsedPacket]:+ """+ EN: TCP/UDP/ICMP dispatch. TCP extracts flags + SNI attempt; UDP extracts+ DNS answers on port 53.+ FR: Répartition TCP/UDP/ICMP. TCP extrait les flags + tente le SNI ; UDP+ extrait les réponses DNS sur le port 53.+ """+ if proto == IPPROTO_TCP:+ if len(payload) < 20:+ return None+ sport, dport = struct.unpack("!HH", payload[:4])+ data_off = (payload[12] >> 4) * 4+ flags = payload[13]+ tcp_payload = payload[data_off:] if data_off <= len(payload) else b""++ sni = None+ # EN: Cheap gate: TLS record starts 0x16 0x03 xx on port 443 (or SNI on+ # any port — be liberal, check both endpoints' payload anyway).+ # FR: Filtre rapide : un enregistrement TLS commence par 0x16 0x03 xx+ # sur le port 443 (ou SNI sur tout port — rester souple).+ if tcp_payload[:2] == b"\x16\x03":+ sni = parse_tls_sni(tcp_payload)++ dns = []+ if sport == 53 or dport == 53:+ # EN: DNS-over-TCP has a 2-byte length prefix. / FR: DNS sur TCP a un préfixe de longueur de 2 octets.+ dns = parse_dns(tcp_payload[2:]) if len(tcp_payload) > 2 else []++ return ParsedPacket(src, dst, "TCP", wire_len, sport, dport, flags, dns, sni)++ if proto == IPPROTO_UDP:+ if len(payload) < 8:+ return None+ sport, dport = struct.unpack("!HH", payload[:4])+ udp_payload = payload[8:]+ dns = parse_dns(udp_payload) if (sport == 53 or dport == 53) else []+ return ParsedPacket(src, dst, "UDP", wire_len, sport, dport, 0, dns, None)++ if proto in (IPPROTO_ICMP, IPPROTO_ICMPV6):+ return ParsedPacket(src, dst, "ICMP", wire_len)++ return ParsedPacket(src, dst, "OTHER", wire_len)+++# ── DNS / DNS ────────────────────────────────────────────────────────────────++def _dns_name(buf: bytes, off: int, depth: int = 0) -> tuple[str, int]:+ """+ EN: Decode a possibly-compressed DNS name. Returns (name, offset_after).+ Compression pointers (0xC0) may jump backwards — depth-capped to avoid+ loops in malformed packets.+ FR: Décoder un nom DNS éventuellement compressé. Renvoie (nom, offset_après).+ Les pointeurs de compression (0xC0) peuvent sauter en arrière — profondeur+ plafonnée pour éviter les boucles dans les paquets malformés.+ """+ labels = []+ jumped = False+ end = off+ while off < len(buf):+ length = buf[off]+ if length == 0:+ off += 1+ if not jumped:+ end = off+ break+ if length & 0xC0 == 0xC0: # EN: compression pointer / FR: pointeur de compression+ if off + 1 >= len(buf):+ break+ ptr = ((length & 0x3F) << 8) | buf[off + 1]+ if not jumped:+ end = off + 2+ jumped = True+ off = ptr+ depth += 1+ if depth > 20:+ break+ continue+ off += 1+ labels.append(buf[off:off + length].decode("ascii", errors="replace"))+ off += length+ if not jumped:+ end = off+ return ".".join(labels), end+++def parse_dns(payload: bytes) -> list[tuple[str, str, int]]:+ """+ EN: Parse a DNS message; returns [(name, ip, ttl)] for A/AAAA answers —+ empty for queries or failures. Errors are non-fatal (return []).+ FR: Analyser un message DNS ; renvoie [(nom, ip, ttl)] pour les réponses+ A/AAAA — vide pour les requêtes ou les échecs. Les erreurs sont non+ fatales (renvoie []).+ """+ try:+ if len(payload) < 12:+ return []+ _, flags, qdcount, ancount = struct.unpack("!HHHH", payload[:8])+ if not (flags & 0x8000): # EN: QR bit — responses only+ return [] # FR: bit QR — réponses seulement++ off = 12+ for _ in range(qdcount): # EN: skip question section / FR: sauter la section questions+ _, off = _dns_name(payload, off)+ off += 4++ answers = []+ for _ in range(ancount):+ name, off = _dns_name(payload, off)+ if off + 10 > len(payload):+ break+ rtype, _, ttl, rdlen = struct.unpack("!HHIH", payload[off:off + 10])+ rdata_off = off + 10+ rdata = payload[rdata_off:rdata_off + rdlen]+ if rtype == 1 and rdlen == 4: # EN: A record / FR: enregistrement A+ answers.append((name, socket.inet_ntop(socket.AF_INET, rdata), ttl))+ elif rtype == 28 and rdlen == 16: # EN: AAAA / FR: AAAA+ answers.append((name, socket.inet_ntop(socket.AF_INET6, rdata), ttl))+ off = rdata_off + rdlen+ return answers+ except (IndexError, struct.error, ValueError):+ return []+++# ── TLS SNI / SNI TLS ────────────────────────────────────────────────────────++def parse_tls_sni(payload: bytes) -> Optional[str]:+ """+ EN: Extract the SNI hostname from a TLS ClientHello when the whole+ handshake fits in one segment — the overwhelmingly common case.+ Layout: record header (5) | handshake type+len (4) | version (2) |+ random (32) | session_id (1+n) | ciphers (2+n) | compression (1+n) |+ extensions len (2) | extensions… — we look for ext type 0.+ FR: Extraire le nom d'hôte SNI d'un ClientHello TLS quand tout le+ handshake tient dans un seul segment — le cas très majoritaire.+ Structure : en-tête d'enregistrement (5) | type+longueur handshake (4) |+ version (2) | aléa (32) | session_id (1+n) | chiffrements (2+n) |+ compression (1+n) | longueur extensions (2) | extensions… — on cherche+ l'extension type 0.+ """+ try:+ if len(payload) < 9 or payload[0] != 0x16 or payload[1] != 0x03:+ return None+ hs = 5+ if payload[hs] != 0x01: # EN: ClientHello / FR: ClientHello+ return None+ hs_len = struct.unpack("!I", b"\x00" + payload[hs + 1:hs + 4])[0]+ body = payload[hs + 4:hs + 4 + hs_len]+ if len(body) < 34:+ return None+ off = 2 + 32 # EN: version + random / FR: version + aléa+ sid_len = body[off]; off += 1 + sid_len+ cs_len = struct.unpack("!H", body[off:off + 2])[0]; off += 2 + cs_len+ cm_len = body[off]; off += 1 + cm_len+ if off + 2 > len(body):+ return None+ ext_total = struct.unpack("!H", body[off:off + 2])[0]; off += 2+ ext_end = min(off + ext_total, len(body))++ while off + 4 <= ext_end:+ etype, elen = struct.unpack("!HH", body[off:off + 4])+ edata = body[off + 4:off + 4 + elen]+ if etype == 0 and len(edata) >= 5: # EN: server_name ext / FR: ext server_name+ # EN: list_len(2) | type(1) | name_len(2) | name+ # FR: longueur liste (2) | type (1) | longueur nom (2) | nom+ if edata[2] == 0:+ nlen = struct.unpack("!H", edata[3:5])[0]+ raw = edata[5:5 + nlen].decode("ascii", errors="strict")+ # EN: IDNA → unicode when possible; the "idna" codec does+ # not accept an errors= argument.+ # FR: IDNA → unicode quand possible ; le codec « idna »+ # n'accepte pas d'argument errors=.+ try:+ return raw.encode("ascii").decode("idna")+ except UnicodeError:+ return raw+ off += 4 + elen+ return None+ except (IndexError, struct.error, ValueError):+ return Nonediff --git a/backend/capture/pcap.py b/backend/capture/pcap.pynew file mode 100644index 0000000..77cf934--- /dev/null+++ b/backend/capture/pcap.py@@ -0,0 +1,318 @@+"""+Snitch — ctypes binding to libpcap / wpcap.++EN: Minimal, dependency-free binding to the system packet-capture library:+ - Windows : wpcap.dll, shipped by Npcap (user-installed — NOT bundled;+ the free Npcap license does not allow external redistribution)+ - Linux : libpcap.so (apt install libpcap0.8)+ - macOS : libpcap.dylib (ships with the OS)++ ctypes is stdlib, so this adds zero compiled dependencies and zero GPL+ contamination (libpcap/Npcap are BSD-style licensed).++ Capture rights are still required: admin on Windows, root or+ cap_net_raw/cap_net_admin on Linux, /dev/bpf* access on macOS.++FR: Liaison ctypes minimale et sans dépendance vers la bibliothèque système de+ capture :+ - Windows : wpcap.dll, fournie par Npcap (installé par l'utilisateur —+ PAS embarqué ; la licence gratuite de Npcap interdit la+ redistribution externe)+ - Linux : libpcap.so (apt install libpcap0.8)+ - macOS : libpcap.dylib (livré avec l'OS)++ ctypes fait partie de la bibliothèque standard : zéro dépendance compilée,+ zéro contamination GPL (libpcap/Npcap sont sous licences de type BSD).++ Les droits de capture restent nécessaires : admin sous Windows, root ou+ cap_net_raw/cap_net_admin sous Linux, accès /dev/bpf* sous macOS.+"""++import ctypes+import ctypes.util+import logging+import sys+from dataclasses import dataclass+from typing import Optional++logger = logging.getLogger("snitch.capture.pcap")+++class PcapError(Exception):+ """EN: Raised when libpcap is missing or a call fails.+ FR: Levée quand libpcap est absente ou qu'un appel échoue."""+ pass+++# ── Structures / Structures ──────────────────────────────────────────────────++class _TimeVal(ctypes.Structure):+ """EN: struct timeval. / FR: struct timeval."""+ _fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long)]+++class PcapPkthdr(ctypes.Structure):+ """EN: struct pcap_pkthdr — timestamp + captured/wire lengths.+ FR: struct pcap_pkthdr — timestamp + longueurs capturée/fil."""+ _fields_ = [+ ("ts", _TimeVal),+ ("caplen", ctypes.c_uint32),+ ("len", ctypes.c_uint32),+ ]+++class PcapAddr(ctypes.Structure):+ """EN: struct pcap_addr (linked list of interface addresses).+ FR: struct pcap_addr (liste chaînée des adresses d'interface)."""+ pass+++PcapAddr._fields_ = [+ ("next", ctypes.POINTER(PcapAddr)),+ ("addr", ctypes.c_void_p),+ ("netmask", ctypes.c_void_p),+ ("broadaddr", ctypes.c_void_p),+ ("dstaddr", ctypes.c_void_p),+]+++class PcapIf(ctypes.Structure):+ """EN: struct pcap_if — device list node. / FR: struct pcap_if — nœud de la liste de périphériques."""+ pass+++PcapIf._fields_ = [+ ("next", ctypes.POINTER(PcapIf)),+ ("name", ctypes.c_char_p),+ ("description", ctypes.c_char_p),+ ("addresses", ctypes.POINTER(PcapAddr)),+ ("flags", ctypes.c_uint32),+]+++class BpfInsn(ctypes.Structure):+ """EN: struct bpf_insn. / FR: struct bpf_insn."""+ _fields_ = [+ ("code", ctypes.c_ushort),+ ("jt", ctypes.c_ubyte),+ ("jf", ctypes.c_ubyte),+ ("k", ctypes.c_uint32),+ ]+++class BpfProgram(ctypes.Structure):+ """EN: struct bpf_program. / FR: struct bpf_program."""+ _fields_ = [+ ("bf_len", ctypes.c_uint),+ ("bf_insns", ctypes.POINTER(BpfInsn)),+ ]+++# ── Library loading / Chargement de la bibliothèque ─────────────────────────++_lib = None+++def _load_lib() -> ctypes.CDLL:+ """+ EN: Locate and load libpcap for the current platform, once. On Windows,+ Npcap installs wpcap.dll under System32\\Npcap — add it to the DLL+ search path explicitly (required since Python 3.8 no longer searches+ PATH for ctypes loads).+ FR: Localiser et charger libpcap pour la plateforme courante, une fois.+ Sous Windows, Npcap installe wpcap.dll dans System32\\Npcap — l'ajouter+ explicitement au chemin de recherche DLL (Python 3.8+ ne consulte plus+ PATH pour les chargements ctypes).+ """+ global _lib+ if _lib is not None:+ return _lib++ candidates: list[str] = []+ if sys.platform == "win32":+ import os+ npcap_dir = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"),+ "System32", "Npcap")+ if os.path.isdir(npcap_dir):+ try:+ os.add_dll_directory(npcap_dir)+ except OSError:+ pass+ candidates = ["wpcap.dll"]+ elif sys.platform == "darwin":+ candidates = ["libpcap.dylib", "libpcap.A.dylib"]+ else:+ found = ctypes.util.find_library("pcap")+ candidates = [found] if found else []+ candidates += ["libpcap.so.0.8", "libpcap.so.1", "libpcap.so"]++ last_err: Optional[Exception] = None+ for name in candidates:+ if not name:+ continue+ try:+ _lib = ctypes.CDLL(name)+ _configure(_lib)+ return _lib+ except OSError as exc:+ last_err = exc++ raise PcapError(_missing_msg(last_err))+++def _missing_msg(err: Optional[Exception]) -> str:+ """EN: Human-readable install guidance per platform.+ FR: Conseils d'installation lisibles selon la plateforme."""+ if sys.platform == "win32":+ return ("Npcap not found — install it from https://npcap.com "+ "(Npcap n'est pas installé — téléchargez-le sur https://npcap.com)")+ if sys.platform == "darwin":+ return "libpcap not found (unexpected on macOS) / libpcap introuvable"+ return ("libpcap not found — install it (apt install libpcap0.8 / dnf install libpcap) "+ "/ libpcap introuvable — installez-la")+++def _configure(lib: ctypes.CDLL) -> None:+ """EN: Declare argtypes/restypes for the functions we bind.+ FR: Déclarer les argtypes/restypes des fonctions liées."""+ lib.pcap_findalldevs.argtypes = [ctypes.POINTER(ctypes.POINTER(PcapIf)), ctypes.c_char_p]+ lib.pcap_findalldevs.restype = ctypes.c_int+ lib.pcap_freealldevs.argtypes = [ctypes.POINTER(PcapIf)]+ lib.pcap_freealldevs.restype = None++ lib.pcap_open_live.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int,+ ctypes.c_int, ctypes.c_char_p]+ lib.pcap_open_live.restype = ctypes.c_void_p++ lib.pcap_datalink.argtypes = [ctypes.c_void_p]+ lib.pcap_datalink.restype = ctypes.c_int++ lib.pcap_compile.argtypes = [ctypes.c_void_p, ctypes.POINTER(BpfProgram),+ ctypes.c_char_p, ctypes.c_int, ctypes.c_uint32]+ lib.pcap_compile.restype = ctypes.c_int++ lib.pcap_setfilter.argtypes = [ctypes.c_void_p, ctypes.POINTER(BpfProgram)]+ lib.pcap_setfilter.restype = ctypes.c_int++ lib.pcap_freecode.argtypes = [ctypes.POINTER(BpfProgram)]+ lib.pcap_freecode.restype = None++ lib.pcap_next_ex.argtypes = [ctypes.c_void_p,+ ctypes.POINTER(ctypes.POINTER(PcapPkthdr)),+ ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte))]+ lib.pcap_next_ex.restype = ctypes.c_int++ lib.pcap_geterr.argtypes = [ctypes.c_void_p]+ lib.pcap_geterr.restype = ctypes.c_char_p++ lib.pcap_close.argtypes = [ctypes.c_void_p]+ lib.pcap_close.restype = None++ lib.pcap_lib_version.restype = ctypes.c_char_p+++def is_available() -> bool:+ """EN: True when libpcap/wpcap loads. / FR: True si libpcap/wpcap se charge."""+ try:+ _load_lib()+ return True+ except PcapError:+ return False+++@dataclass+class PcapDevice:+ """EN: One capture-capable interface. / FR: Une interface capturable."""+ name: str+ description: str+ loopback: bool = False+++def list_devices() -> list[PcapDevice]:+ """+ EN: Enumerate capture interfaces via pcap_findalldevs.+ FR: Énumérer les interfaces de capture via pcap_findalldevs.+ """+ lib = _load_lib()+ devs = ctypes.POINTER(PcapIf)()+ errbuf = ctypes.create_string_buffer(256)+ try:+ if lib.pcap_findalldevs(ctypes.byref(devs), errbuf) != 0:+ raise PcapError(f"pcap_findalldevs: {errbuf.value.decode(errors='replace')}")+ out = []+ cur = devs+ while cur:+ d = cur.contents+ name = d.name.decode(errors="replace") if d.name else ""+ desc = d.description.decode(errors="replace") if d.description else ""+ out.append(PcapDevice(name=name, description=desc,+ loopback=bool(d.flags & 0x1)))+ cur = d.next+ return out+ finally:+ lib.pcap_freealldevs(devs)+++class PcapSession:+ """+ EN: One live capture session on a device. `next_packet()` blocks up to+ `timeout_ms` (set at open) and returns (bytes, wire_len) or None on+ timeout — the caller loop polls and stays interruptible.+ FR: Une session de capture live sur un périphérique. `next_packet()`+ bloque jusqu'à `timeout_ms` (fixé à l'ouverture) et renvoie+ (octets, longueur_fil) ou None en cas de timeout — la boucle appelante+ sonde et reste interruptible.+ """++ def __init__(self, device: str, snaplen: int = 65535, promisc: bool = True,+ timeout_ms: int = 100, bpf_filter: Optional[str] = None):+ self._lib = _load_lib()+ errbuf = ctypes.create_string_buffer(256)+ self._handle = self._lib.pcap_open_live(+ device.encode(), snaplen, 1 if promisc else 0, timeout_ms, errbuf)+ if not self._handle:+ raise PcapError(+ f"pcap_open_live({device}): {errbuf.value.decode(errors='replace')}")+ self.device = device+ self.linktype = self._lib.pcap_datalink(self._handle)+ self._closed = False++ if bpf_filter:+ prog = BpfProgram()+ try:+ if self._lib.pcap_compile(self._handle, ctypes.byref(prog),+ bpf_filter.encode(), 1, 0) != 0:+ raise PcapError(f"pcap_compile({bpf_filter!r}): {self._err()}")+ if self._lib.pcap_setfilter(self._handle, ctypes.byref(prog)) != 0:+ raise PcapError(f"pcap_setfilter: {self._err()}")+ finally:+ self._lib.pcap_freecode(ctypes.byref(prog))++ def _err(self) -> str:+ """EN: Last libpcap error string. / FR: Dernière erreur libpcap."""+ raw = self._lib.pcap_geterr(self._handle)+ return raw.decode(errors="replace") if raw else "unknown error"++ def next_packet(self) -> Optional[tuple[bytes, int]]:+ """+ EN: Next packet — (payload, wire_length) or None on timeout. Raises+ PcapError on capture failure or EOF.+ FR: Paquet suivant — (charge utile, longueur fil) ou None au timeout.+ Lève PcapError en cas d'échec de capture ou de fin de fichier.+ """+ hdr = ctypes.POINTER(PcapPkthdr)()+ data = ctypes.POINTER(ctypes.c_ubyte)()+ rc = self._lib.pcap_next_ex(self._handle, ctypes.byref(hdr), ctypes.byref(data))+ if rc == 1:+ return ctypes.string_at(data, hdr.contents.caplen), hdr.contents.len+ if rc == 0:+ return None # EN: timeout / FR: timeout+ if rc == -2:+ return None # EN: EOF (offline dumps) / FR: fin de fichier (dumps hors ligne)+ raise PcapError(f"pcap_next_ex: {self._err()}")++ def close(self) -> None:+ """EN: Release the capture handle. / FR: Libérer le handle de capture."""+ if not self._closed and self._handle:+ self._lib.pcap_close(self._handle)+ self._closed = Truediff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.pyindex 5c5db94..53527e0 100644--- a/backend/capture/sniffer.py+++ b/backend/capture/sniffer.py@@ -1,69 +1,88 @@"""-Snitch — packet sniffer.--EN: Wraps Scapy's AsyncSniffer to capture IPv4 AND IPv6 packets on the host,- determine their direction (in/out), and attribute them to a local process.- Process attribution used to call `psutil.net_connections()` per packet —- thousands of syscall-heavy scans per second on busy links. It now reads- from a `ConnectionTable`: a snapshot refreshed every ~1.5 s by a dedicated- thread, making per-packet lookup a dict hit.--FR: Enveloppe l'AsyncSniffer de Scapy pour capturer les paquets IPv4 ET IPv6 de- l'hôte, déterminer leur direction (entrant/sortant) et les attribuer à un- processus local. L'attribution appelait avant `psutil.net_connections()`- par paquet — des milliers de scans coûteux par seconde sur un lien actif.- Elle lit désormais une `ConnectionTable` : un instantané rafraîchi toutes- les ~1,5 s par un thread dédié, ramenant la recherche par paquet à un accès- dict.+Snitch — packet sniffer (libpcap edition).++EN: Captures IPv4 AND IPv6 frames through a ctypes libpcap binding+ (capture/pcap.py) and decodes them with our own parser+ (capture/parser.py) — Scapy is gone, along with its GPL-2.0-only license.++ Per packet we keep: addresses, transport ports, the REMOTE port (the fix+ for the inbound-classification bug — dst_port is a local port on inbound+ traffic), TCP flags, DNS answers and TLS SNI.++ Process attribution reads from `ConnectionTable`: a psutil snapshot of+ the OS connection table refreshed every ~1.5 s by a dedicated thread —+ per-packet lookup is a dict hit, not a syscall storm.++FR: Capture les trames IPv4 ET IPv6 via une liaison ctypes à libpcap+ (capture/pcap.py) et les décode avec notre propre parseur+ (capture/parser.py) — Scapy est parti, avec sa licence GPL-2.0-only.++ Par paquet on conserve : adresses, ports de transport, le port DISTANT+ (correction du bug de classification entrant — dst_port est un port local+ en trafic entrant), les flags TCP, les réponses DNS et le SNI TLS.++ L'attribution de processus lit `ConnectionTable` : un instantané psutil de+ la table de connexions OS rafraîchi toutes les ~1,5 s par un thread dédié —+ la recherche par paquet est un accès dict, pas une tempête d'appels système."""import logging+import osimport socketimport threadingimport time-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import Callable, Optional-try:- from scapy.all import IP, IPv6, TCP, UDP, AsyncSniffer- SCAPY_AVAILABLE = True-except ImportError:- # EN: Scapy (or libpcap/Npcap) missing — capture disabled, API still runs.- # FR: Scapy (ou libpcap/Npcap) absent — capture désactivée, l'API tourne quand même.- SCAPY_AVAILABLE = False-import psutil+from capture.pcap import PcapError, PcapSession, is_available, list_devices+from capture.parser import parse_frame+logger = logging.getLogger("snitch.capture.sniffer")+# EN: libpcap presence check — capture disabled but the API still runs.+# FR: Vérification de présence de libpcap — capture désactivée mais l'API tourne.+PCAP_AVAILABLE = is_available()+@dataclassclass Packet:"""- EN: Normalized representation of one captured packet — everything the- rest of the pipeline needs and nothing more.- FR: Représentation normalisée d'un paquet capturé — tout ce dont le reste- du pipeline a besoin, et rien de plus.+ EN: Normalized representation of one captured packet.+ `remote_port` is the port on the OTHER end — always the meaningful+ one for classification, regardless of direction.+ `dns` carries DNS answer tuples (name, ip, ttl) observed in the packet.+ `sni` is the TLS ClientHello hostname when seen.+ FR: Représentation normalisée d'un paquet capturé.+ `remote_port` est le port de l'AUTRE extrémité — toujours le port+ pertinent pour la classification, quel que soit le sens.+ `dns` transporte les tuples de réponse DNS (nom, ip, ttl) observés.+ `sni` est le nom d'hôte du ClientHello TLS quand vu."""src_ip: strdst_ip: strsrc_port: Optional[int]dst_port: Optional[int]+ remote_port: Optional[int]protocol: strsize: inttimestamp: str- direction: str # "out" | "in" (sortant | entrant)+ direction: str # "out" | "in"pid: Optional[int] = Noneprocess_name: Optional[str] = None+ tcp_flags: int = 0+ sni: Optional[str] = None+ dns: list = field(default_factory=list)def get_local_ips() -> set[str]:"""- EN: Collect every IPv4 and IPv6 address bound to a local interface.- IPv6 entries may carry a scope suffix ("fe80::1%eth0") — stripped.- FR: Collecter toutes les adresses IPv4 et IPv6 des interfaces locales.- Les IPv6 peuvent porter un suffixe de scope (« fe80::1%eth0 ») — retiré.+ EN: Every IPv4 and IPv6 address bound to a local interface. IPv6 scope+ suffixes ("fe80::1%eth0") are stripped.+ FR: Toutes les adresses IPv4 et IPv6 des interfaces locales. Les suffixes+ de scope IPv6 (« fe80::1%eth0 ») sont retirés."""ips = set()for iface_addrs in psutil.net_if_addrs().values():@@ -77,14 +96,14 @@ class ConnectionTable:"""EN: Periodic snapshot of the OS connection table:{ "tcp": {local_port: (pid, name)}, "udp": {...} }- `psutil.net_connections()` is expensive (it walks every socket of- every process), so we refresh once per `interval` in a background- thread and let the hot path do plain dict lookups.+ `psutil.net_connections()` walks every socket of every process — far+ too expensive per packet. Refreshed once per `interval` in a daemon+ thread; the hot path does plain dict lookups.FR: Instantané périodique de la table de connexions de l'OS :{ "tcp": {port_local: (pid, nom)}, "udp": {...} }- `psutil.net_connections()` est coûteux (il parcourt chaque socket de- chaque processus) : on rafraîchit une fois par `interval` dans un- thread d'arrière-plan et le chemin chaud fait de simples accès dict.+ `psutil.net_connections()` parcourt chaque socket de chaque processus —+ bien trop coûteux par paquet. Rafraîchi une fois par `interval` dans un+ thread daemon ; le chemin chaud fait de simples accès dict."""def __init__(self, interval: float = 1.5):@@ -144,126 +163,138 @@ class ConnectionTable:class PacketSniffer:"""- EN: Scapy-based capture with an optional BPF port filter. The user- callback fires once per relevant packet — from the sniffer thread,- not the event loop.- FR: Capture basée sur Scapy avec filtre de ports BPF optionnel. Le callback- utilisateur est appelé une fois par paquet pertinent — depuis le thread- du sniffer, pas depuis la boucle asyncio.+ EN: libpcap-backed capture with an optional BPF port filter and an+ interface selector (SNITCH_IFACE env or constructor arg; default =+ first non-loopback device). The user callback fires once per packet+ from the capture thread.+ FR: Capture adossée à libpcap avec filtre de ports BPF optionnel et+ sélecteur d'interface (env SNITCH_IFACE ou argument ; défaut = premier+ périphérique non-loopback). Le callback utilisateur est appelé une fois+ par paquet depuis le thread de capture."""- def __init__(self, callback: Callable[[Packet], None], ports: list[int] | None = None):+ def __init__(self, callback: Callable[[Packet], None],+ ports: list[int] | None = None, iface: str | None = None):self.callback = callbackself.ports = ports or []+ self.iface = iface or os.environ.get("SNITCH_IFACE") or self._default_iface()self.local_ips = get_local_ips()- self._sniffer: Optional[AsyncSniffer] = None+ self._session: Optional[PcapSession] = Noneself._conn_table = ConnectionTable()self._running = False+ self._thread: Optional[threading.Thread] = None++ @staticmethod+ def _default_iface() -> Optional[str]:+ """EN: First non-loopback capture device. / FR: Premier périphérique de capture non-loopback."""+ try:+ for d in list_devices():+ if not d.loopback:+ return d.name+ devs = list_devices()+ return devs[0].name if devs else None+ except PcapError as exc:+ logger.warning("cannot list capture devices: %s", exc)+ return None@propertydef _bpf_filter(self) -> str:"""- EN: Berkeley Packet Filter expression — kernel-side filtering is far- cheaper than Python-side. Covers IPv4 AND IPv6.- FR: Expression BPF — le filtrage côté noyau coûte bien moins cher que- côté Python. Couvre IPv4 ET IPv6.+ EN: Berkeley Packet Filter — kernel-side filtering beats Python-side.+ Covers IPv4 AND IPv6.+ FR: Filtre BPF — le filtrage côté noyau bat le filtrage Python.+ Couvre IPv4 ET IPv6."""if not self.ports:return "ip or ip6"port_expr = " or ".join(f"port {p}" for p in self.ports)return f"(ip or ip6) and ({port_expr})"- def _process_packet(self, pkt) -> None:+ def _handle_frame(self, buf: bytes, wire_len: int) -> None:"""- EN: Convert a raw Scapy packet into our normalized Packet. Drops- non-IP traffic and packets that do not involve this host.- IPv6 is handled transparently: TCP/UDP layers sit above either- network layer.- FR: Convertir un paquet Scapy brut en Packet normalisée. Ignore le- trafic non-IP et les paquets qui ne concernent pas cet hôte.- IPv6 est géré de façon transparente : les couches TCP/UDP se- placent au-dessus de l'une ou l'autre couche réseau.+ EN: Decode + normalize one frame. Drops non-IP traffic and packets+ that do not involve this host.+ FR: Décoder + normaliser une trame. Ignore le trafic non-IP et les+ paquets qui ne concernent pas cet hôte."""- if pkt.haslayer(IP):- ip_layer = pkt[IP]- elif SCAPY_AVAILABLE and pkt.haslayer(IPv6):- ip_layer = pkt[IPv6]- else:+ assert self._session is not None+ parsed = parse_frame(self._session.linktype, buf)+ if parsed is None:return- src = ip_layer.src.split("%")[0]- dst = ip_layer.dst.split("%")[0]-- # EN: Only care about traffic from/to this machine.- # FR: On ne garde que le trafic de/vers cette machine.+ src, dst = parsed.src_ip, parsed.dst_ipif src not in self.local_ips and dst not in self.local_ips:return- proto = "OTHER"- src_port = dst_port = None-- if pkt.haslayer(TCP):- proto = "TCP"- src_port = pkt[TCP].sport- dst_port = pkt[TCP].dport- elif pkt.haslayer(UDP):- proto = "UDP"- src_port = pkt[UDP].sport- dst_port = pkt[UDP].dport-direction = "out" if src in self.local_ips else "in"- local_port = src_port if direction == "out" else dst_port+ local_port = parsed.src_port if direction == "out" else parsed.dst_port+ # EN: The remote port is the one that matters for classification —+ # for inbound traffic dst_port is OUR port, not theirs.+ # FR: Le port distant est celui qui compte pour la classification —+ # en trafic entrant, dst_port est NOTRE port, pas le leur.+ remote_port = parsed.dst_port if direction == "out" else parsed.src_port- # EN: Process attribution via the cached connection table.- # FR: Attribution du processus via la table de connexions en cache.pid, process_name = None, None- if local_port and proto in ("TCP", "UDP"):- pid, process_name = self._conn_table.lookup(local_port, proto)+ if local_port and parsed.protocol in ("TCP", "UDP"):+ pid, process_name = self._conn_table.lookup(local_port, parsed.protocol)- packet = Packet(+ self.callback(Packet(src_ip=src,dst_ip=dst,- src_port=src_port,- dst_port=dst_port,- protocol=proto,- size=len(pkt),+ src_port=parsed.src_port,+ dst_port=parsed.dst_port,+ remote_port=remote_port,+ protocol=parsed.protocol,+ size=parsed.size or wire_len,timestamp=datetime.now(timezone.utc).isoformat(),direction=direction,pid=pid,process_name=process_name,- )- self.callback(packet)+ tcp_flags=parsed.tcp_flags,+ sni=parsed.sni,+ dns=parsed.dns,+ ))def start(self) -> None:- """- EN: Blocking call — run inside a daemon thread. Starts the connection- table first, then the AsyncSniffer, then idles while it works.- FR: Appel bloquant — à lancer dans un thread daemon. Démarre d'abord la- table de connexions, puis l'AsyncSniffer, puis se met en attente.- """- if not SCAPY_AVAILABLE:- logger.warning("scapy not available — packet capture disabled")+ """EN: Launch the capture thread. / FR: Lancer le thread de capture."""+ if not PCAP_AVAILABLE:+ logger.warning("libpcap unavailable — packet capture disabled")+ return+ if not self.iface:+ logger.warning("no capture interface found — packet capture disabled")returnself._running = True+ self._thread = threading.Thread(target=self._run, daemon=True)+ self._thread.start()++ def _run(self) -> None:+ """EN: Capture loop — blocks ≤100 ms per poll so stop() stays snappy.+ FR: Boucle de capture — bloque ≤100 ms par sondage pour que stop()+ reste réactif."""try:self._conn_table.start()- self._sniffer = AsyncSniffer(- filter=self._bpf_filter,- prn=self._process_packet,- store=False, # EN: never keep packets in memory / FR: ne jamais garder les paquets en mémoire- )- self._sniffer.start()+ self._session = PcapSession(self.iface, timeout_ms=100,+ bpf_filter=self._bpf_filter)+ logger.info("capture on %s (linktype=%d, filter=%r)",+ self.iface, self._session.linktype, self._bpf_filter)while self._running:- time.sleep(1)- except Exception as exc:+ try:+ pkt = self._session.next_packet()+ except PcapError as exc:+ logger.error("capture error: %s", exc)+ break+ if pkt is not None:+ self._handle_frame(*pkt)+ except PcapError as exc:logger.error("sniffer failed to start: %s", exc)+ finally:+ if self._session:+ self._session.close()def stop(self) -> None:- """EN: Stop capture + the connection-table thread. / FR: Arrêter la capture + le thread de la table."""+ """EN: Stop capture + the connection-table thread.+ FR: Arrêter la capture + le thread de la table de connexions."""self._running = Falseself._conn_table.stop()- if self._sniffer:- try:- self._sniffer.stop()- except Exception as exc:- logger.debug("sniffer stop failed: %s", exc)+ if self._thread:+ self._thread.join(timeout=2)diff --git a/backend/cli.py b/backend/cli.pynew file mode 100644index 0000000..3ffefa7--- /dev/null+++ b/backend/cli.py@@ -0,0 +1,98 @@+"""+Snitch — command-line entry point (`snitch`).++EN: Starts the local API + bundled web UI on a free loopback port, prints the+ token URL once, and opens the browser. Runs headless in --no-browser mode+ (e.g. remote/Docker use).++ Capture privileges are still required:+ - Windows : run the terminal as Administrator (Npcap installed)+ - Linux : root, or `sudo setcap cap_net_raw,cap_net_admin` on the binary+ - macOS : read access to /dev/bpf*++ Usage: snitch [--port N] [--bind 127.0.0.1] [--no-browser]++FR: Point d'entrée en ligne de commande (`snitch`).++ Lance l'API locale + l'UI web embarquée sur un port loopback libre, affiche+ l'URL avec jeton une fois, et ouvre le navigateur. Mode --no-browser pour+ usage sans interface graphique (ex. distant/Docker).++ Les privilèges de capture restent requis :+ - Windows : terminal Administrateur (Npcap installé)+ - Linux : root, ou `sudo setcap cap_net_raw,cap_net_admin` sur le binaire+ - macOS : accès en lecture aux /dev/bpf*++ Usage : snitch [--port N] [--bind 127.0.0.1] [--no-browser]+"""++import argparse+import logging+import os+import socket+import sys+import threading+import webbrowser+++def _free_port() -> int:+ """EN: Grab a free loopback port. / FR: Prendre un port loopback libre."""+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def main() -> int:+ """EN: CLI entry — parse args, boot uvicorn, open the browser.+ FR: Entrée CLI — parser les args, démarrer uvicorn, ouvrir le navigateur."""+ ap = argparse.ArgumentParser(+ prog="snitch",+ description="Snitch — real-time network traffic visualizer / "+ "visualiseur de trafic réseau en temps réel")+ ap.add_argument("--port", type=int, default=0,+ help="port to bind (0 = pick a free one) / "+ "port d'écoute (0 = choisir un port libre)")+ ap.add_argument("--bind", default="127.0.0.1",+ help="bind address — keep 127.0.0.1 unless you know why / "+ "adresse d'écoute — garder 127.0.0.1 sauf raison explicite")+ ap.add_argument("--no-browser", action="store_true",+ help="don't open the browser / ne pas ouvrir le navigateur")+ args = ap.parse_args()++ # EN: Ensure backend/ is importable when running from a wheel install.+ # FR: Garantir que backend/ est importable en installation wheel.+ pkg_dir = os.path.dirname(os.path.abspath(__file__))+ if pkg_dir not in sys.path:+ sys.path.insert(0, pkg_dir)++ os.environ["SNITCH_USER_DATA"] = "1" # EN: per-OS data dir, not repo/data+ # FR: dossier de données par OS++ from logging_config import setup_logging+ setup_logging(logging.INFO)++ port = args.port or _free_port()+ os.environ["SNITCH_PORT"] = str(port)+ os.environ["SNITCH_BIND"] = args.bind++ from api.main import app # noqa: E402+ from api.security import get_token # noqa: E402+ import uvicorn # noqa: E402++ token = get_token()+ url = f"http://127.0.0.1:{port}/?token={token}"+ print(f"\n Snitch is running / Snitch tourne :\n\n {url}\n")+ print(" Keep this terminal open. Ctrl+C to stop. / "+ "Gardez ce terminal ouvert. Ctrl+C pour arrêter.\n")++ if not args.no_browser:+ # EN: Open after a short delay so uvicorn is listening first.+ # FR: Ouvrir après un court délai pour qu'uvicorn écoute d'abord.+ threading.Timer(1.0, lambda: webbrowser.open(url)).start()++ uvicorn.run(app, host=args.bind, port=port, log_level="warning")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/backend/detection/anomaly.py b/backend/detection/anomaly.pyindex 1395592..901f72e 100644--- a/backend/detection/anomaly.py+++ b/backend/detection/anomaly.py@@ -13,7 +13,9 @@ EN: Stateful, rule-based detector fed with every captured packet and every- SUSPICIOUS_PORT traffic to ports associated with shells/botnets/Tor- BEACON *regular-interval* traffic (low interval variance)— real C2 heartbeat detection, not a dumb rate count- - VOLUME_SPIKE a single packet far above the host's average size+ - 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- 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@@ -39,7 +41,9 @@ FR: Détecteur à état basé sur des règles, alimenté par chaque paquet captu- SUSPICIOUS_PORT trafic vers des ports associés shells/botnets/Tor- BEACON trafic à intervalles *réguliers* (faible variance) —vraie détection de heartbeat C2, pas un simple compteur- - VOLUME_SPIKE un paquet bien au-dessus de la moyenne de l'hôte+ - 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- 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@@ -113,7 +117,30 @@ BEACON_MAX_INTERVAL_S = 600.0BEACON_MAX_CV = 0.35BEACON_MIN_SPAN_S = 60.0-VOLUME_SPIKE_FACTOR = 8 # EN: 8× average bytes → spike / FR: 8× la moyenne → pic+# ── Volume spike / Pic de volume ─────────────────────────────────────────────+# EN: Bytes in a trailing window vs a rolling baseline of completed windows —+# NOT single-packet size (a 1.5 KB packet after 100-byte ACKs used to fire).+# FR: Octets dans une fenêtre glissante vs base roulante des fenêtres passées —+# PAS la taille d'un paquet (un paquet de 1,5 Ko après des ACK de 100 o+# déclenchait tout le temps).+VOLUME_WINDOW_S = 60+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++# ── Port scan / Scan de ports ────────────────────────────────────────────────+SCAN_WINDOW_S = 60+SCAN_THRESHOLD = 20 # EN: distinct remote ports / FR: ports distants+SCAN_COMMON_PORTS = {53, 80, 123, 443, 853} # EN: chatty-by-design ports+ # FR: ports bavards par nature++# EN: Resolver/NTP ports + known DNS-stack processes — excluded from+# port-scan counting (they legitimately touch many ports).+# FR: Ports résolveurs/NTP + processus de pile DNS connus — exclus du comptage+# de scan de ports (ils touchent légitimement beaucoup de ports).+KNOWN_RESOLVER_PORTS = {53, 853, 123}+KNOWN_RESOLVER_PROCS = {"systemd-resolved", "dnsmasq", "named", "svchost"}+COOLDOWN = 60 # EN: seconds before re-alerting the same key# FR: secondes avant de re-alerter la même clé@@ -237,6 +264,13 @@ class AnomalyDetector:self._seen_process_conns = BoundedSet(MAX_SEEN_PROC_CONNS)self._pkt_times: dict[str, deque] = defaultdict(lambda: deque(maxlen=120))self._host_bytes_window: dict[str, deque] = defaultdict(lambda: deque(maxlen=60))+ # EN: (ts, port) events per scan-origin key + (ts, bytes) per remote IP.+ # FR: Événements (ts, port) par clé d'origine de scan + (ts, octets)+ # par IP distante.+ self._scan_events: dict[str, deque] = defaultdict(lambda: deque(maxlen=1000))+ 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] = {}self._cooldowns: dict[str, float] = {}self.history: list[dict] = []self._mic_procs: set[str] = set()@@ -276,6 +310,9 @@ class AnomalyDetector:self._seen_process_conns = BoundedSet(MAX_SEEN_PROC_CONNS)self._pkt_times.clear()self._host_bytes_window.clear()+ self._scan_events.clear()+ self._byte_window.clear()+ self._byte_baseline.clear()self._cooldowns.clear()# ── Public API / API publique ────────────────────────────────────────────@@ -297,8 +334,9 @@ class AnomalyDetector:alerts += self._check_new_host(remote_ip, geo)alerts += self._check_suspicious_process(pkt, remote_ip, geo)alerts += self._check_suspicious_port(pkt, remote_ip, geo)+ alerts += self._check_port_scan(pkt, remote_ip, geo)alerts += self._check_beacon(remote_ip, geo)- alerts += self._check_volume_spike(remote_ip, pkt.size, geo)+ alerts += self._check_volume_spike(remote_ip, pkt, geo)alerts += self._check_media_exfil(pkt, remote_ip, geo)self._record(alerts)return alerts@@ -377,21 +415,87 @@ class AnomalyDetector:)]def _check_suspicious_port(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:- """EN: Traffic to a notorious port → warning (cooldown-limited).- FR: Trafic vers un port sulfureux → warning (limité par cooldown)."""- port = pkt.dst_port+ """+ EN: Traffic involving a notorious REMOTE port → warning. remote_port+ is direction-aware — the old dst_port code flagged inbound+ traffic by OUR local port. Severity rises when a brand-new host+ touches the port (context, not just the number).+ FR: Trafic impliquant un port DISTANT sulfureux → warning.+ remote_port tient compte du sens — l'ancien code sur dst_port+ signalait le trafic entrant via NOTRE port local. La sévérité+ monte quand un hôte tout nouveau touche le port (contexte, pas+ juste le numéro).+ """+ port = pkt.remote_portif port not in SUSPICIOUS_PORTS:return []if not self._cooldown_ok(f"port:{port}:{remote_ip}"):return []label = geo.get("hostname") or remote_ipreason = SUSPICIOUS_PORTS[port]+ is_new_host = remote_ip not in self._seen_hostsreturn [Alert(type="SUSPICIOUS_PORT",- severity="warning",+ severity="critical" if is_new_host else "warning",message=f"Suspicious port {port} ({reason}) -> {label}",node_id=remote_ip,- details={"port": port, "reason": reason, "ip": remote_ip, "host": label},+ details={"port": port, "reason": reason, "ip": remote_ip, "host": label,+ "direction": pkt.direction, "process": pkt.process_name},+ )]++ def _check_port_scan(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:+ """+ EN: Port-scan rule (advertised by the README, previously absent):+ ≥ SCAN_THRESHOLD distinct remote ports within SCAN_WINDOW_S from+ one origin — works in BOTH directions: an inbound scan (one remote+ IP probing many local ports) and an outbound scan (one local+ process touching many remote ports) both register. Common chatty+ ports (53/80/443/853/123) can't feed the counter — a browser+ hitting :443 on 40 servers is traffic, not a scan.+ FR: Règle de scan de ports (annoncée par le README, absente avant) :+ ≥ SCAN_THRESHOLD ports distants distincts en SCAN_WINDOW_S depuis+ une origine — dans les DEUX sens : scan entrant (une IP distante+ sonde beaucoup de ports locaux) et sortant (un processus local+ touche beaucoup de ports distants) comptent tous deux. Les ports+ bavards courants (53/80/443/853/123) n'alimentent pas le compteur —+ un navigateur sur :443 vers 40 serveurs est du trafic, pas un scan.+ """+ remote_port = pkt.remote_port+ if not remote_port or remote_port in SCAN_COMMON_PORTS:+ return []+ proc = (pkt.process_name or "").lower()+ if remote_port in KNOWN_RESOLVER_PORTS or proc in KNOWN_RESOLVER_PROCS:+ return []++ # EN: Key by origin — inbound scans key on the remote IP, outbound on+ # the local process so different apps don't pool their counts.+ # FR: Clé par origine — les scans entrants se clés sur l'IP distante,+ # les sortants sur le processus local pour ne pas fusionner les+ # compteurs d'apps différentes.+ key = remote_ip if pkt.direction == "in" else f"local:{proc or 'unknown'}"+ now = time.time()+ dq = self._scan_events[key]+ dq.append((now, remote_port))+ cutoff = now - SCAN_WINDOW_S+ while dq and dq[0][0] < cutoff:+ dq.popleft()++ if len({p for _, p in dq}) < SCAN_THRESHOLD:+ return []+ dq.clear() # EN: don't re-fire on the same burst+ # FR: ne pas redéclencher sur la même rafale+ if not self._cooldown_ok(f"scan:{key}", cooldown=300):+ return []+ label = geo.get("hostname") or remote_ip+ source = remote_ip if pkt.direction == "in" else (pkt.process_name or "local")+ return [Alert(+ type="PORT_SCAN",+ severity="warning",+ message=f"Port scan: {source} touched {SCAN_THRESHOLD}+ ports in {SCAN_WINDOW_S}s",+ node_id=remote_ip,+ details={"source": source, "ip": remote_ip, "host": label,+ "ports": SCAN_THRESHOLD, "window_s": SCAN_WINDOW_S,+ "direction": pkt.direction},)]def _check_beacon(self, remote_ip: str, geo: dict) -> list[Alert]:@@ -457,29 +561,58 @@ class AnomalyDetector:details={"ip": remote_ip, "host": label, "interval_s": round(mean, 1), "cv": round(cv, 3), "samples": len(intervals)},)]- def _check_volume_spike(self, remote_ip: str, size: int, geo: dict) -> list[Alert]:- """EN: One packet ≥ 8× the rolling average for that host → possible- burst/exfil → warning. / FR: Un paquet ≥ 8× la moyenne glissante de- l'hôte → rafale/exfil possible → warning."""- dq = self._host_bytes_window[remote_ip]- dq.append(size)- if len(self._host_bytes_window) > MAX_TRACKED_IPS:- self._host_bytes_window.clear()- if len(dq) < 10:- return []- avg = sum(dq) / len(dq)- if size < avg * VOLUME_SPIKE_FACTOR or avg < 100:- return []- if not self._cooldown_ok(f"spike:{remote_ip}", cooldown=120):+ def _check_volume_spike(self, remote_ip: str, pkt: Packet, geo: dict) -> list[Alert]:+ """+ EN: Bytes per trailing window vs rolling baseline — not single-packet+ size. Outbound only (exfil risk). Each completed window folds into+ the baseline; a spike is > VOLUME_MULTIPLIER × median AND+ > VOLUME_MIN_BYTES so tiny hosts can't trip it.+ FR: Octets par fenêtre glissante vs base roulante — pas la taille+ d'un paquet. Sortant seulement (risque d'exfiltration). Chaque+ fenêtre terminée alimente la base ; un pic = > VOLUME_MULTIPLIER+ × médiane ET > VOLUME_MIN_BYTES, donc les petits hôtes ne+ déclenchent pas.+ """+ if pkt.direction != "out":return []- label = geo.get("hostname") or remote_ip- return [Alert(- type="VOLUME_SPIKE",- severity="warning",- message=f"Traffic spike to {label} ({size // 1024} KB in one packet)",- node_id=remote_ip,- details={"ip": remote_ip, "host": label, "size": size, "avg": int(avg), "kb": size // 1024},- )]+ if len(self._byte_window) > MAX_TRACKED_IPS:+ self._byte_window.clear()++ now = time.time()+ dq = self._byte_window[remote_ip]+ dq.append((now, pkt.size))+ cutoff = now - VOLUME_WINDOW_S+ while dq and dq[0][0] < cutoff:+ dq.popleft()+ window_bytes = sum(s for _, s in dq)++ baseline = self._byte_baseline[remote_ip]+ base_med = sorted(baseline)[len(baseline) // 2] if len(baseline) >= 3 else 0++ if window_bytes > VOLUME_MIN_BYTES and window_bytes > base_med * VOLUME_MULTIPLIER:+ if not self._cooldown_ok(f"spike:{remote_ip}", cooldown=120):+ return []+ label = geo.get("hostname") or remote_ip+ return [Alert(+ type="VOLUME_SPIKE",+ severity="warning",+ message=f"Data spike to {label}: {window_bytes // 1024} KB in {VOLUME_WINDOW_S}s",+ node_id=remote_ip,+ details={"ip": remote_ip, "host": label, "bytes": window_bytes,+ "window_s": VOLUME_WINDOW_S, "baseline": int(base_med),+ "process": pkt.process_name},+ )]++ # EN: Fold the trailing window into the baseline once per+ # VOLUME_WINDOW_S — one sample per completed window.+ # FR: Plier la fenêtre glissante dans la base une fois par+ # VOLUME_WINDOW_S — un échantillon par fenêtre terminée.+ if now - self._byte_last_fold.get(remote_ip, 0) >= VOLUME_WINDOW_S:+ baseline.append(window_bytes)+ self._byte_last_fold[remote_ip] = now+ if len(self._byte_last_fold) > MAX_TRACKED_IPS:+ self._byte_last_fold.clear()+ return []def _check_media_exfil(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:"""diff --git a/backend/logging_config.py b/backend/logging_config.pyindex f3d9b72..191da7a 100644--- a/backend/logging_config.py+++ b/backend/logging_config.py@@ -15,29 +15,10 @@ FR: Configuration centralisée des logs. Sortie vers stdout ET un fichier"""import logging-import os-import sysfrom logging.handlers import RotatingFileHandlerfrom pathlib import Path--def _data_dir() -> Path:- """- EN: Same resolution as api.security / storage.db — duplicated here so this- module has zero internal dependencies (it must be importable first).- FR: Même résolution que api.security / storage.db — dupliquée ici pour que- ce module n'ait aucune dépendance interne (il doit être importable en- premier).- """- env_dir = os.environ.get("SNITCH_DATA_DIR")- if env_dir:- d = Path(env_dir)- elif getattr(sys, "frozen", False):- d = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "Snitch"- else:- d = Path(__file__).parent.parent / "data"- d.mkdir(parents=True, exist_ok=True)- return d+from paths import data_dirdef setup_logging(level: int = logging.INFO) -> Path:@@ -47,7 +28,7 @@ def setup_logging(level: int = logging.INFO) -> Path:FR: Configurer le logger racine « snitch ». Renvoie le chemin du fichierde log. Idempotent — appelable plusieurs fois sans effet."""- log_dir = _data_dir() / "logs"+ log_dir = data_dir() / "logs"log_dir.mkdir(parents=True, exist_ok=True)log_file = log_dir / "snitch.log"diff --git a/backend/paths.py b/backend/paths.pynew file mode 100644index 0000000..c0f6203--- /dev/null+++ b/backend/paths.py@@ -0,0 +1,56 @@+"""+Snitch — filesystem paths.++EN: Single source of truth for the writable data directory — shared by the+ DB, the API token file and the log file (each used to duplicate this+ logic). Resolution order:+ 1. SNITCH_DATA_DIR env var (tests, custom deployments)+ 2. per-OS user data dir (frozen/Electron installs)+ Windows : %LOCALAPPDATA%\\Snitch+ macOS : ~/Library/Application Support/Snitch+ Linux : $XDG_DATA_HOME/snitch or ~/.local/share/snitch+ 3. <repo>/data (dev / Docker)++ NOTE: PyInstaller bundles are read-only — Path(__file__)-relative data+ dirs land inside the bundle and silently lose writes. Rule 2 exists for+ exactly that reason.++FR: Source de vérité unique pour le dossier de données inscriptible — partagée+ par la BDD, le fichier de jeton API et le fichier de log (chacun dupliquait+ cette logique). Ordre de résolution :+ 1. variable SNITCH_DATA_DIR (tests, déploiements personnalisés)+ 2. dossier de données utilisateur par OS (installations figées/Electron)+ Windows : %LOCALAPPDATA%\\Snitch+ macOS : ~/Library/Application Support/Snitch+ Linux : $XDG_DATA_HOME/snitch ou ~/.local/share/snitch+ 3. <dépôt>/data (dev / Docker)++ ATTENTION : les bundles PyInstaller sont en lecture seule — un dossier de+ données relatif à Path(__file__) atterrit dans le bundle et perd les+ écritures silencieusement. La règle 2 existe exactement pour ça.+"""++import os+import sys+from pathlib import Path+++def data_dir() -> Path:+ """+ EN: Resolve (and create) the writable data directory.+ FR: Résoudre (et créer) le dossier de données inscriptible.+ """+ env_dir = os.environ.get("SNITCH_DATA_DIR")+ if env_dir:+ d = Path(env_dir)+ elif getattr(sys, "frozen", False) or os.environ.get("SNITCH_USER_DATA") == "1":+ if sys.platform == "win32":+ d = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / "Snitch"+ elif sys.platform == "darwin":+ d = Path.home() / "Library" / "Application Support" / "Snitch"+ else:+ d = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share")) / "snitch"+ else:+ d = Path(__file__).parent.parent / "data"+ d.mkdir(parents=True, exist_ok=True)+ return ddiff --git a/backend/requirements.txt b/backend/requirements.txtindex 86f5a97..0e5fcbd 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -1,12 +1,20 @@# EN: Pinned Python dependencies for the Snitch backend.+# NOTE: Scapy was REMOVED — it is GPL-2.0-only, incompatible with the+# project's AGPL-3.0-or-later. Capture now runs through a ctypes binding+# to libpcap (BSD-licensed) plus our own parser (capture/pcap.py,+# capture/parser.py). dnspython went with it — DNS answers are parsed by+# our own parser now.# FR: Dépendances Python épinglées pour le backend Snitch.+# NOTE : Scapy a été RETIRÉ — c'est du GPL-2.0-only, incompatible avec+# l'AGPL-3.0-or-later du projet. La capture passe désormais par une+# liaison ctypes vers libpcap (licence BSD) plus notre propre parseur+# (capture/pcap.py, capture/parser.py). dnspython est parti aussi — les+# réponses DNS sont analysées par notre parseur.fastapi==0.115.0 # EN: REST + WebSocket API framework / FR: framework API REST + WebSocketuvicorn[standard]==0.30.6 # EN: ASGI server / FR: serveur ASGIwebsockets==13.0.1 # EN: WebSocket support / FR: support WebSocket-scapy==2.6.0 # EN: raw packet capture + ARP scan / FR: capture de paquets + scan ARP-dnspython==2.7.0 # EN: DNS utilities / FR: utilitaires DNS-geoip2==4.8.0 # EN: MaxMind GeoLite2 reader / FR: lecteur MaxMind GeoLite2+maxminddb==2.6.3 # EN: raw .mmdb reader — GeoLite2 AND DB-IP Lite / FR: lecteur .mmdb brut — GeoLite2 ET DB-IP Litepsutil==6.1.0 # EN: process + network interface info / FR: infos processus + interfaces réseaupython-dotenv==1.0.1 # EN: .env file support / FR: support des fichiers .envaiofiles==24.1.0 # EN: async file I/O / FR: E/S fichiers asynchronesdiff --git a/backend/resolver/dns_geo.py b/backend/resolver/dns_geo.pyindex c87198b..060564d 100644--- a/backend/resolver/dns_geo.py+++ b/backend/resolver/dns_geo.py@@ -1,237 +1,250 @@"""-Snitch — DNS reverse resolution + IP geolocation.+Snitch — DNS/domain resolution + IP geolocation.EN: Enrichment pipeline for remote IPs:- 1. reverse DNS (hostname) via socket.gethostbyaddr- 2. geolocation, local GeoLite2 offline DB via geoip2 (optional)- 3. OPTIONAL online fallback to ip-api.com via urllib (45 req/min)-- PRIVACY: the online fallback sends every contacted IP to a third-party- service in plaintext. For a privacy tool that's contradictory, so it is- OFF by default — enable it explicitly with SNITCH_ONLINE_GEO=1 and get a- GeoLite2 DB for fully-offline lookups.-- Reliability fixes vs the naive version:- - reverse DNS bounded by a global socket timeout (no more executor- threads parked forever)- - ip-api results use a TTL cache; failures are NOT cached, so a- temporary error doesn't permanently blind an IP- - a tiny client-side rate limiter keeps us under the 45 req/min quota+ 1. observed DNS answers — captured DNS responses map IP → real domain+ (the name the user actually asked for, not a useless CDN PTR)+ 2. observed TLS SNI — ClientHello hostname for the same purpose+ 3. reverse DNS — socket.gethostbyaddr, last resort+ 4. geolocation — local .mmdb ONLY (MaxMind GeoLite2 or DB-IP+ Lite; raw maxminddb reads both formats)++ PRIVACY: there is NO online geolocation fallback. ip-api.com was removed —+ a privacy tool must never leak visited IPs in plaintext. If no .mmdb is+ present the UI shows "no geo" and the README explains how to enable it.+ Databases live in the per-OS user data dir (paths.data_dir()), NOT next to+ __file__ — the old Path(__file__)/data code pointed inside the read-only+ PyInstaller bundle.++ Expected files in <data_dir>/geo/:+ GeoLite2-City.mmdb or dbip-city-lite.mmdb (city/country/lat/lon)+ GeoLite2-ASN.mmdb or dbip-asn-lite.mmdb (org/ASN)+ DB-IP Lite (CC BY 4.0): https://db-ip.com/db/lite.php — attribution shown+ in the UI footer and THIRD_PARTY_NOTICES.FR: Pipeline d'enrichissement des IP distantes :- 1. DNS inverse (hostname) via socket.gethostbyaddr- 2. géolocalisation, BDD hors ligne GeoLite2 via geoip2 (optionnel)- 3. repli en ligne OPTIONNEL vers ip-api.com via urllib (45 req/min)-- CONFIDENTIALITÉ : le repli en ligne envoie chaque IP contactée à un service- tiers en clair. Contradictoire pour un outil de confidentialité : il est- donc DÉSACTIVÉ par défaut — l'activer explicitement avec- SNITCH_ONLINE_GEO=1, ou déposer une base GeoLite2 pour des recherches- 100 % hors ligne.-- Corrections de fiabilité :- - DNS inverse borné par un timeout global de socket (plus de threads- d'executor bloqués indéfiniment)- - résultats ip-api dans un cache à TTL ; les échecs ne sont PAS cachés,- donc une erreur temporaire n'aveugle pas une IP pour toujours- - un petit limiteur côté client reste sous le quota de 45 req/min+ 1. réponses DNS observées — les réponses DNS capturées associent IP →+ vrai domaine (le nom réellement demandé, pas un PTR CDN inutile)+ 2. SNI TLS observé — nom d'hôte du ClientHello, même objectif+ 3. DNS inverse — socket.gethostbyaddr, dernier recours+ 4. géolocalisation — .mmdb local UNIQUEMENT (GeoLite2 MaxMind ou+ DB-IP Lite ; le lecteur maxminddb brut lit les deux formats)++ CONFIDENTIALITÉ : AUCUN repli de géolocalisation en ligne. ip-api.com a été+ supprimé — un outil de confidentialité ne doit jamais divulguer les IP+ visitées en clair. Sans .mmdb, l'UI affiche « sans géo » et le README+ explique comment l'activer. Les bases vivent dans le dossier de données+ utilisateur de l'OS (paths.data_dir()), PAS à côté de __file__ — l'ancien+ code Path(__file__)/data pointait dans le bundle PyInstaller en lecture+ seule.++ Fichiers attendus dans <data_dir>/geo/ :+ GeoLite2-City.mmdb ou dbip-city-lite.mmdb (ville/pays/lat/lon)+ GeoLite2-ASN.mmdb ou dbip-asn-lite.mmdb (org/ASN)+ DB-IP Lite (CC BY 4.0) : https://db-ip.com/db/lite.php — attribution+ affichée dans le pied de l'UI et THIRD_PARTY_NOTICES."""import asyncioimport ipaddress-import jsonimport logging-import osimport socketimport threadingimport time-import urllib.request-from collections import dequefrom functools import lru_cache-from pathlib import Pathfrom typing import Optional+from paths import data_dir+logger = logging.getLogger("snitch.resolver")try:- import geoip2.database- import geoip2.errors- GEOIP_AVAILABLE = True+ import maxminddb+ MMDB_AVAILABLE = Trueexcept ImportError:- # EN: geoip2 not installed — MaxMind lookups unavailable.- # FR: geoip2 non installé — recherches MaxMind indisponibles.- GEOIP_AVAILABLE = False--# EN: Global ceiling for blocking socket operations (reverse DNS mainly).-# gethostbyaddr has no per-call timeout, so we bound it globally.-# FR: Plafond global pour les opérations socket bloquantes (DNS inverse surtout).-# gethostbyaddr n'a pas de timeout par appel : on le borne globalement.+ # EN: maxminddb ships with geoip2 — absent only on minimal installs.+ # FR: maxminddb arrive avec geoip2 — absent seulement des installs minimales.+ MMDB_AVAILABLE = False++# EN: Global ceiling for blocking socket ops — gethostbyaddr has no per-call+# timeout, so we bound it globally (a stuck PTR lookup used to park+# executor threads forever).+# FR: Plafond global pour les opérations socket bloquantes — gethostbyaddr n'a+# pas de timeout par appel, donc on le borne globalement (une résolution+# PTR coincée parquait des threads d'executor indéfiniment).socket.setdefaulttimeout(3)-# EN: Online geolocation is OPT-IN (privacy by default).-# FR: La géolocalisation en ligne est OPT-IN (confidentialité par défaut).-ONLINE_GEO_ENABLED = os.environ.get("SNITCH_ONLINE_GEO", "").strip() == "1"+GEO_DIR = data_dir() / "geo"-# EN: Optional GeoLite2 database — drop GeoLite2-City.mmdb into data/.-# FR: Base GeoLite2 optionnelle — déposer GeoLite2-City.mmdb dans data/.-GEOIP_DB_PATH = Path(__file__).parent.parent.parent / "data" / "GeoLite2-City.mmdb"-_geoip_reader = None+_CITY_NAMES = ("dbip-city-lite.mmdb", "GeoLite2-City.mmdb")+_ASN_NAMES = ("dbip-asn-lite.mmdb", "GeoLite2-ASN.mmdb")+_readers: dict[str, object] = {}+_readers_lock = threading.Lock()-def get_geoip_reader():- """EN: Lazy-open the MaxMind reader once. / FR: Ouverture paresseuse du lecteur MaxMind."""- global _geoip_reader- if _geoip_reader is None and GEOIP_AVAILABLE and GEOIP_DB_PATH.exists():- try:- _geoip_reader = geoip2.database.Reader(str(GEOIP_DB_PATH))- except Exception as exc:- logger.warning("Could not open GeoLite2 DB at %s: %s", GEOIP_DB_PATH, exc)- return _geoip_reader+# EN: ip → (domain, expiry_epoch) learned from captured DNS answers and SNI.+# Bounded — 10k entries, TTL-respecting.+# FR: ip → (domaine, expiration) appris des réponses DNS capturées et du SNI.+# Borné — 10k entrées, respect du TTL.+_domain_map: dict[str, tuple[str, float]] = {}+_domain_lock = threading.Lock()+MAX_DOMAIN_MAP = 10_000def is_private(ip: str) -> bool:- """EN: RFC1918 / loopback / link-local / ULA check — works for v4 and v6.- FR: Test RFC1918 / loopback / link-local / ULA — fonctionne en v4 et v6."""+ """EN: RFC1918 / loopback / link-local / multicast / ULA check (v4 + v6).+ FR: Test RFC1918 / loopback / link-local / multicast / ULA (v4 + v6)."""try:- return ipaddress.ip_address(ip).is_private+ a = ipaddress.ip_address(ip)+ return a.is_private or a.is_loopback or a.is_link_local or a.is_multicastexcept ValueError:return False-@lru_cache(maxsize=2048)-def resolve_hostname(ip: str) -> Optional[str]:+# ── Observed domain names / Noms de domaine observés ─────────────────────────++def learn_dns_answers(answers: list[tuple[str, str, int]]) -> None:"""- EN: Reverse DNS — returns None on NXDOMAIN/timeout. lru_cache caches- negatives too, which is what we want: failed lookups are stable.- FR: DNS inverse — renvoie None sur NXDOMAIN/timeout. lru_cache met aussi en- cache les échecs, ce qui est souhaité : les échecs de résolution sont- stables.+ EN: Store A/AAAA answers from a captured DNS response so subsequent+ packets to those IPs get a meaningful hostname. TTL-aware; expires+ automatically on read.+ FR: Stocker les réponses A/AAAA d'une réponse DNS capturée pour que les+ paquets suivants vers ces IP obtiennent un nom d'hôte utile.+ Conscient du TTL ; expiration automatique à la lecture."""- try:- return socket.gethostbyaddr(ip)[0]- except Exception:+ now = time.time()+ with _domain_lock:+ for name, ip, ttl in answers:+ if not name or not ip:+ continue+ # EN: Bound the map — evict expired first, then oldest.+ # FR: Borner la table — évincer les expirées d'abord, puis les plus anciennes.+ if len(_domain_map) >= MAX_DOMAIN_MAP:+ _domain_map.clear()+ _domain_map[ip] = (name, now + min(ttl, 86400))+++def learn_sni(ip: str, hostname: Optional[str]) -> None:+ """EN: Record a TLS ClientHello hostname for a destination IP.+ FR: Enregistrer le nom d'hôte du ClientHello TLS pour une IP destination."""+ if not hostname:+ return+ with _domain_lock:+ if len(_domain_map) >= MAX_DOMAIN_MAP:+ _domain_map.clear()+ # EN: SNI has no TTL — keep for the session (24h cap).+ # FR: Le SNI n'a pas de TTL — conservation pour la session (plafond 24 h).+ _domain_map.setdefault(ip, (hostname, time.time() + 86400))+++def lookup_domain(ip: str) -> Optional[str]:+ """EN: Domain learned from DNS/SNI, or None. / FR: Domaine appris via DNS/SNI, ou None."""+ with _domain_lock:+ hit = _domain_map.get(ip)+ if hit and hit[1] > time.time():+ return hit[0]return None+# ── Reverse DNS / DNS inverse ────────────────────────────────────────────────+@lru_cache(maxsize=2048)-def resolve_geo_maxmind(ip: str) -> dict:+def resolve_hostname(ip: str) -> Optional[str]:"""- EN: Offline geolocation via the local GeoLite2 DB. Returns {} when the DB- is absent, the IP is private, or the lookup fails. Safe to cache —- results don't change within a session.- FR: Géolocalisation hors ligne via la base GeoLite2 locale. Renvoie {} si- la base est absente, l'IP privée, ou la requête en échec. Cache sûr —- les résultats ne changent pas pendant une session.+ EN: Reverse DNS — None on NXDOMAIN/timeout. lru_cache caches negatives+ too: PTR absence is stable, so that's the desired behavior.+ FR: DNS inverse — None sur NXDOMAIN/timeout. lru_cache met aussi en cache+ les échecs : l'absence de PTR est stable, c'est le comportement voulu."""- reader = get_geoip_reader()- if not reader or is_private(ip):- return {}try:- resp = reader.city(ip)- return {- "country": resp.country.name,- "country_code": resp.country.iso_code,- "city": resp.city.name,- "lat": resp.location.latitude,- "lon": resp.location.longitude,- "org": resp.traits.autonomous_system_organization,- }+ return socket.gethostbyaddr(ip)[0]except Exception:- return {}---# ── Online fallback: TTL cache + rate limiter ────────────────────────────────-# ── Repli en ligne : cache TTL + limiteur de débit ───────────────────────────--GEO_CACHE_TTL = 6 * 3600 # EN: 6h / FR: 6 h-GEO_RATE_MAX = 40 # EN: max requests per window / FR: requêtes max par fenêtre-GEO_RATE_WINDOW = 60 # seconds / secondes+ return None-_geo_cache: dict[str, tuple[float, dict]] = {}-_geo_cache_lock = threading.Lock()-_geo_calls: deque = deque() # EN: timestamps of recent API calls / FR: timestamps des appels récents+# ── Geolocation / Géolocalisation ────────────────────────────────────────────-def _rate_limit_ok() -> bool:+def _get_reader(kind: str):"""- EN: Sliding-window rate limiter — returns False when the quota for the- last 60 s is exhausted.- FR: Limiteur à fenêtre glissante — renvoie False quand le quota des 60- dernières secondes est épuisé.+ EN: Lazy-open one .mmdb reader ('city' or 'asn'). Prefers DB-IP Lite+ (CC BY 4.0) over GeoLite2 when both exist. Returns None if absent.+ FR: Ouvrir paresseusement un lecteur .mmdb (« city » ou « asn »). Préfère+ DB-IP Lite (CC BY 4.0) à GeoLite2 quand les deux existent. Renvoie+ None si absente."""- now = time.time()- while _geo_calls and now - _geo_calls[0] > GEO_RATE_WINDOW:- _geo_calls.popleft()- if len(_geo_calls) >= GEO_RATE_MAX:- return False- _geo_calls.append(now)- return True---def resolve_geo_ipapi(ip: str) -> dict:+ if not MMDB_AVAILABLE:+ return None+ with _readers_lock:+ if kind in _readers:+ return _readers[kind]+ names = _CITY_NAMES if kind == "city" else _ASN_NAMES+ reader = None+ for name in names:+ path = GEO_DIR / name+ if path.exists():+ try:+ reader = maxminddb.open_database(str(path))+ logger.info("geo %s database loaded: %s", kind, path.name)+ except Exception as exc:+ logger.warning("could not open %s: %s", path, exc)+ break+ _readers[kind] = reader+ return reader+++@lru_cache(maxsize=4096)+def resolve_geo(ip: str) -> dict:"""- EN: Online fallback — free ip-api.com, no key, ~45 req/min.- Disabled unless SNITCH_ONLINE_GEO=1. Successes are TTL-cached;- failures return {} and are NOT cached so the IP can retry later.- FR: Repli en ligne — ip-api.com gratuit, sans clé, ~45 req/min.- Désactivé sauf si SNITCH_ONLINE_GEO=1. Les succès sont cachés avec TTL ;- les échecs renvoient {} et ne sont PAS cachés pour permettre un re-essai.+ EN: Offline geolocation via local .mmdb files. Returns {} when no DB is+ present, the IP is private, or the lookup fails. Safe to cache —+ results are stable within a session.+ FR: Géolocalisation hors ligne via les .mmdb locaux. Renvoie {} sans base,+ sur IP privée, ou en cas d'échec. Cache sûr — les résultats sont+ stables pendant une session."""- if not ONLINE_GEO_ENABLED or is_private(ip):- return {}-- now = time.time()- with _geo_cache_lock:- hit = _geo_cache.get(ip)- if hit and now - hit[0] < GEO_CACHE_TTL:- return hit[1]-- if not _rate_limit_ok():- logger.debug("geo rate limit reached — skipping %s", ip)+ if is_private(ip):return {}- try:- url = f"http://ip-api.com/json/{ip}?fields=status,country,countryCode,city,lat,lon,org"- req = urllib.request.Request(url, headers={"User-Agent": "snitch/1.0"})- with urllib.request.urlopen(req, timeout=4) as resp:- data = json.loads(resp.read())- if data.get("status") == "success":+ geo: dict = {}+ city = _get_reader("city")+ if city is not None:+ try:+ rec = city.get(ip) or {}+ country = rec.get("country") or rec.get("registered_country") or {}geo = {- "country": data.get("country"),- "country_code": data.get("countryCode"),- "city": data.get("city"),- "lat": data.get("lat"),- "lon": data.get("lon"),- "org": data.get("org"),+ "country": (country.get("names") or {}).get("en") or country.get("name"),+ "country_code": country.get("iso_code"),+ "city": ((rec.get("city") or {}).get("names") or {}).get("en"),+ "lat": (rec.get("location") or {}).get("latitude"),+ "lon": (rec.get("location") or {}).get("longitude"),}- with _geo_cache_lock:- _geo_cache[ip] = (now, geo)- return geo- except Exception as exc:- logger.debug("ip-api lookup failed for %s: %s", ip, exc)- return {}+ except Exception as exc:+ logger.debug("city lookup failed for %s: %s", ip, exc)+ asn = _get_reader("asn")+ if asn is not None:+ try:+ rec = asn.get(ip) or {}+ geo["org"] = rec.get("autonomous_system_organization")+ except Exception as exc:+ logger.debug("asn lookup failed for %s: %s", ip, exc)-def resolve_geo(ip: str) -> dict:- """- EN: MaxMind first (offline, private), online fallback second.- FR: MaxMind d'abord (hors ligne, privé), repli en ligne ensuite.- """- geo = resolve_geo_maxmind(ip)- if geo:- return geo- return resolve_geo_ipapi(ip)+ return geoasync def enrich_ip(ip: str) -> dict:"""- EN: Async wrapper — runs the blocking DNS/geo work in the default- executor so the event loop stays responsive under load.- FR: Enveloppe async — exécute le travail DNS/geo bloquant dans l'executor- par défaut pour que la boucle reste réactive sous charge.+ EN: Async wrapper — blocking DNS/geo work runs in the default executor so+ the event loop stays responsive. Domain preference order:+ observed DNS/SNI > reverse DNS.+ FR: Enveloppe async — le travail DNS/geo bloquant tourne dans l'executor+ par défaut pour garder la boucle réactive. Préférence de domaine :+ DNS/SNI observé > DNS inverse."""loop = asyncio.get_running_loop()- hostname = await loop.run_in_executor(None, resolve_hostname, ip)+ hostname = lookup_domain(ip)+ if not hostname:+ hostname = await loop.run_in_executor(None, resolve_hostname, ip)geo = await loop.run_in_executor(None, resolve_geo, ip)return {"ip": ip,diff --git a/backend/scanner/arp_scanner.py b/backend/scanner/arp_scanner.pyindex 35cb18f..9369644 100644--- a/backend/scanner/arp_scanner.py+++ b/backend/scanner/arp_scanner.py@@ -1,23 +1,43 @@"""-Snitch — LAN scanner (ARP discovery).+Snitch — LAN device discovery via the system ARP table.-EN: Periodically ARP-scans every IPv4 subnet the host is attached to and- reports each responder as a `Device`. Devices that stop answering are- marked offline. Vendor/device-type identification comes from the local- OUI table (scanner/oui.py).+EN: Scapy is gone (GPL-2.0-only), so active ARP broadcast scanning went with+ it. Discovery now reads the OS neighbour cache — populated passively by+ normal traffic, so it catches what your machine actually talks to:-FR: Scanne périodiquement en ARP chaque sous-réseau IPv4 auquel l'hôte est- rattaché et rapporte chaque répondant comme `Device`. Les appareils qui- cessent de répondre sont marqués hors ligne. L'identification du- fabricant/type vient de la table OUI locale (scanner/oui.py).+ - Linux : /proc/net/arp+ - Windows : `arp -a` (" 192.168.1.1 00-11-22-33-44-55 dynamic")+ - macOS : `arp -a` ("? (192.168.1.1) at 0:11:22:33:44:55 on en0")++ Entries marked "incomplete"/permanent-failed are skipped. Each responder+ is reverse-DNS'd and OUI-matched to guess vendor + device type. Devices+ absent from a scan are flagged offline and announced once more.++FR: Scapy est parti (GPL-2.0-only), donc le scan ARP broadcast actif l'a suivi.+ La découverte lit désormais le cache de voisinage de l'OS — alimenté+ passivement par le trafic normal, donc il attrape ce à quoi votre machine+ parle vraiment :++ - Linux : /proc/net/arp+ - Windows : `arp -a` (« 192.168.1.1 00-11-22-33-44-55 dynamic »)+ - macOS : `arp -a` (« ? (192.168.1.1) at 0:11:22:33:44:55 on en0 »)++ Les entrées « incomplete »/échouées sont ignorées. Chaque répondant passe+ en DNS inverse + correspondance OUI pour deviner fabricant et type+ d'appareil. Les appareils absents d'un scan passent hors ligne et sont+ annoncés une dernière fois."""import ipaddressimport logging+import reimport socket+import subprocess+import sysimport threadingimport timefrom dataclasses import dataclass, field+from pathlib import Pathfrom typing import Callable, Optionalimport psutil@@ -26,151 +46,132 @@ from scanner.oui import lookup, DEVICE_TYPE_COLORSlogger = logging.getLogger("snitch.scanner")-try:- from scapy.all import ARP, Ether, srp- SCAPY_AVAILABLE = True-except ImportError:- # EN: Without Scapy there is no ARP scan — the rest of the app still works.- # FR: Sans Scapy pas de scan ARP — le reste de l'app fonctionne quand même.- SCAPY_AVAILABLE = False+# EN: MAC address matcher — handles both : and - separators.+# FR: Reconnaisseur d'adresse MAC — gère les séparateurs : et -.+MAC_RE = re.compile(r"([0-9a-fA-F]{2}[:\-]){5}[0-9a-fA-F]{2}")+IPV4_RE = re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b")@dataclassclass Device:"""- EN: One host discovered on the local network.- FR: Un hôte découvert sur le réseau local.+ EN: One LAN device as displayed in the graph.+ FR: Un appareil LAN tel qu'affiché dans le graphe."""ip: strmac: str- vendor: str- device_type: str # "router" | "phone" | "pc" | "tv" | "iot" | "unknown"- hostname: Optional[str]+ vendor: str = "Unknown"+ device_type: str = "unknown" # phone / pc / router / iot / tv / unknown+ hostname: Optional[str] = Noneonline: bool = True+ first_seen: float = field(default_factory=time.time)+ last_seen: float = field(default_factory=time.time)+ bytes: int = 0+ packets: int = 0color: str = "#64748b"- icon: str = "?"def to_dict(self) -> dict:- """- EN: Serialize to the node shape the frontend graph expects. The `lan:`- id prefix keeps LAN nodes from colliding with external-IP nodes.- FR: Sérialiser vers la forme de nœud attendue par le graphe frontend.- Le préfixe d'id « lan: » évite les collisions avec les nœuds- d'IP externes.- """+ """EN: Serialize for JSON transport. / FR: Sérialiser pour le transport JSON."""return {"id": f"lan:{self.ip}","ip": self.ip,"mac": self.mac,+ "label": self.hostname or self.vendor or self.ip,+ "hostname": self.hostname,"vendor": self.vendor,+ "category": "lan_device","device_type": self.device_type,- "hostname": self.hostname,- "label": self.hostname or self.vendor or self.ip,"online": self.online,- "category": "lan_device",+ "bytes": self.bytes,+ "packets": self.packets,"color": self.color,- "icon": self.icon,- "bytes": 0,- "packets": 0,}-def _get_local_subnets() -> list[str]:+def _get_local_ips() -> set[str]:+ """EN: This host's own IPv4 addresses — filtered out of results.+ FR: Les IPv4 propres à cet hôte — filtrées des résultats."""+ return {+ addr.address+ for addrs in psutil.net_if_addrs().values()+ for addr in addrs+ if addr.family == socket.AF_INET+ }+++def _read_arp_table() -> list[tuple[str, str]]:"""- EN: Build the list of local IPv4 subnets (CIDR) from interface addresses- and netmasks. Skips loopback and absurdly large/small networks.- FR: Construire la liste des sous-réseaux IPv4 locaux (CIDR) à partir des- adresses d'interfaces et masques. Ignore le loopback et les réseaux- absurdement grands/petits.+ EN: Snapshot of the system ARP/neighbour table as (ip, mac) pairs.+ Platform-specific reader; returns [] on failure — the scanner stays+ alive and retries next interval.+ FR: Instantané de la table ARP/voisinage système en couples (ip, mac).+ Lecteur par plateforme ; renvoie [] en cas d'échec — le scanner reste+ vivant et réessaie à l'intervalle suivant."""- subnets = []- for iface, addrs in psutil.net_if_addrs().items():- for addr in addrs:- if addr.family != socket.AF_INET:- continue- ip = addr.address- netmask = addr.netmask- if not netmask or ip.startswith("127."):- continue- try:- network = ipaddress.IPv4Network(f"{ip}/{netmask}", strict=False)- if network.num_addresses <= 2 or network.num_addresses > 65536:- continue- subnets.append(str(network))- except ValueError:- continue- return subnets+ if sys.platform.startswith("linux"):+ return _read_arp_linux()+ return _read_arp_cmd()-def _resolve_hostname(ip: str) -> Optional[str]:- """EN: Reverse-DNS a LAN IP; None on failure. / FR: DNS inverse d'une IP LAN ; None en cas d'échec."""+def _read_arp_linux() -> list[tuple[str, str]]:+ """EN: Parse /proc/net/arp — flag 0x0 or 00:00:... means incomplete.+ FR: Analyser /proc/net/arp — flag 0x0 ou MAC 00:00:… signifie incomplet."""+ out = []try:- return socket.gethostbyaddr(ip)[0]- except Exception:- return None+ lines = Path("/proc/net/arp").read_text().splitlines()[1:]+ except OSError as exc:+ logger.debug("/proc/net/arp unreadable: %s", exc)+ return out+ for line in lines:+ parts = line.split()+ if len(parts) < 6:+ continue+ ip, _hwtype, flags, mac = parts[0], parts[1], parts[2], parts[3]+ if int(flags, 16) == 0 or mac == "00:00:00:00:00:00":+ continue+ out.append((ip, mac.upper()))+ return out-def _scan_subnet(subnet: str, timeout: int = 2) -> list[Device]:- """- EN: Send one broadcast ARP request per subnet and collect answers.- This host's own IPs are filtered out — the graph already has a- dedicated "local" node.- FR: Envoyer une requête ARP broadcast par sous-réseau et collecter les- réponses. Les IP de cette machine sont filtrées — le graphe possède- déjà un nœud « local » dédié.- """- if not SCAPY_AVAILABLE:- return []+def _read_arp_cmd() -> list[tuple[str, str]]:+ """EN: Parse `arp -a` on Windows ("-"-separated MACs) and macOS+ (parenthesized IPs). / FR: Analyser `arp -a` sous Windows (MAC séparées par+ « - ») et macOS (IP entre parenthèses)."""try:- ans, _ = srp(- Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=subnet),- timeout=timeout,- verbose=False,- retry=1,- )- except Exception as exc:- logger.debug("ARP scan of %s failed: %s", subnet, exc)+ proc = subprocess.run(["arp", "-a"], capture_output=True, text=True,+ timeout=10)+ out_text = proc.stdout+ except (OSError, subprocess.TimeoutExpired) as exc:+ logger.debug("arp -a failed: %s", exc)return []- devices = []- local_ips = {- addr.address- for addrs in psutil.net_if_addrs().values()- for addr in addrs- if addr.family == socket.AF_INET- }-- for sent, received in ans:- ip = received.psrc- mac = received.hwsrc-- if ip in local_ips:+ pairs = []+ for line in out_text.splitlines():+ if "incomplete" in line.lower():continue+ ip_m = IPV4_RE.search(line)+ mac_m = MAC_RE.search(line)+ if ip_m and mac_m:+ pairs.append((ip_m.group(0), mac_m.group(0).replace("-", ":").upper()))+ return pairs- vendor, device_type = lookup(mac)- hostname = _resolve_hostname(ip)-- devices.append(Device(- ip=ip,- mac=mac,- vendor=vendor,- device_type=device_type,- hostname=hostname,- online=True,- color=DEVICE_TYPE_COLORS.get(device_type, "#64748b"),- ))- return devices+def _resolve_hostname(ip: str) -> Optional[str]:+ """EN: Reverse-DNS a LAN IP; None on failure. / FR: DNS inverse d'une IP LAN ; None en cas d'échec."""+ try:+ return socket.gethostbyaddr(ip)[0]+ except Exception:+ return Noneclass ARPScanner:"""- EN: Background scanner — scans all local subnets every `interval` seconds- and invokes `callback(device, is_new)` for each responder, plus once- more with online=False when a known device disappears.- FR: Scanner d'arrière-plan — scanne tous les sous-réseaux locaux toutes les- `interval` secondes et appelle `callback(device, is_new)` pour chaque- répondant, plus une fois avec online=False quand un appareil connu+ EN: Background scanner — re-reads the neighbour table every `interval`+ seconds. Invokes `callback(device, is_new)` for each entry, and once+ with online=False when a known device disappears.+ FR: Scanner d'arrière-plan — relit la table de voisinage toutes les+ `interval` secondes. Appelle `callback(device, is_new)` pour chaque+ entrée, et une fois avec online=False quand un appareil connudisparaît."""@@ -183,21 +184,42 @@ class ARPScanner:def _run(self) -> None:"""- EN: Scan loop. `seen_ips` tracks responders this round; known devices- absent from it are flipped to offline.- FR: Boucle de scan. `seen_ips` suit les répondants du tour ; les- appareils connus absents passent hors ligne.+ EN: Scan loop. `seen_ips` tracks devices present this round; known+ devices absent from it are flipped to offline.+ FR: Boucle de scan. `seen_ips` suit les appareils présents ce tour ;+ les appareils connus absents passent hors ligne."""+ local_ips = _get_local_ips()while self._running:- subnets = _get_local_subnets()seen_ips: set[str] = set()- for subnet in subnets:- for device in _scan_subnet(subnet):- seen_ips.add(device.ip)- is_new = device.ip not in self._known- self._known[device.ip] = device- self.callback(device, is_new)+ for ip, mac in _read_arp_table():+ if ip in local_ips:+ continue+ try:+ addr = ipaddress.ip_address(ip)+ if addr.is_multicast or addr.is_loopback or addr.is_link_local:+ continue+ except ValueError:+ continue++ seen_ips.add(ip)+ is_new = ip not in self._known+ if is_new:+ vendor, device_type = lookup(mac)+ hostname = _resolve_hostname(ip)+ self._known[ip] = Device(+ ip=ip, mac=mac, vendor=vendor, device_type=device_type,+ hostname=hostname, online=True,+ color=DEVICE_TYPE_COLORS.get(device_type, "#64748b"),+ )+ else:+ self._known[ip].last_seen = time.time()+ if not self._known[ip].online:+ self._known[ip].online = True+ is_new = True # EN: treat reappearance as a change event+ # FR: traiter la réapparition comme un événement+ self.callback(self._known[ip], is_new)# EN: Mark disappeared devices as offline.# FR: Marquer hors ligne les appareils disparus.diff --git a/backend/storage/db.py b/backend/storage/db.pyindex 065a2f7..245656c 100644--- a/backend/storage/db.py+++ b/backend/storage/db.py@@ -28,35 +28,16 @@ FR: Deux tables :import jsonimport logging-import osimport sqlite3-import sysimport threadingfrom collections import defaultdictfrom datetime import datetime, timedelta, timezone-from pathlib import Path--logger = logging.getLogger("snitch.storage")+from paths import data_dir-def _get_db_path() -> Path:- """- EN: Resolve the DB path — see module docstring for the precedence order.- FR: Résoudre le chemin de la base — voir le docstring du module pour- l'ordre de priorité.- """- env_dir = os.environ.get("SNITCH_DATA_DIR")- if env_dir:- db_dir = Path(env_dir)- elif getattr(sys, 'frozen', False):- db_dir = Path(os.environ.get('LOCALAPPDATA', Path.home())) / 'Snitch'- else:- db_dir = Path(__file__).parent.parent.parent / 'data'- db_dir.mkdir(parents=True, exist_ok=True)- return db_dir / 'snitch.db'-+logger = logging.getLogger("snitch.storage")-DB_PATH = _get_db_path()+DB_PATH = data_dir() / 'snitch.db'# EN: Single shared connection guarded by a lock — sqlite3 is not thread-safe# by default and we write from several threads.@@ -125,10 +106,57 @@ def _init_schema(conn: sqlite3.Connection) -> None:details TEXT);CREATE INDEX IF NOT EXISTS idx_alerts_ts ON alerts_log(ts);++ -- EN: Persisted settings (filters, whitelist, language, thresholds…).+ -- Values are JSON; the API loads them at startup.+ -- FR: Réglages persistés (filtres, whitelist, langue, seuils…).+ -- Valeurs en JSON ; l'API les charge au démarrage.+ CREATE TABLE IF NOT EXISTS settings (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+ );""")conn.commit()+# ── Settings / Réglages ──────────────────────────────────────────────────────++def get_setting(key: str, default=None):+ """EN: Read one persisted setting (JSON-decoded). / FR: Lire un réglage persisté (décodé JSON)."""+ with _conn_lock:+ row = get_conn().execute(+ "SELECT value FROM settings WHERE key = ?", (key,)).fetchone()+ if not row:+ return default+ try:+ return json.loads(row[0])+ except (json.JSONDecodeError, TypeError):+ return default+++def set_setting(key: str, value) -> None:+ """EN: Persist one setting as JSON. / FR: Persister un réglage en JSON."""+ with _conn_lock:+ conn = get_conn()+ conn.execute(+ "INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",+ (key, json.dumps(value)))+ conn.commit()+++def all_settings() -> dict:+ """EN: All persisted settings as a dict. / FR: Tous les réglages persistés en dict."""+ with _conn_lock:+ rows = get_conn().execute("SELECT key, value FROM settings").fetchall()+ out = {}+ for k, v in rows:+ try:+ out[k] = json.loads(v)+ except (json.JSONDecodeError, TypeError):+ pass+ return out++# ── Write helpers / Aides d'écriture ─────────────────────────────────────────def accumulate(minute: str, category: str, size: int) -> None:@@ -236,6 +264,32 @@ def get_timeline(minutes: int = 60) -> list[dict]:]+def get_alerts(limit: int = 100) -> list[dict]:+ """+ EN: Most recent persisted alerts, newest first — the /alerts endpoint now+ survives restarts instead of serving only the in-memory tail.+ FR: Alertes persistées les plus récentes, plus récentes d'abord — le+ endpoint /alerts survit désormais aux redémarrages au lieu de servir+ seulement la queue en mémoire.+ """+ with _conn_lock:+ rows = get_conn().execute("""+ SELECT id, ts, type, severity, message, node_id, details+ FROM alerts_log ORDER BY ts DESC LIMIT ?+ """, (limit,)).fetchall()+ out = []+ for r in rows:+ try:+ details = json.loads(r[6] or "{}")+ except json.JSONDecodeError:+ details = {}+ out.append({+ "id": r[0], "timestamp": r[1], "type": r[2], "severity": r[3],+ "message": r[4], "node_id": r[5], "details": details,+ })+ return out++def cleanup_old_data(hours: int = 24) -> None:"""EN: Delete rows older than `hours` — keeps the DB bounded since the UIdiff --git a/backend/tests/test_anomaly.py b/backend/tests/test_anomaly.pyindex 9c04393..0844ab5 100644--- a/backend/tests/test_anomaly.py+++ b/backend/tests/test_anomaly.py@@ -30,6 +30,8 @@ def pkt(remote=PUBLIC_IP, direction="out", port=443, size=500, process=None, prodst_ip=remote if direction == "out" else local,src_port=50000 if direction == "out" else port,dst_port=port if direction == "out" else 50000,+ remote_port=port, # EN: the remote end — same both ways+ # FR: l'extrémité distante — identique dans les deux sensprotocol=proto,size=size,timestamp=datetime.now(timezone.utc).isoformat(),diff --git a/backend/tests/test_db.py b/backend/tests/test_db.pyindex d918f72..224028a 100644--- a/backend/tests/test_db.py+++ b/backend/tests/test_db.py@@ -58,3 +58,35 @@ def test_cleanup_deletes_old_rows():db.cleanup_old_data(hours=24)rows = [r for r in db.get_timeline(minutes=99999999) if r["minute"] == "2000-01-01T00:00"]assert rows == []+++def test_settings_roundtrip():+ """EN: set_setting/get_setting persist JSON values; all_settings returns+ the lot. / FR: set_setting/get_setting persistent le JSON ; all_settings+ renvoie le tout."""+ key = f"test_{uuid.uuid4().hex[:8]}"+ assert db.get_setting(key) is None+ db.set_setting(key, {"ports": [443, 80], "nested": True})+ assert db.get_setting(key) == {"ports": [443, 80], "nested": True}+ db.set_setting(key, [1, 2])+ assert db.get_setting(key) == [1, 2]+ assert key in db.all_settings()+++def test_get_alerts_reads_persisted():+ """EN: /alerts is DB-backed — a logged alert must come back via+ get_alerts. / FR: /alerts est adossé à la BDD — une alerte journalisée+ doit revenir via get_alerts."""+ alert = {+ "id": str(uuid.uuid4()),+ "timestamp": datetime.now(timezone.utc).isoformat(),+ "type": "PORT_SCAN",+ "severity": "warning",+ "message": "test scan",+ "node_id": "10.0.0.9",+ "details": {"ports": 25},+ }+ db.log_alert(alert)+ rows = db.get_alerts(100)+ hit = [r for r in rows if r["id"] == alert["id"]]+ assert hit and hit[0]["type"] == "PORT_SCAN" and hit[0]["details"]["ports"] == 25diff --git a/backend/tests/test_parser.py b/backend/tests/test_parser.pynew file mode 100644index 0000000..81ee525--- /dev/null+++ b/backend/tests/test_parser.py@@ -0,0 +1,225 @@+"""+Snitch — parser tests (synthetic packets, no real captures).++EN: Every frame below is built byte-by-byte in the test — no pcap files, no+ real traffic, no Scapy. Coverage: Ethernet/IPv4/TCP, IPv6 + extension+ headers, UDP, DNS answers (A/AAAA/CNAME), TLS ClientHello SNI, malformed+ inputs.++FR: Chaque trame ci-dessous est construite octet par octet dans le test — pas+ de fichiers pcap, pas de trafic réel, pas de Scapy. Couverture :+ Ethernet/IPv4/TCP, IPv6 + en-têtes d'extension, UDP, réponses DNS+ (A/AAAA/CNAME), SNI du ClientHello TLS, entrées malformées.+"""++import struct++from capture.parser import (+ DLT_EN10MB, DLT_LINUX_SLL, DLT_LINUX_SLL2, DLT_NULL, DLT_RAW,+ parse_frame, parse_dns, parse_tls_sni,+)++ETH = DLT_EN10MB+++def eth(payload: bytes, ethertype: int = 0x0800) -> bytes:+ """EN: Ethernet II frame around a payload. / FR: Trame Ethernet II autour d'une charge."""+ return b"\xaa\xbb\xcc\xdd\xee\xff" + b"\x11\x22\x33\x44\x55\x66" + struct.pack("!H", ethertype) + payload+++def ipv4(src: bytes, dst: bytes, proto: int, payload: bytes,+ ihl_extra: bytes = b"") -> bytes:+ """EN: IPv4 packet. / FR: Paquet IPv4."""+ ihl = 5 + len(ihl_extra) // 4+ total = 20 + len(ihl_extra) + len(payload)+ hdr = struct.pack("!BBHHHBBH4s4s",+ (4 << 4) | ihl, 0, total, 0, 0, 64, proto, 0, src, dst)+ return hdr + ihl_extra + payload+++def ipv6(src: bytes, dst: bytes, next_header: int, payload: bytes,+ ext: bytes = b"") -> bytes:+ """EN: IPv6 packet. / FR: Paquet IPv6."""+ plen = len(ext) + len(payload)+ hdr = struct.pack("!IHBB16s16s", 6 << 28, plen, next_header, 64, src, dst)+ return hdr + ext + payload+++def tcp(sport: int, dport: int, flags: int = 0x18, payload: bytes = b"") -> bytes:+ """EN: TCP segment (data offset 5). / FR: Segment TCP (data offset 5)."""+ hdr = struct.pack("!HHIIBBHHH", sport, dport, 0, 0, 5 << 4, flags, 8192, 0, 0)+ return hdr + payload+++def udp(sport: int, dport: int, payload: bytes = b"") -> bytes:+ """EN: UDP datagram. / FR: Datagramme UDP."""+ return struct.pack("!HHHH", sport, dport, 8 + len(payload), 0) + payload+++def dns_response(answers: list[tuple[str, int, bytes]], qname: str = "example.com") -> bytes:+ """+ EN: Minimal DNS response — header + one question + answer RRs. Each+ answer: (name, rtype, rdata). Names are written as label sequences.+ FR: Réponse DNS minimale — en-tête + une question + RR de réponse.+ Chaque réponse : (nom, rtype, rdata). Les noms sont en séquences de+ labels.+ """+ def name_to_wire(n: str) -> bytes:+ out = b""+ for label in n.split("."):+ out += bytes([len(label)]) + label.encode()+ return out + b"\x00"++ hdr = struct.pack("!HHHHHH", 0x1234, 0x8180, 1, len(answers), 0, 0)+ question = name_to_wire(qname) + struct.pack("!HH", 1, 1)+ body = b""+ for name, rtype, rdata in answers:+ body += name_to_wire(name) + struct.pack("!HHIH", rtype, 1, 60, len(rdata)) + rdata+ return hdr + question + body+++def tls_client_hello(sni_host: str) -> bytes:+ """+ EN: Minimal TLS record + ClientHello with a real SNI extension — the+ fixed-layout walk in parse_sni() must find it.+ FR: Enregistrement TLS minimal + ClientHello avec une vraie extension+ SNI — le parcours à layout fixe de parse_sni() doit la trouver.+ """+ host = sni_host.encode()+ # EN: ext = type(2) + len(2) + data; data = list_len(2) + type(1) ++ # name_len(2) + name.+ # FR: ext = type(2) + longueur(2) + données ; données = longueur liste(2)+ # + type(1) + longueur nom(2) + nom.+ name_entry = struct.pack("!BH", 0, len(host)) + host+ sni_data = struct.pack("!H", len(name_entry)) + name_entry+ sni_ext = struct.pack("!HH", 0, len(sni_data)) + sni_data++ ext_block = sni_ext+ hello_body = (+ b"\x03\x03" # client version+ + b"\x00" * 32 # random+ + b"\x00" # session id len+ + struct.pack("!H", 2) + b"\x13\x01" # cipher suites+ + b"\x01\x00" # compression: null+ + struct.pack("!H", len(ext_block)) + ext_block+ )+ handshake = b"\x01" + len(hello_body).to_bytes(3, "big") + hello_body+ return b"\x16\x03\x01" + struct.pack("!H", len(handshake)) + handshake+++# ── Ethernet / IPv4 / TCP ────────────────────────────────────────────────────++def test_ipv4_tcp_outbound():+ payload = tcp(54321, 443)+ ip = ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6, payload)+ p = parse_frame(ETH, eth(ip))+ assert p is not None+ assert p.src_ip == "10.0.0.1" and p.dst_ip == "93.184.216.34"+ assert p.protocol == "TCP"+ assert p.src_port == 54321 and p.dst_port == 443+ assert p.tcp_flags == 0x18+++def test_ipv4_udp_dns():+ dns = dns_response([("example.com", 1, b"\x5d\xb8\xd8\x22")])+ p = parse_frame(ETH, eth(ipv4(b"\x08\x08\x08\x08", b"\x0a\x00\x00\x01", 17, udp(53, 5353, dns))))+ assert p.protocol == "UDP" and p.src_port == 53+ assert ("example.com", "93.184.216.34", 60) in p.dns+++def test_ipv4_aaaa():+ dns = dns_response([("v6.example.com", 28, b"\x26\x06\x28\x00" + b"\x00" * 12)])+ p = parse_frame(ETH, eth(ipv4(b"\x08\x08\x08\x08", b"\x0a\x00\x00\x01", 17, udp(53, 5353, dns))))+ assert p.dns[0][0] == "v6.example.com"+ assert ":" in p.dns[0][1]+++def test_tcp_sni_extracted():+ hello = tls_client_hello("www.example.org")+ p = parse_frame(ETH, eth(ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6,+ tcp(54321, 443, payload=hello))))+ assert p.sni == "www.example.org"+++def test_sni_not_port_443():+ """EN: SNI parses on any port — the TLS record signature is what counts.+ FR: Le SNI se parse sur tout port — c'est la signature TLS qui compte."""+ hello = tls_client_hello("sneaky.example.net")+ p = parse_frame(ETH, eth(ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6,+ tcp(54321, 8443, payload=hello))))+ assert p.sni == "sneaky.example.net"+++# ── IPv6 + extensions / IPv6 + extensions ────────────────────────────────────++def test_ipv6_tcp():+ src = bytes.fromhex("20010db8" + "00" * 12)+ dst = bytes.fromhex("2606" + "2800" + "00" * 12)+ p = parse_frame(ETH, eth(ipv6(src, dst, 6, tcp(1234, 443)), 0x86dd))+ assert p.protocol == "TCP" and p.dst_port == 443+ assert p.src_ip == "2001:db8::"+++def test_ipv6_extension_header_skip():+ """EN: Hop-by-hop ext header (8 bytes) before TCP must be walked, not+ misparsed. / FR: L'en-tête hop-by-hop (8 o) avant TCP doit être sauté."""+ src = bytes.fromhex("20010db8" + "00" * 12)+ dst = bytes.fromhex("2606" + "2800" + "00" * 12)+ ext = bytes([6, 0]) + b"\x00" * 6 # next=tcp, len=0 → 8 bytes total+ p = parse_frame(ETH, eth(ipv6(src, dst, 0, tcp(1234, 443), ext), 0x86dd))+ assert p.protocol == "TCP" and p.dst_port == 443+++# ── Alternate link types / Types de lien alternatifs ─────────────────────────++def test_dlt_raw():+ p = parse_frame(DLT_RAW, ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6, tcp(1, 2)))+ assert p is not None and p.dst_port == 2+++def test_dlt_null_loopback():+ null_hdr = struct.pack("<I", 2) # AF_INET+ p = parse_frame(DLT_NULL, null_hdr + ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6, tcp(1, 2)))+ assert p is not None and p.src_ip == "10.0.0.1"+++def test_dlt_sll():+ sll = b"\x00" * 4 + struct.pack("!H", 0x0800) + b"\x00" * 8 # pkttype+arphrd+lladdrlen+addr+proto+ sll = struct.pack("!HHH8sH", 0, 1, 0, b"\x00" * 8, 0x0800)+ p = parse_frame(DLT_LINUX_SLL, sll + ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6, tcp(1, 2)))+ assert p is not None and p.dst_port == 2+++def test_dlt_sll2():+ # EN: SLL2 header (20 bytes): proto(2) | rsvd(2) | if_index(4) |+ # hatype(2) | pkttype(1) | halen(1) | addr(8).+ # FR: En-tête SLL2 (20 octets) : proto(2) | réservé(2) | if_index(4) |+ # hatype(2) | pkttype(1) | halen(1) | adresse(8).+ sll2 = struct.pack("!HxxIHBB8s", 0x0800, 0, 0, 0, 0, b"\x00" * 8)+ p = parse_frame(DLT_LINUX_SLL2, sll2 + ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6, tcp(1, 2)))+ assert p is not None and p.dst_port == 2+++# ── Malformed inputs / Entrées malformées ────────────────────────────────────++def test_empty_and_garbage():+ assert parse_frame(ETH, b"") is None+ assert parse_frame(ETH, b"\x00" * 10) is None+ assert parse_frame(9999, eth(ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6, tcp(1, 2)))) is None+++def test_truncated_ip():+ p = parse_frame(ETH, eth(ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 6, tcp(1, 2))[:18]))+ assert p is None+++def test_dns_malformed():+ # EN: Malformed DNS never raises — empty list, not None.+ # FR: Un DNS malformé ne lève jamais — liste vide, pas None.+ assert parse_dns(b"\x00") == []+ assert parse_dns(b"\x00" * 12) == []+++def test_sni_garbage():+ assert parse_tls_sni(b"\x16\x03\x01") is None+ assert parse_tls_sni(b"GET / HTTP/1.1\r\n\r\n") is Nonediff --git a/backend/tests/test_security.py b/backend/tests/test_security.pyindex 4914460..1958476 100644--- a/backend/tests/test_security.py+++ b/backend/tests/test_security.py@@ -48,6 +48,8 @@ def test_valid_query_token_passes():@pytest.mark.parametrize("origin", ["http://localhost:5173","http://127.0.0.1:8000",+ "http://localhost:9999", # EN: dynamic backend port / FR: port dynamique du backend+ "http://[::1]:4242","null", # EN: file:// pages under Electron / FR: pages file:// sous Electron])def test_allowed_origins(origin):@@ -56,8 +58,11 @@ def test_allowed_origins(origin):@pytest.mark.parametrize("origin", ["http://evil.example.com",- "http://localhost:9999","https://attacker.invalid",+ "http://localhost.evil.com", # EN: subdomain trick — NOT loopback+ # FR: astuce sous-domaine — PAS loopback+ "http://127.0.0.1.evil.com",+ "null://evil.com",])def test_foreign_origins_rejected(origin):assert not origin_allowed(origin)diff --git a/docker-compose.yml b/docker-compose.ymlindex 6e75419..55b9f13 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -1,6 +1,6 @@# Snitch — Docker Compose# EN: Runs the full Snitch stack (backend + compiled frontend) with host networking.-# Host networking is required so Scapy can capture traffic on real host interfaces.+# Host networking is required so libpcap can capture real host interfaces.# Linux only — Docker Desktop (Mac/Windows) uses a VM and cannot capture host traffic.## SECURITY: SNITCH_BIND defaults to 127.0.0.1 — the API exposes your full@@ -11,7 +11,7 @@# token auth still applies on every endpoint.## FR: Lance toute la stack Snitch (backend + frontend compilé) en réseau hôte.-# Le réseau hôte est requis pour que Scapy capture le trafic des vraies interfaces.+# Le réseau hôte est requis pour que libpcap capture les vraies interfaces.# Linux uniquement — Docker Desktop (Mac/Windows) utilise une VM et ne peut pas# capturer le trafic de l'hôte.#@@ -37,17 +37,25 @@ services:# EN: Uncomment to pin a fixed token instead of an auto-generated one.# FR: Décommenter pour imposer un jeton fixe plutôt qu'un jeton généré.# - SNITCH_TOKEN=change-me- # EN: Opt-in ONLY — sends contacted IPs to ip-api.com over HTTP.- # Offline GeoLite2 (data/GeoLite2-City.mmdb) needs nothing external.- # FR: OPT-IN SEULEMENT — envoie les IP contactées à ip-api.com en HTTP.- # GeoLite2 hors ligne (data/GeoLite2-City.mmdb) ne requiert rien d'externe.- # - SNITCH_ONLINE_GEO=1+ # EN: NO online geolocation exists — the app never sends your IPs+ # anywhere. Drop an .mmdb in data/geo/ for fully-offline lookups.+ # FR: AUCUNE géolocalisation en ligne — l'app n'envoie jamais vos IP.+ # Déposez un .mmdb dans data/geo/ pour des recherches 100 % hors ligne.volumes:- # EN: data/GeoLite2-City.mmdb — optional, for offline geolocation- # data/snitch.db — created automatically at runtime- # data/api_token.txt — generated API token (0600)- # FR: data/GeoLite2-City.mmdb — optionnel, pour la géolocalisation hors ligne- # data/snitch.db — créé automatiquement au démarrage- # data/api_token.txt — jeton API généré (0600)+ # EN: data/geo/*.mmdb — optional, offline geolocation (DB-IP Lite or GeoLite2)+ # data/snitch.db — created automatically at runtime+ # data/api_token.txt — generated API token (0600)+ # FR: data/geo/*.mmdb — optionnel, géolocalisation hors ligne (DB-IP Lite ou GeoLite2)+ # data/snitch.db — créé automatiquement au démarrage+ # data/api_token.txt — jeton API généré (0600)- ./data:/app/data+ healthcheck:+ # EN: /capture/status requires the token — use TCP connect as the liveness+ # probe instead (unauthenticated requests get 401 by design).+ # FR: /capture/status exige le jeton — la sonde de vie est un simple+ # connect TCP (les requêtes non authentifiées reçoivent 401 par design).+ test: ["CMD-SHELL", "python -c \"import socket,os; socket.create_connection(('127.0.0.1', int(os.environ.get('SNITCH_PORT','8000'))), 3)\""]+ interval: 30s+ timeout: 5s+ retries: 3restart: unless-stoppeddiff --git a/docs/architecture.md b/docs/architecture.mdnew file mode 100644index 0000000..1a42f58--- /dev/null+++ b/docs/architecture.md@@ -0,0 +1,62 @@+# Snitch — Architecture / Architecture++## English++```+┌──────────────────────────────────────────────────────────────┐+│ Browser / Electron renderer (React + D3) │+│ WS ◄──── batch (250 ms) ──── REST (token: X-Snitch-Token) │+└───────────────────────────▲──────────────────────────────────┘+ │ 127.0.0.1 only+┌───────────────────────────┴──────────────────────────────────┐+│ FastAPI (api/main.py) │+│ _pkt_queue (bounded) → _drain_loop → _process_batch │+│ filters → LAN accounting → graph aggregates → detector │+│ enrichment: fire-and-forget, dedup per IP │+│ settings ←→ SQLite settings table │+├──────────────────────────────────────────────────────────────┤+│ capture/sniffer.py — PacketSniffer thread │+│ capture/pcap.py — ctypes → wpcap.dll / libpcap.so │+│ capture/parser.py — own parser: Ethernet, IPv4/IPv6, │+│ TCP/UDP, DNS answers, TLS SNI │+│ ConnectionTable — psutil snapshot every ~1.5 s │+│ (proto, local_port) → (pid, name) │+├──────────────────────────────────────────────────────────────┤+│ scanner/arp_scanner.py — system ARP table (passive) │+│ capture/media_monitor.py — mic/camera (win/linux; macOS: │+│ explicitly unsupported) │+│ detection/anomaly.py — NEW_HOST, SUSPICIOUS_PROCESS/PORT, │+│ PORT_SCAN, BEACON (regularity), │+│ VOLUME_SPIKE (window vs baseline), │+│ MEDIA_EXFIL, LAN device rules │+│ resolver/dns_geo.py — observed DNS/SNI map > reverse DNS │+│ > offline .mmdb (DB-IP/GeoLite2) │+│ storage/db.py — SQLite: traffic, alerts, settings │+└──────────────────────────────────────────────────────────────┘+```++**Key invariants**++- No per-packet coroutines or broadcasts — one queue, one drain task, one+ `batch` WS message per ~250 ms.+- `remote_port` is direction-aware everywhere; `dst_port` is never used for+ classification (it's a *local* port on inbound traffic).+- No third-party network call exists in the codebase.+- The detector holds a lock around all mutable state and every container is+ size-bounded.+- macOS: media monitoring reports `supported: false`; the UI hides the badge.++## Français++Le schéma ci-dessus s'applique tel quel — l'architecture est :++- **Capture** : `pcap.py` (ctypes vers libpcap/Npcap) + `parser.py` maison+ (Ethernet, IPv4/IPv6 avec extensions, TCP/UDP, réponses DNS, SNI TLS).+- **Pipeline** : file bornée → tâche de vidage unique (~4 Hz) → un message+ WS `batch` par tick. Aucune coroutine ni diffusion par paquet.+- **Classification** : toujours sur `remote_port` (direction-aware) — le bug+ `dst_port` sur le trafic entrant est corrigé.+- **Enrichissement** : DNS/SNI observés > DNS inverse > .mmdb local ; tâches+ dédupliquées, échecs jamais cachés définitivement.+- **Persistance** : agrégats trafic, alertes et réglages dans SQLite ;+ flush à l'arrêt ; rétention configurable.diff --git a/docs/privacy-score.md b/docs/privacy-score.mdnew file mode 100644index 0000000..3122ccf--- /dev/null+++ b/docs/privacy-score.md@@ -0,0 +1,40 @@+# Privacy Score — Methodology / Méthodologie++## English++The score (A–F, displayed top-right) is computed in+`frontend/src/scoring/privacy.js` from the live node/edge/alert state.+It is a **heuristic**, not a formal guarantee — document your threat model+before relying on the letter grade.++Inputs and weights:++| Signal | Effect |+|---|---|+| Tracker-category nodes (known ad/analytics domains via DNS/SNI) | −8 pts each |+| `critical`/`warning` alerts in the window | −10 / −4 pts each |+| Share of bytes going to tracker-flagged destinations | proportional penalty |+| Distinct remote hosts count | mild penalty above ~30 |+| HTTPS share (port 443 traffic) | small bonus |++Known limitations:++- Tracker matching relies on observed DNS/SNI names only — a tracker reached+ by bare IP won't match. This is intentional (no substring matching on+ reverse PTR, which produced false positives like `notfacebook.com`).+- The A–F letter is an ordinal summary, not a measurement. Treat it as a+ trend indicator over time, not an absolute score.++## Français++Le score (A–F, en haut à droite) est calculé dans+`frontend/src/scoring/privacy.js` à partir de l'état nœuds/arêtes/alertes.+C'est une **heuristique**, pas une garantie formelle.++Entrées et pondérations : voir le tableau ci-dessus (identique).++Limites connues : la correspondance trackers repose uniquement sur les noms+DNS/SNI observés — un tracker joint par IP brute n'est pas détecté. C'est+volontaire (pas de correspondance par sous-chaîne sur le PTR inverse, qui+produisait des faux positifs du type `notfacebook.com`). La lettre est un+résumé ordinal : à lire comme une tendance, pas une mesure absolue.diff --git a/electron/main.js b/electron/main.jsindex b8640a5..ba74ffd 100644--- a/electron/main.js+++ b/electron/main.js@@ -2,39 +2,55 @@* Snitch — Electron main process.** EN: Orchestrates the desktop app:- * 1. ensure Npcap is installed (Windows only, needed for raw capture)+ * 1. check for Npcap (Windows only, needed for raw capture) — NOT+ * bundled: the free Npcap license forbids external redistribution,+ * so we guide the user to npcap.com instead* 2. show a splash screen- * 3. generate a per-launch API token (crypto-random) and spawn the- * PyInstaller-compiled backend with SNITCH_TOKEN set+ * 3. pick a FREE loopback port, generate a per-launch API token+ * (crypto-random) and spawn the PyInstaller backend with+ * SNITCH_PORT + SNITCH_TOKEN in its environment* 4. wait for the API to answer, then open the main window- * 5. kill the backend cleanly on quit+ * 5. kill only OUR backend child on quit — never a port sweep*- * The token is the heart of the local-API trust model: it is created in- * the main process, passed to the backend via its environment, and given- * to the renderer ONLY through the ipcMain.handle('snitch:get-token')- * bridge — never logged, never embedded in the page.+ * Token + port reach the renderer ONLY via the preload bridge+ * (ipcMain.handle → window.snitch.getToken() / getPort()) — never in the+ * page, the URL, or logs.+ *+ * Why the free port: the old code bound a fixed :8000 and ran a netstat+ * sweep that matched ANY line containing ":8000" — including outbound+ * connections to a remote port 8000 — and taskkilled innocent processes.+ * A random port + killing only our own child removes that whole class.** FR: Orchestre l'application bureau :- * 1. vérifier que Npcap est installé (Windows uniquement, requis pour- * la capture brute)+ * 1. vérifier Npcap (Windows uniquement, requis pour la capture brute)+ * — NON embarqué : la licence gratuite de Npcap interdit la+ * redistribution externe, donc on guide vers npcap.com* 2. afficher un écran de démarrage- * 3. générer un jeton API par lancement (crypto-aléatoire) et lancer le- * backend compilé par PyInstaller avec SNITCH_TOKEN défini+ * 3. choisir un port loopback LIBRE, générer un jeton API par lancement+ * (crypto-aléatoire) et lancer le backend PyInstaller avec+ * SNITCH_PORT + SNITCH_TOKEN dans son environnement* 4. attendre que l'API réponde, puis ouvrir la fenêtre principale- * 5. tuer proprement le backend à la fermeture+ * 5. tuer uniquement NOTRE enfant backend à la fermeture — jamais de+ * balayage de port+ *+ * Jeton + port arrivent au renderer UNIQUEMENT via le pont preload+ * (ipcMain.handle → window.snitch.getToken() / getPort()) — jamais dans+ * la page, l'URL ou les logs.*- * Le jeton est le cœur du modèle de confiance de l'API locale : créé dans- * le processus principal, transmis au backend via son environnement, et- * donné au renderer UNIQUEMENT via le pont ipcMain.handle('snitch:get-token')- * — jamais loggué, jamais embarqué dans la page.+ * Pourquoi le port libre : l'ancien code fixait :8000 et lançait un+ * netstat qui retenait TOUTE ligne contenant « :8000 » — y compris les+ * connexions sortantes vers un port distant 8000 — et taskkill tuait des+ * processus innocents. Un port aléatoire + tuer seulement notre enfant+ * supprime toute cette classe de bug.*/const _electron = require('electron')-const { app, BrowserWindow, dialog, ipcMain } = _electron.default || _electron+const { app, BrowserWindow, dialog, ipcMain, shell } = _electron.default || _electronconst { spawn, execSync } = require('child_process')const crypto = require('crypto')const path = require('path')const http = require('http')+const net = require('net')const fs = require('fs')// ── Paths / Chemins ──────────────────────────────────────────────────────────@@ -47,28 +63,35 @@ const resourcesDir = isDev ? path.join(__dirname, '..') : process.resourcesPathconst isWindows = process.platform === 'win32'const backendName = isWindows ? 'snitch-backend.exe' : 'snitch-backend'+// EN: ONEDIR PyInstaller layout — the exe lives inside a snitch-backend/ dir.+// FR: Layout ONEDIR de PyInstaller — l'exe vit dans un dossier snitch-backend/.const backendExe = isDev- ? path.join(resourcesDir, 'dist', 'backend', backendName)- : path.join(resourcesDir, backendName)+ ? path.join(resourcesDir, 'dist', 'backend', 'snitch-backend', backendName)+ : path.join(resourcesDir, 'snitch-backend', backendName)-const npcapInstaller = path.join(resourcesDir, 'resources', 'npcap-installer.exe')const frontendDist = isDev? path.join(resourcesDir, 'frontend', 'dist'): path.join(resourcesDir, 'frontend_dist')-const BACKEND_URL = 'http://127.0.0.1:8000'-const BACKEND_PORT = 8000-const iconPath = isDev? path.join(__dirname, 'icon.png'): path.join(resourcesDir, 'icon.png')+// EN: Backend stdout/stderr go to a real log file — never stdio:'ignore',+// so crashes leave a trace the diagnostics export can pick up.+// FR: stdout/stderr du backend vont dans un vrai fichier de log — jamais+// stdio:'ignore', pour qu'un crash laisse une trace récupérable par+// l'export de diagnostic.+const logDir = path.join(app.getPath('userData'), 'logs')+const logFile = path.join(logDir, 'backend.log')+let mainWindow = nulllet splashWindow = nulllet backendProc = null+let backendPort = 0 // EN: chosen at launch / FR: choisi au lancementlet isQuitting = false-// ── API token / Jeton API ────────────────────────────────────────────────────+// ── API token + port / Jeton API + port ─────────────────────────────────────// EN: 48-hex-char secret generated once per app launch. Passed to the backend// via SNITCH_TOKEN and served to the renderer through ipcMain — the web// page can only obtain it via the preload bridge.@@ -77,85 +100,72 @@ let isQuitting = false// la page web ne peut l'obtenir que par le pont preload.const API_TOKEN = crypto.randomBytes(24).toString('hex')-// EN: IPC handler — the ONLY way the renderer learns the token.-// FR: Handler IPC — la SEULE façon pour le renderer d'apprendre le jeton.-ipcMain.handle('snitch:get-token', () => API_TOKEN)+// EN: IPC handlers — the ONLY way the renderer learns token/port/version.+// FR: Handlers IPC — la SEULE façon pour le renderer d'apprendre jeton/port/version.+ipcMain.handle('snitch:get-token', () => API_TOKEN)+ipcMain.handle('snitch:get-port', () => backendPort)+ipcMain.handle('snitch:get-version', () => app.getVersion())-// ── Port management / Gestion du port ────────────────────────────────────────/**- * EN: Free the backend port — kills any leftover process still listening on- * it (zombies from crashed sessions). Windows uses netstat/taskkill;- * POSIX uses lsof + kill.- * FR: Libérer le port du backend — tue tout processus résiduel qui écoute- * encore dessus (zombies de sessions plantées). Windows utilise- * netstat/taskkill ; POSIX utilise lsof + kill.+ * EN: Find a free loopback port by binding :0 and releasing — the backend+ * then binds the same number. A tiny race window remains (another+ * process could grab it between release and bind); waitForBackend's+ * timeout surfaces it instead of silently stealing someone else's port.+ * FR: Trouver un port loopback libre en liant :0 puis en relâchant — le+ * backend lie ensuite le même numéro. Une minuscule fenêtre de course+ * subsiste (un autre processus pourrait le prendre entre relâche et+ * bind) ; le timeout de waitForBackend la fait surface plutôt que de+ * voler silencieusement le port d'un autre.*/-function killPort(port) {- try {- if (isWindows) {- const out = execSync(`netstat -ano`, { encoding: 'utf8', stdio: 'pipe' })- const pids = new Set()- for (const line of out.split('\n')) {- // EN: Match lines whose local address ends with :PORT.- // FR: Garder les lignes dont l'adresse locale finit par :PORT.- if (!line.includes(`:${port} `) && !line.includes(`:${port}\t`)) continue- const m = line.trim().match(/(\d+)\s*$/)- if (m && m[1] !== '0') pids.add(m[1])- }- for (const pid of pids) {- try { execSync(`taskkill /PID ${pid} /F`, { stdio: 'pipe' }) } catch {}- }- if (pids.size > 0) {- // EN: Brief wait for the OS to release the port (~1s via ping).- // FR: Petite attente pour que l'OS libère le port (~1 s via ping).- try { execSync('ping -n 2 127.0.0.1', { stdio: 'pipe' }) } catch {}- }- } else {- // EN: POSIX — lsof reports PIDs listening on the port, kill them.- // FR: POSIX — lsof rapporte les PID qui écoutent sur le port, on les tue.- try {- const out = execSync(`lsof -ti tcp:${port} -sTCP:LISTEN`, { encoding: 'utf8', stdio: 'pipe' })- for (const pid of out.split('\n').map(s => s.trim()).filter(Boolean)) {- try { process.kill(Number(pid), 'SIGKILL') } catch {}- }- } catch {}- }- } catch {}+function findFreePort() {+ return new Promise((resolve, reject) => {+ const srv = net.createServer()+ srv.listen(0, '127.0.0.1', () => {+ const { port } = srv.address()+ srv.close(() => resolve(port))+ })+ srv.on('error', reject)+ })}// ── Npcap ────────────────────────────────────────────────────────────────────/**- * EN: Npcap is the Windows packet-capture driver Scapy needs. We detect it- * through its registry keys.- * FR: Npcap est le pilote de capture Windows dont Scapy a besoin. On le détecte- * via ses clés de registre.+ * EN: Npcap is the Windows packet-capture driver libpcap needs. Detected via+ * its DLL presence in System32\Npcap — NOT its registry keys, and NOT a+ * bundled installer (which the free license forbids redistributing).+ * FR: Npcap est le pilote de capture Windows requis par libpcap. Détecté via+ * la présence de sa DLL dans System32\Npcap — PAS via ses clés de+ * registre, et PAS via un installateur embarqué (que la licence gratuite+ * interdit de redistribuer).*/function isNpcapInstalled() {- const keys = [- 'HKLM\\SOFTWARE\\Npcap',- 'HKLM\\SOFTWARE\\WOW6432Node\\Npcap',- ]- for (const key of keys) {- try {- const out = execSync(`reg query "${key}"`, { stdio: 'pipe', encoding: 'utf8' })- if (out.includes('Npcap') || out.includes(key)) return true- } catch {}- }- return false+ try {+ const sysRoot = process.env.SystemRoot || 'C:\\Windows'+ return fs.existsSync(path.join(sysRoot, 'System32', 'Npcap', 'wpcap.dll'))+ } catch { return false }}/**- * EN: Run the bundled Npcap installer. Silent mode requires a paid OEM- * license, so we launch the standard GUI installer.- * FR: Lancer l'installateur Npcap fourni. Le mode silencieux exige une licence- * OEM payante, donc on lance l'installateur GUI standard.+ * EN: Offer to open npcap.com in the user's browser. There is intentionally+ * NO silent install — the free installer has no silent mode, and bundling+ * it is a license violation.+ * FR: Proposer d'ouvrir npcap.com dans le navigateur. AUCUNE installation+ * silencieuse — l'installateur gratuit n'a pas de mode silencieux, et+ * l'embarquer violerait la licence.*/-function installNpcap() {- if (!fs.existsSync(npcapInstaller)) return false- try {- execSync(`"${npcapInstaller}"`, { stdio: 'inherit' })- return true- } catch { return false }+async function offerNpcapDownload() {+ const choice = await dialog.showMessageBox({+ type: 'info', title: 'Snitch — Npcap required / Npcap requis',+ message: 'Snitch needs Npcap to capture network traffic on Windows.\n' ++ 'Snitch a besoin de Npcap pour capturer le trafic réseau sous Windows.\n\n' ++ 'Download it free from npcap.com, install it, then restart Snitch.\n' ++ 'Téléchargez-le gratuitement sur npcap.com, installez-le, puis relancez Snitch.',+ buttons: ['Open npcap.com / Ouvrir npcap.com', 'Quit / Quitter'], defaultId: 0,+ })+ if (choice.response === 0) {+ await shell.openExternal('https://npcap.com')+ }+ app.quit()}// ── Windows / Fenêtres ───────────────────────────────────────────────────────@@ -166,23 +176,24 @@ function createSplash() {width: 380, height: 310, frame: false,resizable: false, alwaysOnTop: true, center: true,transparent: true, icon: iconPath,- webPreferences: { nodeIntegration: false },+ webPreferences: { nodeIntegration: false, sandbox: true },})splashWindow.loadFile(path.join(__dirname, 'splash.html'))}function createMain() {/** EN: Main window — loads the Vite dev server in dev, or the compiled- * frontend otherwise.+ * frontend otherwise. Sandbox on: the preload only needs ipcRenderer.* FR: Fenêtre principale — charge le serveur de dev Vite en dev, ou le- * frontend compilé sinon. */+ * frontend compilé sinon. Sandbox activé : le preload n'a besoin que+ * d'ipcRenderer. */mainWindow = new BrowserWindow({width: 1400, height: 860, minWidth: 900, minHeight: 600,show: false, title: 'Snitch', backgroundColor: '#000000',icon: iconPath,webPreferences: {preload: path.join(__dirname, 'preload.js'),- contextIsolation: true, nodeIntegration: false,+ contextIsolation: true, nodeIntegration: false, sandbox: true,},})@@ -213,7 +224,7 @@ function waitForBackend(maxAttempts = 40) {let n = 0function poll() {const req = http.request(- BACKEND_URL + '/graph',+ `http://127.0.0.1:${backendPort}/graph`,{ headers: { 'X-Snitch-Token': API_TOKEN } },res => { res.resume(); res.statusCode === 200 ? resolve() : retry() })@@ -229,12 +240,16 @@ function waitForBackend(maxAttempts = 40) {}/**- * EN: Kill the backend child process and free its port.- * `taskkill /F /T` is more reliable than .kill() on Windows and takes- * the whole process tree; POSIX gets SIGKILL.- * FR: Tuer le processus enfant du backend et libérer son port.- * `taskkill /F /T` est plus fiable que .kill() sous Windows et prend tout- * l'arbre de processus ; POSIX reçoit SIGKILL.+ * EN: Kill ONLY our own backend child — `taskkill /F /T` takes the whole+ * process tree on Windows, POSIX kills the detached process group. No+ * netstat port sweep: with a random port there is no zombie-port problem+ * to clean up, and sweeping by port number was what killed unrelated+ * processes.+ * FR: Tuer UNIQUEMENT notre enfant backend — `taskkill /F /T` prend tout+ * l'arbre sous Windows, POSIX tue le groupe détaché. Pas de balayage+ * netstat : avec un port aléatoire il n'y a plus de zombie à nettoyer, et+ * le balayage par numéro de port était ce qui tuait des processus+ * innocents.*/function killBackend() {if (backendProc) {@@ -249,32 +264,38 @@ function killBackend() {}backendProc = null}- killPort(BACKEND_PORT)}function launchBackend() {- /** EN: Spawn the compiled backend with SNITCH_TOKEN in its environment;- * show a dialog and quit on failure.- * FR: Lancer le backend compilé avec SNITCH_TOKEN dans son environnement ;- * afficher une boîte de dialogue et quitter en cas d'échec. */+ /** EN: Spawn the compiled backend with SNITCH_TOKEN + SNITCH_PORT in its+ * environment; windowsHide keeps a console window from flashing;+ * stdout/stderr stream to the log file for diagnostics.+ * FR: Lancer le backend compilé avec SNITCH_TOKEN + SNITCH_PORT dans son+ * environnement ; windowsHide évite l'éclair d'une fenêtre console ;+ * stdout/stderr vont dans le fichier de log pour le diagnostic. */if (!fs.existsSync(backendExe)) {dialog.showErrorBox('Snitch', `Backend not found / Backend introuvable :\n${backendExe}`)app.quit(); return}- // EN: Free the port first — handles zombies from crashed sessions.- // FR: Libérer le port d'abord — gère les zombies de sessions plantées.- killPort(BACKEND_PORT)+ fs.mkdirSync(logDir, { recursive: true })+ const logFd = fs.openSync(logFile, 'a')const env = Object.assign({}, process.env)- // EN: Inject the API token — the backend will require it on every request.- // FR: Injecter le jeton API — le backend l'exigera sur chaque requête.env.SNITCH_TOKEN = API_TOKEN+ env.SNITCH_PORT = String(backendPort)+ env.SNITCH_USER_DATA = '1' // EN: per-OS user data dir, not the bundle+ // FR: dossier de données utilisateur, pas le bundle// EN: Prevent the child from being interpreted as an Electron/Node process.// FR: Empêcher le processus enfant d'être interprété comme un processus Electron/Node.delete env.ELECTRON_RUN_AS_NODE- backendProc = spawn(backendExe, [], { detached: !isWindows, stdio: 'ignore', env })+ backendProc = spawn(backendExe, [], {+ detached: !isWindows,+ windowsHide: true,+ stdio: ['ignore', logFd, logFd],+ env,+ })backendProc.on('error', err => {if (isQuitting) returndialog.showErrorBox('Snitch', `Failed to start backend / Échec du démarrage du backend :\n${err.message}`)@@ -291,26 +312,17 @@ function launchBackend() {// ── App lifecycle / Cycle de vie de l'application ────────────────────────────app.whenReady().then(async () => {- // EN: On Windows, Npcap is a hard requirement — offer to install it.- // FR: Sous Windows, Npcap est obligatoire — proposer son installation.+ // EN: On Windows, Npcap is a hard requirement — guide the user to npcap.com+ // (it is deliberately NOT bundled; see licensing notes).+ // FR: Sous Windows, Npcap est obligatoire — guider l'utilisateur vers+ // npcap.com (volontairement NON embarqué ; voir les notes de licence).if (isWindows && !isNpcapInstalled()) {- if (fs.existsSync(npcapInstaller)) {- const choice = dialog.showMessageBoxSync({- type: 'question', title: 'Snitch — Npcap required / Npcap requis',- message: 'Snitch needs Npcap to capture network traffic. Install it now?\n' +- 'Snitch a besoin de Npcap pour capturer le trafic réseau. Installer maintenant ?',- buttons: ['Install / Installer', 'Quit / Quitter'], defaultId: 0,- })- if (choice === 1) { app.quit(); return }- if (!installNpcap()) {- dialog.showErrorBox('Snitch', 'Npcap installation failed. Install it manually from https://npcap.com\n' +- "L'installation de Npcap a échoué. Installez-le depuis https://npcap.com")- app.quit(); return- }- }+ await offerNpcapDownload()+ return}createSplash()+ backendPort = await findFreePort()launchBackend()try {diff --git a/electron/package.json b/electron/package.jsonindex a6f6551..7326760 100644--- a/electron/package.json+++ b/electron/package.json@@ -10,7 +10,7 @@"build:dir": "electron-builder --win --x64 --dir"},"devDependencies": {- "electron": "^28.3.3",+ "electron": "^33.4.0","electron-builder": "^25.1.8"},"build": {@@ -31,16 +31,12 @@"to": "icon.png"},{- "from": "../dist/backend/snitch-backend.exe",- "to": "snitch-backend.exe"+ "from": "../dist/backend/snitch-backend",+ "to": "snitch-backend"},{"from": "../frontend/dist","to": "frontend_dist"- },- {- "from": "../resources/npcap-installer.exe",- "to": "npcap-installer.exe"}],"win": {diff --git a/electron/preload.js b/electron/preload.jsindex fe54da5..bc50b44 100644--- a/electron/preload.js+++ b/electron/preload.js@@ -4,20 +4,30 @@* EN: Minimal bridge between the sandboxed renderer and the main process.* `contextIsolation` is enabled, so this is the ONLY surface the web* page can see — keep it that way.- * `getToken` lets the renderer authenticate to the backend API without- * the token ever appearing in the page, the DOM, or logs.+ * `getToken` / `getPort` let the renderer reach the backend API without+ * the token ever appearing in the page, the DOM, or logs. `getVersion`+ * resolves via app.getVersion() in the main process — the old+ * npm_package_version read returned "1.0.0" forever in production.* FR: Pont minimal entre le renderer en sandbox et le processus principal.* `contextIsolation` est activé : c'est la SEULE surface visible par la* page web — gardons-la ainsi.- * `getToken` permet au renderer de s'authentifier auprès de l'API backend+ * `getToken` / `getPort` permettent au renderer de joindre l'API backend* sans que le jeton apparaisse jamais dans la page, le DOM ou les logs.+ * `getVersion` se résout via app.getVersion() dans le processus+ * principal — l'ancienne lecture de npm_package_version renvoyait « 1.0.0 »+ * pour toujours en production.*/const { contextBridge, ipcRenderer } = require('electron')contextBridge.exposeInMainWorld('snitch', {- version: process.env.npm_package_version || '1.0.0',// EN: Async — resolves to the per-launch API token held by the main process.// FR: Asynchrone — résout vers le jeton API par lancement détenu par le processus principal.- getToken: () => ipcRenderer.invoke('snitch:get-token'),+ getToken: () => ipcRenderer.invoke('snitch:get-token'),+ // EN: Async — resolves to the free port the backend was spawned on.+ // FR: Asynchrone — résout vers le port libre sur lequel le backend a été lancé.+ getPort: () => ipcRenderer.invoke('snitch:get-port'),+ // EN: Async — real app version (package.json via app.getVersion()).+ // FR: Asynchrone — vraie version de l'app (package.json via app.getVersion()).+ getVersion: () => ipcRenderer.invoke('snitch:get-version'),})diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 3d3e053..9f2ff80 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -22,11 +22,13 @@ import Timeline from './components/Timeline'import Dropdown from './components/Dropdown'import { useWebSocket } from './hooks/useWebSocket'import { computePrivacyScore } from './scoring/privacy'-import { WS_URL } from './api'+// EN: WS URL is resolved dynamically (port + ws/wss) via api.js wsBase().+// FR: L'URL WS est résolue dynamiquement (port + ws/wss) via wsBase() d'api.js.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(WS_URL)+ 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()+ // FR: null → résout port/schéma dynamiques via wsBase()const [selected, setSelected] = useState(null)const [view, setView] = useState('graph')const [showAlerts, setShowAlerts] = useState(false)diff --git a/frontend/src/api.js b/frontend/src/api.jsindex 460e788..d172106 100644--- a/frontend/src/api.js+++ b/frontend/src/api.js@@ -26,10 +26,45 @@*/const isElectron = window.location.protocol === 'file:'+// EN: Backend port — Electron picks a FREE port at launch and exposes it via+// the preload bridge (window.snitch.getPort()). Browsers/Docker use the+// page origin (same-origin deployment) or the vite proxy. Falls back to+// 8000 only for compatibility.+// FR: Port du backend — Electron choisit un port LIBRE au lancement et+// l'expose via le pont preload (window.snitch.getPort()). Navigateur/+// Docker utilisent l'origine de la page (déploiement same-origin) ou le+// proxy vite. Repli 8000 uniquement pour compatibilité.+let _portPromise = null+export function getApiPort() {+ if (_portPromise) return _portPromise+ _portPromise = (async () => {+ if (window.snitch?.getPort) return await window.snitch.getPort()+ if (isElectron) return 8000+ return window.location.port || (window.location.protocol === 'https:' ? 443 : 80)+ })()+ return _portPromise+}++// EN: ws/wss follows the page scheme — a deployment behind an HTTPS proxy+// must not attempt a plaintext ws://.+// FR: ws/wss suit le schéma de la page — un déploiement derrière un proxy+// HTTPS ne doit pas tenter un ws:// en clair.+const wsScheme = window.location.protocol === 'https:' ? 'wss' : 'ws'++export async function apiBase() {+ if (isElectron) return `http://127.0.0.1:${await getApiPort()}`+ return ''+}++export async function wsBase() {+ if (isElectron) return `${wsScheme}://127.0.0.1:${await getApiPort()}/ws`+ return `${wsScheme}://${window.location.host}/ws`+}+export const API_BASE = isElectron ? 'http://127.0.0.1:8000' : ''export const WS_URL = isElectron- ? 'ws://127.0.0.1:8000/ws'- : `ws://${window.location.host}/ws`+ ? `${wsScheme}://127.0.0.1:8000/ws`+ : `${wsScheme}://${window.location.host}/ws`let _tokenPromise = null@@ -81,5 +116,8 @@ export async function authHeaders(extra = {}) {*/export async function wsUrlWithToken(base) {const token = await getToken()- return token ? `${base}?token=${encodeURIComponent(token)}` : base+ // EN: `base` may be a function (async wsBase) or a legacy static string.+ // FR: `base` peut être une fonction (wsBase async) ou une chaîne statique.+ const url = typeof base === 'function' ? await base() : base+ return token ? `${url}?token=${encodeURIComponent(token)}` : url}diff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsxindex fbef712..38c9604 100644--- a/frontend/src/components/AlertPanel.jsx+++ b/frontend/src/components/AlertPanel.jsx@@ -16,9 +16,9 @@*/import { useState, useEffect, useRef } from 'react'import {- Bell, Info, AlertTriangle, AlertCircle,- Globe, WifiOff, Wifi,- Activity, Unlock, TrendingUp,+ Bell, Info, AlertTriangle, AlertCircle, X,+ Globe, WifiOff, Wifi, ScanLine,+ Activity, Unlock, TrendingUp, Camera,} from 'lucide-react'import { useT } from '../i18n'@@ -38,7 +38,8 @@ const TYPE_ICONS = {VOLUME_SPIKE: TrendingUp,NEW_LAN_DEVICE: Wifi,DEVICE_OFFLINE: WifiOff,- MEDIA_EXFIL: AlertCircle,+ MEDIA_EXFIL: Camera,+ PORT_SCAN: ScanLine,}export function AlertBell({ unread, onClick }) {@@ -92,8 +93,8 @@ export function AlertPanel({ alerts, onClose }) {{criticalCount > 0 && <Badge count={criticalCount} color="#ef4444" />}{warningCount > 0 && <Badge count={warningCount} color="#f59e0b" />}{infoCount > 0 && <Badge count={infoCount} color="#38bdf8" />}- <button onClick={onClose} style={{ background: 'none', border: 'none', color: '#64748b', cursor: 'pointer' }}>- <AlertCircle size={16} />+ <button onClick={onClose} aria-label="Close alerts / Fermer les alertes" style={{ background: 'none', border: 'none', color: '#64748b', cursor: 'pointer' }}>+ <X size={16} /></button></div></div>diff --git a/frontend/src/hooks/useWebSocket.js b/frontend/src/hooks/useWebSocket.jsindex 9e572f6..d16fe85 100644--- a/frontend/src/hooks/useWebSocket.js+++ b/frontend/src/hooks/useWebSocket.js@@ -21,7 +21,7 @@* La connexion s'ouvre avec le jeton API via wsUrlWithToken().*/import { useEffect, useRef, useState } from 'react'-import { API_BASE, authHeaders, wsUrlWithToken } from '../api'+import { apiBase, authHeaders, wsUrlWithToken, wsBase } from '../api'export function useWebSocket(url) {const ws = useRef(null)@@ -69,7 +69,7 @@ export function useWebSocket(url) {async function connect() {// EN: Resolve the token BEFORE opening the socket.// FR: Résoudre le jeton AVANT d'ouvrir le socket.- const wsUrl = await wsUrlWithToken(url)+ const wsUrl = await wsUrlWithToken(url ?? wsBase)if (stopped) returnws.current = new WebSocket(wsUrl)@@ -112,18 +112,69 @@ export function useWebSocket(url) {if (msg.alerts?.length) setAlerts(msg.alerts.reverse())}- // EN: Incremental graph update (one per packet).- // FR: Mise à jour incrémentale du graphe (une par paquet).+ // EN: Incremental graph update (one per packet — legacy path).+ // FR: Mise à jour incrémentale du graphe (une par paquet — chemin hérité).if (msg.type === 'update') {setNodes(prev => ({ ...prev, [msg.node.id]: msg.node }))setEdges(prev => ({ ...prev, [msg.edge.id]: msg.edge }))setPackets(prev => [msg.packet, ...prev].slice(0, 100))- // EN: Accumulate bytes into the current second bucket.- // FR: Accumuler les octets dans le seau de la seconde courante.const sec = Math.floor(Date.now() / 1000) * 1000bwRef.current[sec] = (bwRef.current[sec] || 0) + (msg.packet?.size || 0)}+ // EN: Batched update — the backend coalesces a 250 ms window into one+ // message. All arrays land in a single React state pass each, so+ // a burst of 200 packets = 4 renders/s, not 200.+ // FR: Mise à jour par lot — le backend coalesce une fenêtre de 250 ms+ // en un message. Chaque tableau déclenche un seul passage React,+ // donc une rafale de 200 paquets = 4 rendus/s, pas 200.+ if (msg.type === 'batch') {+ if (msg.nodes?.length) {+ const incoming = msg.nodes+ setNodes(prev => {+ const next = { ...prev }+ for (const n of incoming) next[n.id] = n+ return next+ })+ }+ if (msg.edges?.length) {+ const incoming = msg.edges+ setEdges(prev => {+ const next = { ...prev }+ for (const e of incoming) next[e.id] = e+ return next+ })+ }+ if (msg.devices?.length) {+ const incoming = msg.devices+ setLanDevices(prev => {+ const next = { ...prev }+ for (const d of incoming) next[d.id] = d+ return next+ })+ }+ if (msg.packets?.length) {+ const incoming = msg.packets+ setPackets(prev => [...incoming.slice(-50).reverse(), ...prev].slice(0, 100))+ const sec = Math.floor(Date.now() / 1000) * 1000+ const bytes = incoming.reduce((sum, p) => sum + (p.size || 0), 0)+ bwRef.current[sec] = (bwRef.current[sec] || 0) + bytes+ }+ if (msg.alerts?.length) {+ const incoming = msg.alerts+ setAlerts(prev => [...incoming.slice().reverse(), ...prev].slice(0, 200))+ setUnread(prev => prev + incoming.length)+ }+ }++ // EN: Enriched node patch (hostname/geo resolved after the fact).+ // FR: Patch de nœud enrichi (nom d'hôte/géo résolus après coup).+ if (msg.type === 'node_update') {+ setNodes(prev => prev[msg.node.id]+ ? { ...prev, [msg.node.id]: msg.node }+ : prev)+ }+// EN: LAN device appeared / changed / went offline.// FR: Appareil LAN apparu / modifié / passé hors ligne.if (msg.type === 'device_update') {@@ -161,9 +212,16 @@ export function useWebSocket(url) {})}- // EN: Mic/camera usage changed. / FR: L'usage micro/caméra a changé.+ // EN: Mic/camera usage changed. `supported=false` (macOS) lets the+ // badge hide entirely instead of lying with empty lists.+ // FR: L'usage micro/caméra a changé. `supported=false` (macOS) permet+ // au badge de se masquer plutôt que de mentir avec des listes vides.if (msg.type === 'media') {- setMedia({ mic: msg.mic || [], camera: msg.camera || [] })+ setMedia({+ mic: msg.mic || [],+ camera: msg.camera || [],+ supported: msg.supported !== false,+ })}// EN: Full graph reset (e.g. after the port filter changed).@@ -201,7 +259,7 @@ export function useWebSocket(url) {async function toggleCapture() {const endpoint = capturing ? '/capture/stop' : '/capture/start'- const res = await fetch(`${API_BASE}${endpoint}`, {+ const res = await fetch(`${await apiBase()}${endpoint}`, {method: 'POST',headers: await authHeaders(),})@@ -210,7 +268,7 @@ export function useWebSocket(url) {}async function updatePortFilter(ports) {- const res = await fetch(`${API_BASE}/capture/ports`, {+ const res = await fetch(`${await apiBase()}/capture/ports`, {method: 'POST',headers: await authHeaders({ 'Content-Type': 'application/json' }),body: JSON.stringify({ ports }),@@ -220,7 +278,7 @@ export function useWebSocket(url) {}async function updateProcessFilter(excluded) {- const res = await fetch(`${API_BASE}/capture/processes`, {+ const res = await fetch(`${await apiBase()}/capture/processes`, {method: 'POST',headers: await authHeaders({ 'Content-Type': 'application/json' }),body: JSON.stringify({ excluded }),@@ -230,7 +288,7 @@ export function useWebSocket(url) {}async function updateIpWhitelist(ips) {- const res = await fetch(`${API_BASE}/capture/whitelist`, {+ const res = await fetch(`${await apiBase()}/capture/whitelist`, {method: 'POST',headers: await authHeaders({ 'Content-Type': 'application/json' }),body: JSON.stringify({ ips }),diff --git a/frontend/src/i18n.jsx b/frontend/src/i18n.jsxindex 09172f6..7cab2f3 100644--- a/frontend/src/i18n.jsx+++ b/frontend/src/i18n.jsx@@ -82,6 +82,7 @@ const en = {alert_NEW_LAN_DEVICE: 'New device',alert_DEVICE_OFFLINE: 'Device offline',alert_MEDIA_EXFIL: 'Media exfiltration',+ alert_PORT_SCAN: 'Port scan',// 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@@ -90,10 +91,11 @@ const en = {alertmsg_SUSPICIOUS_PROCESS: d => `Suspicious process: ${d.process} → ${d.host || d.ip}`,alertmsg_SUSPICIOUS_PORT: d => `Suspicious port ${d.port} (${d.reason}) → ${d.host || d.ip}`,alertmsg_BEACON: d => `Beacon-like regularity: ~${d.interval_s}s interval to ${d.host || d.ip}`,- alertmsg_VOLUME_SPIKE: d => `Traffic spike to ${d.host || d.ip} (${d.kb} KB in one packet)`,+ alertmsg_VOLUME_SPIKE: d => `Data spike to ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} KB in ${d.window_s}s`,alertmsg_MEDIA_EXFIL: d => `Suspected ${d.device} exfiltration: ${d.process} → ${d.host || d.ip}`,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`,time_just_now: 'just now',time_seconds: n => `${n}s ago`,time_minutes: n => `${n}min ago`,@@ -237,11 +239,13 @@ const fr = {alert_NEW_LAN_DEVICE: 'Nouvel appareil',alert_DEVICE_OFFLINE: 'Appareil hors ligne',alert_MEDIA_EXFIL: 'Exfiltration média',+ alert_PORT_SCAN: 'Scan de ports',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}`,alertmsg_BEACON: d => `Régularité type beacon : intervalle ~${d.interval_s}s vers ${d.host || d.ip}`,- alertmsg_VOLUME_SPIKE: d => `Pic de trafic vers ${d.host || d.ip} (${d.kb} Ko en un paquet)`,+ alertmsg_VOLUME_SPIKE: d => `Pic de données vers ${d.host || d.ip} : ${Math.round((d.bytes || 0) / 1024)} Ko en ${d.window_s}s`,+ alertmsg_PORT_SCAN: d => `Scan de ports : ${d.source || d.ip} a touché ${d.ports}+ ports en ${d.window_s}s`,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}`,@@ -330,7 +334,14 @@ const I18nContext = createContext(null)* chaînes renvoyées telles quelles, les clés manquantes retombent sur la clé.*/export function I18nProvider({ children }) {- const [lang, setLang] = useState('en')+ // EN: Persisted language — survives restarts (localStorage, not just RAM).+ // FR: Langue persistée — survit aux redémarrages (localStorage, pas juste la RAM).+ const [lang, setLangState] = useState(+ () => localStorage.getItem('snitch_lang') || 'en')+ const setLang = (l) => {+ localStorage.setItem('snitch_lang', l)+ setLangState(l)+ }const dict = lang === 'fr' ? fr : enfunction t(key, ...args) {diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..b73b4f1--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,51 @@+# Snitch — Python packaging.+#+# EN: `pipx install .` (or pip) gives you a `snitch` CLI that serves the web UI+# on 127.0.0.1 and opens the browser with the API token. Capture rights:+# admin on Windows, `sudo setcap cap_net_raw,cap_net_admin` (or root) on+# Linux, /dev/bpf* access on macOS.+# FR: `pipx install .` (ou pip) fournit une CLI `snitch` qui sert l'UI web sur+# 127.0.0.1 et ouvre le navigateur avec le jeton API. Droits de capture :+# admin sous Windows, `sudo setcap cap_net_raw,cap_net_admin` (ou root)+# sous Linux, accès /dev/bpf* sous macOS.++[build-system]+requires = ["setuptools>=68"]+build-backend = "setuptools.build_meta"++[project]+name = "snitch"+version = "1.1.0"+description = "Real-time network traffic visualizer — EN/FR, privacy-first, local-only"+readme = "README.md"+license = { text = "AGPL-3.0-or-later" }+requires-python = ">=3.11"+dependencies = [+ "fastapi==0.115.0",+ "uvicorn[standard]==0.30.6",+ "websockets==13.0.1",+ "maxminddb==2.6.3",+ "psutil==6.1.0",+ "python-dotenv==1.0.1",+ "aiofiles==24.1.0",+]++[project.scripts]+snitch = "cli:main"++[tool.setuptools]+package-dir = { "" = "backend" }+packages = [+ "api", "capture", "classifier", "detection", "resolver", "scanner",+ "storage",+]+py-modules = ["cli", "paths", "logging_config", "run_backend"]++# EN: The built frontend ships inside the wheel — `npm run build` output is+# expected at frontend/dist and gets copied to backend/frontend_dist by+# the release pipeline before building the wheel.+# FR: Le frontend compilé est embarqué dans la wheel — la sortie de+# `npm run build` doit être dans frontend/dist et est copiée vers+# backend/frontend_dist par la chaîne de release avant le build.+[tool.setuptools.package-data]+"*" = ["frontend_dist/**/*"]