Skip to content

Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.

harden: API token auth, restricted CORS, perf & detection fixes

MoneyLisa80b151e69948
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..fa98c5a
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,26 @@
+# Snitch — Dependabot configuration.
+# EN: Weekly update PRs for Python deps, npm deps and GitHub Actions.
+# FR: PRs de mise à jour hebdomadaires pour les deps Python, npm et les
+# GitHub Actions.
+
+version: 2
+updates:
+ - package-ecosystem: "pip"
+ directory: "/backend"
+ schedule:
+ interval: "weekly"
+
+ - package-ecosystem: "npm"
+ directory: "/frontend"
+ schedule:
+ interval: "weekly"
+
+ - package-ecosystem: "npm"
+ directory: "/electron"
+ schedule:
+ interval: "weekly"
+
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "weekly"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..dbebf74
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,41 @@
+# Snitch — continuous integration.
+# EN: Python lint (ruff, critical rules only) + pytest, and the frontend
+# vitest suite + production build on every push/PR.
+# FR: Lint Python (ruff, règles critiques seulement) + pytest, et la suite
+# vitest frontend + build de production à chaque push/PR.
+
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+jobs:
+ backend:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+ - name: Install dependencies
+ run: pip install -r backend/requirements.txt -r backend/requirements-dev.txt
+ - name: Ruff (syntax/critical rules)
+ run: ruff check backend --select E9,F
+ - name: Pytest
+ run: cd backend && python -m pytest tests/ -v
+
+ frontend:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ - name: Install + test + build
+ run: |
+ cd frontend
+ npm install
+ npm test
+ npm run build
diff --git a/README.md b/README.md
index c48ce99..93a0f11 100644
--- a/README.md
+++ b/README.md
@@ -28,7 +28,7 @@ The entire interface is available in **English and French**: use the `EN / FR` t
|---|---|
| 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 |
+| 15/30/60-min Timeline | Sliding history stored locally in SQLite (24 h retention) |
| Anomaly Detection | Flags port scans, beaconing, potential exfiltration |
| Process Attribution | Know which app generates which traffic (top 5 per connection) |
| LAN Scanner | ARP discovery of all devices on your local network |
@@ -44,7 +44,15 @@ The entire interface is available in **English and French**: use the `EN / FR` t
| 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) |
+| Geolocation | MaxMind GeoLite2 (offline; ip-api.com fallback is **opt-in**) |
+
+### Security & privacy
+
+- **API token** — every REST endpoint and the WebSocket require a token. Electron generates it per launch; in Docker/browser it's printed once in the backend logs and stored in `data/api_token.txt`. Open the UI with `http://localhost:8000/?token=<TOKEN>` (or enter it when prompted).
+- **Loopback-only by default** — the API binds `127.0.0.1` in every mode. Set `SNITCH_BIND=0.0.0.0` only if you explicitly want LAN access (token auth still applies).
+- **CORS/WebSocket origin allowlist** — only `localhost:5173`, the backend's own origin and Electron `file://` pages may connect.
+- **Geolocation is offline-first** — drop `GeoLite2-City.mmdb` into `data/` for fully local lookups (free MaxMind account required to download the DB). The ip-api.com fallback is **disabled by default** because it sends contacted IPs to a third party over plaintext HTTP; enable it only deliberately with `SNITCH_ONLINE_GEO=1`.
+- **All data stays local** — `snitch.db` (24 h sliding window) and `data/logs/snitch.log` never leave the machine.
### Docker (Linux)
@@ -67,7 +75,7 @@ mkdir -p data
sudo docker compose up --build
```
-Open **http://localhost:8000** in your browser.
+Get the API token (printed once at startup, or `cat data/api_token.txt`), then open **http://localhost:8000/?token=TOKEN** in your browser.
To run in the background: `sudo docker compose up -d --build`
@@ -87,14 +95,14 @@ Requirements:
# Backend (admin terminal) — API at http://127.0.0.1:8000
cd backend
pip install -r requirements.txt
-python run_backend.py
+python run_backend.py # prints the API token once
-# Frontend (separate terminal) — UI at http://localhost:5173
+# Frontend (separate terminal) — UI at http://localhost:5173/?token=TOKEN
cd frontend
npm install
npm run dev
-# Electron (optional, admin terminal)
+# Electron (optional, admin terminal) — token is injected automatically
cd electron
npm install
set VITE_DEV=1 # Windows
@@ -102,6 +110,13 @@ set VITE_DEV=1 # Windows
npx electron .
```
+Tests:
+
+```bash
+cd backend && pip install -r requirements-dev.txt && python -m pytest tests/ -v
+cd frontend && npm test
+```
+
### Build the installer
```bash
@@ -145,7 +160,7 @@ Toute l'interface est disponible en **français et en anglais** : utilisez le s
|---|---|
| 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 |
+| Timeline 15/30/60 min | Historique glissant stocké localement dans SQLite (rétention 24 h) |
| Détection d'anomalies | Signale scans de ports, beaconing, exfiltration potentielle |
| Attribution processus | Sachez quelle app génère quel trafic (top 5 par connexion) |
| Scanner LAN | Découverte ARP de tous les appareils du réseau local |
@@ -161,7 +176,15 @@ Toute l'interface est disponible en **français et en anglais** : utilisez le s
| 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) |
+| Géolocalisation | MaxMind GeoLite2 (hors ligne ; repli ip-api.com **opt-in**) |
+
+### Sécurité & confidentialité
+
+- **Jeton API** — chaque endpoint REST et le WebSocket exigent un jeton. Electron le génère à chaque lancement ; sous Docker/navigateur il est affiché une fois dans les logs du backend et stocké dans `data/api_token.txt`. Ouvrez l'UI via `http://localhost:8000/?token=<JETON>` (ou saisissez-le à l'invite).
+- **Loopback uniquement par défaut** — l'API écoute sur `127.0.0.1` dans tous les modes. Ne mettez `SNITCH_BIND=0.0.0.0` que pour un accès LAN explicite (le jeton reste exigé).
+- **Liste blanche CORS/Origin WebSocket** — seuls `localhost:5173`, l'origine propre du backend et les pages `file://` d'Electron peuvent se connecter.
+- **Géolocalisation hors ligne d'abord** — déposez `GeoLite2-City.mmdb` dans `data/` pour des recherches 100 % locales (compte MaxMind gratuit requis pour télécharger la base). Le repli ip-api.com est **désactivé par défaut** car il envoie les IP contactées à un tiers en HTTP clair ; ne l'activez que volontairement avec `SNITCH_ONLINE_GEO=1`.
+- **Toutes les données restent locales** — `snitch.db` (fenêtre glissante de 24 h) et `data/logs/snitch.log` ne quittent jamais la machine.
### Docker (Linux)
@@ -177,7 +200,7 @@ mkdir -p data
sudo docker compose up --build
```
-Ouvrez **http://localhost:8000** dans votre navigateur.
+Récupérez le jeton API (affiché une fois au démarrage, ou `cat data/api_token.txt`), puis ouvrez **http://localhost:8000/?token=JETON** dans votre navigateur.
En arrière-plan : `sudo docker compose up -d --build`
Limites Docker :
@@ -199,12 +222,19 @@ cd frontend
npm install
npm run dev
-# Electron (optionnel)
+# Electron (optionnel) — le jeton est injecté automatiquement
cd electron
npm install
VITE_DEV=1 npx electron .
```
+Tests :
+
+```bash
+cd backend && pip install -r requirements-dev.txt && python -m pytest tests/ -v
+cd frontend && npm test
+```
+
### Structure du projet
```
diff --git a/backend/api/main.py b/backend/api/main.py
index 4141d11..47f7506 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -1,29 +1,44 @@
"""
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.
+EN: Heart of the backend. Owns the in-memory graph state (nodes / edges /
+ LAN devices), receives packets from the Scapy sniffer thread, enriches
+ them (DNS + geolocation + classification), feeds the anomaly detector,
+ persists aggregates to SQLite and pushes realtime updates over the
+ WebSocket.
+
+ Security model (see api/security.py):
+ - every REST endpoint requires the API token (X-Snitch-Token header or
+ ?token= param)
+ - the WebSocket requires the token AND a whitelisted Origin header
+ - CORS is restricted to the dev server / self-origin / file:// (Electron)
+
+FR: Cœur du backend. Détenir l'état du graphe en mémoire (nœuds / arêtes /
+ appareils LAN), recevoir les paquets du thread du sniffer Scapy, les
+ enrichir (DNS + géolocalisation + classification), alimenter le détecteur
+ d'anomalies, persister les agrégats dans SQLite et pousser les mises à
+ jour temps réel via le WebSocket.
+
+ Modèle de sécurité (voir api/security.py) :
+ - chaque endpoint REST exige le jeton API (en-tête X-Snitch-Token ou
+ paramètre ?token=)
+ - le WebSocket exige le jeton ET un en-tête Origin autorisé
+ - CORS restreint au serveur de dev / à l'origine propre / file:// (Electron)
"""
import asyncio
import json
+import logging
import threading
import time
from contextlib import asynccontextmanager
-from datetime import datetime
+from datetime import datetime, timezone
-from fastapi import FastAPI, WebSocket, WebSocketDisconnect
+from fastapi import Depends, FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
+from pydantic import BaseModel, Field
+from api.security import ALLOWED_ORIGINS_LIST, require_token, ws_authorized
from capture.sniffer import Packet, PacketSniffer
from capture.media_monitor import MediaMonitor, MediaState
from classifier.traffic import classify
@@ -32,13 +47,11 @@ from scanner.arp_scanner import ARPScanner, Device
from detection.anomaly import AnomalyDetector
import storage.db as db
+logger = logging.getLogger("snitch.api")
+
# ── 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] = {}
@@ -55,15 +68,39 @@ _excluded_processes: set[str] = set()
_whitelisted_ips: set[str] = set()
_media_state: dict = {"mic": [], "camera": []}
+# EN: Hard caps so a long-running instance can't leak memory.
+# FR: Plafonds stricts pour qu'une instance longue durée ne fuie pas de mémoire.
+MAX_GRAPH_NODES = 800
+MAX_ENRICHMENT_CACHE = 4096
+
+
+# ── Pydantic request models / Modèles de requête Pydantic ────────────────────
+# EN: Every POST body is validated — no more bare `dict` bodies.
+# FR: Chaque corps POST est validé — plus de corps `dict` bruts.
+
+class PortFilterBody(BaseModel):
+ """EN: /capture/ports payload. / FR: Charge utile de /capture/ports."""
+ ports: list[int] = Field(default_factory=list)
+
+
+class ProcessFilterBody(BaseModel):
+ """EN: /capture/processes payload. / FR: Charge utile de /capture/processes."""
+ excluded: list[str] = Field(default_factory=list)
+
+
+class WhitelistBody(BaseModel):
+ """EN: /capture/whitelist payload. / FR: Charge utile de /capture/whitelist."""
+ ips: list[str] = Field(default_factory=list)
+
# ── 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.
+ EN: Send a JSON message to every connected WebSocket client; drop the
+ dead ones.
+ FR: Envoyer un message JSON à tous les clients WebSocket connectés ;
+ retirer les morts.
"""
dead = []
for ws in connected_clients:
@@ -79,12 +116,10 @@ async def broadcast(message: dict) -> None:
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`.
+ EN: Called from the Scapy sniffer THREAD — schedule the async handler on
+ the event loop.
+ FR: Appelé depuis le THREAD du sniffer Scapy — planifier le handler async
+ sur la boucle d'événements.
"""
if _loop is None:
return
@@ -94,43 +129,62 @@ def on_packet(pkt: Packet) -> None:
async def _handle_packet(pkt: Packet) -> None:
"""
EN: Per-packet pipeline — filter, enrich, update graph, persist, detect.
+ LAN-destined traffic is accounted on the device node instead of being
+ dropped, so LAN devices show real byte counters.
FR: Pipeline par paquet — filtrer, enrichir, mettre à jour le graphe,
- persister, détecter.
+ persister, détecter. Le trafic vers le LAN est comptabilisé sur le nœud
+ de l'appareil au lieu d'être ignoré, pour que les appareils LAN
+ affichent de vrais compteurs d'octets.
"""
- # EN: 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
+ # ── LAN traffic accounting / Comptabilisation du trafic LAN ─────────────
+ lan_key = f"lan:{remote_ip}"
+ if lan_key in lan_devices:
+ lan_devices[lan_key]["bytes"] = lan_devices[lan_key].get("bytes", 0) + pkt.size
+ lan_devices[lan_key]["packets"] = lan_devices[lan_key].get("packets", 0) + 1
+ edge = edges.get(f"lan-edge-{remote_ip}")
+ if edge:
+ edge["bytes"] += pkt.size
+ edge["packets"] += 1
+ await broadcast({
+ "type": "device_update",
+ "device": lan_devices[lan_key],
+ "edge": edge,
+ "is_new": False,
+ })
+ 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.
+ # The cache is bounded — evict the oldest half when full.
+ # FR: Enrichir une fois par IP (DNS inverse + géolocalisation), puis cacher.
+ # Le cache est borné — évincer la moitié la plus ancienne quand plein.
if remote_ip not in enrichment_cache:
- enrichment_cache[remote_ip] = await enrich_ip(remote_ip)
+ if len(enrichment_cache) > MAX_ENRICHMENT_CACHE:
+ for stale in list(enrichment_cache.keys())[: MAX_ENRICHMENT_CACHE // 2]:
+ enrichment_cache.pop(stale, None)
+ try:
+ enrichment_cache[remote_ip] = await enrich_ip(remote_ip)
+ except Exception as exc:
+ logger.debug("enrich_ip failed for %s: %s", remote_ip, exc)
+ enrichment_cache[remote_ip] = {"ip": remote_ip, "hostname": None, "private": False}
geo = enrichment_cache[remote_ip]
- # 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:
+ # EN: Bound the graph — evict the lowest-traffic non-alerted node.
+ # FR: Borner le graphe — évincer le nœud au plus faible trafic non alerté.
+ if len(nodes) >= MAX_GRAPH_NODES:
+ _evict_weakest_node()
nodes[node_id] = {
"id": node_id,
"label": geo.get("hostname") or remote_ip,
@@ -161,8 +215,6 @@ async def _handle_packet(pkt: Packet) -> None:
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] = {
@@ -178,16 +230,12 @@ async def _handle_packet(pkt: Packet) -> None:
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")
+ # EN: Persist per-minute aggregates — batched, non-blocking.
+ # FR: Persister les agrégats par minute — par lots, sans blocage.
+ minute = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M")
db.accumulate(minute, category.category, pkt.size)
# ── Anomaly detection / Détection d'anomalies ───────────────────────────
- # 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:
@@ -197,8 +245,6 @@ async def _handle_packet(pkt: Packet) -> None:
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],
@@ -215,13 +261,33 @@ async def _handle_packet(pkt: Packet) -> None:
})
+def _evict_weakest_node() -> None:
+ """
+ EN: Remove the lowest-byte, non-alerted, non-local node (and its edges)
+ when the graph hits MAX_GRAPH_NODES. Called from _handle_packet.
+ FR: Retirer le nœud au plus faible trafic, non alerté et non « local »
+ (et ses arêtes) quand le graphe atteint MAX_GRAPH_NODES. Appelé depuis
+ _handle_packet.
+ """
+ candidates = [
+ n for n in nodes.values()
+ if n["id"] != "local" and not n.get("alerted")
+ ]
+ if not candidates:
+ return
+ weakest = min(candidates, key=lambda n: n.get("bytes", 0))
+ wid = weakest["id"]
+ nodes.pop(wid, None)
+ enrichment_cache.pop(wid, None)
+ for eid in [eid for eid, e in edges.items() if e["target"] == wid or e["source"] == wid]:
+ edges.pop(eid, None)
+
+
# ── 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.
- """
+ """EN: ARP scanner callback — schedules async handling.
+ FR: Callback du scanner ARP — planifie le traitement async."""
if _loop is None:
return
asyncio.run_coroutine_threadsafe(_handle_device(device, is_new), _loop)
@@ -229,19 +295,25 @@ def on_device(device: Device, is_new: bool) -> None:
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).
+ EN: Register/update a LAN device node, maintain its dashed edge to
+ "local", run device-level anomaly rules.
+ FR: Enregistrer/mettre à jour le nœud d'un appareil LAN, maintenir son
+ arête pointillée vers « local », lancer les règles niveau appareil.
"""
node = device.to_dict()
- node["alerted"] = False
+ # EN: Preserve accumulated byte counters across rediscovery.
+ # FR: Préserver les compteurs d'octets accumulés à travers les redécouvertes.
+ prev = lan_devices.get(node["id"])
+ if prev:
+ node["bytes"] = prev.get("bytes", 0)
+ node["packets"] = prev.get("packets", 0)
+ node["alerted"] = prev.get("alerted", False)
+ else:
+ 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}"
+ prev_edge = edges.get(edge_id, {})
edges[edge_id] = {
"id": edge_id,
"source": "local",
@@ -249,8 +321,8 @@ async def _handle_device(device: Device, is_new: bool) -> None:
"protocol": "LAN",
"label": "LAN",
"color": node["color"],
- "bytes": 0,
- "packets": 0,
+ "bytes": prev_edge.get("bytes", 0),
+ "packets": prev_edge.get("packets", 0),
"dashed": True,
}
@@ -275,10 +347,9 @@ async def _handle_device(device: Device, is_new: bool) -> None:
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.
+ EN: MediaMonitor callback — sync the detector's media sets and notify UI.
+ FR: Callback MediaMonitor — synchroniser les ensembles média du détecteur
+ et notifier l'UI.
"""
global _media_state
_media_state = {"mic": state.mic, "camera": state.camera}
@@ -291,73 +362,62 @@ def _on_media_change(state: MediaState) -> None:
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.
- """
+ """EN: Periodically flush the traffic accumulator to SQLite.
+ FR: Vider périodiquement l'accumulateur de trafic vers SQLite."""
while True:
time.sleep(10)
try:
db.flush()
- except Exception:
- pass
+ except Exception as exc:
+ logger.error("db flush failed: %s", exc)
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.
+ EN: Drop rows older than 24h — the timeline is a sliding window, the DB
+ must not grow forever.
+ FR: Supprimer les lignes de plus de 24 h — la timeline est une fenêtre
+ glissante, la BDD ne doit pas grossir indéfiniment.
"""
while True:
time.sleep(3600)
try:
db.cleanup_old_data(hours=24)
- except Exception:
- pass
+ except Exception as exc:
+ logger.error("db cleanup failed: %s", exc)
# ── 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.
- """
+ """EN: (Re)start sniffer + ARP scanner in daemon threads.
+ FR: (Re)démarrer sniffer + 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
+ logger.info("capture started (ports=%s)", _port_filter or "all")
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.
- """
+ """EN: Stop both capture sources. / FR: Arrêter les deux sources de capture."""
global _capturing
if _sniffer:
_sniffer.stop()
if _scanner:
_scanner.stop()
_capturing = False
+ logger.info("capture stopped")
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).
- """
+ """EN: Startup — create the "local" node, start capture + background threads.
+ FR: Démarrage — créer le nœud « local », lancer capture + threads d'arrière-plan."""
global _loop
_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",
@@ -374,29 +434,37 @@ async def _startup() -> None:
@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.
+ """EN: FastAPI lifespan — startup logic, then yield for the app's life.
+ FR: Lifespan FastAPI — logique de démarrage, puis yield pour la vie de l'app."""
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).
+# EN: Restricted CORS — dev server, self-origin, and `null` (Electron file://).
+# No `*`, no credentials. Combined with the token check this kills the
+# "any open webpage can drive my API" attack.
+# FR: CORS restreint — serveur de dev, origine propre et `null` (file://
+# Electron). Pas de `*`, pas de credentials. Combiné au jeton, cela tue
+# l'attaque « n'importe quelle page ouverte pilote mon API ».
app.add_middleware(
CORSMiddleware,
- allow_origins=["*"],
- allow_methods=["*"],
- allow_headers=["*"],
+ allow_origins=ALLOWED_ORIGINS_LIST,
+ allow_methods=["GET", "POST"],
+ allow_headers=["X-Snitch-Token", "Content-Type"],
)
+# EN: Applied to every route via `dependencies` AND checked explicitly on the
+# WebSocket handshake (WS can't use Depends the same way).
+# FR: Appliqué à toutes les routes via `dependencies` ET vérifié explicitement
+# au handshake WebSocket (le WS ne peut pas utiliser Depends pareillement).
+_AUTH = [Depends(require_token)]
+
# ── REST endpoints / Endpoints REST ──────────────────────────────────────────
[email protected]("/graph", dependencies=_AUTH)
async def get_graph() -> dict:
"""EN: Full graph snapshot. / FR: Instantané complet du graphe."""
return {
@@ -404,22 +472,22 @@ async def get_graph() -> dict:
"edges": list(edges.values()),
}
[email protected]("/devices")
[email protected]("/devices", dependencies=_AUTH)
async def get_devices() -> dict:
"""EN: LAN device list. / FR: Liste des appareils LAN."""
return {"devices": list(lan_devices.values())}
[email protected]("/alerts", dependencies=_AUTH)
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", dependencies=_AUTH)
async def get_media() -> dict:
"""EN: Current mic/camera usage. / FR: Usage actuel micro/caméra."""
return _media_state
[email protected]("/capture/status")
[email protected]("/capture/status", dependencies=_AUTH)
async def get_capture_status() -> dict:
"""EN: Capture state + all active filters. / FR: État de capture + filtres actifs."""
return {
@@ -429,7 +497,7 @@ async def get_capture_status() -> dict:
"whitelisted_ips": sorted(_whitelisted_ips),
}
[email protected]("/capture/stop")
[email protected]("/capture/stop", dependencies=_AUTH)
async def stop_capture() -> dict:
"""EN: Stop sniffing + ARP scan. / FR: Arrêter le sniffing + le scan ARP."""
_stop_capture()
@@ -442,26 +510,27 @@ async def stop_capture() -> dict:
})
return {"capturing": False}
[email protected]("/capture/ports")
-async def set_port_filter(body: dict) -> dict:
[email protected]("/capture/ports", dependencies=_AUTH)
+async def set_port_filter(body: PortFilterBody) -> 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é.
+ EN: Restrict capture to a list of ports (empty = all). Graph and detector
+ runtime state are both reset so the UI only shows matching traffic.
+ FR: Restreindre la capture à une liste de ports (vide = tous). Le graphe et
+ l'état du détecteur sont réinitialisés pour que l'UI n'affiche que le
+ trafic correspondant.
"""
global _port_filter
- ports = [int(p) for p in body.get("ports", []) if str(p).isdigit() and 1 <= int(p) <= 65535]
- _port_filter = ports
+ _port_filter = [p for p in body.ports if 1 <= p <= 65535]
- # EN: Clear graph state — keep only the "local" node.
- # FR: Vider l'état du graphe — ne garder que le nœud « local ».
+ # EN: Clear graph + detector state — keep only the "local" node.
+ # FR: Vider graphe + état du détecteur — ne garder que le nœud « local ».
local = nodes.get("local")
nodes.clear()
edges.clear()
lan_devices.clear()
if local:
nodes["local"] = local
+ detector.reset_runtime()
if _capturing:
_stop_capture()
@@ -475,7 +544,7 @@ async def set_port_filter(body: dict) -> dict:
})
return {"ports": _port_filter}
[email protected]("/capture/start")
[email protected]("/capture/start", dependencies=_AUTH)
async def start_capture() -> dict:
"""EN: Resume capture. / FR: Reprendre la capture."""
if not _capturing:
@@ -489,11 +558,11 @@ async def start_capture() -> dict:
})
return {"capturing": True}
[email protected]("/capture/processes")
-async def set_process_filter(body: dict) -> dict:
[email protected]("/capture/processes", dependencies=_AUTH)
+async def set_process_filter(body: ProcessFilterBody) -> dict:
"""EN: Hide traffic from named processes. / FR: Masquer le trafic de processus nommés."""
global _excluded_processes
- _excluded_processes = {str(p) for p in body.get("excluded", []) if isinstance(p, str)}
+ _excluded_processes = {str(p) for p in body.excluded}
await broadcast({
"type": "capture_status",
@@ -504,16 +573,19 @@ async def set_process_filter(body: dict) -> dict:
})
return {"excluded_processes": sorted(_excluded_processes)}
[email protected]("/capture/whitelist")
-async def set_ip_whitelist(body: dict) -> dict:
[email protected]("/capture/whitelist", dependencies=_AUTH)
+async def set_ip_whitelist(body: WhitelistBody) -> 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.
+ EN: Mark IPs as trusted — dropped from capture and display. Removed nodes
+ also get forgotten by the detector and the enrichment cache, so
+ un-whitelisting works correctly afterwards.
+ FR: Marquer des IP comme fiables — ignorées de la capture et de
+ l'affichage. Les nœuds retirés sont aussi oubliés par le détecteur et
+ le cache d'enrichissement, pour qu'un retrait de la whitelist
+ fonctionne ensuite correctement.
"""
global _whitelisted_ips
- _whitelisted_ips = {str(ip) for ip in body.get("ips", []) if isinstance(ip, str)}
+ _whitelisted_ips = {str(ip) for ip in body.ips}
removed_ids = [ip for ip in _whitelisted_ips if ip != "local" and nodes.pop(ip, None) is not None]
if removed_ids:
@@ -522,6 +594,8 @@ async def set_ip_whitelist(body: dict) -> dict:
edges.pop(edge_id, None)
for ip in removed_ids:
enrichment_cache.pop(ip, None)
+ detector.forget(ip) # EN: clear seen/beacon/spike state too
+ # FR: vider aussi l'état seen/beacon/spike
await broadcast({
"type": "capture_status",
@@ -534,10 +608,10 @@ async def set_ip_whitelist(body: dict) -> dict:
await broadcast({"type": "nodes_removed", "ids": removed_ids})
return {"whitelisted_ips": sorted(_whitelisted_ips)}
[email protected]("/timeline")
[email protected]("/timeline", dependencies=_AUTH)
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."""
+ """EN: Per-minute aggregates for the timeline chart.
+ FR: Agrégats 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}
@@ -548,13 +622,16 @@ async def get_timeline(minutes: int = 60) -> dict:
@app.websocket("/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.
+ EN: Realtime channel. Handshake is gated by ws_authorized() — Origin
+ allowlist + token. On success we send the `init` snapshot BEFORE
+ registering the client so no `update` can reference unknown nodes.
+ FR: Canal temps réel. Le handshake est filtré par ws_authorized() — liste
+ blanche d'Origin + jeton. En cas de succès on envoie l'instantané
+ `init` AVANT d'enregistrer le client pour qu'aucun `update` ne
+ référence de nœud inconnu.
"""
+ if not await ws_authorized(websocket):
+ return
await websocket.accept()
await websocket.send_text(json.dumps({
@@ -585,11 +662,11 @@ async def websocket_endpoint(websocket: WebSocket) -> None:
# ── 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
+# 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.
+# correspondantes — donc enregistré en DERNIER.
from pathlib import Path
from fastapi.staticfiles import StaticFiles
diff --git a/backend/api/security.py b/backend/api/security.py
new file mode 100644
index 0000000..1f1a567
--- /dev/null
+++ b/backend/api/security.py
@@ -0,0 +1,173 @@
+"""
+Snitch — API security layer.
+
+EN: Three complementary protections:
+ 1. Bearer-style token. Generated at startup (or taken from the
+ SNITCH_TOKEN env var, which is how the Electron wrapper injects
+ it), persisted to <data>/api_token.txt (0600) and printed once to
+ stdout so Docker/dev users can pass ?token=… in the browser.
+ Every REST endpoint and the WebSocket require it.
+ 2. CORS allowlist — no more `*`. Only the Vite dev server, the
+ backend's own origin and `null` (file:// pages under Electron).
+ 3. Origin check on the WebSocket handshake — blocks Cross-Site
+ WebSocket Hijacking even if a browser somehow skips CORS.
+
+FR: Trois protections complémentaires :
+ 1. Jeton d'authentification. Généré au démarrage (ou pris de la variable
+ SNITCH_TOKEN, ce que fait le conteneur Electron), persisté dans
+ <data>/api_token.txt (0600) et affiché une fois sur stdout pour que
+ les utilisateurs Docker/dev passent ?token=… dans le navigateur.
+ Chaque endpoint REST et le WebSocket l'exigent.
+ 2. Liste blanche CORS — plus de `*`. Seulement le serveur de dev Vite,
+ l'origine du backend lui-même et `null` (pages file:// sous Electron).
+ 3. Vérification d'Origin sur le handshake WebSocket — bloque le
+ Cross-Site WebSocket Hijacking même si un navigateur contourne CORS.
+"""
+
+import logging
+import os
+import secrets
+import sys
+from pathlib import Path
+
+from fastapi import HTTPException, Request, WebSocket, status
+
+logger = logging.getLogger("snitch.api.security")
+
+# EN: Origins allowed to reach the API. `null` covers file:// pages (Electron
+# renderer) — browsers send Origin: null for local files.
+# FR: Origines autorisées à joindre l'API. `null` couvre les pages file://
+# (renderer Electron) — les navigateurs envoient Origin: null pour les
+# fichiers locaux.
+ALLOWED_ORIGINS = {
+ "http://localhost:5173", # EN: Vite dev / FR: dev Vite
+ "http://127.0.0.1:5173",
+ "http://localhost:8000", # EN: backend serving its own frontend
+ "http://127.0.0.1:8000", # FR: le backend servant son propre frontend
+ "null", # EN: file:// (Electron) / FR: file:// (Electron)
+}
+
+ALLOWED_ORIGINS_LIST = sorted(ALLOWED_ORIGINS)
+
+
+def _data_dir() -> Path:
+ """
+ EN: Resolve the writable data directory — same rules as storage.db:
+ SNITCH_DATA_DIR env override, LOCALAPPDATA\\Snitch when frozen by
+ PyInstaller, otherwise <repo>/data.
+ FR: Résoudre le dossier de données inscriptible — mêmes règles que
+ storage.db : SNITCH_DATA_DIR en priorité, LOCALAPPDATA\\Snitch quand
+ figé par PyInstaller, sinon <dépôt>/data.
+ """
+ env_dir = os.environ.get("SNITCH_DATA_DIR")
+ if env_dir:
+ d = Path(env_dir)
+ elif getattr(sys, "frozen", False):
+ d = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "Snitch"
+ else:
+ d = Path(__file__).parent.parent.parent / "data"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def _load_or_create_token() -> str:
+ """
+ EN: Token resolution order:
+ 1. SNITCH_TOKEN env var — set by the Electron wrapper
+ 2. existing api_token.txt — survives backend restarts so an open
+ UI doesn't get logged out
+ 3. freshly generated 48-hex secret
+ The token file is created with 0600 permissions where supported.
+ FR: Ordre de résolution du jeton :
+ 1. variable SNITCH_TOKEN — posée par le conteneur Electron
+ 2. api_token.txt existant — survit aux redémarrages du backend pour
+ ne pas déconnecter une UI déjà ouverte
+ 3. secret hexadécimal de 48 caractères fraîchement généré
+ Le fichier est créé en 0600 quand le système le permet.
+ """
+ token = os.environ.get("SNITCH_TOKEN", "").strip()
+ if token:
+ return token
+
+ token_file = _data_dir() / "api_token.txt"
+ try:
+ if token_file.exists():
+ existing = token_file.read_text().strip()
+ if len(existing) >= 32:
+ return existing
+ except OSError:
+ pass
+
+ token = secrets.token_hex(24)
+ try:
+ token_file.write_text(token)
+ try:
+ os.chmod(token_file, 0o600) # EN: owner-only / FR: propriétaire seul
+ except OSError:
+ pass # EN: Windows has no chmod semantics
+ # FR: Windows n'a pas de sémantique chmod
+ except OSError as exc:
+ logger.warning("Could not persist API token to %s: %s", token_file, exc)
+
+ # EN: Printed once so Docker/browser users can complete the ?token= URL.
+ # FR: Affiché une fois pour que les utilisateurs Docker/navigateur complètent l'URL ?token=.
+ print(f"[snitch] API token: {token}", flush=True)
+ return token
+
+
+# EN: Resolved once at import — the token is stable for the process lifetime.
+# FR: Résolu une fois à l'import — le jeton est stable pour la vie du processus.
+API_TOKEN = _load_or_create_token()
+
+
+def _extract_token(request: Request) -> str | None:
+ """
+ EN: Accept `X-Snitch-Token` header (preferred) or `?token=` query param
+ (needed by the WebSocket, which can't set headers in the browser API).
+ FR: Accepter l'en-tête `X-Snitch-Token` (préféré) ou le paramètre `?token=`
+ (nécessaire pour le WebSocket, qui ne peut pas poser d'en-têtes dans
+ l'API navigateur).
+ """
+ return request.headers.get("x-snitch-token") or request.query_params.get("token")
+
+
+def require_token(request: Request) -> None:
+ """
+ EN: FastAPI dependency — 401 unless a valid token is presented.
+ Applies to ALL endpoints: even GET /graph leaks sensitive traffic data.
+ FR: Dépendance FastAPI — 401 sans jeton valide.
+ S'applique à TOUS les endpoints : même GET /graph divulgue des données
+ de trafic sensibles.
+ """
+ token = _extract_token(request)
+ if not token or not secrets.compare_digest(token, API_TOKEN):
+ raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API token")
+
+
+def origin_allowed(origin: str | None) -> bool:
+ """
+ EN: An absent Origin header means a non-browser client (curl, Electron's
+ main process) — allowed. Present origins must be in the allowlist.
+ FR: Un en-tête Origin absent signifie un client non-navigateur (curl,
+ processus principal d'Electron) — autorisé. Les origines présentes
+ doivent figurer dans la liste blanche.
+ """
+ return origin is None or origin in ALLOWED_ORIGINS
+
+
+async def ws_authorized(websocket: WebSocket) -> bool:
+ """
+ EN: WebSocket gate — validates Origin (anti-CSWSH) and the ?token= param.
+ Closes with 4401/4403 and returns False on failure so callers bail out.
+ FR: Barrière WebSocket — valide Origin (anti-CSWSH) et le paramètre
+ ?token=. Ferme avec 4401/4403 et renvoie False en cas d'échec pour
+ que l'appelant abandonne.
+ """
+ if not origin_allowed(websocket.headers.get("origin")):
+ await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
+ return False
+ token = websocket.query_params.get("token") or websocket.headers.get("x-snitch-token")
+ if not token or not secrets.compare_digest(token, API_TOKEN):
+ await websocket.close(code=4401)
+ return False
+ return True
diff --git a/backend/capture/media_monitor.py b/backend/capture/media_monitor.py
index 19d053b..e22fa2b 100644
--- a/backend/capture/media_monitor.py
+++ b/backend/capture/media_monitor.py
@@ -2,32 +2,38 @@
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.
+ the camera. 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.
+ means the device is in use right now. Both packaged (Store/UWP) and
+ unpackaged (desktop) apps are covered — the earlier version only read
+ "NonPackaged" and missed every Store 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.
+ microphone ou la caméra. Alimente la règle MEDIA_EXFIL : un processus
+ inconnu qui utilise le micro ET émet 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.
+ signifie que l'appareil est utilisé en ce moment. Les apps packagées
+ (Store/UWP) et non packagées (bureau) sont toutes deux couvertes — la
+ version précédente ne lisait que « NonPackaged » et ratait toutes les
+ apps du Store.
- Linux : scanne les fichiers ouverts de chaque processus à la recherche
de /dev/snd* et /dev/video*.
"""
+import logging
import sys
import time
-import threading
from dataclasses import dataclass, field
from typing import Callable
import psutil
+logger = logging.getLogger("snitch.capture.media")
+
@dataclass
class MediaState:
@@ -39,50 +45,65 @@ class MediaState:
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.
+ EN: Read Windows' per-app consent store. Sub-keys of `microphone`/`webcam`
+ are either "NonPackaged" (a folder of desktop exe paths) or a packaged
+ app id. `LastUsedTimeStop == 0` means the device is open right now.
+ FR: Lire le magasin de consentement Windows par app. Les sous-clés de
+ `microphone`/`webcam` sont soit « NonPackaged » (un dossier de chemins
+ d'exe bureau), soit un identifiant d'app packagée.
+ `LastUsedTimeStop == 0` signifie que l'appareil est ouvert en ce moment.
"""
import winreg
state = MediaState()
+ def _key_in_use(key) -> bool:
+ """EN: True if this app's LastUsedTimeStop == 0 (device in use now).
+ FR: True si LastUsedTimeStop == 0 pour cette app (appareil utilisé)."""
+ try:
+ val, _ = winreg.QueryValueEx(key, "LastUsedTimeStop")
+ return val == 0
+ except OSError:
+ return False
+
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
+
+ i = 0
+ while True:
+ try:
+ sub = winreg.EnumKey(key, i)
+ i += 1
+ except OSError:
+ break
+
+ try:
+ if sub == "NonPackaged":
+ # EN: Desktop apps — one sub-key per exe path.
+ # FR: Apps bureau — une sous-clé par chemin d'exe.
+ np_key = winreg.OpenKey(key, sub)
+ j = 0
+ while True:
+ try:
+ app = winreg.EnumKey(np_key, j)
+ j += 1
+ app_key = winreg.OpenKey(np_key, app)
+ if _key_in_use(app_key):
+ procs.append(app.split("#")[-1])
+ except OSError:
+ break
+ else:
+ # EN: Packaged (Store/UWP) apps sit directly under the key.
+ # FR: Les apps packagées (Store/UWP) sont directement sous la clé.
+ app_key = winreg.OpenKey(key, sub)
+ if _key_in_use(app_key):
+ procs.append(sub)
+ except OSError:
+ continue
return procs
state.mic = _read_consent("microphone")
@@ -102,8 +123,7 @@ def _detect_linux() -> MediaState:
try:
for proc in psutil.process_iter(['name', 'open_files']):
try:
- files = proc.open_files()
- for f in files:
+ for f in proc.open_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())
@@ -112,8 +132,8 @@ def _detect_linux() -> MediaState:
state.camera.append(proc.name())
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
- except Exception:
- pass
+ except Exception as exc:
+ logger.debug("linux media scan failed: %s", exc)
return state
@@ -148,8 +168,8 @@ class MediaMonitor:
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
+ except Exception as exc:
+ logger.debug("media detect failed: %s", exc)
time.sleep(self.interval)
def stop(self) -> None:
diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.py
index bc5e571..5c5db94 100644
--- a/backend/capture/sniffer.py
+++ b/backend/capture/sniffer.py
@@ -1,25 +1,32 @@
"""
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.
+EN: Wraps Scapy's AsyncSniffer to capture IPv4 AND IPv6 packets on the host,
+ determine their direction (in/out), and attribute them to a local process.
+ Process attribution used to call `psutil.net_connections()` per packet —
+ thousands of syscall-heavy scans per second on busy links. It now reads
+ from a `ConnectionTable`: a snapshot refreshed every ~1.5 s by a dedicated
+ thread, making per-packet lookup a dict hit.
+
+FR: Enveloppe l'AsyncSniffer de Scapy pour capturer les paquets IPv4 ET IPv6 de
+ l'hôte, déterminer leur direction (entrant/sortant) et les attribuer à un
+ processus local. L'attribution appelait avant `psutil.net_connections()`
+ par paquet — des milliers de scans coûteux par seconde sur un lien actif.
+ Elle lit désormais une `ConnectionTable` : un instantané rafraîchi toutes
+ les ~1,5 s par un thread dédié, ramenant la recherche par paquet à un accès
+ dict.
"""
-import asyncio
+import logging
import socket
+import threading
import time
-from dataclasses import dataclass, field
-from datetime import datetime
+from dataclasses import dataclass
+from datetime import datetime, timezone
from typing import Callable, Optional
try:
- from scapy.all import sniff, IP, TCP, UDP, DNS, DNSQR, AsyncSniffer
+ from scapy.all import IP, IPv6, TCP, UDP, AsyncSniffer
SCAPY_AVAILABLE = True
except ImportError:
# EN: Scapy (or libpcap/Npcap) missing — capture disabled, API still runs.
@@ -28,11 +35,13 @@ except ImportError:
import psutil
+logger = logging.getLogger("snitch.capture.sniffer")
+
@dataclass
class Packet:
"""
- EN: Normalized representation of one captured packet, everything the
+ 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.
@@ -51,51 +60,96 @@ class Packet:
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.
+ EN: Collect every IPv4 and IPv6 address bound to a local interface.
+ IPv6 entries may carry a scope suffix ("fe80::1%eth0") — stripped.
+ FR: Collecter toutes les adresses IPv4 et IPv6 des interfaces locales.
+ Les IPv6 peuvent porter un suffixe de scope (« fe80::1%eth0 ») — retiré.
"""
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)
+ if addr.family in (socket.AF_INET, socket.AF_INET6):
+ ips.add(addr.address.split("%")[0])
return ips
-def get_process_for_port(port: int, proto: str) -> tuple[Optional[int], Optional[str]]:
+class ConnectionTable:
"""
- 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).
+ EN: Periodic snapshot of the OS connection table:
+ { "tcp": {local_port: (pid, name)}, "udp": {...} }
+ `psutil.net_connections()` is expensive (it walks every socket of
+ every process), so we refresh once per `interval` in a background
+ thread and let the hot path do plain dict lookups.
+ FR: Instantané périodique de la table de connexions de l'OS :
+ { "tcp": {port_local: (pid, nom)}, "udp": {...} }
+ `psutil.net_connections()` est coûteux (il parcourt chaque socket de
+ chaque processus) : on rafraîchit une fois par `interval` dans un
+ thread d'arrière-plan et le chemin chaud fait de simples accès dict.
"""
- 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
+
+ def __init__(self, interval: float = 1.5):
+ self.interval = interval
+ self._map = {"tcp": {}, "udp": {}}
+ self._lock = threading.Lock()
+ self._running = False
+ self._thread: Optional[threading.Thread] = None
+
+ def _refresh(self) -> None:
+ """EN: Rebuild the whole snapshot. / FR: Reconstruire tout l'instantané."""
+ new_map = {"tcp": {}, "udp": {}}
+ for kind in ("tcp", "udp"):
+ try:
+ for conn in psutil.net_connections(kind=kind):
+ if conn.laddr and conn.pid:
+ name = None
+ try:
+ name = psutil.Process(conn.pid).name()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ pass
+ new_map[kind][conn.laddr.port] = (conn.pid, name)
+ except Exception as exc:
+ logger.debug("net_connections(%s) failed: %s", kind, exc)
+ with self._lock:
+ self._map = new_map
+
+ def _run(self) -> None:
+ """EN: Refresh loop — runs in a daemon thread. / FR: Boucle de rafraîchissement — thread daemon."""
+ while self._running:
+ self._refresh()
+ time.sleep(self.interval)
+
+ def start(self) -> None:
+ """EN: Prime the table synchronously, then start the refresh thread.
+ FR: Remplir la table en synchrone, puis lancer le thread de rafraîchissement."""
+ self._refresh()
+ self._running = True
+ self._thread = threading.Thread(target=self._run, daemon=True)
+ self._thread.start()
+
+ def stop(self) -> None:
+ self._running = False
+
+ def lookup(self, port: int, proto: str) -> tuple[Optional[int], Optional[str]]:
+ """
+ EN: Hot-path lookup — O(1), no syscalls. A miss means the socket
+ appeared/disappeared between refreshes; returned as (None, None).
+ FR: Recherche du chemin chaud — O(1), sans appel système. Un échec
+ signifie que le socket est apparu/disparu entre deux
+ rafraîchissements ; renvoyé comme (None, None).
+ """
+ kind = "tcp" if proto == "TCP" else "udp"
+ with self._lock:
+ return self._map[kind].get(port, (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.
+ EN: Scapy-based capture with an optional BPF port filter. The user
+ callback fires once per relevant packet — from the sniffer thread,
+ not the event loop.
+ FR: Capture basée sur Scapy avec filtre de ports BPF optionnel. Le callback
+ utilisateur est appelé une fois par paquet pertinent — depuis le thread
+ du sniffer, pas depuis la boucle asyncio.
"""
def __init__(self, callback: Callable[[Packet], None], ports: list[int] | None = None):
@@ -103,33 +157,42 @@ class PacketSniffer:
self.ports = ports or []
self.local_ips = get_local_ips()
self._sniffer: Optional[AsyncSniffer] = None
+ self._conn_table = ConnectionTable()
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.
+ EN: Berkeley Packet Filter expression — kernel-side filtering is far
+ cheaper than Python-side. Covers IPv4 AND IPv6.
+ FR: Expression BPF — le filtrage côté noyau coûte bien moins cher que
+ côté Python. Couvre IPv4 ET IPv6.
"""
if not self.ports:
- return "ip"
+ return "ip or ip6"
port_expr = " or ".join(f"port {p}" for p in self.ports)
- return f"ip and ({port_expr})"
+ return f"(ip or ip6) 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.
+ EN: Convert a raw Scapy packet into our normalized Packet. Drops
+ non-IP traffic and packets that do not involve this host.
+ IPv6 is handled transparently: TCP/UDP layers sit above either
+ network layer.
+ FR: Convertir un paquet Scapy brut en Packet normalisée. Ignore le
+ trafic non-IP et les paquets qui ne concernent pas cet hôte.
+ IPv6 est géré de façon transparente : les couches TCP/UDP se
+ placent au-dessus de l'une ou l'autre couche réseau.
"""
- if not pkt.haslayer(IP):
+ if pkt.haslayer(IP):
+ ip_layer = pkt[IP]
+ elif SCAPY_AVAILABLE and pkt.haslayer(IPv6):
+ ip_layer = pkt[IPv6]
+ else:
return
- ip = pkt[IP]
- src, dst = ip.src, ip.dst
+ src = ip_layer.src.split("%")[0]
+ dst = ip_layer.dst.split("%")[0]
# EN: Only care about traffic from/to this machine.
# FR: On ne garde que le trafic de/vers cette machine.
@@ -151,11 +214,11 @@ class PacketSniffer:
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.
+ # EN: Process attribution via the cached connection table.
+ # FR: Attribution du processus via la table de connexions en cache.
pid, process_name = None, None
if local_port and proto in ("TCP", "UDP"):
- pid, process_name = get_process_for_port(local_port, proto)
+ pid, process_name = self._conn_table.lookup(local_port, proto)
packet = Packet(
src_ip=src,
@@ -164,7 +227,7 @@ class PacketSniffer:
dst_port=dst_port,
protocol=proto,
size=len(pkt),
- timestamp=datetime.utcnow().isoformat(),
+ timestamp=datetime.now(timezone.utc).isoformat(),
direction=direction,
pid=pid,
process_name=process_name,
@@ -173,17 +236,17 @@ class PacketSniffer:
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.
+ EN: Blocking call — run inside a daemon thread. Starts the connection
+ table first, then the AsyncSniffer, then idles while it works.
+ FR: Appel bloquant — à lancer dans un thread daemon. Démarre d'abord la
+ table de connexions, puis l'AsyncSniffer, puis se met en attente.
"""
if not SCAPY_AVAILABLE:
- print("[sniffer] scapy not available — packet capture disabled", flush=True)
+ logger.warning("scapy not available — packet capture disabled")
return
self._running = True
try:
+ self._conn_table.start()
self._sniffer = AsyncSniffer(
filter=self._bpf_filter,
prn=self._process_packet,
@@ -193,10 +256,14 @@ class PacketSniffer:
while self._running:
time.sleep(1)
except Exception as exc:
- print(f"[sniffer] failed to start: {exc}", flush=True)
+ logger.error("sniffer failed to start: %s", exc)
def stop(self) -> None:
- """EN: Stop capture. / FR: Arrêter la capture."""
+ """EN: Stop capture + the connection-table thread. / FR: Arrêter la capture + le thread de la table."""
self._running = False
+ self._conn_table.stop()
if self._sniffer:
- self._sniffer.stop()
+ try:
+ self._sniffer.stop()
+ except Exception as exc:
+ logger.debug("sniffer stop failed: %s", exc)
diff --git a/backend/conftest.py b/backend/conftest.py
new file mode 100644
index 0000000..12bc065
--- /dev/null
+++ b/backend/conftest.py
@@ -0,0 +1,21 @@
+"""
+Snitch — pytest bootstrap.
+
+EN: Guarantees that the `backend/` directory is on sys.path regardless of how
+ pytest is invoked, so tests can do `from classifier.traffic import …`.
+ Also redirects the data directory to a temp folder BEFORE any storage
+ module is imported — tests must never touch the real snitch.db.
+
+FR: Garantit que le dossier `backend/` est dans sys.path quelle que soit la
+ façon dont pytest est lancé, pour que les tests puissent faire
+ `from classifier.traffic import …`. Redirige aussi le dossier de données
+ vers un dossier temporaire AVANT tout import de storage — les tests ne
+ doivent jamais toucher la vraie snitch.db.
+"""
+
+import os
+import sys
+import tempfile
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+os.environ.setdefault("SNITCH_DATA_DIR", tempfile.mkdtemp(prefix="snitch-test-"))
diff --git a/backend/detection/anomaly.py b/backend/detection/anomaly.py
index 9213ea9..1395592 100644
--- a/backend/detection/anomaly.py
+++ b/backend/detection/anomaly.py
@@ -2,41 +2,74 @@
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:
+ ARP-discovered device. Emits `Alert` objects broadcast to the UI and
+ persisted to SQLite. Alert *messages* stay English — the frontend maps
+ `alert.type` + `alert.details` to fully translated strings, so rules only
+ need to ship parameters, not prose.
+
+ 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)
+ - SUSPICIOUS_PORT traffic to ports associated with shells/botnets/Tor
+ - BEACON *regular-interval* traffic (low interval variance)
+ — real C2 heartbeat detection, not a dumb rate count
- VOLUME_SPIKE a single packet far above the host's average size
- 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 :
+ Robustness:
+ - every public method takes `self._lock` — the API calls us from a
+ thread-pool executor, so shared structures must be serialized
+ - all sets are size-bounded (`BoundedSet`, LRU eviction) so memory
+ can't grow forever on long-running sessions
+ - whitelists are deliberately strict: browsers are NOT in the media
+ whitelist (a malicious extension exfiltrating mic audio through
+ Chrome must still be caught)
+
+FR: Détecteur à état basé sur des règles, alimenté par chaque paquet capturé
+ et chaque appareil découvert par ARP. Émet des `Alert` diffusés à l'UI et
+ persistés dans SQLite. Les *messages* d'alerte restent en anglais — le
+ frontend traduit à partir de `alert.type` + `alert.details`, donc les
+ règles n'expédient que des paramètres, pas du texte.
+
+ 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
+ - SUSPICIOUS_PROCESS binaires à double usage/abusés qui se connectent
+ - SUSPICIOUS_PORT trafic vers des ports associés shells/botnets/Tor
+ - BEACON trafic à intervalles *réguliers* (faible variance) —
+ vraie détection de heartbeat C2, pas un simple compteur
+ - VOLUME_SPIKE un paquet bien au-dessus de la moyenne de l'hôte
+ - MEDIA_EXFIL processus micro/caméra (non whitelisté) qui émet
- NEW_LAN_DEVICE un appareil apparaît sur le réseau local
- DEVICE_OFFLINE un appareil disparaît du réseau local
+
+ Robustesse :
+ - chaque méthode publique prend `self._lock` — l'API nous appelle depuis
+ un pool de threads, les structures partagées doivent être sérialisées
+ - tous les ensembles sont bornés (`BoundedSet`, éviction LRU) pour que la
+ mémoire ne grossisse pas sans fin sur les longues sessions
+ - whitelists volontairement strictes : les navigateurs ne sont PAS dans
+ la whitelist média (une extension malveillante exfiltrant le micro via
+ Chrome doit être détectée)
"""
import ipaddress
+import logging
+import math
+import threading
import time
import uuid
-from collections import defaultdict, deque
+from collections import OrderedDict, defaultdict, deque
from dataclasses import dataclass, field
-from datetime import datetime
+from datetime import datetime, timezone
from typing import Optional
from capture.sniffer import Packet
from scanner.arp_scanner import Device
+logger = logging.getLogger("snitch.detection")
+
# ── Constants / Constantes ───────────────────────────────────────────────────
# EN: Windows binaries frequently abused for "living off the land" attacks.
@@ -47,8 +80,12 @@ SUSPICIOUS_PROCESSES = {
"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.
+# EN: Ports strongly associated with backdoors/botnets. 8080 and 5900/5901
+# were REMOVED — far too many false positives on legitimate dev tools
+# and VNC on home networks.
+# FR: Ports fortement associés aux backdoors/botnets. 8080 et 5900/5901 ont
+# été RETIRÉS — trop de faux positifs sur les outils de dev légitimes et
+# VNC domestique.
SUSPICIOUS_PORTS = {
4444: "Metasploit shell",
4445: "Metasploit shell",
@@ -56,25 +93,36 @@ SUSPICIOUS_PORTS = {
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
+# ── Beacon detection parameters / Paramètres de détection beacon ─────────────
+# EN: A beacon is periodic traffic: many similarly-sized gaps between packets.
+# We require enough samples, a plausible C2 interval (1 s – 10 min) and a
+# coefficient of variation below BEACON_MAX_CV — streaming/downloads have
+# irregular intervals and won't trigger.
+# FR: Un beacon est un trafic périodique : beaucoup d'intervalles similaires
+# entre paquets. On exige assez d'échantillons, un intervalle C2 plausible
+# (1 s – 10 min) et un coefficient de variation sous BEACON_MAX_CV — le
+# streaming/téléchargement a des intervalles irréguliers et ne déclenche pas.
+BEACON_MIN_SAMPLES = 12
+BEACON_MIN_INTERVAL_S = 1.0
+BEACON_MAX_INTERVAL_S = 600.0
+BEACON_MAX_CV = 0.35
+BEACON_MIN_SPAN_S = 60.0
+
+VOLUME_SPIKE_FACTOR = 8 # EN: 8× average bytes → spike / FR: 8× la moyenne → 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.
+# EN: Legitimate conferencing apps allowed to use mic/camera + network.
+# Browsers were DELIBERATELY removed: an extension exfiltrating mic audio
+# through Chrome/Firefox would otherwise be invisible.
+# FR: Apps de visio légitimes autorisées à utiliser micro/caméra + réseau.
+# Les navigateurs ont été RETIRÉS volontairement : une extension
+# exfiltrant l'audio via Chrome/Firefox serait sinon invisible.
MEDIA_WHITELIST = {
"discord.exe", "discord",
"teams.exe", "ms-teams.exe", "teams",
@@ -82,18 +130,11 @@ MEDIA_WHITELIST = {
"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.
+# EN: IPs that legitimately receive frequent small packets — never beacon-flagged.
+# FR: IP recevant légitimement de fréquents petits paquets — jamais signalées beacon.
BEACON_WHITELIST = {
"1.1.1.1", "1.0.0.1", # Cloudflare
"8.8.8.8", "8.8.4.4", # Google DNS
@@ -105,25 +146,63 @@ BEACON_WHITELIST = {
"129.6.15.28", "129.6.15.29", # NIST NTP
}
+# EN: Caps on long-lived state — a Snitch instance running for days must not
+# leak memory through unbounded sets/dicts.
+# FR: Plafonds sur l'état longue durée — une instance Snitch tournant des jours
+# ne doit pas fuiter de mémoire via des ensembles/dicts non bornés.
+MAX_SEEN_HOSTS = 50_000
+MAX_SEEN_PROC_CONNS = 50_000
+MAX_TRACKED_IPS = 10_000
+MAX_COOLDOWN_KEYS = 10_000
+
+
+class BoundedSet:
+ """
+ EN: Insertion-ordered set with a hard cap — evicts the oldest entry when
+ full. Used for _seen_hosts / _seen_process_conns.
+ FR: Ensemble ordonné par insertion avec plafond strict — évince l'entrée
+ la plus ancienne quand il est plein. Utilisé pour _seen_hosts /
+ _seen_process_conns.
+ """
+
+ def __init__(self, maxlen: int):
+ self._d: OrderedDict = OrderedDict()
+ self._maxlen = maxlen
+
+ def add(self, key: str) -> None:
+ self._d[key] = None
+ self._d.move_to_end(key)
+ while len(self._d) > self._maxlen:
+ self._d.popitem(last=False)
+
+ def discard(self, key: str) -> None:
+ self._d.pop(key, None)
+
+ def __contains__(self, key: str) -> bool:
+ return key in self._d
+
+ def __len__(self) -> int:
+ return len(self._d)
+
# ── 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.
+ EN: One detection event. `severity` drives the UI color; `type` + `details`
+ carry everything the frontend needs to render a translated message.
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` + `details` portent tout ce qu'il faut au frontend pour rendre
+ un message traduit.
"""
type: str
severity: str # "info" | "warning" | "critical"
- message: str
+ message: str # EN: English fallback / FR: texte de repli en anglais
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())
+ timestamp: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
def to_dict(self) -> dict:
return {
@@ -141,21 +220,22 @@ class Alert:
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.
+ EN: Per-host sliding windows (packet timestamps for regularity, byte
+ sizes for spikes), bounded seen-sets and a cooldown map to avoid
+ alert spam. All public methods hold `self._lock` — they are invoked
+ concurrently from the API's thread-pool executor.
+ FR: Fenêtres glissantes par hôte (timestamps des paquets pour la
+ régularité, tailles pour les pics), ensembles bornés et table de
+ cooldown anti-spam. Toutes les méthodes publiques tiennent
+ `self._lock` — elles sont appelées en concurrence depuis le pool de
+ threads de l'API.
"""
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._lock = threading.Lock()
+ self._seen_hosts = BoundedSet(MAX_SEEN_HOSTS)
+ self._seen_process_conns = BoundedSet(MAX_SEEN_PROC_CONNS)
+ self._pkt_times: dict[str, deque] = defaultdict(lambda: deque(maxlen=120))
self._host_bytes_window: dict[str, deque] = defaultdict(lambda: deque(maxlen=60))
self._cooldowns: dict[str, float] = {}
self.history: list[dict] = []
@@ -163,79 +243,105 @@ class AnomalyDetector:
self._cam_procs: set[str] = set()
def update_media_state(self, mic: list[str], camera: list[str]) -> None:
+ """EN: Sync mic/camera process sets from the media monitor.
+ FR: Synchroniser les ensembles micro/caméra depuis le moniteur média."""
+ with self._lock:
+ self._mic_procs = {p.lower() for p in mic}
+ self._cam_procs = {p.lower() for p in camera}
+
+ def forget(self, ip: str) -> None:
+ """
+ EN: Drop all runtime state for an IP (e.g. after it is whitelisted).
+ Without this, a previously-seen IP stays "known" forever.
+ FR: Oublier tout l'état d'une IP (ex. après whitelistage). Sans cela,
+ une IP déjà vue resterait « connue » pour toujours.
+ """
+ with self._lock:
+ self._seen_hosts.discard(ip)
+ self._pkt_times.pop(ip, None)
+ self._host_bytes_window.pop(ip, None)
+ for k in [k for k in self._cooldowns if k.endswith(f":{ip}") or k == ip]:
+ self._cooldowns.pop(k, None)
+
+ def reset_runtime(self) -> 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.
+ EN: Clear detection state (used when the port filter resets the graph).
+ History is kept — resetting the view shouldn't erase the past.
+ FR: Vider l'état de détection (utilisé quand le filtre de ports
+ réinitialise le graphe). L'historique est conservé — réinitialiser
+ la vue ne doit pas effacer le passé.
"""
- self._mic_procs = {p.lower() for p in mic}
- self._cam_procs = {p.lower() for p in camera}
+ with self._lock:
+ self._seen_hosts = BoundedSet(MAX_SEEN_HOSTS)
+ self._seen_process_conns = BoundedSet(MAX_SEEN_PROC_CONNS)
+ self._pkt_times.clear()
+ self._host_bytes_window.clear()
+ self._cooldowns.clear()
# ── 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.
+ EN: Run every packet-level rule under the lock. Private/LAN IPs are
+ ignored — LAN devices have their own device-level rules.
+ FR: Exécuter toutes les règles niveau paquet sous le verrou. 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)
+ return []
- self._record(alerts)
- return alerts
+ with self._lock:
+ alerts: list[Alert] = []
+ 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
+ FR: Règles 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
+ label = device.hostname or device.vendor or device.ip
+
+ with self._lock:
+ if is_new:
+ if self._cooldown_ok(f"new_device:{device.ip}"):
+ alerts.append(Alert(
+ type="NEW_LAN_DEVICE",
+ severity="info",
+ message=f"New device on the network: {label}",
+ node_id=f"lan:{device.ip}",
+ details={"ip": device.ip, "mac": device.mac, "vendor": device.vendor, "host": label},
+ ))
+ elif not device.online:
+ if self._cooldown_ok(f"offline:{device.ip}"):
+ alerts.append(Alert(
+ type="DEVICE_OFFLINE",
+ severity="info",
+ message=f"Device went offline: {label}",
+ node_id=f"lan:{device.ip}",
+ details={"ip": device.ip, "host": label},
+ ))
+
+ self._record(alerts)
+ return alerts
# ── Detection rules / Règles de détection ────────────────────────────────
+ # EN: All called with self._lock held.
+ # FR: Toutes appelées avec self._lock tenu.
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."""
+ """EN: First contact with a remote IP → info alert, once ever.
+ FR: Premier contact avec une IP distante → alerte info, une fois."""
if ip in self._seen_hosts:
return []
self._seen_hosts.add(ip)
@@ -245,7 +351,7 @@ class AnomalyDetector:
severity="info",
message=f"New host contacted: {label}",
node_id=ip,
- details={"ip": ip, "org": geo.get("org", ""), "country": geo.get("country", "")},
+ details={"ip": ip, "host": label, "org": geo.get("org", ""), "country": geo.get("country", "")},
)]
def _check_suspicious_process(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:
@@ -267,7 +373,7 @@ class AnomalyDetector:
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},
+ details={"process": pkt.process_name, "ip": remote_ip, "host": label, "port": pkt.dst_port},
)]
def _check_suspicious_port(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:
@@ -276,8 +382,7 @@ class AnomalyDetector:
port = pkt.dst_port
if port not in SUSPICIOUS_PORTS:
return []
- key = f"port:{port}:{remote_ip}"
- if not self._cooldown_ok(key):
+ if not self._cooldown_ok(f"port:{port}:{remote_ip}"):
return []
label = geo.get("hostname") or remote_ip
reason = SUSPICIOUS_PORTS[port]
@@ -286,52 +391,86 @@ class AnomalyDetector:
severity="warning",
message=f"Suspicious port {port} ({reason}) -> {label}",
node_id=remote_ip,
- details={"port": port, "reason": reason, "ip": remote_ip},
+ details={"port": port, "reason": reason, "ip": remote_ip, "host": label},
)]
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.
+ EN: True beacon detection — regularity, not volume. We look at the
+ inter-packet intervals in a per-host window and require:
+ * ≥ BEACON_MIN_SAMPLES intervals,
+ * a window spanning ≥ BEACON_MIN_SPAN_S,
+ * mean interval inside a C2-plausible range (1 s – 10 min),
+ * coefficient of variation < BEACON_MAX_CV.
+ Streaming and bulk downloads have wildly varying (or sub-second)
+ intervals and won't trip this.
+ FR: Vraie détection de beacon — la régularité, pas le volume. On
+ observe les intervalles inter-paquets dans une fenêtre par hôte et
+ on exige :
+ * ≥ BEACON_MIN_SAMPLES intervalles,
+ * une fenêtre couvrant ≥ BEACON_MIN_SPAN_S,
+ * un intervalle moyen dans la plage plausible C2 (1 s – 10 min),
+ * un coefficient de variation < BEACON_MAX_CV.
+ Le streaming et les gros téléchargements ont des intervalles très
+ variables (ou sous la seconde) et ne déclenchent pas.
"""
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:
+ dq.append(time.time())
+
+ # EN: Bound the tracking dict itself — forget hosts with stale windows.
+ # FR: Borner aussi le dict de suivi — oublier les hôtes à fenêtre périmée.
+ if len(self._pkt_times) > MAX_TRACKED_IPS:
+ self._pkt_times.clear()
+
+ if len(dq) < BEACON_MIN_SAMPLES + 1:
+ return []
+
+ times = list(dq)
+ span = times[-1] - times[0]
+ if span < BEACON_MIN_SPAN_S:
+ return []
+
+ intervals = [b - a for a, b in zip(times, times[1:])]
+ mean = sum(intervals) / len(intervals)
+ if not (BEACON_MIN_INTERVAL_S <= mean <= BEACON_MAX_INTERVAL_S):
+ return []
+ if mean <= 0:
return []
- key = f"beacon:{remote_ip}"
- if not self._cooldown_ok(key, cooldown=300):
+
+ variance = sum((i - mean) ** 2 for i in intervals) / len(intervals)
+ cv = math.sqrt(variance) / mean
+ if cv >= BEACON_MAX_CV:
+ return []
+
+ if not self._cooldown_ok(f"beacon:{remote_ip}", 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}",
+ message=f"Beacon-like regularity: ~{mean:.0f}s interval to {label} (CV {cv:.2f})",
node_id=remote_ip,
- details={"ip": remote_ip, "rate": recent},
+ details={"ip": remote_ip, "host": label, "interval_s": round(mean, 1), "cv": round(cv, 3), "samples": len(intervals)},
)]
def _check_volume_spike(self, remote_ip: str, size: int, geo: dict) -> list[Alert]:
- """
- EN: 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.
- """
+ """EN: One packet ≥ 8× the rolling average for that host → possible
+ burst/exfil → warning. / FR: Un paquet ≥ 8× la moyenne glissante de
+ l'hôte → rafale/exfil possible → warning."""
dq = self._host_bytes_window[remote_ip]
dq.append(size)
+ if len(self._host_bytes_window) > MAX_TRACKED_IPS:
+ self._host_bytes_window.clear()
if len(dq) < 10:
return []
avg = sum(dq) / len(dq)
if size < avg * VOLUME_SPIKE_FACTOR or avg < 100:
return []
- key = f"spike:{remote_ip}"
- if not self._cooldown_ok(key, cooldown=120):
+ if not self._cooldown_ok(f"spike:{remote_ip}", cooldown=120):
return []
label = geo.get("hostname") or remote_ip
return [Alert(
@@ -339,17 +478,17 @@ class AnomalyDetector:
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)},
+ details={"ip": remote_ip, "host": label, "size": size, "avg": int(avg), "kb": size // 1024},
)]
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.
+ EN: Signature rule — a process holding the mic/camera, NOT a known
+ conferencing app, sending outbound traffic → critical.
+ Browsers are intentionally excluded from the whitelist.
+ FR: Règle signature — un processus qui tient le micro/la caméra, qui
+ N'EST PAS une app de visio connue, et qui émet du trafic sortant →
+ critique. Les navigateurs sont volontairement exclus de la whitelist.
"""
if not pkt.process_name:
return []
@@ -360,8 +499,7 @@ class AnomalyDetector:
return []
if pkt.direction != "out":
return []
- key = f"media_exfil:{proc}:{remote_ip}"
- if not self._cooldown_ok(key, cooldown=300):
+ if not self._cooldown_ok(f"media_exfil:{proc}:{remote_ip}", cooldown=300):
return []
device = "microphone" if proc in self._mic_procs else "camera"
label = geo.get("hostname") or remote_ip
@@ -370,29 +508,33 @@ class AnomalyDetector:
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", "")},
+ details={"process": pkt.process_name, "device": device, "ip": remote_ip, "host": label, "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.
+ EN: True (and re-arm) if this key hasn't fired within `cooldown`
+ seconds. The map is pruned when it grows past its cap.
+ FR: True (et réarme) si cette clé n'a pas tiré depuis `cooldown`
+ secondes. La table est purgée quand elle dépasse son plafond.
"""
now = time.time()
+ if len(self._cooldowns) > MAX_COOLDOWN_KEYS:
+ # EN: Drop expired entries first; if still huge, wipe.
+ # FR: Évincer d'abord les entrées expirées ; si encore énorme, vider.
+ self._cooldowns = {k: v for k, v in self._cooldowns.items() if now - v < 3600}
+ if len(self._cooldowns) > MAX_COOLDOWN_KEYS:
+ self._cooldowns.clear()
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).
- """
+ """EN: Append to the bounded in-memory history (last 500).
+ FR: Ajouter à l'historique en mémoire borné (500 dernières)."""
for a in alerts:
self.history.append(a.to_dict())
if len(self.history) > 500:
@@ -400,7 +542,8 @@ class AnomalyDetector:
def _is_private(ip: str) -> bool:
- """EN: RFC1918 / loopback / link-local check. / FR: Test RFC1918 / loopback / link-local."""
+ """EN: RFC1918 / loopback / link-local / ULA check (v4 + v6).
+ FR: Test RFC1918 / loopback / link-local / ULA (v4 + v6)."""
try:
return ipaddress.ip_address(ip).is_private
except ValueError:
diff --git a/backend/logging_config.py b/backend/logging_config.py
new file mode 100644
index 0000000..f3d9b72
--- /dev/null
+++ b/backend/logging_config.py
@@ -0,0 +1,74 @@
+"""
+Snitch — logging configuration.
+
+EN: Central logging setup. Logs go to stdout AND a rotating file in the data
+ directory (<data>/logs/snitch.log, 3 × 1 MB). Called once from
+ run_backend.py; library modules just do `logging.getLogger("snitch.x")`.
+ Replaces the old `except Exception: pass` pattern with real, debuggable
+ diagnostics.
+
+FR: Configuration centralisée des logs. Sortie vers stdout ET un fichier
+ rotatif dans le dossier de données (<data>/logs/snitch.log, 3 × 1 Mo).
+ Appelé une fois depuis run_backend.py ; les modules utilisent simplement
+ `logging.getLogger("snitch.x")`. Remplace l'ancien motif
+ `except Exception: pass` par de vrais diagnostics exploitables.
+"""
+
+import logging
+import os
+import sys
+from logging.handlers import RotatingFileHandler
+from pathlib import Path
+
+
+def _data_dir() -> Path:
+ """
+ EN: Same resolution as api.security / storage.db — duplicated here so this
+ module has zero internal dependencies (it must be importable first).
+ FR: Même résolution que api.security / storage.db — dupliquée ici pour que
+ ce module n'ait aucune dépendance interne (il doit être importable en
+ premier).
+ """
+ env_dir = os.environ.get("SNITCH_DATA_DIR")
+ if env_dir:
+ d = Path(env_dir)
+ elif getattr(sys, "frozen", False):
+ d = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "Snitch"
+ else:
+ d = Path(__file__).parent.parent / "data"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def setup_logging(level: int = logging.INFO) -> Path:
+ """
+ EN: Configure the root "snitch" logger. Returns the log file path.
+ Idempotent — safe to call twice.
+ FR: Configurer le logger racine « snitch ». Renvoie le chemin du fichier
+ de log. Idempotent — appelable plusieurs fois sans effet.
+ """
+ log_dir = _data_dir() / "logs"
+ log_dir.mkdir(parents=True, exist_ok=True)
+ log_file = log_dir / "snitch.log"
+
+ root = logging.getLogger("snitch")
+ if root.handlers:
+ return log_file # EN: already configured / FR: déjà configuré
+
+ root.setLevel(level)
+ fmt = logging.Formatter("%(asctime)s %(levelname)s [%(name)s] %(message)s")
+
+ console = logging.StreamHandler()
+ console.setFormatter(fmt)
+ root.addHandler(console)
+
+ try:
+ file_handler = RotatingFileHandler(
+ log_file, maxBytes=1_000_000, backupCount=3, encoding="utf-8"
+ )
+ file_handler.setFormatter(fmt)
+ root.addHandler(file_handler)
+ except OSError as exc:
+ root.warning("File logging unavailable (%s) — console only", exc)
+
+ return log_file
diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt
new file mode 100644
index 0000000..c8175c8
--- /dev/null
+++ b/backend/requirements-dev.txt
@@ -0,0 +1,9 @@
+# Snitch — dev/test dependencies.
+# EN: Pinned versions only — supply-chain hygiene. Install with:
+# pip install -r requirements.txt -r requirements-dev.txt
+# FR: Versions épinglées uniquement — hygiène de la chaîne d'approvisionnement.
+# Installation : pip install -r requirements.txt -r requirements-dev.txt
+
+pytest==8.3.4
+ruff==0.8.4
+httpx==0.27.2 # EN: needed by FastAPI's TestClient / FR: requis par le TestClient FastAPI
diff --git a/backend/resolver/dns_geo.py b/backend/resolver/dns_geo.py
index 39d76b1..c87198b 100644
--- a/backend/resolver/dns_geo.py
+++ b/backend/resolver/dns_geo.py
@@ -2,40 +2,78 @@
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.
+ 1. reverse DNS (hostname) via socket.gethostbyaddr
+ 2. geolocation, local GeoLite2 offline DB via geoip2 (optional)
+ 3. OPTIONAL online fallback to ip-api.com via urllib (45 req/min)
+
+ PRIVACY: the online fallback sends every contacted IP to a third-party
+ service in plaintext. For a privacy tool that's contradictory, so it is
+ OFF by default — enable it explicitly with SNITCH_ONLINE_GEO=1 and get a
+ GeoLite2 DB for fully-offline lookups.
+
+ Reliability fixes vs the naive version:
+ - reverse DNS bounded by a global socket timeout (no more executor
+ threads parked forever)
+ - ip-api results use a TTL cache; failures are NOT cached, so a
+ temporary error doesn't permanently blind an IP
+ - a tiny client-side rate limiter keeps us under the 45 req/min quota
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.
+ 1. DNS inverse (hostname) via socket.gethostbyaddr
+ 2. géolocalisation, BDD hors ligne GeoLite2 via geoip2 (optionnel)
+ 3. repli en ligne OPTIONNEL vers ip-api.com via urllib (45 req/min)
+
+ CONFIDENTIALITÉ : le repli en ligne envoie chaque IP contactée à un service
+ tiers en clair. Contradictoire pour un outil de confidentialité : il est
+ donc DÉSACTIVÉ par défaut — l'activer explicitement avec
+ SNITCH_ONLINE_GEO=1, ou déposer une base GeoLite2 pour des recherches
+ 100 % hors ligne.
+
+ Corrections de fiabilité :
+ - DNS inverse borné par un timeout global de socket (plus de threads
+ d'executor bloqués indéfiniment)
+ - résultats ip-api dans un cache à TTL ; les échecs ne sont PAS cachés,
+ donc une erreur temporaire n'aveugle pas une IP pour toujours
+ - un petit limiteur côté client reste sous le quota de 45 req/min
"""
import asyncio
import ipaddress
import json
+import logging
+import os
import socket
+import threading
+import time
import urllib.request
+from collections import deque
from functools import lru_cache
from pathlib import Path
from typing import Optional
+logger = logging.getLogger("snitch.resolver")
+
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.
+ # EN: geoip2 not installed — MaxMind lookups unavailable.
+ # FR: geoip2 non installé — recherches MaxMind indisponibles.
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.
+# EN: Global ceiling for blocking socket operations (reverse DNS mainly).
+# gethostbyaddr has no per-call timeout, so we bound it globally.
+# FR: Plafond global pour les opérations socket bloquantes (DNS inverse surtout).
+# gethostbyaddr n'a pas de timeout par appel : on le borne globalement.
+socket.setdefaulttimeout(3)
+
+# EN: Online geolocation is OPT-IN (privacy by default).
+# FR: La géolocalisation en ligne est OPT-IN (confidentialité par défaut).
+ONLINE_GEO_ENABLED = os.environ.get("SNITCH_ONLINE_GEO", "").strip() == "1"
+
+# EN: Optional GeoLite2 database — drop GeoLite2-City.mmdb into data/.
+# FR: Base GeoLite2 optionnelle — déposer GeoLite2-City.mmdb dans data/.
GEOIP_DB_PATH = Path(__file__).parent.parent.parent / "data" / "GeoLite2-City.mmdb"
_geoip_reader = None
@@ -44,12 +82,16 @@ 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))
+ try:
+ _geoip_reader = geoip2.database.Reader(str(GEOIP_DB_PATH))
+ except Exception as exc:
+ logger.warning("Could not open GeoLite2 DB at %s: %s", GEOIP_DB_PATH, exc)
return _geoip_reader
def is_private(ip: str) -> bool:
- """EN: RFC1918 / loopback / link-local check. / FR: Test RFC1918 / loopback / link-local."""
+ """EN: RFC1918 / loopback / link-local / ULA check — works for v4 and v6.
+ FR: Test RFC1918 / loopback / link-local / ULA — fonctionne en v4 et v6."""
try:
return ipaddress.ip_address(ip).is_private
except ValueError:
@@ -59,8 +101,11 @@ def is_private(ip: str) -> bool:
@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.
+ EN: Reverse DNS — returns None on NXDOMAIN/timeout. lru_cache caches
+ negatives too, which is what we want: failed lookups are stable.
+ FR: DNS inverse — renvoie None sur NXDOMAIN/timeout. lru_cache met aussi en
+ cache les échecs, ce qui est souhaité : les échecs de résolution sont
+ stables.
"""
try:
return socket.gethostbyaddr(ip)[0]
@@ -71,10 +116,12 @@ def resolve_hostname(ip: str) -> Optional[str]:
@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.
+ EN: Offline geolocation via the local GeoLite2 DB. Returns {} when the DB
+ is absent, the IP is private, or the lookup fails. Safe to cache —
+ results don't change within a session.
FR: Géolocalisation hors ligne via la base GeoLite2 locale. Renvoie {} si
- la base est absente, l'IP privée, ou la requête en échec.
+ la base est absente, l'IP privée, ou la requête en échec. Cache sûr —
+ les résultats ne changent pas pendant une session.
"""
reader = get_geoip_reader()
if not reader or is_private(ip):
@@ -93,23 +140,63 @@ def resolve_geo_maxmind(ip: str) -> dict:
return {}
-@lru_cache(maxsize=2048)
+# ── Online fallback: TTL cache + rate limiter ────────────────────────────────
+# ── Repli en ligne : cache TTL + limiteur de débit ───────────────────────────
+
+GEO_CACHE_TTL = 6 * 3600 # EN: 6h / FR: 6 h
+GEO_RATE_MAX = 40 # EN: max requests per window / FR: requêtes max par fenêtre
+GEO_RATE_WINDOW = 60 # seconds / secondes
+
+_geo_cache: dict[str, tuple[float, dict]] = {}
+_geo_cache_lock = threading.Lock()
+_geo_calls: deque = deque() # EN: timestamps of recent API calls / FR: timestamps des appels récents
+
+
+def _rate_limit_ok() -> bool:
+ """
+ EN: Sliding-window rate limiter — returns False when the quota for the
+ last 60 s is exhausted.
+ FR: Limiteur à fenêtre glissante — renvoie False quand le quota des 60
+ dernières secondes est épuisé.
+ """
+ now = time.time()
+ while _geo_calls and now - _geo_calls[0] > GEO_RATE_WINDOW:
+ _geo_calls.popleft()
+ if len(_geo_calls) >= GEO_RATE_MAX:
+ return False
+ _geo_calls.append(now)
+ return True
+
+
def resolve_geo_ipapi(ip: str) -> dict:
"""
- 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.
+ EN: Online fallback — free ip-api.com, no key, ~45 req/min.
+ Disabled unless SNITCH_ONLINE_GEO=1. Successes are TTL-cached;
+ failures return {} and are NOT cached so the IP can retry later.
+ FR: Repli en ligne — ip-api.com gratuit, sans clé, ~45 req/min.
+ Désactivé sauf si SNITCH_ONLINE_GEO=1. Les succès sont cachés avec TTL ;
+ les échecs renvoient {} et ne sont PAS cachés pour permettre un re-essai.
"""
- if is_private(ip):
+ if not ONLINE_GEO_ENABLED or is_private(ip):
return {}
+
+ now = time.time()
+ with _geo_cache_lock:
+ hit = _geo_cache.get(ip)
+ if hit and now - hit[0] < GEO_CACHE_TTL:
+ return hit[1]
+
+ if not _rate_limit_ok():
+ logger.debug("geo rate limit reached — skipping %s", ip)
+ 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 {
+ geo = {
"country": data.get("country"),
"country_code": data.get("countryCode"),
"city": data.get("city"),
@@ -117,16 +204,18 @@ def resolve_geo_ipapi(ip: str) -> dict:
"lon": data.get("lon"),
"org": data.get("org"),
}
- except Exception:
- pass
+ with _geo_cache_lock:
+ _geo_cache[ip] = (now, geo)
+ return geo
+ except Exception as exc:
+ logger.debug("ip-api lookup failed for %s: %s", ip, exc)
return {}
-@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.
+ EN: MaxMind first (offline, private), online fallback second.
+ FR: MaxMind d'abord (hors ligne, privé), repli en ligne ensuite.
"""
geo = resolve_geo_maxmind(ip)
if geo:
@@ -141,7 +230,7 @@ async def enrich_ip(ip: str) -> dict:
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()
+ loop = asyncio.get_running_loop()
hostname = await loop.run_in_executor(None, resolve_hostname, ip)
geo = await loop.run_in_executor(None, resolve_geo, ip)
return {
diff --git a/backend/run_backend.py b/backend/run_backend.py
index 1cb23ca..ea28345 100644
--- a/backend/run_backend.py
+++ b/backend/run_backend.py
@@ -1,53 +1,59 @@
"""
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.
+EN: Single entry point — used both in development (`python run_backend.py`)
+ and by PyInstaller for the standalone `snitch-backend` binary that
+ Electron spawns. `app` is imported as an object (not a string) so
+ PyInstaller traces the full import chain.
+
+ Binds to 127.0.0.1 by default in ALL modes — the API holds sensitive
+ traffic data and must never be network-exposed without an explicit
+ SNITCH_BIND override (token auth is always enforced regardless).
+
+FR: Point d'entrée unique — utilisé en développement (`python run_backend.py`)
+ et par PyInstaller pour le binaire autonome `snitch-backend` que lance
+ Electron. `app` est importé comme objet (pas une chaîne) pour que
+ PyInstaller suive toute la chaîne d'imports.
+
+ Écoute sur 127.0.0.1 par défaut dans TOUS les modes — l'API contient des
+ données de trafic sensibles et ne doit jamais être exposée au réseau sans
+ override explicite de SNITCH_BIND (le jeton reste de toute façon exigé).
"""
+import logging
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.
+# FR: Quand l'app est figée par PyInstaller, tous les modules sont dans sys._MEIPASS.
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
+# EN: Configure logging BEFORE importing app modules so they inherit handlers.
+# FR: Configurer les logs AVANT d'importer les modules pour qu'ils héritent des handlers.
+from logging_config import setup_logging # noqa: E402
+
+setup_logging(logging.INFO)
+
+# EN: Direct import — PyInstaller follows this chain and bundles 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).
+# FR: Import direct — PyInstaller suit cette chaîne et embarque tous les
+# paquets backend (api, capture, classifier, detection, resolver,
+# scanner, storage) automatiquement.
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'
+ # EN: Loopback-only by default everywhere — Electron AND Docker/dev.
+ # Set SNITCH_BIND=0.0.0.0 to expose (token auth still applies).
+ # FR: Loopback uniquement par défaut partout — Electron ET Docker/dev.
+ # Poser SNITCH_BIND=0.0.0.0 pour exposer (le jeton reste exigé).
uvicorn.run(
app,
- host=os.environ.get('SNITCH_BIND', default_bind),
+ host=os.environ.get('SNITCH_BIND', '127.0.0.1'),
port=int(os.environ.get('SNITCH_PORT', '8000')),
log_level='warning',
)
diff --git a/backend/scanner/arp_scanner.py b/backend/scanner/arp_scanner.py
index f71d725..35cb18f 100644
--- a/backend/scanner/arp_scanner.py
+++ b/backend/scanner/arp_scanner.py
@@ -13,6 +13,7 @@ FR: Scanne périodiquement en ARP chaque sous-réseau IPv4 auquel l'hôte est
"""
import ipaddress
+import logging
import socket
import threading
import time
@@ -23,6 +24,8 @@ import psutil
from scanner.oui import lookup, DEVICE_TYPE_COLORS
+logger = logging.getLogger("snitch.scanner")
+
try:
from scapy.all import ARP, Ether, srp
SCAPY_AVAILABLE = True
@@ -125,7 +128,8 @@ def _scan_subnet(subnet: str, timeout: int = 2) -> list[Device]:
verbose=False,
retry=1,
)
- except Exception:
+ except Exception as exc:
+ logger.debug("ARP scan of %s failed: %s", subnet, exc)
return []
devices = []
diff --git a/backend/storage/db.py b/backend/storage/db.py
index 92f2f8c..065a2f7 100644
--- a/backend/storage/db.py
+++ b/backend/storage/db.py
@@ -5,37 +5,51 @@ 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.
+ background thread flushes every 10 s. Hourly cleanup keeps the DB to a
+ 24-hour sliding window.
+
+ DB location resolution order:
+ 1. SNITCH_DATA_DIR env var (tests, custom deployments)
+ 2. LOCALAPPDATA\\Snitch (frozen/Electron builds on Windows)
+ 3. <repo>/data (dev / Docker)
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.
+ Un nettoyage horaire limite la base à une fenêtre glissante de 24 h.
+
+ Ordre de résolution de l'emplacement de la base :
+ 1. variable SNITCH_DATA_DIR (tests, déploiements personnalisés)
+ 2. LOCALAPPDATA\\Snitch (builds figés/Electron sous Windows)
+ 3. <dépôt>/data (dev / Docker)
"""
import json
+import logging
import os
import sqlite3
import sys
import threading
from collections import defaultdict
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from pathlib import Path
+logger = logging.getLogger("snitch.storage")
+
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/.
+ EN: Resolve the DB path — see module docstring for the precedence order.
+ FR: Résoudre le chemin de la base — voir le docstring du module pour
+ l'ordre de priorité.
"""
- if getattr(sys, 'frozen', False):
- appdata = Path(os.environ.get('LOCALAPPDATA', Path.home()))
- db_dir = appdata / 'Snitch'
+ env_dir = os.environ.get("SNITCH_DATA_DIR")
+ if env_dir:
+ db_dir = Path(env_dir)
+ elif getattr(sys, 'frozen', False):
+ db_dir = Path(os.environ.get('LOCALAPPDATA', Path.home())) / 'Snitch'
else:
db_dir = Path(__file__).parent.parent.parent / 'data'
db_dir.mkdir(parents=True, exist_ok=True)
@@ -57,6 +71,18 @@ _pending: dict[tuple, list] = defaultdict(lambda: [0, 0])
_pending_lock = threading.Lock()
+def _utcnow_minute() -> str:
+ """EN: Current UTC minute as 'YYYY-MM-DDTHH:MM' (timezone-aware; utcnow()
+ is deprecated since Python 3.12). / FR: Minute UTC courante au format
+ 'YYYY-MM-DDTHH:MM' (conscient du fuseau ; utcnow() est déprécié depuis 3.12)."""
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M")
+
+
+def _utcnow_iso() -> str:
+ """EN: Current UTC instant as ISO string. / FR: Instant UTC courant en ISO."""
+ return datetime.now(timezone.utc).isoformat()
+
+
# ── Connection & schema / Connexion & schéma ─────────────────────────────────
def get_conn() -> sqlite3.Connection:
@@ -131,16 +157,19 @@ def flush() -> None:
_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()
+ try:
+ 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()
+ except sqlite3.Error as exc:
+ logger.error("flush failed: %s", exc)
def log_alert(alert: dict) -> None:
@@ -150,17 +179,20 @@ def log_alert(alert: dict) -> None:
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()
+ try:
+ 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()
+ except sqlite3.Error as exc:
+ logger.error("log_alert failed: %s", exc)
# ── Read helpers / Aides de lecture ──────────────────────────────────────────
@@ -172,7 +204,7 @@ def get_timeline(minutes: int = 60) -> list[dict]:
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")
+ cutoff = (datetime.now(timezone.utc) - timedelta(minutes=minutes)).strftime("%Y-%m-%dT%H:%M")
with _conn_lock:
conn = get_conn()
@@ -211,9 +243,12 @@ def cleanup_old_data(hours: int = 24) -> None:
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()
+ cutoff = (datetime.now(timezone.utc) - timedelta(hours=hours)).strftime("%Y-%m-%dT%H:%M")
+ try:
+ 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()
+ except sqlite3.Error as exc:
+ logger.error("cleanup failed: %s", exc)
diff --git a/backend/tests/test_anomaly.py b/backend/tests/test_anomaly.py
new file mode 100644
index 0000000..9c04393
--- /dev/null
+++ b/backend/tests/test_anomaly.py
@@ -0,0 +1,170 @@
+"""
+Snitch — anomaly detector tests.
+
+EN: Covers per-packet rules: private-IP skip, NEW_HOST once-only, suspicious
+ ports/processes, MEDIA_EXFIL (whitelisting), forget(), and the
+ regularity-based beacon detection (regular intervals alert, bursty
+ traffic doesn't).
+FR: Couvre les règles par paquet : exclusion des IP privées, NEW_HOST une
+ seule fois, ports/processus suspects, MEDIA_EXFIL (whitelist), forget(),
+ et la détection de beacon par régularité (intervalles réguliers → alerte,
+ trafic en rafales → non).
+"""
+
+import time
+from collections import deque
+from datetime import datetime, timezone
+
+from capture.sniffer import Packet
+from detection.anomaly import AnomalyDetector, BEACON_MIN_SAMPLES
+
+PUBLIC_IP = "91.198.174.192" # EN: real public IP (wikipedia.org)
+ # FR: vraie IP publique (wikipedia.org)
+
+
+def pkt(remote=PUBLIC_IP, direction="out", port=443, size=500, process=None, proto="TCP"):
+ """EN: Build a Packet for tests. / FR: Construire un paquet de test."""
+ local = "192.168.1.10"
+ return Packet(
+ src_ip=local if direction == "out" else remote,
+ dst_ip=remote if direction == "out" else local,
+ src_port=50000 if direction == "out" else port,
+ dst_port=port if direction == "out" else 50000,
+ protocol=proto,
+ size=size,
+ timestamp=datetime.now(timezone.utc).isoformat(),
+ direction=direction,
+ process_name=process,
+ )
+
+
+def test_private_ip_produces_no_alerts():
+ det = AnomalyDetector()
+ assert det.analyze_packet(pkt(remote="192.168.1.55"), {}) == []
+
+
+def test_new_host_alerts_once():
+ det = AnomalyDetector()
+ first = det.analyze_packet(pkt(), {})
+ assert any(a.type == "NEW_HOST" for a in first)
+ assert det.analyze_packet(pkt(), {}) == []
+
+
+def test_suspicious_port():
+ det = AnomalyDetector()
+ alerts = det.analyze_packet(pkt(port=4444), {})
+ assert any(a.type == "SUSPICIOUS_PORT" and a.details["port"] == 4444 for a in alerts)
+
+
+def test_port_8080_not_flagged():
+ """EN: 8080 was removed from SUSPICIOUS_PORTS — dev servers must not alert.
+ FR: 8080 a été retiré des SUSPICIOUS_PORTS — les serveurs de dev ne doivent pas alerter."""
+ det = AnomalyDetector()
+ alerts = det.analyze_packet(pkt(port=8080), {})
+ assert not any(a.type == "SUSPICIOUS_PORT" for a in alerts)
+
+
+def test_suspicious_process():
+ det = AnomalyDetector()
+ alerts = det.analyze_packet(pkt(process="powershell.exe"), {})
+ assert any(a.type == "SUSPICIOUS_PROCESS" for a in alerts)
+
+
+def test_media_exfil_critical_for_unknown_process():
+ det = AnomalyDetector()
+ det.update_media_state(["evil.exe"], [])
+ alerts = det.analyze_packet(pkt(process="evil.exe"), {})
+ media = [a for a in alerts if a.type == "MEDIA_EXFIL"]
+ assert media and media[0].severity == "critical"
+
+
+def test_media_whitelisted_process_no_exfil():
+ """EN: A known conferencing app using the mic is not flagged.
+ FR: Une app de visio connue utilisant le micro n'est pas signalée."""
+ det = AnomalyDetector()
+ det.update_media_state(["zoom.exe"], [])
+ alerts = det.analyze_packet(pkt(process="zoom.exe"), {})
+ assert not any(a.type == "MEDIA_EXFIL" for a in alerts)
+
+
+def test_browser_not_media_whitelisted():
+ """EN: Browsers were removed from the whitelist — a mic-using Chrome
+ process exfiltrating MUST alert. / FR: Les navigateurs ont été retirés de
+ la whitelist — un Chrome micro-actif qui émet DOIT alerter."""
+ det = AnomalyDetector()
+ det.update_media_state(["chrome.exe"], [])
+ alerts = det.analyze_packet(pkt(process="chrome.exe"), {})
+ assert any(a.type == "MEDIA_EXFIL" for a in alerts)
+
+
+def test_inbound_traffic_never_media_exfil():
+ det = AnomalyDetector()
+ det.update_media_state(["evil.exe"], [])
+ alerts = det.analyze_packet(pkt(process="evil.exe", direction="in"), {})
+ assert not any(a.type == "MEDIA_EXFIL" for a in alerts)
+
+
+def test_forget_resets_seen_state():
+ """EN: After forget(), the host is treated as new again — needed when the
+ user removes an IP from the whitelist. / FR: Après forget(), l'hôte est
+ traité comme nouveau — nécessaire quand l'utilisateur retire une IP de la
+ whitelist."""
+ det = AnomalyDetector()
+ det.analyze_packet(pkt(), {})
+ det.forget(PUBLIC_IP)
+ alerts = det.analyze_packet(pkt(), {})
+ assert any(a.type == "NEW_HOST" for a in alerts)
+
+
+def test_beacon_detects_regular_intervals(monkeypatch):
+ """
+ EN: Regular 5 s intervals over a 60 s+ window → BEACON alert.
+ time.time is patched so the appended 'now' continues the cadence.
+ FR: Intervalles réguliers de 5 s sur une fenêtre de 60 s+ → alerte BEACON.
+ time.time est patché pour que le « maintenant » ajouté poursuive la
+ cadence.
+ """
+ det = AnomalyDetector()
+ t0 = 1_000_000.0
+ det._pkt_times[PUBLIC_IP] = deque(
+ [t0 + i * 5.0 for i in range(BEACON_MIN_SAMPLES)], maxlen=120
+ )
+ monkeypatch.setattr(time, "time", lambda: t0 + BEACON_MIN_SAMPLES * 5.0)
+ alerts = det._check_beacon(PUBLIC_IP, {})
+ assert any(a.type == "BEACON" for a in alerts)
+ monkeypatch.undo()
+
+
+def test_beacon_ignores_bursty_traffic(monkeypatch):
+ """EN: Irregular intervals (bursts) must NOT be flagged as beacons —
+ that's what streaming/download looks like. / FR: Des intervalles
+ irréguliers (rafales) ne doivent PAS être signalés — c'est à ça que
+ ressemble le streaming/téléchargement."""
+ det = AnomalyDetector()
+ t0 = 1_000_000.0
+ # EN: Wildly varying gaps: 0.01 s … 40 s. / FR: Écarts très variables : 0,01 s … 40 s.
+ gaps = [0.01, 12, 0.4, 30, 0.05, 8, 40, 0.1, 3, 25, 0.02, 15, 7]
+ times, cur = [t0], t0
+ for g in gaps:
+ cur += g
+ times.append(cur)
+ det._pkt_times[PUBLIC_IP] = deque(times, maxlen=120)
+ monkeypatch.setattr(time, "time", lambda: cur + 0.1)
+ alerts = det._check_beacon(PUBLIC_IP, {})
+ assert not any(a.type == "BEACON" for a in alerts)
+
+
+def test_beacon_whitelisted_dns_never_alerts():
+ """EN: Public resolvers get constant small traffic — never beacons.
+ FR: Les résolveurs publics reçoivent du trafic constant — jamais de beacon."""
+ det = AnomalyDetector()
+ det._pkt_times["8.8.8.8"] = deque([time.time() - i * 5 for i in range(60)], maxlen=120)
+ assert det._check_beacon("8.8.8.8", {}) == []
+
+
+def test_reset_runtime_clears_state():
+ det = AnomalyDetector()
+ det.analyze_packet(pkt(), {})
+ det.reset_runtime()
+ alerts = det.analyze_packet(pkt(), {})
+ assert any(a.type == "NEW_HOST" for a in alerts)
diff --git a/backend/tests/test_classifier.py b/backend/tests/test_classifier.py
new file mode 100644
index 0000000..7476db7
--- /dev/null
+++ b/backend/tests/test_classifier.py
@@ -0,0 +1,45 @@
+"""
+Snitch — classifier tests.
+
+EN: Covers the classification priority: tracker domains > CDN > well-known
+ ports > unknown fallback.
+FR: Couvre la priorité de classification : domaines trackers > CDN > ports
+ connus > repli « unknown ».
+"""
+
+from classifier.traffic import classify
+
+
+def test_tracker_domain_wins_over_port():
+ """EN: A tracker hostname on 443 is still 'tracking', not 'safe'.
+ FR: Un hostname tracker sur 443 reste « tracking », pas « safe »."""
+ r = classify("stats.doubleclick.net", 443, "TCP")
+ assert r.category == "tracking"
+ assert r.label == "HTTPS"
+
+
+def test_cdn_domain():
+ r = classify("cdn.cloudflare.com", 443, "TCP")
+ assert r.category == "cdn"
+
+
+def test_https_port_is_safe():
+ r = classify("example.com", 443, "TCP")
+ assert r.category == "safe"
+
+
+def test_dns_port():
+ r = classify(None, 53, "UDP")
+ assert r.category == "dns"
+ assert r.label == "DNS"
+
+
+def test_ssh_is_admin():
+ r = classify(None, 22, "TCP")
+ assert r.category == "admin"
+
+
+def test_unknown_port_falls_back_to_protocol_label():
+ r = classify(None, 9999, "TCP")
+ assert r.category == "unknown"
+ assert r.label == "TCP"
diff --git a/backend/tests/test_db.py b/backend/tests/test_db.py
new file mode 100644
index 0000000..d918f72
--- /dev/null
+++ b/backend/tests/test_db.py
@@ -0,0 +1,60 @@
+"""
+Snitch — SQLite persistence tests.
+
+EN: Uses an isolated SNITCH_DATA_DIR (set in conftest.py) so the real
+ snitch.db is never touched. Covers accumulate→flush→timeline and alert
+ logging.
+FR: Utilise un SNITCH_DATA_DIR isolé (posé dans conftest.py) pour ne jamais
+ toucher la vraie snitch.db. Couvre accumulate→flush→timeline et le
+ journal d'alertes.
+"""
+
+import uuid
+from datetime import datetime, timezone
+
+import storage.db as db
+
+
+def test_accumulate_flush_timeline_roundtrip():
+ # EN: get_timeline filters on a sliding window — use the CURRENT minute.
+ # FR: get_timeline filtre sur une fenêtre glissante — utiliser la minute COURANTE.
+ minute = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M")
+ db.accumulate(minute, "safe", 500)
+ db.accumulate(minute, "safe", 700)
+ db.accumulate(minute, "tracking", 100)
+ db.flush()
+
+ rows = [r for r in db.get_timeline(minutes=99999) if r["minute"] == minute]
+ assert len(rows) == 1
+ assert rows[0]["packets"] == 2 + 1
+ assert rows[0]["bytes"] == 1300
+
+
+def test_log_alert_persists():
+ alert = {
+ "id": str(uuid.uuid4()),
+ "timestamp": "2024-06-01T12:00:00+00:00",
+ "type": "NEW_HOST",
+ "severity": "info",
+ "message": "test",
+ "node_id": "1.2.3.4",
+ "details": {"ip": "1.2.3.4"},
+ }
+ db.log_alert(alert)
+ # EN: Second insert of the same id must be a no-op (INSERT OR IGNORE).
+ # FR: Une seconde insertion du même id doit être un no-op (INSERT OR IGNORE).
+ db.log_alert(alert)
+
+ with db._conn_lock:
+ rows = db.get_conn().execute(
+ "SELECT COUNT(*) FROM alerts_log WHERE id = ?", (alert["id"],)
+ ).fetchone()
+ assert rows[0] == 1
+
+
+def test_cleanup_deletes_old_rows():
+ db.accumulate("2000-01-01T00:00", "safe", 1)
+ db.flush()
+ db.cleanup_old_data(hours=24)
+ rows = [r for r in db.get_timeline(minutes=99999999) if r["minute"] == "2000-01-01T00:00"]
+ assert rows == []
diff --git a/backend/tests/test_oui.py b/backend/tests/test_oui.py
new file mode 100644
index 0000000..acf444d
--- /dev/null
+++ b/backend/tests/test_oui.py
@@ -0,0 +1,31 @@
+"""
+Snitch — OUI lookup tests.
+
+EN: MAC normalization (colons/dashes/case) and the unknown-prefix fallback.
+FR: Normalisation des MAC (deux-points/tirets/casse) et le repli pour préfixe
+ inconnu.
+"""
+
+from scanner.oui import lookup
+
+
+def test_known_apple_prefix():
+ vendor, dev_type = lookup("A4:C1:38:12:34:56")
+ assert vendor == "Apple"
+ assert dev_type == "phone"
+
+
+def test_normalization_dashes_and_lowercase():
+ vendor, _ = lookup("a4-c1-38-aa-bb-cc")
+ assert vendor == "Apple"
+
+
+def test_short_prefix_input():
+ vendor, _ = lookup("B827EB")
+ assert vendor == "Raspberry Pi"
+
+
+def test_unknown_prefix():
+ vendor, dev_type = lookup("ZZ:ZZ:ZZ:00:11:22")
+ assert vendor == "Unknown"
+ assert dev_type == "unknown"
diff --git a/backend/tests/test_security.py b/backend/tests/test_security.py
new file mode 100644
index 0000000..4914460
--- /dev/null
+++ b/backend/tests/test_security.py
@@ -0,0 +1,69 @@
+"""
+Snitch — API security tests.
+
+EN: Verifies the token gate (401 without / wrong token, 200 with header or
+ ?token=) and the Origin allowlist used by both CORS and the WebSocket
+ handshake.
+FR: Vérifie la barrière à jeton (401 sans jeton / mauvais jeton, 200 avec
+ en-tête ou ?token=) et la liste blanche d'Origin utilisée par CORS et le
+ handshake WebSocket.
+"""
+
+import pytest
+from fastapi import Depends, FastAPI
+from fastapi.testclient import TestClient
+
+from api.security import API_TOKEN, origin_allowed, require_token
+
+_test_app = FastAPI()
+
+
+@_test_app.get("/protected", dependencies=[Depends(require_token)])
+def _protected():
+ return {"ok": True}
+
+
+client = TestClient(_test_app)
+
+
+def test_missing_token_is_401():
+ assert client.get("/protected").status_code == 401
+
+
+def test_wrong_token_is_401():
+ r = client.get("/protected", headers={"X-Snitch-Token": "0" * 48})
+ assert r.status_code == 401
+
+
+def test_valid_header_token_passes():
+ r = client.get("/protected", headers={"X-Snitch-Token": API_TOKEN})
+ assert r.status_code == 200
+
+
+def test_valid_query_token_passes():
+ r = client.get(f"/protected?token={API_TOKEN}")
+ assert r.status_code == 200
+
+
[email protected]("origin", [
+ "http://localhost:5173",
+ "http://127.0.0.1:8000",
+ "null", # EN: file:// pages under Electron / FR: pages file:// sous Electron
+])
+def test_allowed_origins(origin):
+ assert origin_allowed(origin)
+
+
[email protected]("origin", [
+ "http://evil.example.com",
+ "http://localhost:9999",
+ "https://attacker.invalid",
+])
+def test_foreign_origins_rejected(origin):
+ assert not origin_allowed(origin)
+
+
+def test_absent_origin_allowed():
+ """EN: No Origin header = non-browser client (curl, Electron main) — allowed.
+ FR: Pas d'en-tête Origin = client non-navigateur (curl, main Electron) — autorisé."""
+ assert origin_allowed(None)
diff --git a/docker-compose.yml b/docker-compose.yml
index a1d50de..6e75419 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -2,10 +2,25 @@
# 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.
+#
+# SECURITY: SNITCH_BIND defaults to 127.0.0.1 — the API exposes your full
+# traffic graph, process names and alerts. Every request needs the API
+# token (printed once in `docker logs`, persisted in data/api_token.txt).
+# Open the UI with: http://localhost:8000/?token=<TOKEN>
+# Only set SNITCH_BIND=0.0.0.0 if you explicitly want LAN access —
+# token auth still applies on every endpoint.
+#
# FR: Lance toute la stack Snitch (backend + frontend compilé) en réseau hôte.
# Le réseau hôte est requis pour que Scapy capture le trafic des vraies interfaces.
# Linux uniquement — Docker Desktop (Mac/Windows) utilise une VM et ne peut pas
# capturer le trafic de l'hôte.
+#
+# SÉCURITÉ : SNITCH_BIND vaut 127.0.0.1 par défaut — l'API expose tout votre
+# graphe de trafic, vos noms de processus et vos alertes. Chaque requête
+# exige le jeton API (affiché une fois dans `docker logs`, persisté dans
+# data/api_token.txt). Ouvrez l'UI avec : http://localhost:8000/?token=<JETON>
+# Ne mettez SNITCH_BIND=0.0.0.0 que pour un accès LAN explicite —
+# le jeton reste exigé sur tous les endpoints.
services:
snitch:
@@ -15,14 +30,24 @@ services:
- 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
+ # EN: Loopback by default — see SECURITY note above.
+ # FR: Loopback par défaut — voir la note SÉCURITÉ ci-dessus.
+ - SNITCH_BIND=${SNITCH_BIND:-127.0.0.1}
+ - SNITCH_PORT=${SNITCH_PORT:-8000}
+ # EN: Uncomment to pin a fixed token instead of an auto-generated one.
+ # FR: Décommenter pour imposer un jeton fixe plutôt qu'un jeton généré.
+ # - SNITCH_TOKEN=change-me
+ # EN: Opt-in ONLY — sends contacted IPs to ip-api.com over HTTP.
+ # Offline GeoLite2 (data/GeoLite2-City.mmdb) needs nothing external.
+ # FR: OPT-IN SEULEMENT — envoie les IP contactées à ip-api.com en HTTP.
+ # GeoLite2 hors ligne (data/GeoLite2-City.mmdb) ne requiert rien d'externe.
+ # - SNITCH_ONLINE_GEO=1
volumes:
# EN: data/GeoLite2-City.mmdb — optional, for offline geolocation
# data/snitch.db — created automatically at runtime
+ # data/api_token.txt — generated API token (0600)
# FR: data/GeoLite2-City.mmdb — optionnel, pour la géolocalisation hors ligne
# data/snitch.db — créé automatiquement au démarrage
+ # data/api_token.txt — jeton API généré (0600)
- ./data:/app/data
restart: unless-stopped
diff --git a/electron/main.js b/electron/main.js
index 2a4cc4c..b8640a5 100644
--- a/electron/main.js
+++ b/electron/main.js
@@ -4,22 +4,35 @@
* 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
+ * 3. generate a per-launch API token (crypto-random) and spawn the
+ * PyInstaller-compiled backend with SNITCH_TOKEN set
* 4. wait for the API to answer, then open the main window
* 5. kill the backend cleanly on quit
*
+ * The token is the heart of the local-API trust model: it is created in
+ * the main process, passed to the backend via its environment, and given
+ * to the renderer ONLY through the ipcMain.handle('snitch:get-token')
+ * bridge — never logged, never embedded in the page.
+ *
* 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
+ * 3. générer un jeton API par lancement (crypto-aléatoire) et lancer le
+ * backend compilé par PyInstaller avec SNITCH_TOKEN défini
* 4. attendre que l'API réponde, puis ouvrir la fenêtre principale
* 5. tuer proprement le backend à la fermeture
+ *
+ * Le jeton est le cœur du modèle de confiance de l'API locale : créé dans
+ * le processus principal, transmis au backend via son environnement, et
+ * donné au renderer UNIQUEMENT via le pont ipcMain.handle('snitch:get-token')
+ * — jamais loggué, jamais embarqué dans la page.
*/
const _electron = require('electron')
-const { app, BrowserWindow, dialog } = _electron.default || _electron
+const { app, BrowserWindow, dialog, ipcMain } = _electron.default || _electron
const { spawn, execSync } = require('child_process')
+const crypto = require('crypto')
const path = require('path')
const http = require('http')
const fs = require('fs')
@@ -32,9 +45,11 @@ const fs = require('fs')
const isDev = !app.isPackaged
const resourcesDir = isDev ? path.join(__dirname, '..') : process.resourcesPath
+const isWindows = process.platform === 'win32'
+const backendName = isWindows ? 'snitch-backend.exe' : 'snitch-backend'
const backendExe = isDev
- ? path.join(resourcesDir, 'dist', 'backend', 'snitch-backend.exe')
- : path.join(resourcesDir, 'snitch-backend.exe')
+ ? path.join(resourcesDir, 'dist', 'backend', backendName)
+ : path.join(resourcesDir, backendName)
const npcapInstaller = path.join(resourcesDir, 'resources', 'npcap-installer.exe')
const frontendDist = isDev
@@ -53,31 +68,57 @@ let splashWindow = null
let backendProc = null
let isQuitting = false
+// ── API token / Jeton API ────────────────────────────────────────────────────
+// EN: 48-hex-char secret generated once per app launch. Passed to the backend
+// via SNITCH_TOKEN and served to the renderer through ipcMain — the web
+// page can only obtain it via the preload bridge.
+// FR: Secret hexadécimal de 48 caractères généré une fois par lancement.
+// Transmis au backend via SNITCH_TOKEN et servi au renderer via ipcMain —
+// la page web ne peut l'obtenir que par le pont preload.
+const API_TOKEN = crypto.randomBytes(24).toString('hex')
+
+// EN: IPC handler — the ONLY way the renderer learns the token.
+// FR: Handler IPC — la SEULE façon pour le renderer d'apprendre le jeton.
+ipcMain.handle('snitch:get-token', () => API_TOKEN)
+
// ── 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.
+ * it (zombies from crashed sessions). Windows uses netstat/taskkill;
+ * POSIX uses lsof + kill.
* FR: Libérer le port du backend — tue tout processus résiduel qui écoute
- * encore dessus (zombies de sessions plantées). Windows uniquement.
+ * encore dessus (zombies de sessions plantées). Windows utilise
+ * netstat/taskkill ; POSIX utilise lsof + kill.
*/
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 {}
+ if (isWindows) {
+ const out = execSync(`netstat -ano`, { encoding: 'utf8', stdio: 'pipe' })
+ const pids = new Set()
+ for (const line of out.split('\n')) {
+ // EN: Match lines whose local address ends with :PORT.
+ // FR: Garder les lignes dont l'adresse locale finit par :PORT.
+ if (!line.includes(`:${port} `) && !line.includes(`:${port}\t`)) continue
+ const m = line.trim().match(/(\d+)\s*$/)
+ if (m && m[1] !== '0') pids.add(m[1])
+ }
+ for (const pid of pids) {
+ try { execSync(`taskkill /PID ${pid} /F`, { stdio: 'pipe' }) } catch {}
+ }
+ if (pids.size > 0) {
+ // EN: Brief wait for the OS to release the port (~1s via ping).
+ // FR: Petite attente pour que l'OS libère le port (~1 s via ping).
+ try { execSync('ping -n 2 127.0.0.1', { stdio: 'pipe' }) } catch {}
+ }
+ } else {
+ // EN: POSIX — lsof reports PIDs listening on the port, kill them.
+ // FR: POSIX — lsof rapporte les PID qui écoutent sur le port, on les tue.
+ try {
+ const out = execSync(`lsof -ti tcp:${port} -sTCP:LISTEN`, { encoding: 'utf8', stdio: 'pipe' })
+ for (const pid of out.split('\n').map(s => s.trim()).filter(Boolean)) {
+ try { process.kill(Number(pid), 'SIGKILL') } catch {}
+ }
+ } catch {}
}
} catch {}
}
@@ -162,17 +203,22 @@ function createMain() {
// ── 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.
+ * EN: Poll the REST API until it answers or we run out of attempts. The
+ * token is sent so we get a real 200 rather than a 401.
+ * FR: Interroger l'API REST jusqu'à réponse ou épuisement des essais. Le jeton
+ * est envoyé pour obtenir un vrai 200 plutôt qu'un 401.
*/
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)
+ const req = http.request(
+ BACKEND_URL + '/graph',
+ { headers: { 'X-Snitch-Token': API_TOKEN } },
+ res => { res.resume(); res.statusCode === 200 ? resolve() : retry() }
+ )
+ req.on('error', retry)
+ req.end()
}
function retry() {
if (++n >= maxAttempts) reject(new Error('Backend timeout'))
@@ -185,24 +231,32 @@ function waitForBackend(maxAttempts = 40) {
/**
* EN: Kill the backend child process and free its port.
* `taskkill /F /T` is more reliable than .kill() on Windows and takes
- * the whole process tree.
+ * the whole process tree; POSIX gets SIGKILL.
* FR: Tuer le processus enfant du backend et libérer son port.
- * `taskkill /F /T` est plus fiable que .kill() sous Windows et prend
- * tout l'arbre de processus.
+ * `taskkill /F /T` est plus fiable que .kill() sous Windows et prend tout
+ * l'arbre de processus ; POSIX reçoit SIGKILL.
*/
function killBackend() {
if (backendProc) {
try {
- execSync(`taskkill /PID ${backendProc.pid} /T /F`, { stdio: 'pipe' })
- } catch {}
+ if (isWindows) {
+ execSync(`taskkill /PID ${backendProc.pid} /T /F`, { stdio: 'pipe' })
+ } else {
+ process.kill(-backendProc.pid, 'SIGKILL') // EN: kill the process group
+ } // FR: tuer le groupe de processus
+ } catch {
+ try { backendProc.kill('SIGKILL') } 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. */
+ /** EN: Spawn the compiled backend with SNITCH_TOKEN in its environment;
+ * show a dialog and quit on failure.
+ * FR: Lancer le backend compilé avec SNITCH_TOKEN dans son environnement ;
+ * afficher une boîte de dialogue et quitter en cas d'échec. */
if (!fs.existsSync(backendExe)) {
dialog.showErrorBox('Snitch', `Backend not found / Backend introuvable :\n${backendExe}`)
app.quit(); return
@@ -213,11 +267,14 @@ function launchBackend() {
killPort(BACKEND_PORT)
const env = Object.assign({}, process.env)
+ // EN: Inject the API token — the backend will require it on every request.
+ // FR: Injecter le jeton API — le backend l'exigera sur chaque requête.
+ env.SNITCH_TOKEN = API_TOKEN
// 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 = spawn(backendExe, [], { detached: !isWindows, 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}`)
@@ -236,7 +293,7 @@ function launchBackend() {
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 (isWindows && !isNpcapInstalled()) {
if (fs.existsSync(npcapInstaller)) {
const choice = dialog.showMessageBoxSync({
type: 'question', title: 'Snitch — Npcap required / Npcap requis',
diff --git a/electron/preload.js b/electron/preload.js
index 7248ffb..fe54da5 100644
--- a/electron/preload.js
+++ b/electron/preload.js
@@ -4,13 +4,20 @@
* EN: Minimal bridge between the sandboxed renderer and the main process.
* `contextIsolation` is enabled, so this is the ONLY surface the web
* page can see — keep it that way.
+ * `getToken` lets the renderer authenticate to the backend API without
+ * the token ever appearing in the page, the DOM, or logs.
* FR: Pont minimal entre le renderer en sandbox et le processus principal.
* `contextIsolation` est activé : c'est la SEULE surface visible par la
* page web — gardons-la ainsi.
+ * `getToken` permet au renderer de s'authentifier auprès de l'API backend
+ * sans que le jeton apparaisse jamais dans la page, le DOM ou les logs.
*/
-const { contextBridge } = require('electron')
+const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('snitch', {
version: process.env.npm_package_version || '1.0.0',
+ // EN: Async — resolves to the per-launch API token held by the main process.
+ // FR: Asynchrone — résout vers le jeton API par lancement détenu par le processus principal.
+ getToken: () => ipcRenderer.invoke('snitch:get-token'),
})
diff --git a/electron/splash.html b/electron/splash.html
index 0f056e9..7a4d6ab 100644
--- a/electron/splash.html
+++ b/electron/splash.html
@@ -3,10 +3,10 @@
Snitch — splash screen.
EN: Frameless startup screen shown while the backend boots. Pure SVG + CSS,
- no external requests (the @import is progressive enhancement only).
+ ZERO external requests — works fully offline (system font fallbacks).
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).
+ SVG + CSS uniquement, AUCUNE requête externe — fonctionne 100 % hors
+ ligne (polices système de repli).
-->
<html lang="en">
<head>
@@ -60,7 +60,6 @@
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>
@@ -131,13 +130,13 @@
<!-- 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>
+ font-family="'Courier New', ui-monospace, 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"
+ font-family="'Segoe UI', 'Helvetica Neue', Arial, 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>
+ font-family="'Segoe UI', 'Helvetica Neue', Arial, 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>
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
new file mode 100644
index 0000000..9490be1
--- /dev/null
+++ b/frontend/package-lock.json
@@ -0,0 +1,2884 @@
+{
+ "name": "snitch-frontend",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "snitch-frontend",
+ "version": "1.0.0",
+ "license": "AGPL-3.0-or-later",
+ "dependencies": {
+ "d3": "^7.9.0",
+ "lucide-react": "^0.462.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",
+ "vitest": "^2.1.8"
+ }
+ },
+ "node_modules/@babel/code-frame": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "js-tokens": "^4.0.0",
+ "picocolors": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/compat-data": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/core": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
+ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-compilation-targets": "^7.29.7",
+ "@babel/helper-module-transforms": "^7.29.7",
+ "@babel/helpers": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7",
+ "@jridgewell/remapping": "^2.3.5",
+ "convert-source-map": "^2.0.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.2",
+ "json5": "^2.2.3",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/babel"
+ }
+ },
+ "node_modules/@babel/generator": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz",
+ "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.8",
+ "@babel/types": "^7.29.8",
+ "@jridgewell/gen-mapping": "^0.3.12",
+ "@jridgewell/trace-mapping": "^0.3.28",
+ "jsesc": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-compilation-targets": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
+ "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/compat-data": "^7.29.7",
+ "@babel/helper-validator-option": "^7.29.7",
+ "browserslist": "^4.24.0",
+ "lru-cache": "^5.1.1",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-globals": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-imports": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-transforms": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
+ "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-module-imports": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "@babel/traverse": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0"
+ }
+ },
+ "node_modules/@babel/helper-plugin-utils": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz",
+ "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-option": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helpers": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
+ "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.9",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
+ "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.8"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-self": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz",
+ "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-source": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz",
+ "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/template": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/traverse": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz",
+ "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.8",
+ "@babel/helper-globals": "^7.29.7",
+ "@babel/parser": "^7.29.8",
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.8",
+ "debug": "^4.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
+ "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/remapping": {
+ "version": "2.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.0-beta.27",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
+ "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.6.tgz",
+ "integrity": "sha512-G6xF9OVRWsbHadMfoPNUDwW/Jt70QYG+ZDUvtYCFxjf3SPhqVAO0u9ShXZ7Cf5silVoRWyN4bDjCEKnJkXkw0w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.6.tgz",
+ "integrity": "sha512-Us/kTH5e2anr1CQvO8MEq4eeCVcIXI3Ag7OFxDI30n2OW7Q7xWuxo8ItbYq28PG2Sm1NWmZzG9+SqVEaj25SFA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.6.tgz",
+ "integrity": "sha512-fwaSNrSHp9PJuEh4bKtd0mYC+G3FeVDjSTmsSiSlIYu7TFCpxrfB6lk7Ao8cIbswFyklPB1ZDUV8LkLBM15VWw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.6.tgz",
+ "integrity": "sha512-QR2tx26gCeGh4eAGnUasfnJuRc+d7Vc0Jo1/fYtKGuiKqCuhbVpbNEvqgYGBwGDZGyS04jj+zdHi9W8uvb1Sdw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.6.tgz",
+ "integrity": "sha512-7E1wRJEW8r7WlqmCy58ugndWHrzoEV/pRt2x0D9el7Inra62+Cw00lYW9XhW6iUCtFjhNw49McsSCIzJ/nG8uw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.6.tgz",
+ "integrity": "sha512-13KJeF+vDswMzEHmMIouCVcEQdov3CzAA3ZhM8QFmBJV/FZ/VMZI49UHDvPXTK+wokk86kYPmQ9Qb3xGGJbZoQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.6.tgz",
+ "integrity": "sha512-hV+W1r8HM84PER4If94QuzrrD0DNk4CxobNhVUiz9ZiiWHDzJss4Jra2AYGH1a7GOTzjS1sIyZ35yYEhw/aq+g==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.6.tgz",
+ "integrity": "sha512-5dWs/GENZufRph8PEfl0TrNH/R3DHJA+VxF/dqlfV2oUZfxRtN3qmFXg2DZj8DYM8d+Vd3dgZtuVmoBE/nb2YQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.6.tgz",
+ "integrity": "sha512-inQYLPVIUvYk+s7zpxQldqwrajUNs+t4TJjPGzsdPTvsT8gsQXVcW/sQFolHZ3YSWVk0nMMwU7TtRi0Ow+QMuw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.6.tgz",
+ "integrity": "sha512-sH+0MV1HmDC1q7+bQnlN9ywKBmHqkA2EdD/hHYrrz654ybc+vNC1FRNyzuYKicMQVtZZ4X2jz0osJYmsOtnj4g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.6.tgz",
+ "integrity": "sha512-mCECvRr6HGekdBc6dvHzUWubqEti4JyOqlNePrOzl4Wimk26iW5Zy9rld2mQbC9id1NYjfF8nHLFq5fr3CuOKQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.6.tgz",
+ "integrity": "sha512-bb9rdoCPwM4DEsbOP3CJgFnvhSJ3XKCUYyUhxnlSs/XGT0DknpOYgLCPbK8VUzwl+cZGzFQm0KbBYRaSGZC2YQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.6.tgz",
+ "integrity": "sha512-aIJRoGCHev45JSu7JMzVrMzu1NX3nQrXx1Vb/6y4AblxW7JpCMpk4e8C6lHzvSElxi3UEcMdFJldsuWQjV1ddA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.6.tgz",
+ "integrity": "sha512-LvjnulezHjiaM5Ga9MPCDLTVddjvcrJhZc6vEz9fxeFRGPJsPAX9HuTuPTUQ3l8d+nYpZB/xWzUpuKJlLQm3VQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.6.tgz",
+ "integrity": "sha512-YmhSBeYZwJ937s8tKpYAhms48N+tj7e+oFkbkVVxfMRdAiynK2AxqRapJXB4utyXxc/iYTkMfPRQ+7ZP0IO78w==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.6.tgz",
+ "integrity": "sha512-9+YukhzqTvJvzfDXJJzkURK9TDY01nofNH3pyHGuucGC4xPvBVtIfCAqJjkjnmBEGJYNXB8sBc2EDt7xDgGenw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.6.tgz",
+ "integrity": "sha512-9G5AtEkpN/A89BILHHEL9aYRYTuFjwa8PUQqoEg8SDrwOZBKpwYqNlQCBNI5QPwGrf7qFlb6LNFilo8FCSA3Wg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.6.tgz",
+ "integrity": "sha512-Ezx2E5D6Siz805j41x91JiGbzuCm8i2U98U37SQ7ytY737+wsJq+P9nPL6UmqDww491zO7MTivYOTrtmTTeCSw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.6.tgz",
+ "integrity": "sha512-8EZ1Q3PB7yUjvR4MbFAnCBF1wF0XRe5QQqbtlJXP7ZX5C8iYlSQJugUhj9oS0gbUP4jp9qGhaIgFnV9Nvod86Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.6.tgz",
+ "integrity": "sha512-3JI27TALItfZ/qaxXKdbRXfV6WepUoUa3IN07FE+1xxoRdl3JIyrp5PiDF0vOHsPgEiOFkF8s3B3BRymQkdwGA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.6.tgz",
+ "integrity": "sha512-BNOGeNFNRZDT7Hfc7b9JbTZFXkpAXeXl/CZWtxdd5CNfBaor/0RkJjg+q+E2gwVIvGqqp/NclThKFGrhuScVhw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.6.tgz",
+ "integrity": "sha512-D3eEyLSIim5WF5fHbwnx+ryk0delN7fJyBrDTO3wVCCNBZ/cA8aCGwLS3SiuK+vRI4E7dqikAlStGuR20dBMuw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.6.tgz",
+ "integrity": "sha512-xwbs9g8zLbHzj1poG1uh27xtubsu27Gk2nuN6kvvGDybjiTfwMksQAnF+phlvI5oeXkJWWDc6kg1t3XpgUYvrg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.6.tgz",
+ "integrity": "sha512-Tr6rhRNnFthvXr45zWVZQ5P8jZ5UwZnXNc7Qnu80cP/VVYtSioOPmvv7wP6UMgRfkBCJr2Pm60ua0YBDSJjgnw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.6.tgz",
+ "integrity": "sha512-0RAxO1pS/6lY1mSoD2Apm+6aPyfUlm+OWKgncIdj/eVN9I+pDY3lKgD7xsUNFei1u7MZQETGOo6m8POXMDp53A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@types/babel__core": {
+ "version": "7.20.5",
+ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
+ "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.20.7",
+ "@babel/types": "^7.20.7",
+ "@types/babel__generator": "*",
+ "@types/babel__template": "*",
+ "@types/babel__traverse": "*"
+ }
+ },
+ "node_modules/@types/babel__generator": {
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",
+ "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.0.0"
+ }
+ },
+ "node_modules/@types/babel__template": {
+ "version": "7.4.4",
+ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
+ "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.1.0",
+ "@babel/types": "^7.0.0"
+ }
+ },
+ "node_modules/@types/babel__traverse": {
+ "version": "7.28.0",
+ "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
+ "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.28.2"
+ }
+ },
+ "node_modules/@types/d3": {
+ "version": "7.4.3",
+ "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",
+ "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-array": "*",
+ "@types/d3-axis": "*",
+ "@types/d3-brush": "*",
+ "@types/d3-chord": "*",
+ "@types/d3-color": "*",
+ "@types/d3-contour": "*",
+ "@types/d3-delaunay": "*",
+ "@types/d3-dispatch": "*",
+ "@types/d3-drag": "*",
+ "@types/d3-dsv": "*",
+ "@types/d3-ease": "*",
+ "@types/d3-fetch": "*",
+ "@types/d3-force": "*",
+ "@types/d3-format": "*",
+ "@types/d3-geo": "*",
+ "@types/d3-hierarchy": "*",
+ "@types/d3-interpolate": "*",
+ "@types/d3-path": "*",
+ "@types/d3-polygon": "*",
+ "@types/d3-quadtree": "*",
+ "@types/d3-random": "*",
+ "@types/d3-scale": "*",
+ "@types/d3-scale-chromatic": "*",
+ "@types/d3-selection": "*",
+ "@types/d3-shape": "*",
+ "@types/d3-time": "*",
+ "@types/d3-time-format": "*",
+ "@types/d3-timer": "*",
+ "@types/d3-transition": "*",
+ "@types/d3-zoom": "*"
+ }
+ },
+ "node_modules/@types/d3-array": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-axis": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",
+ "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-brush": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",
+ "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-chord": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",
+ "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-color": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-contour": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",
+ "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-array": "*",
+ "@types/geojson": "*"
+ }
+ },
+ "node_modules/@types/d3-delaunay": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
+ "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-dispatch": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz",
+ "integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-drag": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-dsv": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",
+ "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-ease": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-fetch": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",
+ "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-dsv": "*"
+ }
+ },
+ "node_modules/@types/d3-force": {
+ "version": "3.0.10",
+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",
+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-format": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz",
+ "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-geo": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.1.tgz",
+ "integrity": "sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*"
+ }
+ },
+ "node_modules/@types/d3-hierarchy": {
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",
+ "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-interpolate": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-color": "*"
+ }
+ },
+ "node_modules/@types/d3-path": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-polygon": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",
+ "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-quadtree": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",
+ "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-random": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.4.tgz",
+ "integrity": "sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-scale": {
+ "version": "4.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-time": "*"
+ }
+ },
+ "node_modules/@types/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-selection": {
+ "version": "3.0.12",
+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.12.tgz",
+ "integrity": "sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-shape": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz",
+ "integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-path": "*"
+ }
+ },
+ "node_modules/@types/d3-time": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-time-format": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz",
+ "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-timer": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-transition": {
+ "version": "3.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-zoom": {
+ "version": "3.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.9.tgz",
+ "integrity": "sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-interpolate": "*",
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/geojson": {
+ "version": "7946.0.16",
+ "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
+ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitejs/plugin-react": {
+ "version": "4.7.0",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
+ "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/core": "^7.28.0",
+ "@babel/plugin-transform-react-jsx-self": "^7.27.1",
+ "@babel/plugin-transform-react-jsx-source": "^7.27.1",
+ "@rolldown/pluginutils": "1.0.0-beta.27",
+ "@types/babel__core": "^7.20.5",
+ "react-refresh": "^0.17.0"
+ },
+ "engines": {
+ "node": "^14.18.0 || >=16.0.0"
+ },
+ "peerDependencies": {
+ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
+ }
+ },
+ "node_modules/@vitest/expect": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
+ "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "2.1.9",
+ "@vitest/utils": "2.1.9",
+ "chai": "^5.1.2",
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz",
+ "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "2.1.9",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.12"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^5.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
+ "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",
+ "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "2.1.9",
+ "pathe": "^1.1.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
+ "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "2.1.9",
+ "magic-string": "^0.30.12",
+ "pathe": "^1.1.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",
+ "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyspy": "^3.0.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",
+ "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "2.1.9",
+ "loupe": "^3.1.2",
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/baseline-browser-mapping": {
+ "version": "2.11.26",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.26.tgz",
+ "integrity": "sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "baseline-browser-mapping": "dist/cli.cjs"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/browserslist": {
+ "version": "4.29.3",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz",
+ "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "baseline-browser-mapping": "^2.11.26",
+ "caniuse-lite": "^1.0.30001813",
+ "electron-to-chromium": "^1.5.439",
+ "node-releases": "^2.0.57",
+ "update-browserslist-db": "^1.3.3"
+ },
+ "bin": {
+ "browserslist": "cli.js"
+ },
+ "engines": {
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+ }
+ },
+ "node_modules/cac": {
+ "version": "6.7.14",
+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001814",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
+ "integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "CC-BY-4.0"
+ },
+ "node_modules/chai": {
+ "version": "5.3.3",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
+ "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "assertion-error": "^2.0.1",
+ "check-error": "^2.1.1",
+ "deep-eql": "^5.0.1",
+ "loupe": "^3.1.0",
+ "pathval": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/check-error": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
+ "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 16"
+ }
+ },
+ "node_modules/commander": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/d3": {
+ "version": "7.9.0",
+ "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",
+ "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "3",
+ "d3-axis": "3",
+ "d3-brush": "3",
+ "d3-chord": "3",
+ "d3-color": "3",
+ "d3-contour": "4",
+ "d3-delaunay": "6",
+ "d3-dispatch": "3",
+ "d3-drag": "3",
+ "d3-dsv": "3",
+ "d3-ease": "3",
+ "d3-fetch": "3",
+ "d3-force": "3",
+ "d3-format": "3",
+ "d3-geo": "3",
+ "d3-hierarchy": "3",
+ "d3-interpolate": "3",
+ "d3-path": "3",
+ "d3-polygon": "3",
+ "d3-quadtree": "3",
+ "d3-random": "3",
+ "d3-scale": "4",
+ "d3-scale-chromatic": "3",
+ "d3-selection": "3",
+ "d3-shape": "3",
+ "d3-time": "3",
+ "d3-time-format": "4",
+ "d3-timer": "3",
+ "d3-transition": "3",
+ "d3-zoom": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-array": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
+ "license": "ISC",
+ "dependencies": {
+ "internmap": "1 - 2"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-axis": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",
+ "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-brush": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",
+ "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "3",
+ "d3-transition": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-chord": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",
+ "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-color": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-contour": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",
+ "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "^3.2.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-delaunay": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
+ "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",
+ "license": "ISC",
+ "dependencies": {
+ "delaunator": "5"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dispatch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-drag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-selection": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dsv": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",
+ "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",
+ "license": "ISC",
+ "dependencies": {
+ "commander": "7",
+ "iconv-lite": "0.6",
+ "rw": "1"
+ },
+ "bin": {
+ "csv2json": "bin/dsv2json.js",
+ "csv2tsv": "bin/dsv2dsv.js",
+ "dsv2dsv": "bin/dsv2dsv.js",
+ "dsv2json": "bin/dsv2json.js",
+ "json2csv": "bin/json2dsv.js",
+ "json2dsv": "bin/json2dsv.js",
+ "json2tsv": "bin/json2dsv.js",
+ "tsv2csv": "bin/dsv2dsv.js",
+ "tsv2json": "bin/dsv2json.js"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-ease": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-fetch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",
+ "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dsv": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-force": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",
+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-quadtree": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-format": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",
+ "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-geo": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",
+ "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.5.0 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-hierarchy": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",
+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-path": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-polygon": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",
+ "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-quadtree": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",
+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-random": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",
+ "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-scale": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.10.0 - 3",
+ "d3-format": "1 - 3",
+ "d3-interpolate": "1.2.0 - 3",
+ "d3-time": "2.1.1 - 3",
+ "d3-time-format": "2 - 4"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-interpolate": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-selection": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-shape": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time-format": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-time": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-timer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-transition": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-dispatch": "1 - 3",
+ "d3-ease": "1 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "d3-selection": "2 - 3"
+ }
+ },
+ "node_modules/d3-zoom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "2 - 3",
+ "d3-transition": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/deep-eql": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
+ "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/delaunator": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz",
+ "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==",
+ "license": "ISC",
+ "dependencies": {
+ "robust-predicates": "^3.0.2"
+ }
+ },
+ "node_modules/electron-to-chromium": {
+ "version": "1.5.443",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.443.tgz",
+ "integrity": "sha512-TDJG36L9A3CWWwZ97HKaE+Iz1sW80pNp6sAU0owzCIV3Zc9eVyRqZK8Vz6NKuMIU8WjP0pIkoqCa0VRf/yFD0Q==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/es-module-lexer": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
+ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
+ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.21.5",
+ "@esbuild/android-arm": "0.21.5",
+ "@esbuild/android-arm64": "0.21.5",
+ "@esbuild/android-x64": "0.21.5",
+ "@esbuild/darwin-arm64": "0.21.5",
+ "@esbuild/darwin-x64": "0.21.5",
+ "@esbuild/freebsd-arm64": "0.21.5",
+ "@esbuild/freebsd-x64": "0.21.5",
+ "@esbuild/linux-arm": "0.21.5",
+ "@esbuild/linux-arm64": "0.21.5",
+ "@esbuild/linux-ia32": "0.21.5",
+ "@esbuild/linux-loong64": "0.21.5",
+ "@esbuild/linux-mips64el": "0.21.5",
+ "@esbuild/linux-ppc64": "0.21.5",
+ "@esbuild/linux-riscv64": "0.21.5",
+ "@esbuild/linux-s390x": "0.21.5",
+ "@esbuild/linux-x64": "0.21.5",
+ "@esbuild/netbsd-x64": "0.21.5",
+ "@esbuild/openbsd-x64": "0.21.5",
+ "@esbuild/sunos-x64": "0.21.5",
+ "@esbuild/win32-arm64": "0.21.5",
+ "@esbuild/win32-ia32": "0.21.5",
+ "@esbuild/win32-x64": "0.21.5"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/gensync": {
+ "version": "1.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/internmap": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+ "license": "MIT"
+ },
+ "node_modules/jsesc": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "jsesc": "bin/jsesc"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/json5": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "json5": "lib/cli.js"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/loose-envify": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "js-tokens": "^3.0.0 || ^4.0.0"
+ },
+ "bin": {
+ "loose-envify": "cli.js"
+ }
+ },
+ "node_modules/loupe": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
+ "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "yallist": "^3.0.2"
+ }
+ },
+ "node_modules/lucide-react": {
+ "version": "0.462.0",
+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.462.0.tgz",
+ "integrity": "sha512-NTL7EbAao9IFtuSivSZgrAh4fZd09Lr+6MTkqIxuHaH2nnYiYIzXPo06cOxHg9wKLdj6LL8TByG4qpePqwgx/g==",
+ "license": "ISC",
+ "peerDependencies": {
+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.19",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",
+ "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/node-releases": {
+ "version": "2.0.57",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz",
+ "integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/pathe": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
+ "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pathval": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
+ "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.16"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/postcss": {
+ "version": "8.5.28",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.18",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/react": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
+ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "scheduler": "^0.23.2"
+ },
+ "peerDependencies": {
+ "react": "^18.3.1"
+ }
+ },
+ "node_modules/react-refresh": {
+ "version": "0.17.0",
+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
+ "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/robust-predicates": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
+ "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
+ "license": "Unlicense"
+ },
+ "node_modules/rollup": {
+ "version": "4.63.6",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.6.tgz",
+ "integrity": "sha512-w4+GKyTBqshj84F1GF3s2zxAPFZPEmNkCbQtqilsYS7GsksmX6VoV7UggfZg8sUHCCOkBe7UtQp6fZwbH311FQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.9"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",
+ "@rollup/rollup-android-arm-eabi": "4.63.6",
+ "@rollup/rollup-android-arm64": "4.63.6",
+ "@rollup/rollup-darwin-arm64": "4.63.6",
+ "@rollup/rollup-darwin-x64": "4.63.6",
+ "@rollup/rollup-freebsd-arm64": "4.63.6",
+ "@rollup/rollup-freebsd-x64": "4.63.6",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.63.6",
+ "@rollup/rollup-linux-arm-musleabihf": "4.63.6",
+ "@rollup/rollup-linux-arm64-gnu": "4.63.6",
+ "@rollup/rollup-linux-arm64-musl": "4.63.6",
+ "@rollup/rollup-linux-loong64-gnu": "4.63.6",
+ "@rollup/rollup-linux-loong64-musl": "4.63.6",
+ "@rollup/rollup-linux-ppc64-gnu": "4.63.6",
+ "@rollup/rollup-linux-ppc64-musl": "4.63.6",
+ "@rollup/rollup-linux-riscv64-gnu": "4.63.6",
+ "@rollup/rollup-linux-riscv64-musl": "4.63.6",
+ "@rollup/rollup-linux-s390x-gnu": "4.63.6",
+ "@rollup/rollup-linux-x64-gnu": "4.63.6",
+ "@rollup/rollup-linux-x64-musl": "4.63.6",
+ "@rollup/rollup-openbsd-x64": "4.63.6",
+ "@rollup/rollup-openharmony-arm64": "4.63.6",
+ "@rollup/rollup-win32-arm64-msvc": "4.63.6",
+ "@rollup/rollup-win32-ia32-msvc": "4.63.6",
+ "@rollup/rollup-win32-x64-gnu": "4.63.6",
+ "@rollup/rollup-win32-x64-msvc": "4.63.6",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/rw": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
+ "node_modules/scheduler": {
+ "version": "0.23.2",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
+ "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ }
+ },
+ "node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "3.10.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
+ "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
+ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinypool": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
+ "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
+ "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tinyspy": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",
+ "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/topojson-client": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/topojson-client/-/topojson-client-3.1.0.tgz",
+ "integrity": "sha512-605uxS6bcYxGXw9qi62XyrV6Q3xwbndjachmNxu8HWTtVPxZfEJN9fd/SZS1Q54Sn2y0TMyMxFj/cJINqGHrKw==",
+ "license": "ISC",
+ "dependencies": {
+ "commander": "2"
+ },
+ "bin": {
+ "topo2geo": "bin/topo2geo",
+ "topomerge": "bin/topomerge",
+ "topoquantize": "bin/topoquantize"
+ }
+ },
+ "node_modules/topojson-client/node_modules/commander": {
+ "version": "2.20.3",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
+ "license": "MIT"
+ },
+ "node_modules/update-browserslist-db": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz",
+ "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "escalade": "^3.2.0",
+ "picocolors": "^1.1.1"
+ },
+ "bin": {
+ "update-browserslist-db": "cli.js"
+ },
+ "peerDependencies": {
+ "browserslist": ">= 4.21.0"
+ }
+ },
+ "node_modules/vite": {
+ "version": "5.4.21",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
+ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.21.3",
+ "postcss": "^8.4.43",
+ "rollup": "^4.20.0"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^18.0.0 || >=20.0.0",
+ "less": "*",
+ "lightningcss": "^1.21.0",
+ "sass": "*",
+ "sass-embedded": "*",
+ "stylus": "*",
+ "sugarss": "*",
+ "terser": "^5.4.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vite-node": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz",
+ "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cac": "^6.7.14",
+ "debug": "^4.3.7",
+ "es-module-lexer": "^1.5.4",
+ "pathe": "^1.1.2",
+ "vite": "^5.0.0"
+ },
+ "bin": {
+ "vite-node": "vite-node.mjs"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/vitest": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz",
+ "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "2.1.9",
+ "@vitest/mocker": "2.1.9",
+ "@vitest/pretty-format": "^2.1.9",
+ "@vitest/runner": "2.1.9",
+ "@vitest/snapshot": "2.1.9",
+ "@vitest/spy": "2.1.9",
+ "@vitest/utils": "2.1.9",
+ "chai": "^5.1.2",
+ "debug": "^4.3.7",
+ "expect-type": "^1.1.0",
+ "magic-string": "^0.30.12",
+ "pathe": "^1.1.2",
+ "std-env": "^3.8.0",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^0.3.1",
+ "tinypool": "^1.0.1",
+ "tinyrainbow": "^1.2.0",
+ "vite": "^5.0.0",
+ "vite-node": "2.1.9",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@types/node": "^18.0.0 || >=20.0.0",
+ "@vitest/browser": "2.1.9",
+ "@vitest/ui": "2.1.9",
+ "happy-dom": "*",
+ "jsdom": "*"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/yallist": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
+ "dev": true,
+ "license": "ISC"
+ }
+ }
+}
diff --git a/frontend/package.json b/frontend/package.json
index 5fcd01f..f67b6e8 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -2,15 +2,17 @@
"name": "snitch-frontend",
"version": "1.0.0",
"private": true,
+ "license": "AGPL-3.0-or-later",
"description": "Snitch UI — React + D3.js / Interface React + D3.js",
"scripts": {
"dev": "vite",
"build": "vite build",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "test": "vitest run"
},
"dependencies": {
"d3": "^7.9.0",
- "lucide-react": "^1.9.0",
+ "lucide-react": "^0.462.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"topojson-client": "^3.1.0"
@@ -18,6 +20,7 @@
"devDependencies": {
"@types/d3": "^7.4.3",
"@vitejs/plugin-react": "^4.3.1",
- "vite": "^5.4.8"
+ "vite": "^5.4.8",
+ "vitest": "^2.1.8"
}
}
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 2711266..3d3e053 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -12,13 +12,14 @@
* 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 { useState, useMemo } from 'react'
import { Hexagon, Globe, Wifi, Smartphone, Monitor, Cpu, ShieldCheck, Radio, Zap, HelpCircle, AlertTriangle, Square, Play, Filter, Mic, Camera, Download, ShieldOff } from 'lucide-react'
import 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 Dropdown from './components/Dropdown'
import { useWebSocket } from './hooks/useWebSocket'
import { computePrivacyScore } from './scoring/privacy'
import { WS_URL } from './api'
@@ -175,21 +176,12 @@ function toCSV(rows, cols) {
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. */
+/** EN: Dropdown offering graph/alerts export in JSON and CSV — built on the
+ * shared `Dropdown` component (outside-click handling included).
+ * FR: Menu déroulant d'export du graphe/des alertes en JSON et CSV — basé
+ * sur le composant `Dropdown` partagé (clic extérieur inclus). */
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(':', '-')
@@ -200,25 +192,21 @@ function ExportButton({ nodes, edges, lanDevices, alerts }) {
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 = [
@@ -229,40 +217,34 @@ function ExportButton({ nodes, edges, lanDevices, alerts }) {
]
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,
+ <Dropdown
+ panelStyle={{ overflow: 'hidden' }}
+ button={
+ <button style={{
+ display: 'flex', alignItems: 'center', gap: 6,
background: '#1e293b', border: '1px solid #334155',
- borderRadius: 10, overflow: 'hidden',
- boxShadow: '0 8px 24px rgba(0,0,0,0.4)', minWidth: 180,
+ borderRadius: 20, padding: '5px 14px',
+ cursor: 'pointer', color: '#64748b',
+ fontSize: 11, fontWeight: 600, transition: 'all 0.15s',
}}>
- {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>
+ <Download size={11} />
+ {t('export_btn')}
+ </button>
+ }
+ >
+ {(close) => items.map(({ label, action }) => (
+ <button key={label} onClick={() => { action(); close() }} 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>
+ ))}
+ </Dropdown>
)
}
@@ -302,16 +284,6 @@ function MediaBadge({ media }) {
* 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.
@@ -333,76 +305,70 @@ function ProcessFilter({ excluded, onChange, nodes }) {
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)',
+ <Dropdown
+ panelStyle={{ padding: 12, minWidth: 220, maxHeight: 300, overflowY: 'auto' }}
+ button={
+ <button 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',
}}>
- <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>
+ {t('process_filter')}
+ {active && (
+ <span style={{
+ background: '#ef4444', color: '#fff',
+ borderRadius: 10, padding: '0 6px', fontSize: 10,
+ }}>{excluded.length}</span>
)}
+ </button>
+ }
+ >
+ <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 8 }}>
+ {t('process_filter_hint')}
+ </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>
- )
- })}
+ {allProcesses.length === 0 && (
+ <div style={{ fontSize: 11, color: '#475569' }}>{t('process_none')}</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',
+ {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',
}}>
- {t('process_clear')}
- </button>
- )}
- </div>
+ {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>
+ </Dropdown>
)
}
@@ -410,18 +376,8 @@ function ProcessFilter({ excluded, onChange, nodes }) {
* 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()
@@ -440,87 +396,81 @@ function PortFilter({ ports, onUpdate }) {
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)',
+ <Dropdown
+ panelStyle={{ padding: 12, minWidth: 220 }}
+ button={
+ <button 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',
}}>
- <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>}
-
+ <Filter size={11} />
+ {t('port_filter')}
{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>
+ <span style={{
+ background: '#3b82f6', color: '#fff',
+ borderRadius: 10, padding: '0 6px', fontSize: 10,
+ }}>{ports.length}</span>
)}
- </div>
+ </button>
+ }
+ >
+ <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>
+ </Dropdown>
)
}
@@ -536,18 +486,8 @@ function isValidIp(ip) {
* 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()
@@ -566,87 +506,81 @@ function IPWhitelist({ ips, onUpdate }) {
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)',
+ <Dropdown
+ panelStyle={{ padding: 12, minWidth: 220 }}
+ button={
+ <button 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',
}}>
- <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>}
-
+ <ShieldOff size={11} />
+ {t('ip_whitelist')}
{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>
+ <span style={{
+ background: '#22c55e', color: '#052e16',
+ borderRadius: 10, padding: '0 6px', fontSize: 10,
+ }}>{ips.length}</span>
)}
- </div>
+ </button>
+ }
+ >
+ <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>
+ </Dropdown>
)
}
@@ -771,14 +705,14 @@ function StatusBadge({ status, lanCount }) {
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: Wifi, color: '#f97316', label: t('legend_router') },
+ { Icon: Smartphone, color: '#a855f7', label: t('legend_phone') },
+ { Icon: Monitor, color: '#06b6d4', label: t('legend_pc') },
+ { Icon: Cpu, color: '#84cc16', label: t('legend_iot') },
+ { Icon: ShieldCheck, color: '#22c55e', label: t('legend_https') },
+ { Icon: Radio, color: '#f59e0b', label: t('legend_tracking') },
+ { Icon: Zap, color: '#6366f1', label: t('legend_cdn') },
+ { Icon: Globe, color: '#38bdf8', label: t('legend_dns') },
{ Icon: AlertTriangle, color: '#ef4444', label: t('legend_alert') },
{ Icon: HelpCircle, color: '#94a3b8', label: t('legend_unknown') },
]
diff --git a/frontend/src/api.js b/frontend/src/api.js
index 9e05734..460e788 100644
--- a/frontend/src/api.js
+++ b/frontend/src/api.js
@@ -1,13 +1,28 @@
/**
- * Snitch — API endpoint helpers.
+ * Snitch — API endpoint helpers + auth token plumbing.
*
* 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.
+ * proxy — all backend calls use the absolute loopback URL.
+ * In dev/browser mode we rely on the Vite proxy and relative URLs.
+ *
+ * AUTH: every request needs the API token. Resolution order:
+ * 1. window.snitch.getToken() — Electron preload bridge (IPC)
+ * 2. ?token= URL param — Docker/browser first open
+ * 3. sessionStorage — survives reloads in the same tab
+ * 4. window.prompt() — last-resort manual entry
+ * The resolved promise is cached — only ONE prompt can ever appear.
+ *
* 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.
+ * dev-server — tous les appels backend utilisent l'URL loopback absolue.
+ * En mode dev/navigateur on s'appuie sur le proxy Vite avec des URL
+ * relatives.
+ *
+ * AUTH : chaque requête exige le jeton API. Ordre de résolution :
+ * 1. window.snitch.getToken() — pont preload Electron (IPC)
+ * 2. paramètre ?token= d'URL — première ouverture Docker/navigateur
+ * 3. sessionStorage — survit aux rechargements de l'onglet
+ * 4. window.prompt() — saisie manuelle en dernier recours
+ * La promesse résolue est mise en cache — une SEULE invite peut apparaître.
*/
const isElectron = window.location.protocol === 'file:'
@@ -15,3 +30,56 @@ 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`
+
+let _tokenPromise = null
+
+/**
+ * EN: Resolve the API token once — see module docstring for the order.
+ * FR: Résoudre le jeton API une fois — voir le docstring du module pour
+ * l'ordre.
+ */
+export function getToken() {
+ if (_tokenPromise) return _tokenPromise
+ _tokenPromise = (async () => {
+ // EN: Electron — the token never touches the URL or the DOM.
+ // FR: Electron — le jeton ne touche jamais l'URL ni le DOM.
+ if (window.snitch?.getToken) {
+ return await window.snitch.getToken()
+ }
+ const fromUrl = new URLSearchParams(window.location.search).get('token')
+ if (fromUrl) {
+ sessionStorage.setItem('snitch_token', fromUrl)
+ return fromUrl
+ }
+ const stored = sessionStorage.getItem('snitch_token')
+ if (stored) return stored
+ const manual = window.prompt('Snitch API token / Jeton API Snitch :')
+ if (manual) {
+ const t = manual.trim()
+ sessionStorage.setItem('snitch_token', t)
+ return t
+ }
+ return null
+ })()
+ return _tokenPromise
+}
+
+/**
+ * EN: Headers for an authenticated fetch — merges X-Snitch-Token into `extra`.
+ * FR: En-têtes pour un fetch authentifié — fusionne X-Snitch-Token dans `extra`.
+ */
+export async function authHeaders(extra = {}) {
+ const token = await getToken()
+ return token ? { ...extra, 'X-Snitch-Token': token } : extra
+}
+
+/**
+ * EN: WebSocket URL with the token as a query param — the browser WS API
+ * can't set headers, so ?token= is the transport.
+ * FR: URL WebSocket avec le jeton en paramètre de requête — l'API WS du
+ * navigateur ne peut pas poser d'en-têtes, donc ?token= fait le transport.
+ */
+export async function wsUrlWithToken(base) {
+ const token = await getToken()
+ return token ? `${base}?token=${encodeURIComponent(token)}` : base
+}
diff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsx
index 0b6970c..fbef712 100644
--- a/frontend/src/components/AlertPanel.jsx
+++ b/frontend/src/components/AlertPanel.jsx
@@ -110,6 +110,22 @@ export function AlertPanel({ alerts, onClose }) {
)
}
+/**
+ * EN: Translated alert message — the backend ships a code (alert.type) plus
+ * structured params (alert.details); the `alertmsg_*` i18n functions
+ * build the prose locally. Falls back to the backend's English `message`
+ * if no key exists.
+ * FR: Message d'alerte traduit — le backend envoie un code (alert.type) plus
+ * des paramètres structurés (alert.details) ; les fonctions i18n
+ * `alertmsg_*` construisent le texte localement. Retombe sur le `message`
+ * anglais du backend si aucune clé n'existe.
+ */
+function alertMessage(t, alert) {
+ const key = `alertmsg_${alert.type}`
+ const translated = t(key, alert.details || {})
+ return translated !== key ? translated : alert.message
+}
+
function AlertRow({ alert }) {
const { t } = useT()
const sev = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.info
@@ -134,7 +150,7 @@ function AlertRow({ alert }) {
{typeLabel}
</span>
</div>
- <div style={{ fontSize: 11, color: '#e2e8f0', lineHeight: 1.4 }}>{alert.message}</div>
+ <div style={{ fontSize: 11, color: '#e2e8f0', lineHeight: 1.4 }}>{alertMessage(t, alert)}</div>
{alert.details && Object.keys(alert.details).length > 0 && (
<div style={{ marginTop: 3, fontSize: 9, color: '#64748b', fontFamily: 'monospace' }}>
{Object.entries(alert.details).filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`).join(' · ')}
@@ -246,7 +262,7 @@ function Toast({ alert, index, dying }) {
<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 style={{ fontSize: 10, color: '#94a3b8', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{alertMessage(t, alert)}</div>
</div>
</div>
)
diff --git a/frontend/src/components/Dropdown.jsx b/frontend/src/components/Dropdown.jsx
new file mode 100644
index 0000000..4c4589b
--- /dev/null
+++ b/frontend/src/components/Dropdown.jsx
@@ -0,0 +1,69 @@
+/**
+ * Snitch — generic dropdown component.
+ *
+ * EN: Reusable wrapper replacing the four copy-pasted "open state + outside
+ * click" blocks that used to live in App.jsx. `useClickOutside` is the
+ * extracted hook; `Dropdown` wires it together with a toggle button and
+ * an absolutely-positioned panel.
+ *
+ * Usage:
+ * <Dropdown
+ * button={<button>…</button>} // onClick injected via cloneElement
+ * panelStyle={{ padding: 12 }} // overrides for the panel
+ * >
+ * {(close) => <div>…content…</div>} // render-prop OR plain node
+ * </Dropdown>
+ *
+ * FR: Enveloppe réutilisable remplaçant les quatre blocs copiés-collés
+ * « état open + clic extérieur » qui vivaient dans App.jsx.
+ * `useClickOutside` est le hook extrait ; `Dropdown` le combine avec un
+ * bouton bascule et un panneau positionné en absolu.
+ */
+import { useState, useRef, useEffect, cloneElement } from 'react'
+
+/**
+ * EN: Call `onClose` when a mousedown lands outside `ref`.
+ * FR: Appeler `onClose` quand un mousedown tombe en dehors de `ref`.
+ */
+export function useClickOutside(ref, onClose) {
+ useEffect(() => {
+ function handler(e) {
+ if (ref.current && !ref.current.contains(e.target)) onClose()
+ }
+ document.addEventListener('mousedown', handler)
+ return () => document.removeEventListener('mousedown', handler)
+ }, [ref, onClose])
+}
+
+/**
+ * EN: Self-contained dropdown — the button element's onClick is overridden to
+ * toggle open state; children render inside the floating panel and may be
+ * a render-prop receiving a `close()` callback.
+ * FR: Menu déroulant autonome — le onClick du bouton est remplacé pour
+ * basculer l'état ; les enfants s'affichent dans le panneau flottant et
+ * peuvent être un render-prop recevant un callback `close()`.
+ */
+export default function Dropdown({ button, children, panelStyle }) {
+ const [open, setOpen] = useState(false)
+ const ref = useRef(null)
+ useClickOutside(ref, () => setOpen(false))
+
+ const close = () => setOpen(false)
+
+ return (
+ <div ref={ref} style={{ position: 'relative' }}>
+ {cloneElement(button, { onClick: () => setOpen(v => !v) })}
+ {open && (
+ <div style={{
+ position: 'absolute', top: '110%', right: 0, zIndex: 100,
+ background: '#1e293b', border: '1px solid #334155',
+ borderRadius: 10, minWidth: 180,
+ boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
+ ...panelStyle,
+ }}>
+ {typeof children === 'function' ? children(close) : children}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/components/Timeline.jsx b/frontend/src/components/Timeline.jsx
index 8933b44..c06c3c3 100644
--- a/frontend/src/components/Timeline.jsx
+++ b/frontend/src/components/Timeline.jsx
@@ -10,7 +10,7 @@
*/
import { useEffect, useRef, useState, useCallback } from 'react'
import * as d3 from 'd3'
-import { API_BASE } from '../api'
+import { API_BASE, authHeaders } from '../api'
import { useT } from '../i18n'
const EXPANDED_H = 110
@@ -41,7 +41,10 @@ export default function Timeline() {
}
const fetchTimeline = useCallback(() => {
- fetch(`${API_BASE}/timeline?minutes=${range}`)
+ // EN: Auth header required — the API token protects every endpoint.
+ // FR: En-tête d'auth requis — le jeton API protège tous les endpoints.
+ authHeaders()
+ .then(headers => fetch(`${API_BASE}/timeline?minutes=${range}`, { headers }))
.then(r => r.json())
.then(d => setData(d.timeline || []))
.catch(() => {})
@@ -190,7 +193,7 @@ export default function Timeline() {
fontSize: 9, color: '#22c55e', marginLeft: 8,
}}>
<div style={{ width: 5, height: 5, borderRadius: '50%', background: '#22c55e' }} />
- Live
+ {t('timeline_live')}
</div>
</div>
</div>
diff --git a/frontend/src/graph/ForceGraph.jsx b/frontend/src/graph/ForceGraph.jsx
index 06cf8f0..c55db95 100644
--- a/frontend/src/graph/ForceGraph.jsx
+++ b/frontend/src/graph/ForceGraph.jsx
@@ -2,38 +2,80 @@
* 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.
+ * every connection an edge anchored on the central "local" node.
+ *
+ * PERFORMANCE (the big fix): the simulation is ONLY rebuilt when the
+ * graph *structure* changes — i.e. the SET of node ids or edge ids. On a
+ * busy link the old code rebuilt the whole sim once per WebSocket packet
+ * because `nodes`/`edges` were new objects every render. Now a
+ * `structKey` string (sorted ids) gates the rebuild effect, and a second
+ * lightweight effect updates the volatile visuals — edge width, tooltips,
+ * alert rings — by mutating the existing D3 selections in place.
+ * Node positions live in `posCache`, so rebuilds keep the layout stable.
*
* 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.
+ *
+ * PERFORMANCE (la grosse correction) : la simulation n'est reconstruite
+ * QUE quand la *structure* du graphe change — c.-à-d. l'ENSEMBLE des ids
+ * de nœuds ou d'arêtes. Sur un lien actif, l'ancien code reconstruisait
+ * toute la sim à chaque paquet WebSocket car `nodes`/`edges` étaient de
+ * nouveaux objets à chaque rendu. Désormais une `structKey` (ids triés)
+ * pilote l'effet de reconstruction, et un second effet léger met à jour
+ * les visuels volatils — largeur des arêtes, infobulles, anneaux d'alerte
+ * — en mutant les sélections D3 existantes sur place.
+ * Les positions des nœuds vivent dans `posCache` : les reconstructions
+ * gardent une mise en page stable.
*/
-import { useEffect, useRef } from 'react'
+import { useEffect, useMemo, useRef } from 'react'
import * as d3 from 'd3'
import { nodeIconURI } from './icons'
+/** EN: Edge stroke width scales with logged traffic volume.
+ * FR: La largeur d'arête suit le volume de trafic en échelle log. */
+const edgeWidth = d => d.dashed ? 1 : Math.min(1 + Math.log1p((d.bytes || 0) / 1024), 6)
+
+/** EN: Native tooltip text for a node datum. / FR: Texte d'infobulle native d'un nœud. */
+const nodeTitle = d =>
+ [d.label || d.ip, d.vendor, d.mac, d.country, d.org, `${d.packets || 0} pkts`]
+ .filter(Boolean).join('\n')
+
+/** EN: Truncated label under a node. / FR: Étiquette tronquée sous un nœud. */
+const nodeLabel = d => {
+ const label = d.label || d.ip || ''
+ return label.length > 20 ? label.slice(0, 18) + '…' : label
+}
+
+const radius = d => d.id === 'local' ? 22 : d.category === 'lan_device' ? 18 : 13
+
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 ─────────
+ const nodeSel = useRef(null) // EN: d3 selection of node <g>s / FR: sélection d3 des <g> nœuds
+ const linkSel = useRef(null) // EN: d3 selection of edge <line>s / FR: sélection d3 des <line> arêtes
+ const labelSel = useRef(null) // EN: d3 selection of edge <text>s / FR: sélection d3 des <text> arêtes
+ const posCache = useRef({}) // EN: { id: {x,y,fx,fy} } / FR: positions persistées
+ const dataRef = useRef({ nodes: {}, edges: {}, lanDevices: {} })
+
+ // EN: Always-latest data for effects that don't rebuild the sim.
+ // FR: Données toujours à jour pour les effets qui ne reconstruisent pas la sim.
+ dataRef.current = { nodes, edges, lanDevices }
+
+ /**
+ * EN: Structure signature — sorted node ids + sorted edge ids. The sim is
+ * rebuilt only when THIS string changes, no matter how often the
+ * byte/packet counters churn.
+ * FR: Signature de structure — ids de nœuds triés + ids d'arêtes triés. La
+ * sim n'est reconstruite que quand CETTE chaîne change, peu importe la
+ * fréquence des changements de compteurs d'octets/paquets.
+ */
+ const structKey = useMemo(() => {
+ const nids = [...Object.keys(nodes), ...Object.keys(lanDevices)].sort()
+ const eids = Object.keys(edges).sort()
+ return nids.join(',') + '|' + eids.join(',')
+ }, [nodes, edges, lanDevices])
+
+ // ── Full simulation — rebuilds ONLY on structural change ─────────────────
+ // ── Simulation complète — reconstruite SEULEMENT sur changement structurel ─
useEffect(() => {
const svg = d3.select(svgRef.current)
svg.selectAll('*').remove()
@@ -95,11 +137,11 @@ export default function ForceGraph({ nodes, edges, lanDevices, alertedNodes = ne
.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-width', edgeWidth)
.attr('stroke-dasharray', d => d.dashed ? '5,4' : null)
.attr('marker-end', d => d.dashed ? null : 'url(#arrow)')
- linkRef.current = link
+ linkSel.current = link
const linkLabel = g.append('g').selectAll('text')
.data(allEdges.filter(e => !e.dashed))
@@ -109,6 +151,8 @@ export default function ForceGraph({ nodes, edges, lanDevices, alertedNodes = ne
.attr('text-anchor', 'middle')
.text(d => d.label)
+ labelSel.current = linkLabel
+
const node = g.append('g').selectAll('g')
.data(allNodes)
.join('g')
@@ -125,25 +169,13 @@ export default function ForceGraph({ nodes, edges, lanDevices, alertedNodes = ne
})
)
- nodeRef.current = node
+ nodeSel.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: Alert rings are added/removed by the lightweight metrics effect —
+ // painted here too for freshly-built nodes.
+ // FR: Les anneaux d'alerte sont gérés par l'effet métriques léger —
+ // peints ici aussi pour les nœuds fraîchement créés.
+ paintAlertRings(node, alertedNodes)
// 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')
@@ -178,17 +210,13 @@ export default function ForceGraph({ nodes, edges, lanDevices, alertedNodes = ne
.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
- })
+ .text(nodeLabel)
- // 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')
- )
+ // EN: Native tooltip with full detail on hover — kept fresh by the
+ // metrics effect below.
+ // FR: Infobulle native avec le détail complet au survol — maintenue à jour
+ // par l'effet métriques ci-dessous.
+ node.append('title').text(nodeTitle)
sim.on('tick', () => {
link
@@ -210,12 +238,37 @@ export default function ForceGraph({ nodes, edges, lanDevices, alertedNodes = ne
})
return () => sim.stop()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [structKey])
+
+ // ── Metrics refresh — NO simulation restart ──────────────────────────────
+ // ── Rafraîchissement des métriques — SANS relancer la simulation ──────────
+ useEffect(() => {
+ const link = linkSel.current
+ const node = nodeSel.current
+ if (!link || !node) return
+
+ const { nodes, edges, lanDevices } = dataRef.current
+ // EN: Look up the LATEST datum by id — the objects bound in the sim are
+ // stale copies from the last structural rebuild.
+ // FR: Chercher la donnée LA PLUS RÉCENTE par id — les objets liés dans la
+ // sim sont des copies périmées de la dernière reconstruction.
+ const edgeById = new Map(Object.values(edges).map(e => [e.id, e]))
+ const nodeById = new Map(
+ [...Object.values(nodes), ...Object.values(lanDevices)].map(n => [n.id, n])
+ )
+
+ link.attr('stroke-width', d => edgeWidth(edgeById.get(d.id) || d))
+ node.select('title').text(d => nodeTitle(nodeById.get(d.id) || d))
+ node.select('text').text(d => nodeLabel(nodeById.get(d.id) || d))
+
+ paintAlertRings(node, alertedNodes)
}, [nodes, edges, lanDevices, alertedNodes])
- // ── Filter dimming — no simulation restart ────────────────────────────────
+ // ── Filter dimming — no simulation restart ───────────────────────────────
// ── Estompage par filtre — sans relancer la simulation ────────────────────
useEffect(() => {
- if (!nodeRef.current || !linkRef.current) return
+ if (!nodeSel.current || !linkSel.current) return
function matches(d) {
if (!filter || (filter.category === 'all' && !filter.text)) return true
@@ -233,9 +286,9 @@ export default function ForceGraph({ nodes, edges, lanDevices, alertedNodes = ne
return true
}
- nodeRef.current.attr('opacity', d => matches(d) ? 1 : 0.1)
+ nodeSel.current.attr('opacity', d => matches(d) ? 1 : 0.1)
- linkRef.current.attr('stroke-opacity', d => {
+ linkSel.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
@@ -244,3 +297,37 @@ export default function ForceGraph({ nodes, edges, lanDevices, alertedNodes = ne
return <svg ref={svgRef} style={{ width: '100%', height: '100%', background: '#0f172a' }} />
}
+
+/**
+ * EN: Sync pulsing red alert rings with the current alerted-node set —
+ * adds rings to newly-alerted nodes, removes them elsewhere. Works on
+ * live selections, so it costs nothing when nothing changed.
+ * FR: Synchroniser les anneaux rouges pulsants avec l'ensemble actuel des
+ * nœuds en alerte — ajoute des anneaux aux nœuds nouvellement alertés,
+ * les retire ailleurs. Travaille sur les sélections vivantes, donc ne
+ * coûte rien quand rien n'a changé.
+ */
+function paintAlertRings(nodeSel, alertedNodes) {
+ nodeSel.each(function (d) {
+ const g = d3.select(this)
+ const shouldAlert = alertedNodes.has(d.id) || d.alerted
+ const ring = g.select('circle.alert-ring')
+ if (shouldAlert && ring.empty()) {
+ // EN: Insert BEFORE the body circle so the ring sits behind the node.
+ // FR: Insérer AVANT le cercle du corps pour que l'anneau soit derrière.
+ g.insert('circle', ':first-child')
+ .attr('class', 'alert-ring')
+ .attr('r', radius(d) + 9)
+ .attr('fill', 'none')
+ .attr('stroke', '#ef4444')
+ .attr('stroke-width', 1.5)
+ .attr('stroke-opacity', 0.7)
+ .append('animate')
+ .attr('attributeName', 'stroke-opacity')
+ .attr('values', '0.7;0.1;0.7')
+ .attr('dur', '1.5s').attr('repeatCount', 'indefinite')
+ } else if (!shouldAlert && !ring.empty()) {
+ ring.remove()
+ }
+ })
+}
diff --git a/frontend/src/hooks/useWebSocket.js b/frontend/src/hooks/useWebSocket.js
index b3d25a5..9e572f6 100644
--- a/frontend/src/hooks/useWebSocket.js
+++ b/frontend/src/hooks/useWebSocket.js
@@ -3,20 +3,25 @@
*
* 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).
+ * per-second bandwidth buckets that feed the sparkline.
+ *
+ * Reconnection: exponential backoff (1 s → 2 s → 4 s … capped at 30 s)
+ * instead of a fixed 2 s — a dead backend no longer gets hammered. The
+ * pending retry timer IS cleared on unmount (the old version leaked it).
+ * The connection is opened with the API token via wsUrlWithToken().
*
* 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).
+ * sparkline.
+ *
+ * Reconnexion : backoff exponentiel (1 s → 2 s → 4 s … plafonné à 30 s)
+ * au lieu de 2 s fixes — un backend mort n'est plus martelé. Le timer de
+ * réessai EST nettoyé au démontage (l'ancienne version le fuyait).
+ * La connexion s'ouvre avec le jeton API via wsUrlWithToken().
*/
import { useEffect, useRef, useState } from 'react'
-import { API_BASE } from '../api'
+import { API_BASE, authHeaders, wsUrlWithToken } from '../api'
export function useWebSocket(url) {
const ws = useRef(null)
@@ -57,13 +62,30 @@ export function useWebSocket(url) {
}, [])
useEffect(() => {
- function connect() {
- ws.current = new WebSocket(url)
+ let stopped = false
+ let attempts = 0
+ let timer = null
+
+ async function connect() {
+ // EN: Resolve the token BEFORE opening the socket.
+ // FR: Résoudre le jeton AVANT d'ouvrir le socket.
+ const wsUrl = await wsUrlWithToken(url)
+ if (stopped) return
- ws.current.onopen = () => setStatus('connected')
+ ws.current = new WebSocket(wsUrl)
+
+ ws.current.onopen = () => {
+ attempts = 0
+ setStatus('connected')
+ }
ws.current.onclose = () => {
+ if (stopped) return
setStatus('disconnected')
- setTimeout(connect, 2000) // EN: auto-reconnect / FR: reconnexion auto
+ // EN: Exponential backoff — 1s, 2s, 4s … max 30s.
+ // FR: Backoff exponentiel — 1s, 2s, 4s … max 30s.
+ const delay = Math.min(30000, 1000 * 2 ** attempts)
+ attempts += 1
+ timer = setTimeout(connect, delay)
}
ws.current.onerror = () => setStatus('error')
@@ -106,7 +128,7 @@ export function useWebSocket(url) {
// 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.edge) setEdges(prev => ({ ...prev, [msg.edge.id]: msg.edge }))
}
if (msg.type === 'alert') {
@@ -164,7 +186,13 @@ export function useWebSocket(url) {
}
connect()
- return () => ws.current?.close()
+ return () => {
+ // EN: Stop reconnecting and free the pending timer on unmount.
+ // FR: Arrêter les reconnexions et libérer le timer en attente au démontage.
+ stopped = true
+ if (timer) clearTimeout(timer)
+ ws.current?.close()
+ }
}, [url])
const clearUnread = () => setUnread(0)
@@ -173,7 +201,10 @@ export function useWebSocket(url) {
async function toggleCapture() {
const endpoint = capturing ? '/capture/stop' : '/capture/start'
- const res = await fetch(`${API_BASE}${endpoint}`, { method: 'POST' })
+ const res = await fetch(`${API_BASE}${endpoint}`, {
+ method: 'POST',
+ headers: await authHeaders(),
+ })
const data = await res.json()
setCapturing(data.capturing)
}
@@ -181,7 +212,7 @@ export function useWebSocket(url) {
async function updatePortFilter(ports) {
const res = await fetch(`${API_BASE}/capture/ports`, {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: await authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ ports }),
})
const data = await res.json()
@@ -191,7 +222,7 @@ export function useWebSocket(url) {
async function updateProcessFilter(excluded) {
const res = await fetch(`${API_BASE}/capture/processes`, {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: await authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ excluded }),
})
const data = await res.json()
@@ -201,7 +232,7 @@ export function useWebSocket(url) {
async function updateIpWhitelist(ips) {
const res = await fetch(`${API_BASE}/capture/whitelist`, {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: await authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ ips }),
})
const data = await res.json()
diff --git a/frontend/src/i18n.jsx b/frontend/src/i18n.jsx
index 67b1aab..09172f6 100644
--- a/frontend/src/i18n.jsx
+++ b/frontend/src/i18n.jsx
@@ -28,6 +28,14 @@ const en = {
// Legend / Légende
legend_alert: 'Alert',
legend_unknown: 'Unknown',
+ legend_router: 'Router',
+ legend_phone: 'Phone',
+ legend_pc: 'PC',
+ legend_iot: 'IoT',
+ legend_https: 'HTTPS',
+ legend_tracking: 'Tracking',
+ legend_cdn: 'CDN',
+ legend_dns: 'DNS',
// Sidebar header + stats / En-tête de barre latérale + stats
app_name: 'SNITCH',
@@ -74,6 +82,18 @@ const en = {
alert_NEW_LAN_DEVICE: 'New device',
alert_DEVICE_OFFLINE: 'Device offline',
alert_MEDIA_EXFIL: 'Media exfiltration',
+ // EN: Full alert messages built from backend codes + details — the backend
+ // only sends type + params, never prose.
+ // FR: Messages d'alerte complets construits depuis les codes + détails du
+ // backend — le backend n'envoie que type + paramètres, jamais de prose.
+ alertmsg_NEW_HOST: d => `New host contacted: ${d.host || d.ip}`,
+ alertmsg_SUSPICIOUS_PROCESS: d => `Suspicious process: ${d.process} → ${d.host || d.ip}`,
+ alertmsg_SUSPICIOUS_PORT: d => `Suspicious port ${d.port} (${d.reason}) → ${d.host || d.ip}`,
+ alertmsg_BEACON: d => `Beacon-like regularity: ~${d.interval_s}s interval to ${d.host || d.ip}`,
+ alertmsg_VOLUME_SPIKE: d => `Traffic spike to ${d.host || d.ip} (${d.kb} KB in one packet)`,
+ alertmsg_MEDIA_EXFIL: d => `Suspected ${d.device} exfiltration: ${d.process} → ${d.host || d.ip}`,
+ alertmsg_NEW_LAN_DEVICE: d => `New device on the network: ${d.host || d.ip}`,
+ alertmsg_DEVICE_OFFLINE: d => `Device went offline: ${d.host || d.ip}`,
time_just_now: 'just now',
time_seconds: n => `${n}s ago`,
time_minutes: n => `${n}min ago`,
@@ -94,6 +114,7 @@ const en = {
// Timeline
timeline_packets: n => `${n.toLocaleString()} packets`,
timeline_alerts: n => `${n} alert${n > 1 ? 's' : ''}`,
+ timeline_live: 'Live',
// Capture toggle / Bascule de capture
capture_stop: 'Stop',
@@ -162,6 +183,14 @@ const fr = {
// Légende / Legend
legend_alert: 'Alerte',
legend_unknown: 'Inconnu',
+ legend_router: 'Routeur',
+ legend_phone: 'Téléphone',
+ legend_pc: 'PC',
+ legend_iot: 'IoT',
+ legend_https: 'HTTPS',
+ legend_tracking: 'Tracking',
+ legend_cdn: 'CDN',
+ legend_dns: 'DNS',
// En-tête de barre latérale + stats / Sidebar header + stats
app_name: 'SNITCH',
@@ -208,6 +237,14 @@ const fr = {
alert_NEW_LAN_DEVICE: 'Nouvel appareil',
alert_DEVICE_OFFLINE: 'Appareil hors ligne',
alert_MEDIA_EXFIL: 'Exfiltration média',
+ alertmsg_NEW_HOST: d => `Nouvel hôte contacté : ${d.host || d.ip}`,
+ alertmsg_SUSPICIOUS_PROCESS: d => `Processus suspect : ${d.process} → ${d.host || d.ip}`,
+ alertmsg_SUSPICIOUS_PORT: d => `Port suspect ${d.port} (${d.reason}) → ${d.host || d.ip}`,
+ alertmsg_BEACON: d => `Régularité type beacon : intervalle ~${d.interval_s}s vers ${d.host || d.ip}`,
+ alertmsg_VOLUME_SPIKE: d => `Pic de trafic vers ${d.host || d.ip} (${d.kb} Ko en un paquet)`,
+ alertmsg_MEDIA_EXFIL: d => `Exfiltration ${d.device === 'camera' ? 'caméra' : 'micro'} suspectée : ${d.process} → ${d.host || d.ip}`,
+ alertmsg_NEW_LAN_DEVICE: d => `Nouvel appareil sur le réseau : ${d.host || d.ip}`,
+ alertmsg_DEVICE_OFFLINE: d => `Appareil hors ligne : ${d.host || d.ip}`,
time_just_now: "à l'instant",
time_seconds: n => `il y a ${n}s`,
time_minutes: n => `il y a ${n}min`,
@@ -228,6 +265,7 @@ const fr = {
// Timeline
timeline_packets: n => `${n.toLocaleString('fr-FR')} paquets`,
timeline_alerts: n => `${n} alerte${n > 1 ? 's' : ''}`,
+ timeline_live: 'Direct',
// Bascule de capture / Capture toggle
capture_stop: 'Stop',
diff --git a/frontend/src/scoring/privacy.test.js b/frontend/src/scoring/privacy.test.js
new file mode 100644
index 0000000..37dcf64
--- /dev/null
+++ b/frontend/src/scoring/privacy.test.js
@@ -0,0 +1,74 @@
+/**
+ * Snitch — privacy score tests (Vitest).
+ *
+ * EN: Exercises computePrivacyScore's main branches: baseline, tracker
+ * penalties, beacon/critical penalties, grade/color/label mapping and
+ * positive factors.
+ * FR: Couvre les branches principales de computePrivacyScore : base,
+ * pénalités trackers, pénalités beacon/critiques, correspondance
+ * note/couleur/libellé et facteurs positifs.
+ */
+import { describe, it, expect } from 'vitest'
+import { computePrivacyScore } from './privacy'
+
+const node = (over = {}) => ({
+ id: '1.2.3.4', category: 'unknown', bytes: 1000, packets: 10, org: null, ...over,
+})
+const alert = (type, severity = 'warning') => ({ type, severity })
+
+describe('computePrivacyScore', () => {
+ it('returns a perfect baseline with no external nodes', () => {
+ const r = computePrivacyScore({ local: node({ id: 'local' }) }, [])
+ expect(r.score).toBe(100)
+ expect(r.grade).toBe('A')
+ expect(r.color).toBe('#22c55e')
+ expect(r.labelKey).toBe('privacy_label_excellent')
+ })
+
+ it('penalizes tracker nodes', () => {
+ const nodes = {
+ local: node({ id: 'local' }),
+ '9.9.9.9': node({ id: '9.9.9.9', category: 'tracking', bytes: 5000 }),
+ }
+ const r = computePrivacyScore(nodes, [])
+ expect(r.score).toBeLessThan(100)
+ expect(r.factors.some(f => f.key === 'score_trackers')).toBe(true)
+ })
+
+ it('penalizes beacon and critical alerts heavily', () => {
+ const r = computePrivacyScore(
+ { local: node({ id: 'local' }), '1.1.1.1': node() },
+ [alert('BEACON'), alert('MEDIA_EXFIL', 'critical')],
+ )
+ expect(r.score).toBeLessThan(80)
+ expect(r.factors.some(f => f.key === 'score_beacons')).toBe(true)
+ expect(r.factors.some(f => f.key === 'score_critical_alerts')).toBe(true)
+ })
+
+ it('rewards high HTTPS share with a positive factor', () => {
+ const nodes = {
+ local: node({ id: 'local' }),
+ 'a': node({ id: 'a', category: 'safe', packets: 100 }),
+ 'b': node({ id: 'b', category: 'unknown', packets: 10 }),
+ }
+ const r = computePrivacyScore(nodes, [])
+ expect(r.factors.some(f => f.key === 'score_https_ratio' && !f.bad)).toBe(true)
+ expect(r.factors.some(f => f.key === 'score_no_trackers' && !f.bad)).toBe(true)
+ })
+
+ it('detects ad networks by org name', () => {
+ const nodes = {
+ local: node({ id: 'local' }),
+ 'x': node({ id: 'x', org: 'Google LLC' }),
+ }
+ const r = computePrivacyScore(nodes, [])
+ expect(r.factors.some(f => f.key === 'score_ad_networks')).toBe(true)
+ })
+
+ it('score is always clamped to [0, 100]', () => {
+ const many = Array.from({ length: 50 }, (_, i) => alert('BEACON', 'critical'))
+ const r = computePrivacyScore({}, many)
+ expect(r.score).toBeGreaterThanOrEqual(0)
+ expect(r.score).toBeLessThanOrEqual(100)
+ })
+})
diff --git a/frontend/vite.config.js b/frontend/vite.config.js
index 3aa3b0f..2636fe6 100644
--- a/frontend/vite.config.js
+++ b/frontend/vite.config.js
@@ -14,6 +14,11 @@ import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: './',
+ // EN: Vitest reads this — plain Node environment is enough for our pure
+ // logic tests (privacy scoring).
+ // FR: Vitest lit cette clé — l'environnement Node suffit pour nos tests de
+ // logique pure (score de confidentialité).
+ test: { environment: 'node' },
server: {
port: 5173,
proxy: {