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: initial Snitch release — bilingual EN/FR network traffic visualizer
MoneyLisa66e2a72608cf
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 0000000..c02fdf3--- /dev/null+++ b/.dockerignore@@ -0,0 +1,17 @@+# EN: Files and folders excluded from the Docker build context.+# FR: Fichiers et dossiers exclus du contexte de build Docker.++.git+.devin+.claude+backend/.venv+backend/__pycache__+backend/**/__pycache__+frontend/node_modules+frontend/dist+electron+dist+docs+resources+data+*.logdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..fdc6cd5--- /dev/null+++ b/.gitignore@@ -0,0 +1,28 @@+# EN: Python artifacts / FR: Artefacts Python+__pycache__/+*.py[cod]+.venv/+*.spec.bak++# EN: Node artifacts / FR: Artefacts Node+node_modules/+frontend/dist/++# EN: Build output / FR: Sortie de build+dist/+build/++# EN: Runtime data (SQLite DB, GeoLite2) / FR: Données d'exécution (SQLite, GeoLite2)+data/+*.db+*.db-wal+*.db-shm+*.mmdb++# EN: Electron generated files / FR: Fichiers générés Electron+electron/icon.png++# EN: OS / editor noise / FR: Fichiers système et éditeur+.DS_Store+*.log+.envdiff --git a/Dockerfile b/Dockerfilenew file mode 100644index 0000000..f531ffc--- /dev/null+++ b/Dockerfile@@ -0,0 +1,36 @@+# ── Stage 1: Build the React frontend ─────────────────────────────────────────+# EN: Compile the Vite/React app into static files served later by FastAPI.+# FR: Compiler l'application Vite/React en fichiers statiques servis par FastAPI.+FROM node:20-alpine AS frontend-builder+WORKDIR /build+COPY frontend/package*.json ./+RUN npm ci --prefer-offline+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).+FROM python:3.11-slim-bookworm+WORKDIR /app++RUN apt-get update \+ && apt-get install -y --no-install-recommends libpcap-dev \+ && rm -rf /var/lib/apt/lists/*++# EN: Install Python dependencies first to leverage Docker layer caching.+# FR: Installer les dépendances Python d'abord pour profiter du cache Docker.+COPY backend/requirements.txt ./+RUN pip install --no-cache-dir -r requirements.txt++# EN: Backend source code.+# FR: Code source du backend.+COPY backend/ ./backend/++# EN: Compiled React app — served as static files by FastAPI.+# FR: Application React compilée — servie en fichiers statiques par FastAPI.+COPY --from=frontend-builder /build/dist ./frontend_dist/++EXPOSE 8000+WORKDIR /app/backend+CMD ["python", "run_backend.py"]diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..966cbab--- /dev/null+++ b/LICENSE@@ -0,0 +1,34 @@+ GNU AFFERO GENERAL PUBLIC LICENSE+ Version 3, 19 November 2007++ Copyright (C) 2026 Snitch contributors++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU Affero General Public License as published+ by the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU Affero General Public License for more details.++ You should have received a copy of the GNU Affero General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++--------------------------------------------------------------------------------++Ce programme est un logiciel libre : vous pouvez le redistribuer et/ou le+modifier selon les termes de la licence GNU Affero General Public License+telle que publiée par la Free Software Foundation, version 3 ou toute+version ultérieure.++Ce programme est distribué dans l'espoir qu'il sera utile, mais SANS AUCUNE+GARANTIE ; sans même la garantie implicite de QUALITÉ MARCHANDE ou+d'ADÉQUATION À UN USAGE PARTICULIER. Voir la licence GNU Affero General+Public License pour plus de détails.++--------------------------------------------------------------------------------++ Full license text / Texte complet de la licence :+ https://www.gnu.org/licenses/agpl-3.0.txtdiff --git a/README.md b/README.mdnew file mode 100644index 0000000..c48ce99--- /dev/null+++ b/README.md@@ -0,0 +1,226 @@+<div align="center">++# Snitch++**Know who's talking. / Sache qui parle.**++[English](#english) | [Français](#français)++[](LICENSE)+[]()+[-blue.svg)]()+[]()++</div>++---++## English++**Snitch** is a real-time network traffic visualizer.+See every connection your computer makes — who it talks to, where they are, and which app is responsible.++The entire interface is available in **English and French**: use the `EN / FR` toggle in the top-right toolbar.++### Features++| Feature | Description |+|---|---|+| Force Graph | Live node graph — your machine at the center, every connection as a node |+| World Map | Geolocated IPs with animated arcs on an interactive globe |+| 60-min Timeline | Sliding history stored locally in SQLite |+| 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 |+| 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 |++### Stack++| Layer | Technology |+|---|---|+| Packet capture | Python — Scapy — Npcap (Windows) / libpcap (Linux) |+| Backend API | FastAPI — WebSockets — SQLite |+| Frontend | React 18 — Vite — D3.js v7 — TopoJSON |+| Desktop wrapper | Electron 28 |+| Geolocation | MaxMind GeoLite2 (optional, falls back to ip-api.com) |++### Docker (Linux)++The Docker deployment is for Linux users who want to run Snitch without installing anything beyond Docker.+Packet capture works via `network_mode: host` — the container sees real host traffic.++> **Note:** Docker Desktop on Mac/Windows runs inside a VM and cannot capture traffic from the host. Use the Electron app on those platforms.++```bash+# Clone and enter the repo / Cloner puis entrer dans le dépôt+git clone <your-repo-url> snitch+cd snitch++# Optional: place your MaxMind GeoLite2-City.mmdb in data/ for offline geolocation+# Optionnel : placez votre GeoLite2-City.mmdb dans data/ pour la géolocalisation hors ligne+mkdir -p data++# Build and run (requires Docker + root/sudo for raw socket capture)+# Construire et lancer (Docker + root/sudo requis pour la capture)+sudo docker compose up --build+```++Open **http://localhost:8000** in your browser.++To run in the background: `sudo docker compose up -d --build`++Docker limitations:+- Process attribution is limited to container processes (host PIDs are not shared by default)+- LAN scanner may be unavailable on some network configurations++### Development++Requirements:+- Python 3.11++- Node.js 18++- [Npcap](https://npcap.com/) installed (Windows only)+- Administrator/root terminal for the backend (raw packet capture)++```bash+# Backend (admin terminal) — API at http://127.0.0.1:8000+cd backend+pip install -r requirements.txt+python run_backend.py++# Frontend (separate terminal) — UI at http://localhost:5173+cd frontend+npm install+npm run dev++# Electron (optional, admin terminal)+cd electron+npm install+set VITE_DEV=1 # Windows+# VITE_DEV=1 # macOS/Linux shell+npx electron .+```++### Build the installer++```bash+# 1 — Compile backend (PyInstaller)+cd backend+pip install pyinstaller+pyinstaller backend.spec --distpath ../dist/backend++# 2 — Build frontend+cd frontend+npm run build++# 3 — Build Electron installer+cd electron+npm run build:dir+```++### Project structure++```+snitch/+├── backend/ Python FastAPI + Scapy capture engine+├── frontend/ React + D3.js UI (EN/FR)+├── electron/ Electron wrapper (main, splash, preload)+├── data/ Runtime data (SQLite DB, GeoLite2 DB)+└── dist/ Compiled output (backend exe, installer)+```++---++## Français++**Snitch** est un visualiseur de trafic réseau en temps réel.+Voyez chaque connexion que votre ordinateur établit — à qui il parle, où se trouvent les serveurs, et quelle application est responsable.++Toute l'interface est disponible en **français et en anglais** : utilisez le sélecteur `EN / FR` dans la barre d'outils en haut à droite.++### Fonctionnalités++| Fonctionnalité | Description |+|---|---|+| Graphe de force | Graphe de nœuds en direct — votre machine au centre, chaque connexion comme nœud |+| Carte du monde | IPs géolocalisées avec arcs animés sur un globe interactif |+| Timeline 60 min | Historique glissant stocké localement dans SQLite |+| 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 |+| 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 |++### Stack technique++| Couche | Technologie |+|---|---|+| Capture de paquets | Python — Scapy — Npcap (Windows) / libpcap (Linux) |+| API backend | FastAPI — WebSockets — SQLite |+| Frontend | React 18 — Vite — D3.js v7 — TopoJSON |+| Conteneur bureau | Electron 28 |+| Géolocalisation | MaxMind GeoLite2 (optionnel, repli sur ip-api.com) |++### Docker (Linux)++Le déploiement Docker est destiné aux utilisateurs Linux qui veulent lancer Snitch sans rien installer d'autre que Docker.+La capture fonctionne via `network_mode: host` — le conteneur voit le vrai trafic de l'hôte.++> **Remarque :** Docker Desktop sur Mac/Windows tourne dans une VM et ne peut pas capturer le trafic de l'hôte. Utilisez l'application Electron sur ces plateformes.++```bash+git clone <url-de-votre-depot> snitch+cd snitch+mkdir -p data+sudo docker compose up --build+```++Ouvrez **http://localhost:8000** dans votre navigateur.+En arrière-plan : `sudo docker compose up -d --build`++Limites Docker :+- L'attribution de processus est limitée aux processus du conteneur+- Le scanner LAN peut être indisponible selon la configuration réseau++### Développement++Prérequis : Python 3.11+, Node.js 18+, Npcap (Windows), terminal administrateur pour le backend.++```bash+# Backend (terminal admin)+cd backend+pip install -r requirements.txt+python run_backend.py++# Frontend (autre terminal)+cd frontend+npm install+npm run dev++# Electron (optionnel)+cd electron+npm install+VITE_DEV=1 npx electron .+```++### Structure du projet++```+snitch/+├── backend/ Moteur de capture Python FastAPI + Scapy+├── frontend/ Interface React + D3.js (FR/EN)+├── electron/ Conteneur Electron (main, splash, preload)+├── data/ Données d'exécution (SQLite, GeoLite2)+└── dist/ Sortie compilée (exe backend, installateur)+```++---++## License / Licence++AGPL v3 — see / voir [LICENSE](LICENSE).++EN: Free to use, study, and modify. Derivative works must remain open source under AGPL v3.+FR: Libre d'utilisation, d'étude et de modification. Les œuvres dérivées doivent rester open source sous AGPL v3.diff --git a/backend/api/__init__.py b/backend/api/__init__.pynew file mode 100644index 0000000..e6eecfe--- /dev/null+++ b/backend/api/__init__.py@@ -0,0 +1,2 @@+# EN: Snitch API package — FastAPI application and WebSocket endpoint.+# FR: Paquet API de Snitch — application FastAPI et endpoint WebSocket.diff --git a/backend/api/main.py b/backend/api/main.pynew file mode 100644index 0000000..4141d11--- /dev/null+++ b/backend/api/main.py@@ -0,0 +1,598 @@+"""+Snitch — FastAPI application.++EN: This module is the heart of the backend. It 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+ real-time updates to every connected frontend over a WebSocket.++FR: Ce module est le cœur du backend. Il détient l'état du graphe en mémoire+ (nœuds / arêtes / appareils LAN), reçoit les paquets du thread du sniffer+ Scapy, les enrichit (DNS + géolocalisation + classification), alimente le+ détecteur d'anomalies, persiste les agrégats dans SQLite et pousse les+ mises à jour en temps réel vers chaque frontend connecté via WebSocket.+"""++import asyncio+import json+import threading+import time+from contextlib import asynccontextmanager+from datetime import datetime++from fastapi import FastAPI, WebSocket, WebSocketDisconnect+from fastapi.middleware.cors import CORSMiddleware++from capture.sniffer import Packet, PacketSniffer+from capture.media_monitor import MediaMonitor, MediaState+from classifier.traffic import classify+from resolver.dns_geo import enrich_ip+from scanner.arp_scanner import ARPScanner, Device+from detection.anomaly import AnomalyDetector+import storage.db as db++# ── Shared state / État partagé ──────────────────────────────────────────────+# EN: All mutable application state lives here at module level.+# `nodes` and `edges` describe the external-traffic graph; `lan_devices`+# describes ARP-discovered local devices.+# FR: Tout l'état mutable de l'application vit ici au niveau module.+# `nodes` et `edges` décrivent le graphe de trafic externe ;+# `lan_devices` décrit les appareils locaux découverts par ARP.+nodes: dict[str, dict] = {}+edges: dict[str, dict] = {}+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+detector = AnomalyDetector()+_loop: asyncio.AbstractEventLoop | None = None+_sniffer: PacketSniffer | None = None+_scanner: ARPScanner | None = None+_capturing: bool = True+_port_filter: list[int] = []+_excluded_processes: set[str] = set()+_whitelisted_ips: set[str] = set()+_media_state: dict = {"mic": [], "camera": []}+++# ── Broadcast / Diffusion ────────────────────────────────────────────────────++async def broadcast(message: dict) -> None:+ """+ EN: Send a JSON message to every connected WebSocket client.+ Clients that fail to receive (disconnected, closed tab…) are removed.+ FR: Envoie un message JSON à tous les clients WebSocket connectés.+ Les clients en échec (déconnectés, onglet fermé…) sont retirés.+ """+ dead = []+ for ws in connected_clients:+ try:+ await ws.send_text(json.dumps(message))+ except Exception:+ dead.append(ws)+ for ws in dead:+ connected_clients.remove(ws)+++# ── Packet handling / Traitement des paquets ─────────────────────────────────++def on_packet(pkt: Packet) -> None:+ """+ EN: Called from the Scapy sniffer THREAD for every captured packet.+ We cannot `await` there, so the real work is scheduled on the+ asyncio event loop via `run_coroutine_threadsafe`.+ FR: Appelé depuis le THREAD du sniffer Scapy pour chaque paquet capturé.+ Impossible d'utiliser `await` là-bas : le vrai travail est planifié+ sur la boucle asyncio via `run_coroutine_threadsafe`.+ """+ if _loop is None:+ return+ asyncio.run_coroutine_threadsafe(_handle_packet(pkt), _loop)+++async def _handle_packet(pkt: Packet) -> None:+ """+ EN: Per-packet pipeline — filter, enrich, update graph, persist, detect.+ FR: Pipeline par paquet — filtrer, enrichir, mettre à jour le graphe,+ persister, détecter.+ """+ # EN: Drop packets produced by user-excluded processes.+ # FR: Ignorer les paquets produits par les processus exclus par l'utilisateur.+ if pkt.process_name and pkt.process_name in _excluded_processes:+ return++ # EN: The "remote" endpoint is the destination for outbound traffic and+ # the source for inbound traffic.+ # FR: L'endpoint « distant » est la destination pour le trafic sortant et+ # la source pour le trafic entrant.+ remote_ip = pkt.dst_ip if pkt.direction == "out" else pkt.src_ip++ # EN: Trusted IPs are skipped entirely — not shown, not stored.+ # FR: Les IP de confiance sont totalement ignorées — ni affichées ni stockées.+ if remote_ip in _whitelisted_ips:+ return++ # EN: Enrich once per IP (reverse DNS + geolocation), then cache it.+ # FR: On enrichit une fois par IP (DNS inverse + géolocalisation), puis cache.+ if remote_ip not in enrichment_cache:+ enrichment_cache[remote_ip] = await enrich_ip(remote_ip)+ geo = enrichment_cache[remote_ip]++ # EN: LAN devices already appear in the device list — skip duplicates.+ # FR: Les appareils LAN apparaissent déjà dans la liste — on évite les doublons.+ if f"lan:{remote_ip}" in lan_devices:+ return++ # EN: Classify the connection (HTTPS, DNS, tracking, CDN…) for color/label.+ # FR: Classifier la connexion (HTTPS, DNS, tracking, CDN…) pour couleur/label.+ 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:+ 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,+ }++ 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 ──────────────────────────+ # EN: One edge per (remote host, protocol) pair, always anchored on "local".+ # FR: Une arête par couple (hôte distant, protocole), toujours ancrée sur « local ».+ 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++ # EN: Persist per-minute aggregates in a batched, non-blocking way.+ # FR: Persister les agrégats par minute, par lots et sans bloquer.+ minute = datetime.utcnow().strftime("%Y-%m-%dT%H:%M")+ db.accumulate(minute, category.category, pkt.size)++ # ── Anomaly detection / Détection d'anomalies ───────────────────────────+ # EN: Detection runs in a thread executor — it is CPU-only and must not+ # block the event loop on busy networks.+ # FR: La détection tourne dans un executor — purement CPU, elle ne doit pas+ # bloquer la boucle événementielle sur les réseaux chargés.+ 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})++ # EN: Push the node/edge update plus the raw packet to all clients.+ # FR: Pousser la mise à jour nœud/arête plus le paquet brut à tous les clients.+ 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,+ "timestamp": pkt.timestamp,+ },+ })+++# ── LAN device handling / Gestion des appareils LAN ──────────────────────────++def on_device(device: Device, is_new: bool) -> None:+ """+ EN: Called from the ARP scanner thread — schedules async handling.+ FR: Appelé depuis le thread du scanner ARP — planifie le traitement async.+ """+ if _loop is None:+ return+ asyncio.run_coroutine_threadsafe(_handle_device(device, is_new), _loop)+++async def _handle_device(device: Device, is_new: bool) -> None:+ """+ EN: Register/update a LAN device node, add its dashed edge to "local",+ run device-level anomaly checks (new device, device offline).+ FR: Enregistrer/mettre à jour le nœud d'un appareil LAN, ajouter son arête+ pointillée vers « local », lancer les détections au niveau appareil+ (nouvel appareil, appareil hors ligne).+ """+ node = device.to_dict()+ node["alerted"] = False+ lan_devices[node["id"]] = node++ # EN: LAN devices use a dashed edge — visual distinction in the graph.+ # FR: Les appareils LAN utilisent une arête pointillée — distinction visuelle.+ edge_id = f"lan-edge-{device.ip}"+ edges[edge_id] = {+ "id": edge_id,+ "source": "local",+ "target": node["id"],+ "protocol": "LAN",+ "label": "LAN",+ "color": node["color"],+ "bytes": 0,+ "packets": 0,+ "dashed": True,+ }++ loop = asyncio.get_running_loop()+ alerts = await loop.run_in_executor(None, detector.analyze_device, device, is_new)+ for alert in alerts:+ if alert.node_id and alert.node_id in lan_devices:+ lan_devices[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})++ await broadcast({+ "type": "device_update",+ "device": node,+ "edge": edges[edge_id],+ "is_new": is_new,+ })+++# ── Background threads / Threads d'arrière-plan ──────────────────────────────++def _on_media_change(state: MediaState) -> None:+ """+ EN: Called by the MediaMonitor thread whenever mic/camera usage changes.+ Updates the detector (media-exfil rule) and notifies the UI.+ FR: Appelé par le thread MediaMonitor quand l'usage micro/caméra change.+ Met à jour le détecteur (règle d'exfiltration média) et notifie l'UI.+ """+ global _media_state+ _media_state = {"mic": state.mic, "camera": state.camera}+ detector.update_media_state(state.mic, state.camera)+ if _loop:+ asyncio.run_coroutine_threadsafe(+ broadcast({"type": "media", "mic": state.mic, "camera": state.camera}),+ _loop,+ )+++def _flush_loop() -> None:+ """+ EN: Periodically flush the in-memory traffic accumulator to SQLite.+ FR: Vider périodiquement l'accumulateur de trafic en mémoire vers SQLite.+ """+ while True:+ time.sleep(10)+ try:+ db.flush()+ except Exception:+ pass+++def _cleanup_loop() -> None:+ """+ EN: Drop traffic/alert rows older than 24h — the timeline is a sliding+ window, the DB must not grow forever.+ FR: Supprimer les lignes trafic/alertes de plus de 24 h — la timeline est+ une fenêtre glissante, la BDD ne doit pas grossir indéfiniment.+ """+ while True:+ time.sleep(3600)+ try:+ db.cleanup_old_data(hours=24)+ except Exception:+ pass+++# ── Capture lifecycle / Cycle de vie de la capture ───────────────────────────++def _start_capture() -> None:+ """+ EN: (Re)start the packet sniffer and the ARP scanner in daemon threads.+ FR: (Re)démarrer le sniffer de paquets et le scanner 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()+ _scanner = ARPScanner(callback=on_device, interval=30)+ threading.Thread(target=_scanner.start, daemon=True).start()+ _capturing = True+++def _stop_capture() -> None:+ """+ EN: Stop both capture sources. Safe to call when already stopped.+ FR: Arrêter les deux sources de capture. Sans effet si déjà arrêtées.+ """+ global _capturing+ if _sniffer:+ _sniffer.stop()+ if _scanner:+ _scanner.stop()+ _capturing = False+++async def _startup() -> None:+ """+ EN: Application startup — create the "local" node, start capture, and+ spawn background threads (flush, cleanup, media monitor).+ FR: Démarrage de l'application — créer le nœud « local », lancer la capture+ et les threads d'arrière-plan (flush, nettoyage, moniteur média).+ """+ global _loop+ _loop = asyncio.get_running_loop()++ # EN: The local machine is always the center of the graph.+ # FR: La machine locale est toujours le centre du graphe.+ nodes["local"] = {+ "id": "local", "label": "This Device", "ip": "local",+ "category": "local", "color": "#3b82f6",+ "bytes": 0, "packets": 0, "alerted": False,+ }++ _start_capture()+ 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()+++@asynccontextmanager+async def lifespan(app: FastAPI):+ # EN: FastAPI lifespan — run startup logic, then yield for the app's life.+ # FR: Lifespan FastAPI — logique de démarrage, puis yield pour la vie de l'app.+ await _startup()+ yield+++app = FastAPI(title="Snitch API", lifespan=lifespan)++# EN: Permissive CORS — the API only listens on localhost in production, and+# the dev frontend runs on another port (Vite proxy would also work).+# FR: CORS permissif — l'API n'écoute que sur localhost en production, et le+# frontend de dev tourne sur un autre port (le proxy Vite fonctionne aussi).+app.add_middleware(+ CORSMiddleware,+ allow_origins=["*"],+ allow_methods=["*"],+ allow_headers=["*"],+)+++# ── REST endpoints / Endpoints REST ──────────────────────────────────────────+[email protected]("/graph")+async def get_graph() -> dict:+ """EN: Full graph snapshot. / FR: Instantané complet du graphe."""+ return {+ "nodes": list(nodes.values()) + list(lan_devices.values()),+ "edges": list(edges.values()),+ }+[email protected]("/devices")+async def get_devices() -> dict:+ """EN: LAN device list. / FR: Liste des appareils LAN."""+ return {"devices": list(lan_devices.values())}+[email protected]("/alerts")+async def get_alerts() -> dict:+ """EN: Last 100 in-memory alerts. / FR: Les 100 dernières alertes en mémoire."""+ return {"alerts": detector.history[-100:]}+[email protected]("/media")+async def get_media() -> dict:+ """EN: Current mic/camera usage. / FR: Usage actuel micro/caméra."""+ return _media_state+[email protected]("/capture/status")+async def get_capture_status() -> dict:+ """EN: Capture state + all active filters. / FR: État de capture + filtres actifs."""+ return {+ "capturing": _capturing,+ "ports": _port_filter,+ "excluded_processes": sorted(_excluded_processes),+ "whitelisted_ips": sorted(_whitelisted_ips),+ }+[email protected]("/capture/stop")+async def stop_capture() -> dict:+ """EN: Stop sniffing + ARP scan. / FR: Arrêter le sniffing + le scan ARP."""+ _stop_capture()+ await broadcast({+ "type": "capture_status",+ "capturing": False,+ "ports": _port_filter,+ "excluded_processes": sorted(_excluded_processes),+ "whitelisted_ips": sorted(_whitelisted_ips),+ })+ return {"capturing": False}+[email protected]("/capture/ports")+async def set_port_filter(body: dict) -> dict:+ """+ EN: Restrict capture to a list of ports (empty list = all ports).+ The graph is wiped so the UI only shows traffic matching the filter.+ FR: Restreindre la capture à une liste de ports (liste vide = tous).+ Le graphe est vidé pour que l'UI n'affiche que le trafic filtré.+ """+ global _port_filter+ ports = [int(p) for p in body.get("ports", []) if str(p).isdigit() and 1 <= int(p) <= 65535]+ _port_filter = ports++ # EN: Clear graph state — keep only the "local" node.+ # FR: Vider l'état du graphe — ne garder que le nœud « local ».+ local = nodes.get("local")+ nodes.clear()+ edges.clear()+ lan_devices.clear()+ if local:+ nodes["local"] = local++ if _capturing:+ _stop_capture()+ _start_capture()++ await broadcast({+ "type": "reset",+ "ports": _port_filter,+ "nodes": list(nodes.values()) + list(lan_devices.values()),+ "edges": list(edges.values()),+ })+ return {"ports": _port_filter}+[email protected]("/capture/start")+async def start_capture() -> dict:+ """EN: Resume capture. / FR: Reprendre la capture."""+ if not _capturing:+ _start_capture()+ await broadcast({+ "type": "capture_status",+ "capturing": True,+ "ports": _port_filter,+ "excluded_processes": sorted(_excluded_processes),+ "whitelisted_ips": sorted(_whitelisted_ips),+ })+ return {"capturing": True}+[email protected]("/capture/processes")+async def set_process_filter(body: dict) -> dict:+ """EN: Hide traffic from named processes. / FR: Masquer le trafic de processus nommés."""+ global _excluded_processes+ _excluded_processes = {str(p) for p in body.get("excluded", []) if isinstance(p, str)}++ await broadcast({+ "type": "capture_status",+ "capturing": _capturing,+ "ports": _port_filter,+ "excluded_processes": sorted(_excluded_processes),+ "whitelisted_ips": sorted(_whitelisted_ips),+ })+ return {"excluded_processes": sorted(_excluded_processes)}+[email protected]("/capture/whitelist")+async def set_ip_whitelist(body: dict) -> dict:+ """+ EN: Mark IPs as trusted — they are no longer captured or displayed.+ Existing nodes/edges for those IPs are removed immediately.+ FR: Marquer des IP comme fiables — elles ne sont plus capturées ni affichées.+ Les nœuds/arêtes existants pour ces IP sont retirés immédiatement.+ """+ global _whitelisted_ips+ _whitelisted_ips = {str(ip) for ip in body.get("ips", []) if isinstance(ip, str)}++ 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]:+ edges.pop(edge_id, None)+ for ip in removed_ids:+ enrichment_cache.pop(ip, None)++ await broadcast({+ "type": "capture_status",+ "capturing": _capturing,+ "ports": _port_filter,+ "excluded_processes": sorted(_excluded_processes),+ "whitelisted_ips": sorted(_whitelisted_ips),+ })+ if removed_ids:+ await broadcast({"type": "nodes_removed", "ids": removed_ids})+ return {"whitelisted_ips": sorted(_whitelisted_ips)}+[email protected]("/timeline")+async def get_timeline(minutes: int = 60) -> dict:+ """EN: Per-minute traffic/alert aggregates for the timeline chart.+ FR: Agrégats trafic/alertes par minute pour le graphique timeline."""+ loop = asyncio.get_running_loop()+ data = await loop.run_in_executor(None, db.get_timeline, minutes)+ return {"timeline": data}+++# ── WebSocket ────────────────────────────────────────────────────────────────+[email protected]("/ws")+async def websocket_endpoint(websocket: WebSocket) -> None:+ """+ EN: Main realtime channel. On connect we send an `init` snapshot BEFORE+ registering the client — this guarantees no `update` referencing an+ unknown node can reach the client first and corrupt its graph state.+ FR: Canal temps réel principal. À la connexion on envoie un instantané+ `init` AVANT d'enregistrer le client — cela garantit qu'aucun `update`+ référençant un nœud inconnu n'arrive en premier et ne corrompe l'état.+ """+ await websocket.accept()++ await websocket.send_text(json.dumps({+ "type": "init",+ "nodes": list(nodes.values()) + list(lan_devices.values()),+ "edges": list(edges.values()),+ "alerts": detector.history[-50:],+ "media": _media_state,+ "capturing": _capturing,+ "ports": _port_filter,+ "excluded_processes": sorted(_excluded_processes),+ "whitelisted_ips": sorted(_whitelisted_ips),+ }))++ connected_clients.append(websocket)++ try:+ while True:+ # EN: We never read client messages — receive_text() only serves+ # to detect disconnection.+ # FR: On ne lit jamais les messages clients — receive_text() sert+ # seulement à détecter la déconnexion.+ await websocket.receive_text()+ except WebSocketDisconnect:+ if websocket in connected_clients:+ connected_clients.remove(websocket)+++# ── Serve the React build — MUST be registered last ──────────────────────────+# EN: In Docker / non-Electron mode, FastAPI serves the compiled frontend as+# static files. Mounted at "/" it catches all unmatched routes, so it has+# to be the LAST route registered.+# FR: En mode Docker / hors Electron, FastAPI sert le frontend compilé en+# fichiers statiques. Monté sur "/", il intercepte toutes les routes non+# correspondantes — il doit donc être 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/backend.spec b/backend/backend.specnew file mode 100644index 0000000..974ee17--- /dev/null+++ b/backend/backend.spec@@ -0,0 +1,110 @@+# backend.spec — PyInstaller specification for the Snitch backend.+#+# 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.+#+# 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++# 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')++block_cipher = None++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,+ hiddenimports=(+ scapy_hiddenimports++ # ── uvicorn internals / éléments internes d'uvicorn ─────────────+ + collect_submodules('uvicorn')++ # ── FastAPI / Starlette / Pydantic ──────────────────────────────+ + collect_submodules('starlette')+ + collect_submodules('fastapi')+ + collect_submodules('pydantic')+ + collect_submodules('pydantic_core')++ # ── async / HTTP / WebSocket ────────────────────────────────────+ + collect_submodules('anyio')+ + collect_submodules('websockets')+ + [+ 'h11',+ 'httptools',+ 'wsproto',+ 'aiofiles',+ ]++ # ── DNS / networking / réseau ───────────────────────────────────+ + collect_submodules('dns')+ + [+ 'psutil',+ 'psutil._pswindows',+ 'psutil._psutil_windows',+ ]++ # ── stdlib extras often missed / modules stdlib souvent oubliés ──+ + [+ 'email.mime.text',+ 'email.mime.multipart',+ 'email.mime.base',+ 'logging.handlers',+ 'asyncio',+ 'asyncio.windows_events',+ 'sqlite3',+ ]+ ),+ 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.+ excludes=['tkinter', 'matplotlib', 'numpy', 'PIL', 'PyQt5', 'wx'],+ win_no_prefer_redirects=False,+ win_private_assemblies=False,+ cipher=block_cipher,+ noarchive=False,+)++pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)++exe = EXE(+ pyz,+ a.scripts,+ a.binaries,+ a.zipfiles,+ a.datas,+ [],+ name='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,+ disable_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).+ uac_admin=False,+)diff --git a/backend/capture/__init__.py b/backend/capture/__init__.pynew file mode 100644index 0000000..21fa94f--- /dev/null+++ b/backend/capture/__init__.py@@ -0,0 +1,2 @@+# EN: Packet capture package — Scapy sniffer and microphone/camera monitor.+# FR: Paquet de capture — sniffer Scapy et moniteur microphone/caméra.diff --git a/backend/capture/media_monitor.py b/backend/capture/media_monitor.pynew file mode 100644index 0000000..19d053b--- /dev/null+++ b/backend/capture/media_monitor.py@@ -0,0 +1,157 @@+"""+Snitch — microphone / camera usage monitor.++EN: Polls the OS to find which processes currently hold the microphone or+ the camera. This powers the MEDIA_EXFIL anomaly rule: an unknown process+ using the mic AND sending traffic out is a red flag.++ - Windows: reads the ConsentStore registry keys. `LastUsedTimeStop == 0`+ means the device is currently in use by that app.+ - Linux: scans each process's open files for /dev/snd* and /dev/video*.++FR: Interroge l'OS pour savoir quels processus utilisent actuellement le+ microphone ou la caméra. Cela alimente la règle d'anomalie MEDIA_EXFIL :+ un processus inconnu qui utilise le micro ET envoie du trafic est un+ signal d'alerte.++ - Windows : lit les clés de registre ConsentStore. `LastUsedTimeStop == 0`+ signifie que l'appareil est actuellement utilisé par cette app.+ - Linux : scanne les fichiers ouverts de chaque processus à la recherche+ de /dev/snd* et /dev/video*.+"""++import sys+import time+import threading+from dataclasses import dataclass, field+from typing import Callable++import psutil+++@dataclass+class MediaState:+ """EN: Snapshot of which process names are using mic/camera.+ FR: Instantané des noms de processus utilisant micro/caméra."""+ mic: list[str] = field(default_factory=list)+ camera: list[str] = field(default_factory=list)+++def _detect_windows() -> MediaState:+ """+ EN: Read Windows' per-app consent store. Each sub-key under+ `microphone`/`webcam` is an app; `LastUsedTimeStop == 0` means the+ device is open right now.+ FR: Lire le magasin de consentement Windows par app. Chaque sous-clé sous+ `microphone`/`webcam` est une app ; `LastUsedTimeStop == 0` signifie+ que l'appareil est ouvert en ce moment.+ """+ import winreg+ state = MediaState()++ def _read_consent(device: str) -> list[str]:+ procs = []+ key_path = rf"SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\{device}"+ try:+ key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path)+ i = 0+ while True:+ try:+ sub = winreg.EnumKey(key, i)+ i += 1+ if sub == "NonPackaged":+ # EN: Desktop (non-UWP) apps live under "NonPackaged".+ # FR: Les apps bureau (non-UWP) sont sous « NonPackaged ».+ 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)+ try:+ val, _ = winreg.QueryValueEx(app_key, "LastUsedTimeStop")+ if val == 0:+ # EN: 0 = device currently in use.+ # FR: 0 = appareil en cours d'utilisation.+ procs.append(app.split("#")[-1])+ except FileNotFoundError:+ pass+ except OSError:+ break+ except OSError:+ break+ except OSError:+ pass+ return procs++ state.mic = _read_consent("microphone")+ state.camera = _read_consent("webcam")+ return state+++def _detect_linux() -> MediaState:+ """+ EN: Heuristic — a process holding /dev/snd* uses audio; /dev/video* means+ camera. Requires read access to other processes' fd lists.+ FR: Heuristique — un processus qui tient /dev/snd* utilise l'audio ;+ /dev/video* signifie caméra. Nécessite l'accès en lecture aux+ descripteurs de fichiers des autres processus.+ """+ state = MediaState()+ try:+ for proc in psutil.process_iter(['name', 'open_files']):+ try:+ files = proc.open_files()+ for f in files:+ if '/dev/snd' in f.path or '/dev/audio' in f.path:+ if proc.name() not in state.mic:+ state.mic.append(proc.name())+ if '/dev/video' in f.path:+ if proc.name() not in state.camera:+ state.camera.append(proc.name())+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ pass+ except Exception:+ pass+ return state+++def detect_media_usage() -> MediaState:+ """EN: Platform dispatch. / FR: Répartition selon la plateforme."""+ if sys.platform == "win32":+ return _detect_windows()+ return _detect_linux()+++class MediaMonitor:+ """+ EN: Poll-based watcher. The callback fires only on CHANGE — same state+ twice in a row produces no event.+ FR: Observateur par sondage. Le callback ne se déclenche qu'en cas de+ CHANGEMENT — deux états identiques d'affilée ne produisent rien.+ """++ def __init__(self, callback: Callable[[MediaState], None], interval: int = 3):+ self.callback = callback+ self.interval = interval+ self._running = False+ self._last: MediaState | None = None++ def start(self) -> None:+ """EN: Blocking loop — run inside a daemon thread.+ FR: Boucle bloquante — à lancer dans un thread daemon."""+ self._running = True+ while self._running:+ try:+ state = detect_media_usage()+ if self._last is None or state.mic != self._last.mic or state.camera != self._last.camera:+ self._last = state+ self.callback(state)+ except Exception:+ pass+ time.sleep(self.interval)++ def stop(self) -> None:+ """EN: Stop the polling loop. / FR: Arrêter la boucle de sondage."""+ self._running = Falsediff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.pynew file mode 100644index 0000000..bc5e571--- /dev/null+++ b/backend/capture/sniffer.py@@ -0,0 +1,202 @@+"""+Snitch — packet sniffer.++EN: Wraps Scapy's AsyncSniffer to capture IP packets on the host, determine+ their direction (in/out), and attribute them to a local process by+ matching the local port against psutil's connection table.++FR: Enveloppe l'AsyncSniffer de Scapy pour capturer les paquets IP de l'hôte,+ déterminer leur direction (entrant/sortant) et les attribuer à un+ processus local en comparant le port local à la table de connexions+ de psutil.+"""++import asyncio+import socket+import time+from dataclasses import dataclass, field+from datetime import datetime+from typing import Callable, Optional++try:+ from scapy.all import sniff, IP, TCP, UDP, DNS, DNSQR, 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+++@dataclass+class 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.+ """+ src_ip: str+ dst_ip: str+ src_port: Optional[int]+ dst_port: Optional[int]+ protocol: str+ size: int+ timestamp: str+ direction: str # "out" | "in" (sortant | entrant)+ pid: Optional[int] = None+ process_name: Optional[str] = None+++def get_local_ips() -> set[str]:+ """+ EN: Collect every IPv4 address bound to a local interface — used to+ decide packet direction and to ignore host-to-host noise.+ FR: Collecter toutes les adresses IPv4 des interfaces locales — sert à+ déterminer la direction des paquets et ignorer le bruit inter-hôtes.+ """+ ips = set()+ for iface_addrs in psutil.net_if_addrs().values():+ for addr in iface_addrs:+ if addr.family == socket.AF_INET:+ ips.add(addr.address)+ return ips+++def get_process_for_port(port: int, proto: str) -> tuple[Optional[int], Optional[str]]:+ """+ EN: Best-effort process attribution — find which local PID owns the local+ port of this connection, then resolve the process name.+ Note: this is inherently racy for short-lived UDP flows; misses are+ simply returned as (None, None).+ FR: Attribution de processus au mieux — trouver quel PID local possède le+ port local de la connexion, puis résoudre le nom du processus.+ Remarque : intrinsèquement sujet aux courses pour les flux UDP courts ;+ les échecs renvoient simplement (None, None).+ """+ kind = "tcp" if proto == "TCP" else "udp"+ try:+ for conn in psutil.net_connections(kind=kind):+ if conn.laddr and conn.laddr.port == port and conn.pid:+ try:+ return conn.pid, psutil.Process(conn.pid).name()+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ return conn.pid, None+ except Exception:+ pass+ return None, None+++class PacketSniffer:+ """+ EN: Scapy-based packet capture with an optional BPF port filter.+ The user callback is invoked once per relevant packet — from the+ sniffer thread, not the event loop.+ FR: Capture de paquets 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.+ """++ def __init__(self, callback: Callable[[Packet], None], ports: list[int] | None = None):+ self.callback = callback+ self.ports = ports or []+ self.local_ips = get_local_ips()+ self._sniffer: Optional[AsyncSniffer] = None+ self._running = False++ @property+ def _bpf_filter(self) -> str:+ """+ EN: Build a Berkeley Packet Filter expression. Filtering in the kernel+ (Npcap/libpcap) is far cheaper than filtering in Python.+ FR: Construire une expression BPF. Filtrer dans le noyau+ (Npcap/libpcap) coûte bien moins cher que filtrer en Python.+ """+ if not self.ports:+ return "ip"+ port_expr = " or ".join(f"port {p}" for p in self.ports)+ return f"ip and ({port_expr})"++ def _process_packet(self, pkt) -> None:+ """+ EN: Convert a raw Scapy packet into our normalized Packet dataclass.+ Drops non-IP traffic and packets that do not involve this host.+ FR: Convertir un paquet Scapy brut en dataclass Packet normalisée.+ Ignore le trafic non-IP et les paquets qui ne concernent pas cet hôte.+ """+ if not pkt.haslayer(IP):+ return++ ip = pkt[IP]+ src, dst = ip.src, ip.dst++ # EN: Only care about traffic from/to this machine.+ # FR: On ne garde que le trafic de/vers cette machine.+ if 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++ # EN: Try to attribute the flow to a local process.+ # FR: Tenter d'attribuer le flux à un processus local.+ pid, process_name = None, None+ if local_port and proto in ("TCP", "UDP"):+ pid, process_name = get_process_for_port(local_port, proto)++ packet = Packet(+ src_ip=src,+ dst_ip=dst,+ src_port=src_port,+ dst_port=dst_port,+ protocol=proto,+ size=len(pkt),+ timestamp=datetime.utcnow().isoformat(),+ direction=direction,+ pid=pid,+ process_name=process_name,+ )+ self.callback(packet)++ def start(self) -> None:+ """+ EN: Blocking call — run this inside a daemon thread. Keeps itself+ alive so the thread does not exit while AsyncSniffer works.+ FR: Appel bloquant — à lancer dans un thread daemon. Se maintient en+ vie pour que le thread ne se termine pas pendant que l'AsyncSniffer+ travaille.+ """+ if not SCAPY_AVAILABLE:+ print("[sniffer] scapy not available — packet capture disabled", flush=True)+ return+ self._running = True+ try:+ 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()+ while self._running:+ time.sleep(1)+ except Exception as exc:+ print(f"[sniffer] failed to start: {exc}", flush=True)++ def stop(self) -> None:+ """EN: Stop capture. / FR: Arrêter la capture."""+ self._running = False+ if self._sniffer:+ self._sniffer.stop()diff --git a/backend/classifier/__init__.py b/backend/classifier/__init__.pynew file mode 100644index 0000000..4adb576--- /dev/null+++ b/backend/classifier/__init__.py@@ -0,0 +1,2 @@+# EN: Traffic classification package — labels connections by category and risk.+# FR: Paquet de classification — étiquette les connexions par catégorie et risque.diff --git a/backend/classifier/traffic.py b/backend/classifier/traffic.pynew file mode 100644index 0000000..0b88a2d--- /dev/null+++ b/backend/classifier/traffic.py@@ -0,0 +1,103 @@+"""+Snitch — traffic classifier.++EN: Assigns each connection a label (HTTPS, DNS, SSH…), a category+ (safe / tracking / cdn / dns / admin / unknown), a risk level and a UI+ color. Classification is heuristic: known tracker/CDN domain suffixes+ first, then well-known ports.++FR: Attribue à chaque connexion un label (HTTPS, DNS, SSH…), une catégorie+ (safe / tracking / cdn / dns / admin / unknown), un niveau de risque et+ une couleur pour l'UI. Classification heuristique : d'abord les suffixes+ de domaines trackers/CDN connus, puis les ports bien connus.+"""++from dataclasses import dataclass+from typing import Optional++# EN: Well-known tracker / analytics domains — flagged "tracking" (amber).+# FR: Domaines de tracking / analytics connus — signalés « tracking » (ambre).+KNOWN_TRACKERS = {+ "doubleclick.net", "googlesyndication.com", "facebook.com",+ "fbcdn.net", "amazon-adsystem.com", "scorecardresearch.com",+ "quantserve.com", "hotjar.com", "mixpanel.com", "segment.io",+}++# EN: Major CDN providers — flagged "cdn" (indigo). Not dangerous, but useful+# to distinguish infrastructure from real endpoints.+# FR: Grands fournisseurs CDN — signalés « cdn » (indigo). Pas dangereux, mais+# utile pour distinguer l'infrastructure des vrais endpoints.+KNOWN_CDN = {+ "cloudflare.com", "akamaiedge.net", "fastly.net",+ "cloudfront.net", "edgekey.net",+}++# EN: Human-readable service names for common destination ports.+# FR: Noms de service lisibles pour les ports de destination courants.+PORT_LABELS: dict[int, str] = {+ 80: "HTTP",+ 443: "HTTPS",+ 53: "DNS",+ 22: "SSH",+ 21: "FTP",+ 25: "SMTP",+ 3306: "MySQL",+ 5432: "PostgreSQL",+ 6379: "Redis",+ 27017: "MongoDB",+}++RISK_LEVELS = ("safe", "tracking", "cdn", "unknown", "suspicious")+++@dataclass+class TrafficCategory:+ """+ EN: Result of classification — everything the UI needs to render a node.+ FR: Résultat de la classification — tout ce qu'il faut à l'UI pour+ afficher un nœud.+ """+ label: str # EN: "HTTPS", "DNS", "SSH"… / FR: « HTTPS », « DNS », « SSH »…+ category: str # EN: "tracking", "cdn", "safe", "unknown"… / FR: idem+ risk: str # EN: "low" | "medium" | "high" / FR: « low » | « medium » | « high »+ color: str # EN: hex color for the graph / FR: couleur hex pour le graphe+++def classify(+ hostname: Optional[str],+ dst_port: Optional[int],+ protocol: str,+) -> TrafficCategory:+ """+ EN: Classify one connection. Priority order:+ 1. hostname contains a known tracker domain -> tracking+ 2. hostname contains a known CDN domain -> cdn+ 3. well-known destination port -> safe/dns/admin+ 4. fallback -> unknown+ FR: Classifier une connexion. Ordre de priorité :+ 1. hostname contient un domaine tracker connu -> tracking+ 2. hostname contient un domaine CDN connu -> cdn+ 3. port de destination bien connu -> safe/dns/admin+ 4. repli -> unknown+ """+ label = PORT_LABELS.get(dst_port or 0, protocol)++ if hostname:+ h = hostname.lower()+ for tracker in KNOWN_TRACKERS:+ if tracker in h:+ return TrafficCategory(label, "tracking", "medium", "#f59e0b")+ for cdn in KNOWN_CDN:+ if cdn in h:+ return TrafficCategory(label, "cdn", "low", "#6366f1")++ if dst_port == 443:+ return TrafficCategory(label, "safe", "low", "#22c55e")+ if dst_port == 80:+ return TrafficCategory(label, "safe", "low", "#84cc16")+ if dst_port == 53:+ return TrafficCategory(label, "dns", "low", "#38bdf8")+ if dst_port == 22:+ return TrafficCategory(label, "admin", "medium", "#fb923c")++ return TrafficCategory(label, "unknown", "low", "#94a3b8")diff --git a/backend/detection/__init__.py b/backend/detection/__init__.pynew file mode 100644index 0000000..d7b70d5--- /dev/null+++ b/backend/detection/__init__.py@@ -0,0 +1,2 @@+# EN: Anomaly detection package — beaconing, suspicious ports/processes, spikes.+# FR: Paquet de détection d'anomalies — beaconing, ports/processus suspects, pics.diff --git a/backend/detection/anomaly.py b/backend/detection/anomaly.pynew file mode 100644index 0000000..9213ea9--- /dev/null+++ b/backend/detection/anomaly.py@@ -0,0 +1,407 @@+"""+Snitch — anomaly detector.++EN: Stateful, rule-based detector fed with every captured packet and every+ ARP-discovered device. Emits `Alert` objects that are broadcast to the UI+ and persisted to SQLite. Rules:+ - NEW_HOST first time we see a remote IP+ - SUSPICIOUS_PROCESS known dual-use/abused binaries making connections+ - SUSPICIOUS_PORT traffic to ports associated with shells/proxies/Tor+ - BEACON > N packets/min to the same host (C2 heartbeat)+ - VOLUME_SPIKE a single packet far above the host's average size+ - 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++FR: Détecteur à état, basé sur des règles, alimenté par chaque paquet capturé+ et chaque appareil découvert par ARP. Émet des objets `Alert` diffusés à+ l'UI et persistés dans SQLite. Règles :+ - NEW_HOST première fois qu'on voit une IP distante+ - SUSPICIOUS_PROCESS binaires à double usage/abusés établissant des connexions+ - SUSPICIOUS_PORT trafic vers des ports associés à shells/proxies/Tor+ - BEACON > N paquets/min vers le même hôte (heartbeat C2)+ - VOLUME_SPIKE un paquet bien au-dessus de la taille moyenne de l'hôte+ - MEDIA_EXFIL processus utilisant 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+"""++import ipaddress+import time+import uuid+from collections import defaultdict, deque+from dataclasses import dataclass, field+from datetime import datetime+from typing import Optional++from capture.sniffer import Packet+from scanner.arp_scanner import Device++# ── Constants / Constantes ───────────────────────────────────────────────────++# EN: Windows binaries frequently abused for "living off the land" attacks.+# FR: Binaires Windows fréquemment abusés dans les attaques « living off the land ».+SUSPICIOUS_PROCESSES = {+ "cmd.exe", "powershell.exe", "wscript.exe", "cscript.exe",+ "mshta.exe", "regsvr32.exe", "certutil.exe", "bitsadmin.exe",+ "rundll32.exe", "msiexec.exe", "schtasks.exe", "at.exe",+}++# EN: Ports historically associated with backdoors, botnets and proxies.+# FR: Ports historiquement associés aux backdoors, botnets et proxies.+SUSPICIOUS_PORTS = {+ 4444: "Metasploit shell",+ 4445: "Metasploit shell",+ 1337: "Hacker port",+ 31337: "Back Orifice",+ 6666: "IRC botnet",+ 6667: "IRC botnet",+ 5900: "VNC (remote desktop)",+ 5901: "VNC (remote desktop)",+ 1080: "SOCKS proxy",+ 8080: "Alt HTTP / proxy",+ 9001: "Tor relay",+ 9050: "Tor SOCKS",+}++BEACON_THRESHOLD = 30 # EN: packets/min to same IP → suspicious beacon+ # FR: paquets/min vers la même IP → beacon suspect+VOLUME_SPIKE_FACTOR = 8 # EN: 8× average bytes → spike+ # FR: 8× la moyenne d'octets → pic+COOLDOWN = 60 # EN: seconds before re-alerting the same key+ # FR: secondes avant de re-alerter la même clé++# EN: Legitimate apps known to use mic/camera + network (calls, meetings) —+# never flagged for media exfiltration.+# FR: Apps légitimes connues pour utiliser micro/caméra + réseau (appels,+# réunions) — jamais signalées pour exfiltration média.+MEDIA_WHITELIST = {+ "discord.exe", "discord",+ "teams.exe", "ms-teams.exe", "teams",+ "zoom.exe", "zoom",+ "skype.exe", "skype",+ "slack.exe", "slack",+ "webex.exe", "webex",+ "chrome.exe", "chrome",+ "firefox.exe", "firefox",+ "msedge.exe", "msedge",+ "brave.exe", "brave",+ "opera.exe", "opera",+ "facetime", "whatsapp.exe", "whatsapp",+}++# EN: IPs that legitimately receive frequent small packets (DNS resolvers,+# NTP servers) — never flagged as beaconing.+# FR: IP qui reçoivent légitimement de fréquents petits paquets (résolveurs+# DNS, serveurs NTP) — jamais signalées comme beaconing.+BEACON_WHITELIST = {+ "1.1.1.1", "1.0.0.1", # Cloudflare+ "8.8.8.8", "8.8.4.4", # Google DNS+ "9.9.9.9", "149.112.112.112", # Quad9+ "208.67.222.222", "208.67.220.220", # OpenDNS+ "4.2.2.1", "4.2.2.2", # Level3+ "216.239.35.0", "216.239.35.4", # Google NTP+ "216.239.35.8", "216.239.35.12", # Google NTP+ "129.6.15.28", "129.6.15.29", # NIST NTP+}+++# ── Alert model / Modèle d'alerte ────────────────────────────────────────────++@dataclass+class Alert:+ """+ EN: One detection event. `severity` drives the UI color; `type` maps to a+ translated label key in the frontend i18n dictionary.+ FR: Un événement de détection. `severity` pilote la couleur dans l'UI ;+ `type` correspond à une clé de traduction du dictionnaire i18n du+ frontend.+ """+ type: str+ severity: str # "info" | "warning" | "critical"+ message: str+ node_id: Optional[str] = None+ details: dict = field(default_factory=dict)+ id: str = field(default_factory=lambda: str(uuid.uuid4()))+ timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())++ def to_dict(self) -> dict:+ return {+ "id": self.id,+ "type": self.type,+ "severity": self.severity,+ "message": self.message,+ "node_id": self.node_id,+ "details": self.details,+ "timestamp": self.timestamp,+ }+++# ── Detector / Détecteur ─────────────────────────────────────────────────────++class AnomalyDetector:+ """+ EN: Keeps per-host sliding windows (packet timestamps, byte sizes), a set+ of seen hosts/connections and a cooldown map to avoid alert spam.+ All methods are synchronous and CPU-only — callers run them in a+ thread executor.+ FR: Maintient des fenêtres glissantes par hôte (timestamps des paquets,+ tailles en octets), un ensemble d'hôtes/connexions déjà vus et une+ table de cooldown pour éviter le spam d'alertes. Toutes les méthodes+ sont synchrones et purement CPU — l'appelant les exécute dans un+ thread executor.+ """++ def __init__(self):+ self._seen_hosts: set[str] = set()+ self._seen_process_conns: set[str] = set()+ self._pkt_times: dict[str, deque] = defaultdict(lambda: deque(maxlen=200))+ self._host_bytes_window: dict[str, deque] = defaultdict(lambda: deque(maxlen=60))+ self._cooldowns: dict[str, float] = {}+ self.history: list[dict] = []+ self._mic_procs: set[str] = set()+ self._cam_procs: set[str] = set()++ def update_media_state(self, mic: list[str], camera: list[str]) -> None:+ """+ EN: Called by the API whenever the media monitor reports a change.+ FR: Appelé par l'API à chaque changement rapporté par le moniteur média.+ """+ self._mic_procs = {p.lower() for p in mic}+ self._cam_procs = {p.lower() for p in camera}++ # ── Public API / API publique ────────────────────────────────────────────++ def analyze_packet(self, pkt: Packet, geo: dict) -> list[Alert]:+ """+ EN: Run every packet-level rule and return the alerts produced.+ Private/LAN IPs are ignored — LAN devices have their own rules.+ FR: Exécuter toutes les règles au niveau paquet et renvoyer les alertes+ produites. Les IP privées/LAN sont ignorées — les appareils LAN+ ont leurs propres règles.+ """+ alerts: list[Alert] = []+ remote_ip = pkt.dst_ip if pkt.direction == "out" else pkt.src_ip++ if _is_private(remote_ip):+ return alerts++ 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_beacon(remote_ip, geo)+ alerts += self._check_volume_spike(remote_ip, pkt.size, geo)+ alerts += self._check_media_exfil(pkt, remote_ip, geo)++ self._record(alerts)+ return alerts++ def analyze_device(self, device: Device, is_new: bool) -> list[Alert]:+ """+ EN: Device-level rules — alert when a device joins or leaves the LAN.+ FR: Règles au niveau appareil — alerter quand un appareil rejoint ou+ quitte le LAN.+ """+ alerts: list[Alert] = []++ if is_new:+ key = f"new_device:{device.ip}"+ alert = Alert(+ type="NEW_LAN_DEVICE",+ severity="info",+ message=f"New device on the network: {device.hostname or device.vendor or device.ip}",+ node_id=f"lan:{device.ip}",+ details={"ip": device.ip, "mac": device.mac, "vendor": device.vendor},+ )+ if self._cooldown_ok(key):+ alerts.append(alert)++ elif not device.online:+ key = f"offline:{device.ip}"+ alert = Alert(+ type="DEVICE_OFFLINE",+ severity="info",+ message=f"Device went offline: {device.hostname or device.ip}",+ node_id=f"lan:{device.ip}",+ details={"ip": device.ip},+ )+ if self._cooldown_ok(key):+ alerts.append(alert)++ self._record(alerts)+ return alerts++ # ── Detection rules / Règles de détection ────────────────────────────────++ def _check_new_host(self, ip: str, geo: dict) -> list[Alert]:+ """EN: First contact with a remote IP → info alert.+ FR: Premier contact avec une IP distante → alerte info."""+ if ip in self._seen_hosts:+ return []+ self._seen_hosts.add(ip)+ label = geo.get("hostname") or ip+ return [Alert(+ type="NEW_HOST",+ severity="info",+ message=f"New host contacted: {label}",+ node_id=ip,+ details={"ip": ip, "org": geo.get("org", ""), "country": geo.get("country", "")},+ )]++ def _check_suspicious_process(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:+ """EN: Known dual-use binary opening a connection → warning, once per+ (process, ip) pair. / FR: Binaire à double usage connu ouvrant une+ connexion → warning, une fois par couple (processus, ip)."""+ if not pkt.process_name:+ return []+ proc = pkt.process_name.lower()+ if proc not in SUSPICIOUS_PROCESSES:+ return []+ key = f"proc:{proc}:{remote_ip}"+ if key in self._seen_process_conns:+ return []+ self._seen_process_conns.add(key)+ label = geo.get("hostname") or remote_ip+ return [Alert(+ type="SUSPICIOUS_PROCESS",+ severity="warning",+ message=f"Suspicious process: {pkt.process_name} -> {label}",+ node_id=remote_ip,+ details={"process": pkt.process_name, "ip": remote_ip, "port": pkt.dst_port},+ )]++ 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+ if port not in SUSPICIOUS_PORTS:+ return []+ key = f"port:{port}:{remote_ip}"+ if not self._cooldown_ok(key):+ return []+ label = geo.get("hostname") or remote_ip+ reason = SUSPICIOUS_PORTS[port]+ return [Alert(+ type="SUSPICIOUS_PORT",+ severity="warning",+ message=f"Suspicious port {port} ({reason}) -> {label}",+ node_id=remote_ip,+ details={"port": port, "reason": reason, "ip": remote_ip},+ )]++ def _check_beacon(self, remote_ip: str, geo: dict) -> list[Alert]:+ """+ EN: >BEACON_THRESHOLD packets to the same host within 60s looks like+ a C2 heartbeat → warning, 5-minute cooldown.+ FR: >BEACON_THRESHOLD paquets vers le même hôte en 60 s ressemblent à+ un heartbeat C2 → warning, cooldown de 5 minutes.+ """+ if remote_ip in BEACON_WHITELIST:+ return []+ now = time.time()+ dq = self._pkt_times[remote_ip]+ dq.append(now)+ recent = sum(1 for t in dq if now - t < 60)+ if recent < BEACON_THRESHOLD:+ return []+ key = f"beacon:{remote_ip}"+ if not self._cooldown_ok(key, cooldown=300):+ return []+ label = geo.get("hostname") or remote_ip+ return [Alert(+ type="BEACON",+ severity="warning",+ message=f"Beacon-like behavior: {recent} packets/min to {label}",+ node_id=remote_ip,+ details={"ip": remote_ip, "rate": recent},+ )]++ def _check_volume_spike(self, remote_ip: str, size: int, geo: dict) -> list[Alert]:+ """+ EN: A single packet ≥ 8× the rolling average for that host suggests a+ data burst (possible exfiltration) → warning.+ FR: Un paquet ≥ 8× la moyenne glissante pour cet hôte suggère une+ rafale de données (exfiltration possible) → warning.+ """+ dq = self._host_bytes_window[remote_ip]+ dq.append(size)+ if len(dq) < 10:+ return []+ avg = sum(dq) / len(dq)+ if size < avg * VOLUME_SPIKE_FACTOR or avg < 100:+ return []+ key = f"spike:{remote_ip}"+ if not self._cooldown_ok(key, cooldown=120):+ 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, "size": size, "avg": int(avg)},+ )]++ def _check_media_exfil(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:+ """+ EN: A process that currently holds the mic or camera, is NOT a known+ conferencing app, and is sending outbound traffic → critical.+ This is Snitch's signature rule.+ FR: Un processus qui détient actuellement le micro ou la caméra, qui+ N'EST PAS une app de visio connue et qui émet du trafic sortant →+ critique. C'est la règle signature de Snitch.+ """+ if not pkt.process_name:+ return []+ proc = pkt.process_name.lower()+ if proc not in self._mic_procs and proc not in self._cam_procs:+ return []+ if proc in MEDIA_WHITELIST:+ return []+ if pkt.direction != "out":+ return []+ key = f"media_exfil:{proc}:{remote_ip}"+ if not self._cooldown_ok(key, cooldown=300):+ return []+ device = "microphone" if proc in self._mic_procs else "camera"+ label = geo.get("hostname") or remote_ip+ return [Alert(+ type="MEDIA_EXFIL",+ severity="critical",+ message=f"Suspected {device} exfiltration: {pkt.process_name} -> {label}",+ node_id=remote_ip,+ details={"process": pkt.process_name, "device": device, "ip": remote_ip, "org": geo.get("org", "")},+ )]++ # ── Helpers / Utilitaires ────────────────────────────────────────────────++ def _cooldown_ok(self, key: str, cooldown: int = COOLDOWN) -> bool:+ """+ EN: Return True (and arm the timer) if this alert key has not fired+ within `cooldown` seconds. Prevents alert storms.+ FR: Renvoyer True (et armer le minuteur) si cette clé d'alerte n'a pas+ tiré depuis `cooldown` secondes. Évite les tempêtes d'alertes.+ """+ now = time.time()+ if now - self._cooldowns.get(key, 0) < cooldown:+ return False+ self._cooldowns[key] = now+ return True++ def _record(self, alerts: list[Alert]) -> None:+ """+ EN: Append alerts to the bounded in-memory history (last 500).+ FR: Ajouter les alertes à l'historique en mémoire borné (500 dernières).+ """+ for a in alerts:+ self.history.append(a.to_dict())+ if len(self.history) > 500:+ self.history = self.history[-500:]+++def _is_private(ip: str) -> bool:+ """EN: RFC1918 / loopback / link-local check. / FR: Test RFC1918 / loopback / link-local."""+ try:+ return ipaddress.ip_address(ip).is_private+ except ValueError:+ return Falsediff --git a/backend/requirements.txt b/backend/requirements.txtnew file mode 100644index 0000000..86f5a97--- /dev/null+++ b/backend/requirements.txt@@ -0,0 +1,12 @@+# EN: Pinned Python dependencies for the Snitch backend.+# FR: Dépendances Python épinglées pour le backend Snitch.++fastapi==0.115.0 # EN: REST + WebSocket API framework / FR: framework API REST + WebSocket+uvicorn[standard]==0.30.6 # EN: ASGI server / FR: serveur ASGI+websockets==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+psutil==6.1.0 # EN: process + network interface info / FR: infos processus + interfaces réseau+python-dotenv==1.0.1 # EN: .env file support / FR: support des fichiers .env+aiofiles==24.1.0 # EN: async file I/O / FR: E/S fichiers asynchronesdiff --git a/backend/resolver/__init__.py b/backend/resolver/__init__.pynew file mode 100644index 0000000..0654031--- /dev/null+++ b/backend/resolver/__init__.py@@ -0,0 +1,2 @@+# EN: Resolver package — reverse DNS and IP geolocation enrichment.+# FR: Paquet de résolution — DNS inverse et enrichissement géographique des IP.diff --git a/backend/resolver/dns_geo.py b/backend/resolver/dns_geo.pynew file mode 100644index 0000000..39d76b1--- /dev/null+++ b/backend/resolver/dns_geo.py@@ -0,0 +1,152 @@+"""+Snitch — DNS reverse resolution + IP geolocation.++EN: Enrichment pipeline for remote IPs:+ 1. reverse DNS (hostname) via socket.gethostbyaddr+ 2. geolocation, MaxMind GeoLite2 offline DB via geoip2 (optional)+ 3. geolocation fallback, free ip-api.com via urllib (45 req/min)+ Everything is memoized with lru_cache — each unique IP is resolved once.++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 de géolocalisation, ip-api.com gratuit via urllib (45 req/min)+ Tout est mémoïsé avec lru_cache — chaque IP unique n'est résolue qu'une fois.+"""++import asyncio+import ipaddress+import json+import socket+import urllib.request+from functools import lru_cache+from pathlib import Path+from typing import Optional++try:+ import geoip2.database+ import geoip2.errors+ GEOIP_AVAILABLE = True+except ImportError:+ # EN: geoip2 not installed — will fall back to ip-api.com.+ # FR: geoip2 non installé — repli sur ip-api.com.+ GEOIP_AVAILABLE = False++# EN: The GeoLite2-City.mmdb file is optional — drop it into data/ for fully+# offline geolocation.+# FR: Le fichier GeoLite2-City.mmdb est optionnel — déposez-le dans data/ pour+# une géolocalisation entièrement hors ligne.+GEOIP_DB_PATH = Path(__file__).parent.parent.parent / "data" / "GeoLite2-City.mmdb"+_geoip_reader = None+++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():+ _geoip_reader = geoip2.database.Reader(str(GEOIP_DB_PATH))+ return _geoip_reader+++def is_private(ip: str) -> bool:+ """EN: RFC1918 / loopback / link-local check. / FR: Test RFC1918 / loopback / link-local."""+ try:+ return ipaddress.ip_address(ip).is_private+ except ValueError:+ return False+++@lru_cache(maxsize=2048)+def resolve_hostname(ip: str) -> Optional[str]:+ """+ EN: Reverse DNS — returns None on NXDOMAIN/timeout. Never raises.+ FR: DNS inverse — renvoie None sur NXDOMAIN/timeout. Ne lève jamais d'erreur.+ """+ try:+ return socket.gethostbyaddr(ip)[0]+ except Exception:+ return None+++@lru_cache(maxsize=2048)+def resolve_geo_maxmind(ip: str) -> dict:+ """+ EN: Offline geolocation via the local GeoLite2 database. Returns {} when+ the DB is absent, the IP is private, or the lookup fails.+ 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.+ """+ 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,+ }+ except Exception:+ return {}+++@lru_cache(maxsize=2048)+def resolve_geo_ipapi(ip: str) -> dict:+ """+ EN: Online fallback — free ip-api.com endpoint, no API key, 45 req/min.+ A 4s timeout keeps a dead connection from stalling the pipeline.+ FR: Repli en ligne — endpoint gratuit ip-api.com, sans clé API, 45 req/min.+ Un timeout de 4 s empêche une connexion morte de bloquer le pipeline.+ """+ 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":+ return {+ "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"),+ }+ except Exception:+ pass+ return {}+++@lru_cache(maxsize=2048)+def resolve_geo(ip: str) -> dict:+ """+ EN: MaxMind first, ip-api.com as fallback — best of offline + online.+ FR: MaxMind d'abord, ip-api.com en repli — le meilleur du hors ligne + en ligne.+ """+ geo = resolve_geo_maxmind(ip)+ if geo:+ return geo+ return resolve_geo_ipapi(ip)+++async 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.+ """+ loop = asyncio.get_event_loop()+ hostname = await loop.run_in_executor(None, resolve_hostname, ip)+ geo = await loop.run_in_executor(None, resolve_geo, ip)+ return {+ "ip": ip,+ "hostname": hostname,+ "private": is_private(ip),+ **geo,+ }diff --git a/backend/run_backend.py b/backend/run_backend.pynew file mode 100644index 0000000..1cb23ca--- /dev/null+++ b/backend/run_backend.py@@ -0,0 +1,53 @@+"""+Snitch backend entry point.++EN: This script is the single entry point for the Snitch backend.+ It is used both in development (`python run_backend.py`) and by+ PyInstaller when producing the standalone `snitch-backend` binary+ launched by the Electron wrapper as a child process.+ `app` is imported as an object (not a string) so PyInstaller can trace+ the full import chain and bundle api, capture, classifier, etc.++FR: Point d'entrée unique du backend Snitch.+ Utilisé à la fois en développement (`python run_backend.py`) et par+ PyInstaller pour produire le binaire autonome `snitch-backend` lancé+ par le conteneur Electron comme processus enfant.+ `app` est importé comme objet (pas comme chaîne) pour que PyInstaller+ suive toute la chaîne d'imports et embarque api, capture, classifier, etc.+"""++import os+import sys++# EN: When frozen by PyInstaller, all modules live inside sys._MEIPASS.+# Make sure that directory is importable.+# FR: Quand l'app est figée par PyInstaller, tous les modules sont dans+# sys._MEIPASS. On s'assure que ce dossier est importable.+if getattr(sys, 'frozen', False):+ bundle_dir = sys._MEIPASS+ if bundle_dir not in sys.path:+ sys.path.insert(0, bundle_dir)++# EN: Direct import — PyInstaller follows this chain and includes every+# backend package (api, capture, classifier, detection, resolver,+# scanner, storage) automatically.+# FR: Import direct — PyInstaller suit cette chaîne et inclut automatiquement+# tous les paquets backend (api, capture, classifier, detection, resolver,+# scanner, storage).+from api.main import app # noqa: E402+import uvicorn # noqa: E402++if __name__ == '__main__':+ # EN: In the frozen (Electron) build, bind to localhost only — the UI is+ # a local app, there is no reason to expose the API on the network.+ # In Docker/dev we default to all interfaces so the UI is reachable.+ # FR: Dans le build figé (Electron), on n'écoute que sur localhost — l'UI+ # est une app locale, aucune raison d'exposer l'API sur le réseau.+ # En Docker/dev on écoute sur toutes les interfaces.+ default_bind = '127.0.0.1' if getattr(sys, 'frozen', False) else '0.0.0.0'+ uvicorn.run(+ app,+ host=os.environ.get('SNITCH_BIND', default_bind),+ port=int(os.environ.get('SNITCH_PORT', '8000')),+ log_level='warning',+ )diff --git a/backend/scanner/__init__.py b/backend/scanner/__init__.pynew file mode 100644index 0000000..c237d72--- /dev/null+++ b/backend/scanner/__init__.py@@ -0,0 +1,2 @@+# EN: LAN scanner package — ARP discovery and OUI vendor lookup.+# FR: Paquet scanner LAN — découverte ARP et identification du fabricant via OUI.diff --git a/backend/scanner/arp_scanner.py b/backend/scanner/arp_scanner.pynew file mode 100644index 0000000..f71d725--- /dev/null+++ b/backend/scanner/arp_scanner.py@@ -0,0 +1,220 @@+"""+Snitch — LAN scanner (ARP discovery).++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).++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).+"""++import ipaddress+import socket+import threading+import time+from dataclasses import dataclass, field+from typing import Callable, Optional++import psutil++from scanner.oui import lookup, DEVICE_TYPE_COLORS++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+++@dataclass+class Device:+ """+ EN: One host discovered on the local network.+ FR: Un hôte découvert sur le réseau local.+ """+ ip: str+ mac: str+ vendor: str+ device_type: str # "router" | "phone" | "pc" | "tv" | "iot" | "unknown"+ hostname: Optional[str]+ online: bool = True+ color: 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.+ """+ return {+ "id": f"lan:{self.ip}",+ "ip": self.ip,+ "mac": self.mac,+ "vendor": self.vendor,+ "device_type": self.device_type,+ "hostname": self.hostname,+ "label": self.hostname or self.vendor or self.ip,+ "online": self.online,+ "category": "lan_device",+ "color": self.color,+ "icon": self.icon,+ "bytes": 0,+ "packets": 0,+ }+++def _get_local_subnets() -> list[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.+ """+ 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+++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 None+++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 []+ try:+ ans, _ = srp(+ Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=subnet),+ timeout=timeout,+ verbose=False,+ retry=1,+ )+ except Exception:+ 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:+ continue++ 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+++class 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+ disparaît.+ """++ def __init__(self, callback: Callable[[Device, bool], None], interval: int = 30):+ self.callback = callback+ self.interval = interval+ self._known: dict[str, Device] = {}+ self._running = False+ self._thread: Optional[threading.Thread] = None++ 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.+ """+ 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)++ # EN: Mark disappeared devices as offline.+ # FR: Marquer hors ligne les appareils disparus.+ for ip, device in list(self._known.items()):+ if ip not in seen_ips and device.online:+ device.online = False+ self.callback(device, False)++ time.sleep(self.interval)++ def start(self) -> None:+ """EN: Spawn the daemon scan thread. / FR: Lancer le thread de scan daemon."""+ self._running = True+ self._thread = threading.Thread(target=self._run, daemon=True)+ self._thread.start()++ def stop(self) -> None:+ """EN: Signal the loop to exit. / FR: Demander à la boucle de s'arrêter."""+ self._running = False++ @property+ def devices(self) -> list[dict]:+ """EN: Snapshot of all known devices. / FR: Instantané de tous les appareils connus."""+ return [d.to_dict() for d in self._known.values()]diff --git a/backend/scanner/oui.py b/backend/scanner/oui.pynew file mode 100644index 0000000..8933ce9--- /dev/null+++ b/backend/scanner/oui.py@@ -0,0 +1,79 @@+"""+Snitch — OUI lookup table.++EN: Maps the first 6 hex chars of a MAC address (the Organizationally Unique+ Identifier) to a (vendor, device_type) pair. This is a partial,+ hand-picked table covering the most common home-network devices — extend+ it freely.++FR: Associe les 6 premiers caractères hex d'une adresse MAC (l'Organizationally+ Unique Identifier) à un couple (fabricant, type d'appareil). Table+ partielle et choisie couvrant les appareils domestiques les plus courants —+ à enrichir librement.+"""++# EN: Partial OUI table — key = first 6 hex chars of MAC (uppercase, no colons).+# FR: Table OUI partielle — clé = 6 premiers caractères hex de la MAC (majuscules, sans « : »).+OUI_TABLE: dict[str, tuple[str, str]] = {+ # Apple+ "A4C138": ("Apple", "phone"), "F0DCE2": ("Apple", "phone"),+ "3C0754": ("Apple", "phone"), "8C8590": ("Apple", "phone"),+ "ACBC32": ("Apple", "phone"), "F82793": ("Apple", "phone"),+ # Samsung+ "8CCE4E": ("Samsung", "phone"), "A0CBFD": ("Samsung", "phone"),+ "5425EA": ("Samsung", "phone"), "D87D76": ("Samsung", "tv"),+ # Cisco / Linksys+ "000C29": ("Cisco", "router"), "001A2F": ("Cisco", "router"),+ "1C1B0D": ("Cisco", "router"), "44D9E7": ("Cisco", "router"),+ # Netgear+ "20E52A": ("Netgear", "router"), "A021B7": ("Netgear", "router"),+ "C03F0E": ("Netgear", "router"),+ # TP-Link+ "50C7BF": ("TP-Link", "router"), "B0487A": ("TP-Link", "router"),+ "E894F6": ("TP-Link", "router"), "F4F26D": ("TP-Link", "router"),+ # ASUS+ "10BF48": ("ASUS", "router"), "107B44": ("ASUS", "router"),+ "2C4D54": ("ASUS", "router"),+ # Raspberry Pi+ "B827EB": ("Raspberry Pi", "iot"), "DC8E95": ("Raspberry Pi", "iot"),+ "E45F01": ("Raspberry Pi", "iot"),+ # Intel — EN: usually PC/laptop / FR: généralement PC/portable+ "8086F2": ("Intel", "pc"), "A4C3F0": ("Intel", "pc"),+ # Realtek — EN: PC NICs / FR: cartes réseau de PC+ "00E04C": ("Realtek", "pc"),+ # Google — Chromecast, Home, etc.+ "54600A": ("Google", "iot"), "F88FCA": ("Google", "iot"),+ "A47733": ("Google", "iot"),+ # Amazon — Echo, Fire TV+ "A002DC": ("Amazon", "iot"), "FC65DE": ("Amazon", "iot"),+ "B47C9C": ("Amazon", "iot"),+ # Sonos+ "5CAAFD": ("Sonos", "iot"), "B8E937": ("Sonos", "iot"),+ # Microsoft — Xbox, Surface+ "7C1E52": ("Microsoft", "pc"), "28184D": ("Microsoft", "pc"),+ # Sony — PlayStation, TVs+ "00D9D1": ("Sony", "iot"), "F8D0AC": ("Sony", "iot"),+}+++# EN: UI color per device type — matches the legend in the frontend.+# FR: Couleur UI par type d'appareil — correspond à la légende du frontend.+DEVICE_TYPE_COLORS: dict[str, str] = {+ "router": "#f97316",+ "phone": "#a855f7",+ "pc": "#06b6d4",+ "tv": "#ec4899",+ "iot": "#84cc16",+ "unknown": "#64748b",+}+++def lookup(mac: str) -> tuple[str, str]:+ """+ EN: Return (vendor, device_type) for a MAC address string. Unknown OUIs+ return ("Unknown", "unknown").+ FR: Renvoyer (fabricant, type d'appareil) pour une adresse MAC. Les OUI+ inconnus renvoient ("Unknown", "unknown").+ """+ key = mac.upper().replace(":", "").replace("-", "")[:6]+ return OUI_TABLE.get(key, ("Unknown", "unknown"))diff --git a/backend/storage/__init__.py b/backend/storage/__init__.pynew file mode 100644index 0000000..e383ad9--- /dev/null+++ b/backend/storage/__init__.py@@ -0,0 +1,2 @@+# EN: Storage package — local SQLite persistence for traffic and alerts.+# FR: Paquet de stockage — persistance SQLite locale pour le trafic et les alertes.diff --git a/backend/storage/db.py b/backend/storage/db.pynew file mode 100644index 0000000..92f2f8c--- /dev/null+++ b/backend/storage/db.py@@ -0,0 +1,219 @@+"""+Snitch — SQLite persistence layer.++EN: Two tables:+ - traffic : per-minute aggregates (packets + bytes by category)+ - alerts_log : every emitted alert, serialized as JSON details+ Writes are cheap: packets only feed an in-memory accumulator that a+ background thread flushes every 10 s. A nightly-style cleanup keeps the+ DB to a 24-hour sliding window.++FR: Deux tables :+ - traffic : agrégats par minute (paquets + octets par catégorie)+ - alerts_log : chaque alerte émise, détails sérialisés en JSON+ Les écritures sont légères : les paquets ne font qu'alimenter un+ accumulateur en mémoire qu'un thread d'arrière-plan vide toutes les 10 s.+ Un nettoyage régulier limite la base à une fenêtre glissante de 24 h.+"""++import json+import os+import sqlite3+import sys+import threading+from collections import defaultdict+from datetime import datetime, timedelta+from pathlib import Path+++def _get_db_path() -> Path:+ """+ EN: Database location. Frozen (Electron) builds write to the user's+ LOCALAPPDATA dir; dev/Docker builds write into ./data/.+ FR: Emplacement de la base. Les builds figés (Electron) écrivent dans le+ dossier LOCALAPPDATA de l'utilisateur ; dev/Docker écrivent dans ./data/.+ """+ if getattr(sys, 'frozen', False):+ appdata = Path(os.environ.get('LOCALAPPDATA', Path.home()))+ db_dir = appdata / 'Snitch'+ else:+ db_dir = Path(__file__).parent.parent.parent / 'data'+ db_dir.mkdir(parents=True, exist_ok=True)+ return db_dir / 'snitch.db'+++DB_PATH = _get_db_path()++# EN: Single shared connection guarded by a lock — sqlite3 is not thread-safe+# by default and we write from several threads.+# FR: Connexion unique partagée protégée par un verrou — sqlite3 n'est pas+# thread-safe par défaut et nous écrivons depuis plusieurs threads.+_conn: sqlite3.Connection | None = None+_conn_lock = threading.Lock()++# EN: In-memory write accumulator — (minute, category) -> [packets, bytes].+# FR: Accumulateur d'écriture en mémoire — (minute, catégorie) -> [paquets, octets].+_pending: dict[tuple, list] = defaultdict(lambda: [0, 0])+_pending_lock = threading.Lock()+++# ── Connection & schema / Connexion & schéma ─────────────────────────────────++def get_conn() -> sqlite3.Connection:+ """+ EN: Lazily create the shared connection with WAL journaling — better+ concurrent read/write behavior for our single-writer pattern.+ FR: Créer paresseusement la connexion partagée avec journal WAL — meilleur+ comportement lecture/écriture concurrente pour notre schéma à un+ seul rédacteur.+ """+ global _conn+ if _conn is None:+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)+ _conn = sqlite3.connect(str(DB_PATH), check_same_thread=False)+ _conn.execute("PRAGMA journal_mode=WAL")+ _conn.execute("PRAGMA synchronous=NORMAL")+ _init_schema(_conn)+ return _conn+++def _init_schema(conn: sqlite3.Connection) -> None:+ """EN: Create tables + indexes if absent. / FR: Créer tables + index si absentes."""+ conn.executescript("""+ CREATE TABLE IF NOT EXISTS traffic (+ minute TEXT NOT NULL,+ category TEXT NOT NULL,+ packets INTEGER DEFAULT 0,+ bytes INTEGER DEFAULT 0,+ PRIMARY KEY (minute, category)+ );+ CREATE INDEX IF NOT EXISTS idx_traffic_minute ON traffic(minute);++ CREATE TABLE IF NOT EXISTS alerts_log (+ id TEXT PRIMARY KEY,+ ts TEXT NOT NULL,+ type TEXT,+ severity TEXT,+ message TEXT,+ node_id TEXT,+ details TEXT+ );+ CREATE INDEX IF NOT EXISTS idx_alerts_ts ON alerts_log(ts);+ """)+ conn.commit()+++# ── Write helpers / Aides d'écriture ─────────────────────────────────────────++def accumulate(minute: str, category: str, size: int) -> None:+ """+ EN: Fast, lock-minimal accumulator called once per captured packet —+ must never block the packet pipeline on disk I/O.+ FR: Accumulateur rapide à verrou minimal appelé pour chaque paquet capturé —+ ne doit jamais bloquer le pipeline de paquets sur de l'E/S disque.+ """+ with _pending_lock:+ _pending[(minute, category)][0] += 1+ _pending[(minute, category)][1] += size+++def flush() -> None:+ """+ EN: Batch-write the accumulator to SQLite using UPSERT semantics.+ Called by the background flush thread every ~10 s.+ FR: Écrire l'accumulateur dans SQLite par lots avec sémantique UPSERT.+ Appelé par le thread de flush toutes les ~10 s.+ """+ with _pending_lock:+ if not _pending:+ return+ batch = dict(_pending)+ _pending.clear()++ rows = [(m, c, v[0], v[1]) for (m, c), v in batch.items()]+ with _conn_lock:+ conn = get_conn()+ conn.executemany("""+ INSERT INTO traffic (minute, category, packets, bytes)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(minute, category) DO UPDATE SET+ packets = packets + excluded.packets,+ bytes = bytes + excluded.bytes+ """, rows)+ conn.commit()+++def log_alert(alert: dict) -> None:+ """+ EN: Persist one alert. INSERT OR IGNORE makes retries idempotent on the+ UUID primary key.+ FR: Persister une alerte. INSERT OR IGNORE rend les réessais idempotents+ grâce à la clé primaire UUID.+ """+ with _conn_lock:+ conn = get_conn()+ conn.execute("""+ INSERT OR IGNORE INTO alerts_log (id, ts, type, severity, message, node_id, details)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """, (+ alert["id"], alert["timestamp"], alert["type"],+ alert["severity"], alert["message"],+ alert.get("node_id"), json.dumps(alert.get("details", {})),+ ))+ conn.commit()+++# ── Read helpers / Aides de lecture ──────────────────────────────────────────++def get_timeline(minutes: int = 60) -> list[dict]:+ """+ EN: Per-minute packet/byte totals plus the number of alerts per minute —+ exactly what the frontend timeline chart draws.+ FR: Totaux de paquets/octets par minute plus le nombre d'alertes par+ minute — exactement ce que dessine le graphique timeline du frontend.+ """+ cutoff = (datetime.utcnow() - timedelta(minutes=minutes)).strftime("%Y-%m-%dT%H:%M")++ with _conn_lock:+ conn = get_conn()+ traffic_rows = conn.execute("""+ SELECT minute, SUM(packets), SUM(bytes)+ FROM traffic+ WHERE minute >= ?+ GROUP BY minute+ ORDER BY minute ASC+ """, (cutoff,)).fetchall()++ alert_rows = conn.execute("""+ SELECT substr(ts, 1, 16) AS minute, COUNT(*) AS cnt+ FROM alerts_log+ WHERE ts >= ?+ GROUP BY minute+ """, (cutoff,)).fetchall()++ alert_map = {r[0]: r[1] for r in alert_rows}++ return [+ {+ "minute": r[0],+ "packets": r[1],+ "bytes": r[2],+ "alerts": alert_map.get(r[0], 0),+ }+ for r in traffic_rows+ ]+++def cleanup_old_data(hours: int = 24) -> None:+ """+ EN: Delete rows older than `hours` — keeps the DB bounded since the UI+ only ever displays a sliding window.+ FR: Supprimer les lignes de plus de `hours` heures — borne la taille de la+ base puisque l'UI n'affiche qu'une fenêtre glissante.+ """+ cutoff = (datetime.utcnow() - timedelta(hours=hours)).strftime("%Y-%m-%dT%H:%M")+ with _conn_lock:+ conn = get_conn()+ conn.execute("DELETE FROM traffic WHERE minute < ?", (cutoff,))+ conn.execute("DELETE FROM alerts_log WHERE ts < ?", (cutoff,))+ conn.commit()diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 0000000..a1d50de--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,28 @@+# 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.+# Linux only — Docker Desktop (Mac/Windows) uses a VM and cannot capture host traffic.+# 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.+# Linux uniquement — Docker Desktop (Mac/Windows) utilise une VM et ne peut pas+# capturer le trafic de l'hôte.++services:+ snitch:+ build: .+ network_mode: host+ cap_add:+ - NET_ADMIN # EN: promiscuous mode / FR: mode promiscuité+ - NET_RAW # EN: raw socket / packet capture / FR: socket brut / capture de paquets+ environment:+ # EN: Bind address for the API (0.0.0.0 = all interfaces inside the container)+ # FR: Adresse d'écoute de l'API (0.0.0.0 = toutes les interfaces du conteneur)+ - SNITCH_BIND=0.0.0.0+ - SNITCH_PORT=8000+ volumes:+ # EN: data/GeoLite2-City.mmdb — optional, for offline geolocation+ # data/snitch.db — created automatically at runtime+ # FR: data/GeoLite2-City.mmdb — optionnel, pour la géolocalisation hors ligne+ # data/snitch.db — créé automatiquement au démarrage+ - ./data:/app/data+ restart: unless-stoppeddiff --git a/electron/generate-icon.js b/electron/generate-icon.jsnew file mode 100644index 0000000..b9ccf9f--- /dev/null+++ b/electron/generate-icon.js@@ -0,0 +1,179 @@+/**+ * Snitch — application icon generator.+ *+ * EN: Draws electron/icon.png (256×256 RGBA) from scratch using only Node.js+ * built-ins — no image library needed. The icon is a wireframe sphere+ * ringed by nodes, matching the splash screen.+ *+ * Run: node generate-icon.js+ *+ * FR: Dessine electron/icon.png (256×256 RGBA) à partir de zéro avec les+ * modules Node.js intégrés uniquement — aucune lib d'image nécessaire.+ * L'icône est une sphère filaire entourée de nœuds, assortie au splash.+ *+ * Usage : node generate-icon.js+ */++const zlib = require('zlib')+const fs = require('fs')+const path = require('path')++const S = 256+// EN: RGBA pixel buffer, fully transparent. / FR: buffer de pixels RGBA, entièrement transparent.+const buf = Buffer.alloc(S * S * 4, 0)++/**+ * EN: Alpha-composite one pixel over the buffer (source-over blending).+ * FR: Composite un pixel en alpha au-dessus du buffer (mélange source-over).+ */+function px(x, y, r, g, b, a) {+ x = Math.round(x); y = Math.round(y)+ if (x < 0 || x >= S || y < 0 || y >= S || a <= 0) return+ const i = (y * S + x) * 4+ const sa = a / 255, da = buf[i+3] / 255+ const oa = sa + da * (1 - sa)+ if (oa < 0.001) return+ buf[i] = Math.round((r * sa + buf[i] * da * (1 - sa)) / oa)+ buf[i+1] = Math.round((g * sa + buf[i+1] * da * (1 - sa)) / oa)+ buf[i+2] = Math.round((b * sa + buf[i+2] * da * (1 - sa)) / oa)+ buf[i+3] = Math.round(oa * 255)+}++/** EN: Filled circle with 1px antialiased edge. / FR: Cercle plein avec bord anticrénelé de 1 px. */+function fillCircle(cx, cy, R, r, g, b, a) {+ for (let y = Math.ceil(cy - R - 1); y <= cy + R + 1; y++)+ for (let x = Math.ceil(cx - R - 1); x <= cx + R + 1; x++) {+ const d = Math.sqrt((x-cx)**2 + (y-cy)**2)+ if (d < R + 0.5) px(x, y, r, g, b, Math.round(a * Math.min(1, R + 0.5 - d)))+ }+}++/** EN: Ring of stroke width `sw`. / FR: Anneau d'épaisseur `sw`. */+function strokeCircle(cx, cy, R, sw, r, g, b, a) {+ for (let y = Math.ceil(cy - R - sw - 1); y <= cy + R + sw + 1; y++)+ for (let x = Math.ceil(cx - R - sw - 1); x <= cx + R + sw + 1; x++) {+ const d = Math.sqrt((x-cx)**2 + (y-cy)**2)+ const dist = Math.abs(d - R)+ if (dist < sw/2 + 0.5) px(x, y, r, g, b, Math.round(a * Math.min(1, sw/2 + 0.5 - dist)))+ }+}++/** EN: Straight line via linear interpolation. / FR: Ligne droite par interpolation linéaire. */+function drawLine(x0, y0, x1, y1, r, g, b, a) {+ const dx = x1-x0, dy = y1-y0+ const steps = Math.ceil(Math.sqrt(dx*dx + dy*dy)) * 2+ for (let i = 0; i <= steps; i++) {+ const t = i / steps+ px(x0 + t*dx, y0 + t*dy, r, g, b, a)+ }+}++/** EN: Ellipse outline — used for the sphere's lat/long wireframe. / FR: Contour d'ellipse — pour le filaire lat/long de la sphère. */+function drawEllipse(cx, cy, rx, ry, r, g, b, a) {+ const steps = Math.ceil(Math.PI * (rx + ry) * 2.5)+ for (let i = 0; i < steps; i++) {+ const t = (i / steps) * Math.PI * 2+ px(cx + rx * Math.cos(t), cy + ry * Math.sin(t), r, g, b, a)+ }+}++const cx = S / 2, cy = S / 2+const R = 92 // EN: sphere radius / FR: rayon de la sphère++// ── Rounded-square black background / Fond noir à coins arrondis ─────────────+const cornerR = 50+for (let y = 0; y < S; y++)+ for (let x = 0; x < S; x++) {+ const dx = Math.abs(x - cx) - (cx - cornerR)+ const dy = Math.abs(y - cy) - (cy - cornerR)+ const d = dx > 0 && dy > 0 ? Math.sqrt(dx*dx + dy*dy) : Math.max(dx, dy, 0)+ if (d <= cornerR) { const i=(y*S+x)*4; buf[i]=0;buf[i+1]=0;buf[i+2]=0;buf[i+3]=255 }+ }++// ── Latitude lines / Lignes de latitude ──────────────────────────────────────+for (const ry_f of [0.28, 0.63, 0.92])+ drawEllipse(cx, cy, R, R * ry_f, 255, 255, 255, 38)++// ── Longitude lines / Lignes de longitude ────────────────────────────────────+for (const rx_f of [0.32, 0.74])+ drawEllipse(cx, cy, R * rx_f, R, 255, 255, 255, 38)++// ── Sphere ring / Anneau de la sphère ────────────────────────────────────────+strokeCircle(cx, cy, R, 2.8, 255, 255, 255, 190)++// ── Peripheral nodes / Nœuds périphériques ───────────────────────────────────+const scale = R / 118+function svgPt(sx, sy) { return [cx + (sx-240)*scale, cy + (sy-210)*scale] }+const nodes = [+ svgPt(155,110), svgPt(332,118), svgPt(355,230),+ svgPt(308,300), svgPt(158,298), svgPt(124,175),+]++// EN: Ring lines between adjacent nodes. / FR: Lignes d'anneau entre nœuds adjacents.+for (let i = 0; i < nodes.length; i++) {+ const [ax,ay] = nodes[i], [bx,by] = nodes[(i+1) % nodes.length]+ drawLine(ax, ay, bx, by, 255, 255, 255, 55)+}+// EN: Spokes to center. / FR: Rayons vers le centre.+for (const [nx,ny] of nodes) drawLine(cx, cy, nx, ny, 255, 255, 255, 38)++for (const [nx,ny] of nodes) {+ fillCircle(nx, ny, 5.5, 0, 0, 0, 255)+ strokeCircle(nx, ny, 5.5, 1.8, 255, 255, 255, 210)+ fillCircle(nx, ny, 2.8, 247, 176, 22, 255)+}++// ── Center node / Nœud central ───────────────────────────────────────────────+fillCircle(cx, cy, 18, 247, 176, 22, 45)+fillCircle(cx, cy, 11, 247, 176, 22, 155)+fillCircle(cx, cy, 7, 247, 176, 22, 255)+fillCircle(cx, cy, 3, 255, 255, 255, 255)++// ── PNG encoding / Encodage PNG ──────────────────────────────────────────────+// EN: Minimal hand-rolled PNG writer: signature + IHDR + IDAT + IEND with+// CRC32 checksums. Avoids pulling in a whole image dependency.+// FR: Encodeur PNG minimal fait main : signature + IHDR + IDAT + IEND avec+// sommes CRC32. Évite d'ajouter toute une dépendance d'image.+function crc32(data) {+ const T = new Int32Array(256)+ for (let i = 0; i < 256; i++) {+ let c = i+ for (let j = 0; j < 8; j++) c = c & 1 ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)+ T[i] = c+ }+ let crc = -1+ for (const b of data) crc = T[(crc ^ b) & 0xFF] ^ (crc >>> 8)+ return (crc ^ -1) >>> 0+}++function ck(type, data) {+ const tb = Buffer.from(type, 'ascii')+ const body = Buffer.concat([tb, data])+ const len = Buffer.alloc(4); len.writeUInt32BE(data.length)+ const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(body))+ return Buffer.concat([len, body, crc])+}++const ihdr = Buffer.alloc(13)+ihdr.writeUInt32BE(S, 0); ihdr.writeUInt32BE(S, 4)+ihdr[8] = 8; ihdr[9] = 6 // EN: 8-bit RGBA / FR: RGBA 8 bits++const raw = []+for (let y = 0; y < S; y++) {+ raw.push(0) // EN: PNG filter type: None / FR: filtre PNG : None+ for (let x = 0; x < S; x++) {+ const i = (y*S+x)*4+ raw.push(buf[i], buf[i+1], buf[i+2], buf[i+3])+ }+}++const png = Buffer.concat([+ Buffer.from([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A]),+ ck('IHDR', ihdr),+ ck('IDAT', zlib.deflateSync(Buffer.from(raw), { level: 9 })),+ ck('IEND', Buffer.alloc(0)),+])++const out = path.join(__dirname, 'icon.png')+fs.writeFileSync(out, png)+console.log('Generated', out, '-', png.length, 'bytes')diff --git a/electron/main.js b/electron/main.jsnew file mode 100644index 0000000..2a4cc4c--- /dev/null+++ b/electron/main.js@@ -0,0 +1,281 @@+/**+ * Snitch — Electron main process.+ *+ * EN: Orchestrates the desktop app:+ * 1. ensure Npcap is installed (Windows only, needed for raw capture)+ * 2. show a splash screen+ * 3. spawn the PyInstaller-compiled backend as a child process+ * 4. wait for the API to answer, then open the main window+ * 5. kill the backend cleanly on quit+ *+ * FR: Orchestre l'application bureau :+ * 1. vérifier que Npcap est installé (Windows uniquement, requis pour+ * la capture brute)+ * 2. afficher un écran de démarrage+ * 3. lancer le backend compilé par PyInstaller comme processus enfant+ * 4. attendre que l'API réponde, puis ouvrir la fenêtre principale+ * 5. tuer proprement le backend à la fermeture+ */++const _electron = require('electron')+const { app, BrowserWindow, dialog } = _electron.default || _electron+const { spawn, execSync } = require('child_process')+const path = require('path')+const http = require('http')+const fs = require('fs')++// ── Paths / Chemins ──────────────────────────────────────────────────────────+// EN: In dev, resources resolve against the repo root; in packaged builds they+// live inside process.resourcesPath.+// FR: En dev, les ressources sont résolues depuis la racine du dépôt ; en build+// packagé elles vivent dans process.resourcesPath.+const isDev = !app.isPackaged+const resourcesDir = isDev ? path.join(__dirname, '..') : process.resourcesPath++const backendExe = isDev+ ? path.join(resourcesDir, 'dist', 'backend', 'snitch-backend.exe')+ : path.join(resourcesDir, 'snitch-backend.exe')++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')++let mainWindow = null+let splashWindow = null+let backendProc = null+let isQuitting = false++// ── Port management / Gestion du port ────────────────────────────────────────+/**+ * EN: Free the backend port — kills any leftover process still listening on+ * it (zombies from crashed sessions). Windows-only implementation.+ * FR: Libérer le port du backend — tue tout processus résiduel qui écoute+ * encore dessus (zombies de sessions plantées). Windows uniquement.+ */+function killPort(port) {+ try {+ 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 {}+ }+ } catch {}+}++// ── 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.+ */+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+}++/**+ * 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.+ */+function installNpcap() {+ if (!fs.existsSync(npcapInstaller)) return false+ try {+ execSync(`"${npcapInstaller}"`, { stdio: 'inherit' })+ return true+ } catch { return false }+}++// ── Windows / Fenêtres ───────────────────────────────────────────────────────+function createSplash() {+ /** EN: Frameless transparent splash shown while the backend boots.+ * FR: Splash sans cadre et transparent affiché pendant le démarrage du backend. */+ splashWindow = new BrowserWindow({+ width: 380, height: 310, frame: false,+ resizable: false, alwaysOnTop: true, center: true,+ transparent: true, icon: iconPath,+ webPreferences: { nodeIntegration: false },+ })+ splashWindow.loadFile(path.join(__dirname, 'splash.html'))+}++function createMain() {+ /** EN: Main window — loads the Vite dev server in dev, or the compiled+ * frontend otherwise.+ * FR: Fenêtre principale — charge le serveur de dev Vite en dev, ou le+ * frontend compilé sinon. */+ 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,+ },+ })++ if (isDev && process.env.VITE_DEV === '1') {+ mainWindow.loadURL('http://localhost:5173')+ mainWindow.webContents.openDevTools()+ } else {+ mainWindow.loadFile(path.join(frontendDist, 'index.html'))+ }++ mainWindow.once('ready-to-show', () => {+ if (splashWindow) { splashWindow.destroy(); splashWindow = null }+ mainWindow.show()+ mainWindow.focus()+ })+ mainWindow.on('closed', () => { mainWindow = null })+}++// ── Backend process / Processus backend ──────────────────────────────────────+/**+ * EN: Poll the REST API until it answers or we run out of attempts.+ * FR: Interroger l'API REST jusqu'à réponse ou épuisement des essais.+ */+function waitForBackend(maxAttempts = 40) {+ return new Promise((resolve, reject) => {+ let n = 0+ function poll() {+ http.get(BACKEND_URL + '/graph', res => {+ if (res.statusCode === 200) resolve()+ else retry()+ }).on('error', retry)+ }+ function retry() {+ if (++n >= maxAttempts) reject(new Error('Backend timeout'))+ else setTimeout(poll, 1000)+ }+ poll()+ })+}++/**+ * 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.+ * 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.+ */+function killBackend() {+ if (backendProc) {+ try {+ execSync(`taskkill /PID ${backendProc.pid} /T /F`, { stdio: 'pipe' })+ } catch {}+ backendProc = null+ }+ killPort(BACKEND_PORT)+}++function launchBackend() {+ /** EN: Spawn the compiled backend; show a dialog and quit on failure.+ * FR: Lancer le backend compilé ; afficher une boîte de dialogue et quitter en cas d'échec. */+ 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)++ const env = Object.assign({}, process.env)+ // 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: false, stdio: 'ignore', env })+ backendProc.on('error', err => {+ if (isQuitting) return+ dialog.showErrorBox('Snitch', `Failed to start backend / Échec du démarrage du backend :\n${err.message}`)+ app.quit()+ })+ backendProc.on('exit', (code) => {+ if (isQuitting) return // EN: normal shutdown — don't alert / FR: arrêt normal — ne pas alerter+ if (mainWindow) {+ dialog.showErrorBox('Snitch', `Backend stopped (code ${code}) / Backend arrêté (code ${code}).`)+ app.quit()+ }+ })+}++// ── 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.+ if (process.platform === 'win32' && !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+ }+ }+ }++ createSplash()+ launchBackend()++ try {+ await waitForBackend()+ } catch (e) {+ dialog.showErrorBox('Snitch', `Backend unavailable / Backend indisponible :\n${e.message}`)+ app.quit(); return+ }++ createMain()+})++app.on('window-all-closed', () => {+ if (process.platform !== 'darwin') {+ // EN: Set the flag before quit so spurious exit dialogs are suppressed.+ // FR: Positionner le drapeau avant quit pour supprimer les dialogues parasites.+ isQuitting = true+ app.quit()+ }+})++app.on('before-quit', () => {+ isQuitting = true+ killBackend()+})diff --git a/electron/package.json b/electron/package.jsonnew file mode 100644index 0000000..a6f6551--- /dev/null+++ b/electron/package.json@@ -0,0 +1,58 @@+{+ "name": "snitch",+ "version": "1.0.0",+ "description": "Snitch — real-time network traffic visualizer / visualiseur de trafic réseau en temps réel",+ "main": "main.js",+ "license": "AGPL-3.0-or-later",+ "scripts": {+ "start": "electron .",+ "build": "electron-builder --win --x64",+ "build:dir": "electron-builder --win --x64 --dir"+ },+ "devDependencies": {+ "electron": "^28.3.3",+ "electron-builder": "^25.1.8"+ },+ "build": {+ "appId": "com.snitch.app",+ "productName": "Snitch",+ "directories": {+ "output": "../dist/installer"+ },+ "files": [+ "main.js",+ "preload.js",+ "splash.html",+ "icon.png"+ ],+ "extraResources": [+ {+ "from": "icon.png",+ "to": "icon.png"+ },+ {+ "from": "../dist/backend/snitch-backend.exe",+ "to": "snitch-backend.exe"+ },+ {+ "from": "../frontend/dist",+ "to": "frontend_dist"+ },+ {+ "from": "../resources/npcap-installer.exe",+ "to": "npcap-installer.exe"+ }+ ],+ "win": {+ "target": "nsis",+ "requestedExecutionLevel": "requireAdministrator"+ },+ "nsis": {+ "oneClick": false,+ "allowToChangeInstallationDirectory": true,+ "createDesktopShortcut": true,+ "createStartMenuShortcut": true,+ "shortcutName": "Snitch"+ }+ }+}diff --git a/electron/preload.js b/electron/preload.jsnew file mode 100644index 0000000..7248ffb--- /dev/null+++ b/electron/preload.js@@ -0,0 +1,16 @@+/**+ * Snitch — Electron preload script.+ *+ * 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.+ * 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.+ */++const { contextBridge } = require('electron')++contextBridge.exposeInMainWorld('snitch', {+ version: process.env.npm_package_version || '1.0.0',+})diff --git a/electron/splash.html b/electron/splash.htmlnew file mode 100644index 0000000..0f056e9--- /dev/null+++ b/electron/splash.html@@ -0,0 +1,145 @@+<!DOCTYPE html>+<!--+ Snitch — splash screen.++ EN: Frameless startup screen shown while the backend boots. Pure SVG + CSS,+ no external requests (the @import is progressive enhancement only).+ FR: Écran de démarrage sans cadre affiché pendant le boot du backend.+ SVG + CSS uniquement, aucune requête externe obligatoire (l'@import est+ un bonus progressif).+-->+<html lang="en">+<head>+ <meta charset="UTF-8" />+ <style>+ * { margin: 0; padding: 0; box-sizing: border-box; }+ body {+ background: #000000;+ border-radius: 14px;+ border: 1px solid #111;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ height: 100vh;+ overflow: hidden;+ user-select: none;+ }++ .logo-wrap { width: 210px; }+ .logo-wrap svg { width: 100%; height: auto; display: block; }++ /* EN: fake progress bar — the window closes when the real backend is ready.+ FR: fausse barre de progression — la fenêtre se ferme quand le vrai backend est prêt. */+ .bar-wrap {+ width: 150px;+ height: 2px;+ background: #111;+ border-radius: 1px;+ overflow: hidden;+ margin-top: 8px;+ }+ .bar {+ height: 100%;+ width: 0%;+ background: #f7b016;+ border-radius: 1px;+ animation: fill 4s ease-out forwards;+ }+ @keyframes fill {+ 0% { width: 0% }+ 60% { width: 75% }+ 85% { width: 88% }+ 100% { width: 95% }+ }+ </style>+</head>+<body>+ <div class="logo-wrap">+ <!-- EN: Globe + connected nodes logo with the SNITCH wordmark.+ FR: Logo globe + nœuds connectés avec le mot-signature SNITCH. -->+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 520">+ <defs>+ <style>@import url('https://fonts.googleapis.com/css2?family=Syne:wght@800&family=Space+Mono&family=Outfit:wght@300&display=swap');</style>+ <filter id="glow-sm" x="-50%" y="-50%" width="200%" height="200%">+ <feGaussianBlur stdDeviation="2.5" result="blur"/>+ <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>+ </filter>+ <filter id="glow-md" x="-80%" y="-80%" width="260%" height="260%">+ <feGaussianBlur stdDeviation="5" result="blur"/>+ <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>+ </filter>+ <radialGradient id="bg-glow" cx="50%" cy="42%" r="45%">+ <stop offset="0%" stop-color="#ffffff" stop-opacity="0.06"/>+ <stop offset="100%" stop-color="#000000" stop-opacity="0"/>+ </radialGradient>+ <radialGradient id="center-node" cx="35%" cy="35%" r="65%">+ <stop offset="0%" stop-color="#fde68a"/>+ <stop offset="100%" stop-color="#f7b016"/>+ </radialGradient>+ <linearGradient id="ring-grad" x1="0%" y1="0%" x2="0%" y2="100%">+ <stop offset="0%" stop-color="#ffffff" stop-opacity="0.9"/>+ <stop offset="100%" stop-color="#ffffff" stop-opacity="0.3"/>+ </linearGradient>+ <clipPath id="sphere-clip"><circle cx="240" cy="210" r="118"/></clipPath>+ </defs>++ <rect width="480" height="520" fill="#000000"/>+ <circle cx="240" cy="210" r="160" fill="url(#bg-glow)"/>++ <!-- EN: wireframe sphere / FR: sphère filaire -->+ <g clip-path="url(#sphere-clip)" opacity="0.15">+ <ellipse cx="240" cy="210" rx="118" ry="32" fill="none" stroke="#ffffff" stroke-width="0.8"/>+ <ellipse cx="240" cy="210" rx="118" ry="75" fill="none" stroke="#ffffff" stroke-width="0.8"/>+ <ellipse cx="240" cy="210" rx="118" ry="108" fill="none" stroke="#ffffff" stroke-width="0.8"/>+ <ellipse cx="240" cy="210" rx="35" ry="118" fill="none" stroke="#ffffff" stroke-width="0.8"/>+ <ellipse cx="240" cy="210" rx="80" ry="118" fill="none" stroke="#ffffff" stroke-width="0.8"/>+ </g>+ <circle cx="240" cy="210" r="118" fill="none" stroke="url(#ring-grad)" stroke-width="1.8" filter="url(#glow-sm)"/>++ <!-- EN: node ring + spokes / FR: anneau de nœuds + rayons -->+ <line x1="155" y1="110" x2="332" y2="118" stroke="#ffffff" stroke-width="0.9" opacity="0.25"/>+ <line x1="332" y1="118" x2="355" y2="230" stroke="#ffffff" stroke-width="0.9" opacity="0.25"/>+ <line x1="355" y1="230" x2="308" y2="300" stroke="#ffffff" stroke-width="0.9" opacity="0.25"/>+ <line x1="308" y1="300" x2="158" y2="298" stroke="#ffffff" stroke-width="0.9" opacity="0.25"/>+ <line x1="158" y1="298" x2="124" y2="175" stroke="#ffffff" stroke-width="0.9" opacity="0.25"/>+ <line x1="124" y1="175" x2="155" y2="110" stroke="#ffffff" stroke-width="0.9" opacity="0.25"/>+ <line x1="155" y1="110" x2="240" y2="210" stroke="#ffffff" stroke-width="0.7" opacity="0.15"/>+ <line x1="332" y1="118" x2="240" y2="210" stroke="#ffffff" stroke-width="0.7" opacity="0.15"/>+ <line x1="355" y1="230" x2="240" y2="210" stroke="#ffffff" stroke-width="0.7" opacity="0.15"/>+ <line x1="308" y1="300" x2="240" y2="210" stroke="#ffffff" stroke-width="0.7" opacity="0.15"/>+ <line x1="124" y1="175" x2="240" y2="210" stroke="#ffffff" stroke-width="0.7" opacity="0.15"/>++ <circle cx="155" cy="110" r="6.5" fill="#111" stroke="#ffffff" stroke-width="1.5" filter="url(#glow-sm)"/>+ <circle cx="155" cy="110" r="3" fill="#f7b016"/>+ <circle cx="332" cy="118" r="5.5" fill="#111" stroke="#ffffff" stroke-width="1.5" filter="url(#glow-sm)"/>+ <circle cx="332" cy="118" r="2.5" fill="#f7b016"/>+ <circle cx="355" cy="230" r="6" fill="#111" stroke="#ffffff" stroke-width="1.5" filter="url(#glow-sm)"/>+ <circle cx="355" cy="230" r="3" fill="#f7b016"/>+ <circle cx="308" cy="300" r="5" fill="#111" stroke="#ffffff" stroke-width="1.5" filter="url(#glow-sm)"/>+ <circle cx="308" cy="300" r="2.5" fill="#f7b016"/>+ <circle cx="158" cy="298" r="4.5" fill="#111" stroke="#ffffff" stroke-width="1.5" filter="url(#glow-sm)"/>+ <circle cx="158" cy="298" r="2" fill="#f7b016"/>+ <circle cx="124" cy="175" r="6" fill="#111" stroke="#ffffff" stroke-width="1.5" filter="url(#glow-sm)"/>+ <circle cx="124" cy="175" r="3" fill="#f7b016"/>++ <!-- EN: pulsing center node = this machine / FR: nœud central pulsant = cette machine -->+ <circle cx="240" cy="210" r="22" fill="#f7b016" fill-opacity="0.08"/>+ <circle cx="240" cy="210" r="14" fill="#f7b016" fill-opacity="0.2" filter="url(#glow-md)"/>+ <circle cx="240" cy="210" r="7" fill="url(#center-node)" filter="url(#glow-md)"/>+ <circle cx="240" cy="210" r="3" fill="#ffffff"/>++ <!-- EN: wordmark / FR: mot-signature -->+ <text x="240" y="374" text-anchor="middle" fill="#f7b016"+ font-family="'Space Mono', monospace" font-size="10" letter-spacing="8">REAL-TIME NETWORK</text>+ <text x="240" y="434" text-anchor="middle" fill="#ffffff"+ font-family="'Syne', sans-serif" font-size="56" font-weight="800" letter-spacing="10"+ filter="url(#glow-sm)">SNITCH</text>+ <line x1="148" y1="447" x2="332" y2="447" stroke="#f7b016" stroke-width="0.8" opacity="0.5"/>+ <text x="240" y="470" text-anchor="middle" fill="#ffffff" fill-opacity="0.4"+ font-family="'Outfit', sans-serif" font-size="12" letter-spacing="3" font-weight="300">Know who's talking.</text>+ </svg>+ </div>+ <div class="bar-wrap"><div class="bar"></div></div>+</body>+</html>diff --git a/frontend/index.html b/frontend/index.htmlnew file mode 100644index 0000000..f109834--- /dev/null+++ b/frontend/index.html@@ -0,0 +1,27 @@+<!DOCTYPE html>+<!--+ Snitch — HTML shell.++ EN: Single entry point for the Vite/React app. The #root div is where React+ mounts; everything else lives in src/.+ FR: Point d'entrée unique de l'app Vite/React. Le div #root est l'endroit où+ React se monte ; tout le reste vit dans src/.+-->+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <link rel="icon" type="image/svg+xml" href="favicon.svg" />+ <title>Snitch — Know who's talking.</title>+ <style>+ /* EN: Global reset + dark base theme.+ FR: Reset global + thème sombre de base. */+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }+ body { background: #0f172a; color: #e2e8f0; font-family: 'Inter', system-ui, sans-serif; overflow: hidden; }+ </style>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.jsx"></script>+ </body>+</html>diff --git a/frontend/package.json b/frontend/package.jsonnew file mode 100644index 0000000..5fcd01f--- /dev/null+++ b/frontend/package.json@@ -0,0 +1,23 @@+{+ "name": "snitch-frontend",+ "version": "1.0.0",+ "private": true,+ "description": "Snitch UI — React + D3.js / Interface React + D3.js",+ "scripts": {+ "dev": "vite",+ "build": "vite build",+ "preview": "vite preview"+ },+ "dependencies": {+ "d3": "^7.9.0",+ "lucide-react": "^1.9.0",+ "react": "^18.3.1",+ "react-dom": "^18.3.1",+ "topojson-client": "^3.1.0"+ },+ "devDependencies": {+ "@types/d3": "^7.4.3",+ "@vitejs/plugin-react": "^4.3.1",+ "vite": "^5.4.8"+ }+}diff --git a/frontend/public/countries-110m.json b/frontend/public/countries-110m.jsonnew file mode 100644index 0000000..055d19f--- /dev/null+++ b/frontend/public/countries-110m.json@@ -0,0 +1 @@+{"type":"Topology","objects":{"countries":{"type":"GeometryCollection","geometries":[{"type":"MultiPolygon","arcs":[[[0]],[[1]]],"id":"242","properties":{"name":"Fiji"}},{"type":"Polygon","arcs":[[2,3,4,5,6,7,8,9,10]],"id":"834","properties":{"name":"Tanzania"}},{"type":"Polygon","arcs":[[11,12,13,14]],"id":"732","properties":{"name":"W. Sahara"}},{"type":"MultiPolygon","arcs":[[[15,16,17,18]],[[19]],[[20]],[[21]],[[22]],[[23]],[[24]],[[25]],[[26]],[[27]],[[28]],[[29]],[[30]],[[31]],[[32]],[[33]],[[34]],[[35]],[[36]],[[37]],[[38]],[[39]],[[40]],[[41]],[[42]],[[43]],[[44]],[[45]],[[46]],[[47]]],"id":"124","properties":{"name":"Canada"}},{"type":"MultiPolygon","arcs":[[[-19,48,49,50]],[[51]],[[52]],[[53]],[[54]],[[55]],[[56]],[[57]],[[-17,58]],[[59]]],"id":"840","properties":{"name":"United States of America"}},{"type":"Polygon","arcs":[[60,61,62,63,64,65]],"id":"398","properties":{"name":"Kazakhstan"}},{"type":"Polygon","arcs":[[-63,66,67,68,69]],"id":"860","properties":{"name":"Uzbekistan"}},{"type":"MultiPolygon","arcs":[[[70,71]],[[72]],[[73]],[[74]]],"id":"598","properties":{"name":"Papua New Guinea"}},{"type":"MultiPolygon","arcs":[[[-72,75]],[[76,77]],[[78]],[[79,80]],[[81]],[[82]],[[83]],[[84]],[[85]],[[86]],[[87]],[[88]],[[89]]],"id":"360","properties":{"name":"Indonesia"}},{"type":"MultiPolygon","arcs":[[[90,91]],[[92,93,94,95,96,97]]],"id":"032","properties":{"name":"Argentina"}},{"type":"MultiPolygon","arcs":[[[-92,98]],[[99,-95,100,101]]],"id":"152","properties":{"name":"Chile"}},{"type":"Polygon","arcs":[[-8,102,103,104,105,106,107,108,109,110,111]],"id":"180","properties":{"name":"Dem. Rep. Congo"}},{"type":"Polygon","arcs":[[112,113,114,115]],"id":"706","properties":{"name":"Somalia"}},{"type":"Polygon","arcs":[[-3,116,117,118,-113,119]],"id":"404","properties":{"name":"Kenya"}},{"type":"Polygon","arcs":[[120,121,122,123,124,125,126,127]],"id":"729","properties":{"name":"Sudan"}},{"type":"Polygon","arcs":[[-122,128,129,130,131]],"id":"148","properties":{"name":"Chad"}},{"type":"Polygon","arcs":[[132,133]],"id":"332","properties":{"name":"Haiti"}},{"type":"Polygon","arcs":[[-133,134]],"id":"214","properties":{"name":"Dominican Rep."}},{"type":"MultiPolygon","arcs":[[[135]],[[136]],[[137]],[[138]],[[139]],[[140]],[[141,142,143]],[[144]],[[145]],[[146,147,148,149,-66,150,151,152,153,154,155,156,157,158,159,160,161]],[[162]],[[163,164]]],"id":"643","properties":{"name":"Russia"}},{"type":"MultiPolygon","arcs":[[[165]],[[166]],[[167]]],"id":"044","properties":{"name":"Bahamas"}},{"type":"Polygon","arcs":[[168]],"id":"238","properties":{"name":"Falkland Is."}},{"type":"MultiPolygon","arcs":[[[169]],[[-161,170,171,172]],[[173]],[[174]]],"id":"578","properties":{"name":"Norway"}},{"type":"Polygon","arcs":[[175]],"id":"304","properties":{"name":"Greenland"}},{"type":"Polygon","arcs":[[176]],"id":"260","properties":{"name":"Fr. S. Antarctic Lands"}},{"type":"Polygon","arcs":[[177,-77]],"id":"626","properties":{"name":"Timor-Leste"}},{"type":"Polygon","arcs":[[178,179,180,181,182,183,184],[185]],"id":"710","properties":{"name":"South Africa"}},{"type":"Polygon","arcs":[[-186]],"id":"426","properties":{"name":"Lesotho"}},{"type":"Polygon","arcs":[[-50,186,187,188,189]],"id":"484","properties":{"name":"Mexico"}},{"type":"Polygon","arcs":[[190,191,-93]],"id":"858","properties":{"name":"Uruguay"}},{"type":"Polygon","arcs":[[-191,-98,192,193,194,195,196,197,198,199,200]],"id":"076","properties":{"name":"Brazil"}},{"type":"Polygon","arcs":[[-194,201,-96,-100,202]],"id":"068","properties":{"name":"Bolivia"}},{"type":"Polygon","arcs":[[-195,-203,-102,203,204,205]],"id":"604","properties":{"name":"Peru"}},{"type":"Polygon","arcs":[[-196,-206,206,207,208,209,210]],"id":"170","properties":{"name":"Colombia"}},{"type":"Polygon","arcs":[[-209,211,212,213]],"id":"591","properties":{"name":"Panama"}},{"type":"Polygon","arcs":[[-213,214,215,216]],"id":"188","properties":{"name":"Costa Rica"}},{"type":"Polygon","arcs":[[-216,217,218,219]],"id":"558","properties":{"name":"Nicaragua"}},{"type":"Polygon","arcs":[[-219,220,221,222,223]],"id":"340","properties":{"name":"Honduras"}},{"type":"Polygon","arcs":[[-222,224,225]],"id":"222","properties":{"name":"El Salvador"}},{"type":"Polygon","arcs":[[-189,226,227,-223,-226,228]],"id":"320","properties":{"name":"Guatemala"}},{"type":"Polygon","arcs":[[-188,229,-227]],"id":"084","properties":{"name":"Belize"}},{"type":"Polygon","arcs":[[-197,-211,230,231]],"id":"862","properties":{"name":"Venezuela"}},{"type":"Polygon","arcs":[[-198,-232,232,233]],"id":"328","properties":{"name":"Guyana"}},{"type":"Polygon","arcs":[[-199,-234,234,235]],"id":"740","properties":{"name":"Suriname"}},{"type":"MultiPolygon","arcs":[[[-200,-236,236]],[[237,238,239,240,241,242,243,244]],[[245]]],"id":"250","properties":{"name":"France"}},{"type":"Polygon","arcs":[[-205,246,-207]],"id":"218","properties":{"name":"Ecuador"}},{"type":"Polygon","arcs":[[247]],"id":"630","properties":{"name":"Puerto Rico"}},{"type":"Polygon","arcs":[[248]],"id":"388","properties":{"name":"Jamaica"}},{"type":"Polygon","arcs":[[249]],"id":"192","properties":{"name":"Cuba"}},{"type":"Polygon","arcs":[[-181,250,251,252]],"id":"716","properties":{"name":"Zimbabwe"}},{"type":"Polygon","arcs":[[-180,253,254,-251]],"id":"072","properties":{"name":"Botswana"}},{"type":"Polygon","arcs":[[-179,255,256,257,-254]],"id":"516","properties":{"name":"Namibia"}},{"type":"Polygon","arcs":[[258,259,260,261,262,263,264]],"id":"686","properties":{"name":"Senegal"}},{"type":"Polygon","arcs":[[-261,265,266,267,268,269,270]],"id":"466","properties":{"name":"Mali"}},{"type":"Polygon","arcs":[[-13,271,-266,-260,272]],"id":"478","properties":{"name":"Mauritania"}},{"type":"Polygon","arcs":[[273,274,275,276,277]],"id":"204","properties":{"name":"Benin"}},{"type":"Polygon","arcs":[[-131,278,279,-277,280,-268,281,282]],"id":"562","properties":{"name":"Niger"}},{"type":"Polygon","arcs":[[-278,-280,283,284]],"id":"566","properties":{"name":"Nigeria"}},{"type":"Polygon","arcs":[[-130,285,286,287,288,289,-284,-279]],"id":"120","properties":{"name":"Cameroon"}},{"type":"Polygon","arcs":[[-275,290,291,292]],"id":"768","properties":{"name":"Togo"}},{"type":"Polygon","arcs":[[-292,293,294,295]],"id":"288","properties":{"name":"Ghana"}},{"type":"Polygon","arcs":[[-270,296,-295,297,298,299]],"id":"384","properties":{"name":"Côte d'Ivoire"}},{"type":"Polygon","arcs":[[-262,-271,-300,300,301,302,303]],"id":"324","properties":{"name":"Guinea"}},{"type":"Polygon","arcs":[[-263,-304,304]],"id":"624","properties":{"name":"Guinea-Bissau"}},{"type":"Polygon","arcs":[[-299,305,306,-301]],"id":"430","properties":{"name":"Liberia"}},{"type":"Polygon","arcs":[[-302,-307,307]],"id":"694","properties":{"name":"Sierra Leone"}},{"type":"Polygon","arcs":[[-269,-281,-276,-293,-296,-297]],"id":"854","properties":{"name":"Burkina Faso"}},{"type":"Polygon","arcs":[[-108,308,-286,-129,-121,309]],"id":"140","properties":{"name":"Central African Rep."}},{"type":"Polygon","arcs":[[-107,310,311,312,-287,-309]],"id":"178","properties":{"name":"Congo"}},{"type":"Polygon","arcs":[[-288,-313,313,314]],"id":"266","properties":{"name":"Gabon"}},{"type":"Polygon","arcs":[[-289,-315,315]],"id":"226","properties":{"name":"Eq. Guinea"}},{"type":"Polygon","arcs":[[-7,316,317,-252,-255,-258,318,-103]],"id":"894","properties":{"name":"Zambia"}},{"type":"Polygon","arcs":[[-6,319,-317]],"id":"454","properties":{"name":"Malawi"}},{"type":"Polygon","arcs":[[-5,320,-184,321,-182,-253,-318,-320]],"id":"508","properties":{"name":"Mozambique"}},{"type":"Polygon","arcs":[[-183,-322]],"id":"748","properties":{"name":"eSwatini"}},{"type":"MultiPolygon","arcs":[[[-106,322,-311]],[[-104,-319,-257,323]]],"id":"024","properties":{"name":"Angola"}},{"type":"Polygon","arcs":[[-9,-112,324]],"id":"108","properties":{"name":"Burundi"}},{"type":"Polygon","arcs":[[325,326,327,328,329,330,331]],"id":"376","properties":{"name":"Israel"}},{"type":"Polygon","arcs":[[-331,332,333]],"id":"422","properties":{"name":"Lebanon"}},{"type":"Polygon","arcs":[[334]],"id":"450","properties":{"name":"Madagascar"}},{"type":"Polygon","arcs":[[-327,335]],"id":"275","properties":{"name":"Palestine"}},{"type":"Polygon","arcs":[[-265,336]],"id":"270","properties":{"name":"Gambia"}},{"type":"Polygon","arcs":[[337,338,339]],"id":"788","properties":{"name":"Tunisia"}},{"type":"Polygon","arcs":[[-12,340,341,-338,342,-282,-267,-272]],"id":"012","properties":{"name":"Algeria"}},{"type":"Polygon","arcs":[[-326,343,344,345,346,-328,-336]],"id":"400","properties":{"name":"Jordan"}},{"type":"Polygon","arcs":[[347,348,349,350,351]],"id":"784","properties":{"name":"United Arab Emirates"}},{"type":"Polygon","arcs":[[352,353]],"id":"634","properties":{"name":"Qatar"}},{"type":"Polygon","arcs":[[354,355,356]],"id":"414","properties":{"name":"Kuwait"}},{"type":"Polygon","arcs":[[-345,357,358,359,360,-357,361]],"id":"368","properties":{"name":"Iraq"}},{"type":"MultiPolygon","arcs":[[[-351,362,363,364]],[[-349,365]]],"id":"512","properties":{"name":"Oman"}},{"type":"MultiPolygon","arcs":[[[366]],[[367]]],"id":"548","properties":{"name":"Vanuatu"}},{"type":"Polygon","arcs":[[368,369,370,371]],"id":"116","properties":{"name":"Cambodia"}},{"type":"Polygon","arcs":[[-369,372,373,374,375,376]],"id":"764","properties":{"name":"Thailand"}},{"type":"Polygon","arcs":[[-370,-377,377,378,379]],"id":"418","properties":{"name":"Laos"}},{"type":"Polygon","arcs":[[-376,380,381,382,383,-378]],"id":"104","properties":{"name":"Myanmar"}},{"type":"Polygon","arcs":[[-371,-380,384,385]],"id":"704","properties":{"name":"Vietnam"}},{"type":"MultiPolygon","arcs":[[[386,386,386]],[[-147,387,388,389,390]]],"id":"408","properties":{"name":"North Korea"}},{"type":"Polygon","arcs":[[-389,391]],"id":"410","properties":{"name":"South Korea"}},{"type":"Polygon","arcs":[[-149,392]],"id":"496","properties":{"name":"Mongolia"}},{"type":"Polygon","arcs":[[-383,393,394,395,396,397,398,399,400]],"id":"356","properties":{"name":"India"}},{"type":"Polygon","arcs":[[-382,401,-394]],"id":"050","properties":{"name":"Bangladesh"}},{"type":"Polygon","arcs":[[-400,402]],"id":"064","properties":{"name":"Bhutan"}},{"type":"Polygon","arcs":[[-398,403]],"id":"524","properties":{"name":"Nepal"}},{"type":"Polygon","arcs":[[-396,404,405,406,407]],"id":"586","properties":{"name":"Pakistan"}},{"type":"Polygon","arcs":[[-69,408,409,-407,410,411]],"id":"004","properties":{"name":"Afghanistan"}},{"type":"Polygon","arcs":[[-68,412,413,-409]],"id":"762","properties":{"name":"Tajikistan"}},{"type":"Polygon","arcs":[[-62,414,-413,-67]],"id":"417","properties":{"name":"Kyrgyzstan"}},{"type":"Polygon","arcs":[[-64,-70,-412,415,416]],"id":"795","properties":{"name":"Turkmenistan"}},{"type":"Polygon","arcs":[[-360,417,418,419,420,421,-416,-411,-406,422]],"id":"364","properties":{"name":"Iran"}},{"type":"Polygon","arcs":[[-332,-334,423,424,-358,-344]],"id":"760","properties":{"name":"Syria"}},{"type":"Polygon","arcs":[[-420,425,426,427,428]],"id":"051","properties":{"name":"Armenia"}},{"type":"Polygon","arcs":[[-172,429,430]],"id":"752","properties":{"name":"Sweden"}},{"type":"Polygon","arcs":[[-156,431,432,433,434]],"id":"112","properties":{"name":"Belarus"}},{"type":"Polygon","arcs":[[-155,435,-164,436,437,438,439,440,441,442,-432]],"id":"804","properties":{"name":"Ukraine"}},{"type":"Polygon","arcs":[[-433,-443,443,444,445,446,-142,447]],"id":"616","properties":{"name":"Poland"}},{"type":"Polygon","arcs":[[448,449,450,451,452,453,454]],"id":"040","properties":{"name":"Austria"}},{"type":"Polygon","arcs":[[-441,455,456,457,458,-449,459]],"id":"348","properties":{"name":"Hungary"}},{"type":"Polygon","arcs":[[-439,460]],"id":"498","properties":{"name":"Moldova"}},{"type":"Polygon","arcs":[[-438,461,462,463,-456,-440,-461]],"id":"642","properties":{"name":"Romania"}},{"type":"Polygon","arcs":[[-434,-448,-144,464,465]],"id":"440","properties":{"name":"Lithuania"}},{"type":"Polygon","arcs":[[-157,-435,-466,466,467]],"id":"428","properties":{"name":"Latvia"}},{"type":"Polygon","arcs":[[-158,-468,468]],"id":"233","properties":{"name":"Estonia"}},{"type":"Polygon","arcs":[[-446,469,-453,470,-238,471,472,473,474,475,476]],"id":"276","properties":{"name":"Germany"}},{"type":"Polygon","arcs":[[-463,477,478,479,480,481]],"id":"100","properties":{"name":"Bulgaria"}},{"type":"MultiPolygon","arcs":[[[482]],[[-480,483,484,485,486]]],"id":"300","properties":{"name":"Greece"}},{"type":"MultiPolygon","arcs":[[[-359,-425,487,488,-427,-418]],[[-479,489,-484]]],"id":"792","properties":{"name":"Turkey"}},{"type":"Polygon","arcs":[[-486,490,491,492,493]],"id":"008","properties":{"name":"Albania"}},{"type":"Polygon","arcs":[[-458,494,495,496,497,498]],"id":"191","properties":{"name":"Croatia"}},{"type":"Polygon","arcs":[[-452,499,-239,-471]],"id":"756","properties":{"name":"Switzerland"}},{"type":"Polygon","arcs":[[-472,-245,500]],"id":"442","properties":{"name":"Luxembourg"}},{"type":"Polygon","arcs":[[-473,-501,-244,501,502]],"id":"056","properties":{"name":"Belgium"}},{"type":"Polygon","arcs":[[-474,-503,503]],"id":"528","properties":{"name":"Netherlands"}},{"type":"Polygon","arcs":[[504,505]],"id":"620","properties":{"name":"Portugal"}},{"type":"Polygon","arcs":[[-505,506,-242,507]],"id":"724","properties":{"name":"Spain"}},{"type":"Polygon","arcs":[[508,509]],"id":"372","properties":{"name":"Ireland"}},{"type":"Polygon","arcs":[[510]],"id":"540","properties":{"name":"New Caledonia"}},{"type":"MultiPolygon","arcs":[[[511]],[[512]],[[513]],[[514]],[[515]]],"id":"090","properties":{"name":"Solomon Is."}},{"type":"MultiPolygon","arcs":[[[516]],[[517]]],"id":"554","properties":{"name":"New Zealand"}},{"type":"MultiPolygon","arcs":[[[518]],[[519]]],"id":"036","properties":{"name":"Australia"}},{"type":"Polygon","arcs":[[520]],"id":"144","properties":{"name":"Sri Lanka"}},{"type":"MultiPolygon","arcs":[[[521]],[[-61,-150,-393,-148,-391,522,-385,-379,-384,-401,-403,-399,-404,-397,-408,-410,-414,-415]]],"id":"156","properties":{"name":"China"}},{"type":"Polygon","arcs":[[523]],"id":"158","properties":{"name":"Taiwan"}},{"type":"MultiPolygon","arcs":[[[-451,524,525,-240,-500]],[[526]],[[527]]],"id":"380","properties":{"name":"Italy"}},{"type":"MultiPolygon","arcs":[[[-476,528]],[[529]]],"id":"208","properties":{"name":"Denmark"}},{"type":"MultiPolygon","arcs":[[[-510,530]],[[531]]],"id":"826","properties":{"name":"United Kingdom"}},{"type":"Polygon","arcs":[[532]],"id":"352","properties":{"name":"Iceland"}},{"type":"MultiPolygon","arcs":[[[-152,533,-421,-429,534]],[[-419,-426]]],"id":"031","properties":{"name":"Azerbaijan"}},{"type":"Polygon","arcs":[[-153,-535,-428,-489,535]],"id":"268","properties":{"name":"Georgia"}},{"type":"MultiPolygon","arcs":[[[536]],[[537]],[[538]],[[539]],[[540]],[[541]],[[542]]],"id":"608","properties":{"name":"Philippines"}},{"type":"MultiPolygon","arcs":[[[-374,543]],[[-81,544,545,546]]],"id":"458","properties":{"name":"Malaysia"}},{"type":"Polygon","arcs":[[-546,547]],"id":"096","properties":{"name":"Brunei"}},{"type":"Polygon","arcs":[[-450,-459,-499,548,-525]],"id":"705","properties":{"name":"Slovenia"}},{"type":"Polygon","arcs":[[-160,549,-430,-171]],"id":"246","properties":{"name":"Finland"}},{"type":"Polygon","arcs":[[-442,-460,-455,550,-444]],"id":"703","properties":{"name":"Slovakia"}},{"type":"Polygon","arcs":[[-445,-551,-454,-470]],"id":"203","properties":{"name":"Czechia"}},{"type":"Polygon","arcs":[[-126,551,552,553]],"id":"232","properties":{"name":"Eritrea"}},{"type":"MultiPolygon","arcs":[[[554]],[[555]],[[556]]],"id":"392","properties":{"name":"Japan"}},{"type":"Polygon","arcs":[[-193,-97,-202]],"id":"600","properties":{"name":"Paraguay"}},{"type":"Polygon","arcs":[[-364,557,558]],"id":"887","properties":{"name":"Yemen"}},{"type":"Polygon","arcs":[[-346,-362,-356,559,-354,560,-352,-365,-559,561]],"id":"682","properties":{"name":"Saudi Arabia"}},{"type":"MultiPolygon","arcs":[[[562]],[[563]],[[564]],[[565]],[[566]],[[567]],[[568]],[[569]]],"id":"010","properties":{"name":"Antarctica"}},{"type":"Polygon","arcs":[[570,571]],"properties":{"name":"N. Cyprus"}},{"type":"Polygon","arcs":[[-572,572]],"id":"196","properties":{"name":"Cyprus"}},{"type":"Polygon","arcs":[[-341,-15,573]],"id":"504","properties":{"name":"Morocco"}},{"type":"Polygon","arcs":[[-124,574,575,-329,576]],"id":"818","properties":{"name":"Egypt"}},{"type":"Polygon","arcs":[[-123,-132,-283,-343,-340,577,-575]],"id":"434","properties":{"name":"Libya"}},{"type":"Polygon","arcs":[[-114,-119,578,-127,-554,579,580]],"id":"231","properties":{"name":"Ethiopia"}},{"type":"Polygon","arcs":[[-553,581,582,-580]],"id":"262","properties":{"name":"Djibouti"}},{"type":"Polygon","arcs":[[-115,-581,-583,583]],"properties":{"name":"Somaliland"}},{"type":"Polygon","arcs":[[-11,584,-110,585,-117]],"id":"800","properties":{"name":"Uganda"}},{"type":"Polygon","arcs":[[-10,-325,-111,-585]],"id":"646","properties":{"name":"Rwanda"}},{"type":"Polygon","arcs":[[-496,586,587]],"id":"070","properties":{"name":"Bosnia and Herz."}},{"type":"Polygon","arcs":[[-481,-487,-494,588,589]],"id":"807","properties":{"name":"Macedonia"}},{"type":"Polygon","arcs":[[-457,-464,-482,-590,590,591,-587,-495]],"id":"688","properties":{"name":"Serbia"}},{"type":"Polygon","arcs":[[-492,592,-497,-588,-592,593]],"id":"499","properties":{"name":"Montenegro"}},{"type":"Polygon","arcs":[[-493,-594,-591,-589]],"properties":{"name":"Kosovo"}},{"type":"Polygon","arcs":[[594]],"id":"780","properties":{"name":"Trinidad and Tobago"}},{"type":"Polygon","arcs":[[-109,-310,-128,-579,-118,-586]],"id":"728","properties":{"name":"S. Sudan"}}]},"land":{"type":"GeometryCollection","geometries":[{"type":"MultiPolygon","arcs":[[[0]],[[1]],[[3,320,184,255,323,104,322,311,313,315,289,284,273,290,293,297,305,307,302,304,263,336,258,272,13,573,341,338,577,575,329,332,423,487,535,153,435,164,436,461,477,489,484,490,592,497,548,525,240,507,505,506,242,501,503,474,528,476,446,142,464,466,468,158,549,430,172,161,387,391,389,522,385,371,372,543,374,380,401,394,404,422,360,354,559,352,560,347,365,349,362,557,561,346,576,124,551,581,583,115,119],[421,416,64,150,533]],[[17,48,186,229,227,223,219,216,213,209,230,232,234,236,200,191,93,100,203,246,207,211,214,217,220,224,228,189,50,15,58]],[[19]],[[20]],[[21]],[[22]],[[23]],[[24]],[[25]],[[26]],[[27]],[[28]],[[29]],[[30]],[[31]],[[32]],[[33]],[[34]],[[35]],[[36]],[[37]],[[38]],[[39]],[[40]],[[41]],[[42]],[[43]],[[44]],[[45]],[[46]],[[47]],[[51]],[[52]],[[53]],[[54]],[[55]],[[56]],[[57]],[[59]],[[70,75]],[[72]],[[73]],[[74]],[[77,177]],[[78]],[[546,79,544,547]],[[81]],[[82]],[[83]],[[84]],[[85]],[[86]],[[87]],[[88]],[[89]],[[90,98]],[[133,134]],[[135]],[[136]],[[137]],[[138]],[[139]],[[140]],[[144]],[[145]],[[162]],[[165]],[[166]],[[167]],[[168]],[[169]],[[173]],[[174]],[[175]],[[176]],[[245]],[[247]],[[248]],[[249]],[[334]],[[366]],[[367]],[[482]],[[508,530]],[[510]],[[511]],[[512]],[[513]],[[514]],[[515]],[[516]],[[517]],[[518]],[[519]],[[520]],[[521]],[[523]],[[526]],[[527]],[[529]],[[531]],[[532]],[[536]],[[537]],[[538]],[[539]],[[540]],[[541]],[[542]],[[554]],[[555]],[[556]],[[562]],[[563]],[[564]],[[565]],[[566]],[[567]],[[568]],[[569]],[[570,572]],[[594]]]}]}},"arcs":[[[99478,40237],[69,98],[96,-171],[-46,-308],[-172,-81],[-153,73],[-27,260],[107,203],[126,-74]],[[0,41087],[57,27],[-34,-284],[-23,-32],[99822,-145],[-177,-124],[-36,220],[139,121],[88,33],[163,184],[-99999,0]],[[59417,50018],[47,-65],[1007,-1203],[19,-343],[399,-590]],[[60889,47817],[-128,-728],[16,-335],[178,-216],[8,-153],[-76,-357],[16,-180],[-18,-282],[97,-370],[115,-583],[101,-129]],[[61198,44484],[-221,-342],[-303,-230],[-167,10],[-99,-177],[-193,-16],[-73,-74],[-334,166],[-209,-48]],[[59599,43773],[-77,804],[-95,275],[-55,164],[-273,110]],[[59099,45126],[-157,177],[-177,100],[-111,99],[-116,150]],[[58538,45652],[-150,745],[-161,330],[-55,343],[27,307],[-50,544]],[[58149,47921],[115,28],[101,214],[108,308],[69,124],[-3,192],[-60,134],[-16,233]],[[58463,49154],[80,74],[16,348],[-110,333]],[[58449,49909],[98,71],[304,-7],[566,45]],[[47592,66920],[1,-40],[-6,-114]],[[47587,66766],[-1,-895],[-911,31],[9,-1512],[-261,-53],[-68,-304],[53,-853],[-1088,4],[-60,-197]],[[45260,62987],[12,249]],[[45272,63236],[5,-1],[625,48],[33,213],[114,265],[92,816],[386,637],[131,745],[86,44],[91,460],[234,63],[100,-76],[126,0],[90,134],[172,19],[-7,317],[42,0]],[[15878,79530],[-38,1],[-537,581],[-199,255],[-503,244],[-155,523],[40,363],[-356,252],[-48,476],[-336,429],[-6,304]],[[13740,82958],[154,285],[-7,373],[-473,376],[-284,674],[-173,424],[-255,266],[-187,242],[-147,306],[-279,-192],[-270,-330],[-247,388],[-194,259],[-271,164],[-273,17],[1,3364],[2,2193]],[[10837,91767],[518,-142],[438,-285],[289,-54],[244,247],[336,184],[413,-72],[416,259],[455,148],[191,-245],[207,138],[62,278],[192,-63],[470,-530],[369,401],[38,-449],[341,97],[105,173],[337,-34],[424,-248],[650,-217],[383,-100],[272,38],[374,-300],[-390,-293],[502,-127],[750,70],[236,103],[296,-354],[302,299],[-283,251],[179,202],[338,27],[223,59],[224,-141],[279,-321],[310,47],[491,-266],[431,94],[405,-14],[-32,367],[247,103],[431,-200],[-2,-559],[177,471],[223,-16],[126,594],[-298,364],[-324,239],[22,653],[329,429],[366,-95],[281,-261],[378,-666],[-247,-290],[517,-120],[-1,-604],[371,463],[332,-380],[-83,-438],[269,-399],[290,427],[202,510],[16,649],[394,-46],[411,-87],[373,-293],[17,-293],[-207,-315],[196,-316],[-36,-288],[-544,-413],[-386,-91],[-287,178],[-83,-297],[-268,-498],[-81,-259],[-322,-399],[-397,-39],[-220,-250],[-18,-384],[-323,-74],[-340,-479],[-301,-665],[-108,-466],[-16,-686],[409,-99],[125,-553],[130,-448],[388,117],[517,-256],[277,-225],[199,-279],[348,-163],[294,-248],[459,-34],[302,-58],[-45,-511],[86,-594],[201,-661],[414,-561],[214,192],[150,607],[-145,934],[-196,311],[445,276],[314,415],[154,411],[-23,395],[-188,502],[-338,445],[328,619],[-121,535],[-93,922],[194,137],[476,-161],[286,-57],[230,155],[258,-200],[342,-343],[85,-229],[495,-45],[-8,-496],[92,-747],[254,-92],[201,-348],[402,328],[266,652],[184,274],[216,-527],[362,-754],[307,-709],[-112,-371],[370,-333],[250,-338],[442,-152],[179,-189],[110,-500],[216,-78],[112,-223],[20,-664],[-202,-222],[-199,-207],[-458,-210],[-349,-486],[-470,-96],[-594,125],[-417,4],[-287,-41],[-233,-424],[-354,-262],[-401,-782],[-320,-545],[236,97],[446,776],[583,493],[415,58],[246,-289],[-262,-397],[88,-637],[91,-446],[361,-295],[459,86],[278,664],[19,-429],[180,-214],[-344,-387],[-615,-351],[-276,-239],[-310,-426],[-211,44],[-11,500],[483,488],[-445,-19],[-309,-72]],[[31350,77248],[-181,334],[0,805],[-123,171],[-187,-100],[-92,155],[-212,-446],[-84,-460],[-99,-269],[-118,-91],[-89,-30],[-28,-146],[-512,0],[-422,-4],[-125,-109],[-294,-425],[-34,-46],[-89,-231],[-255,1],[-273,-3],[-125,-93],[44,-116],[25,-181],[-5,-60],[-363,-293],[-286,-93],[-323,-316],[-70,0],[-94,93],[-31,85],[6,61],[61,207],[131,325],[81,349],[-56,514],[-59,536],[-290,277],[35,105],[-41,73],[-76,0],[-56,93],[-14,140],[-54,-61],[-75,18],[17,59],[-65,58],[-27,155],[-216,189],[-224,197],[-272,229],[-261,214],[-248,-167],[-91,-6],[-342,154],[-225,-77],[-269,183],[-284,94],[-194,36],[-86,100],[-49,325],[-94,-3],[-1,-227],[-575,0],[-951,0],[-944,0],[-833,0],[-834,0],[-819,0],[-847,0],[-273,0],[-824,0],[-789,0]],[[26668,87478],[207,273],[381,-6],[-6,-114],[-325,-326],[-196,13],[-61,160]],[[27840,93593],[-306,313],[12,213],[133,39],[636,-63],[479,-325],[25,-163],[-296,17],[-299,13],[-304,-80],[-80,36]],[[27690,87261],[107,177],[114,-13],[70,-121],[-108,-310],[-123,50],[-73,176],[13,41]],[[23996,94879],[-151,-229],[-403,44],[-337,155],[148,266],[399,159],[243,-208],[101,-187]],[[23933,96380],[-126,-17],[-521,38],[-74,165],[559,-9],[195,-109],[-33,-68]],[[23124,97116],[332,-205],[-76,-214],[-411,-122],[-226,138],[-119,221],[-22,245],[360,-24],[162,-39]],[[25514,94532],[-449,73],[-738,190],[-96,325],[-34,293],[-279,258],[-574,72],[-322,183],[104,242],[573,-37],[308,-190],[547,1],[240,-194],[-64,-222],[319,-134],[177,-140],[374,-26],[406,-50],[441,128],[566,51],[451,-42],[298,-223],[62,-244],[-174,-157],[-414,-127],[-355,72],[-797,-91],[-570,-11]],[[19093,96754],[392,-92],[-93,-177],[-518,-170],[-411,191],[224,188],[406,60]],[[19177,97139],[361,-120],[-339,-115],[-461,1],[5,84],[285,177],[149,-27]],[[34555,80899],[-148,-372],[-184,-517],[181,199],[187,-126],[-98,-206],[247,-162],[128,144],[277,-182],[-86,-433],[194,101],[36,-313],[86,-367],[-117,-520],[-125,-22],[-183,111],[60,484],[-77,75],[-322,-513],[-166,21],[196,277],[-267,144],[-298,-35],[-539,18],[-43,175],[173,208],[-121,160],[234,356],[287,941],[172,336],[241,204],[129,-26],[-54,-160]],[[26699,89048],[304,-203],[318,-184],[25,-281],[204,46],[199,-196],[-247,-186],[-432,142],[-156,266],[-275,-314],[-396,-306],[-95,346],[-377,-57],[242,292],[35,465],[95,542],[201,-49],[51,-259],[143,91],[161,-155]],[[28119,93327],[263,235],[616,-299],[383,-282],[36,-258],[515,134],[290,-376],[670,-234],[242,-238],[263,-553],[-510,-275],[654,-386],[441,-130],[400,-543],[437,-39],[-87,-414],[-487,-687],[-342,253],[-437,568],[-359,-74],[-35,-338],[292,-344],[377,-272],[114,-157],[181,-584],[-96,-425],[-350,160],[-697,473],[393,-509],[289,-357],[45,-206],[-753,236],[-596,343],[-337,287],[97,167],[-414,304],[-405,286],[5,-171],[-803,-94],[-235,203],[183,435],[522,10],[571,76],[-92,211],[96,294],[360,576],[-77,261],[-107,203],[-425,286],[-563,201],[178,150],[-294,367],[-245,34],[-219,201],[-149,-175],[-503,-76],[-1011,132],[-588,174],[-450,89],[-231,207],[290,270],[-394,2],[-88,599],[213,528],[286,241],[717,158],[-204,-382],[219,-369],[256,477],[704,242],[477,-611],[-42,-387],[550,172]],[[23749,94380],[579,-20],[530,-144],[-415,-526],[-331,-115],[-298,-442],[-317,22],[-173,519],[4,294],[145,251],[276,161]],[[15873,95551],[472,442],[570,383],[426,-9],[381,87],[-38,-454],[-214,-205],[-259,-29],[-517,-252],[-444,-91],[-377,128]],[[13136,82508],[267,47],[-84,-671],[242,-475],[-111,1],[-167,270],[-103,272],[-140,184],[-51,260],[16,188],[131,-76]],[[20696,97433],[546,-81],[751,-215],[212,-281],[108,-247],[-453,66],[-457,192],[-619,21],[268,176],[-335,142],[-21,227]],[[15692,79240],[-140,-82],[-456,269],[-84,209],[-248,207],[-50,168],[-286,107],[-107,321],[24,137],[291,-129],[171,-89],[261,-63],[94,-204],[138,-280],[277,-244],[115,-327]],[[16239,94566],[397,-123],[709,-33],[270,-171],[298,-249],[-349,-149],[-681,-415],[-344,-414],[0,-257],[-731,-285],[-147,259],[-641,312],[119,250],[192,432],[241,388],[-272,362],[939,93]],[[20050,95391],[247,99],[291,-26],[49,-289],[-169,-281],[-940,-91],[-701,-256],[-423,-14],[-35,193],[577,261],[-1255,-70],[-389,106],[379,577],[262,165],[782,-199],[493,-350],[485,-45],[-397,565],[255,215],[286,-68],[94,-282],[109,-210]],[[20410,93755],[311,-239],[175,-575],[86,-417],[466,-293],[502,-279],[-31,-260],[-456,-48],[178,-227],[-94,-217],[-503,93],[-478,160],[-322,-36],[-522,-201],[-704,-88],[-494,-56],[-151,279],[-379,161],[-246,-66],[-343,468],[185,62],[429,101],[392,-26],[362,103],[-537,138],[-594,-47],[-394,12],[-146,217],[644,237],[-428,-9],[-485,156],[233,443],[193,235],[744,359],[284,-114],[-139,-277],[618,179],[386,-298],[314,302],[254,-194],[227,-580],[140,244],[-197,606],[244,86],[276,-94]],[[22100,93536],[-306,386],[329,286],[331,-124],[496,75],[72,-172],[-259,-283],[420,-254],[-50,-532],[-455,-229],[-268,50],[-192,225],[-690,456],[5,189],[567,-73]],[[20389,94064],[372,24],[211,-130],[-244,-390],[-434,413],[95,83]],[[22639,95907],[212,-273],[9,-303],[-127,-440],[-458,-60],[-298,94],[5,345],[-455,-46],[-18,457],[299,-18],[419,201],[390,-34],[22,77]],[[23329,98201],[192,180],[285,42],[-122,135],[646,30],[355,-315],[468,-127],[455,-112],[220,-390],[334,-190],[-381,-176],[-513,-445],[-492,-42],[-575,76],[-299,240],[4,215],[220,157],[-508,-4],[-306,196],[-176,268],[193,262]],[[24559,98965],[413,112],[324,19],[545,96],[409,220],[344,-30],[300,-166],[211,319],[367,95],[498,65],[849,24],[148,-63],[802,100],[601,-38],[602,-37],[742,-47],[597,-75],[508,-161],[-12,-157],[-678,-257],[-672,-119],[-251,-133],[605,3],[-656,-358],[-452,-167],[-476,-483],[-573,-98],[-177,-120],[-841,-64],[383,-74],[-192,-105],[230,-292],[-264,-202],[-429,-167],[-132,-232],[-388,-176],[39,-134],[475,23],[6,-144],[-742,-355],[-726,163],[-816,-91],[-414,71],[-525,31],[-35,284],[514,133],[-137,427],[170,41],[742,-255],[-379,379],[-450,113],[225,229],[492,141],[79,206],[-392,231],[-118,304],[759,-26],[220,-64],[433,216],[-625,68],[-972,-38],[-491,201],[-232,239],[-324,173],[-61,202]],[[29106,90427],[-180,-174],[-312,-30],[-69,289],[118,331],[255,82],[217,-163],[3,-253],[-32,-82]],[[23262,91636],[169,-226],[-173,-207],[-374,179],[-226,-65],[-380,266],[245,183],[194,256],[295,-168],[166,-106],[84,-112]],[[32078,80046],[96,49],[365,-148],[284,-247],[8,-108],[-135,-11],[-360,186],[-258,279]],[[32218,78370],[97,-288],[202,-79],[257,16],[-137,-242],[-102,-38],[-353,250],[-69,198],[105,183]],[[31350,77248],[48,-194],[-296,-286],[-286,-204],[-293,-175],[-147,-351],[-47,-133],[-3,-313],[92,-313],[115,-15],[-29,216],[83,-131],[-22,-169],[-188,-96],[-133,11],[-205,-103],[-121,-29],[-162,-29],[-231,-171],[408,111],[82,-112],[-389,-177],[-177,-1],[8,72],[-84,-164],[82,-27],[-60,-424],[-203,-455],[-20,152],[-61,30],[-91,148],[57,-318],[69,-105],[5,-223],[-89,-230],[-157,-472],[-25,24],[86,402],[-142,225],[-33,491],[-53,-255],[59,-375],[-183,93],[191,-191],[12,-562],[79,-41],[29,-204],[39,-591],[-176,-439],[-288,-175],[-182,-346],[-139,-38],[-141,-217],[-39,-199],[-305,-383],[-157,-281],[-131,-351],[-43,-419],[50,-411],[92,-505],[124,-418],[1,-256],[132,-685],[-9,-398],[-12,-230],[-69,-361],[-83,-75],[-137,72],[-44,259],[-105,136],[-148,508],[-129,452],[-42,231],[57,393],[-77,325],[-217,494],[-108,90],[-281,-268],[-49,30],[-135,275],[-174,147],[-314,-75],[-247,66],[-212,-41],[-114,-92],[50,-157],[-5,-240],[59,-117],[-53,-77],[-103,87],[-104,-112],[-202,18],[-207,312],[-242,-73],[-202,137],[-173,-42],[-234,-138],[-253,-438],[-276,-255],[-152,-282],[-63,-266],[-3,-407],[14,-284],[52,-201]],[[23016,65864],[-108,-18],[-197,130],[-217,184],[-78,277],[-61,414],[-164,337],[-96,346],[-139,404],[-196,236],[-227,-11],[-175,-467],[-230,177],[-144,178],[-69,325],[-92,309],[-165,260],[-142,186],[-102,210],[-481,0],[0,-244],[-221,0],[-552,-4],[-634,416],[-419,287],[26,116],[-353,-64],[-316,-46]],[[17464,69802],[-46,302],[-180,340],[-130,71],[-30,169],[-156,30],[-100,159],[-258,59],[-71,95],[-33,324],[-270,594],[-231,821],[10,137],[-123,195],[-215,495],[-38,482],[-148,323],[61,489],[-10,507],[-89,453],[109,557],[34,536],[33,536],[-50,792],[-88,506],[-80,274],[33,115],[402,-200],[148,-558],[69,156],[-45,484],[-94,485]],[[6833,62443],[49,-51],[45,-79],[71,-207],[-7,-33],[-108,-126],[-89,-92],[-41,-99],[-69,84],[8,165],[-46,216],[14,65],[48,97],[-19,116],[16,55],[21,-11],[107,-100]],[[6668,62848],[-23,-71],[-94,-43],[-47,125],[-32,48],[-3,37],[27,50],[99,-56],[73,-90]],[[6456,63091],[-9,-63],[-149,17],[21,72],[137,-26]],[[6104,63411],[23,-38],[80,-196],[-15,-34],[-19,8],[-97,21],[-35,133],[-11,24],[74,82]],[[5732,63705],[5,-138],[-33,-58],[-93,107],[14,43],[43,58],[64,-12]],[[3759,86256],[220,-54],[27,-226],[-171,-92],[-182,110],[-168,161],[274,101]],[[7436,84829],[185,-40],[117,-183],[-240,-281],[-277,-225],[-142,152],[-43,277],[252,210],[148,90]],[[13740,82958],[-153,223],[-245,188],[-78,515],[-358,478],[-150,558],[-267,38],[-441,15],[-326,170],[-574,613],[-266,112],[-486,211],[-385,-51],[-546,272],[-330,252],[-309,-125],[58,-411],[-154,-38],[-321,-123],[-245,-199],[-308,-126],[-39,348],[125,580],[295,182],[-76,148],[-354,-329],[-190,-394],[-400,-420],[203,-287],[-262,-424],[-299,-248],[-278,-180],[-69,-261],[-434,-305],[-87,-278],[-325,-252],[-191,45],[-259,-165],[-282,-201],[-231,-197],[-477,-169],[-43,99],[304,276],[271,182],[296,324],[345,66],[137,243],[385,353],[62,119],[205,208],[48,448],[141,349],[-320,-179],[-90,102],[-150,-215],[-181,300],[-75,-212],[-104,294],[-278,-236],[-170,0],[-24,352],[50,216],[-179,211],[-361,-113],[-235,277],[-190,142],[-1,334],[-214,252],[108,340],[226,330],[99,303],[225,43],[191,-94],[224,285],[201,-51],[212,183],[-52,270],[-155,106],[205,228],[-170,-7],[-295,-128],[-85,-131],[-219,131],[-392,-67],[-407,142],[-117,238],[-351,343],[390,247],[620,289],[228,0],[-38,-296],[586,23],[-225,366],[-342,225],[-197,296],[-267,252],[-381,187],[155,309],[493,19],[350,270],[66,287],[284,281],[271,68],[526,262],[256,-40],[427,315],[421,-124],[201,-266],[123,114],[469,-35],[-16,-136],[425,-101],[283,59],[585,-186],[534,-56],[214,-77],[370,96],[421,-177],[302,-83]],[[2297,88264],[171,-113],[173,61],[225,-156],[276,-79],[-23,-64],[-211,-125],[-211,128],[-106,107],[-245,-34],[-66,52],[17,223]],[[74266,79657],[-212,-393],[-230,-56],[-13,-592],[-155,-267],[-551,194],[-200,-1058],[-143,-131],[-550,-236],[250,-1026],[-190,-154],[22,-337]],[[72294,75601],[-171,87],[-140,212],[-412,62],[-461,16],[-100,-65],[-396,248],[-158,-122],[-43,-349],[-457,204],[-183,-84],[-62,-259]],[[69711,75551],[-159,-109],[-367,-412],[-121,-422],[-104,-4],[-76,280],[-353,19],[-57,484],[-135,4],[21,593],[-333,431],[-476,-46],[-326,-86],[-265,533],[-227,223],[-431,423],[-52,51],[-715,-349],[11,-2178]],[[65546,74986],[-142,-29],[-195,463],[-188,166],[-315,-123],[-123,-197]],[[64583,75266],[-15,144],[68,246],[-53,206],[-322,202],[-125,530],[-154,150],[-9,192],[270,-56],[11,432],[236,96],[243,-88],[50,576],[-50,365],[-278,-28],[-236,144],[-321,-260],[-259,-124]],[[63639,77993],[-142,96],[29,304],[-177,395],[-207,-17],[-235,401],[160,448],[-81,120],[222,649],[285,-342],[35,431],[573,643],[434,15],[612,-409],[329,-239],[295,249],[440,12],[356,-306],[80,175],[391,-25],[69,280],[-450,406],[267,288],[-52,161],[266,153],[-200,405],[127,202],[1039,205],[136,146],[695,218],[250,245],[499,-127],[88,-612],[290,144],[356,-202],[-23,-322],[267,33],[696,558],[-102,-185],[355,-457],[620,-1500],[148,309],[383,-340],[399,151],[154,-106],[133,-341],[194,-115],[119,-251],[358,79],[147,-361]],[[69711,75551],[83,-58],[-234,-382],[205,-223],[198,147],[329,-311],[-355,-425],[-212,58]],[[69725,74357],[-114,-15],[-40,164],[58,274],[-371,-137],[-89,-380],[-132,-326],[-232,28],[-72,-261],[204,-140],[60,-440],[-156,-598]],[[68841,72526],[-210,124],[-154,4]],[[68477,72654],[7,362],[-369,253],[-291,289],[-181,278],[-317,408],[-137,609],[-93,108],[-301,-27],[-106,121],[-30,471],[-374,312],[-234,-343],[-237,-204],[45,-297],[-313,-8]],[[89166,49043],[482,-407],[513,-338],[192,-302],[154,-297],[43,-349],[462,-365],[68,-313],[-256,-64],[62,-393],[248,-388],[180,-627],[159,20],[-11,-262],[215,-100],[-84,-111],[295,-249],[-30,-171],[-184,-41],[-69,153],[-238,66],[-281,89],[-216,377],[-158,325],[-144,517],[-362,259],[-235,-169],[-170,-195],[35,-436],[-218,-203],[-155,99],[-288,25]],[[89175,45193],[-4,1925],[-5,1925]],[[92399,48417],[106,-189],[33,-307],[-87,-157],[-52,348],[-65,229],[-126,193],[-158,252],[-200,174],[77,143],[150,-166],[94,-130],[117,-142],[111,-248]],[[92027,47129],[-152,-144],[-142,-138],[-148,1],[-228,171],[-158,165],[23,183],[249,-86],[152,46],[42,283],[40,15],[27,-314],[158,45],[78,202],[155,211],[-30,348],[166,11],[56,-97],[-5,-327],[-93,-361],[-146,-48],[-44,-166]],[[92988,47425],[84,-134],[135,-375],[131,-200],[-39,-166],[-78,-59],[-120,227],[-122,375],[-59,450],[38,57],[30,-175]],[[89175,45193],[-247,485],[-282,118],[-69,-168],[-352,-18],[118,481],[175,164],[-72,642],[-134,496],[-538,500],[-229,50],[-417,546],[-82,-287],[-107,-52],[-63,216],[-1,257],[-212,290],[299,213],[198,-11],[-23,156],[-407,1],[-110,352],[-248,109],[-117,293],[374,143],[142,192],[446,-242],[44,-220],[78,-955],[287,-354],[232,627],[319,356],[247,1],[238,-206],[206,-212],[298,-113]],[[84713,45326],[28,-117],[5,-179]],[[84746,45030],[-181,-441],[-238,-130],[-33,71],[25,201],[119,360],[275,235]],[[87280,46506],[-27,445],[49,212],[58,200],[63,-173],[0,-282],[-143,-402]],[[82744,53024],[-158,-533],[204,-560],[-48,-272],[312,-546],[-329,-70],[-93,-403],[12,-535],[-267,-404],[-7,-589],[-107,-903],[-41,210],[-316,-266],[-110,361],[-198,34],[-139,189],[-330,-212],[-101,285],[-182,-32],[-229,68],[-43,793],[-138,164],[-134,505],[-38,517],[32,548],[165,392]],[[80461,51765],[47,-395],[190,-334],[179,121],[177,-43],[162,299],[133,52],[263,-166],[226,126],[143,822],[107,205],[96,672],[319,0],[241,-100]],[[85936,48924],[305,-172],[101,-452],[-234,244],[-232,49],[-157,-39],[-192,21],[65,325],[344,24]],[[85242,48340],[-192,108],[-54,254],[281,29],[69,-195],[-104,-196]],[[85536,51864],[20,-322],[164,-52],[26,-241],[-15,-517],[-143,58],[-42,-359],[114,-312],[-78,-71],[-112,374],[-82,755],[56,472],[92,215]],[[84146,51097],[319,25],[275,429],[48,-132],[-223,-587],[-209,-113],[-267,115],[-463,-29],[-243,-85],[-39,-447],[248,-526],[150,268],[518,201],[-22,-272],[-121,86],[-121,-347],[-245,-229],[263,-757],[-50,-203],[249,-682],[-2,-388],[-148,-173],[-109,207],[134,484],[-273,-229],[-69,164],[36,228],[-200,346],[21,576],[-186,-179],[24,-689],[11,-846],[-176,-85],[-119,173],[79,544],[-43,570],[-117,4],[-86,405],[115,387],[40,469],[139,891],[58,243],[237,439],[217,-174],[350,-82]],[[83414,44519],[-368,414],[259,116],[146,-180],[97,-180],[-17,-159],[-117,-11]],[[83705,45536],[185,45],[249,216],[-41,-328],[-417,-168],[-370,73],[0,216],[220,123],[174,-177]],[[82849,45639],[172,48],[69,-251],[-321,-119],[-193,-79],[-149,5],[95,340],[153,5],[74,209],[100,-158]],[[80134,46785],[38,-210],[533,-59],[61,244],[515,-284],[101,-383],[417,-108],[341,-351],[-317,-225],[-306,238],[-251,-16],[-288,44],[-260,106],[-322,225],[-204,59],[-116,-74],[-506,243],[-48,254],[-255,44],[191,564],[337,-35],[224,-231],[115,-45]],[[78991,49939],[47,-412],[97,-330],[204,-52],[135,-374],[-70,-735],[-11,-914],[-308,-12],[-234,494],[-356,482],[-119,358],[-210,481],[-138,443],[-212,827],[-244,493],[-81,508],[-103,461],[-250,372],[-145,506],[-209,330],[-290,652],[-24,300],[178,-24],[430,-114],[246,-577],[215,-401],[153,-246],[263,-635],[283,-9],[233,-405],[161,-495],[211,-270],[-111,-482],[159,-205],[100,-15]],[[30935,19481],[106,-274],[139,-443],[361,-355],[389,-147],[-125,-296],[-264,-29],[-141,208]],[[31400,18145],[-168,16],[-297,1],[0,1319]],[[33993,32727],[-70,-473],[-74,-607],[3,-588],[-61,-132],[-21,-382]],[[33770,30545],[-19,-308],[353,-506],[-38,-408],[173,-257],[-14,-289],[-267,-757],[-412,-317],[-557,-123],[-305,59],[59,-352],[-57,-442],[51,-298],[-167,-208],[-284,-82],[-267,216],[-108,-155],[39,-587],[188,-178],[152,186],[82,-307],[-255,-183],[-223,-367],[-41,-595],[-66,-316],[-262,-2],[-218,-302],[-80,-443],[273,-433],[266,-119],[-96,-531],[-328,-333],[-180,-692],[-254,-234],[-113,-276],[89,-614],[185,-342],[-117,30]],[[30952,19680],[-257,93],[-672,79],[-115,344],[6,443],[-185,-38],[-98,214],[-24,626],[213,260],[88,375],[-33,299],[148,504],[101,782],[-30,347],[122,112],[-30,223],[-129,118],[92,248],[-126,224],[-65,682],[112,120],[-47,720],[65,605],[75,527],[166,215],[-84,576],[-1,543],[210,386],[-7,494],[159,576],[1,544],[-72,108],[-128,1020],[171,607],[-27,572],[100,537],[182,555],[196,367],[-83,232],[58,190],[-9,985],[302,291],[96,614],[-34,148]],[[31359,37147],[231,534],[364,-144],[163,-427],[109,475],[316,-24],[45,-127]],[[32587,37434],[511,-964],[227,-89],[339,-437],[286,-231],[40,-261],[-273,-898],[280,-160],[312,-91],[220,95],[252,453],[45,521]],[[34826,35372],[138,114],[139,-341],[-6,-472],[-234,-326],[-186,-241],[-314,-573],[-370,-806]],[[31400,18145],[-92,-239],[-238,-183],[-137,19],[-164,48],[-202,177],[-291,86],[-350,330],[-283,317],[-383,662],[229,-124],[390,-395],[369,-212],[143,271],[90,405],[256,244],[198,-70]],[[30669,40193],[136,-402],[37,-426],[146,-250],[-88,-572],[150,-663],[109,-814],[200,81]],[[30952,19680],[-247,4],[-134,-145],[-250,-213],[-45,-552],[-118,-14],[-313,192],[-318,412],[-346,338],[-87,374],[79,346],[-140,393],[-36,1007],[119,568],[293,457],[-422,172],[265,522],[94,982],[309,-208],[145,1224],[-186,157],[-87,-738],[-175,83],[87,845],[95,1095],[127,404],[-80,576],[-22,666],[117,19],[170,954],[192,945],[118,881],[-64,885],[83,487],[-34,730],[163,721],[50,1143],[89,1227],[87,1321],[-20,967],[-58,832]],[[30452,39739],[143,151],[74,303]],[[58538,45652],[-109,60],[-373,-99],[-75,-71],[-79,-377],[62,-261],[-49,-699],[-34,-593],[75,-105],[194,-230],[76,107],[23,-637],[-212,5],[-114,325],[-103,252],[-213,82],[-62,310],[-170,-187],[-222,83],[-93,268],[-176,55],[-131,-15],[-15,184],[-96,15]],[[56642,44124],[-127,35],[-172,-89],[-121,15],[-68,-54],[15,703],[-93,219],[-21,363],[41,356],[-56,228],[-5,372],[-337,-5],[24,213],[-142,-2],[-15,-103],[-172,-23],[-69,-344],[-42,-148],[-154,83],[-91,-83],[-184,-47],[-106,309],[-64,191],[-80,354],[-68,440],[-820,8],[-98,-71],[-80,11],[-115,-79]],[[53422,46976],[-39,183]],[[53383,47159],[71,62],[9,258],[45,152],[101,124]],[[53609,47755],[73,-60],[95,226],[152,-6],[17,-167],[104,-105],[164,370],[161,289],[71,189],[-10,486],[121,574],[127,304],[183,285],[32,189],[7,216],[45,205],[-14,335],[34,524],[55,368],[83,316],[16,357]],[[55125,52650],[25,412],[108,300],[149,190],[229,-200],[177,-218],[203,-59],[207,-115],[83,357],[38,46],[127,-60],[309,295],[110,-125],[90,18],[41,143],[104,51],[209,-62],[178,-14],[91,63]],[[57603,53672],[169,-488],[124,-71],[75,99],[128,-39],[155,125],[66,-252],[244,-393]],[[58564,52653],[-16,-691],[111,-80],[-89,-210],[-107,-157],[-106,-308],[-59,-274],[-15,-475],[-65,-225],[-2,-446]],[[58216,49787],[-80,-165],[-10,-351],[-38,-46],[-26,-323]],[[58062,48902],[70,-268],[17,-713]],[[61551,49585],[-165,488],[-3,2152],[243,670]],[[61626,52895],[76,186],[178,11],[247,417],[362,26],[785,1773]],[[63274,55308],[194,493],[125,363],[0,308],[0,596],[1,244],[2,9]],[[63596,57321],[89,12],[128,88],[147,59],[132,202],[105,2],[6,-163],[-25,-344],[1,-310],[-59,-214],[-78,-639],[-134,-659],[-172,-755],[-238,-866],[-237,-661],[-327,-806],[-278,-479],[-415,-586],[-259,-450],[-304,-715],[-64,-312],[-63,-140]],[[59417,50018],[-3,627],[80,239],[137,391],[101,431],[-123,678],[-32,296],[-132,411]],[[59445,53091],[171,352],[188,390]],[[59804,53833],[145,-99],[0,-332],[95,-194],[193,0],[352,-502],[87,-6],[65,16],[62,-68],[185,-47],[82,247],[254,247],[112,-200],[190,0]],[[61551,49585],[-195,-236],[-68,-246],[-104,-44],[-40,-416],[-89,-238],[-54,-393],[-112,-195]],[[56824,55442],[-212,258],[-96,170],[-18,184],[45,246],[-1,241],[-160,369],[-31,253]],[[56351,57163],[3,143],[-102,174],[-3,343],[-58,228],[-98,-34],[28,217],[72,246],[-32,245],[92,181],[-58,138],[73,365],[127,435],[240,-41],[-14,2345]],[[56621,62148],[3,248],[320,2],[0,1180]],[[56944,63578],[1117,0],[1077,0],[1102,0]],[[60240,63578],[90,-580],[-61,-107],[40,-608],[102,-706],[106,-145],[152,-219]],[[60669,61213],[-141,-337],[-204,-97],[-88,-181],[-27,-393],[-120,-868],[30,-236]],[[60119,59101],[-45,-508],[-112,-582],[-168,-293],[-119,-451],[-28,-241],[-132,-166],[-82,-618],[4,-531]],[[59437,55711],[-3,460],[-39,12],[5,294],[-33,203],[-143,233],[-34,426],[34,436],[-129,41],[-19,-132],[-167,-30],[67,-173],[23,-355],[-152,-324],[-138,-426],[-144,-61],[-233,345],[-105,-122],[-29,-172],[-143,-112],[-9,-122],[-277,0],[-38,122],[-200,20],[-100,-101],[-77,51],[-143,344],[-48,163],[-200,-81],[-76,-274],[-72,-528],[-95,-111],[-85,-65],[189,-230]],[[56351,57163],[-176,-101],[-141,-239],[-201,-645],[-261,-273],[-269,36],[-78,-54],[28,-208],[-145,-207],[-118,-230],[-350,-226],[-69,134],[-46,11],[-52,-152],[-229,-44]],[[54244,54965],[43,160],[-87,407],[-39,245],[-121,100],[-164,345],[60,279],[127,-60],[78,42],[155,-6],[-151,537],[10,393],[-18,392],[-111,378]],[[54026,58177],[28,279],[-178,13],[0,380],[-115,219],[120,778],[354,557],[15,769],[107,1199],[60,254],[-116,203],[-4,188],[-104,153],[-68,919]],[[54125,64088],[280,323],[1108,-1132],[1108,-1131]],[[30080,62227],[24,-321],[-21,-228],[-68,-99],[71,-177],[-5,-161]],[[30081,61241],[-185,100],[-131,-41],[-169,43],[-130,-110],[-149,184],[24,190],[256,-82],[210,-47],[100,131],[-127,256],[2,226],[-175,92],[62,163],[170,-26],[241,-93]],[[30080,62227],[34,101],[217,-3],[165,-152],[73,15],[50,-209],[152,11],[-9,-176],[124,-21],[136,-217],[-103,-240],[-132,128],[-127,-25],[-92,28],[-50,-107],[-106,-37],[-43,144],[-92,-85],[-111,-405],[-71,94],[-14,170]],[[76049,98451],[600,133],[540,-297],[640,-572],[-69,-531],[-606,-73],[-773,170],[-462,226],[-213,423],[-379,117],[722,404]],[[78565,97421],[704,-336],[-82,-240],[-1566,-228],[507,776],[229,66],[208,-38]],[[88563,95563],[734,-26],[1004,-313],[-219,-439],[-1023,16],[-461,-139],[-550,384],[149,406],[366,111]],[[91172,95096],[697,-155],[-321,-234],[-444,53],[-516,233],[66,192],[518,-89]],[[88850,93928],[263,234],[348,54],[394,-226],[34,-155],[-421,-4],[-569,66],[-49,31]],[[62457,98194],[542,107],[422,8],[57,-160],[159,142],[262,97],[412,-129],[-107,-90],[-373,-78],[-250,-45],[-39,-97],[-324,-98],[-301,140],[158,185],[-618,18]],[[56314,82678],[-511,-9],[-342,67]],[[55461,82736],[63,260],[383,191]],[[55907,83187],[291,-103],[123,-94],[-30,-162],[23,-150]],[[64863,94153],[665,518],[-75,268],[621,312],[917,380],[925,110],[475,220],[541,76],[193,-233],[-187,-184],[-984,-293],[-848,-282],[-863,-562],[-414,-577],[-435,-568],[56,-491],[531,-484],[-164,-52],[-907,77],[-74,262],[-503,158],[-40,320],[284,126],[-10,323],[551,503],[-255,73]],[[89698,82309],[96,-569],[-7,-581],[114,-597],[280,-1046],[-411,195],[-171,-854],[271,-605],[-8,-413],[-211,356],[-182,-457],[-51,496],[31,575],[-32,638],[64,446],[13,790],[-163,581],[24,808],[257,271],[-110,274],[123,83],[73,-391]],[[86327,75524],[-39,104]],[[86288,75628],[-2,300],[142,16],[40,698],[-73,506],[238,208],[338,-104],[186,575],[96,647],[107,216],[146,532],[-459,-175],[-240,-233],[-423,1],[-112,555],[-329,420],[-483,189],[-103,579],[-97,363],[-104,254],[-172,596],[-244,217],[-415,176],[-369,-16],[-345,-106],[-229,-294],[152,-141],[4,-326],[-155,-189],[-251,-627],[3,-260],[-392,-373],[-333,223]],[[82410,80055],[-331,-49],[-146,198],[-166,63],[-407,-416],[-366,-98],[-255,-146],[-350,96],[-258,-6],[-168,302],[-272,284],[-279,78],[-351,-78],[-263,-109],[-394,248],[-53,443],[-327,152],[-252,69],[-311,244],[-288,-612],[113,-348],[-270,-411],[-402,148],[-277,22],[-186,276],[-289,8],[-242,182],[-423,-278],[-530,-509],[-292,-102]],[[74375,79706],[-109,-49]],[[63639,77993],[-127,-350],[-269,-97],[-276,-610],[252,-561],[-27,-398],[303,-696]],[[63495,75281],[-166,-238],[-48,-150],[-122,40],[-191,359],[-78,20]],[[62890,75312],[-175,137],[-85,242],[-259,124],[-169,-93],[-48,110],[-378,283],[-409,96],[-235,101],[-34,-70]],[[61098,76242],[-354,499],[-317,223],[-240,347],[202,95],[231,494],[-156,234],[410,241],[-8,129],[-249,-95]],[[60617,78409],[9,262],[143,165],[269,43],[44,197],[-62,326],[113,310],[-3,173],[-410,192],[-162,-6],[-172,277],[-213,-94],[-352,208],[6,116],[-99,256],[-222,29],[-23,183],[70,120],[-178,334],[-288,-57],[-84,30],[-70,-134],[-104,23]],[[58829,81362],[-68,379],[-66,196],[54,55],[224,-20],[108,129],[-80,157],[-187,104],[16,107],[-113,108],[-174,387],[60,159],[-27,277],[-272,141],[-146,-70],[-39,146],[-293,149]],[[57826,83766],[-89,348],[-24,287],[-134,136]],[[57579,84537],[120,187],[-83,551],[198,341],[-42,103]],[[57772,85719],[316,327],[-291,280]],[[57797,86326],[594,755],[258,341],[105,301],[-411,405],[113,385],[-250,440],[187,506],[-323,673],[256,445],[-425,394],[41,414]],[[57942,91385],[224,54],[473,237]],[[58639,91676],[286,206],[456,-358],[761,-140],[1050,-668],[213,-281],[18,-393],[-308,-311],[-454,-157],[-1240,449],[-204,-75],[453,-433],[18,-274],[18,-604],[358,-180],[217,-153],[36,286],[-168,254],[177,224],[672,-368],[233,144],[-186,433],[647,578],[256,-34],[260,-206],[161,406],[-231,352],[136,353],[-204,367],[777,-190],[158,-331],[-351,-73],[1,-328],[219,-203],[429,128],[68,377],[580,282],[970,507],[209,-29],[-273,-359],[344,-61],[199,202],[521,16],[412,245],[317,-356],[315,391],[-291,343],[145,195],[820,-179],[385,-185],[1006,-675],[186,309],[-282,313],[-8,125],[-335,58],[92,280],[-149,461],[-8,189],[512,535],[183,537],[206,116],[736,-156],[57,-328],[-263,-479],[173,-189],[89,-413],[-63,-809],[307,-362],[-120,-395],[-544,-839],[318,-87],[110,213],[306,151],[74,293],[240,281],[-162,336],[130,390],[-304,49],[-67,328],[222,593],[-361,482],[497,398],[-64,421],[139,13],[145,-328],[-109,-570],[297,-108],[-127,426],[465,233],[577,31],[513,-337],[-247,492],[-28,630],[483,119],[669,-26],[602,77],[-226,309],[321,388],[319,16],[540,293],[734,79],[93,162],[729,55],[227,-133],[624,314],[510,-10],[77,255],[265,252],[656,242],[476,-191],[-378,-146],[629,-90],[75,-292],[254,143],[812,-7],[626,-289],[223,-221],[-69,-307],[-307,-175],[-730,-328],[-209,-175],[345,-83],[410,-149],[251,112],[141,-379],[122,153],[444,93],[892,-97],[67,-276],[1162,-88],[15,451],[590,-104],[443,4],[449,-312],[128,-378],[-165,-247],[349,-465],[437,-240],[268,620],[446,-266],[473,159],[538,-182],[204,166],[455,-83],[-201,549],[367,256],[2509,-384],[236,-351],[727,-451],[1122,112],[553,-98],[231,-244],[-33,-432],[342,-168],[372,121],[492,15],[525,-116],[526,66],[484,-526],[344,189],[-224,378],[123,262],[886,-165],[578,36],[799,-282],[-99610,-258],[681,-451],[728,-588],[-24,-367],[187,-147],[-64,429],[754,-88],[544,-553],[-276,-257],[-455,-61],[-7,-578],[-111,-122],[-260,17],[-212,206],[-369,172],[-62,257],[-283,96],[-315,-76],[-151,207],[60,219],[-333,-140],[126,-278],[-158,-251],[99997,-3],[-357,-260],[-360,44],[250,-315],[166,-487],[128,-159],[32,-244],[-71,-157],[-518,129],[-777,-445],[-247,-69],[-425,-415],[-403,-362],[-102,-269],[-397,409],[-724,-464],[-126,219],[-268,-253],[-371,81],[-90,-388],[-333,-572],[10,-239],[316,-132],[-37,-860],[-258,-22],[-119,-494],[116,-255],[-486,-302],[-96,-674],[-415,-144],[-83,-600],[-400,-551],[-103,407],[-119,862],[-155,1313],[134,819],[234,353],[14,276],[432,132],[496,744],[479,608],[499,471],[223,833],[-337,-50],[-167,-487],[-705,-649],[-227,727],[-717,-201],[-696,-990],[230,-362],[-620,-154],[-430,-61],[20,427],[-431,90],[-344,-291],[-850,102],[-914,-175],[-899,-1153],[-1065,-1394],[438,-74],[136,-370],[270,-132],[178,295],[305,-38],[401,-650],[9,-503],[-217,-590],[-23,-705],[-126,-945],[-418,-855],[-94,-409],[-377,-688],[-374,-682],[-179,-349],[-370,-346],[-175,-8],[-175,287],[-373,-432],[-43,-197]],[[0,92833],[36,24],[235,-1],[402,-169],[-24,-81],[-286,-141],[-363,-36],[99694,-30],[-49,187],[-99645,247]],[[59287,77741],[73,146],[198,-127],[89,-23],[36,-117],[42,-18]],[[59725,77602],[2,-51],[136,-142],[284,35],[-55,-210],[-304,-103],[-377,-342],[-154,121],[61,277],[-304,173],[50,113],[265,197],[-42,71]],[[28061,66408],[130,47],[184,-18],[8,-153],[-303,-95],[-19,219]],[[28391,66555],[220,-265],[-48,-420],[-51,75],[4,309],[-124,234],[-1,67]],[[28280,65474],[84,-23],[97,-491],[1,-343],[-68,-29],[-70,340],[-104,171],[60,375]],[[33000,19946],[333,354],[236,-148],[167,237],[222,-266],[-83,-207],[-375,-177],[-125,207],[-236,-266],[-139,266]],[[54206,97653],[105,202],[408,20],[350,-206],[915,-440],[-699,-233],[-155,-435],[-243,-111],[-132,-490],[-335,-23],[-598,361],[252,210],[-416,170],[-541,499],[-216,463],[757,212],[152,-207],[396,8]],[[57942,91385],[117,414],[-356,235],[-431,-200],[-137,-433],[-265,-262],[-298,143],[-362,-29],[-309,312],[-167,-156]],[[55734,91409],[-172,-24],[-41,-389],[-523,95],[-74,-329],[-267,2],[-183,-421],[-278,-655],[-431,-831],[101,-202],[-97,-234],[-275,10],[-180,-554],[17,-784],[177,-300],[-92,-694],[-231,-405],[-122,-341]],[[53063,85353],[-187,363],[-548,-684],[-371,-138],[-384,301],[-99,635],[-88,1363],[256,381],[733,496],[549,609],[508,824],[668,1141],[465,444],[763,741],[610,259],[457,-31],[423,489],[506,-26],[499,118],[869,-433],[-358,-158],[305,-371]],[[57613,97879],[-412,-318],[-806,-70],[-819,98],[-50,163],[-398,11],[-304,271],[858,165],[403,-142],[281,177],[702,-148],[545,-207]],[[56867,96577],[-620,-241],[-490,137],[191,152],[-167,189],[575,119],[110,-222],[401,-134]],[[37010,99398],[932,353],[975,-27],[354,218],[982,57],[2219,-74],[1737,-469],[-513,-227],[-1062,-26],[-1496,-58],[140,-105],[984,65],[836,-204],[540,181],[231,-212],[-305,-344],[707,220],[1348,229],[833,-114],[156,-253],[-1132,-420],[-157,-136],[-888,-102],[643,-28],[-324,-431],[-224,-383],[9,-658],[333,-386],[-434,-24],[-457,-187],[513,-313],[65,-502],[-297,-55],[360,-508],[-617,-42],[322,-241],[-91,-208],[-391,-91],[-388,-2],[348,-400],[4,-263],[-549,244],[-143,-158],[375,-148],[364,-361],[105,-476],[-495,-114],[-214,228],[-344,340],[95,-401],[-322,-311],[732,-25],[383,-32],[-745,-515],[-755,-466],[-813,-204],[-306,-2],[-288,-228],[-386,-624],[-597,-414],[-192,-24],[-370,-145],[-399,-138],[-238,-365],[-4,-415],[-141,-388],[-453,-472],[112,-462],[-125,-488],[-142,-577],[-391,-36],[-410,482],[-556,3],[-269,324],[-186,577],[-481,735],[-141,385],[-38,530],[-384,546],[100,435],[-186,208],[275,691],[418,220],[110,247],[58,461],[-318,-209],[-151,-88],[-249,-84],[-341,193],[-19,401],[109,314],[258,9],[567,-157],[-478,375],[-249,202],[-276,-83],[-232,147],[310,550],[-169,220],[-220,409],[-335,626],[-353,230],[3,247],[-745,346],[-590,43],[-743,-24],[-677,-44],[-323,188],[-482,372],[729,186],[559,31],[-1188,154],[-627,241],[39,229],[1051,285],[1018,284],[107,214],[-750,213],[243,235],[961,413],[404,63],[-115,265],[658,156],[854,93],[853,5],[303,-184],[737,325],[663,-221],[390,-46],[577,-192],[-660,318],[38,253]],[[69148,21851],[179,-186],[263,-74],[9,-112],[-77,-269],[-427,-38],[-7,314],[41,244],[19,121]],[[84713,45326],[32,139],[239,133],[194,20],[87,74],[105,-74],[-102,-160],[-289,-258],[-233,-170]],[[54540,33696],[133,292],[109,-162],[47,-252],[125,-43],[175,-112],[149,43],[248,302],[0,2182]],[[55526,35946],[75,-88],[165,-562],[-26,-360],[62,-207],[199,60],[139,264],[132,177],[68,283],[135,137],[117,-71],[133,-166],[226,-29],[178,138],[28,184],[48,283],[152,47],[83,222],[93,393],[249,442],[393,435]],[[58175,37528],[113,-7],[134,-100],[94,71],[148,-59]],[[58664,37433],[133,-832],[72,-419],[-49,-659],[23,-212]],[[58843,35311],[-140,108],[-80,-42],[-26,-172],[-76,-222],[2,-204],[166,-320],[163,63],[56,263]],[[58908,34785],[211,-5]],[[59119,34780],[-70,-430],[-32,-491],[-72,-267],[-190,-298],[-54,-86],[-118,-300],[-77,-303],[-158,-424],[-314,-609],[-196,-355],[-210,-269],[-290,-229],[-141,-31],[-36,-164],[-169,88],[-138,-113],[-301,114],[-168,-72],[-115,31],[-286,-233],[-238,-94],[-171,-223],[-127,-14],[-117,210],[-94,11],[-120,264],[-13,-82],[-37,159],[2,346],[-90,396],[89,108],[-7,453],[-182,553],[-139,501],[-1,1],[-199,768]],[[58049,33472],[-121,182],[-130,-120],[-151,-232],[-148,-374],[209,-454],[99,59],[51,188],[155,93],[47,192],[85,288],[-96,178]],[[23016,65864],[-107,-518],[-49,-426],[-20,-791],[-27,-289],[48,-322],[86,-288],[56,-458],[184,-440],[65,-337],[109,-291],[295,-157],[114,-247],[244,165],[212,60],[208,106],[175,101],[176,241],[67,345],[22,496],[48,173],[188,155],[294,137],[246,-21],[169,50],[66,-125],[-9,-285],[-149,-351],[-66,-360],[51,-103],[-42,-255],[-69,-461],[-71,152],[-58,-10]],[[25472,61510],[-53,-8],[-99,-357],[-51,70],[-33,-27],[2,-87]],[[25238,61101],[-257,7],[-259,-1],[-1,-333],[-125,-1],[103,-198],[103,-136],[31,-128],[45,-36],[-7,-201],[-357,-2],[-133,-481],[39,-111],[-32,-138],[-7,-172]],[[24381,59170],[-314,636],[-144,191],[-226,155],[-156,-43],[-223,-223],[-140,-58],[-196,156],[-208,112],[-260,271],[-208,83],[-314,275],[-233,282],[-70,158],[-155,35],[-284,187],[-116,270],[-299,335],[-139,373],[-66,288],[93,57],[-29,169],[64,153],[1,204],[-93,266],[-25,235],[-94,298],[-244,587],[-280,462],[-135,368],[-238,241],[-51,145],[42,365],[-142,138],[-164,287],[-69,412],[-149,48],[-162,311],[-130,288],[-12,184],[-149,446],[-99,452],[5,227],[-201,234],[-93,-25],[-159,163],[-44,-240],[46,-284],[27,-444],[95,-243],[206,-407],[46,-139],[42,-42],[37,-203],[49,8],[56,-381],[85,-150],[59,-210],[174,-300],[92,-550],[83,-259],[77,-277],[15,-311],[134,-20],[112,-268],[100,-264],[-6,-106],[-117,-217],[-49,3],[-74,359],[-181,337],[-201,286],[-142,150],[9,432],[-42,320],[-132,183],[-191,264],[-37,-76],[-70,154],[-171,143],[-164,343],[20,44],[115,-33],[103,221],[10,266],[-214,422],[-163,163],[-102,369],[-103,388],[-129,472],[-113,531]],[[33993,32727],[180,63],[279,-457],[103,18],[286,-379],[218,-327],[160,-402],[-122,-280],[77,-334]],[[35174,30629],[-121,-372],[-313,-328],[-205,118],[-151,-63],[-256,253],[-189,-19],[-169,327]],[[34826,35372],[54,341],[38,350],[0,325],[-100,107],[-104,-96],[-103,26],[-33,228],[-26,541],[-52,177],[-187,160],[-114,-116],[-293,113],[18,802],[-82,329]],[[33842,38659],[87,122],[-27,337],[77,259],[49,465],[-66,367],[-151,166],[-30,233],[41,342],[-533,24],[-107,688],[81,10],[-3,255],[-55,172],[-12,342],[-161,175],[-175,-6],[-115,172],[-188,117],[-109,220],[-311,98],[-302,529],[23,396],[-34,227],[29,443],[-363,-100],[-147,-222],[-243,-239],[-62,-179],[-143,-13],[-206,50]],[[30686,44109],[-157,-102],[-126,68],[18,898],[-228,-348],[-245,15],[-105,315],[-184,34],[59,254],[-155,359],[-115,532],[73,108],[0,250],[168,171],[-28,319],[71,206],[20,275],[318,402],[227,114],[37,89],[251,-28]],[[30585,48040],[125,1620],[6,256],[-43,339],[-123,215],[1,430],[156,97],[56,-61],[9,226],[-162,61],[-4,370],[541,-13],[92,203],[77,-187],[55,-349],[52,73]],[[31423,51320],[153,-312],[216,38],[54,181],[206,138],[115,97],[32,250],[198,168],[-15,124],[-235,51],[-39,372],[12,396],[-125,153],[52,55],[206,-76],[221,-148],[80,140],[200,92],[310,221],[102,225],[-37,167]],[[33129,53652],[145,26],[64,-136],[-36,-259],[96,-90],[63,-274],[-77,-209],[-44,-502],[71,-299],[20,-274],[171,-277],[137,-29],[30,116],[88,25],[126,104],[90,157],[154,-50],[67,21]],[[34294,51702],[151,-48],[25,120],[-46,118],[28,171],[112,-53],[131,61],[159,-125]],[[34854,51946],[121,-122],[86,160],[62,-25],[38,-166],[133,42],[107,224],[85,436],[164,540]],[[35650,53035],[95,28],[69,-327],[155,-1033],[149,-97],[7,-408],[-208,-487],[86,-178],[491,-92],[10,-593],[211,388],[349,-212],[462,-361],[135,-346],[-45,-327],[323,182],[540,-313],[415,23],[411,-489],[355,-662],[214,-170],[237,-24],[101,-186],[94,-752],[46,-358],[-110,-977],[-142,-385],[-391,-822],[-177,-668],[-206,-513],[-69,-11],[-78,-435],[20,-1107],[-77,-910],[-30,-390],[-88,-233],[-49,-790],[-282,-771],[-47,-610],[-225,-256],[-65,-355],[-302,2],[-437,-227],[-195,-263],[-311,-173],[-327,-470],[-235,-586],[-41,-441],[46,-326],[-51,-597],[-63,-289],[-195,-325],[-308,-1040],[-244,-468],[-189,-277],[-127,-562],[-183,-337]],[[33842,38659],[-4,182],[-259,302],[-258,9],[-484,-172],[-133,-520],[-7,-318],[-110,-708]],[[30669,40193],[175,638],[-119,496],[63,199],[-49,219],[108,295],[6,503],[13,415],[60,200],[-240,951]],[[30452,39739],[-279,340],[-24,242],[-551,593],[-498,646],[-214,365],[-115,488],[46,170],[-236,775],[-274,1090],[-262,1177],[-114,269],[-87,435],[-216,386],[-198,239],[90,264],[-134,563],[86,414],[221,373]],[[27693,48568],[33,-246],[-79,-141],[8,-216],[114,47],[113,-64],[116,-298],[157,243],[53,398],[170,514],[334,233],[303,619],[86,384],[-38,449]],[[29063,50490],[74,56],[184,-280],[89,-279],[129,-152],[163,-620],[207,-74],[153,157],[101,-103],[166,51],[213,-276],[-179,-602],[83,-14],[139,-314]],[[29063,50490],[-119,140],[-137,195],[-79,-94],[-235,82],[-68,255],[-52,-10],[-278,338]],[[28095,51396],[-37,183],[103,44],[-12,296],[65,214],[138,40],[117,371],[106,310],[-102,141],[52,343],[-62,540],[59,155],[-44,500],[-112,315]],[[28366,54848],[36,287],[89,-43],[52,176],[-64,348],[34,86]],[[28513,55702],[143,-18],[209,412],[114,63],[3,195],[51,500],[159,274],[175,11],[22,123],[218,-49],[218,298],[109,132],[134,285],[98,-36],[73,-156],[-54,-199]],[[30185,57537],[-178,-99],[-71,-295],[-107,-169],[-81,-220],[-34,-422],[-77,-345],[144,-40],[35,-271],[62,-130],[21,-238],[-33,-219],[10,-123],[69,-49],[66,-207],[357,57],[161,-75],[196,-508],[112,63],[200,-32],[158,68],[99,-102],[-50,-318],[-62,-199],[-22,-423],[56,-393],[79,-175],[9,-133],[-140,-294],[100,-130],[74,-207],[85,-589]],[[28366,54848],[-93,170],[-59,319],[68,158],[-70,40],[-52,196],[-138,164],[-122,-38],[-56,-205],[-112,-149],[-61,-20],[-27,-123],[132,-321],[-75,-76],[-40,-87],[-130,-30],[-48,353],[-36,-101],[-92,35],[-56,238],[-114,39],[-72,69],[-119,-1],[-8,-128],[-32,89]],[[26954,55439],[14,117],[23,120],[-10,107],[41,70],[-58,88],[-1,238],[107,53]],[[27070,56232],[100,-212],[-6,-126],[111,-26],[26,48],[77,-145],[136,42],[119,150],[168,119],[95,176],[153,-34],[-10,-58],[155,-21],[124,-102],[90,-177],[105,-164]],[[26954,55439],[-151,131],[-56,124],[32,103],[-11,130],[-77,142],[-109,116],[-95,76],[-19,173],[-73,105],[18,-172],[-55,-141],[-64,164],[-89,58],[-38,120],[2,179],[36,187],[-78,83],[64,114]],[[26191,57131],[42,76],[183,-156],[63,77],[89,-50],[46,-121],[82,-40],[66,126]],[[26762,57043],[70,-321],[108,-238],[130,-252]],[[26191,57131],[-96,186],[-130,238],[-61,200],[-117,185],[-140,267],[31,91],[46,-88],[21,41]],[[25745,58251],[86,25],[35,135],[41,5],[-6,290],[65,14],[58,-4],[60,158],[82,-120],[29,74],[51,70],[97,163],[4,121],[27,-5],[36,141],[29,17],[47,-90],[56,-27],[61,76],[70,0],[97,77],[38,81],[95,-12]],[[26903,59440],[-24,-57],[-14,-132],[29,-216],[-64,-202],[-30,-237],[-9,-261],[15,-152],[7,-266],[-43,-58],[-26,-253],[19,-156],[-56,-151],[12,-159],[43,-97]],[[25745,58251],[-48,185],[-84,51]],[[25613,58487],[19,237],[-38,64],[-57,42],[-122,-70],[-10,79],[-84,95],[-60,118],[-82,50]],[[25179,59102],[58,150],[-22,116],[20,113],[131,166],[127,225]],[[25493,59872],[29,-23],[61,104],[79,8],[26,-48],[43,29],[129,-53],[128,15],[90,66],[32,66],[89,-31],[66,-40],[73,14],[55,51],[127,-82],[44,-13],[85,-110],[80,-132],[101,-91],[73,-162]],[[25613,58487],[-31,-139],[-161,9],[-100,57],[-115,117],[-154,37],[-79,127]],[[24973,58695],[9,86],[95,149],[52,66],[-15,69],[65,37]],[[25238,61101],[-2,-468],[-22,-667],[83,0]],[[25297,59966],[90,-107],[24,88],[82,-75]],[[24973,58695],[-142,103],[-174,11],[-127,117],[-149,244]],[[25472,61510],[1,-87],[53,-3],[-5,-160],[-45,-256],[24,-91],[-29,-212],[18,-56],[-32,-299],[-55,-156],[-50,-19],[-55,-205]],[[30185,57537],[-8,-139],[-163,-69],[91,-268],[-3,-309],[-123,-344],[105,-468],[120,38],[62,427],[-86,208],[-14,447],[346,241],[-38,278],[97,186],[100,-415],[195,-9],[180,-330],[11,-195],[249,-6],[297,61],[159,-264],[213,-74],[155,185],[4,149],[344,35],[333,9],[-236,-175],[95,-279],[222,-44],[210,-291],[45,-473],[144,13],[109,-139]],[[33400,55523],[-220,-347],[-24,-215],[95,-220],[-69,-110],[-171,-95],[5,-273],[-75,-163],[188,-448]],[[33400,55523],[183,-217],[171,-385],[8,-304],[105,-14],[149,-289],[109,-205]],[[34125,54109],[-44,-532],[-169,-154],[15,-139],[-51,-305],[123,-429],[89,-1],[37,-333],[169,-514]],[[34125,54109],[333,-119],[30,107],[225,43],[298,-159]],[[35011,53981],[-144,-508],[22,-404],[109,-351],[-49,-254],[-24,-270],[-71,-248]],[[35011,53981],[95,-65],[204,-140],[294,-499],[46,-242]],[[51718,79804],[131,-155],[400,-109],[-140,-404],[-35,-421]],[[52074,78715],[-77,-101],[-126,54],[9,-150],[-203,-332],[-5,-267],[133,92],[95,-259]],[[51900,77752],[-11,-167],[82,-222],[-97,-180],[72,-457],[151,-75],[-32,-256]],[[52065,76395],[-252,-334],[-548,160],[-404,-192],[-32,-355]],[[50829,75674],[-322,-77],[-313,267],[-101,-127],[-511,268],[-111,230]],[[49471,76235],[144,354],[53,1177],[-287,620],[-205,299],[-424,227],[-28,431],[360,129],[466,-152],[-88,669],[263,-254],[646,461],[84,484],[243,119]],[[50698,80799],[40,-207],[129,-10],[129,-237],[194,-279],[143,46],[243,-269]],[[51576,79843],[62,-52],[80,13]],[[52429,75765],[179,226],[47,-507],[-92,-456],[-126,120],[-64,398],[56,219]],[[27693,48568],[148,442],[-60,258],[-106,-275],[-166,259],[56,167],[-47,536],[97,89],[52,368],[105,381],[-20,241],[153,126],[190,236]],[[31588,61519],[142,-52],[50,-118],[-71,-149],[-209,4],[-163,-21],[-16,253],[40,86],[227,-3]],[[28453,61504],[187,-53],[147,-142],[46,-161],[-195,-11],[-84,-99],[-156,95],[-159,215],[34,135],[116,41],[64,-20]],[[27147,64280],[240,-42],[219,-7],[261,-201],[110,-216],[260,66],[98,-138],[235,-366],[173,-267],[92,8],[165,-120],[-20,-167],[205,-24],[210,-242],[-33,-138],[-185,-75],[-187,-29],[-191,46],[-398,-57],[186,329],[-113,154],[-179,39],[-96,171],[-66,336],[-157,-23],[-259,159],[-83,124],[-362,91],[-97,115],[104,148],[-273,30],[-199,-307],[-115,-8],[-40,-144],[-138,-65],[-118,56],[146,183],[60,213],[126,131],[142,116],[210,56],[67,65]],[[58175,37528],[-177,267],[-215,90],[-82,375],[0,208],[-119,64],[-315,649],[-87,342],[-56,105],[-107,473]],[[57017,40101],[311,-65],[90,-68],[94,13],[154,383],[241,486],[100,46],[33,205],[159,235],[210,81]],[[58409,41417],[18,-220],[232,12],[128,-125],[60,-146],[132,-43],[145,-190],[0,-748],[-54,-409],[-12,-442],[45,-175],[-31,-348],[-42,-53],[-74,-426],[-292,-671]],[[55526,35946],[0,1725],[274,20],[8,2105],[207,19],[428,207],[106,-243],[177,231],[85,2],[156,133]],[[56967,40145],[50,-44]],[[54540,33696],[-207,446],[-108,432],[-62,575],[-68,428],[-93,910],[-7,707],[-35,322],[-108,243],[-144,489],[-146,708],[-60,371],[-226,577],[-17,453]],[[53259,40357],[134,113],[166,100],[180,-17],[166,-267],[42,41],[1126,26],[192,-284],[673,-83],[510,241]],[[56448,40227],[228,134],[180,-34],[109,-133],[2,-49]],[[45357,58612],[-115,460],[-138,210],[122,112],[134,415],[66,304]],[[45426,60113],[96,189],[138,-51],[135,129],[155,6],[133,-173],[184,-157],[168,-435],[184,-405]],[[46619,59216],[13,-368],[54,-338],[104,-166],[24,-229],[-13,-184]],[[46801,57931],[-40,-33],[-151,47],[-21,-66],[-61,-13],[-200,144],[-134,6]],[[46194,58016],[-513,25],[-75,-67],[-92,19],[-147,-96]],[[45367,57897],[-46,453]],[[45321,58350],[253,-13],[67,83],[50,5],[103,136],[119,-124],[121,-11],[120,133],[-56,170],[-92,-99],[-86,3],[-110,145],[-88,-9],[-63,-140],[-302,-17]],[[46619,59216],[93,107],[47,348],[88,14],[194,-165],[157,117],[107,-39],[42,131],[1114,9],[62,414],[-48,73],[-134,2550],[-134,2550],[425,10]],[[48632,65335],[937,-1289],[937,-1289],[66,-277],[173,-169],[129,-96],[3,-376],[308,58]],[[51185,61897],[1,-1361],[-152,-394],[-24,-364],[-247,-94],[-379,-51],[-102,-210],[-178,-23]],[[50104,59400],[-178,-3],[-70,114],[-153,-84],[-259,-246],[-53,-184],[-216,-265],[-38,-152],[-116,-120],[-134,79],[-76,-144],[-41,-405],[-221,-490],[7,-200],[-76,-250],[18,-343]],[[48498,56707],[-114,-88],[-65,-74],[-43,253],[-80,-67],[-48,11],[-51,-172],[-215,5],[-77,89],[-36,-54]],[[47769,56610],[-85,170],[15,176],[-35,69],[-59,-58],[11,192],[57,152],[-114,248],[-33,163],[-62,130],[-55,15],[-67,-83],[-90,-79],[-76,-128],[-119,48],[-77,150],[-46,19],[-73,-78],[-44,-1],[-16,216]],[[47587,66766],[1045,-1431]],[[45426,60113],[-24,318],[78,291],[34,557],[-30,583],[-34,294],[28,295],[-72,281],[-146,255]],[[50747,54278],[-229,-69]],[[50518,54209],[-69,407],[13,1357],[-56,122],[-11,290],[-96,207],[-85,174],[35,311]],[[50249,57077],[96,67],[56,258],[136,56],[61,176]],[[50598,57634],[93,173],[100,2],[212,-340]],[[51003,57469],[-11,-197],[62,-350],[-54,-238],[29,-159],[-135,-366],[-86,-181],[-52,-372],[7,-376],[-16,-952]],[[54026,58177],[-78,-34],[-9,-188]],[[53939,57955],[-52,-13],[-188,647],[-65,24],[-217,-331],[-215,173],[-150,34],[-80,-83],[-163,18],[-164,-252],[-141,-14],[-337,305],[-131,-145],[-142,10],[-104,223],[-279,221],[-298,-70],[-72,-128],[-39,-340],[-80,-238],[-19,-527]],[[50598,57634],[6,405],[-320,134],[-9,286],[-156,386],[-37,269],[22,286]],[[51185,61897],[392,263],[804,1161],[952,1126]],[[53333,64447],[439,-255],[156,-324],[197,220]],[[53939,57955],[110,-235],[-31,-107],[-14,-196],[-234,-457],[-74,-377],[-39,-307],[-59,-132],[-56,-414],[-148,-243],[-43,-299],[-63,-238],[-26,-246],[-191,-199],[-156,243],[-105,-10],[-165,-345],[-81,-6],[-132,-570],[-71,-418]],[[52361,53399],[-289,-213],[-105,31],[-107,-132],[-222,13],[-149,370],[-91,427],[-197,389],[-209,-7],[-245,1]],[[54244,54965],[-140,-599],[-67,-107],[-21,-458],[28,-249],[-23,-176],[132,-309],[23,-212],[103,-305],[127,-190],[12,-269],[29,-172]],[[54447,51919],[-20,-319],[-220,140],[-225,156],[-350,23]],[[53632,51919],[-35,32],[-164,-76],[-169,79],[-132,-38]],[[53132,51916],[-452,13]],[[52680,51929],[40,466],[-108,391],[-127,100],[-56,265],[-72,85],[4,163]],[[50518,54209],[-224,-126]],[[50294,54083],[-62,207],[-74,375],[-22,294],[61,532],[-69,215],[-27,466],[1,429],[-116,305],[20,184]],[[50006,57090],[243,-13]],[[50294,54083],[-436,-346],[-154,-203],[-250,-171],[-248,168]],[[49206,53531],[13,233],[-121,509],[73,667],[117,496],[-74,841]],[[49214,56277],[-38,444],[7,336],[482,27],[123,-43],[90,96],[128,-47]],[[48498,56707],[125,-129],[49,-195],[125,-125],[97,149],[130,22],[190,-152]],[[49206,53531],[-126,-7],[-194,116],[-178,-7],[-329,-103],[-193,-170],[-275,-217],[-54,15]],[[47857,53158],[22,487],[26,74],[-8,233],[-118,247],[-88,40],[-81,162],[60,262],[-28,286],[13,172]],[[47655,55121],[44,0],[17,258],[-22,114],[27,82],[103,71],[-69,473],[-64,245],[23,200],[55,46]],[[47655,55121],[-78,15],[-57,-238],[-78,3],[-55,126],[19,237],[-116,362],[-73,-67],[-59,-13]],[[47158,55546],[-77,-34],[3,217],[-44,155],[9,171],[-60,249],[-78,211],[-222,1],[-65,-112],[-76,-13],[-48,-128],[-32,-163],[-148,-260]],[[46320,55840],[-122,349],[-108,232],[-71,76],[-69,118],[-32,261],[-41,130],[-80,97]],[[45797,57103],[123,288],[84,-11],[73,99],[61,1],[44,78],[-24,196],[31,62],[5,200]],[[45797,57103],[-149,247],[-117,39],[-63,166],[1,90],[-84,125],[-18,127]],[[47857,53158],[-73,-5],[-286,282],[-252,449],[-237,324],[-187,381]],[[46822,54589],[66,189],[15,172],[126,320],[129,276]],[[46822,54589],[-75,44],[-200,238],[-144,316],[-49,216],[-34,437]],[[55125,52650],[-178,33],[-188,99],[-166,-313],[-146,-550]],[[56824,55442],[152,-239],[2,-192],[187,-308],[116,-255],[70,-355],[208,-234],[44,-187]],[[53609,47755],[-104,203],[-84,-100],[-112,-255]],[[53309,47603],[-228,626]],[[53081,48229],[212,326],[-105,391],[95,148],[187,73],[23,261],[148,-283],[245,-25],[85,279],[36,393],[-31,461],[-131,350],[120,684],[-69,117],[-207,-48],[-78,305],[21,258]],[[53081,48229],[-285,596],[-184,488],[-169,610],[9,196],[61,189],[67,430],[56,438]],[[52636,51176],[94,35],[404,-6],[-2,711]],[[52636,51176],[-52,90],[96,663]],[[59099,45126],[131,-264],[71,-501],[-47,-160],[-56,-479],[53,-490],[-87,-205],[-85,-549],[147,-153]],[[59226,42325],[-843,-487],[26,-421]],[[56448,40227],[-181,369],[-188,483],[13,1880],[579,-7],[-24,203],[41,222],[-49,277],[32,286],[-29,184]],[[59599,43773],[-77,-449],[77,-768],[97,9],[100,-191],[116,-427],[24,-760],[-120,-124],[-85,-410],[-181,365],[-21,417],[59,274],[-16,237],[-110,149],[-77,-54],[-159,284]],[[61198,44484],[45,-265],[-11,-588],[34,-519],[11,-923],[49,-290],[-83,-422],[-108,-410],[-177,-366],[-254,-225],[-313,-287],[-313,-634],[-107,-108],[-194,-420],[-115,-136],[-23,-421],[132,-448],[54,-346],[4,-177],[49,29],[-8,-579],[-45,-275],[65,-101],[-41,-245],[-116,-211],[-229,-199],[-334,-320],[-122,-219],[24,-248],[71,-40],[-24,-311]],[[58908,34785],[-24,261],[-41,265]],[[53383,47159],[-74,444]],[[53259,40357],[-26,372],[38,519],[96,541],[15,254],[90,532],[66,243],[159,386],[90,263],[29,438],[-15,335],[-83,211],[-74,358],[-68,355],[15,122],[85,235],[-84,570],[-57,396],[-139,374],[26,115]],[[58062,48902],[169,-46],[85,336],[147,-38]],[[59922,69905],[-49,-186]],[[59873,69719],[-100,82],[-58,-394],[69,-66],[-71,-81],[-12,-156],[131,80]],[[59832,69184],[7,-230],[-139,-944]],[[59700,68010],[-27,153],[-155,862]],[[59518,69025],[80,194],[-19,34],[74,276],[56,446],[40,149],[8,6]],[[59757,70130],[93,-1],[25,104],[75,8]],[[59950,70241],[4,-242],[-38,-90],[6,-4]],[[59757,70130],[99,482],[138,416],[5,21]],[[59999,71049],[125,-31],[45,-231],[-151,-223],[-68,-323]],[[63761,43212],[74,-251],[69,-390],[45,-711],[72,-276],[-28,-284],[-49,-174],[-94,347],[-53,-175],[53,-438],[-24,-250],[-77,-137],[-18,-500],[-109,-689],[-137,-814],[-172,-1120],[-106,-821],[-125,-685],[-226,-140],[-243,-250],[-160,151],[-220,211],[-77,312],[-18,524],[-98,471],[-26,425],[50,426],[128,102],[1,197],[133,447],[25,377],[-65,280],[-52,372],[-23,544],[97,331],[38,375],[138,22],[155,121],[103,107],[122,7],[158,337],[229,364],[83,297],[-38,253],[118,-71],[153,410],[6,356],[92,264],[96,-254]],[[59873,69719],[0,-362],[-41,-173]],[[45321,58350],[36,262]],[[52633,68486],[-118,1061],[-171,238],[-3,143],[-227,352],[-24,445],[171,330],[65,487],[-44,563],[57,303]],[[52339,72408],[302,239],[195,-71],[-9,-299],[236,217],[20,-113],[-139,-290],[-2,-273],[96,-147],[-36,-511],[-183,-297],[53,-322],[143,-10],[70,-281],[106,-92]],[[53191,70158],[-16,-454],[-135,-170],[-86,-189],[-191,-228],[30,-244],[-24,-250],[-136,-137]],[[47592,66920],[-2,700],[449,436],[277,90],[227,159],[107,295],[324,234],[12,438],[161,51],[126,219],[363,99],[51,230],[-73,125],[-96,624],[-17,359],[-104,379]],[[49397,71358],[267,323],[300,102],[175,244],[268,180],[471,105],[459,48],[140,-87],[262,232],[297,5],[113,-137],[190,35]],[[52633,68486],[90,-522],[15,-274],[-49,-482],[21,-270],[-36,-323],[24,-371],[-110,-247],[164,-431],[11,-253],[99,-330],[130,109],[219,-275],[122,-370]],[[59922,69905],[309,-234],[544,630]],[[60775,70301],[112,-720]],[[60887,69581],[-53,-89],[-556,-296],[277,-591],[-92,-101],[-46,-197],[-212,-82],[-66,-213],[-120,-182],[-310,94]],[[59709,67924],[-9,86]],[[64327,64904],[49,29],[11,-162],[217,93],[230,-15],[168,-18],[190,400],[207,379],[176,364]],[[65575,65974],[52,-202]],[[65627,65772],[38,-466]],[[65665,65306],[-142,-3],[-23,-384],[50,-82],[-126,-117],[-1,-241],[-81,-245],[-7,-238]],[[65335,63996],[-56,-125],[-835,298],[-106,599],[-11,136]],[[64113,65205],[-18,430],[75,310],[76,64],[84,-185],[5,-346],[-61,-348]],[[64274,65130],[-77,-42],[-84,117]],[[63326,68290],[58,-261],[-25,-135],[89,-445]],[[63448,67449],[-196,-16],[-69,282],[-248,57]],[[62935,67772],[204,567],[187,-49]],[[60775,70301],[615,614],[105,715],[-26,431],[152,146],[142,369]],[[61763,72576],[119,92],[324,-77],[97,-150],[133,100]],[[62436,72541],[180,-705],[182,-177],[21,-345],[-139,-204],[-65,-461],[193,-562],[340,-324],[143,-449],[-46,-428],[89,0],[3,-314],[153,-311]],[[63490,68261],[-164,29]],[[62935,67772],[-516,47],[-784,1188],[-413,414],[-335,160]],[[65665,65306],[125,-404],[155,-214],[203,-78],[165,-107],[125,-339],[75,-196],[100,-75],[-1,-132],[-101,-352],[-44,-166],[-117,-189],[-104,-404],[-126,31],[-58,-141],[-44,-300],[34,-395],[-26,-72],[-128,2],[-174,-221],[-27,-288],[-63,-125],[-173,5],[-109,-149],[1,-238],[-134,-165],[-153,56],[-186,-199],[-128,-34]],[[64752,60417],[-91,413],[-217,975]],[[64444,61805],[833,591],[185,1182],[-127,418]],[[65575,65974],[80,201],[35,-51],[-26,-244],[-37,-108]],[[96448,41190],[175,-339],[-92,-78],[-93,259],[10,158]],[[96330,41322],[-39,163],[-6,453],[133,-182],[45,-476],[-75,74],[-58,-32]],[[78495,57780],[-66,713],[178,492],[359,112],[261,-84]],[[79227,59013],[229,-232],[126,407],[246,-217]],[[79828,58971],[64,-394],[-34,-708],[-467,-455],[122,-358],[-292,-43],[-240,-238]],[[78981,56775],[-233,87],[-112,307],[-141,611]],[[78495,57780],[-249,271],[-238,-11],[41,464],[-245,-3],[-22,-650],[-150,-863],[-90,-522],[19,-428],[181,-18],[113,-539],[50,-512],[155,-338],[168,-69],[144,-306]],[[78372,54256],[-91,-243],[-183,-71],[-22,304],[-227,258],[-48,-105]],[[77801,54399],[-110,227],[-47,292],[-148,334],[-135,280],[-45,-347],[-53,328],[30,369],[82,566]],[[77375,56448],[135,607],[152,551],[-108,539],[4,274],[-32,330],[-185,470],[-66,296],[96,109],[101,514],[-113,390],[-177,431],[-134,519],[117,107],[127,639],[196,26],[162,256],[159,137]],[[77809,62643],[120,-182],[16,-355],[188,-27],[-68,-623],[6,-530],[293,353],[83,-104],[163,17],[56,205],[210,-40],[211,-480],[18,-583],[224,-515],[-12,-500],[-90,-266]],[[77809,62643],[59,218],[237,384]],[[78105,63245],[25,-139],[148,-16],[-42,676],[144,86]],[[78380,63852],[162,-466],[125,-537],[342,-5],[108,-515],[-178,-155],[-80,-212],[333,-353],[231,-699],[175,-520],[210,-411],[70,-418],[-50,-590]],[[77375,56448],[-27,439],[86,452],[-94,350],[23,644],[-113,306],[-90,707],[-50,746],[-121,490],[-183,-297],[-315,-421],[-156,53],[-172,138],[96,732],[-58,554],[-218,681],[34,213],[-163,76],[-197,481]],[[75657,62792],[-18,476],[97,-90],[6,424]],[[75742,63602],[137,140],[-30,251],[63,201],[11,612],[217,-135],[124,487],[14,288],[153,496],[-8,338],[359,408],[199,-107],[-23,364],[97,108],[-20,224]],[[77035,67277],[162,44],[93,-348],[121,-141],[8,-452],[-11,-487],[-263,-493],[-33,-701],[293,98],[66,-544],[176,-115],[-81,-490],[206,-222],[121,-109],[203,172],[9,-244]],[[78380,63852],[149,145],[221,-3],[271,68],[236,315],[134,-222],[254,-108],[-44,-340],[132,-240],[280,-154]],[[80013,63313],[-371,-505],[-231,-558],[-61,-410],[212,-623],[260,-772],[252,-365],[169,-475],[127,-1093],[-37,-1039],[-232,-389],[-318,-381],[-227,-492],[-346,-550],[-101,378],[78,401],[-206,335]],[[86327,75524],[0,0]],[[86327,75524],[-106,36],[-120,-200],[-83,-202],[10,-424],[-143,-130],[-50,-105],[-104,-174],[-185,-97],[-121,-159],[-9,-256],[-32,-65],[111,-96],[157,-259]],[[85652,73393],[-40,-143],[-118,-39],[-197,-29],[-108,-266],[-124,21],[-17,-54]],[[85048,72883],[-135,112],[-34,-111],[-81,-49],[-10,112],[-72,54],[-75,94],[76,260],[66,69],[-25,108],[71,319],[-18,96],[-163,65],[-131,158]],[[84517,74170],[227,379],[306,318],[191,419],[131,-185],[241,-22],[-44,312],[429,254],[111,331],[179,-348]],[[85652,73393],[240,-697],[68,-383],[3,-681],[-105,-325],[-252,-113],[-222,-245],[-250,-51],[-31,322],[51,443],[-122,615],[206,99],[-190,506]],[[82410,80055],[-135,-446],[-197,-590],[72,-241],[157,74],[274,-92],[214,219],[223,-189],[251,-413],[-30,-210],[-219,66],[-404,-78],[-195,-168],[-204,-391],[-423,-229],[-277,-313],[-286,120],[-156,53],[-146,-381],[89,-227],[45,-195],[-194,-199],[-200,-316],[-324,-208],[-417,-22],[-448,-205],[-324,-318],[-123,184],[-336,-1],[-411,359],[-274,88],[-369,-82],[-574,133],[-306,-14],[-163,351],[-127,544],[-171,66],[-336,368],[-374,83],[-330,101],[-100,256],[107,690],[-192,476],[-396,222],[-233,313],[-73,413]],[[75742,63602],[-147,937],[-76,-2],[-46,-377],[-152,306],[86,336],[124,34],[128,500],[-160,101],[-257,-8],[-265,81],[-24,410],[-133,30],[-220,255],[-98,-401],[200,-313],[-173,-220],[-62,-215],[171,-159],[-47,-356],[96,-444],[43,-486]],[[74730,63611],[-39,-216],[-189,7],[-343,-122],[16,-445],[-148,-349],[-400,-398],[-311,-695],[-209,-373],[-276,-387],[-1,-271],[-138,-146],[-251,-212],[-129,-31],[-84,-450],[58,-769],[15,-490],[-118,-561],[-1,-1004],[-144,-29],[-126,-450],[84,-195],[-253,-168],[-93,-401],[-112,-170],[-263,552],[-128,827],[-107,596],[-97,279],[-148,568],[-69,739],[-48,369],[-253,811],[-115,1145],[-83,756],[1,716],[-54,553],[-404,-353],[-196,70],[-362,716],[133,214],[-82,232],[-326,501]],[[68937,64577],[185,395],[612,-2],[-56,507],[-156,300],[-31,455],[-182,265],[306,619],[323,-45],[290,620],[174,599],[270,593],[-4,421],[236,342],[-224,292],[-96,400],[-99,517],[137,255],[421,-144],[310,88],[268,496]],[[71621,71550],[298,-692],[-28,-482],[111,-303],[-9,-301],[-200,79],[78,-651],[273,-374],[386,-413]],[[72530,68413],[-176,-268],[-108,-553],[269,-224],[262,-289],[362,-332],[381,-76],[160,-301],[215,-56],[334,-138],[231,10],[32,234],[-36,375],[21,255]],[[74477,67050],[170,124],[23,-465]],[[74670,66709],[6,-119],[252,-224],[175,92],[234,-39],[227,17],[20,363],[-113,189]],[[75471,66988],[224,74],[252,439],[321,376],[233,-145],[198,249],[130,-367],[-94,-248],[300,-89]],[[75657,62792],[-79,308],[-16,301],[-53,285],[-116,344],[-256,23],[25,-243],[-87,-329],[-118,120],[-41,-108],[-78,65],[-108,53]],[[74670,66709],[184,439],[150,150],[198,-137],[147,-14],[122,-159]],[[72530,68413],[115,141],[223,-182],[280,-385],[157,-84],[93,-284],[216,-117],[225,-259],[314,-136],[324,-57]],[[68937,64577],[-203,150],[-83,424],[-215,450],[-512,-111],[-451,-11],[-391,-83]],[[67082,65396],[105,687],[400,305],[-23,272],[-133,96],[-7,520],[-266,260],[-112,357],[-137,310]],[[66909,68203],[465,-301],[278,88],[166,-75],[56,129],[194,-52],[361,246],[10,503],[154,334],[207,-1],[31,166],[212,77],[103,-55],[108,166],[-15,355],[118,356],[177,150],[-110,390],[265,-18],[76,213],[-12,227],[139,248],[-32,294],[-66,250],[163,258],[298,124],[319,68],[141,109],[162,67]],[[70877,72519],[205,-276],[82,-454],[457,-239]],[[68841,72526],[85,-72],[201,189],[93,-114],[90,271],[166,-12],[43,86],[29,239],[120,205],[150,-134],[-30,-181],[84,-28],[-26,-496],[110,-194],[97,125],[123,58],[173,265],[192,-44],[286,-1]],[[70827,72688],[50,-169]],[[66909,68203],[252,536],[-23,380],[-210,100],[-22,375],[-91,472],[119,323],[-121,87],[76,430],[113,736]],[[67002,71642],[284,-224],[209,79],[58,268],[219,89],[157,180],[55,472],[234,114],[44,211],[131,-158],[84,-19]],[[69725,74357],[-101,-182],[-303,98],[-26,-340],[301,46],[343,-192],[526,89]],[[70465,73876],[70,-546],[91,59],[169,-134],[-10,-230],[42,-337]],[[72294,75601],[-39,-134],[-438,-320],[-99,-234],[-356,-70],[-105,-378],[-294,80],[-192,-116],[-266,-279],[39,-138],[-79,-136]],[[67002,71642],[-24,498],[-207,21],[-318,523],[-221,65],[-308,299],[-197,55],[-122,-110],[-186,17],[-197,-338],[-244,-114]],[[64978,72558],[-52,417],[40,618],[-216,200],[71,405],[-184,34],[61,498],[262,-145],[244,189],[-202,355],[-80,338],[-224,-151],[-28,-433],[-87,383]],[[62436,72541],[-152,473],[55,183],[-87,678],[190,168]],[[62442,74043],[44,-223],[141,-273],[190,-78]],[[62817,73469],[101,17]],[[62918,73486],[327,436],[104,44],[82,-174],[-95,-292],[173,-309],[69,29]],[[63578,73220],[88,-436],[263,-123],[193,-296],[395,-102],[434,156],[27,139]],[[67082,65396],[-523,179],[-303,136],[-313,76],[-118,725],[-133,105],[-214,-106],[-280,-286],[-339,196],[-281,454],[-267,168],[-186,561],[-205,788],[-149,-96],[-177,196],[-104,-231]],[[59999,71049],[-26,452],[68,243]],[[60041,71744],[74,129],[75,130],[15,329],[91,-115],[306,165],[147,-112],[229,2],[320,222],[149,-10],[316,92]],[[62817,73469],[-113,342],[1,91],[-123,-2],[-82,159],[-58,-16]],[[62442,74043],[-109,172],[-207,147],[27,288],[-47,208]],[[62106,74858],[386,92]],[[62492,74950],[57,-155],[106,-103],[-56,-148],[148,-202],[-78,-189],[118,-160],[124,-97],[7,-410]],[[55734,91409],[371,-289],[433,-402],[8,-910],[93,-230]],[[56639,89578],[-478,-167],[-269,-413],[43,-361],[-441,-475],[-537,-509],[-202,-832],[198,-416],[265,-328],[-255,-666],[-289,-138],[-106,-992],[-157,-554],[-337,57],[-158,-468],[-321,-27],[-89,558],[-232,671],[-211,835]],[[58829,81362],[-239,-35],[-85,-129],[-18,-298],[-111,57],[-250,-28],[-73,138],[-104,-103],[-105,86],[-218,12],[-310,141],[-281,47],[-215,-14],[-152,-160],[-133,-23]],[[56535,81053],[-6,263],[-85,274],[166,121],[2,235],[-77,225],[-12,261]],[[56523,82432],[268,-4],[302,223],[64,333],[228,190],[-26,264]],[[57359,83438],[169,100],[298,228]],[[60617,78409],[-222,-48],[-185,-191],[-260,-31],[-239,-220],[14,-317]],[[59287,77741],[-38,64],[-432,149],[-19,221],[-257,-73],[-103,-325],[-215,-437]],[[58223,77340],[-126,101],[-131,-95],[-124,109]],[[57842,77455],[70,64],[49,203],[76,188],[-20,106],[58,47],[27,-81],[164,-18],[74,44],[-52,60],[19,88],[-97,150],[-40,247],[-101,97],[20,200],[-125,159],[-115,22],[-204,184],[-185,-58],[-66,-87]],[[57394,79070],[-118,0],[-69,-139],[-205,-56],[-95,-91],[-129,144],[-178,3],[-172,65],[-120,-127]],[[56308,78869],[-19,159],[-155,161]],[[56134,79189],[55,238],[77,154]],[[56266,79581],[60,-35],[-71,266],[252,491],[138,69],[29,166],[-139,515]],[[56266,79581],[-264,227],[-200,-84],[-131,61],[-165,-127],[-140,210],[-114,-81],[-16,36]],[[55236,79823],[-127,291],[-207,36],[-26,185],[-191,66],[-41,-153],[-151,122],[17,163],[-207,51],[-132,191]],[[54171,80775],[-114,377],[22,204],[-69,316],[-101,210],[77,158],[-64,300]],[[53922,82340],[189,174],[434,273],[350,200],[277,-100],[21,-144],[268,-7]],[[56314,82678],[142,-64],[67,-182]],[[54716,79012],[-21,-241],[-156,-2],[53,-128],[-92,-380]],[[54500,78261],[-53,-100],[-243,-14],[-140,-134],[-229,45]],[[53835,78058],[-398,153],[-62,205],[-274,-102],[-32,-113],[-169,84]],[[52900,78285],[-142,16],[-125,108],[42,145],[-10,104]],[[52665,78658],[83,33],[141,-164],[39,156],[245,-25],[199,106],[133,-18],[87,-121],[26,100],[-40,385],[100,75],[98,272]],[[53776,79457],[206,-190],[157,242],[98,44],[215,-180],[131,30],[128,-111]],[[54711,79292],[-23,-75],[28,-205]],[[56308,78869],[-170,-123],[-131,-401],[-168,-401],[-223,-111]],[[55616,77833],[-173,26],[-213,-155]],[[55230,77704],[-104,-89],[-229,114],[-208,253],[-88,73]],[[54601,78055],[-54,200],[-47,6]],[[54716,79012],[141,-151],[103,-65],[233,73],[22,118],[111,18],[135,92],[30,-38],[130,74],[66,139],[91,36],[297,-180],[59,61]],[[57842,77455],[-50,270],[30,252],[-9,259],[-160,352],[-89,249],[-86,175],[-84,58]],[[58223,77340],[6,-152],[-135,-128],[-84,56],[-78,-713]],[[57932,76403],[-163,62],[-202,215],[-327,-138],[-138,-150],[-408,31],[-213,92],[-108,-43],[-80,243]],[[56293,76715],[-51,103],[65,99],[-69,74],[-87,-133],[-162,172],[-22,244],[-169,139],[-31,188],[-151,232]],[[55907,83187],[-59,497]],[[55848,83684],[318,181],[466,-38],[273,59],[39,-123],[148,-38],[267,-287]],[[55848,83684],[10,445],[136,371],[262,202],[221,-442],[223,12],[53,453]],[[56753,84725],[237,105],[121,-73],[239,-219],[229,-1]],[[56753,84725],[32,349],[-102,-75],[-176,210],[-24,340],[351,164],[350,86],[301,-97],[287,17]],[[54171,80775],[-124,-62],[-73,68],[-70,-113],[-200,-114],[-103,-147],[-202,-129],[49,-176],[30,-249],[141,-142],[157,-254]],[[52665,78658],[-298,181],[-57,-128],[-236,4]],[[51718,79804],[16,259],[-56,133]],[[51678,80196],[32,400]],[[51710,80596],[-47,619],[167,0],[70,222],[69,541],[-51,200]],[[51918,82178],[54,125],[232,32],[52,-130],[188,291],[-63,222],[-13,335]],[[52368,83053],[210,-78],[178,90]],[[52756,83065],[4,-228],[281,-138],[-3,-210],[283,111],[156,162],[313,-233],[132,-189]],[[57932,76403],[-144,-245],[-101,-422],[89,-337]],[[57776,75399],[-239,79],[-283,-186]],[[57254,75292],[-3,-294],[-252,-56],[-196,206],[-222,-162],[-206,17]],[[56375,75003],[-20,391],[-139,189]],[[56216,75583],[46,84],[-30,70],[47,188],[105,185],[-135,255],[-24,216],[68,134]],[[57302,71436],[-35,-175],[-400,-50],[3,98],[-339,115],[52,251],[152,-199],[216,34],[207,-42],[-7,-103],[151,71]],[[57254,75292],[135,-157],[-86,-369],[-66,-67]],[[57237,74699],[-169,17],[-145,56],[-336,-154],[192,-332],[-141,-96],[-154,-1],[-147,305],[-52,-130],[62,-353],[139,-277],[-105,-129],[155,-273],[137,-171],[4,-334],[-257,157],[82,-302],[-176,-62],[105,-521],[-184,-8],[-228,257],[-104,473],[-49,393],[-108,272],[-143,337],[-18,168]],[[55597,73991],[129,287],[16,192],[91,85],[5,155]],[[55838,74710],[182,53],[106,129],[150,-12],[46,103],[53,20]],[[60041,71744],[-102,268],[105,222],[-169,-51],[-233,136],[-191,-340],[-421,-66],[-225,317],[-300,20],[-64,-245],[-192,-70],[-268,314],[-303,-11],[-165,588],[-203,328],[135,459],[-176,283],[308,565],[428,23],[117,449],[529,-78],[334,383],[324,167],[459,13],[485,-417],[399,-228],[323,91],[239,-53],[328,309]],[[61542,75120],[296,28],[268,-290]],[[57776,75399],[33,-228],[243,-190],[-51,-145],[-330,-33],[-118,-182],[-232,-319],[-87,276],[3,121]],[[55597,73991],[-48,41],[-5,130],[-154,199],[-24,281],[23,403],[38,184],[-47,93]],[[55380,75322],[-18,188],[120,291],[18,-111],[75,52]],[[55575,75742],[59,-159],[66,-60],[19,-214]],[[55719,75309],[-35,-201],[39,-254],[115,-144]],[[55230,77704],[67,-229],[89,-169],[-107,-222]],[[55279,77084],[-126,131],[-192,-8],[-239,98],[-130,-13],[-60,-123],[-99,136],[-59,-245],[136,-277],[61,-183],[127,-221],[106,-130],[105,-247],[246,-224]],[[55155,75778],[-31,-100]],[[55124,75678],[-261,218],[-161,213],[-254,176],[-233,434],[56,45],[-127,248],[-5,200],[-179,93],[-85,-255],[-82,198],[6,205],[10,9]],[[53809,77462],[194,-20],[51,100],[94,-97],[109,-11],[-1,165],[97,60],[27,239],[221,157]],[[52900,78285],[-22,-242],[-122,-100],[-206,75],[-60,-239],[-132,-19],[-48,94],[-156,-200],[-134,-28],[-120,126]],[[51576,79843],[30,331],[72,22]],[[50698,80799],[222,117]],[[50920,80916],[204,-47],[257,123],[176,-258],[153,-138]],[[50920,80916],[143,162],[244,869],[380,248],[231,-17]],[[47490,75324],[101,150],[113,86],[70,-289],[164,0],[47,75],[162,-21],[78,-296],[-129,-160],[-3,-461],[-45,-86],[-11,-280],[-120,-48],[111,-355],[-77,-388],[96,-175],[-38,-161],[-103,-222],[23,-195]],[[47929,72498],[-112,-153],[-146,83],[-143,-65],[42,462],[-26,363],[-124,55],[-67,224],[22,386],[111,215],[20,239],[58,355],[-6,250],[-56,212],[-12,200]],[[47490,75324],[14,420],[-114,257],[393,426],[340,-106],[373,3],[296,-101],[230,31],[449,-19]],[[50829,75674],[15,-344],[-263,-393],[-356,-125],[-25,-199],[-171,-327],[-107,-481],[108,-338],[-160,-263],[-60,-384],[-210,-118],[-197,-454],[-352,-9],[-265,11],[-174,-209],[-106,-223],[-136,49],[-103,199],[-79,340],[-259,92]],[[48278,82406],[46,-422],[-210,-528],[-493,-349],[-393,89],[225,617],[-145,601],[378,463],[210,276]],[[47896,83153],[57,-317],[-57,-317],[172,9],[210,-122]],[[96049,38125],[228,-366],[144,-272],[-105,-142],[-153,160],[-199,266],[-179,313],[-184,416],[-38,201],[119,-9],[156,-201],[122,-200],[89,-166]],[[95032,44386],[78,-203],[-194,4],[-106,363],[166,-142],[56,-22]],[[94910,44908],[-42,-109],[-206,512],[-57,353],[94,0],[100,-473],[111,-283]],[[94680,44747],[-108,-14],[-170,60],[-58,91],[17,235],[183,-93],[91,-124],[45,-155]],[[94344,45841],[65,-187],[12,-119],[-218,251],[-152,212],[-104,197],[41,60],[128,-142],[228,-272]],[[93649,46431],[111,-193],[-56,-33],[-121,134],[-114,243],[14,99],[166,-250]],[[99134,26908],[-105,-319],[-138,-404],[-214,-236],[-48,155],[-116,85],[160,486],[-91,326],[-299,236],[8,214],[201,206],[47,455],[-13,382],[-113,396],[8,104],[-133,244],[-218,523],[-117,418],[104,46],[151,-328],[216,-153],[78,-526],[202,-622],[5,403],[126,-161],[41,-447],[224,-192],[188,-48],[158,226],[141,-69],[-67,-524],[-85,-345],[-212,12],[-74,-179],[26,-254],[-41,-110]],[[97129,24846],[238,310],[167,306],[123,441],[106,149],[41,330],[195,273],[61,-251],[63,-244],[198,239],[80,-249],[0,-249],[-103,-274],[-182,-435],[-142,-238],[103,-284],[-214,-7],[-238,-223],[-75,-387],[-157,-597],[-219,-264],[-138,-169],[-256,13],[-180,194],[-302,42],[-46,217],[149,438],[349,583],[179,111],[200,225]],[[91024,26469],[166,-39],[20,-702],[-95,-203],[-29,-476],[-97,162],[-193,-412],[-57,32],[-171,19],[-171,505],[-38,390],[-160,515],[7,271],[181,-52],[269,-204],[151,81],[217,113]],[[85040,31546],[-294,-303],[-241,-137],[-53,-309],[-103,-240],[-236,-15],[-174,-52],[-246,107],[-199,-64],[-191,-27],[-165,-315],[-81,26],[-140,-167],[-133,-187],[-203,23],[-186,0],[-295,377],[-149,113],[6,338],[138,81],[47,134],[-10,212],[34,411],[-31,350],[-147,598],[-45,337],[12,336],[-111,385],[-7,174],[-123,235],[-35,463],[-158,467],[-39,252],[122,-255],[-93,548],[137,-171],[83,-229],[-5,303],[-138,465],[-26,186],[-65,177],[31,341],[56,146],[38,295],[-29,346],[114,425],[21,-450],[118,406],[225,198],[136,252],[212,217],[126,46],[77,-73],[219,220],[168,66],[42,129],[74,54],[153,-14],[292,173],[151,262],[71,316],[163,300],[13,236],[7,321],[194,502],[117,-510],[119,118],[-99,279],[87,287],[122,-128],[34,449],[152,291],[67,233],[140,101],[4,165],[122,-69],[5,148],[122,85],[134,80],[205,-271],[155,-350],[173,-4],[177,-56],[-59,325],[133,473],[126,155],[-44,147],[121,338],[168,208],[142,-70],[234,111],[-5,302],[-204,195],[148,86],[184,-147],[148,-242],[234,-151],[79,60],[172,-182],[162,169],[105,-51],[65,113],[127,-292],[-74,-316],[-105,-239],[-96,-20],[32,-236],[-81,-295],[-99,-291],[20,-166],[221,-327],[214,-189],[143,-204],[201,-350],[78,1],[145,-151],[43,-183],[265,-200],[183,202],[55,317],[56,262],[34,324],[85,470],[-39,286],[20,171],[-32,339],[37,445],[53,120],[-43,197],[67,313],[52,325],[7,168],[104,222],[78,-289],[19,-371],[70,-71],[11,-249],[101,-300],[21,-335],[-10,-214],[100,-464],[179,223],[92,-250],[133,-231],[-29,-262],[60,-506],[42,-295],[70,-72],[75,-505],[-27,-307],[90,-400],[301,-309],[197,-281],[186,-257],[-37,-143],[159,-371],[108,-639],[111,130],[113,-256],[68,91],[48,-626],[197,-363],[129,-226],[217,-478],[78,-475],[7,-337],[-19,-365],[132,-502],[-16,-523],[-48,-274],[-75,-527],[6,-339],[-55,-423],[-123,-538],[-205,-290],[-102,-458],[-93,-292],[-82,-510],[-107,-294],[-70,-442],[-36,-407],[14,-187],[-159,-205],[-311,-22],[-257,-242],[-127,-229],[-168,-254],[-230,262],[-170,104],[43,308],[-152,-112],[-243,-428],[-240,160],[-158,94],[-159,42],[-269,171],[-179,364],[-52,449],[-64,298],[-137,240],[-267,71],[91,287],[-67,438],[-136,-408],[-247,-109],[146,327],[42,341],[107,289],[-22,438],[-226,-504],[-174,-202],[-106,-470],[-217,243],[9,313],[-174,429],[-147,221],[52,137],[-356,358],[-195,17],[-267,287],[-498,-56],[-359,-211],[-317,-197],[-265,39]],[[72718,55024],[-42,-615],[-116,-168],[-242,-135],[-132,470],[-49,849],[126,959],[192,-328],[129,-416],[134,-616]],[[80409,61331],[-228,183],[-8,509],[137,267],[304,166],[159,-14],[62,-226],[-122,-260],[-64,-341],[-240,-284]],[[84517,74170],[-388,-171],[-204,-277],[-300,-161],[148,274],[-58,230],[220,397],[-147,310],[-242,-209],[-314,-411],[-171,-381],[-272,-29],[-142,-275],[147,-400],[227,-97],[9,-265],[220,-173],[311,422],[247,-230],[179,-15],[45,-310],[-393,-165],[-130,-319],[-270,-296],[-142,-414],[299,-325],[109,-581],[169,-541],[189,-454],[-5,-439],[-174,-161],[66,-315],[164,-184],[-43,-481],[-71,-468],[-155,-53],[-203,-640],[-225,-775],[-258,-705],[-382,-545],[-386,-498],[-313,-68],[-170,-262],[-96,192],[-157,-294],[-388,-296],[-294,-90],[-95,-624],[-154,-35],[-73,429],[66,228],[-373,189],[-131,-96]],[[83826,64992],[-167,-947],[-119,-485],[-146,499],[-32,438],[163,581],[223,447],[127,-176],[-49,-357]],[[53835,78058],[-31,-291],[67,-251]],[[53871,77516],[-221,86],[-226,-210],[15,-293],[-34,-168],[91,-301],[261,-298],[140,-488],[309,-476],[217,3],[68,-130],[-78,-118],[249,-214],[204,-178],[238,-308],[29,-111],[-52,-211],[-154,276],[-242,97],[-116,-382],[200,-219],[-33,-309],[-116,-35],[-148,-506],[-116,-46],[1,181],[57,317],[60,126],[-108,342],[-85,298],[-115,74],[-82,255],[-179,107],[-120,238],[-206,38],[-217,267],[-254,384],[-189,340],[-86,585],[-138,68],[-226,195],[-128,-80],[-161,-274],[-115,-43]],[[54100,73116],[211,51],[-100,-465],[41,-183],[-58,-303],[-213,222],[-141,64],[-387,300],[38,304],[325,-54],[284,64]],[[52419,74744],[139,183],[166,-419],[-39,-782],[-126,38],[-113,-197],[-105,156],[-11,713],[-64,338],[153,-30]],[[52368,83053],[-113,328],[-8,604],[46,159],[80,177],[244,37],[98,163],[223,167],[-9,-304],[-82,-192],[33,-166],[151,-89],[-68,-223],[-83,64],[-200,-425],[76,-288]],[[53436,83731],[88,-296],[-166,-478],[-291,333],[-39,246],[408,195]],[[47896,83153],[233,24],[298,-365],[-149,-406]],[[49140,82132],[1,0],[40,343],[-186,364],[-4,8],[-337,104],[-66,160],[101,264],[-92,163],[-149,-279],[-17,569],[-140,301],[101,611],[216,480],[222,-47],[335,49],[-297,-639],[283,81],[304,-3],[-72,-481],[-250,-530],[287,-38],[22,-62],[248,-697],[190,-95],[171,-673],[79,-233],[337,-113],[-34,-378],[-142,-173],[111,-305],[-250,-310],[-371,6],[-473,-163],[-130,116],[-183,-276],[-257,67],[-195,-226],[-148,118],[407,621],[249,127],[-2,1],[-434,98],[-79,235],[291,183],[-152,319],[52,387],[413,-54]],[[45969,89843],[-64,-382],[314,-403],[-361,-451],[-801,-405],[-240,-107],[-365,87],[-775,187],[273,261],[-605,289],[492,114],[-12,174],[-583,137],[188,385],[421,87],[433,-400],[422,321],[349,-167],[453,315],[461,-42]],[[63495,75281],[146,-311],[141,-419],[130,-28],[85,-159],[-228,-47],[-49,-459],[-48,-207],[-101,-138],[7,-293]],[[62492,74950],[68,96],[207,-169],[149,-36],[38,70],[-136,319],[72,82]],[[61542,75120],[42,252],[-70,403],[-160,218],[-154,68],[-102,181]],[[83564,58086],[-142,450],[238,-22],[97,-213],[-74,-510],[-119,295]],[[84051,56477],[70,165],[30,367],[153,35],[-44,-398],[205,570],[-26,-563],[-100,-195],[-87,-373],[-87,-175],[-171,409],[57,158]],[[85104,55551],[28,-392],[16,-332],[-94,-540],[-102,602],[-130,-300],[89,-435],[-79,-277],[-327,343],[-78,428],[84,280],[-176,280],[-87,-245],[-131,23],[-205,-330],[-46,173],[109,498],[175,166],[151,223],[98,-268],[212,162],[45,264],[196,15],[-16,457],[225,-280],[23,-297],[20,-218]],[[82917,56084],[-369,-561],[136,414],[200,364],[167,409],[146,587],[49,-482],[-183,-325],[-146,-406]],[[83982,61347],[-46,-245],[95,-423],[-73,-491],[-164,-196],[-43,-476],[62,-471],[147,-65],[123,70],[347,-328],[-27,-321],[91,-142],[-29,-272],[-216,290],[-103,310],[-71,-217],[-177,354],[-253,-87],[-138,130],[14,244],[87,151],[-83,136],[-36,-213],[-137,340],[-41,257],[-11,566],[112,-195],[29,925],[90,535],[169,-1],[171,-168],[85,153],[26,-150]],[[83899,57324],[-43,282],[166,-183],[177,1],[-5,-247],[-129,-251],[-176,-178],[-10,275],[20,301]],[[84861,57766],[78,-660],[-214,157],[5,-199],[68,-364],[-132,-133],[-11,416],[-84,31],[-43,357],[163,-47],[-4,224],[-169,451],[266,-13],[77,-220]],[[78372,54256],[64,-56],[164,-356],[116,-396],[16,-398],[-29,-269],[27,-203],[20,-349],[98,-163],[109,-523],[-5,-199],[-197,-40],[-263,438],[-329,469],[-32,301],[-161,395],[-38,489],[-100,322],[30,431],[-61,250]],[[80461,51765],[204,-202],[214,110],[56,500],[119,112],[333,128],[199,467],[137,374]],[[81723,53254],[126,-307],[58,202],[133,-19],[16,377],[13,291]],[[82069,53798],[214,411],[140,462],[112,2],[143,-299],[13,-257],[183,-165],[231,-177],[-20,-232],[-186,-29],[50,-289],[-205,-201]],[[81723,53254],[110,221],[236,323]],[[53809,77462],[62,54]],[[57797,86326],[-504,-47],[-489,-216],[-452,-125],[-161,323],[-269,193],[62,582],[-135,533],[133,345],[252,371],[635,640],[185,124],[-28,250],[-387,279]],[[54711,79292],[39,130],[123,-10],[95,61],[7,55],[54,28],[18,134],[64,26],[43,106],[82,1]],[[60669,61213],[161,-684],[77,-542],[152,-288],[379,-558],[154,-336],[151,-341],[87,-203],[136,-178]],[[61966,58083],[-83,-144],[-119,51]],[[61764,57990],[-95,191],[-114,346],[-124,190],[-71,204],[-242,237],[-191,7],[-67,124],[-163,-139],[-168,268],[-87,-441],[-323,124]],[[89411,73729],[-256,-595],[4,-610],[-104,-472],[48,-296],[-145,-416],[-355,-278],[-488,-36],[-396,-675],[-186,227],[-12,442],[-483,-130],[-329,-279],[-325,-11],[282,-435],[-186,-1004],[-179,-248],[-135,229],[69,533],[-176,172],[-113,405],[263,182],[145,371],[280,306],[203,403],[553,177],[297,-121],[291,1050],[185,-282],[408,591],[158,229],[174,723],[-47,664],[117,374],[295,108],[152,-819],[-9,-479]],[[90169,76553],[197,250],[62,-663],[-412,-162],[-244,-587],[-436,404],[-152,-646],[-308,-9],[-39,587],[138,455],[296,33],[81,817],[83,460],[326,-615],[213,-198],[195,-126]],[[86769,70351],[154,352],[158,-68],[114,248],[204,-127],[35,-203],[-156,-357],[-114,189],[-143,-137],[-73,-346],[-181,168],[2,281]],[[64752,60417],[-201,-158],[-54,-263],[-6,-201],[-277,-249],[-444,-276],[-249,-417],[-122,-33],[-83,35],[-163,-245],[-177,-114],[-233,-30],[-70,-34],[-61,-156],[-73,-43],[-43,-150],[-137,13],[-89,-80],[-192,30],[-72,345],[8,323],[-46,174],[-54,437],[-80,243],[56,29],[-29,270],[34,114],[-12,257]],[[61883,60238],[121,189],[-28,249],[74,290],[114,-153],[75,53],[321,14],[50,-59],[269,-60],[106,30],[70,-197],[130,99],[199,620],[259,266],[801,226]],[[63448,67449],[109,-510],[137,-135],[47,-207],[190,-249],[16,-243],[-27,-197],[35,-199],[80,-165],[37,-194],[41,-145]],[[64274,65130],[53,-226]],[[61883,60238],[-37,252],[-83,178],[-22,236],[-143,212],[-148,495],[-79,482],[-192,406],[-124,97],[-184,563],[-32,411],[12,350],[-159,655],[-130,231],[-150,122],[-92,339],[15,133],[-77,306],[-81,132],[-108,440],[-170,476],[-141,406],[-139,-3],[44,325],[12,206],[34,236]],[[36483,4468],[141,0],[414,127],[419,-127],[342,-255],[120,-359],[33,-254],[11,-301],[-430,-186],[-452,-150],[-522,-139],[-582,-116],[-658,35],[-365,197],[49,243],[593,162],[239,197],[174,254],[126,220],[168,209],[180,243]],[[31586,3163],[625,-23],[599,-58],[207,243],[147,208],[288,-243],[-82,-301],[-81,-266],[-582,81],[-621,-35],[-348,197],[0,23],[-152,174]],[[29468,8472],[190,70],[321,-23],[82,301],[16,219],[-6,475],[158,278],[256,93],[147,-220],[65,-220],[120,-267],[92,-254],[76,-267],[33,-266],[-49,-231],[-76,-220],[-326,-81],[-311,-116],[-364,11],[136,232],[-327,-81],[-310,-81],[-212,174],[-16,243],[305,231]],[[21575,8103],[174,104],[353,-81],[403,-46],[305,-81],[304,69],[163,-335],[-217,46],[-337,-23],[-343,23],[-376,-35],[-283,116],[-146,243]],[[15938,7061],[60,197],[332,-104],[359,-93],[332,104],[-158,-208],[-261,-151],[-386,47],[-278,208]],[[14643,7177],[202,127],[277,-139],[425,-231],[-164,23],[-359,58],[-381,162]],[[4524,4144],[169,220],[517,-93],[277,-185],[212,-209],[76,-266],[-533,-81],[-364,208],[-163,209],[-11,35],[-180,162]],[[0,529],[16,-5],[245,344],[501,-185],[32,21],[294,188],[38,-7],[32,-4],[402,-246],[352,246],[63,34],[816,104],[265,-138],[130,-71],[419,-196],[789,-151],[625,-185],[1072,-139],[800,162],[1181,-116],[669,-185],[734,174],[773,162],[60,278],[-1094,23],[-898,139],[-234,231],[-745,128],[49,266],[103,243],[104,220],[-55,243],[-462,162],[-212,209],[-430,185],[675,-35],[642,93],[402,-197],[495,173],[457,220],[223,197],[-98,243],[-359,162],[-408,174],[-571,35],[-500,81],[-539,58],[-180,220],[-359,185],[-217,208],[-87,672],[136,-58],[250,-185],[457,58],[441,81],[228,-255],[441,58],[370,127],[348,162],[315,197],[419,58],[-11,220],[-97,220],[81,208],[359,104],[163,-196],[425,115],[321,151],[397,12],[375,57],[376,139],[299,128],[337,127],[218,-35],[190,-46],[414,81],[370,-104],[381,11],[364,81],[375,-57],[414,-58],[386,23],[403,-12],[413,-11],[381,23],[283,174],[337,92],[349,-127],[331,104],[300,208],[179,-185],[98,-208],[180,-197],[288,174],[332,-220],[375,-70],[321,-162],[392,35],[354,104],[418,-23],[376,-81],[381,-104],[147,254],[-180,197],[-136,209],[-359,46],[-158,220],[-60,220],[-98,440],[213,-81],[364,-35],[359,35],[327,-93],[283,-174],[119,-208],[376,-35],[359,81],[381,116],[342,70],[283,-139],[370,46],[239,451],[224,-266],[321,-104],[348,58],[228,-232],[365,-23],[337,-69],[332,-128],[218,220],[108,209],[278,-232],[381,58],[283,-127],[190,-197],[370,58],[288,127],[283,151],[337,81],[392,69],[354,81],[272,127],[163,186],[65,254],[-32,244],[-87,231],[-98,232],[-87,231],[-71,209],[-16,231],[27,232],[130,220],[109,243],[44,231],[-55,255],[-32,232],[136,266],[152,173],[180,220],[190,186],[223,173],[109,255],[152,162],[174,151],[267,34],[174,186],[196,115],[228,70],[202,150],[157,186],[218,69],[163,-151],[-103,-196],[-283,-174],[-120,-127],[-206,92],[-229,-58],[-190,-139],[-202,-150],[-136,-174],[-38,-231],[17,-220],[130,-197],[-190,-139],[-261,-46],[-153,-197],[-163,-185],[-174,-255],[-44,-220],[98,-243],[147,-185],[229,-139],[212,-185],[114,-232],[60,-220],[82,-232],[130,-196],[82,-220],[38,-544],[81,-220],[22,-232],[87,-231],[-38,-313],[-152,-243],[-163,-197],[-370,-81],[-125,-208],[-169,-197],[-419,-220],[-370,-93],[-348,-127],[-376,-128],[-223,-243],[-446,-23],[-489,23],[-441,-46],[-468,0],[87,-232],[424,-104],[311,-162],[174,-208],[-310,-185],[-479,58],[-397,-151],[-17,-243],[-11,-232],[327,-196],[60,-220],[353,-220],[588,-93],[500,-162],[398,-185],[506,-186],[690,-92],[681,-162],[473,-174],[517,-197],[272,-278],[136,-220],[337,209],[457,173],[484,186],[577,150],[495,162],[691,12],[680,-81],[560,-139],[180,255],[386,173],[702,12],[550,127],[522,128],[577,81],[614,104],[430,150],[-196,209],[-119,208],[0,220],[-539,-23],[-571,-93],[-544,0],[-77,220],[39,440],[125,128],[397,138],[468,139],[337,174],[337,174],[251,231],[380,104],[376,81],[190,47],[430,23],[408,81],[343,116],[337,139],[305,139],[386,185],[245,197],[261,173],[82,232],[-294,139],[98,243],[185,185],[288,116],[305,139],[283,185],[217,232],[136,277],[202,163],[331,-35],[136,-197],[332,-23],[11,220],[142,231],[299,-58],[71,-220],[331,-34],[360,104],[348,69],[315,-34],[120,-243],[305,196],[283,105],[315,81],[310,81],[283,139],[310,92],[240,128],[168,208],[207,-151],[288,81],[202,-277],[157,-209],[316,116],[125,232],[283,162],[365,-35],[108,-220],[229,220],[299,69],[326,23],[294,-11],[310,-70],[300,-34],[130,-197],[180,-174],[304,104],[327,24],[315,0],[310,11],[278,81],[294,70],[245,162],[261,104],[283,58],[212,162],[152,324],[158,197],[288,-93],[109,-208],[239,-139],[289,46],[196,-208],[206,-151],[283,139],[98,255],[250,104],[289,197],[272,81],[326,116],[218,127],[228,139],[218,127],[261,-69],[250,208],[180,162],[261,-11],[229,139],[54,208],[234,162],[228,116],[278,93],[256,46],[244,-35],[262,-58],[223,-162],[27,-254],[245,-197],[168,-162],[332,-70],[185,-162],[229,-162],[266,-35],[223,116],[240,243],[261,-127],[272,-70],[261,-69],[272,-46],[277,0],[229,-614],[-11,-150],[-33,-267],[-266,-150],[-218,-220],[38,-232],[310,12],[-38,-232],[-141,-220],[-131,-243],[212,-185],[321,-58],[321,104],[153,232],[92,220],[153,185],[174,174],[70,208],[147,289],[174,58],[316,24],[277,69],[283,93],[136,231],[82,220],[190,220],[272,151],[234,115],[153,197],[157,104],[202,93],[277,-58],[250,58],[272,69],[305,-34],[201,162],[142,393],[103,-162],[131,-278],[234,-115],[266,-47],[267,70],[283,-46],[261,-12],[174,58],[234,-35],[212,-127],[250,81],[300,0],[255,81],[289,-81],[185,197],[141,196],[191,163],[348,439],[179,-81],[212,-162],[185,-208],[354,-359],[272,-12],[256,0],[299,70],[299,81],[229,162],[190,174],[310,23],[207,127],[218,-116],[141,-185],[196,-185],[305,23],[190,-150],[332,-151],[348,-58],[288,47],[218,185],[185,185],[250,46],[251,-81],[288,-58],[261,93],[250,0],[245,-58],[256,-58],[250,104],[299,93],[283,23],[316,0],[255,58],[251,46],[76,290],[11,243],[174,-162],[49,-266],[92,-244],[115,-196],[234,-105],[315,35],[365,12],[250,35],[364,0],[262,11],[364,-23],[310,-46],[196,-186],[-54,-220],[179,-173],[299,-139],[310,-151],[360,-104],[375,-92],[283,-93],[315,-12],[180,197],[245,-162],[212,-185],[245,-139],[337,-58],[321,-69],[136,-232],[316,-139],[212,-208],[310,-93],[321,12],[299,-35],[332,12],[332,-47],[310,-81],[288,-139],[289,-116],[195,-173],[-32,-232],[-147,-208],[-125,-266],[-98,-209],[-131,-243],[-364,-93],[-163,-208],[-360,-127],[-125,-232],[-190,-220],[-201,-185],[-115,-243],[-70,-220],[-28,-266],[6,-220],[158,-232],[60,-220],[130,-208],[517,-81],[109,-255],[-501,-93],[-424,-127],[-528,-23],[-234,-336],[-49,-278],[-119,-220],[-147,-220],[370,-196],[141,-244],[239,-219],[338,-197],[386,-186],[419,-185],[636,-185],[142,-289],[800,-128],[53,-45],[208,-175],[767,151],[636,-186],[479,-142],[-99999,0]],[[59092,71341],[19,3],[40,143],[200,-8],[253,176],[-188,-251],[21,-111]],[[59437,71293],[-30,21],[-53,-45],[-42,12],[-14,-22],[-5,59],[-20,37],[-54,6],[-75,-51],[-52,31]],[[59437,71293],[8,-48],[-285,-240],[-136,77],[-64,237],[132,22]],[[45272,63236],[13,274],[106,161],[91,308],[-18,200],[96,417],[155,376],[93,95],[74,344],[6,315],[100,365],[185,216],[177,603],[5,8],[139,227],[259,65],[218,404],[140,158],[232,493],[-70,735],[106,508],[37,312],[179,399],[278,270],[206,244],[186,612],[87,362],[205,-2],[167,-251],[264,41],[288,-131],[121,-6]],[[56944,63578],[0,2175],[0,2101],[-83,476],[71,365],[-43,253],[101,283]],[[56990,69231],[369,10],[268,-156],[275,-175],[129,-92],[214,188],[114,169],[245,49],[198,-75],[75,-293],[65,193],[222,-140],[217,-33],[137,149]],[[59700,68010],[-78,-238],[-60,-446],[-75,-308],[-65,-103],[-93,191],[-125,263],[-198,847],[-29,-53],[115,-624],[171,-594],[210,-920],[102,-321],[90,-334],[249,-654],[-55,-103],[9,-384],[323,-530],[49,-121]],[[53191,70158],[326,-204],[117,51],[232,-98],[368,-264],[130,-526],[250,-114],[391,-248],[296,-293],[136,153],[133,272],[-65,452],[87,288],[200,277],[192,80],[375,-121],[95,-264],[104,-2],[88,-101],[276,-70],[68,-195]],[[59804,53833],[-164,643],[-127,137],[-48,236],[-141,288],[-171,42],[95,337],[147,14],[42,181]],[[61764,57990],[-98,-261],[-94,-277],[22,-163],[4,-180],[155,-10],[67,42],[62,-106]],[[61882,57035],[-61,-209],[103,-325],[102,-285],[106,-210],[909,-702],[233,4]],[[61966,58083],[66,-183],[-9,-245],[-158,-142],[119,-161]],[[61984,57352],[-102,-317]],[[61984,57352],[91,-109],[54,-245],[125,-247],[138,-2],[262,151],[302,70],[245,184],[138,39],[99,108],[158,20]],[[58449,49909],[-166,-182],[-67,60]],[[58564,52653],[115,161],[176,-132],[224,138],[195,-1],[171,272]],[[55279,77084],[100,2],[-69,-260],[134,-227],[-41,-278],[-65,-27]],[[55338,76294],[-52,-53],[-90,-138],[-41,-325]],[[55719,75309],[35,-5],[13,121],[164,91],[62,23]],[[55993,75539],[95,35],[128,9]],[[55993,75539],[-9,44],[33,71],[31,144],[-39,-4],[-54,110],[-46,28],[-36,94],[-52,36],[-40,84],[-50,-33],[-38,-196],[-66,-43]],[[55627,75874],[22,51],[-106,123],[-91,63],[-40,82],[-74,101]],[[55380,75322],[-58,46],[-78,192],[-120,118]],[[55627,75874],[-52,-132]],[[32866,56937],[160,77],[58,-21],[-11,-440],[-232,-65],[-50,53],[81,163],[-6,233]]],"bbox":[-180,-85.60903777459771,180,83.64513000000001],"transform":{"scale":[0.0036000360003600037,0.0016925586033320105],"translate":[-180,-85.60903777459771]}}diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svgnew file mode 100644index 0000000..324541f--- /dev/null+++ b/frontend/public/favicon.svg@@ -0,0 +1,19 @@+<!--+ Snitch favicon.+ EN: Amber dot at the center of a white sphere ring with satellite nodes —+ the same mark as the splash screen and app icon.+ FR: Point ambre au centre d'un anneau de sphère blanc avec des nœuds+ satellites — le même emblème que le splash et l'icône de l'app.+-->+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">+ <rect width="64" height="64" rx="14" fill="#000000"/>+ <circle cx="32" cy="32" r="22" fill="none" stroke="#ffffff" stroke-opacity="0.7" stroke-width="2"/>+ <ellipse cx="32" cy="32" rx="22" ry="8" fill="none" stroke="#ffffff" stroke-opacity="0.2" stroke-width="1"/>+ <ellipse cx="32" cy="32" rx="8" ry="22" fill="none" stroke="#ffffff" stroke-opacity="0.2" stroke-width="1"/>+ <circle cx="14" cy="16" r="2.5" fill="#f7b016"/>+ <circle cx="50" cy="18" r="2.5" fill="#f7b016"/>+ <circle cx="52" cy="44" r="2.5" fill="#f7b016"/>+ <circle cx="12" cy="42" r="2.5" fill="#f7b016"/>+ <circle cx="32" cy="32" r="7" fill="#f7b016"/>+ <circle cx="32" cy="32" r="3" fill="#ffffff"/>+</svg>diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxnew file mode 100644index 0000000..2711266--- /dev/null+++ b/frontend/src/App.jsx@@ -0,0 +1,799 @@+/**+ * Snitch — root application component.+ *+ * EN: Owns the top-level layout (sidebar | main view | timeline) and the+ * toolbar (language toggle, view switch, export, filters, capture+ * start/stop, alerts, status). All realtime state comes from+ * `useWebSocket`; UI-only state (selected node, view, panel toggles)+ * lives here.+ * FR: Définit la mise en page principale (barre latérale | vue centrale |+ * timeline) et la barre d'outils (sélecteur de langue, changement de vue,+ * export, filtres, start/stop capture, alertes, statut). Tout l'état temps+ * réel vient de `useWebSocket` ; l'état purement UI (nœud sélectionné,+ * vue, panneaux) vit ici.+ */+import { useState, useMemo, useRef, useEffect } from 'react'+import { Hexagon, Globe, Wifi, Smartphone, Monitor, Cpu, ShieldCheck, Radio, Zap, HelpCircle, AlertTriangle, Square, Play, Filter, Mic, Camera, Download, ShieldOff } from 'lucide-react'+import ForceGraph from './graph/ForceGraph'+import MapView from './map/MapView'+import Sidebar from './components/Sidebar'+import { AlertBell, AlertPanel, AlertToasts } from './components/AlertPanel'+import Timeline from './components/Timeline'+import { useWebSocket } from './hooks/useWebSocket'+import { computePrivacyScore } from './scoring/privacy'+import { WS_URL } from './api'+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 [selected, setSelected] = useState(null)+ const [view, setView] = useState('graph')+ const [showAlerts, setShowAlerts] = useState(false)+ const [filter, setFilter] = useState({ text: '', category: 'all' })++ // EN: Node ids that currently have at least one alert — drives the red glow.+ // FR: Ids des nœuds ayant au moins une alerte — pilote le halo rouge.+ const alertedNodes = useMemo(() =>+ new Set(alerts.map(a => a.node_id).filter(Boolean)),+ [alerts]+ )++ // EN: When processes are excluded, hide nodes whose traffic comes ONLY from+ // excluded apps — keeps the graph honest about what's filtered.+ // FR: Quand des processus sont exclus, masquer les nœuds dont le trafic vient+ // UNIQUEMENT d'apps exclues — le graphe reflète honnêtement le filtre.+ const filteredNodes = useMemo(() => {+ if (excludedProcesses.length === 0) return nodes+ const out = {}+ for (const [id, node] of Object.entries(nodes)) {+ if (id === 'local') { out[id] = node; continue }+ const procs = node.processes ? Object.keys(node.processes) : []+ if (procs.length > 0 && procs.every(p => excludedProcesses.includes(p))) continue+ out[id] = node+ }+ return out+ }, [nodes, excludedProcesses])++ const filteredEdges = useMemo(() => {+ if (excludedProcesses.length === 0) return edges+ const visibleIds = new Set([...Object.keys(filteredNodes), ...Object.keys(lanDevices)])+ const out = {}+ for (const [id, edge] of Object.entries(edges)) {+ if (visibleIds.has(edge.source) && visibleIds.has(edge.target)) out[id] = edge+ }+ return out+ }, [edges, filteredNodes, lanDevices, excludedProcesses])++ const filteredPackets = useMemo(() =>+ excludedProcesses.length === 0+ ? packets+ : packets.filter(p => !p.process || !excludedProcesses.includes(p.process)),+ [packets, excludedProcesses]+ )++ const privacyScore = useMemo(() =>+ computePrivacyScore(nodes, alerts),+ [nodes, alerts]+ )++ function handleBell() {+ setShowAlerts(v => !v)+ clearUnread()+ }++ function handleWhitelist(ip) {+ if (!ip || whitelistedIps.includes(ip)) return+ updateIpWhitelist([...whitelistedIps, ip])+ setSelected(null)+ }++ return (+ <div style={{ display: 'flex', height: '100vh', width: '100vw', overflow: 'hidden' }}>+ <Sidebar+ nodes={filteredNodes}+ lanDevices={lanDevices}+ packets={filteredPackets}+ selected={selected}+ onClose={() => setSelected(null)}+ privacyScore={privacyScore}+ bandwidth={bandwidth}+ filter={filter}+ onFilterChange={setFilter}+ onWhitelist={handleWhitelist}+ />++ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ <div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>+ {view === 'graph' && (+ <ForceGraph+ nodes={filteredNodes}+ edges={filteredEdges}+ lanDevices={lanDevices}+ alertedNodes={alertedNodes}+ onNodeClick={setSelected}+ filter={filter}+ />+ )}+ {view === 'map' && (+ <MapView nodes={filteredNodes} onNodeClick={setSelected} />+ )}++ {/* EN: Top-right toolbar / FR: Barre d'outils en haut à droite */}+ <div style={{+ position: 'absolute', top: 16, right: 16,+ display: 'flex', alignItems: 'center', gap: 8,+ }}>+ <MediaBadge media={media} />+ <LangToggle />+ <ViewToggle view={view} onChange={setView} />+ <ExportButton nodes={nodes} edges={edges} lanDevices={lanDevices} alerts={alerts} />+ <ProcessFilter excluded={excludedProcesses} onChange={updateProcessFilter} nodes={nodes} />+ <PortFilter ports={portFilter} onUpdate={updatePortFilter} />+ <IPWhitelist ips={whitelistedIps} onUpdate={updateIpWhitelist} />+ <CaptureToggle capturing={capturing} onToggle={toggleCapture} />+ <AlertBell unread={unread} onClick={handleBell} />+ <StatusBadge status={status} lanCount={Object.keys(lanDevices).length} />+ </div>++ {showAlerts && (+ <AlertPanel alerts={alerts} onClose={() => setShowAlerts(false)} />+ )}++ {/* EN: Floating toasts for warning/critical alerts.+ FR: Toasts flottants pour les alertes warning/critiques. */}+ <AlertToasts alerts={alerts.filter(a => a.severity !== 'info').slice(0, 3)} />++ {view === 'graph' && <Legend />}+ </div>++ <Timeline />+ </div>+ </div>+ )+}++// ── Export helpers / Aides d'export ──────────────────────────────────────────++/** EN: Trigger a browser download of a text payload. / FR: Déclencher un téléchargement navigateur d'un contenu texte. */+function downloadFile(content, filename) {+ const a = document.createElement('a')+ a.href = URL.createObjectURL(new Blob([content], { type: 'text/plain' }))+ a.download = filename+ a.click()+ URL.revokeObjectURL(a.href)+}++/** EN: Serialize rows to CSV with proper quoting. / FR: Sérialiser des lignes en CSV avec échappement correct. */+function toCSV(rows, cols) {+ const header = cols.join(',')+ const lines = rows.map(r => cols.map(c => {+ const v = r[c] ?? ''+ const s = typeof v === 'object' ? JSON.stringify(v) : String(v)+ return s.includes(',') || s.includes('"') || s.includes('\n')+ ? `"${s.replace(/"/g, '""')}"` : s+ }).join(','))+ return [header, ...lines].join('\n')+}++/** EN: Dropdown offering graph/alerts export in JSON and CSV.+ * FR: Menu déroulant d'export du graphe/des alertes en JSON et CSV. */+function ExportButton({ nodes, edges, lanDevices, alerts }) {+ const { t } = useT()+ const [open, setOpen] = useState(false)+ const ref = useRef(null)++ // EN: Close the dropdown on outside click. / FR: Fermer le menu au clic extérieur.+ useEffect(() => {+ function onClickOutside(e) {+ if (ref.current && !ref.current.contains(e.target)) setOpen(false)+ }+ document.addEventListener('mousedown', onClickOutside)+ return () => document.removeEventListener('mousedown', onClickOutside)+ }, [])++ const stamp = () => new Date().toISOString().slice(0, 16).replace(':', '-')++ function exportGraphJSON() {+ const data = {+ exported_at: new Date().toISOString(),+ nodes: [...Object.values(nodes), ...Object.values(lanDevices)],+ edges: Object.values(edges),+ }+ downloadFile(JSON.stringify(data, null, 2), `snitch-graph-${stamp()}.json`)+ setOpen(false)+ }++ function exportGraphCSV() {+ const allNodes = [...Object.values(nodes), ...Object.values(lanDevices)]+ const cols = ['id', 'label', 'ip', 'category', 'country', 'city', 'org', 'bytes', 'packets']+ downloadFile(toCSV(allNodes, cols), `snitch-graph-${stamp()}.csv`)+ setOpen(false)+ }++ function exportAlertsJSON() {+ downloadFile(JSON.stringify(alerts, null, 2), `snitch-alerts-${stamp()}.json`)+ setOpen(false)+ }++ function exportAlertsCSV() {+ const cols = ['id', 'type', 'severity', 'message', 'node_id', 'timestamp']+ downloadFile(toCSV(alerts, cols), `snitch-alerts-${stamp()}.csv`)+ setOpen(false)+ }++ const items = [+ { label: t('export_graph_json'), action: exportGraphJSON },+ { label: t('export_graph_csv'), action: exportGraphCSV },+ { label: t('export_alerts_json'), action: exportAlertsJSON },+ { label: t('export_alerts_csv'), action: exportAlertsCSV },+ ]++ return (+ <div ref={ref} style={{ position: 'relative' }}>+ <button onClick={() => setOpen(v => !v)} style={{+ display: 'flex', alignItems: 'center', gap: 6,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 20, padding: '5px 14px',+ cursor: 'pointer', color: '#64748b',+ fontSize: 11, fontWeight: 600, transition: 'all 0.15s',+ }}>+ <Download size={11} />+ {t('export_btn')}+ </button>++ {open && (+ <div style={{+ position: 'absolute', top: '110%', right: 0, zIndex: 100,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 10, overflow: 'hidden',+ boxShadow: '0 8px 24px rgba(0,0,0,0.4)', minWidth: 180,+ }}>+ {items.map(({ label, action }) => (+ <button key={label} onClick={action} style={{+ display: 'block', width: '100%', textAlign: 'left',+ background: 'none', border: 'none', borderBottom: '1px solid #0f172a',+ padding: '9px 14px', color: '#e2e8f0',+ fontSize: 11, cursor: 'pointer',+ }}+ onMouseEnter={e => e.target.style.background = '#334155'}+ onMouseLeave={e => e.target.style.background = 'none'}>+ {label}+ </button>+ ))}+ </div>+ )}+ </div>+ )+}++/** EN: Red badge shown while a process holds the mic or camera.+ * FR: Badge rouge affiché quand un processus utilise le micro ou la caméra. */+function MediaBadge({ media }) {+ const micActive = media.mic.length > 0+ const camActive = media.camera.length > 0+ if (!micActive && !camActive) return null++ return (+ <div style={{+ display: 'flex', alignItems: 'center', gap: 6,+ background: '#2d1b1b', border: '1px solid #ef4444',+ borderRadius: 20, padding: '5px 12px',+ }}>+ {micActive && (+ <div title={media.mic.join(', ')} style={{ display: 'flex', alignItems: 'center', gap: 4, cursor: 'default' }}>+ <Mic size={11} color="#f87171" />+ <span style={{ fontSize: 10, color: '#fca5a5' }}>{media.mic[0]}</span>+ </div>+ )}+ {micActive && camActive && <span style={{ color: '#4b1f1f', fontSize: 10 }}>|</span>}+ {camActive && (+ <div title={media.camera.join(', ')} style={{ display: 'flex', alignItems: 'center', gap: 4, cursor: 'default' }}>+ <Camera size={11} color="#f87171" />+ <span style={{ fontSize: 10, color: '#fca5a5' }}>{media.camera[0]}</span>+ </div>+ )}+ </div>+ )+}++/** EN: Dropdown listing detected processes — toggling one hides its traffic+ * from capture (server-side) and from the graph (client-side).+ * FR: Menu listant les processus détectés — en cocher un masque son trafic+ * de la capture (côté serveur) et du graphe (côté client). */+function ProcessFilter({ excluded, onChange, nodes }) {+ const { t } = useT()+ const [open, setOpen] = useState(false)+ const ref = useRef(null)++ useEffect(() => {+ function onClickOutside(e) {+ if (ref.current && !ref.current.contains(e.target)) setOpen(false)+ }+ document.addEventListener('mousedown', onClickOutside)+ return () => document.removeEventListener('mousedown', onClickOutside)+ }, [])++ // EN: Union of every process name seen on any node.+ // FR: Union de tous les noms de processus vus sur les nœuds.+ const allProcesses = useMemo(() => {+ const set = new Set()+ Object.values(nodes).forEach(n => {+ if (n.processes) Object.keys(n.processes).forEach(p => set.add(p))+ })+ return Array.from(set).sort()+ }, [nodes])++ function toggle(proc) {+ onChange(excluded.includes(proc)+ ? excluded.filter(p => p !== proc)+ : [...excluded, proc]+ )+ }++ const active = excluded.length > 0++ return (+ <div ref={ref} style={{ position: 'relative' }}>+ <button onClick={() => setOpen(v => !v)} style={{+ display: 'flex', alignItems: 'center', gap: 6,+ background: active ? '#3b1f2b' : '#1e293b',+ border: `1px solid ${active ? '#f87171' : '#334155'}`,+ borderRadius: 20, padding: '5px 14px',+ cursor: 'pointer', color: active ? '#fca5a5' : '#64748b',+ fontSize: 11, fontWeight: 600, transition: 'all 0.15s',+ }}>+ {t('process_filter')}+ {active && (+ <span style={{+ background: '#ef4444', color: '#fff',+ borderRadius: 10, padding: '0 6px', fontSize: 10,+ }}>{excluded.length}</span>+ )}+ </button>++ {open && (+ <div style={{+ position: 'absolute', top: '110%', right: 0, zIndex: 100,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 10, padding: 12, minWidth: 220, maxHeight: 300,+ overflowY: 'auto', boxShadow: '0 8px 24px rgba(0,0,0,0.4)',+ }}>+ <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 8 }}>+ {t('process_filter_hint')}+ </div>++ {allProcesses.length === 0 && (+ <div style={{ fontSize: 11, color: '#475569' }}>{t('process_none')}</div>+ )}++ {allProcesses.map(proc => {+ const isExcluded = excluded.includes(proc)+ return (+ <div key={proc} onClick={() => toggle(proc)} style={{+ display: 'flex', alignItems: 'center', gap: 8,+ padding: '5px 6px', borderRadius: 6, cursor: 'pointer',+ background: isExcluded ? '#2d1b1b' : 'transparent',+ marginBottom: 2,+ }}>+ <div style={{+ width: 12, height: 12, borderRadius: 3, flexShrink: 0,+ border: `1px solid ${isExcluded ? '#ef4444' : '#475569'}`,+ background: isExcluded ? '#ef4444' : 'transparent',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ }}>+ {isExcluded && <span style={{ color: '#fff', fontSize: 9, lineHeight: 1 }}>✕</span>}+ </div>+ <span style={{ fontSize: 11, color: isExcluded ? '#fca5a5' : '#e2e8f0' }}>+ {proc}+ </span>+ </div>+ )+ })}++ {active && (+ <button onClick={() => onChange([])} style={{+ marginTop: 8, width: '100%', background: 'none',+ border: '1px solid #334155', borderRadius: 6,+ padding: '4px 0', color: '#64748b', fontSize: 10,+ cursor: 'pointer',+ }}>+ {t('process_clear')}+ </button>+ )}+ </div>+ )}+ </div>+ )+}++/** EN: Port filter chip — restricts capture to the listed ports.+ * FR: Puce de filtre de ports — restreint la capture aux ports listés. */+function PortFilter({ ports, onUpdate }) {+ const { t } = useT()+ const [open, setOpen] = useState(false)+ const [input, setInput] = useState('')+ const [error, setError] = useState(false)+ const ref = useRef(null)++ useEffect(() => {+ function onClickOutside(e) {+ if (ref.current && !ref.current.contains(e.target)) setOpen(false)+ }+ document.addEventListener('mousedown', onClickOutside)+ return () => document.removeEventListener('mousedown', onClickOutside)+ }, [])++ function addPort(e) {+ e.preventDefault()+ const p = parseInt(input, 10)+ if (!p || p < 1 || p > 65535) { setError(true); return }+ if (ports.includes(p)) { setInput(''); return }+ setError(false)+ setInput('')+ onUpdate([...ports, p])+ }++ function removePort(p) {+ onUpdate(ports.filter(x => x !== p))+ }++ const active = ports.length > 0++ return (+ <div ref={ref} style={{ position: 'relative' }}>+ <button onClick={() => setOpen(v => !v)} style={{+ display: 'flex', alignItems: 'center', gap: 6,+ background: active ? '#1e3a5f' : '#1e293b',+ border: `1px solid ${active ? '#3b82f6' : '#334155'}`,+ borderRadius: 20, padding: '5px 14px',+ cursor: 'pointer', color: active ? '#93c5fd' : '#64748b',+ fontSize: 11, fontWeight: 600, transition: 'all 0.15s',+ }}>+ <Filter size={11} />+ {t('port_filter')}+ {active && (+ <span style={{+ background: '#3b82f6', color: '#fff',+ borderRadius: 10, padding: '0 6px', fontSize: 10,+ }}>{ports.length}</span>+ )}+ </button>++ {open && (+ <div style={{+ position: 'absolute', top: '110%', right: 0, zIndex: 100,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 10, padding: 12, minWidth: 220,+ boxShadow: '0 8px 24px rgba(0,0,0,0.4)',+ }}>+ <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 8 }}>+ {active ? `${ports.length} port${ports.length > 1 ? 's' : ''}` : t('port_all')}+ </div>++ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: ports.length ? 10 : 0 }}>+ {ports.map(p => (+ <span key={p} style={{+ display: 'flex', alignItems: 'center', gap: 4,+ background: '#0f172a', border: '1px solid #3b82f6',+ borderRadius: 12, padding: '2px 8px',+ fontSize: 11, color: '#93c5fd',+ }}>+ {p}+ <button onClick={() => removePort(p)} style={{+ background: 'none', border: 'none', cursor: 'pointer',+ color: '#64748b', padding: 0, lineHeight: 1, fontSize: 13,+ }}>×</button>+ </span>+ ))}+ </div>++ <form onSubmit={addPort} style={{ display: 'flex', gap: 6 }}>+ <input+ autoFocus+ value={input}+ onChange={e => { setInput(e.target.value); setError(false) }}+ placeholder={t('port_placeholder')}+ style={{+ flex: 1, background: '#0f172a',+ border: `1px solid ${error ? '#ef4444' : '#334155'}`,+ borderRadius: 6, padding: '5px 8px',+ color: '#e2e8f0', fontSize: 11, outline: 'none',+ }}+ />+ <button type="submit" style={{+ background: '#3b82f6', border: 'none', borderRadius: 6,+ padding: '5px 10px', color: '#fff', fontSize: 11,+ cursor: 'pointer', fontWeight: 600,+ }}>+</button>+ </form>+ {error && <div style={{ fontSize: 10, color: '#ef4444', marginTop: 4 }}>{t('port_invalid')}</div>}++ {active && (+ <button onClick={() => onUpdate([])} style={{+ marginTop: 10, width: '100%', background: 'none',+ border: '1px solid #334155', borderRadius: 6,+ padding: '4px 0', color: '#64748b', fontSize: 10,+ cursor: 'pointer',+ }}>+ {t('port_all')}+ </button>+ )}+ </div>+ )}+ </div>+ )+}++// EN: Basic IPv4 shape + range check. / FR: Vérification basique de forme et de plage IPv4.+const IPV4_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/++function isValidIp(ip) {+ const m = ip.match(IPV4_RE)+ return !!m && m.slice(1).every(o => +o >= 0 && +o <= 255)+}++/** EN: Trusted-IP whitelist chip — listed IPs are dropped server-side.+ * FR: Puce de liste blanche d'IP — les IP listées sont ignorées côté serveur. */+function IPWhitelist({ ips, onUpdate }) {+ const { t } = useT()+ const [open, setOpen] = useState(false)+ const [input, setInput] = useState('')+ const [error, setError] = useState(false)+ const ref = useRef(null)++ useEffect(() => {+ function onClickOutside(e) {+ if (ref.current && !ref.current.contains(e.target)) setOpen(false)+ }+ document.addEventListener('mousedown', onClickOutside)+ return () => document.removeEventListener('mousedown', onClickOutside)+ }, [])++ function addIp(e) {+ e.preventDefault()+ const ip = input.trim()+ if (!isValidIp(ip)) { setError(true); return }+ if (ips.includes(ip)) { setInput(''); return }+ setError(false)+ setInput('')+ onUpdate([...ips, ip])+ }++ function removeIp(ip) {+ onUpdate(ips.filter(x => x !== ip))+ }++ const active = ips.length > 0++ return (+ <div ref={ref} style={{ position: 'relative' }}>+ <button onClick={() => setOpen(v => !v)} style={{+ display: 'flex', alignItems: 'center', gap: 6,+ background: active ? '#153824' : '#1e293b',+ border: `1px solid ${active ? '#22c55e' : '#334155'}`,+ borderRadius: 20, padding: '5px 14px',+ cursor: 'pointer', color: active ? '#86efac' : '#64748b',+ fontSize: 11, fontWeight: 600, transition: 'all 0.15s',+ }}>+ <ShieldOff size={11} />+ {t('ip_whitelist')}+ {active && (+ <span style={{+ background: '#22c55e', color: '#052e16',+ borderRadius: 10, padding: '0 6px', fontSize: 10,+ }}>{ips.length}</span>+ )}+ </button>++ {open && (+ <div style={{+ position: 'absolute', top: '110%', right: 0, zIndex: 100,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 10, padding: 12, minWidth: 220,+ boxShadow: '0 8px 24px rgba(0,0,0,0.4)',+ }}>+ <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 8 }}>+ {t('ip_whitelist_hint')}+ </div>++ <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: ips.length ? 10 : 0 }}>+ {ips.map(ip => (+ <span key={ip} style={{+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ background: '#0f172a', border: '1px solid #22c55e',+ borderRadius: 6, padding: '3px 8px',+ fontSize: 11, color: '#86efac', fontFamily: 'monospace',+ }}>+ {ip}+ <button onClick={() => removeIp(ip)} style={{+ background: 'none', border: 'none', cursor: 'pointer',+ color: '#64748b', padding: 0, lineHeight: 1, fontSize: 13,+ }}>×</button>+ </span>+ ))}+ </div>++ <form onSubmit={addIp} style={{ display: 'flex', gap: 6 }}>+ <input+ autoFocus+ value={input}+ onChange={e => { setInput(e.target.value); setError(false) }}+ placeholder={t('ip_placeholder')}+ style={{+ flex: 1, background: '#0f172a',+ border: `1px solid ${error ? '#ef4444' : '#334155'}`,+ borderRadius: 6, padding: '5px 8px',+ color: '#e2e8f0', fontSize: 11, outline: 'none',+ }}+ />+ <button type="submit" style={{+ background: '#22c55e', border: 'none', borderRadius: 6,+ padding: '5px 10px', color: '#052e16', fontSize: 11,+ cursor: 'pointer', fontWeight: 600,+ }}>+</button>+ </form>+ {error && <div style={{ fontSize: 10, color: '#ef4444', marginTop: 4 }}>{t('ip_invalid')}</div>}++ {active && (+ <button onClick={() => onUpdate([])} style={{+ marginTop: 10, width: '100%', background: 'none',+ border: '1px solid #334155', borderRadius: 6,+ padding: '4px 0', color: '#64748b', fontSize: 10,+ cursor: 'pointer',+ }}>+ {t('ip_clear')}+ </button>+ )}+ </div>+ )}+ </div>+ )+}++/** EN: Start/stop capture button. / FR: Bouton démarrer/arrêter la capture. */+function CaptureToggle({ capturing, onToggle }) {+ const { t } = useT()+ const [loading, setLoading] = useState(false)++ async function handleClick() {+ setLoading(true)+ await onToggle()+ setLoading(false)+ }++ const label = loading+ ? (capturing ? t('capture_stopping') : t('capture_starting'))+ : (capturing ? t('capture_stop') : t('capture_start'))++ const Icon = capturing ? Square : Play++ return (+ <button onClick={handleClick} disabled={loading} style={{+ display: 'flex', alignItems: 'center', gap: 6,+ background: capturing ? '#1e293b' : '#166534',+ border: `1px solid ${capturing ? '#334155' : '#16a34a'}`,+ borderRadius: 20, padding: '5px 14px',+ cursor: loading ? 'wait' : 'pointer',+ color: capturing ? '#f87171' : '#4ade80',+ fontSize: 11, fontWeight: 600,+ transition: 'all 0.15s',+ opacity: loading ? 0.7 : 1,+ }}>+ <Icon size={11} />+ {label}+ </button>+ )+}++/** EN: EN/FR language toggle — the headline feature.+ * FR: Bascule de langue EN/FR — la fonctionnalité vedette. */+function LangToggle() {+ const { lang, setLang } = useT()+ return (+ <div style={{+ display: 'flex', background: '#1e293b',+ border: '1px solid #334155', borderRadius: 20, overflow: 'hidden',+ }}>+ {['en', 'fr'].map(l => (+ <button key={l} onClick={() => setLang(l)} style={{+ background: lang === l ? '#3b82f6' : 'transparent',+ border: 'none', cursor: 'pointer',+ color: lang === l ? '#fff' : '#64748b',+ padding: '5px 12px', fontSize: 11, fontWeight: 600,+ textTransform: 'uppercase',+ transition: 'background 0.15s',+ }}>+ {l}+ </button>+ ))}+ </div>+ )+}++/** EN: Graph/map view switcher. / FR: Bascule entre vue graphe et carte. */+function ViewToggle({ view, onChange }) {+ const { t } = useT()+ const items = [+ { id: 'graph', Icon: Hexagon, label: t('nav_graph') },+ { id: 'map', Icon: Globe, label: t('nav_map') },+ ]+ return (+ <div style={{+ display: 'flex', background: '#1e293b',+ border: '1px solid #334155', borderRadius: 20, overflow: 'hidden',+ }}>+ {items.map(({ id, Icon, label }) => (+ <button key={id} onClick={() => onChange(id)} style={{+ background: view === id ? '#3b82f6' : 'transparent',+ border: 'none', cursor: 'pointer',+ color: view === id ? '#fff' : '#64748b',+ padding: '5px 14px', fontSize: 11, fontWeight: 600,+ display: 'flex', alignItems: 'center', gap: 5,+ transition: 'background 0.15s',+ }}>+ <Icon size={12} /> {label}+ </button>+ ))}+ </div>+ )+}++/** EN: WebSocket status badge + LAN device count.+ * FR: Badge de statut WebSocket + compteur d'appareils LAN. */+function StatusBadge({ status, lanCount }) {+ const { t } = useT()+ const colors = { connected: '#22c55e', connecting: '#f59e0b', disconnected: '#ef4444', error: '#ef4444' }+ const labels = {+ connected: t('status_connected'),+ connecting: t('status_connecting'),+ disconnected: t('status_disconnected'),+ error: t('status_error'),+ }+ return (+ <div style={{+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 20, padding: '5px 14px',+ display: 'flex', alignItems: 'center', gap: 8,+ }}>+ <div style={{ width: 7, height: 7, borderRadius: '50%', background: colors[status] || '#94a3b8' }} />+ <span style={{ fontSize: 11, color: '#e2e8f0' }}>{labels[status] || status}</span>+ {lanCount > 0 && (+ <span style={{ fontSize: 11, color: '#f97316', borderLeft: '1px solid #334155', paddingLeft: 8 }}>+ {t('lan_devices', lanCount)}+ </span>+ )}+ </div>+ )+}++/** EN: Bottom-right color legend for node categories.+ * FR: Légende de couleurs en bas à droite pour les catégories de nœuds. */+function Legend() {+ const { t } = useT()+ const items = [+ { Icon: Wifi, color: '#f97316', label: 'Router' },+ { Icon: Smartphone, color: '#a855f7', label: 'Phone' },+ { Icon: Monitor, color: '#06b6d4', label: 'PC' },+ { Icon: Cpu, color: '#84cc16', label: 'IoT' },+ { Icon: ShieldCheck, color: '#22c55e', label: 'HTTPS' },+ { Icon: Radio, color: '#f59e0b', label: 'Tracking' },+ { Icon: Zap, color: '#6366f1', label: 'CDN' },+ { Icon: Globe, color: '#38bdf8', label: 'DNS' },+ { Icon: AlertTriangle, color: '#ef4444', label: t('legend_alert') },+ { Icon: HelpCircle, color: '#94a3b8', label: t('legend_unknown') },+ ]+ return (+ <div style={{+ position: 'absolute', bottom: 16, right: 16,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 8, padding: '10px 14px',+ }}>+ {items.map(({ Icon, color, label }) => (+ <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>+ <Icon size={12} color={color} />+ <span style={{ fontSize: 10, color: '#94a3b8' }}>{label}</span>+ </div>+ ))}+ </div>+ )+}diff --git a/frontend/src/api.js b/frontend/src/api.jsnew file mode 100644index 0000000..9e05734--- /dev/null+++ b/frontend/src/api.js@@ -0,0 +1,17 @@+/**+ * Snitch — API endpoint helpers.+ *+ * EN: Under Electron the app is loaded from file://, so there is no dev-server+ * proxy — all backend calls must use the absolute loopback URL.+ * In dev/browser mode we rely on the Vite proxy and use relative URLs.+ * FR: Sous Electron, l'app est chargée depuis file://, donc pas de proxy de+ * dev-server — tous les appels backend doivent utiliser l'URL loopback+ * absolue. En mode dev/navigateur on s'appuie sur le proxy Vite avec des+ * URL relatives.+ */+const isElectron = window.location.protocol === 'file:'++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`diff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsxnew file mode 100644index 0000000..0b6970c--- /dev/null+++ b/frontend/src/components/AlertPanel.jsx@@ -0,0 +1,253 @@+/**+ * Snitch — alert UI components.+ *+ * EN: Three exports:+ * AlertBell — toolbar bell with an unread counter+ * AlertPanel — dropdown listing all alerts, grouped visually by severity+ * AlertToasts — transient bottom-left popups for warning/critical alerts+ * Alert `type` values map to translated labels via the `alert_*` i18n keys.+ * FR: Trois exports :+ * AlertBell — cloche de la barre d'outils avec compteur de non-lus+ * AlertPanel — panneau listant toutes les alertes, groupées par sévérité+ * AlertToasts — popups transitoires en bas à gauche pour les alertes+ * warning/critiques+ * Les `type` d'alerte correspondent aux libellés traduits via les clés+ * i18n `alert_*`.+ */+import { useState, useEffect, useRef } from 'react'+import {+ Bell, Info, AlertTriangle, AlertCircle,+ Globe, WifiOff, Wifi,+ Activity, Unlock, TrendingUp,+} from 'lucide-react'+import { useT } from '../i18n'++// EN: Visual style per severity. / FR: Style visuel par sévérité.+const SEVERITY_STYLES = {+ info: { color: '#38bdf8', Icon: Info, bg: '#0c2340' },+ warning: { color: '#f59e0b', Icon: AlertTriangle, bg: '#2d1a00' },+ critical: { color: '#ef4444', Icon: AlertCircle, bg: '#2d0000' },+}++// EN: Per-alert-type icon. / FR: Icône par type d'alerte.+const TYPE_ICONS = {+ NEW_HOST: Globe,+ SUSPICIOUS_PROCESS: AlertTriangle,+ SUSPICIOUS_PORT: Unlock,+ BEACON: Activity,+ VOLUME_SPIKE: TrendingUp,+ NEW_LAN_DEVICE: Wifi,+ DEVICE_OFFLINE: WifiOff,+ MEDIA_EXFIL: AlertCircle,+}++export function AlertBell({ unread, onClick }) {+ return (+ <button onClick={onClick} style={{+ position: 'relative', background: '#1e293b',+ border: '1px solid #334155', borderRadius: 20,+ padding: '5px 14px', cursor: 'pointer',+ display: 'flex', alignItems: 'center', gap: 6,+ color: unread > 0 ? '#f59e0b' : '#64748b',+ }}>+ <Bell size={14} />+ {unread > 0 && (+ <span style={{+ background: '#ef4444', color: '#fff',+ borderRadius: 10, fontSize: 9, fontWeight: 700,+ padding: '1px 5px', minWidth: 16, textAlign: 'center',+ }}>+ {unread > 99 ? '99+' : unread}+ </span>+ )}+ </button>+ )+}++export function AlertPanel({ alerts, onClose }) {+ const { t } = useT()+ const warningCount = alerts.filter(a => a.severity === 'warning').length+ const criticalCount = alerts.filter(a => a.severity === 'critical').length+ const infoCount = alerts.filter(a => a.severity === 'info').length++ return (+ <div style={{+ position: 'absolute', top: 56, right: 16, zIndex: 200,+ width: 380, maxHeight: 'calc(100vh - 80px)',+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 12, overflow: 'hidden',+ boxShadow: '0 8px 40px rgba(0,0,0,0.6)',+ display: 'flex', flexDirection: 'column',+ }}>+ {/* EN: Header with severity counters / FR: En-tête avec compteurs de sévérité */}+ <div style={{+ padding: '14px 18px', borderBottom: '1px solid #334155',+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',+ }}>+ <div>+ <span style={{ fontWeight: 700, fontSize: 13, color: '#f1f5f9' }}>{t('alerts_title')}</span>+ <span style={{ fontSize: 11, color: '#64748b', marginLeft: 8 }}>{alerts.length} {t('alerts_total')}</span>+ </div>+ <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>+ {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>+ </div>+ </div>++ <div style={{ overflowY: 'auto', flex: 1 }}>+ {alerts.length === 0 && (+ <div style={{ padding: 32, textAlign: 'center', color: '#64748b', fontSize: 12 }}>+ {t('alerts_empty')}+ </div>+ )}+ {alerts.map(alert => <AlertRow key={alert.id} alert={alert} />)}+ </div>+ </div>+ )+}++function AlertRow({ alert }) {+ const { t } = useT()+ const sev = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.info+ const TypeIcon = TYPE_ICONS[alert.type] || Info+ const SevIcon = sev.Icon+ // EN: Translate the type if a key exists, else show the raw type.+ // FR: Traduire le type si une clé existe, sinon afficher le type brut.+ const typeLabel = t(`alert_${alert.type}`) !== `alert_${alert.type}` ? t(`alert_${alert.type}`) : alert.type++ return (+ <div style={{+ padding: '10px 18px', borderBottom: '1px solid #1e293b',+ borderLeft: `3px solid ${sev.color}`, background: sev.bg,+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>+ <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>+ <SevIcon size={14} color={sev.color} style={{ flexShrink: 0, marginTop: 1 }} />+ <div>+ <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 2 }}>+ <TypeIcon size={11} color={sev.color} />+ <span style={{ fontSize: 10, color: sev.color, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>+ {typeLabel}+ </span>+ </div>+ <div style={{ fontSize: 11, color: '#e2e8f0', lineHeight: 1.4 }}>{alert.message}</div>+ {alert.details && Object.keys(alert.details).length > 0 && (+ <div style={{ marginTop: 3, fontSize: 9, color: '#64748b', fontFamily: 'monospace' }}>+ {Object.entries(alert.details).filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`).join(' · ')}+ </div>+ )}+ </div>+ </div>+ <span style={{ fontSize: 9, color: '#475569', flexShrink: 0, marginTop: 2 }}>+ {timeAgo(alert.timestamp, t)}+ </span>+ </div>+ </div>+ )+}++/** EN: Relative timestamp via i18n keys. / FR: Horodatage relatif via les clés i18n. */+function timeAgo(iso, t) {+ const diff = Math.floor((Date.now() - new Date(iso + 'Z')) / 1000)+ if (diff < 5) return t('time_just_now')+ if (diff < 60) return t('time_seconds', diff)+ if (diff < 3600) return t('time_minutes', Math.floor(diff / 60))+ return t('time_hours', Math.floor(diff / 3600))+}++function Badge({ count, color }) {+ return (+ <span style={{+ background: color + '22', color, border: `1px solid ${color}44`,+ borderRadius: 10, fontSize: 10, fontWeight: 700, padding: '1px 7px',+ }}>+ {count}+ </span>+ )+}++const TOAST_DURATION = 5000 // EN: ms before fade starts / FR: ms avant le début du fondu+const TOAST_FADE = 800 // EN: fade duration in ms / FR: durée du fondu en ms++/**+ * EN: Stacked transient notifications. New alerts appear for TOAST_DURATION,+ * then fade out over TOAST_FADE and unmount.+ * FR: Notifications empilées transitoires. Les nouvelles alertes restent+ * TOAST_DURATION puis fondent en TOAST_FADE avant démontage.+ */+export function AlertToasts({ alerts }) {+ const [visible, setVisible] = useState([]) // [{ alert, dying }]+ const timers = useRef({})+ const prevIds = useRef(new Set())++ useEffect(() => {+ const incoming = alerts.filter(a => a.severity !== 'info').slice(0, 10)+ const newOnes = incoming.filter(a => !prevIds.current.has(a.id))+ if (!newOnes.length) return++ newOnes.forEach(a => prevIds.current.add(a.id))++ setVisible(prev => {+ const next = [...newOnes.map(a => ({ alert: a, dying: false })), ...prev].slice(0, 5)+ return next+ })++ newOnes.forEach(a => {+ timers.current[a.id] = setTimeout(() => {+ setVisible(prev => prev.map(t => t.alert.id === a.id ? { ...t, dying: true } : t))+ setTimeout(() => {+ setVisible(prev => prev.filter(t => t.alert.id !== a.id))+ delete timers.current[a.id]+ }, TOAST_FADE)+ }, TOAST_DURATION)+ })+ }, [alerts])++ useEffect(() => () => Object.values(timers.current).forEach(clearTimeout), [])++ return (+ <div style={{+ position: 'absolute', bottom: 16, left: 16,+ display: 'flex', flexDirection: 'column-reverse', gap: 4,+ pointerEvents: 'none', zIndex: 300, maxWidth: 260,+ }}>+ {visible.map(({ alert, dying }, i) => (+ <Toast key={alert.id} alert={alert} index={i} dying={dying} />+ ))}+ </div>+ )+}++function Toast({ alert, index, dying }) {+ const { t } = useT()+ const sev = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.info+ const TypeIcon = TYPE_ICONS[alert.type] || Info+ const typeLabel = t(`alert_${alert.type}`) !== `alert_${alert.type}` ? t(`alert_${alert.type}`) : alert.type++ // EN: Older toasts fade progressively in the stack.+ // FR: Les toasts plus anciens s'estompent progressivement dans la pile.+ const baseOpacity = Math.max(0, 1 - index * 0.2)++ return (+ <div style={{+ background: '#1e293b', border: `1px solid ${sev.color}44`,+ borderLeft: `3px solid ${sev.color}`,+ borderRadius: 6, padding: '5px 10px',+ display: 'flex', alignItems: 'center', gap: 8,+ opacity: dying ? 0 : baseOpacity,+ transform: `scale(${1 - index * 0.02})`,+ transition: dying ? `opacity ${TOAST_FADE}ms ease` : 'opacity 0.3s ease',+ transformOrigin: 'bottom left',+ }}>+ <TypeIcon size={12} color={sev.color} style={{ flexShrink: 0 }} />+ <div style={{ minWidth: 0 }}>+ <div style={{ fontSize: 9, color: sev.color, fontWeight: 700, textTransform: 'uppercase' }}>{typeLabel}</div>+ <div style={{ fontSize: 10, color: '#94a3b8', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{alert.message}</div>+ </div>+ </div>+ )+}diff --git a/frontend/src/components/BandwidthChart.jsx b/frontend/src/components/BandwidthChart.jsxnew file mode 100644index 0000000..191499b--- /dev/null+++ b/frontend/src/components/BandwidthChart.jsx@@ -0,0 +1,71 @@+/**+ * Snitch — bandwidth sparkline.+ *+ * EN: Tiny D3 area/line chart showing bytes-per-second over the last 60 s.+ * Rendered at the top of the sidebar; redrawn whenever the `data` prop+ * changes (once per second from the WebSocket hook).+ * FR: Petit graphique aire/ligne D3 montrant les octets/seconde sur les 60+ * dernières secondes. Affiché en haut de la barre latérale ; redessiné à+ * chaque changement de `data` (une fois par seconde via le hook WebSocket).+ */+import { useEffect, useRef } from 'react'+import * as d3 from 'd3'++/** EN: Human-readable throughput. / FR: Débit lisible par un humain. */+function fmtBps(bps) {+ if (bps >= 1024 * 1024) return `${(bps / 1024 / 1024).toFixed(1)} MB/s`+ if (bps >= 1024) return `${(bps / 1024).toFixed(0)} KB/s`+ return `${bps} B/s`+}++export default function BandwidthChart({ data }) {+ const svgRef = useRef(null)++ useEffect(() => {+ const el = svgRef.current+ if (!el) return+ const W = el.clientWidth || 260+ const H = 36+ const svg = d3.select(el).attr('height', H)+ svg.selectAll('*').remove()++ const now = Date.now()+ const xDomain = [now - 60000, now]+ const x = d3.scaleLinear().domain(xDomain).range([0, W])+ const maxBps = d3.max(data, d => d.bps) || 1+ const y = d3.scaleLinear().domain([0, maxBps * 1.2]).range([H, 2])++ // EN: Gradient fill under the line. / FR: Dégradé sous la courbe.+ const defs = svg.append('defs')+ const grad = defs.append('linearGradient')+ .attr('id', 'bw-grad').attr('x1', 0).attr('y1', 0).attr('x2', 0).attr('y2', 1)+ grad.append('stop').attr('offset', '0%').attr('stop-color', '#3b82f6').attr('stop-opacity', 0.35)+ grad.append('stop').attr('offset', '100%').attr('stop-color', '#3b82f6').attr('stop-opacity', 0)++ if (data.length > 1) {+ const area = d3.area().x(d => x(d.ts)).y0(H).y1(d => y(d.bps)).curve(d3.curveCatmullRom)+ const line = d3.line().x(d => x(d.ts)).y(d => y(d.bps)).curve(d3.curveCatmullRom)++ svg.append('path').datum(data).attr('d', area).attr('fill', 'url(#bw-grad)')+ svg.append('path').datum(data).attr('d', line)+ .attr('fill', 'none').attr('stroke', '#3b82f6').attr('stroke-width', 1.5)+ }++ // EN: Current throughput label, right-aligned.+ // FR: Étiquette du débit courant, alignée à droite.+ const current = data.length ? data[data.length - 1].bps : 0+ svg.append('text')+ .attr('x', W - 2).attr('y', 11)+ .attr('text-anchor', 'end')+ .attr('fill', current > 0 ? '#3b82f6' : '#334155')+ .attr('font-size', 9).attr('font-weight', 700)+ .text(fmtBps(current))+ }, [data])++ return (+ <svg+ ref={svgRef}+ style={{ width: '100%', height: 36, display: 'block' }}+ />+ )+}diff --git a/frontend/src/components/PrivacyScore.jsx b/frontend/src/components/PrivacyScore.jsxnew file mode 100644index 0000000..3653062--- /dev/null+++ b/frontend/src/components/PrivacyScore.jsx@@ -0,0 +1,130 @@+/**+ * Snitch — privacy score widget.+ *+ * EN: Renders the 0–100 score as an SVG donut plus the top contributing+ * factors. `factors` entries carry an i18n `key` + `args` so the labels+ * stay translated; `bad` flags penalties vs. positive signals.+ * FR: Affiche le score de 0 à 100 sous forme de donut SVG plus les principaux+ * facteurs. Les entrées `factors` portent une `key` i18n + `args` pour que+ * les libellés restent traduits ; `bad` distingue pénalités et signaux+ * positifs.+ */+import {+ Radio, BarChart2, Target, Activity,+ AlertTriangle, Unlock, ShieldAlert, Bell,+ Lock, CheckCircle2,+} from 'lucide-react'+import { useT } from '../i18n'++// EN: Icon lookup by the string key produced by the scoring engine.+// FR: Table d'icônes indexée par la clé chaîne produite par le moteur de score.+const SCORE_ICONS = {+ 'radio': Radio,+ 'bar-chart': BarChart2,+ 'target': Target,+ 'activity': Activity,+ 'alert-triangle': AlertTriangle,+ 'unlock': Unlock,+ 'shield-alert': ShieldAlert,+ 'bell': Bell,+ 'lock': Lock,+ 'check-circle': CheckCircle2,+}++const R = 34+const CIRC = 2 * Math.PI * R+const STROKE = 7++export default function PrivacyScore({ score, grade, color, labelKey, factors }) {+ const { t } = useT()+ const filled = (score / 100) * CIRC+ const badCount = factors.filter(f => f.bad).length++ return (+ <div style={{ padding: '14px 20px', borderBottom: '1px solid #334155' }}>+ <div style={{ fontSize: 10, color: '#64748b', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10 }}>+ {t('privacy_title')}+ </div>++ <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>+ {/* EN: Donut — arc length proportional to the score.+ FR: Donut — longueur d'arc proportionnelle au score. */}+ <div style={{ flexShrink: 0 }}>+ <svg width={84} height={84}>+ <circle cx={42} cy={42} r={R} fill="none" stroke="#1e3a5f" strokeWidth={STROKE} />+ <circle+ cx={42} cy={42} r={R}+ fill="none" stroke={color} strokeWidth={STROKE}+ strokeDasharray={`${filled} ${CIRC - filled}`}+ strokeLinecap="round"+ transform="rotate(-90 42 42)"+ style={{ transition: 'stroke-dasharray 0.6s ease' }}+ />+ <text x={42} y={38} textAnchor="middle" fill={color} fontSize={20} fontWeight={700} fontFamily="system-ui">+ {score}+ </text>+ <text x={42} y={54} textAnchor="middle" fill={color} fontSize={11} fontWeight={600} opacity={0.7}>+ {grade}+ </text>+ </svg>+ </div>++ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ fontSize: 13, fontWeight: 700, color, marginBottom: 2 }}>{t(labelKey)}</div>+ <div style={{ fontSize: 10, color: '#64748b', marginBottom: 8 }}>+ {t('privacy_risk_factors', badCount)}+ </div>++ {/* EN: Top 3 factors with their point penalty.+ FR: Top 3 des facteurs avec leur pénalité en points. */}+ {factors.slice(0, 3).map((f, i) => {+ const Icon = SCORE_ICONS[f.icon]+ return (+ <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>+ {Icon && <Icon size={12} color={f.bad ? '#94a3b8' : '#22c55e'} />}+ <span style={{+ fontSize: 10, color: f.bad ? '#cbd5e1' : '#64748b',+ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ }}>+ {t(f.key, ...f.args)}+ </span>+ {f.bad && f.penalty > 0 && (+ <span style={{ fontSize: 9, color: '#ef4444', flexShrink: 0 }}>-{f.penalty}</span>+ )}+ </div>+ )+ })}++ {factors.length > 3 && (+ <div style={{ fontSize: 9, color: '#475569', marginTop: 2 }}>+ {t('privacy_more_factors', factors.length - 3)}+ </div>+ )}+ </div>+ </div>++ {/* EN: Gradient scale with the score cursor.+ FR: Échelle en dégradé avec le curseur du score. */}+ <div style={{ marginTop: 12 }}>+ <div style={{+ height: 4, borderRadius: 2,+ background: 'linear-gradient(to right, #ef4444, #f97316, #f59e0b, #84cc16, #22c55e)',+ position: 'relative',+ }}>+ <div style={{+ position: 'absolute', left: `${score}%`, top: '50%',+ transform: 'translate(-50%, -50%)',+ width: 10, height: 10, borderRadius: '50%',+ background: color, border: '2px solid #0f172a',+ boxShadow: `0 0 6px ${color}`,+ transition: 'left 0.6s ease',+ }} />+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 3 }}>+ <span style={{ fontSize: 8, color: '#ef4444' }}>{t('privacy_critical_label')}</span>+ <span style={{ fontSize: 8, color: '#22c55e' }}>{t('privacy_excellent_label')}</span>+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/components/SearchBar.jsx b/frontend/src/components/SearchBar.jsxnew file mode 100644index 0000000..6e61421--- /dev/null+++ b/frontend/src/components/SearchBar.jsx@@ -0,0 +1,82 @@+/**+ * Snitch — search & category filter bar.+ *+ * EN: Text search (matches label/IP/country/org/hostname) plus a row of+ * category chips. Controlled component: state lives in App, this just+ * reports changes.+ * FR: Recherche texte (correspond à label/IP/pays/org/hostname) plus une+ * rangée de puces de catégorie. Composant contrôlé : l'état vit dans App,+ * il ne fait que remonter les changements.+ */+import { Search, X } from 'lucide-react'+import { useT } from '../i18n'++// EN: Category chips — `label` is a hardcoded English service name, otherwise+// the chip falls back to an i18n key.+// FR: Puces de catégorie — `label` est un nom de service anglais fixe, sinon+// la puce utilise une clé i18n.+const CATEGORY_IDS = [+ { id: 'all', color: '#64748b' },+ { id: 'safe', label: 'HTTPS', color: '#22c55e' },+ { id: 'tracking', label: 'Tracking', color: '#f59e0b' },+ { id: 'cdn', label: 'CDN', color: '#6366f1' },+ { id: 'dns', label: 'DNS', color: '#38bdf8' },+ { id: 'unknown', color: '#94a3b8' },+]++export default function SearchBar({ filter, onChange }) {+ const { t } = useT()+ const { text, category } = filter++ const categories = CATEGORY_IDS.map(c => ({+ ...c,+ label: c.label ?? (c.id === 'all' ? t('cat_all') : t('cat_unknown')),+ }))++ return (+ <div style={{ padding: '8px 12px', borderBottom: '1px solid #334155' }}>+ {/* EN: Text field / FR: Champ texte */}+ <div style={{ position: 'relative', marginBottom: 7 }}>+ <Search size={11} style={{+ position: 'absolute', left: 8, top: '50%',+ transform: 'translateY(-50%)', color: '#64748b', pointerEvents: 'none',+ }} />+ <input+ value={text}+ onChange={e => onChange({ ...filter, text: e.target.value })}+ placeholder={t('search_placeholder')}+ style={{+ width: '100%', boxSizing: 'border-box',+ background: '#0f172a', border: '1px solid #334155',+ borderRadius: 6, padding: '5px 26px 5px 26px',+ color: '#e2e8f0', fontSize: 11, outline: 'none',+ }}+ />+ {text && (+ <button onClick={() => onChange({ ...filter, text: '' })} style={{+ position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)',+ background: 'none', border: 'none', color: '#64748b', cursor: 'pointer', padding: 0,+ }}>+ <X size={11} />+ </button>+ )}+ </div>++ {/* EN: Category chips / FR: Puces de catégorie */}+ <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>+ {categories.map(c => (+ <button key={c.id} onClick={() => onChange({ ...filter, category: c.id })} style={{+ background: category === c.id ? c.color + '22' : 'transparent',+ border: `1px solid ${category === c.id ? c.color : '#334155'}`,+ borderRadius: 10, padding: '2px 8px',+ fontSize: 9, fontWeight: 600,+ color: category === c.id ? c.color : '#64748b',+ cursor: 'pointer', transition: 'all 0.15s',+ }}>+ {c.label}+ </button>+ ))}+ </div>+ </div>+ )+}diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsxnew file mode 100644index 0000000..ed8a08d--- /dev/null+++ b/frontend/src/components/Sidebar.jsx@@ -0,0 +1,291 @@+/**+ * Snitch — left sidebar.+ *+ * EN: Column layout: brand header + bandwidth sparkline, quick stats,+ * privacy score, selected-node detail card, search bar, scrollable+ * LAN-device + external-host lists, and the recent-packet feed.+ * FR: Colonne : en-tête de marque + sparkline de débit, stats rapides, score+ * de confidentialité, fiche du nœud sélectionné, barre de recherche,+ * listes déroulantes appareils LAN + hôtes externes, et le flux de+ * paquets récents.+ */+import { Wifi, Smartphone, Monitor, Tv, Cpu, HelpCircle, ShieldOff } from 'lucide-react'+import PrivacyScore from './PrivacyScore'+import BandwidthChart from './BandwidthChart'+import SearchBar from './SearchBar'+import { useT } from '../i18n'++// EN: Lucide icon per LAN device type. / FR: Icône Lucide par type d'appareil LAN.+const DEVICE_ICONS = {+ router: Wifi,+ phone: Smartphone,+ pc: Monitor,+ tv: Tv,+ iot: Cpu,+ unknown: HelpCircle,+}++// EN: Dot color per traffic category — mirrors the backend classifier.+// FR: Couleur de point par catégorie de trafic — reflète le classifieur backend.+const CATEGORY_COLORS = {+ safe: '#22c55e', tracking: '#f59e0b', cdn: '#6366f1',+ dns: '#38bdf8', admin: '#fb923c', unknown: '#94a3b8', local: '#3b82f6',+}++/** EN: Human-readable byte size. / FR: Taille en octets lisible. */+function fmt(bytes) {+ if (!bytes) return '0 B'+ if (bytes < 1024) return `${bytes} B`+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`+ return `${(bytes / 1024 / 1024).toFixed(2)} MB`+}++/**+ * EN: Does a node match the active search filter? The "local" node and any+ * node matching the category always pass unless the text fails.+ * FR: Un nœud correspond-il au filtre de recherche actif ? Le nœud « local »+ * et tout nœud de la bonne catégorie passent sauf si le texte échoue.+ */+function matchesFilter(node, filter) {+ if (!filter || (filter.category === 'all' && !filter.text)) return true+ if (filter.category !== 'all' && node.category !== filter.category) return false+ if (filter.text) {+ const t = filter.text.toLowerCase()+ return (node.label || '').toLowerCase().includes(t)+ || (node.ip || '').toLowerCase().includes(t)+ || (node.country || '').toLowerCase().includes(t)+ || (node.org || '').toLowerCase().includes(t)+ }+ return true+}++export default function Sidebar({ nodes, lanDevices, packets, selected, onClose, privacyScore, bandwidth, filter, onFilterChange, onWhitelist }) {+ const { t } = useT()+ const extNodes = Object.values(nodes).filter(n => n.id !== 'local')+ const devList = Object.values(lanDevices)+ const totalBytes = extNodes.reduce((a, n) => a + (n.bytes || 0), 0)++ const filteredNodes = extNodes.filter(n => matchesFilter(n, filter))+ const hiddenCount = filteredNodes.length < extNodes.length ? extNodes.length : null++ return (+ <div style={{+ width: 300, height: '100vh', background: '#1e293b',+ borderRight: '1px solid #334155', display: 'flex',+ flexDirection: 'column', overflow: 'hidden',+ }}>+ {/* EN: Brand + live bandwidth / FR: Marque + débit en direct */}+ <div style={{ padding: '14px 20px 8px', borderBottom: '1px solid #334155' }}>+ <div style={{ marginBottom: 6 }}>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 7, marginBottom: 2 }}>+ <span style={{ fontSize: 9, fontFamily: 'monospace', color: '#f7b016', letterSpacing: 3, fontWeight: 600 }}>NET</span>+ <span style={{ fontSize: 17, fontWeight: 800, color: '#f1f5f9', letterSpacing: 1 }}>{t('app_name')}</span>+ </div>+ <span style={{ fontSize: 10, color: '#475569', letterSpacing: 1 }}>{t('tagline')}</span>+ </div>+ <BandwidthChart data={bandwidth || []} />+ </div>++ {/* EN: Quick counters / FR: Compteurs rapides */}+ <div style={{ padding: '10px 20px', borderBottom: '1px solid #334155' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <Stat label={t('stat_lan')} value={devList.length} color="#f97316" />+ <Stat label={t('stat_ext')} value={extNodes.length} />+ <Stat label={t('stat_traffic')} value={fmt(totalBytes)} />+ </div>+ </div>++ {privacyScore && (+ <PrivacyScore+ score={privacyScore.score}+ grade={privacyScore.grade}+ color={privacyScore.color}+ labelKey={privacyScore.labelKey}+ factors={privacyScore.factors}+ />+ )}++ {/* EN: Detail card for the clicked node. / FR: Fiche détail du nœud cliqué. */}+ {selected && (+ <div style={{ padding: '12px 20px', borderBottom: '1px solid #334155', background: '#0f172a' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>+ <span style={{ fontSize: 12, fontWeight: 600, color: '#f1f5f9' }}>+ {selected.label || selected.ip}+ </span>+ <button onClick={onClose} style={{ background: 'none', border: 'none', color: '#64748b', cursor: 'pointer', fontSize: 16 }}>x</button>+ </div>+ <NodeDetail node={selected} onWhitelist={onWhitelist} />+ </div>+ )}++ <SearchBar filter={filter} onChange={onFilterChange} />++ <div style={{ flex: 1, overflowY: 'auto' }}>+ {devList.length > 0 && (+ <>+ <SectionTitle label={t('section_lan', devList.length)} />+ {devList.map(d => <DeviceRow key={d.id} device={d} />)}+ </>+ )}++ <SectionTitle label={t('section_ext', filteredNodes.length, hiddenCount)} />+ {filteredNodes+ .sort((a, b) => (b.bytes || 0) - (a.bytes || 0))+ .map(n => <NodeRow key={n.id} node={n} />)}+ </div>++ {/* EN: Recent packet feed / FR: Flux de paquets récents */}+ <div style={{ borderTop: '1px solid #334155', maxHeight: 160, overflowY: 'auto' }}>+ <SectionTitle label={t('section_packets')} />+ {packets.slice(0, 25).map((p, i) => <PacketRow key={i} packet={p} />)}+ </div>+ </div>+ )+}++/** EN: Sticky list section header. / FR: En-tête de section de liste collant. */+function SectionTitle({ label }) {+ return (+ <div style={{ padding: '5px 20px', fontSize: 10, color: '#64748b', textTransform: 'uppercase', letterSpacing: 1, background: '#1e293b', position: 'sticky', top: 0 }}>+ {label}+ </div>+ )+}++function Stat({ label, value, color }) {+ return (+ <div style={{ textAlign: 'center' }}>+ <div style={{ fontSize: 16, fontWeight: 700, color: color || '#f1f5f9' }}>{value}</div>+ <div style={{ fontSize: 10, color: '#64748b' }}>{label}</div>+ </div>+ )+}++/** EN: One row of the LAN device list. / FR: Une ligne de la liste d'appareils LAN. */+function DeviceRow({ device }) {+ const { t } = useT()+ const Icon = DEVICE_ICONS[device.device_type] || HelpCircle+ return (+ <div style={{+ padding: '7px 20px', display: 'flex', alignItems: 'center', gap: 8,+ borderBottom: '1px solid #1e293b',+ opacity: device.online === false ? 0.45 : 1,+ }}>+ <Icon size={16} color={device.color} />+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ fontSize: 11, fontWeight: 600, color: '#e2e8f0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {device.hostname || device.vendor || device.ip}+ </div>+ <div style={{ fontSize: 9, color: '#64748b', fontFamily: 'monospace' }}>+ {device.ip} · {device.mac}+ </div>+ </div>+ <div style={{ fontSize: 9, color: device.online === false ? '#ef4444' : '#22c55e', flexShrink: 0 }}>+ {device.online === false ? t('offline') : t('online')}+ </div>+ </div>+ )+}++/** EN: One row of the external-host list. / FR: Une ligne de la liste d'hôtes externes. */+function NodeRow({ node }) {+ return (+ <div style={{ padding: '6px 20px', display: 'flex', alignItems: 'center', gap: 8, borderBottom: '1px solid #1e293b' }}>+ <div style={{ width: 7, height: 7, borderRadius: '50%', background: CATEGORY_COLORS[node.category] || '#94a3b8', flexShrink: 0 }} />+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ fontSize: 11, color: '#e2e8f0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {node.label || node.ip}+ </div>+ <div style={{ fontSize: 9, color: '#64748b' }}>{node.country || '-'} · {node.packets || 0} pkt</div>+ </div>+ <div style={{ fontSize: 10, color: '#94a3b8', flexShrink: 0 }}>{fmt(node.bytes || 0)}</div>+ </div>+ )+}++/** EN: Selected-node fields + top processes + whitelist action.+ * FR: Champs du nœud sélectionné + top processus + action de whitelist. */+function NodeDetail({ node, onWhitelist }) {+ const { t } = useT()+ const fields = [+ [t('field_ip'), node.ip],+ [t('field_mac'), node.mac],+ [t('field_hostname'), node.hostname],+ [t('field_vendor'), node.vendor],+ [t('field_type'), node.device_type],+ [t('field_country'), node.country],+ [t('field_city'), node.city],+ [t('field_org'), node.org],+ [t('field_category'), node.category],+ [t('field_traffic'), fmt(node.bytes || 0)],+ [t('field_packets'), node.packets],+ ]++ // EN: Top-5 processes by bytes on this node.+ // FR: Top 5 des processus par octets sur ce nœud.+ const processes = node.processes+ ? Object.entries(node.processes).sort(([, a], [, b]) => b.bytes - a.bytes).slice(0, 5)+ : []++ return (+ <div>+ {fields.filter(([, v]) => v != null && v !== '').map(([k, v]) => (+ <div key={k} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 3 }}>+ <span style={{ fontSize: 10, color: '#64748b' }}>{k}</span>+ <span style={{ fontSize: 10, color: '#e2e8f0', maxWidth: 170, textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v}</span>+ </div>+ ))}++ {processes.length > 0 && (+ <>+ <div style={{ fontSize: 9, color: '#475569', textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 8, marginBottom: 4 }}>+ {t('processes')}+ </div>+ {processes.map(([name, stats]) => (+ <div key={name} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 3, alignItems: 'center' }}>+ <span style={{ fontSize: 10, color: '#94a3b8', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 150 }}>+ {name}+ </span>+ <span style={{ fontSize: 9, color: '#475569', flexShrink: 0 }}>{fmt(stats.bytes)}</span>+ </div>+ ))}+ </>+ )}++ {/* EN: "Mark as trusted" — sends the IP to the whitelist endpoint.+ FR: « Marquer comme fiable » — envoie l'IP à l'endpoint de whitelist. */}+ {node.id !== 'local' && node.ip && onWhitelist && (+ <button onClick={() => onWhitelist(node.ip)} style={{+ marginTop: 10, width: '100%', display: 'flex', alignItems: 'center',+ justifyContent: 'center', gap: 6,+ background: 'none', border: '1px solid #22c55e', borderRadius: 6,+ padding: '5px 0', color: '#86efac', fontSize: 10, cursor: 'pointer',+ }}>+ <ShieldOff size={11} />+ {t('whitelist_action')}+ </button>+ )}+ </div>+ )+}++/** EN: One row of the packet feed — direction arrow, process, dst, size.+ * FR: Une ligne du flux de paquets — flèche de direction, processus, dst, taille. */+function PacketRow({ packet }) {+ const out = packet.direction === 'out'+ const color = out ? '#22c55e' : '#3b82f6'+ return (+ <div style={{ padding: '3px 20px', display: 'flex', alignItems: 'center', gap: 6 }}>+ <span style={{ color, fontSize: 10, flexShrink: 0 }}>{out ? '>' : '<'}</span>+ {packet.process && (+ <span style={{ fontSize: 9, color: '#f59e0b', flexShrink: 0, maxWidth: 80, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {packet.process}+ </span>+ )}+ <span style={{ fontSize: 9, color: '#94a3b8', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {packet.dst} · {packet.protocol}+ </span>+ <span style={{ fontSize: 9, color: '#475569', flexShrink: 0 }}>{packet.size}B</span>+ </div>+ )+}diff --git a/frontend/src/components/Timeline.jsx b/frontend/src/components/Timeline.jsxnew file mode 100644index 0000000..8933b44--- /dev/null+++ b/frontend/src/components/Timeline.jsx@@ -0,0 +1,234 @@+/**+ * Snitch — bottom timeline chart.+ *+ * EN: Collapsible per-minute bar chart of packets (with bytes and alert+ * counts in the tooltip) over the last 15/30/60 min. Data comes from the+ * backend's SQLite aggregates, refreshed every 15 s.+ * FR: Histogramme repliable par minute des paquets (avec octets et nombre+ * d'alertes dans l'infobulle) sur les 15/30/60 dernières minutes. Données+ * issues des agrégats SQLite du backend, rafraîchies toutes les 15 s.+ */+import { useEffect, useRef, useState, useCallback } from 'react'+import * as d3 from 'd3'+import { API_BASE } from '../api'+import { useT } from '../i18n'++const EXPANDED_H = 110+const COLLAPSED_H = 32++/** EN: Human-readable byte size. / FR: Taille en octets lisible. */+function fmt(bytes) {+ if (bytes < 1024) return `${bytes} B`+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`+}++export default function Timeline() {+ const { t, lang } = useT()+ const svgRef = useRef(null)+ const [data, setData] = useState([])+ const [expanded, setExpanded] = useState(true)+ const [tooltip, setTooltip] = useState(null)+ const [range, setRange] = useState(60)++ /**+ * EN: Minute labels localized to the UI language.+ * FR: Étiquettes de minute localisées selon la langue de l'UI.+ */+ function fmtMinute(iso) {+ const d = new Date(iso + ':00Z')+ return d.toLocaleTimeString(lang === 'fr' ? 'fr-FR' : 'en-US', { hour: '2-digit', minute: '2-digit' })+ }++ const fetchTimeline = useCallback(() => {+ fetch(`${API_BASE}/timeline?minutes=${range}`)+ .then(r => r.json())+ .then(d => setData(d.timeline || []))+ .catch(() => {})+ }, [range])++ // EN: Poll every 15 s. / FR: Sondage toutes les 15 s.+ useEffect(() => {+ fetchTimeline()+ const id = setInterval(fetchTimeline, 15000)+ return () => clearInterval(id)+ }, [fetchTimeline])++ useEffect(() => {+ if (!expanded || !svgRef.current || data.length === 0) return+ drawChart()+ }, [data, expanded, lang])++ function drawChart() {+ const el = svgRef.current+ const W = el.clientWidth+ const H = EXPANDED_H - 32+ const margin = { top: 8, right: 16, bottom: 24, left: 40 }+ const innerW = W - margin.left - margin.right+ const innerH = H - margin.top - margin.bottom++ const svg = d3.select(el)+ svg.selectAll('*').remove()++ const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`)++ const x = d3.scaleBand()+ .domain(data.map(d => d.minute))+ .range([0, innerW])+ .padding(0.15)++ const maxPkts = d3.max(data, d => d.packets) || 1+ const y = d3.scaleLinear().domain([0, maxPkts]).range([innerH, 0]).nice()++ // EN: Horizontal grid lines. / FR: Lignes de grille horizontales.+ g.append('g').attr('class', 'grid')+ .call(d3.axisLeft(y).ticks(3).tickSize(-innerW).tickFormat(''))+ .selectAll('line').attr('stroke', '#1e3a5f').attr('stroke-dasharray', '3,3')+ g.select('.grid .domain').remove()++ // EN: Bars — amber when the minute produced alerts, blue otherwise.+ // FR: Barres — ambre quand la minute a produit des alertes, bleu sinon.+ g.selectAll('rect.bar')+ .data(data)+ .join('rect')+ .attr('class', 'bar')+ .attr('x', d => x(d.minute))+ .attr('y', d => y(d.packets))+ .attr('width', x.bandwidth())+ .attr('height', d => innerH - y(d.packets))+ .attr('fill', d => d.alerts > 0 ? '#f59e0b' : '#3b82f6')+ .attr('fill-opacity', d => d.alerts > 0 ? 0.85 : 0.65)+ .attr('rx', 2)+ .on('mouseover', (e, d) => setTooltip({ x: e.clientX, y: e.clientY, d }))+ .on('mousemove', (e) => setTooltip(tt => tt ? { ...tt, x: e.clientX, y: e.clientY } : null))+ .on('mouseout', () => setTooltip(null))++ // EN: Red dot on top of alert-producing minutes.+ // FR: Point rouge au-dessus des minutes à alertes.+ g.selectAll('circle.alert')+ .data(data.filter(d => d.alerts > 0))+ .join('circle')+ .attr('class', 'alert')+ .attr('cx', d => x(d.minute) + x.bandwidth() / 2)+ .attr('cy', d => y(d.packets) - 5)+ .attr('r', 3)+ .attr('fill', '#ef4444')+ .attr('pointer-events', 'none')++ // EN: Thin out x labels — ~8 ticks max.+ // FR: Espacer les étiquettes x — ~8 graduations max.+ const step = Math.max(1, Math.floor(data.length / 8))+ const xAxis = d3.axisBottom(x)+ .tickValues(data.filter((_, i) => i % step === 0).map(d => d.minute))+ .tickFormat(fmtMinute)++ g.append('g')+ .attr('transform', `translate(0,${innerH})`)+ .call(xAxis)+ .selectAll('text')+ .attr('fill', '#475569').attr('font-size', 9)+ g.selectAll('.domain, .tick line').attr('stroke', '#334155')++ g.append('g')+ .call(d3.axisLeft(y).ticks(3).tickFormat(d => d > 999 ? `${(d / 1000).toFixed(0)}k` : d))+ .selectAll('text').attr('fill', '#475569').attr('font-size', 9)+ g.select('.domain').attr('stroke', '#334155')+ }++ const totalPkts = data.reduce((a, d) => a + d.packets, 0)+ const totalBytes = data.reduce((a, d) => a + d.bytes, 0)+ const totalAlerts = data.reduce((a, d) => a + d.alerts, 0)++ return (+ <div style={{+ height: expanded ? EXPANDED_H : COLLAPSED_H,+ background: '#0f172a',+ borderTop: '1px solid #1e3a5f',+ transition: 'height 0.2s ease',+ overflow: 'hidden',+ flexShrink: 0,+ position: 'relative',+ }}>+ {/* EN: Header row — click to collapse/expand.+ FR: Ligne d'en-tête — cliquer pour replier/déplier. */}+ <div+ onClick={() => setExpanded(v => !v)}+ style={{+ height: COLLAPSED_H, display: 'flex', alignItems: 'center',+ padding: '0 16px', gap: 20, cursor: 'pointer',+ borderBottom: expanded ? '1px solid #1e3a5f' : 'none',+ }}+ >+ <span style={{ fontSize: 10, fontWeight: 700, color: '#64748b', textTransform: 'uppercase', letterSpacing: 1 }}>+ {expanded ? 'v' : '^'} Timeline+ </span>++ <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>+ <Chip label={t('timeline_packets', totalPkts)} color="#3b82f6" />+ <Chip label={fmt(totalBytes)} color="#6366f1" />+ {totalAlerts > 0 && <Chip label={t('timeline_alerts', totalAlerts)} color="#f59e0b" />}+ </div>++ {/* EN: Range picker / FR: Sélecteur de plage */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>+ {[15, 30, 60].map(m => (+ <button+ key={m}+ onClick={e => { e.stopPropagation(); setRange(m) }}+ style={{+ background: range === m ? '#1e3a5f' : 'transparent',+ border: '1px solid #1e3a5f', borderRadius: 4,+ color: range === m ? '#93c5fd' : '#475569',+ fontSize: 9, padding: '2px 7px', cursor: 'pointer',+ }}+ >+ {m}min+ </button>+ ))}+ <div style={{+ display: 'flex', alignItems: 'center', gap: 5,+ fontSize: 9, color: '#22c55e', marginLeft: 8,+ }}>+ <div style={{ width: 5, height: 5, borderRadius: '50%', background: '#22c55e' }} />+ Live+ </div>+ </div>+ </div>++ {expanded && (+ <svg+ ref={svgRef}+ style={{ width: '100%', height: EXPANDED_H - COLLAPSED_H, display: 'block' }}+ />+ )}++ {/* EN: Hover tooltip / FR: Infobulle au survol */}+ {tooltip && (+ <div style={{+ position: 'fixed', left: tooltip.x + 12, top: tooltip.y - 60,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 6, padding: '6px 10px', fontSize: 10,+ color: '#e2e8f0', pointerEvents: 'none', zIndex: 500,+ }}>+ <div style={{ fontWeight: 700, marginBottom: 3 }}>{fmtMinute(tooltip.d.minute)}</div>+ <div>{t('timeline_packets', tooltip.d.packets)}</div>+ <div style={{ color: '#64748b' }}>{fmt(tooltip.d.bytes)}</div>+ {tooltip.d.alerts > 0 && (+ <div style={{ color: '#f59e0b', marginTop: 2 }}>! {t('timeline_alerts', tooltip.d.alerts)}</div>+ )}+ </div>+ )}+ </div>+ )+}++function Chip({ label, color }) {+ return (+ <span style={{+ fontSize: 10, color, background: color + '1a',+ border: `1px solid ${color}44`, borderRadius: 10, padding: '1px 8px',+ }}>+ {label}+ </span>+ )+}diff --git a/frontend/src/graph/ForceGraph.jsx b/frontend/src/graph/ForceGraph.jsxnew file mode 100644index 0000000..06cf8f0--- /dev/null+++ b/frontend/src/graph/ForceGraph.jsx@@ -0,0 +1,246 @@+/**+ * Snitch — D3 force-directed graph view.+ *+ * EN: The main visualization. Every remote host and LAN device is a node,+ * every connection an edge anchored on the central "local" node. The+ * simulation is rebuilt whenever the data changes, but node positions+ * are cached in `posCache` so the layout stays stable across updates —+ * the sim only reheats when new nodes appear. Once cooled, every node is+ * pinned (fx/fy) so the graph never drifts.+ * A second lightweight effect dims non-matching nodes/links when the+ * search filter is active, without restarting the simulation.+ *+ * FR: La visualisation principale. Chaque hôte distant et appareil LAN est un+ * nœud, chaque connexion une arête ancrée sur le nœud central « local ».+ * La simulation est reconstruite à chaque changement de données, mais les+ * positions des nœuds sont mises en cache dans `posCache` pour garder une+ * mise en page stable — la sim ne se réchauffe que quand de nouveaux nœuds+ * apparaissent. Une fois refroidie, chaque nœud est épinglé (fx/fy) pour+ * que le graphe ne dérive jamais.+ * Un second effet léger estompe les nœuds/liens non correspondants quand+ * le filtre de recherche est actif, sans relancer la simulation.+ */+import { useEffect, useRef } from 'react'+import * as d3 from 'd3'+import { nodeIconURI } from './icons'++export default function ForceGraph({ nodes, edges, lanDevices, alertedNodes = new Set(), onNodeClick, filter }) {+ const svgRef = useRef(null)+ const nodeRef = useRef(null)+ const linkRef = useRef(null)+ // EN: { nodeId: {x, y, fx, fy} } — persists positions across re-renders.+ // FR: { nodeId: {x, y, fx, fy} } — conserve les positions entre les rendus.+ const posCache = useRef({})++ // ── Full simulation — reruns when data changes ────────────────────────────+ // ── Simulation complète — relancée à chaque changement de données ─────────+ useEffect(() => {+ const svg = d3.select(svgRef.current)+ svg.selectAll('*').remove()++ const width = svgRef.current.clientWidth+ const height = svgRef.current.clientHeight++ const zoom = d3.zoom().scaleExtent([0.15, 6]).on('zoom', e => g.attr('transform', e.transform))+ svg.call(zoom)++ const g = svg.append('g')++ // EN: Arrowhead marker for directed edges. / FR: Marqueur de flèche pour les arêtes dirigées.+ svg.append('defs').append('marker')+ .attr('id', 'arrow')+ .attr('viewBox', '0 -5 10 10')+ .attr('refX', 22).attr('refY', 0)+ .attr('markerWidth', 6).attr('markerHeight', 6)+ .attr('orient', 'auto')+ .append('path').attr('fill', '#475569').attr('d', 'M0,-5L10,0L0,5')++ const allNodes = [...Object.values(nodes), ...Object.values(lanDevices)]+ const nodeIds = new Set(allNodes.map(n => n.id))+ // EN: D3 may have already replaced source/target with node objects —+ // normalize both shapes before filtering.+ // FR: D3 peut avoir déjà remplacé source/target par des objets nœud —+ // normaliser les deux formes avant de filtrer.+ const allEdges = Object.values(edges).filter(e => {+ const src = typeof e.source === 'object' ? e.source.id : e.source+ const tgt = typeof e.target === 'object' ? e.target.id : e.target+ return nodeIds.has(src) && nodeIds.has(tgt)+ })++ // EN: Restore cached positions — pinned nodes won't move at all.+ // FR: Restaurer les positions en cache — les nœuds épinglés ne bougent pas.+ let hasNew = false+ allNodes.forEach(n => {+ const c = posCache.current[n.id]+ if (c) { n.x = c.x; n.y = c.y; n.fx = c.fx; n.fy = c.fy }+ else { hasNew = true }+ })++ const sim = d3.forceSimulation(allNodes)+ .alpha(hasNew ? 0.6 : 0.05) // EN: barely reheat if nothing new+ // FR: réchauffer à peine si rien de nouveau+ .alphaDecay(0.04) // EN: settle ~2× faster / FR: stabilisation ~2× plus rapide+ .velocityDecay(0.55) // EN: more friction, less overshoot / FR: plus de friction, moins de dépassement+ .force('link', d3.forceLink(allEdges).id(d => d.id).distance(d => d.dashed ? 80 : 130).strength(0.4))+ .force('charge', d3.forceManyBody().strength(d => d.category === 'lan_device' ? -300 : -400))+ .force('center', d3.forceCenter(width / 2, height / 2).strength(0.03))+ .force('collision', d3.forceCollide(d => d.id === 'local' ? 30 : 20))+ // EN: Gentle pull toward center for LAN devices so they orbit "local".+ // FR: Légère attraction centrale pour les appareils LAN afin qu'ils orbitent « local ».+ .force('lan_x', d3.forceX(width / 2).strength(d => d.category === 'lan_device' ? 0.15 : 0))+ .force('lan_y', d3.forceY(height / 2).strength(d => d.category === 'lan_device' ? 0.15 : 0))++ const link = g.append('g').selectAll('line')+ .data(allEdges)+ .join('line')+ .attr('stroke', d => d.color || '#475569')+ .attr('stroke-opacity', d => d.dashed ? 0.35 : 0.55)+ .attr('stroke-width', d => d.dashed ? 1 : Math.min(1 + Math.log1p((d.bytes || 0) / 1024), 6))+ .attr('stroke-dasharray', d => d.dashed ? '5,4' : null)+ .attr('marker-end', d => d.dashed ? null : 'url(#arrow)')++ linkRef.current = link++ const linkLabel = g.append('g').selectAll('text')+ .data(allEdges.filter(e => !e.dashed))+ .join('text')+ .attr('fill', '#475569')+ .attr('font-size', 9)+ .attr('text-anchor', 'middle')+ .text(d => d.label)++ const node = g.append('g').selectAll('g')+ .data(allNodes)+ .join('g')+ .attr('cursor', 'pointer')+ .on('click', (_, d) => onNodeClick?.(d))+ .call(d3.drag()+ .on('start', (e, d) => { if (!e.active) sim.alphaTarget(0.15).restart(); d.fx = d.x; d.fy = d.y })+ .on('drag', (e, d) => { d.fx = e.x; d.fy = e.y })+ .on('end', (e, d) => {+ if (!e.active) sim.alphaTarget(0)+ // EN: Lock the node where the user dropped it.+ // FR: Verrouiller le nœud là où l'utilisateur l'a déposé.+ posCache.current[d.id] = { x: d.x, y: d.y, fx: d.x, fy: d.y }+ })+ )++ nodeRef.current = node++ const radius = d => d.id === 'local' ? 22 : d.category === 'lan_device' ? 18 : 13++ // EN: Pulsing red ring on alerted nodes.+ // FR: Anneau rouge pulsant sur les nœuds en alerte.+ node.filter(d => alertedNodes.has(d.id) || d.alerted)+ .append('circle')+ .attr('r', d => radius(d) + 9)+ .attr('fill', 'none')+ .attr('stroke', '#ef4444')+ .attr('stroke-width', 1.5)+ .attr('stroke-opacity', 0.7)+ .each(function () {+ d3.select(this).append('animate')+ .attr('attributeName', 'stroke-opacity')+ .attr('values', '0.7;0.1;0.7')+ .attr('dur', '1.5s').attr('repeatCount', 'indefinite')+ })++ // EN: Soft halo behind local/LAN nodes. / FR: Halo doux derrière les nœuds locaux/LAN.+ node.filter(d => d.id === 'local' || d.category === 'lan_device')+ .append('circle')+ .attr('r', d => radius(d) + 6)+ .attr('fill', d => d.color)+ .attr('fill-opacity', 0.15)++ node.append('circle')+ .attr('r', radius)+ .attr('fill', d => d.color || '#475569')+ .attr('fill-opacity', d => d.online === false ? 0.35 : 0.85)+ .attr('stroke', d => d.online === false ? '#475569' : '#1e293b')+ .attr('stroke-width', d => d.category === 'lan_device' ? 2.5 : 1.5)+ .attr('stroke-dasharray', d => d.online === false ? '4,3' : null)++ // EN: White Lucide icon inside the circle, via data-URI SVG.+ // FR: Icône Lucide blanche dans le cercle, via SVG en data-URI.+ const iconSize = d => d.id === 'local' ? 20 : d.category === 'lan_device' ? 16 : 12+ node.append('image')+ .attr('href', d => nodeIconURI(d))+ .attr('width', d => iconSize(d))+ .attr('height', d => iconSize(d))+ .attr('x', d => -iconSize(d) / 2)+ .attr('y', d => -iconSize(d) / 2)+ .attr('pointer-events', 'none')+ .attr('opacity', d => d.online === false ? 0.4 : 0.9)++ node.append('text')+ .attr('y', d => radius(d) + 11)+ .attr('text-anchor', 'middle')+ .attr('fill', d => d.category === 'lan_device' ? '#e2e8f0' : '#94a3b8')+ .attr('font-size', d => d.category === 'lan_device' ? 10 : 9)+ .attr('font-weight', d => d.category === 'lan_device' ? '600' : '400')+ .text(d => {+ const label = d.label || d.ip || ''+ return label.length > 20 ? label.slice(0, 18) + '…' : label+ })++ // EN: Native tooltip with full detail on hover.+ // FR: Infobulle native avec le détail complet au survol.+ node.append('title').text(d =>+ [d.label || d.ip, d.vendor, d.mac, d.country, d.org, `${d.packets || 0} pkts`]+ .filter(Boolean).join('\n')+ )++ sim.on('tick', () => {+ link+ .attr('x1', d => d.source.x).attr('y1', d => d.source.y)+ .attr('x2', d => d.target.x).attr('y2', d => d.target.y)+ linkLabel+ .attr('x', d => (d.source.x + d.target.x) / 2)+ .attr('y', d => (d.source.y + d.target.y) / 2)+ node.attr('transform', d => `translate(${d.x},${d.y})`)+ })++ // EN: Once the sim cools down, pin every node and cache its position.+ // FR: Une fois la sim refroidie, épingler chaque nœud et cacher sa position.+ sim.on('end', () => {+ allNodes.forEach(n => {+ n.fx = n.x; n.fy = n.y+ posCache.current[n.id] = { x: n.x, y: n.y, fx: n.x, fy: n.y }+ })+ })++ return () => sim.stop()+ }, [nodes, edges, lanDevices, alertedNodes])++ // ── Filter dimming — no simulation restart ────────────────────────────────+ // ── Estompage par filtre — sans relancer la simulation ────────────────────+ useEffect(() => {+ if (!nodeRef.current || !linkRef.current) return++ function matches(d) {+ if (!filter || (filter.category === 'all' && !filter.text)) return true+ if (d.id === 'local') return true+ const { text, category } = filter+ if (category !== 'all' && d.category !== category) return false+ if (text) {+ const t = text.toLowerCase()+ return (d.label || '').toLowerCase().includes(t)+ || (d.ip || '').toLowerCase().includes(t)+ || (d.country || '').toLowerCase().includes(t)+ || (d.org || '').toLowerCase().includes(t)+ || (d.hostname|| '').toLowerCase().includes(t)+ }+ return true+ }++ nodeRef.current.attr('opacity', d => matches(d) ? 1 : 0.1)++ linkRef.current.attr('stroke-opacity', d => {+ const src = typeof d.source === 'object' ? d.source : { id: d.source, category: '' }+ const tgt = typeof d.target === 'object' ? d.target : { id: d.target, category: '' }+ return (matches(src) || matches(tgt)) ? (d.dashed ? 0.35 : 0.55) : 0.04+ })+ }, [filter])++ return <svg ref={svgRef} style={{ width: '100%', height: '100%', background: '#0f172a' }} />+}diff --git a/frontend/src/graph/icons.js b/frontend/src/graph/icons.jsnew file mode 100644index 0000000..b2f98f7--- /dev/null+++ b/frontend/src/graph/icons.js@@ -0,0 +1,122 @@+/**+ * Snitch — node icon renderer.+ *+ * EN: D3 nodes are plain SVG, so we can't use React icons inside them.+ * This module hand-embeds Lucide path data (viewBox 0 0 24 24,+ * stroke-based) and builds cacheable `data:image/svg+xml` URIs that an+ * <image> element can draw inside each graph node.+ * FR: Les nœuds D3 sont du SVG pur, impossible d'y utiliser des icônes React.+ * Ce module embarque manuellement les données de chemins Lucide+ * (viewBox 0 0 24 24, en contour) et construit des URI+ * `data:image/svg+xml` cachables qu'un élément <image> peut dessiner dans+ * chaque nœud du graphe.+ */++// EN: Lucide stroke paths per icon name. / FR: Chemins Lucide (contour) par nom d'icône.+const PATHS = {+ laptop: [+ 'M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9',+ 'M2 16h20',+ 'M6 21h12',+ 'M12 16v5',+ ],+ wifi: [+ 'M5 12.55a11 11 0 0 1 14.08 0',+ 'M1.42 9a16 16 0 0 1 21.16 0',+ 'M8.53 16.11a6 6 0 0 1 6.95 0',+ 'M12 20h.01',+ ],+ smartphone: [+ 'M17 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2z',+ 'M12 18h.01',+ ],+ monitor: [+ 'M2 3h20v14H2z',+ 'M8 21h8',+ 'M12 17v4',+ ],+ tv: [+ 'M2 7h20v13H2z',+ 'M2 7V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v2',+ ],+ home: [+ 'M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z',+ 'M9 22V12h6v10',+ ],+ shield_check: [+ 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z',+ 'M9 12l2 2 4-4',+ ],+ radio: [+ 'M4.9 19.1C1 15.2 1 8.8 4.9 4.9',+ 'M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5',+ 'M12 12h.01',+ 'M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5',+ 'M19.1 4.9C23 8.8 23 15.1 19.1 19',+ ],+ zap: [+ 'M13 2L3 14h9l-1 8 10-12h-9l1-8z',+ ],+ globe: [+ 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z',+ 'M2 12h20',+ 'M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z',+ ],+ terminal: [+ 'M4 17l6-6-6-6',+ 'M12 19h8',+ ],+ help_circle: [+ 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z',+ 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3',+ 'M12 17h.01',+ ],+}++// EN: Data-URI cache — icons are rebuilt at most once per (type, color).+// FR: Cache de data-URI — les icônes ne sont reconstruites qu'une fois par (type, couleur).+const _cache = {}++function makeURI(type, color = '#ffffff') {+ const key = `${type}:${color}`+ if (_cache[key]) return _cache[key]+ const paths = PATHS[type] || PATHS.help_circle+ const elems = paths.map(d =>+ `<path d="${d}" stroke="${color}" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>`+ ).join('')+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">${elems}</svg>`+ _cache[key] = 'data:image/svg+xml,' + encodeURIComponent(svg)+ return _cache[key]+}++// EN: Traffic category → icon name. / FR: Catégorie de trafic → nom d'icône.+const CATEGORY_TO_ICON = {+ local: 'laptop',+ safe: 'shield_check',+ tracking: 'radio',+ cdn: 'zap',+ dns: 'globe',+ admin: 'terminal',+ unknown: 'help_circle',+}++// EN: LAN device type → icon name. / FR: Type d'appareil LAN → nom d'icône.+const DEVICE_TYPE_TO_ICON = {+ router: 'wifi',+ phone: 'smartphone',+ pc: 'monitor',+ tv: 'tv',+ iot: 'home',+ unknown: 'help_circle',+}++/**+ * EN: Pick the right icon for a graph node and return its data URI.+ * FR: Choisir la bonne icône pour un nœud du graphe et renvoyer sa data URI.+ */+export function nodeIconURI(d) {+ const iconType = d.category === 'lan_device'+ ? (DEVICE_TYPE_TO_ICON[d.device_type] || 'help_circle')+ : (CATEGORY_TO_ICON[d.category] || 'help_circle')+ return makeURI(iconType, '#ffffff')+}diff --git a/frontend/src/hooks/useWebSocket.js b/frontend/src/hooks/useWebSocket.jsnew file mode 100644index 0000000..b3d25a5--- /dev/null+++ b/frontend/src/hooks/useWebSocket.js@@ -0,0 +1,212 @@+/**+ * Snitch — WebSocket hook.+ *+ * EN: Single source of truth for realtime state. Maintains the node/edge/LAN+ * device maps, the recent-packet list, alerts, capture status and the+ * per-second bandwidth buckets that feed the sparkline. Automatically+ * reconnects every 2 s after a disconnect.+ * Also exposes the REST-backed control actions (start/stop capture,+ * filters, whitelist).+ *+ * FR: Source de vérité unique pour l'état temps réel. Maintient les tables de+ * nœuds/arêtes/appareils LAN, la liste des paquets récents, les alertes,+ * le statut de capture et les seaux de débit par seconde qui alimentent la+ * sparkline. Reconnexion automatique toutes les 2 s après une déconnexion.+ * Expose aussi les actions de contrôle REST (start/stop capture, filtres,+ * whitelist).+ */+import { useEffect, useRef, useState } from 'react'+import { API_BASE } from '../api'++export function useWebSocket(url) {+ const ws = useRef(null)+ const [nodes, setNodes] = useState({})+ const [edges, setEdges] = useState({})+ const [lanDevices, setLanDevices] = useState({})+ const [packets, setPackets] = useState([])+ const [alerts, setAlerts] = useState([])+ const [unread, setUnread] = useState(0)+ const [status, setStatus] = useState('connecting')+ const [bandwidth, setBandwidth] = useState([])+ const [capturing, setCapturing] = useState(true)+ const [portFilter, setPortFilter] = useState([])+ const [excludedProcesses, setExcludedProcesses] = useState([])+ const [whitelistedIps, setWhitelistedIps] = useState([])+ const [media, setMedia] = useState({ mic: [], camera: [] })+ // EN: { secondTimestamp: bytesReceivedThatSecond } — rolled into `bandwidth`.+ // FR: { timestampSeconde: octetsReçusCetteSeconde } — agrégé dans `bandwidth`.+ const bwRef = useRef({})++ // EN: Every second, fold the byte buckets into the `bandwidth` array and+ // drop buckets older than ~61 s.+ // FR: Chaque seconde, transformer les seaux d'octets en tableau `bandwidth`+ // et jeter les seaux de plus de ~61 s.+ useEffect(() => {+ const id = setInterval(() => {+ const now = Date.now()+ const cutoff = now - 61000+ Object.keys(bwRef.current).forEach(k => {+ if (+k < cutoff) delete bwRef.current[k]+ })+ const arr = Object.entries(bwRef.current)+ .map(([ts, bps]) => ({ ts: +ts, bps }))+ .sort((a, b) => a.ts - b.ts)+ setBandwidth(arr)+ }, 1000)+ return () => clearInterval(id)+ }, [])++ useEffect(() => {+ function connect() {+ ws.current = new WebSocket(url)++ ws.current.onopen = () => setStatus('connected')+ ws.current.onclose = () => {+ setStatus('disconnected')+ setTimeout(connect, 2000) // EN: auto-reconnect / FR: reconnexion auto+ }+ ws.current.onerror = () => setStatus('error')++ ws.current.onmessage = (evt) => {+ const msg = JSON.parse(evt.data)++ // EN: Initial snapshot — replaces all local state.+ // FR: Instantané initial — remplace tout l'état local.+ if (msg.type === 'init') {+ if (msg.media) setMedia(msg.media)+ if (msg.capturing !== undefined) setCapturing(msg.capturing)+ if (msg.ports !== undefined) setPortFilter(msg.ports)+ if (msg.excluded_processes !== undefined) setExcludedProcesses(msg.excluded_processes)+ if (msg.whitelisted_ips !== undefined) setWhitelistedIps(msg.whitelisted_ips)+ const nodeMap = {}, edgeMap = {}, deviceMap = {}+ msg.nodes.forEach(n => {+ if (n.category === 'lan_device') deviceMap[n.id] = n+ else nodeMap[n.id] = n+ })+ msg.edges.forEach(e => { edgeMap[e.id] = e })+ setNodes(nodeMap)+ setEdges(edgeMap)+ setLanDevices(deviceMap)+ 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).+ 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) * 1000+ bwRef.current[sec] = (bwRef.current[sec] || 0) + (msg.packet?.size || 0)+ }++ // EN: LAN device appeared / changed / went offline.+ // FR: Appareil LAN apparu / modifié / passé hors ligne.+ if (msg.type === 'device_update') {+ setLanDevices(prev => ({ ...prev, [msg.device.id]: msg.device }))+ setEdges(prev => ({ ...prev, [msg.edge.id]: msg.edge }))+ }++ if (msg.type === 'alert') {+ setAlerts(prev => [msg.alert, ...prev].slice(0, 200))+ setUnread(prev => prev + 1)+ }++ // EN: Capture/filter status changed (local or remote action).+ // FR: Le statut capture/filtres a changé (action locale ou distante).+ if (msg.type === 'capture_status') {+ setCapturing(msg.capturing)+ if (msg.ports !== undefined) setPortFilter(msg.ports)+ if (msg.excluded_processes !== undefined) setExcludedProcesses(msg.excluded_processes)+ if (msg.whitelisted_ips !== undefined) setWhitelistedIps(msg.whitelisted_ips)+ }++ // EN: Whitelisted nodes were removed server-side — mirror the removal.+ // FR: Des nœuds whitelistés ont été retirés côté serveur — refléter la suppression.+ if (msg.type === 'nodes_removed') {+ const removed = new Set(msg.ids || [])+ setNodes(prev => {+ const out = {}+ for (const [id, n] of Object.entries(prev)) if (!removed.has(id)) out[id] = n+ return out+ })+ setEdges(prev => {+ const out = {}+ for (const [id, e] of Object.entries(prev)) if (!removed.has(e.source) && !removed.has(e.target)) out[id] = e+ return out+ })+ }++ // EN: Mic/camera usage changed. / FR: L'usage micro/caméra a changé.+ if (msg.type === 'media') {+ setMedia({ mic: msg.mic || [], camera: msg.camera || [] })+ }++ // EN: Full graph reset (e.g. after the port filter changed).+ // FR: Réinitialisation complète du graphe (ex. après changement du filtre de ports).+ if (msg.type === 'reset') {+ const nodeMap = {}, deviceMap = {}+ ;(msg.nodes || []).forEach(n => {+ if (n.category === 'lan_device') deviceMap[n.id] = n+ else nodeMap[n.id] = n+ })+ const edgeMap = {}+ ;(msg.edges || []).forEach(e => { edgeMap[e.id] = e })+ setNodes(nodeMap)+ setEdges(edgeMap)+ setLanDevices(deviceMap)+ setPackets([])+ if (msg.ports !== undefined) setPortFilter(msg.ports)+ }+ }+ }++ connect()+ return () => ws.current?.close()+ }, [url])++ const clearUnread = () => setUnread(0)++ // ── REST control actions / Actions de contrôle REST ────────────────────────++ async function toggleCapture() {+ const endpoint = capturing ? '/capture/stop' : '/capture/start'+ const res = await fetch(`${API_BASE}${endpoint}`, { method: 'POST' })+ const data = await res.json()+ setCapturing(data.capturing)+ }++ async function updatePortFilter(ports) {+ const res = await fetch(`${API_BASE}/capture/ports`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ ports }),+ })+ const data = await res.json()+ setPortFilter(data.ports)+ }++ async function updateProcessFilter(excluded) {+ const res = await fetch(`${API_BASE}/capture/processes`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ excluded }),+ })+ const data = await res.json()+ setExcludedProcesses(data.excluded_processes)+ }++ async function updateIpWhitelist(ips) {+ const res = await fetch(`${API_BASE}/capture/whitelist`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ ips }),+ })+ const data = await res.json()+ setWhitelistedIps(data.whitelisted_ips)+ }++ return { nodes, edges, lanDevices, packets, alerts, unread, clearUnread, status, bandwidth, capturing, toggleCapture, portFilter, updatePortFilter, excludedProcesses, updateProcessFilter, whitelistedIps, updateIpWhitelist, media }+}diff --git a/frontend/src/i18n.jsx b/frontend/src/i18n.jsxnew file mode 100644index 0000000..67b1aab--- /dev/null+++ b/frontend/src/i18n.jsx@@ -0,0 +1,312 @@+/**+ * Snitch — internationalization (English / Français).+ *+ * EN: Tiny homemade i18n layer. Two flat dictionaries (`en` / `fr`) keyed by+ * string. Values can be plain strings or functions for interpolation,+ * e.g. t('lan_devices', 3) → "3 devices LAN" / "3 devices LAN".+ * `useT()` returns { lang, t, setLang } to any component.+ * FR: Petite couche i18n maison. Deux dictionnaires plats (`en` / `fr`) indexés+ * par chaîne. Les valeurs peuvent être des chaînes simples ou des fonctions+ * pour l'interpolation, ex. t('lan_devices', 3) → "3 devices LAN".+ * `useT()` renvoie { lang, t, setLang } à tout composant.+ */+import { createContext, useContext, useState } from 'react'++// ── English dictionary / Dictionnaire anglais ────────────────────────────────+const en = {+ // Navigation+ nav_graph: 'Graph',+ nav_map: 'Map',++ // Status badge / Badge de statut+ status_connected: 'Live',+ status_connecting: 'Connecting…',+ status_disconnected: 'Disconnected',+ status_error: 'Error',+ lan_devices: n => `${n} device${n > 1 ? 's' : ''} LAN`,++ // Legend / Légende+ legend_alert: 'Alert',+ legend_unknown: 'Unknown',++ // Sidebar header + stats / En-tête de barre latérale + stats+ app_name: 'SNITCH',+ tagline: "Know who's talking.",+ stat_lan: 'LAN Devices',+ stat_ext: 'Ext. hosts',+ stat_traffic: 'Traffic',++ // Sidebar sections / Sections de la barre latérale+ section_lan: n => `LAN Devices (${n})`,+ section_ext: (n, total) => total ? `External hosts (${n}/${total})` : `External hosts (${n})`,+ section_packets: 'Recent traffic',++ // Node detail field labels / Étiquettes des champs de détail de nœud+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'Hostname',+ field_vendor: 'Vendor',+ field_type: 'Type',+ field_country: 'Country',+ field_city: 'City',+ field_org: 'Org',+ field_category: 'Category',+ field_traffic: 'Traffic',+ field_packets: 'Packets',+ processes: 'Processes',+ online: 'online',+ offline: 'offline',++ // Search / Recherche+ search_placeholder: 'Search host, IP, country…',+ cat_all: 'All',+ cat_unknown: 'Unknown',++ // Alert panel / Panneau d'alertes+ alerts_title: 'Alerts',+ alerts_total: 'total',+ alerts_empty: 'No alerts yet',+ alert_NEW_HOST: 'New host',+ alert_SUSPICIOUS_PROCESS: 'Suspicious process',+ alert_SUSPICIOUS_PORT: 'Suspicious port',+ alert_BEACON: 'Beacon C2',+ alert_VOLUME_SPIKE: 'Traffic spike',+ alert_NEW_LAN_DEVICE: 'New device',+ alert_DEVICE_OFFLINE: 'Device offline',+ alert_MEDIA_EXFIL: 'Media exfiltration',+ time_just_now: 'just now',+ time_seconds: n => `${n}s ago`,+ time_minutes: n => `${n}min ago`,+ time_hours: n => `${n}h ago`,++ // Privacy score / Score de confidentialité+ privacy_title: 'Privacy Score',+ privacy_critical_label: 'Critical',+ privacy_excellent_label: 'Excellent',+ privacy_risk_factors: n => `${n} risk factor${n !== 1 ? 's' : ''}`,+ privacy_more_factors: n => `+${n} more factor${n > 1 ? 's' : ''}`,+ privacy_label_excellent: 'Excellent',+ privacy_label_good: 'Good',+ privacy_label_average: 'Average',+ privacy_label_weak: 'Weak',+ privacy_label_critical: 'Critical',++ // Timeline+ timeline_packets: n => `${n.toLocaleString()} packets`,+ timeline_alerts: n => `${n} alert${n > 1 ? 's' : ''}`,++ // Capture toggle / Bascule de capture+ capture_stop: 'Stop',+ capture_start: 'Start',+ capture_stopping: 'Stopping…',+ capture_starting: 'Starting…',++ // Port filter / Filtre de ports+ port_filter: 'Ports',+ port_all: 'All ports',+ port_placeholder: 'Add port (e.g. 443)',+ port_invalid: 'Invalid port',++ // Export+ export_btn: 'Export',+ export_graph_json: 'Graph (JSON)',+ export_graph_csv: 'Graph (CSV)',+ export_alerts_json: 'Alerts (JSON)',+ export_alerts_csv: 'Alerts (CSV)',++ // Process filter / Filtre de processus+ process_filter: 'Apps',+ process_filter_hint: 'Click to hide app from graph',+ process_none: 'No processes detected yet',+ process_clear: 'Show all apps',++ // IP whitelist / Liste blanche d'IP+ ip_whitelist: 'Trusted',+ ip_whitelist_hint: 'Trusted IPs are no longer captured or shown',+ ip_placeholder: 'Add IP (e.g. 1.1.1.1)',+ ip_invalid: 'Invalid IP address',+ ip_clear: 'Clear whitelist',+ whitelist_action: 'Mark as trusted',++ // Map / Carte+ map_you: 'You',+ map_located: n => `${n} located host${n !== 1 ? 's' : ''}`,+ map_no_geo: 'no geo',++ // Scoring factor labels / Libellés des facteurs de score+ score_trackers: n => `${n} tracker${n > 1 ? 's' : ''} contacted`,+ score_tracker_traffic: pct => `${pct}% traffic to trackers`,+ score_ad_networks: n => `${n} ad network${n > 1 ? 's' : ''}`,+ score_beacons: n => `${n} beacon behavior${n > 1 ? 's' : ''}`,+ score_susp_proc: n => `${n} suspicious process${n > 1 ? 'es' : ''}`,+ score_susp_ports: n => `${n} dangerous port${n > 1 ? 's' : ''}`,+ score_critical_alerts: n => `${n} critical alert${n > 1 ? 's' : ''}`,+ score_warnings: n => `${n} warnings`,+ score_https_ratio: pct => `${pct}% HTTPS traffic`,+ score_no_trackers: 'No trackers detected',+}++// ── Dictionnaire français / French dictionary ────────────────────────────────+const fr = {+ // Navigation+ nav_graph: 'Graphe',+ nav_map: 'Carte',++ // Badge de statut / Status badge+ status_connected: 'Live',+ status_connecting: 'Connexion…',+ status_disconnected: 'Déconnecté',+ status_error: 'Erreur',+ lan_devices: n => `${n} appareil${n > 1 ? 's' : ''} LAN`,++ // Légende / Legend+ legend_alert: 'Alerte',+ legend_unknown: 'Inconnu',++ // En-tête de barre latérale + stats / Sidebar header + stats+ app_name: 'SNITCH',+ tagline: 'Sache qui parle.',+ stat_lan: 'Appareils LAN',+ stat_ext: 'Hôtes ext.',+ stat_traffic: 'Trafic',++ // Sections de la barre latérale / Sidebar sections+ section_lan: n => `Appareils LAN (${n})`,+ section_ext: (n, total) => total ? `Hôtes externes (${n}/${total})` : `Hôtes externes (${n})`,+ section_packets: 'Flux récents',++ // Étiquettes des champs de détail de nœud / Node detail field labels+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'Nom d\'hôte',+ field_vendor: 'Fabricant',+ field_type: 'Type',+ field_country: 'Pays',+ field_city: 'Ville',+ field_org: 'Org',+ field_category: 'Catégorie',+ field_traffic: 'Trafic',+ field_packets: 'Paquets',+ processes: 'Processus',+ online: 'en ligne',+ offline: 'hors ligne',++ // Recherche / Search+ search_placeholder: 'Rechercher hôte, IP, pays…',+ cat_all: 'Tout',+ cat_unknown: 'Inconnu',++ // Panneau d'alertes / Alert panel+ alerts_title: 'Alertes',+ alerts_total: 'total',+ alerts_empty: "Aucune alerte pour l'instant",+ alert_NEW_HOST: 'Nouvel hôte',+ alert_SUSPICIOUS_PROCESS: 'Processus suspect',+ alert_SUSPICIOUS_PORT: 'Port suspect',+ alert_BEACON: 'Beacon C2',+ alert_VOLUME_SPIKE: 'Pic de trafic',+ alert_NEW_LAN_DEVICE: 'Nouvel appareil',+ alert_DEVICE_OFFLINE: 'Appareil hors ligne',+ alert_MEDIA_EXFIL: 'Exfiltration média',+ time_just_now: "à l'instant",+ time_seconds: n => `il y a ${n}s`,+ time_minutes: n => `il y a ${n}min`,+ time_hours: n => `il y a ${n}h`,++ // Score de confidentialité / Privacy score+ privacy_title: 'Score de confidentialité',+ privacy_critical_label: 'Critique',+ privacy_excellent_label: 'Excellent',+ privacy_risk_factors: n => `${n} facteur${n !== 1 ? 's' : ''} de risque`,+ privacy_more_factors: n => `+${n} autre${n > 1 ? 's' : ''} facteur${n > 1 ? 's' : ''}`,+ privacy_label_excellent: 'Excellente',+ privacy_label_good: 'Bonne',+ privacy_label_average: 'Moyenne',+ privacy_label_weak: 'Faible',+ privacy_label_critical: 'Critique',++ // Timeline+ timeline_packets: n => `${n.toLocaleString('fr-FR')} paquets`,+ timeline_alerts: n => `${n} alerte${n > 1 ? 's' : ''}`,++ // Bascule de capture / Capture toggle+ capture_stop: 'Stop',+ capture_start: 'Démarrer',+ capture_stopping: 'Arrêt…',+ capture_starting: 'Démarrage…',++ // Filtre de ports / Port filter+ port_filter: 'Ports',+ port_all: 'Tous les ports',+ port_placeholder: 'Ajouter un port (ex: 443)',+ port_invalid: 'Port invalide',++ // Export+ export_btn: 'Exporter',+ export_graph_json: 'Graphe (JSON)',+ export_graph_csv: 'Graphe (CSV)',+ export_alerts_json: 'Alertes (JSON)',+ export_alerts_csv: 'Alertes (CSV)',++ // Filtre de processus / Process filter+ process_filter: 'Apps',+ process_filter_hint: 'Cliquer pour masquer une app du graphe',+ process_none: 'Aucun processus détecté pour l\'instant',+ process_clear: 'Tout afficher',++ // Liste blanche d'IP / IP whitelist+ ip_whitelist: 'Confiance',+ ip_whitelist_hint: 'Les IP de confiance ne sont plus capturées ni affichées',+ ip_placeholder: 'Ajouter une IP (ex: 1.1.1.1)',+ ip_invalid: 'Adresse IP invalide',+ ip_clear: 'Vider la liste',+ whitelist_action: 'Marquer comme fiable',++ // Carte / Map+ map_you: 'Vous',+ map_located: n => `${n} hôte${n !== 1 ? 's' : ''} localisé${n !== 1 ? 's' : ''}`,+ map_no_geo: 'sans géo',++ // Libellés des facteurs de score / Scoring factor labels+ score_trackers: n => `${n} tracker${n > 1 ? 's' : ''} contacté${n > 1 ? 's' : ''}`,+ score_tracker_traffic: pct => `${pct}% de trafic vers des trackers`,+ score_ad_networks: n => `${n} régie${n > 1 ? 's' : ''} publicitaire${n > 1 ? 's' : ''}`,+ score_beacons: n => `${n} comportement${n > 1 ? 's' : ''} beacon`,+ score_susp_proc: n => `${n} processus suspect${n > 1 ? 's' : ''}`,+ score_susp_ports: n => `${n} port${n > 1 ? 's' : ''} dangereux`,+ score_critical_alerts: n => `${n} alerte${n > 1 ? 's' : ''} critique${n > 1 ? 's' : ''}`,+ score_warnings: n => `${n} alertes`,+ score_https_ratio: pct => `${pct}% de trafic HTTPS`,+ score_no_trackers: 'Aucun tracker détecté',+}++// ── Context / Contexte ───────────────────────────────────────────────────────+const I18nContext = createContext(null)++/**+ * EN: Provides { lang, t, setLang } to the whole tree. `t(key, ...args)`+ * resolves a dictionary entry — functions are called with args, strings+ * returned as-is, missing keys fall back to the key itself.+ * FR: Fournit { lang, t, setLang } à tout l'arbre. `t(key, ...args)` résout une+ * entrée du dictionnaire — les fonctions sont appelées avec args, les+ * chaînes renvoyées telles quelles, les clés manquantes retombent sur la clé.+ */+export function I18nProvider({ children }) {+ const [lang, setLang] = useState('en')+ const dict = lang === 'fr' ? fr : en++ function t(key, ...args) {+ const val = dict[key]+ if (val === undefined) return key+ if (typeof val === 'function') return val(...args)+ return val+ }++ return (+ <I18nContext.Provider value={{ lang, t, setLang }}>+ {children}+ </I18nContext.Provider>+ )+}++export const useT = () => useContext(I18nContext)diff --git a/frontend/src/main.jsx b/frontend/src/main.jsxnew file mode 100644index 0000000..40b020a--- /dev/null+++ b/frontend/src/main.jsx@@ -0,0 +1,20 @@+/**+ * Snitch — React entry point.+ *+ * EN: Mounts the App inside StrictMode and wraps it in the I18nProvider so+ * every component can call `useT()` for EN/FR translations.+ * FR: Monte l'App dans StrictMode et l'enveloppe dans l'I18nProvider pour que+ * chaque composant puisse appeler `useT()` pour les traductions EN/FR.+ */+import React from 'react'+import ReactDOM from 'react-dom/client'+import App from './App'+import { I18nProvider } from './i18n'++ReactDOM.createRoot(document.getElementById('root')).render(+ <React.StrictMode>+ <I18nProvider>+ <App />+ </I18nProvider>+ </React.StrictMode>+)diff --git a/frontend/src/map/MapView.jsx b/frontend/src/map/MapView.jsxnew file mode 100644index 0000000..e951846--- /dev/null+++ b/frontend/src/map/MapView.jsx@@ -0,0 +1,440 @@+/**+ * Snitch — world map view.+ *+ * EN: D3 + TopoJSON natural-earth map. The user's position (browser+ * geolocation, Paris fallback) sits at the origin; geolocated remote+ * hosts are drawn as pulsing dots with animated dashed arcs flowing from+ * the user. Node coordinates get a small deterministic jitter so hosts+ * sharing a datacenter don't stack on one pixel.+ * Labels use a collision pass (`applyLabelCollision`) — highest-traffic+ * nodes win — and everything is counter-scaled by the zoom factor `k`+ * so stroke widths and fonts stay constant on screen.+ *+ * FR: Carte natural-earth D3 + TopoJSON. La position de l'utilisateur+ * (géolocalisation navigateur, repli sur Paris) est l'origine ; les hôtes+ * distants géolocalisés sont des points pulsants avec des arcs animés en+ * pointillés partant de l'utilisateur. Les coordonnées reçoivent un+ * jitter déterministe pour que les hôtes d'un même datacenter ne se+ * superposent pas.+ * Les étiquettes passent par une détection de collision+ * (`applyLabelCollision`) — les nœuds au plus fort trafic gagnent — et+ * tout est contre-dimensionné par le facteur de zoom `k` pour que les+ * épaisseurs et polices restent constantes à l'écran.+ */+import { useEffect, useRef, useState } from 'react'+import * as d3 from 'd3'+import * as topojson from 'topojson-client'+import { useT } from '../i18n'++const STYLE = `+ @keyframes arcFlow {+ from { stroke-dashoffset: 1; }+ to { stroke-dashoffset: 0; }+ }+ .arc-flow { animation: arcFlow linear infinite; }+`++/** EN: Stable per-id hash. / FR: Hash stable par id. */+function hashId(id) {+ let h = 0+ for (const c of String(id)) h = (h * 31 + c.charCodeAt(0)) & 0xffff+ return h+}++/**+ * EN: Deterministic offset so co-located hosts don't overlap.+ * FR: Décalage déterministe pour éviter la superposition des hôtes co-localisés.+ */+function jitter(id) {+ const h = hashId(id)+ const angle = (h / 0x8000) * Math.PI * 2+ const r = 0.3 + (h & 0xff) / 255 * 1.2+ return [Math.cos(angle) * r, Math.sin(angle) * r]+}++/** EN: Per-arc animation duration (varied for organic feel). / FR: Durée d'animation par arc (variée pour un effet organique). */+function animDur(id) {+ return (1.8 + (hashId(id) / 0xffff) * 2).toFixed(2) + 's'+}++// ── Label collision detection in map-coordinate space ────────────────────────+// EN: Nodes with more traffic take priority; losers hide their labels.+// FR: Les nœuds au plus fort trafic sont prioritaires ; les perdants cachent leurs étiquettes.+function applyLabelCollision(g, k) {+ const SHOW_AT = 2.5+ if (k < SHOW_AT) {+ g.selectAll('g.dest .dot-label').attr('display', 'none')+ return+ }++ const items = []+ g.selectAll('g.dest').each(function (d) {+ const t = d3.select(this).attr('transform') || ''+ const m = t.match(/translate\(([^,]+),([^)]+)\)/)+ if (!m) return+ items.push({ el: this, d, mx: +m[1], my: +m[2] })+ })++ items.sort((a, b) => (b.d?.bytes || 0) - (a.d?.bytes || 0))++ const placed = [] // EN: accepted bounding boxes (map coords) / FR: boîtes acceptées (coords carte)++ for (const { el, d, mx, my } of items) {+ const labelSel = d3.select(el).select('.dot-label')+ const text = labelSel.text()+ if (!text) { labelSel.attr('display', 'none'); continue }++ const fs = Math.max(9 / k, 5)+ const lw = text.length * fs * 0.58+ const lh = fs + 2+ const r = Math.min(3 + Math.log1p((d?.packets || 0) * 0.4), 9) / k+ const ly = my + r + 10 / k // EN: label center-y (below dot) / FR: y du centre de l'étiquette (sous le point)+ const pad = 4 / k++ const box = { x: mx - lw / 2 - pad, y: ly - lh / 2 - pad, w: lw + pad * 2, h: lh + pad * 2 }++ const hit = placed.some(b =>+ box.x < b.x + b.w && box.x + box.w > b.x &&+ box.y < b.y + b.h && box.y + box.h > b.y+ )++ if (hit) {+ labelSel.attr('display', 'none')+ } else {+ labelSel.attr('display', null)+ placed.push(box)+ }+ }+}++export default function MapView({ nodes, onNodeClick }) {+ const { t, lang } = useT()+ const svgRef = useRef(null)+ const gRef = useRef(null)+ const projRef = useRef(null)+ const kRef = useRef(1)+ const userPosRef = useRef(null)++ const [worldTopo, setWorldTopo] = useState(null)+ const [userPos, setUserPos] = useState(null)+ const [tooltip, setTooltip] = useState(null)++ // EN: Load the world TopoJSON + resolve the user's position once.+ // FR: Charger le TopoJSON du monde + résoudre la position utilisateur une fois.+ useEffect(() => {+ const worldUrl = window.location.protocol === 'file:'+ ? new URL('countries-110m.json', window.location.href).href+ : '/countries-110m.json'+ fetch(worldUrl).then(r => r.json()).then(setWorldTopo)+ navigator.geolocation?.getCurrentPosition(+ p => setUserPos([p.coords.longitude, p.coords.latitude]),+ () => setUserPos([2.35, 48.85]) // EN: Paris fallback / FR: repli sur Paris+ )+ if (!navigator.geolocation) setUserPos([2.35, 48.85])+ }, [])++ useEffect(() => {+ if (!worldTopo || !userPos || !svgRef.current) return+ userPosRef.current = userPos+ drawBase(worldTopo, userPos, t('map_you'))+ }, [worldTopo, userPos, lang])++ useEffect(() => {+ if (!gRef.current || !projRef.current) return+ drawConnections(projRef.current)+ }, [nodes])++ /**+ * EN: Counter-scale all fixed-screen-size elements after a zoom so text and+ * strokes stay readable at any zoom level.+ * FR: Contre-dimensionner tous les éléments à taille écran fixe après un+ * zoom pour que texte et traits restent lisibles à tout niveau.+ */+ function rescaleAll(k) {+ const g = gRef.current+ if (!g) return++ g.select('.graticule').attr('stroke-width', 0.3 / k)+ g.select('.borders').attr('stroke-width', 0.3 / k)+ g.selectAll('.countries path').attr('stroke-width', 0.5 / k)++ g.selectAll('path.arc-flow').each(function (d) {+ const base = 0.8 + Math.log1p((d?.bytes || 0) / 512)+ d3.select(this).attr('stroke-width', Math.min(base, 3.5) / k)+ })++ g.selectAll('g.dest').each(function (d) {+ const r = Math.min(3 + Math.log1p((d?.packets || 0) * 0.4), 9)+ const vr = r / k+ d3.select(this).select('.dot').attr('r', vr).attr('stroke-width', 1 / k)+ d3.select(this).select('.dot-label')+ .attr('font-size', Math.max(9 / k, 5))+ .attr('y', vr + 10 / k)+ })++ g.select('.user-dot').attr('r', 7 / k).attr('stroke-width', 1.5 / k)+ g.select('.user-label').attr('font-size', 11 / k).attr('x', function () {+ return +d3.select(this).attr('data-ux') + 10 / k+ })++ // EN: Recompute collision at the new zoom level.+ // FR: Recalculer les collisions au nouveau niveau de zoom.+ applyLabelCollision(g, k)+ }++ /**+ * EN: Draw the static map layers: ocean, graticule, countries, borders,+ * the user's pulsing location, and the (empty) arc/dot groups.+ * FR: Dessiner les couches statiques : océan, graticule, pays, frontières,+ * la position pulsante de l'utilisateur et les groupes arcs/points+ * (initialement vides).+ */+ function drawBase(topo, pos, youLabel) {+ const el = svgRef.current+ const svg = d3.select(el)+ svg.selectAll('*').remove()+ svg.append('defs').append('style').text(STYLE)++ const W = el.clientWidth+ const H = el.clientHeight++ const projection = d3.geoNaturalEarth1()+ .scale(W / 6.3)+ .translate([W / 2, H / 2])+ projRef.current = projection++ const geoPath = d3.geoPath().projection(projection)++ const zoom = d3.zoom()+ .scaleExtent([0.7, 20])+ .on('zoom', e => {+ g.attr('transform', e.transform)+ kRef.current = e.transform.k+ rescaleAll(e.transform.k)+ })+ svg.call(zoom)++ const g = svg.append('g')+ gRef.current = g++ // EN: Ocean background (oversized for pan headroom).+ // FR: Fond océan (surdimensionné pour la marge de déplacement).+ g.append('rect')+ .attr('width', W * 4).attr('height', H * 4)+ .attr('x', -W).attr('y', -H)+ .attr('fill', '#0a1628')++ g.append('path')+ .attr('class', 'graticule')+ .datum(d3.geoGraticule()())+ .attr('d', geoPath)+ .attr('fill', 'none')+ .attr('stroke', '#1e3a5f')+ .attr('stroke-width', 0.3)++ const countries = topojson.feature(topo, topo.objects.countries)+ g.append('g').attr('class', 'countries')+ .selectAll('path')+ .data(countries.features)+ .join('path')+ .attr('d', geoPath)+ .attr('fill', '#1e293b')+ .attr('stroke', '#2d4a6e')+ .attr('stroke-width', 0.5)++ g.append('path')+ .attr('class', 'borders')+ .datum(topojson.mesh(topo, topo.objects.countries, (a, b) => a !== b))+ .attr('d', geoPath)+ .attr('fill', 'none')+ .attr('stroke', '#334155')+ .attr('stroke-width', 0.3)++ // EN: Layer order matters: arcs below dots.+ // FR: L'ordre des couches compte : arcs sous les points.+ g.append('g').attr('class', 'arcs')+ g.append('g').attr('class', 'dots')++ // EN: User's position — pulsing rings + blue dot + "You/Vous" label.+ // FR: Position de l'utilisateur — anneaux pulsants + point bleu + label.+ const up = projection(pos)+ if (up) {+ const [ux, uy] = up+ const userG = g.append('g').attr('class', 'user-loc')++ for (let i = 0; i < 2; i++) {+ const base = 10 + i * 8+ userG.append('circle')+ .attr('cx', ux).attr('cy', uy).attr('r', base)+ .attr('fill', 'none').attr('stroke', '#3b82f6')+ .attr('stroke-opacity', 0.3 - i * 0.1)+ .append('animate').attr('attributeName', 'r')+ .attr('values', `${base};${base + 18};${base}`)+ .attr('dur', `${2.5 + i * 0.8}s`).attr('repeatCount', 'indefinite')+ }++ userG.append('circle')+ .attr('class', 'user-dot')+ .attr('cx', ux).attr('cy', uy).attr('r', 7)+ .attr('fill', '#3b82f6').attr('fill-opacity', 0.9)+ .attr('stroke', '#93c5fd').attr('stroke-width', 1.5)++ userG.append('text')+ .attr('class', 'user-label')+ .attr('data-ux', ux)+ .attr('x', ux + 10).attr('y', uy + 4)+ .attr('fill', '#93c5fd').attr('font-size', 11).attr('font-weight', '700')+ .text(youLabel)+ }++ drawConnections(projection)+ }++ /**+ * EN: Join/update/exit arcs + destination dots for geolocated nodes.+ * Called on every `nodes` prop change — D3's data join makes updates+ * cheap (only diffs are touched).+ * FR: Entrée/mise à jour/sortie des arcs + points de destination pour les+ * nœuds géolocalisés. Appelé à chaque changement de `nodes` — le data+ * join de D3 rend les mises à jour légères (seuls les diffs bougent).+ */+ function drawConnections(projection) {+ const g = gRef.current+ if (!g) return+ const geoPath = d3.geoPath().projection(projection)+ const pos = userPosRef.current || [2.35, 48.85]+ const k = kRef.current++ const geoNodes = Object.values(nodes)+ .filter(n => n.id !== 'local' && n.lat != null && n.lon != null)++ // ── Arcs ────────────────────────────────────────────────────────────────+ const arcs = g.select('.arcs').selectAll('path.arc-flow')+ .data(geoNodes, d => d.id)++ const arcsEnter = arcs.enter().append('path')+ .attr('class', 'arc-flow')+ .attr('fill', 'none')+ .attr('pointer-events', 'none')+ .style('animation-duration', d => animDur(d.id))++ arcsEnter.merge(arcs)+ .attr('d', d => {+ const [jx, jy] = jitter(d.id)+ return geoPath({ type: 'LineString', coordinates: [pos, [d.lon + jx, d.lat + jy]] })+ })+ .attr('stroke', d => d.color || '#94a3b8')+ .attr('stroke-opacity', 0.4)+ .attr('stroke-width', d => Math.min(0.8 + Math.log1p((d.bytes || 0) / 512), 3.5) / k)+ .each(function () {+ // EN: pathLength normalizes the dash cycle so CSS animation works+ // on any arc length.+ // FR: pathLength normalise le cycle de pointillés pour que l'animation+ // CSS fonctionne quelle que soit la longueur d'arc.+ const len = this.getTotalLength() || 500+ d3.select(this)+ .attr('stroke-dasharray', `${len * 0.1} ${len * 0.9}`)+ .attr('pathLength', 1)+ })++ arcs.exit().remove()++ // ── Destination dots / Points de destination ────────────────────────────+ const dotGroups = g.select('.dots').selectAll('g.dest')+ .data(geoNodes, d => d.id)++ const enter = dotGroups.enter().append('g').attr('class', 'dest')+ enter.append('circle').attr('class', 'pulse').attr('fill', 'none').attr('stroke-opacity', 0)+ enter.append('circle').attr('class', 'dot').attr('stroke', '#0a1628')+ enter.append('text').attr('class', 'dot-label').attr('fill', '#cbd5e1').attr('text-anchor', 'middle').attr('pointer-events', 'none')++ const all = enter.merge(dotGroups)++ all.each(function (d) {+ const [jx, jy] = jitter(d.id)+ const pt = projection([d.lon + jx, d.lat + jy])+ if (!pt) return+ const [x, y] = pt+ const r = Math.min(3 + Math.log1p(d.packets || 0) * 0.4, 9)+ const vr = r / k++ d3.select(this).attr('transform', `translate(${x},${y})`)++ const pulse = d3.select(this).select('.pulse')+ pulse.attr('r', (r + 3) / k).attr('stroke', d.color || '#94a3b8')+ pulse.selectAll('animate').remove()+ pulse.append('animate').attr('attributeName', 'stroke-opacity')+ .attr('values', '0.5;0;0.5').attr('dur', '3s').attr('repeatCount', 'indefinite')++ d3.select(this).select('.dot')+ .attr('r', vr)+ .attr('fill', d.color || '#94a3b8')+ .attr('stroke-width', 1 / k)+ .attr('cursor', 'pointer')++ d3.select(this).select('.dot-label')+ .attr('display', 'none') // EN: collision pass decides visibility+ // FR: la passe de collision décide de la visibilité+ .attr('font-size', Math.max(9 / k, 5))+ .attr('y', vr + 10 / k)+ .text(() => {+ const lbl = d.label || d.ip || ''+ return lbl.length > 18 ? lbl.slice(0, 16) + '…' : lbl+ })+ })++ all+ .on('mouseover', (e, d) => setTooltip({ x: e.clientX, y: e.clientY, node: d }))+ .on('mouseout', () => setTooltip(null))+ .on('click', (_, d) => onNodeClick?.(d))++ dotGroups.exit().remove()++ applyLabelCollision(g, k)+ }++ const geoCount = Object.values(nodes).filter(n => n.id !== 'local' && n.lat).length+ const noGeoCount = Object.values(nodes).filter(n => n.id !== 'local' && !n.lat).length++ return (+ <div style={{ width: '100%', height: '100%', position: 'relative' }}>+ <svg ref={svgRef} style={{ width: '100%', height: '100%' }} />++ {/* EN: Geolocated-host counter badge / FR: Badge compteur d'hôtes géolocalisés */}+ <div style={{+ position: 'absolute', top: 16, left: 16,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 8, padding: '8px 14px', fontSize: 10, color: '#64748b',+ }}>+ <span style={{ color: '#22c55e', fontWeight: 700 }}>{t('map_located', geoCount)}</span>+ {noGeoCount > 0 && <span> · <span style={{ color: '#f59e0b' }}>{noGeoCount}</span> {t('map_no_geo')}</span>}+ </div>++ {/* EN: Hover tooltip / FR: Infobulle au survol */}+ {tooltip && (+ <div style={{+ position: 'fixed', left: tooltip.x + 14, top: tooltip.y - 10, zIndex: 100,+ background: '#1e293b', border: '1px solid #334155',+ borderRadius: 8, padding: '8px 12px', pointerEvents: 'none',+ boxShadow: '0 4px 20px rgba(0,0,0,0.5)',+ }}>+ <div style={{ fontWeight: 700, fontSize: 12, color: '#f1f5f9', marginBottom: 3 }}>+ {tooltip.node.label || tooltip.node.ip}+ </div>+ {tooltip.node.country && (+ <div style={{ fontSize: 10, color: '#94a3b8' }}>+ {[tooltip.node.city, tooltip.node.country].filter(Boolean).join(', ')}+ </div>+ )}+ {tooltip.node.org && (+ <div style={{ fontSize: 10, color: '#64748b' }}>{tooltip.node.org}</div>+ )}+ <div style={{ marginTop: 5, fontSize: 10, display: 'flex', gap: 10 }}>+ <span style={{ color: tooltip.node.color }}>{tooltip.node.category}</span>+ <span style={{ color: '#475569' }}>{tooltip.node.packets} pkt</span>+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/scoring/privacy.js b/frontend/src/scoring/privacy.jsnew file mode 100644index 0000000..435bbd4--- /dev/null+++ b/frontend/src/scoring/privacy.js@@ -0,0 +1,143 @@+/**+ * Snitch — privacy score engine.+ *+ * EN: Computes a 0–100 score from the live node map and alert history.+ * Starts at 100 and subtracts penalties: trackers contacted, share of+ * traffic going to trackers, ad-network orgs, beaconing, suspicious+ * processes/ports and critical alerts. Positive signals (high HTTPS+ * ratio, zero trackers) are listed as good factors. Also returns a letter+ * grade, a color and an i18n label key for the UI.+ *+ * FR: Calcule un score de 0 à 100 à partir de la table de nœuds en direct et+ * de l'historique d'alertes. Départ à 100, puis pénalités : trackers+ * contactés, part du trafic vers les trackers, régies publicitaires,+ * beaconing, processus/ports suspects et alertes critiques. Les signaux+ * positifs (fort ratio HTTPS, zéro tracker) sont listés comme bons+ * facteurs. Renvoie aussi une note lettre, une couleur et une clé i18n.+ */++// EN: Substrings matched against the ASN/org name to spot ad networks.+// FR: Sous-chaînes recherchées dans le nom d'ASN/org pour repérer les régies pubs.+const AD_ORGS = [+ 'google', 'doubleclick', 'facebook', 'meta', 'amazon ads',+ 'amazon advertising', 'twitter', 'tiktok', 'snap', 'pinterest',+ 'taboola', 'outbrain', 'criteo', 'appnexus', 'pubmatic',+ 'openx', 'rubicon', 'sharethrough', 'index exchange',+]++function isAdOrg(org) {+ if (!org) return false+ const lower = org.toLowerCase()+ return AD_ORGS.some(a => lower.includes(a))+}++/**+ * EN: Main entry — pure function, safe to call on every render via useMemo.+ * FR: Point d'entrée — fonction pure, sûre à appeler à chaque rendu via useMemo.+ */+export function computePrivacyScore(nodes, alerts) {+ const extNodes = Object.values(nodes).filter(n => n.id !== 'local')+ const totalBytes = extNodes.reduce((a, n) => a + (n.bytes || 0), 0)+ const totalPackets = extNodes.reduce((a, n) => a + (n.packets || 0), 0)++ const trackerNodes = extNodes.filter(n => n.category === 'tracking')+ const trackerBytes = trackerNodes.reduce((a, n) => a + (n.bytes || 0), 0)+ const adOrgNodes = extNodes.filter(n => isAdOrg(n.org))++ const byType = type => alerts.filter(a => a.type === type).length+ const bySev = sev => alerts.filter(a => a.severity === sev).length++ const beaconCount = byType('BEACON')+ const suspProcCount = byType('SUSPICIOUS_PROCESS')+ const suspPortCount = byType('SUSPICIOUS_PORT')+ const criticalCount = bySev('critical')+ const warningCount = bySev('warning')++ let score = 100+ const factors = []++ // EN: Each tracker contacted costs 4 points (cap −28).+ // FR: Chaque tracker contacté coûte 4 points (plafond −28).+ if (trackerNodes.length > 0) {+ const p = Math.min(trackerNodes.length * 4, 28)+ score -= p+ factors.push({ icon: 'radio', key: 'score_trackers', args: [trackerNodes.length], penalty: p, bad: true })+ }++ // EN: A high share of tracker traffic is worse than a high count.+ // FR: Une forte part de trafic vers les trackers est pire qu'un grand nombre.+ if (totalBytes > 0 && trackerBytes > 0) {+ const pct = (trackerBytes / totalBytes) * 100+ if (pct > 3) {+ const p = Math.min(Math.floor(pct / 3), 15)+ score -= p+ factors.push({ icon: 'bar-chart', key: 'score_tracker_traffic', args: [pct.toFixed(0)], penalty: p, bad: true })+ }+ }++ // EN: Ad-network orgs not already counted as trackers get a smaller penalty.+ // FR: Les régies pubs non déjà comptées comme trackers ont une pénalité réduite.+ if (adOrgNodes.length > trackerNodes.length) {+ const extra = adOrgNodes.length - trackerNodes.length+ const p = Math.min(extra * 3, 12)+ score -= p+ factors.push({ icon: 'target', key: 'score_ad_networks', args: [adOrgNodes.length], penalty: p, bad: true })+ }++ // EN: Beaconing is a strong C2 signal — heavy penalty.+ // FR: Le beaconing est un fort signal de C2 — pénalité lourde.+ if (beaconCount > 0) {+ const p = Math.min(beaconCount * 12, 24)+ score -= p+ factors.push({ icon: 'activity', key: 'score_beacons', args: [beaconCount], penalty: p, bad: true })+ }++ if (suspProcCount > 0) {+ const p = Math.min(suspProcCount * 8, 20)+ score -= p+ factors.push({ icon: 'alert-triangle', key: 'score_susp_proc', args: [suspProcCount], penalty: p, bad: true })+ }++ if (suspPortCount > 0) {+ const p = Math.min(suspPortCount * 7, 18)+ score -= p+ factors.push({ icon: 'unlock', key: 'score_susp_ports', args: [suspPortCount], penalty: p, bad: true })+ }++ if (criticalCount > 0) {+ const p = Math.min(criticalCount * 10, 20)+ score -= p+ factors.push({ icon: 'shield-alert', key: 'score_critical_alerts', args: [criticalCount], penalty: p, bad: true })+ }++ // EN: Only penalize warnings beyond the first few — noise happens.+ // FR: Ne pénaliser les warnings qu'au-delà des premiers — le bruit arrive.+ if (warningCount > 5) {+ const p = Math.min((warningCount - 5) * 2, 10)+ score -= p+ factors.push({ icon: 'bell', key: 'score_warnings', args: [warningCount], penalty: p, bad: true })+ }++ // ── Positive factors / Facteurs positifs ──────────────────────────────────+ const httpsNodes = extNodes.filter(n => n.category === 'safe')+ if (totalPackets > 0 && httpsNodes.length > 0) {+ const ratio = httpsNodes.reduce((a, n) => a + (n.packets || 0), 0) / totalPackets+ if (ratio > 0.7) {+ factors.push({ icon: 'lock', key: 'score_https_ratio', args: [Math.round(ratio * 100)], penalty: 0, bad: false })+ }+ }++ if (extNodes.length > 0 && trackerNodes.length === 0) {+ factors.push({ icon: 'check-circle', key: 'score_no_trackers', args: [], penalty: 0, bad: false })+ }++ score = Math.max(0, Math.min(100, Math.round(score)))++ // EN: Map the numeric score to a letter grade, a color, and an i18n label key.+ // FR: Associer le score numérique à une note lettre, une couleur et une clé i18n.+ const grade = score >= 90 ? 'A' : score >= 75 ? 'B' : score >= 55 ? 'C' : score >= 35 ? 'D' : 'F'+ const color = score >= 80 ? '#22c55e' : score >= 60 ? '#84cc16' : score >= 40 ? '#f59e0b' : score >= 20 ? '#f97316' : '#ef4444'+ const labelKey = score >= 80 ? 'privacy_label_excellent' : score >= 60 ? 'privacy_label_good' : score >= 40 ? 'privacy_label_average' : score >= 20 ? 'privacy_label_weak' : 'privacy_label_critical'++ return { score, grade, color, labelKey, factors }+}diff --git a/frontend/vite.config.js b/frontend/vite.config.jsnew file mode 100644index 0000000..3aa3b0f--- /dev/null+++ b/frontend/vite.config.js@@ -0,0 +1,29 @@+/**+ * Snitch — Vite configuration.+ *+ * EN: In dev, the API and WebSocket are proxied to the Python backend on+ * :8000 so the frontend code can use relative URLs. `base: './'` makes+ * the production build work when served from file:// by Electron.+ * FR: En dev, l'API et le WebSocket sont proxifiés vers le backend Python sur+ * :8000 pour que le frontend utilise des URL relatives. `base: './'` permet+ * au build de production de fonctionner servi en file:// par Electron.+ */+import { defineConfig } from 'vite'+import react from '@vitejs/plugin-react'++export default defineConfig({+ plugins: [react()],+ base: './',+ server: {+ port: 5173,+ proxy: {+ '/ws': { target: 'ws://localhost:8000', ws: true },+ '/graph': { target: 'http://localhost:8000' },+ '/devices': { target: 'http://localhost:8000' },+ '/alerts': { target: 'http://localhost:8000' },+ '/timeline': { target: 'http://localhost:8000' },+ '/capture': { target: 'http://localhost:8000' },+ '/media': { target: 'http://localhost:8000' },+ },+ },+})