Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.
Python cybersecurityd3jsebpfedrelectronfastapifirewallfleet-managementlinuxlittle-snitch-alternativemacosnetwork-monitornetwork-securitypacket-captureprivacyreactrustself-hostedsiemwindows
Add security suite: firewall, threat intel, forensics
MoneyLisa048c260c2a6a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 614d31f..855fc40 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,21 @@ All notable changes to Snitch. / Toutes les modifications notables de Snitch.The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.+## [Unreleased]++### Added / Ajouté++- **Outbound firewall orchestration / Orchestration du pare-feu sortant** — user rules (`ip`, `cidr`, `domain`, `process`, `port`) applied to the OS-native firewall best-effort: `netsh advfirewall` on Windows, `iptables` on Linux, a generated `pf` anchor on macOS. Persisted, re-applied at startup, honest `applied=False` when privileges are missing (matching + `BLOCKED_ATTEMPT` counters still work). / Règles utilisateur (`ip`, `cidr`, `domain`, `process`, `port`) appliquées au pare-feu natif OS au mieux : `netsh` sous Windows, `iptables` sous Linux, ancre `pf` sous macOS. Persistées, réappliquées au démarrage, `applied=False` honnête sans privilèges (matching + compteurs `BLOCKED_ATTEMPT` actifs).+- **Lockdown / Confinement** — panic switch dropping outbound traffic to public IPs while keeping loopback/LAN alive (Linux `SNITCH_LOCK` chain, `netsh` rules, `pf` anchor). / Interrupteur panique coupant le trafic sortant vers les IP publiques tout en préservant loopback/LAN.+- **Process actions / Actions processus** — `POST /processes/kill` and `POST /processes/suspend` (by PID, refuses PIDs ≤ 3 and Snitch itself); kill/suspend buttons in the process list. / `POST /processes/kill` et `POST /processes/suspend` (par PID, refuse les PID ≤ 3 et Snitch) ; boutons kill/suspend dans la liste des processus.+- **Threat intelligence (opt-in) / Threat intel (opt-in)** — reputation checks against AbuseIPDB, AlienVault OTX or VirusTotal with your own API key; off by default, one call per newly-seen public IP, bounded LRU cache + dedup, `THREAT_HIT` alerts on suspicious/malicious verdicts. / Vérifs de réputation via AbuseIPDB, AlienVault OTX ou VirusTotal avec votre clé ; désactivé par défaut, un appel par IP publique nouvelle, cache LRU borné + dédup, alertes `THREAT_HIT`.+- **External webhooks (opt-in) / Webhooks externes (opt-in)** — warning/critical alerts POSTed live to Discord, Slack, Telegram (with chat ID) or any endpoint; off by default. / Alertes warning/critiques POSTées en direct vers Discord, Slack, Telegram ou tout endpoint ; désactivé par défaut.+- **Detection additions / Ajouts de détection** — `DNS_TUNNEL` (oversized DNS names/labels), `CLEARTEXT` (FTP/Telnet/HTTP/plain-mail egress), `BASELINE_DEVIATION` (per-process learned country profile, persisted). / `DNS_TUNNEL` (noms/labels DNS surdimensionnés), `CLEARTEXT` (sorties FTP/Telnet/HTTP/mail en clair), `BASELINE_DEVIATION` (profil pays appris par processus, persisté).+- **Security audit / Audit de sécurité** — `GET /security/audit` computes a 0–100 score plus plain-language recommendations from recent alerts and the live graph; surfaced in the Firewall panel. / `GET /security/audit` calcule un score 0–100 + recommandations en langage clair depuis les alertes récentes et le graphe ; affiché dans le panneau Pare-feu.+- **Forensics export / Export forensique** — `GET /forensics/export?format=json|csv|stix` bundles process tree, executable SHA-256, matching alerts and traffic history; STIX is a minimal 2.1 bundle (indicators + observed-data) for SIEM import. / `GET /forensics/export?format=json|csv|stix` — arbre de processus, SHA-256 de l'exécutable, alertes et historique ; STIX = bundle 2.1 minimal pour SIEM.+- **Firewall & security UI / UI pare-feu & sécurité** — dedicated panel: lockdown switch, rule create/toggle/delete, per-rule blocked counters, platform-support honesty, audit report, forensics download buttons; per-connection Block action in the sidebar. / Panneau dédié : lockdown, création/bascule/suppression de règles, compteurs bloqués par règle, honnêteté plateforme, rapport d'audit, boutons d'export forensique ; action Bloquer par connexion dans la sidebar.+- **Five new UI locales / Cinq nouvelles locales** — de, ru, ja, pt-BR, zh-CN (8 total, 280-key parity-checked); dictionaries moved to `frontend/src/locales/*.js` so a new language is a single-file PR. / de, ru, ja, pt-BR, zh-CN (8 au total, parité 280 clés) ; dictionnaires déplacés vers `frontend/src/locales/*.js` — une nouvelle langue = PR d'un fichier.+## [1.1.0] — 2026-10-22### Added / Ajoutédiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0e55eb9..68c8c4d 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -3,7 +3,11 @@## EnglishThanks for your interest! Snitch is a bilingual (EN/FR) project — code-comments and user-facing text should exist in both languages where practical.+comments and user-facing text should exist in both languages where+practical. The UI ships 8 locales under `frontend/src/locales/` — a new+language is a single file copied from `en.js` (keep key parity) plus an+entry in `LANGS`/`LANG_NAMES` in `frontend/src/i18n.jsx`. Translation PRs+are very welcome.**Ground rules**@@ -30,7 +34,10 @@ Frontend: `npm run dev` → http://localhost:5173/?token=<token from backend outMerci de votre intérêt ! Snitch est un projet bilingue (EN/FR) — lescommentaires de code et les textes utilisateur doivent exister dans les deux-langues autant que possible.+langues autant que possible. L'UI compte 8 locales dans+`frontend/src/locales/` — une nouvelle langue = un nouveau fichier copiant+`en.js` (gardez les clés en parité) + une entrée dans `LANGS`/`LANG_NAMES`+de `frontend/src/i18n.jsx`.**Règles de base**diff --git a/PRIVACY.md b/PRIVACY.mdindex 3dbdd8f..ef6fdb2 100644--- a/PRIVACY.md+++ b/PRIVACY.md@@ -7,8 +7,9 @@ Snitch is a privacy tool — it must never leak the very data it helps you monit**Telemetry: none.** Snitch contains no analytics, no crash reporting, nophone-home of any kind.-**Outbound network calls made by Snitch: two, both optional.** Everything-below is passive observation or user-triggered — there is no silent traffic:+**Outbound network calls made by Snitch: all optional, all off by+default.** Everything below is passive observation or user-triggered —+there is no silent traffic:- captures packets on your local interfaces (passive observation),- reads your system ARP/neighbour table (no active scanning),@@ -26,6 +27,18 @@ and the backend itself never check for updates.The **GeoIP database download** (`Settings → Geolocation`) fetches ~50 MBfrom db-ip.com — only when you click it, with an explicit consent flag.+**Threat intelligence (opt-in, off by default).** When you configure a+provider (AbuseIPDB, AlienVault OTX or VirusTotal) *and* paste your own API key in+Settings, Snitch queries that provider for the reputation of newly-seen+public hosts — sending them the queried IP only. Verdicts are cached+locally; the key is stored in `snitch.db` (never logged, masked in the UI).+With no provider or no key, zero lookups are made — `ti.check()` is a no-op.++**External webhooks (opt-in, off by default).** When you paste a webhook+URL (Discord, Slack, Telegram bot endpoint or any URL) and flip the switch,+warning/critical alert texts are POSTed to that endpoint in real time.+Nothing is sent while the switch is off.+**Geolocation is offline-only.** Once a DB-IP Lite or MaxMind GeoLite2`.mmdb` file sits in `<data_dir>/geo/`, lookups happen locally against thatfile. Without it, IPs simply show no location. There is no HTTP geolocation@@ -54,8 +67,9 @@ données qu'il vous aide à surveiller.**Télémétrie : aucune.** Pas d'analytics, pas de rapports de crash, aucunappel « maison » d'aucune sorte.-**Appels réseau émis par Snitch : deux, tous deux optionnels.** Tout le-reste est observation passive ou déclenché par vous — aucun trafic silencieux :+**Appels réseau émis par Snitch : tous optionnels, tous désactivés par+défaut.** Tout le reste est observation passive ou déclenché par vous —+aucun trafic silencieux :- capturer les paquets sur vos interfaces locales (observation passive),- lire la table ARP/voisinage système (pas de scan actif),@@ -74,6 +88,20 @@ puis toutes les 6 h (electron-updater, lecture des fichiers publicsrécupère ~50 Mo depuis db-ip.com — uniquement à votre clic, avec unconsentement explicite.+**Threat intelligence (opt-in, désactivé par défaut).** Quand vous+configurez un fournisseur (AbuseIPDB, AlienVault OTX ou VirusTotal) *et* collez votre+propre clé API dans les Réglages, Snitch interroge ce fournisseur sur la+réputation des nouveaux hôtes publics — seule l'IP interrogée lui est+envoyée. Les verdicts sont cachés localement ; la clé est stockée dans+`snitch.db` (jamais journalisée, masquée dans l'UI). Sans fournisseur ni+clé, aucune requête n'est faite — `ti.check()` est inerte.++**Webhooks externes (opt-in, désactivés par défaut).** Quand vous collez+une URL de webhook (Discord, Slack, endpoint de bot Telegram ou toute URL)+et basculez l'interrupteur, les textes des alertes warning/critiques sont+POSTés vers cet endpoint en temps réel. Rien n'est envoyé tant que+l'interrupteur est éteint.+**La géolocalisation est 100 % hors ligne.** Une fois un fichier `.mmdb`DB-IP Lite ou MaxMind GeoLite2 dans `<data_dir>/geo/`, les recherches sefont localement. Sans base, les IP n'affichent simplement pas de position.diff --git a/README.md b/README.mdindex a510175..0e3d2b7 100644--- a/README.md+++ b/README.md@@ -31,11 +31,11 @@**Snitch** is a real-time network traffic visualizer.See every connection your computer makes — who it talks to, where they are, and which app is responsible.-The entire interface is available in **English, French and Spanish**: use the `EN / FR / ES` toggle in the top-right toolbar.+The entire interface is available in **English, Français, Español, Deutsch, Русский, 日本語, Português (BR) and 简体中文**: use the language picker in the top-right toolbar.### Why Snitch?-- **vs Little Snitch / Lulu** — those are macOS firewalls that *block* connections; Snitch *visualizes and explains* traffic, is cross-platform, free and open-source.+- **vs Little Snitch / Lulu** — same idea (per-app outbound visibility + blocking rules), but Snitch is cross-platform, free and open-source. Blocking is orchestrated through the OS-native firewall (`netsh` / `iptables` / `pf`) — Snitch never filters in user-space.- **vs GlassWire** — Snitch is free, open-source (AGPL), requires no account and makes **zero outbound calls**; even geolocation is offline.- **vs Wireshark** — Snitch gives a live, high-level overview anyone can read, instead of raw packet dissection.- **vs cloud-based monitors** — everything runs on `127.0.0.1` behind a token; your traffic data never leaves the machine.@@ -47,7 +47,15 @@ The entire interface is available in **English, French and Spanish**: use the `E| 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 || 15/30/60-min Timeline | Sliding history stored locally in SQLite (24 h retention) |-| Anomaly Detection | Flags port scans, beaconing, potential exfiltration |+| Anomaly Detection | Flags port scans, beaconing (regular-interval C2), potential exfiltration |+| Advanced Detection | DNS-tunnelling heuristic, cleartext-port spotting, per-app country baseline deviation |+| Firewall Orchestration | Block rules (IP/CIDR/domain/process/port) applied to the OS firewall — `netsh`/`iptables`/`pf`, persisted, per-rule blocked counters |+| Lockdown Mode | Panic switch — flags & blocks all public outbound traffic, LAN stays up |+| Incident Response | Kill / suspend a process, block an IP — one click from the connection detail |+| Threat Intelligence | **Opt-in** reputation checks (AbuseIPDB / AlienVault OTX / VirusTotal) with your own API key — off by default, results cached |+| Security Audit | Built-in hardening report — score, findings, plain-language recommendations |+| Forensics Export | One-click investigation bundle — process tree + SHA-256 of the binary, history & matching alerts |+| Webhook Alerting | **Opt-in** forwarding of warning/critical alerts to Discord, Slack, Telegram or any endpoint || Process Attribution | Know which app generates which traffic (top 5 per connection) || LAN Scanner | Passive discovery via the system ARP table (no broadcast scans) || Privacy Score | Real-time score of your outgoing traffic exposure |@@ -56,7 +64,7 @@ The entire interface is available in **English, French and Spanish**: use the `E| Settings Panel | Language, retention, filters, consent-gated GeoIP download, diagnostics || Tracker Detection | Suffix-matched domain lists shipped as editable data files (`backend/classifier/lists/`) || Bandwidth Monitor | Live MB/s sparkline |-| EN / FR / ES UI | Full trilingual interface, one click to switch |+| 8-language UI | EN · FR · ES · DE · RU · JA · PT-BR · ZH-CN — one click to switch, locales live in `frontend/src/locales/` || Light / Dark Theme | Follows your OS preference by default, manual toggle persists || Auto-Update | Desktop app checks GitHub Releases (opt-out in Settings; `SNITCH_NO_UPDATE=1`) || QUIC / HTTP/3 | UDP/443 flows labeled honestly — QUIC SNI is encrypted and never read |@@ -98,14 +106,16 @@ Or grab the latest release: **[github.com/aixisstudio/Snitch/releases](https://g- **API token** — every REST endpoint and the WebSocket require a token. Electron generates it per launch; in Docker/browser it's printed once in the backend logs and stored in `data/api_token.txt`. Open the UI with `http://localhost:8000/?token=<TOKEN>` (or enter it when prompted).- **Loopback-only by default** — the API binds `127.0.0.1` in every mode. Set `SNITCH_BIND=0.0.0.0` only if you explicitly want LAN access (token auth still applies).- **CORS/WebSocket origin allowlist** — only `localhost:5173`, the backend's own origin and Electron `file://` pages may connect.-- **Geolocation is offline-only** — there is *no* online lookup. DB-IP Lite ([CC BY 4.0](https://db-ip.com/db/lite.php)) ships gzip'd in `backend/data/geo/` and is auto-extracted into `<data_dir>/geo/` on first launch — geo works out of the box, zero network calls. You may still drop newer `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) into `<data_dir>/geo/`, or download a fresh DB-IP Lite from the Settings panel (explicit consent, the only possible outbound call).-- **All data stays local** — `snitch.db` (24 h sliding window, configurable via `retention_hours` setting) and `data/logs/snitch.log` never leave the machine. No telemetry. The **only** possible outbound call is the opt-in DB-IP Lite download (Settings → "Download DB-IP Lite"), which requires an explicit click.-- **Settings persist** — port filters, excluded processes, the IP whitelist, language and retention are stored in SQLite and restored on restart.+- **Geolocation is offline-only** — there is *no* online lookup. DB-IP Lite ([CC BY 4.0](https://db-ip.com/db/lite.php)) ships gzip'd in `backend/data/geo/` and is auto-extracted into `<data_dir>/geo/` on first launch — geo works out of the box, zero network calls. You may still drop newer `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) into `<data_dir>/geo/`, or download a fresh DB-IP Lite from the Settings panel (explicit consent; the other opt-in outbound calls — threat intel, webhooks, update checks — are listed in [PRIVACY.md](PRIVACY.md)).+- **All data stays local** — `snitch.db` (24 h sliding window, configurable via `retention_hours` setting) and `data/logs/snitch.log` never leave the machine. No telemetry. Every outbound call is opt-in — DB-IP Lite download, threat-intel lookups, webhooks and update checks are each gated by your explicit action or a switch (see [PRIVACY.md](PRIVACY.md)).+- **Settings persist** — port filters, excluded processes, the IP whitelist, firewall rules, language and retention are stored in SQLite and restored on restart.+- **Firewall rules are best-effort** — the backend drives the OS firewall (`netsh advfirewall`, `iptables`, `pf` anchors); when privileges are missing the rule is kept and matched for *visibility* (BLOCKED_ATTEMPT alerts) and marked "not applied" instead of pretending enforcement. Lockdown keeps loopback + LAN alive so the UI stays reachable.+- **Threat intelligence & webhooks are opt-in** — disabled by default; enabling a provider (AbuseIPDB/OTX/VirusTotal, your own API key) or a webhook adds outbound calls, documented in [PRIVACY.md](PRIVACY.md).- **Alert suppression** — each alert has an "Ignore this type/host" action; suppression rules are persisted (`alert_suppressions` table), applied before alerts are emitted or logged, and survivable across restarts via `POST /alerts/ignore` / `DELETE /alerts/ignore` / `GET /alerts/ignore`.- **History** — per-minute per-host and per-process byte/packet aggregates are kept in SQLite (`host_history`, `process_history`) for the retention window, powering the per-application view and `GET /history/host/{ip}` / `GET /history/process/{name}`.- **Diagnostics** — `GET /diagnostics` returns a JSON snapshot of the runtime (capture state, geo DB status, interface, versions, paths) with no secrets; the Settings panel can export it or open the log directory (Electron).- **LAN devices** are discovered passively from the system ARP table — no active broadcast scanning. Device names are learned from what devices broadcast themselves: mDNS `*.local` (Apple/Linux), LLMNR & NetBIOS names (Windows), DHCP hostname options, plus the full offline IEEE OUI vendor table, and your gateway is auto-detected as the router.-- See [docs/threat-model.md](docs/threat-model.md) for the full threat model.+- See [docs/threat-model.md](docs/threat-model.md) for the full threat model and [docs/FIREWALL.md](docs/FIREWALL.md) for the security suite (firewall orchestration, lockdown, threat intel, webhooks, audit, forensics).### Docker (Linux)@@ -229,11 +239,11 @@ snitch/**Snitch** est un visualiseur de trafic réseau en temps réel.Voyez chaque connexion que votre ordinateur établit — à qui il parle, où se trouvent les serveurs, et quelle application est responsable.-Toute l'interface est disponible en **français, anglais et espagnol** : utilisez le sélecteur `EN / FR / ES` dans la barre d'outils en haut à droite.+Toute l'interface est disponible en **English, Français, Español, Deutsch, Русский, 日本語, Português (BR) et 简体中文** : utilisez le sélecteur de langue dans la barre d'outils en haut à droite.### Pourquoi Snitch ?-- **vs Little Snitch / Lulu** — ce sont des pare-feux macOS qui *bloquent* les connexions ; Snitch *visualise et explique* le trafic, est multiplateforme, gratuit et open-source.+- **vs Little Snitch / Lulu** — même idée (visibilité par app + règles de blocage sortantes), mais Snitch est multiplateforme, gratuit et open-source. Le blocage est orchestré via le pare-feu natif de l'OS (`netsh` / `iptables` / `pf`) — Snitch ne filtre jamais en user-space.- **vs GlassWire** — Snitch est gratuit, open-source (AGPL), sans compte et n'effectue **aucun appel sortant** ; même la géolocalisation est hors ligne.- **vs Wireshark** — Snitch offre une vue d'ensemble en direct lisible par tous, plutôt qu'une dissection brute de paquets.- **vs les moniteurs cloud** — tout tourne sur `127.0.0.1` derrière un jeton ; vos données de trafic ne quittent jamais la machine.@@ -245,7 +255,15 @@ Toute l'interface est disponible en **français, anglais et espagnol** : utilise| 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 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 |+| Détection d'anomalies | Signale scans de ports, beaconing (C2 à intervalle régulier), exfiltration potentielle |+| Détection avancée | Heuristique de tunnel DNS, repérage de trafic en clair, déviation de baseline pays par application |+| Orchestration pare-feu | Règles de blocage (IP/CIDR/domaine/processus/port) appliquées au pare-feu OS — `netsh`/`iptables`/`pf`, persistées, compteurs de blocages |+| Mode lockdown | Bouton panique — signale & bloque tout le trafic sortant public, le LAN reste actif |+| Réponse à incident | Tuer / suspendre un processus, bloquer une IP — en un clic depuis le détail d'une connexion |+| Threat intelligence | Vérifs de réputation **opt-in** (AbuseIPDB / AlienVault OTX / VirusTotal) avec votre propre clé API — désactivé par défaut, résultats cachés |+| Audit de sécurité | Rapport de durcissement intégré — score, constats, recommandations en langage clair |+| Export forensique | Paquet d'investigation en un clic — arbre de processus + SHA-256 du binaire, historique & alertes associées |+| Webhook d'alertes | Relais **opt-in** des alertes warning/critiques vers Discord, Slack, Telegram ou tout endpoint || Attribution processus | Sachez quelle app génère quel trafic (top 5 par connexion) || Scanner LAN | Découverte passive via la table ARP système (aucun scan broadcast) || Score de confidentialité | Score en temps réel de l'exposition de votre trafic sortant |@@ -254,7 +272,7 @@ Toute l'interface est disponible en **français, anglais et espagnol** : utilise| Panneau Réglages | Langue, rétention, filtres, téléchargement GeoIP sous consentement, diagnostic || Détection de trackers | Listes de domaines par suffixe, livrées en fichiers de données éditables (`backend/classifier/lists/`) || Moniteur de débit | Sparkline MB/s en direct |-| UI FR / EN / ES | Interface entièrement trilingue, bascule en un clic |+| UI 8 langues | EN · FR · ES · DE · RU · JA · PT-BR · ZH-CN — bascule en un clic, locales dans `frontend/src/locales/` || Thème clair / sombre | Suit la préférence système par défaut, bascule manuelle persistée || Mise à jour auto | L'app bureau vérifie les releases GitHub (désactivable dans Réglages ; `SNITCH_NO_UPDATE=1`) || QUIC / HTTP/3 | Flux UDP/443 étiquetés honnêtement — le SNI QUIC est chiffré, jamais lu |@@ -291,14 +309,16 @@ Ou récupérez la dernière release : **[github.com/aixisstudio/Snitch/releases]- **Jeton API** — chaque endpoint REST et le WebSocket exigent un jeton. Electron le génère à chaque lancement ; sous Docker/navigateur il est affiché une fois dans les logs du backend et stocké dans `data/api_token.txt`. Ouvrez l'UI via `http://localhost:8000/?token=<JETON>` (ou saisissez-le à l'invite).- **Loopback uniquement par défaut** — l'API écoute sur `127.0.0.1` dans tous les modes. Ne mettez `SNITCH_BIND=0.0.0.0` que pour un accès LAN explicite (le jeton reste exigé).- **Liste blanche CORS/Origin WebSocket** — seuls `localhost:5173`, l'origine propre du backend et les pages `file://` d'Electron peuvent se connecter.-- **Géolocalisation 100 % hors ligne** — *aucune* recherche en ligne. DB-IP Lite ([CC BY 4.0](https://db-ip.com/db/lite.php)) est embarquée gzipée dans `backend/data/geo/` et auto-extraite vers `<data_dir>/geo/` au premier lancement — la géo fonctionne d'emblée, zéro appel réseau. Vous pouvez toujours déposer des `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) plus récents dans `<data_dir>/geo/`, ou télécharger une DB-IP Lite fraîche depuis Réglages (consentement explicite, seul appel sortant possible).-- **Toutes les données restent locales** — `snitch.db` (fenêtre glissante de 24 h, configurable via le réglage `retention_hours`) et `data/logs/snitch.log` ne quittent jamais la machine. Pas de télémétrie. Le **seul** appel sortant possible est le téléchargement opt-in de DB-IP Lite (Réglages → « Télécharger DB-IP Lite »), qui exige un clic explicite.-- **Réglages persistés** — filtres de ports, processus exclus, whitelist IP, langue et rétention sont stockés dans SQLite et restaurés au redémarrage.+- **Géolocalisation 100 % hors ligne** — *aucune* recherche en ligne. DB-IP Lite ([CC BY 4.0](https://db-ip.com/db/lite.php)) est embarquée gzipée dans `backend/data/geo/` et auto-extraite vers `<data_dir>/geo/` au premier lancement — la géo fonctionne d'emblée, zéro appel réseau. Vous pouvez toujours déposer des `GeoLite2-City.mmdb`/`GeoLite2-ASN.mmdb` (MaxMind) plus récents dans `<data_dir>/geo/`, ou télécharger une DB-IP Lite fraîche depuis Réglages (consentement explicite ; les autres appels sortants opt-in — threat intel, webhooks, mises à jour — sont listés dans PRIVACY.md).+- **Toutes les données restent locales** — `snitch.db` (fenêtre glissante de 24 h, configurable via le réglage `retention_hours`) et `data/logs/snitch.log` ne quittent jamais la machine. Pas de télémétrie. Chaque appel sortant est opt-in — téléchargement DB-IP Lite, vérifications threat-intel, webhooks et mises à jour sont chacun conditionnés à une action explicite ou un interrupteur (voir [PRIVACY.md](PRIVACY.md)).+- **Réglages persistés** — filtres de ports, processus exclus, whitelist IP, règles pare-feu, langue et rétention sont stockés dans SQLite et restaurés au redémarrage.+- **Règles pare-feu best-effort** — le backend pilote le pare-feu OS (`netsh advfirewall`, `iptables`, ancres `pf`) ; sans privilèges, la règle est conservée et évaluée pour la *visibilité* (alertes BLOCKED_ATTEMPT) et marquée « non appliquée » au lieu de simuler. Le lockdown conserve loopback + LAN pour garder l'UI joignable.+- **Threat intel & webhooks opt-in** — désactivés par défaut ; activer un fournisseur (AbuseIPDB/OTX/VirusTotal, votre propre clé) ou un webhook ajoute des appels sortants, documentés dans [PRIVACY.md](PRIVACY.md).- **Suppression d'alertes** — chaque alerte offre « Ignorer ce type/cet hôte » ; les règles sont persistées (`alert_suppressions`), appliquées avant émission, et gérables via `POST /alerts/ignore`, `DELETE /alerts/ignore`, `GET /alerts/ignore`.- **Historique** — les agrégats octets/paquets par minute, par hôte et par processus sont conservés dans SQLite (`host_history`, `process_history`) sur la fenêtre de rétention, et alimentent la vue par application ainsi que `GET /history/host/{ip}` et `GET /history/process/{nom}`.- **Diagnostic** — `GET /diagnostics` renvoie un instantané JSON du runtime (état de capture, géo, interface, versions, chemins) sans secrets ; le panneau Réglages peut l'exporter ou ouvrir le dossier des logs (Electron).- **Appareils LAN** découverts passivement via la table ARP système — aucun scan broadcast actif. Les noms sont appris de ce que les appareils diffusent eux-mêmes : mDNS `*.local` (Apple/Linux), LLMNR et noms NetBIOS (Windows), option hostname DHCP, plus la table de fabricants IEEE OUI complète hors ligne ; votre passerelle est détectée automatiquement comme routeur.-- Voir [docs/threat-model.md](docs/threat-model.md) pour le modèle de menace complet.+- Voir [docs/threat-model.md](docs/threat-model.md) pour le modèle de menace complet et [docs/FIREWALL.md](docs/FIREWALL.md) pour la suite sécurité (orchestration pare-feu, lockdown, threat intel, webhooks, audit, forensique).### Docker (Linux)diff --git a/ROADMAP.md b/ROADMAP.mdindex 4b1b841..453c871 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -13,6 +13,8 @@Also live / également en place : Docker image on GHCR, Homebrew tap (`brew install --cask aixisstudio/tap/snitch`), winget package [submitted](https://github.com/microsoft/winget-pkgs/pull/455520), zh-CN README, GitHub Discussions.+| **v1.2 (main, untagged)** | **Security & threat-hunting suite** — OS-firewall orchestration (rules IP/CIDR/domain/process/port via `netsh`/`iptables`/`pf`, best-effort privileges), lockdown panic switch, kill/suspend process actions, opt-in threat intel (AbuseIPDB/OTX), opt-in webhooks (Discord/Slack/Telegram/generic), DNS-tunnel & cleartext & country-baseline detection, security audit report, forensics export (process tree + SHA-256), 8-language UI (`locales/` files) / **suite sécurité & chasse aux menaces** — orchestration pare-feu OS, bouton lockdown, actions kill/suspend, threat intel opt-in, webhooks opt-in, détection tunnel DNS / trafic clair / déviation pays, audit de sécurité, export forensique, UI en 8 langues |+## 🚧 v1.x — in progress / en cours- [x] **Signed Windows installer** — CI wired for [SignPath](https://signpath.org) OSS (free Authenticode for approved projects); activates once the application is accepted — see `docs/SIGNING.md` / CI branchée sur SignPath OSS (signature Authenticode gratuite pour projets acceptés) ; s'active dès l'acceptation — voir `docs/SIGNING.md`@@ -31,17 +33,40 @@ Also live / également en place : Docker image on GHCR, Homebrew tap (`brew inst- ~~Per-process bandwidth alert~~ — shipped as `UPLOAD_SPIKE` / livré via `UPLOAD_SPIKE`- Custom alert rules in the UI / règles d'alerte personnalisées dans l'UI- ~~Light theme / thème clair~~ — shipped in v1.0.7 / livré en v1.0.7-- ~~More languages~~ — Spanish shipped; more welcome via `frontend/src/i18n.jsx` / espagnol livré ; d'autres bienvenues via `frontend/src/i18n.jsx`+- ~~More languages~~ — 8 locales shipped in `frontend/src/locales/`; more welcome via a single-file PR / 8 locales livrées dans `frontend/src/locales/` ; d'autres bienvenues via une PR d'un seul fichier- Optional remote pairing for headless hosts — consent-gated, token-protected / appairage optionnel d'hôtes sans écran — avec consentement et jeton- Map layers: ASN / organisation view / couches de carte : vue ASN / organisation+- Blocklist imports (StevenBlack hosts, EasyList) — needs a privacy/licensing review first / import de blocklists — revue vie privée/licence requise+- Firewall profiles (strict/travel vs developer/permissive) / profils pare-feu (strict/voyage vs dev/permissif)++## � Research — documented, not implemented / documenté, pas implémenté++Ideas that would take Snitch toward a desktop EDR/XDR. They are tracked+here honestly — **none of them is implemented**, each needs its own design,+native components and often a second binary artifact / Idées qui mèneraient+Snitch vers un EDR/XDR de bureau. Suivies ici honnêtement — **aucune n'est+implémentée**, chacune exige sa conception, des composants natifs et souvent+un second artefact binaire :++- **eBPF probes (Linux)** — `sys_enter_connect`/`accept` kernel-space capture, bypass-resistant; needs a compiled BPF program + root / sondes eBPF — capture noyau in-contournable ; exige un programme BPF compilé + root+- **WFP callout (Windows)** — real kernel packet filtering instead of `netsh` rule orchestration; needs a signed kernel driver / callout WFP — filtrage noyau réel au lieu de l'orchestration `netsh` ; exige un driver signé+- **NetworkExtension (macOS)** — `NEFilterProvider` for per-bundle filtering; needs Apple Developer ID + entitlements / `NEFilterProvider` pour filtrer par bundle ; exige Developer ID + entitlements+- **Memory/flow correlation** — unsigned-DLL / `PAGE_EXECUTE_READWRITE` inspection crossed with suspicious connections / corrélation mémoire/flux — inspection des régions exécutables croisée avec les connexions+- **Dynamic Taint Analysis** — prove exfiltration byte-for-byte; heavy research / analyse de teinture dynamique — prouver l'exfiltration octet par octet ; recherche lourde+- **Local SecOps SLM** — a 1–3 B param model explaining alerts in natural language / SLM SecOps local — un modèle 1–3 Md paramètres expliquant les alertes en langage naturel+- **ZKP fleet intel** — share detections across a peer fleet without revealing endpoints / intel de flotte en ZKP — partager les détections sans révéler les endpoints+- **PMU/hardware counters** — ransomware tells below the OS (speculation, crypto bursts) / compteurs matériels PMU — signaux de ransomware sous l'OS+- **Merkle integrity of loaded modules** — detect hot-patched DLLs before first packet / intégrité Merkle des modules chargés — détecter les DLL patchées avant le premier paquet+- **Sinkholing / micro-containment** — redirect a suspicious flow to a local honeypot instead of killing it / sinkholing / micro-confinement — rediriger un flux suspect vers un honeypot local au lieu de le tuer+- **PCAP export** stays in scope above / l'export PCAP reste dans le périmètre ci-dessus## 🚫 Out of scope / hors périmètreDeliberately, by design / volontairement, par conception :-- **Blocking / firewall rules** — Snitch *observes and explains*; it does not block. Pair it with [OpenSnitch](https://github.com/evilsocket/opensnitch) or [Portmaster](https://safing.io/) if you need blocking. / **Blocage / pare-feu** — Snitch *observe et explique*, il ne bloque pas. Combinez-le avec OpenSnitch ou Portmaster si vous voulez bloquer.- **Telemetry, analytics, accounts, cloud sync** — never. / **Télémétrie, analytics, comptes, synchro cloud** — jamais.- **Passive network-wide IDS** — Snitch watches *this* machine, not the whole network. / **IDS passif à l'échelle du réseau** — Snitch observe *cette* machine, pas tout le réseau.+- **User-space packet filtering** — blocking is delegated to the OS-native firewall (or future kernel components), never reimplemented. / **Filtrage de paquets en user-space** — le blocage est délégué au pare-feu natif de l'OS (ou à de futurs composants noyau), jamais réimplémenté.## 🤝 Contributing / contribuerdiff --git a/backend/api/main.py b/backend/api/main.pyindex 909cfc5..de34e4d 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -73,8 +73,9 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Optional-from fastapi import Depends, FastAPI, WebSocket, WebSocketDisconnect+from fastapi import Depends, FastAPI, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddleware+from fastapi.responses import PlainTextResponsefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel, Field@@ -87,7 +88,11 @@ from resolver.dns_geo import (enrich_ip, is_private, learn_dns_answers,learn_sni, lookup_domain)from scanner.arp_scanner import ARPScanner, Device, default_gateway as _default_gatewayfrom scanner.arp_scanner import READ_STATS as _arp_stats-from detection.anomaly import AnomalyDetector+from detection.anomaly import AnomalyDetector, Alert+from detection.firewall import FirewallManager+from detection.threatintel import ThreatIntel+from api.notify import notifier+from paths import data_dirimport storage.db as dbfrom version import __version__@@ -105,6 +110,12 @@ enrichment_cache: dict[str, dict] = {} # EN: remote_ip -> geo/hostname result_inflight_geo: set[str] = set() # EN: IPs with a running enrich task# FR: IP avec une tâche d'enrichissement en coursdetector = AnomalyDetector()+# EN: Firewall orchestration + threat-intel reputation client — both loaded+# from persisted settings at startup (see _load_settings).+# FR: Orchestration pare-feu + client de réputation threat-intel — chargés+# des réglages persistés au démarrage (voir _load_settings).+fw = FirewallManager(data_dir())+ti = ThreatIntel()_loop: asyncio.AbstractEventLoop | None = None_sniffer: PacketSniffer | None = None_scanner: ARPScanner | None = None@@ -183,6 +194,38 @@ class IgnoreBody(BaseModel):ip: Optional[str] = None+class FirewallRuleBody(BaseModel):+ """EN: /firewall/rules payload — block an IP, domain suffix or process.+ FR: Charge utile de /firewall/rules — bloquer une IP, un suffixe de+ domaine ou un processus."""+ kind: str+ value: str+++class FirewallToggleBody(BaseModel):+ """EN: Enable/disable a single rule. / FR: Activer/désactiver une règle."""+ enabled: bool = True+++class LockdownBody(BaseModel):+ """EN: /firewall/lockdown payload — panic switch on/off.+ FR: Charge utile de /firewall/lockdown — bouton panique on/off."""+ on: bool = True+++class PidBody(BaseModel):+ """EN: /processes/* payload — target PID for kill/suspend.+ FR: Charge utile de /processes/* — PID cible pour tuer/suspendre."""+ pid: int+++class ThreatCheckBody(BaseModel):+ """EN: /security/threat_check payload — manual IP/domain reputation check.+ FR: Charge utile de /security/threat_check — vérification manuelle de+ réputation d'une IP/domaine."""+ ip: str++class GeoDownloadBody(BaseModel):"""EN: /geo/download payload — explicit consent is REQUIRED, this is theonly outbound call in the whole app. / FR: Charge utile de /geo/download —@@ -578,6 +621,55 @@ def _geo_for(ip: str) -> dict:return {"ip": ip, "hostname": lookup_domain(ip), "private": is_private(ip)}+async def _ti_check(ip: str) -> None:+ """+ EN: Background threat-intel lookup for a newly-seen host. Runs the+ blocking HTTP call in an executor; on a suspicious/malicious verdict+ it raises, logs and broadcasts a THREAT_HIT alert. Silent on errors —+ reputation is a bonus, never a dependency.+ FR: Vérification threat-intel en fond pour un hôte nouvellement vu.+ L'appel HTTP bloquant tourne dans un executor ; sur verdict suspect/+ malveillant, une alerte THREAT_HIT est émise, journalisée et diffusée.+ Silencieux en erreur — la réputation est un bonus, pas une dépendance.+ """+ loop = asyncio.get_running_loop()+ try:+ verdict = await loop.run_in_executor(None, ti.check, ip)+ except Exception as exc:+ logger.debug("ti.check failed for %s: %s", ip, exc)+ return+ if not verdict or verdict.get("verdict") not in ("malicious", "suspicious"):+ return+ alert = Alert(+ type="THREAT_HIT",+ severity="critical" if verdict["verdict"] == "malicious" else "warning",+ message=f"Threat intel: {ip} reported {verdict['verdict']} "+ f"({verdict.get('provider', '?')}: {verdict.get('detail', '')})",+ node_id=ip,+ details=verdict,+ )+ _flag_alert(alert, nodes)+ d = alert.to_dict()+ db.log_alert(d)+ await broadcast({"type": "alert", "alert": d})+ await _notify(d)+++async def _notify(alert_dict: dict) -> None:+ """+ EN: Forward one alert to the configured webhook (if any) — the blocking+ POST happens in an executor so detection is never delayed.+ FR: Relayer une alerte vers le webhook configuré (le cas échéant) — le+ POST bloquant passe par un executor pour ne jamais retarder la+ détection.+ """+ loop = asyncio.get_running_loop()+ try:+ await loop.run_in_executor(None, notifier.dispatch, alert_dict)+ except Exception as exc:+ logger.debug("webhook notify failed: %s", exc)++def _process_batch(packets: list[Packet]) -> None:"""EN: One drain tick — runs on the event-loop thread. Per packet: filters,@@ -707,6 +799,10 @@ def _process_batch(packets: list[Packet]) -> None:proc = procs.setdefault(pkt.process_name, {"bytes": 0, "packets": 0})proc["bytes"] += pkt.sizeproc["packets"] += 1+ # EN: Last-seen PID for the kill/suspend actions in the UI.+ # FR: Dernier PID vu pour les actions tuer/suspendre de l'UI.+ if pkt.pid:+ proc["pid"] = pkt.pidedge_id = f"local-{node_id}-{pkt.protocol}"edge = edges.setdefault(edge_id, {@@ -734,6 +830,45 @@ def _process_batch(packets: list[Packet]) -> None:alert_dict = alert.to_dict()db.log_alert(alert_dict)out_alerts.append(alert_dict)+ # EN: Relay warning/critical alerts to the external webhook (opt-in).+ # FR: Relayer les alertes warning/critical vers le webhook externe+ # (opt-in).+ asyncio.get_running_loop().create_task(_notify(alert_dict))+ # EN: A NEW_HOST alert marks the first sighting — the right moment+ # for an opt-in reputation lookup on public IPs.+ # FR: Une alerte NEW_HOST marque une première vue — le bon moment+ # pour une vérif de réputation opt-in sur les IP publiques.+ if (alert.type == "NEW_HOST" and ti.enabled+ and not is_private(remote_ip)+ and ti.begin_check(remote_ip)):+ asyncio.get_running_loop().create_task(_ti_check(remote_ip))++ # EN: Firewall visibility — a packet matching an active rule (or the+ # lockdown) raises BLOCKED_ATTEMPT. This flags policy hits; actual+ # dropping requires the optional privileged rule sync documented+ # in /firewall/status.+ # FR: Visibilité pare-feu — un paquet correspondant à une règle active+ # (ou au lockdown) lève BLOCKED_ATTEMPT. Cela signale les violations+ # de politique ; le drop réel exige la synchro privilégiée+ # documentée dans /firewall/status.+ fw_rule = fw.check_packet(pkt)+ if fw_rule:+ ctx = fw.note_blocked(fw_rule["id"])+ if ctx:+ matched = ctx.get("rule") or fw_rule+ a = Alert(+ type="BLOCKED_ATTEMPT", severity="warning",+ message=f"Firewall rule matched: {matched.get('value')} "+ f"({matched.get('kind')}) — attempt #{ctx['count']}"+ + (" by " + pkt.process_name if pkt.process_name else ""),+ node_id=remote_ip,+ details={"rule": matched, "process": pkt.process_name,+ "direction": pkt.direction},+ )+ _flag_alert(a, nodes)+ ad = a.to_dict()+ db.log_alert(ad)+ out_alerts.append(ad)touched_nodes[node_id] = nodetouched_edges[edge_id] = edge@@ -742,6 +877,7 @@ def _process_batch(packets: list[Packet]) -> None:"protocol": pkt.protocol, "size": pkt.size,"direction": pkt.direction, "process": pkt.process_name,"remote_port": pkt.remote_port, "sni": pkt.sni,+ "pid": pkt.pid,"timestamp": pkt.timestamp,})@@ -938,6 +1074,11 @@ def _flush_loop() -> None:time.sleep(10)try:db.flush()+ # EN: Snapshot learned process baselines — they power the+ # baseline-deviation alerts across restarts.+ # FR: Sauvegarder les baselines de processus apprises — elles+ # alimentent les alertes de déviation entre redémarrages.+ db.set_setting("app_baselines", detector.dump_baselines())except Exception as exc:logger.error("db flush failed: %s", exc)@@ -1056,6 +1197,18 @@ def _load_settings() -> None:detector.set_watchlist(_watchlist)detector.set_upload_threshold_mb(float(db.get_setting("upload_threshold_mb", 50)))+ # EN: Security modules — firewall rules/lockdown, opt-in threat intel,+ # learned process baselines and the external webhook.+ # FR: Modules de sécurité — règles/lockdown pare-feu, threat intel opt-in,+ # baselines de processus apprises et webhook externe.+ fw.load(db.get_setting("firewall_rules", []) or [],+ bool(db.get_setting("firewall_lockdown", False)))+ ti.configure(db.get_setting("ti_provider", "none") or "none",+ db.get_setting("ti_api_key", "") or "")+ detector.load_baselines(db.get_setting("app_baselines", {}) or {})+ notifier.configure(db.get_setting("webhook_url", "") or "",+ bool(db.get_setting("webhook_enabled", False)),+ db.get_setting("telegram_chat_id", "") or "")if _port_filter:logger.info("restored port filter: %s", _port_filter)@@ -1217,6 +1370,17 @@ async def post_settings(body: SettingsBody) -> dict:detector.set_upload_threshold_mb(float(value))except (TypeError, ValueError):pass+ # EN: Live-apply security settings — no restart needed when the user+ # toggles a provider, rotates a key or flips the webhook switch.+ # FR: Appliquer à chaud les réglages de sécurité — pas de redémarrage+ # quand l'utilisateur change de fournisseur, de clé ou de webhook.+ if key in ("ti_provider", "ti_api_key"):+ ti.configure(db.get_setting("ti_provider", "none") or "none",+ db.get_setting("ti_api_key", "") or "")+ if key in ("webhook_url", "webhook_enabled", "telegram_chat_id"):+ notifier.configure(db.get_setting("webhook_url", "") or "",+ bool(db.get_setting("webhook_enabled", False)),+ db.get_setting("telegram_chat_id", "") or "")return {"ok": True}@app.get("/capture/status", dependencies=_AUTH)@@ -1695,6 +1859,481 @@ async def geo_status() -> dict:return {"databases": present, "dir": str(geo_dir)}+# ── Security: firewall / process actions / threat intel / audit / forensics ──+# EN: The firewall API manages user rules (IP / domain / process) and the+# lockdown panic switch. Rules are MATCHED live so the UI can show which+# connections violate policy; actually dropping packets needs the+# optional privileged sync shipped in tools/ (documented honestly in+# /firewall/status — we never claim kernel enforcement we don't have).+# FR: L'API pare-feu gère les règles utilisateur (IP / domaine / processus)+# et le bouton panique. Les règles sont ÉVALUÉES en direct pour montrer+# quelles connexions violent la politique ; le drop réel exige la synchro+# privilégiée optionnelle de tools/ (documenté honnêtement dans+# /firewall/status — jamais de prétention à une application noyau absente).+[email protected]("/firewall/status", dependencies=_AUTH)+async def firewall_status() -> dict:+ """EN: Rules, lockdown and platform capability report.+ FR: Règles, lockdown et rapport de capacité de la plateforme."""+ return fw.status()++[email protected]("/firewall/rules", dependencies=_AUTH)+async def firewall_rules() -> dict:+ """EN: All rules + lockdown flag + privilege sync status.+ FR: Toutes les règles + drapeau lockdown + état de la synchro privilégiée."""+ rules, lockdown = fw.serialized()+ return {"rules": rules, "lockdown": lockdown, "supported": fw.supported()}++[email protected]("/firewall/rules", dependencies=_AUTH)+async def firewall_add_rule(body: FirewallRuleBody) -> dict:+ """EN: Create a rule {kind: ip|domain|process, value}. Persisted.+ FR: Créer une règle {kind: ip|domain|process, value}. Persistée."""+ loop = asyncio.get_running_loop()+ try:+ rule = await loop.run_in_executor(None, fw.add_rule, body.kind, body.value)+ except ValueError as exc:+ raise HTTPException(400, str(exc))+ rules, lockdown = fw.serialized()+ db.set_setting("firewall_rules", rules)+ await broadcast({"type": "firewall", "rules": rules, "lockdown": lockdown})+ return {"rule": rule, "rules": rules}++[email protected]("/firewall/rules/{rule_id}", dependencies=_AUTH)+async def firewall_del_rule(rule_id: str) -> dict:+ """EN: Delete a rule. / FR: Supprimer une règle."""+ loop = asyncio.get_running_loop()+ removed = await loop.run_in_executor(None, fw.remove_rule, rule_id)+ if not removed:+ raise HTTPException(404, "rule not found")+ rules, lockdown = fw.serialized()+ db.set_setting("firewall_rules", rules)+ await broadcast({"type": "firewall", "rules": rules, "lockdown": lockdown})+ return {"ok": True, "rules": rules}++[email protected]("/firewall/rules/{rule_id}/toggle", dependencies=_AUTH)+async def firewall_toggle_rule(rule_id: str, body: FirewallToggleBody) -> dict:+ """EN: Enable/disable a rule without deleting it.+ FR: Activer/désactiver une règle sans la supprimer."""+ loop = asyncio.get_running_loop()+ ok = await loop.run_in_executor(None, fw.toggle_rule, rule_id, body.enabled)+ if not ok:+ raise HTTPException(404, "rule not found")+ rules, lockdown = fw.serialized()+ db.set_setting("firewall_rules", rules)+ await broadcast({"type": "firewall", "rules": rules, "lockdown": lockdown})+ return {"ok": True, "rules": rules}++[email protected]("/firewall/lockdown", dependencies=_AUTH)+async def firewall_lockdown(body: LockdownBody) -> dict:+ """EN: Panic switch — while ON, every outbound packet is flagged+ BLOCKED_ATTEMPT and (with privilege sync) actually dropped.+ A LOCKDOWN alert is broadcast so every connected client shows it.+ FR: Bouton panique — actif, chaque paquet sortant est signalé+ BLOCKED_ATTEMPT et (avec la synchro privilégiée) réellement droppé.+ Une alerte LOCKDOWN est diffusée pour l'afficher sur tous les clients."""+ loop = asyncio.get_running_loop()+ res = await loop.run_in_executor(None, fw.set_lockdown, body.on)+ db.set_setting("firewall_lockdown", res["lockdown"])+ if body.on:+ alert = Alert(type="LOCKDOWN", severity="critical",+ message="Lockdown mode ENABLED — all outbound traffic blocked",+ details={"applied": res["ok"], "error": res["error"]})+ d = alert.to_dict()+ db.log_alert(d)+ await broadcast({"type": "alert", "alert": d})+ rules, lockdown = fw.serialized()+ await broadcast({"type": "firewall", "rules": rules, "lockdown": lockdown})+ return res++[email protected]("/processes/kill", dependencies=_AUTH)+async def kill_process(body: PidBody) -> dict:+ """EN: Kill a process by PID — incident-response action. Refuses to kill+ PIDs 0..3 and Snitch itself. Requires normal OS privileges.+ FR: Tuer un processus par PID — action de réponse à incident. Refuse les+ PID 0..3 et Snitch lui-même. Exige les privilèges OS usuels."""+ import psutil+ if body.pid <= 3 or body.pid == os.getpid():+ raise HTTPException(400, "refusing to kill a system/critical pid")+ loop = asyncio.get_running_loop()++ def _do() -> str:+ p = psutil.Process(body.pid)+ name = p.name()+ p.kill()+ return name+ try:+ name = await loop.run_in_executor(None, _do)+ except Exception as exc:+ raise HTTPException(400, f"kill failed: {exc}")+ return {"ok": True, "pid": body.pid, "name": name}++[email protected]("/processes/suspend", dependencies=_AUTH)+async def suspend_process(body: PidBody) -> dict:+ """EN: Suspend/resume a process by PID (SIGSTOP/SIGCONT semantics).+ FR: Suspendre/reprendre un processus par PID (sémantique SIGSTOP/SIGCONT)."""+ import psutil+ if body.pid <= 3 or body.pid == os.getpid():+ raise HTTPException(400, "refusing to suspend a system/critical pid")+ loop = asyncio.get_running_loop()++ def _do() -> dict:+ p = psutil.Process(body.pid)+ name = p.name()+ if p.status() == "stopped":+ p.resume()+ return {"name": name, "suspended": False}+ p.suspend()+ return {"name": name, "suspended": True}+ try:+ res = await loop.run_in_executor(None, _do)+ except Exception as exc:+ raise HTTPException(400, f"suspend failed: {exc}")+ return {"ok": True, "pid": body.pid, **res}++[email protected]("/security/ti", dependencies=_AUTH)+async def ti_status() -> dict:+ """EN: Threat-intel configuration (provider, cache size, key masked).+ FR: Configuration threat-intel (fournisseur, taille du cache, clé masquée)."""+ return ti.config()++[email protected]("/security/threat_check", dependencies=_AUTH)+async def threat_check(body: ThreatCheckBody) -> dict:+ """EN: Manual reputation check for one IP/domain. Only actually queries+ the provider when threat intel is enabled — otherwise it reports the+ disabled state (and never makes a call).+ FR: Vérification manuelle de réputation pour une IP/domaine. N'interroge+ le fournisseur que si la threat intel est activée — sinon renvoie+ l'état désactivé (et ne fait aucun appel)."""+ loop = asyncio.get_running_loop()+ verdict = await loop.run_in_executor(None, ti.check, body.ip)+ return {"verdict": verdict, "config": ti.config()}++[email protected]("/security/audit", dependencies=_AUTH)+async def security_audit() -> dict:+ """EN: Hardening report computed from the last 500 alerts + live graph:+ alert-type breakdown, high-risk-country contacts, cleartext usage,+ unseen domains, firewall posture, and a defensible 0–100 score.+ FR: Rapport de durcissement calculé sur les 500 dernières alertes + le+ graphe : répartition par type, contacts vers pays à risque, trafic en+ clair, domaines sans nom, posture pare-feu et score 0–100."""+ loop = asyncio.get_running_loop()+ alerts = await loop.run_in_executor(None, db.get_alerts, 500)+ counts: dict[str, int] = {}+ for a in alerts:+ counts[a.get("type", "?")] = counts.get(a.get("type", "?"), 0) + 1+ critical = sum(1 for a in alerts if a.get("severity") == "critical")+ warning = sum(1 for a in alerts if a.get("severity") == "warning")++ # EN: Nodes currently on the graph whose geo country is in the high-risk+ # watchlist — a finding worth surfacing, not an accusation.+ # FR: Nœuds du graphe dont le pays géolocalisé est dans la liste à risque+ # — un constat à remonter, pas une accusation.+ risky = sorted({+ ip for ip, n in nodes.items()+ if ip != "local" and (n.get("country_code") or "").upper()+ in {"RU", "KP", "IR", "BY", "CU", "SY", "AF", "MM", "VE", "NI"}+ })+ unlabeled = sorted({+ ip for ip, n in nodes.items()+ if ip != "local" and not n.get("label") and not n.get("hostname")+ })++ rules, lockdown = fw.serialized()+ active_rules = sum(1 for r in rules if r.get("enabled"))+ blocked_total = sum(r.get("blocked_total", 0) for r in rules)++ score = 100 - min(60, critical * 8) - min(20, warning) \+ - min(10, len(risky)) - (5 if lockdown else 0)+ score = max(0, score)++ return {+ "score": score,+ "period": "last 500 alerts",+ "alert_counts": counts,+ "critical": critical, "warning": warning,+ "findings": {+ "high_risk_countries": risky,+ "unresolved_hosts": unlabeled[:50],+ "cleartext_alerts": counts.get("CLEARTEXT", 0),+ "dns_tunnel_alerts": counts.get("DNS_TUNNEL", 0),+ "threat_hits": counts.get("THREAT_HIT", 0),+ },+ "firewall": {+ "active_rules": active_rules,+ "lockdown": lockdown,+ "blocked_attempts": blocked_total,+ "supported": fw.supported(),+ "platform": fw.status().get("platform"),+ },+ "threat_intel": ti.config(),+ "recommendations": _audit_recommendations(+ counts, risky, unlabeled, active_rules, lockdown),+ }+++def _audit_recommendations(counts: dict, risky: list, unlabeled: list,+ active_rules: int, lockdown: bool) -> list[dict]:+ """EN: Plain-language next steps derived from the findings.+ FR: Étapes concrètes en langage clair dérivées des constats."""+ recs: list[dict] = []+ if lockdown:+ recs.append({"level": "info", "text": "Lockdown is ON — every outbound "+ "attempt is being flagged. / Lockdown actif — chaque "+ "tentative sortante est signalée."})+ if counts.get("CLEARTEXT"):+ recs.append({"level": "high", "text": "Plain-text traffic on port 80 "+ "detected — prefer HTTPS or flag the destination. / "+ "Trafic en clair sur le port 80 détecté — privilégier "+ "HTTPS ou signaler la destination."})+ if counts.get("DNS_TUNNEL"):+ recs.append({"level": "high", "text": "Possible DNS tunnelling — "+ "inspect the flagged process and consider blocking it. / "+ "Tunnel DNS possible — inspecter le processus signalé et "+ "envisager de le bloquer."})+ if counts.get("THREAT_HIT"):+ recs.append({"level": "high", "text": "Threat intel flagged hosts — "+ "add firewall rules for the reported IPs. / La threat "+ "intel a signalé des hôtes — ajouter des règles pare-feu "+ "pour les IP rapportées."})+ if counts.get("BEACON"):+ recs.append({"level": "medium", "text": "Regular-interval connections "+ "(beaconing) observed — review the flagged process's "+ "executable hash in the forensics export. / Connexions à "+ "intervalle régulier (beaconing) observées — vérifier le "+ "hash de l'exécutable via l'export forensique."})+ if risky:+ recs.append({"level": "medium", "text": "Connections to high-risk "+ "countries observed — verify they match expected services "+ "(news, CDN, gaming). / Connexions vers des pays à risque "+ "observées — vérifier qu'elles correspondent à des "+ "services attendus."})+ if active_rules == 0 and not lockdown:+ recs.append({"level": "low", "text": "No firewall rules configured — "+ "create one from any connection row to harden egress. / "+ "Aucune règle pare-feu — en créer une depuis une ligne de "+ "connexion pour durcir les sorties."})+ if len(unlabeled) > 20:+ recs.append({"level": "low", "text": "Many hosts have no resolved "+ "domain — check the GeoIP database is downloaded. / "+ "Beaucoup d'hôtes sans domaine résolu — vérifier que la "+ "base GeoIP est téléchargée."})+ return recs++[email protected]("/forensics/export", dependencies=_AUTH)+async def forensics_export(process: Optional[str] = None,+ ip: Optional[str] = None,+ format: str = "json"):+ """EN: One-click investigation bundle — process tree + SHA-256 of the+ executable, matching alerts and traffic history. format=json (default)+ returns the bundle; format=csv a flat spreadsheet; format=stix a+ minimal STIX 2.1 bundle (indicators + observed-data) for SIEM import.+ Local data only; nothing is sent anywhere.+ FR: Paquet d'investigation en un clic — arbre de processus + SHA-256 de+ l'exécutable, alertes et historique associés. format=json (défaut)+ renvoie le bundle ; format=csv un tableur plat ; format=stix un+ bundle STIX 2.1 minimal (indicateurs + observed-data) pour SIEM.+ Données locales uniquement ; rien n'est envoyé nulle part."""+ import hashlib+ import psutil+ loop = asyncio.get_running_loop()+ bundle: dict = {+ "generated_at": datetime.now(timezone.utc).isoformat(),+ "version": __version__,+ "host": socket.gethostname(),+ "processes": [],+ "alerts": [],+ "history": {},+ }++ def _sha256(path: str) -> Optional[str]:+ try:+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for chunk in iter(lambda: f.read(1 << 20), b""):+ h.update(chunk)+ return h.hexdigest()+ except Exception:+ return None++ if process:+ def _procs() -> list[dict]:+ out = []+ for p in psutil.process_iter(["pid", "name", "exe", "ppid",+ "cmdline", "create_time"]):+ try:+ info = p.info+ if info["name"] != process:+ continue+ chain, cur = [], p.ppid()+ for _ in range(8):+ if not cur:+ break+ try:+ par = psutil.Process(cur)+ chain.append({"pid": par.pid, "name": par.name()})+ cur = par.ppid()+ except Exception:+ break+ out.append({+ "pid": info["pid"], "name": info["name"],+ "exe": info["exe"],+ "sha256": _sha256(info["exe"]) if info["exe"] else None,+ "cmdline": info["cmdline"],+ "started": info["create_time"],+ "parents": chain,+ })+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ continue+ return out+ bundle["processes"] = await loop.run_in_executor(None, _procs)+ bundle["history"]["process"] = await loop.run_in_executor(+ None, db.get_history, "process", process, 1440)+ if ip:+ bundle["history"]["host"] = await loop.run_in_executor(+ None, db.get_history, "host", ip, 1440)+ bundle["geo"] = enrichment_cache.get(ip)++ all_alerts = await loop.run_in_executor(None, db.get_alerts, 500)+ # EN: No filter → export every stored alert; with a filter, keep the+ # alerts mentioning the process or tied to the node.+ # FR: Sans filtre → exporter toutes les alertes stockées ; avec filtre,+ # garder celles mentionnant le processus ou liées au nœud.+ bundle["alerts"] = all_alerts if not (process or ip) else [+ a for a in all_alerts+ if (process and process in (a.get("message") or "")+ + str(a.get("details") or ""))+ or (ip and a.get("node_id") == ip)+ ]++ if format == "csv":+ return _forensics_csv(bundle)+ if format == "stix":+ return _forensics_stix(bundle, ip=ip)+ return bundle+++def _forensics_csv(bundle: dict) -> PlainTextResponse:+ """EN: Flatten the bundle into one CSV (section, key/value rows) —+ spreadsheet- and grep-friendly.+ FR: Aplatir le bundle en un CSV (section, lignes clé/valeur) — lisible+ en tableur comme en grep."""+ import csv+ import io+ buf = io.StringIO()+ w = csv.writer(buf)+ w.writerow(["section", "field", "value"])+ w.writerow(["meta", "generated_at", bundle["generated_at"]])+ w.writerow(["meta", "version", bundle["version"]])+ w.writerow(["meta", "host", bundle["host"]])+ for p in bundle.get("processes", []):+ for field in ("pid", "name", "exe", "sha256", "cmdline", "started"):+ val = p.get(field)+ w.writerow(["process", field,+ " ".join(val) if isinstance(val, list) else val])+ for par in p.get("parents", []):+ w.writerow(["process", "parent",+ f"{par.get('name')} (pid {par.get('pid')})"])+ for section, rows in (bundle.get("history") or {}).items():+ for row in rows:+ w.writerow([f"history_{section}", row.get("bucket", ""),+ json.dumps(row, ensure_ascii=False)])+ for a in bundle.get("alerts", []):+ w.writerow(["alert", a.get("type", ""), a.get("message", "")])+ return PlainTextResponse(+ buf.getvalue(), media_type="text/csv",+ headers={"Content-Disposition":+ 'attachment; filename="snitch-forensics.csv"'})+++def _forensics_stix(bundle: dict, ip: Optional[str] = None) -> dict:+ """EN: Minimal STIX 2.1 bundle — an identity for Snitch, indicators for+ the flagged IPs/hashes and observed-data sightings. Enough for a+ SIEM to ingest; deliberately not a full graph.+ FR: Bundle STIX 2.1 minimal — une identity pour Snitch, des indicateurs+ pour les IP/hashes signalés et des observed-data. Suffisant pour un+ SIEM ; volontairement pas un graphe complet."""+ import uuid+ ts = bundle["generated_at"]+ _uid = lambda s: str(uuid.uuid5(uuid.NAMESPACE_DNS, f"snitch.local/{s}"))+ objects: list[dict] = [{+ "type": "identity", "spec_version": "2.1",+ "id": f"identity--{_uid('exporter')}",+ "created": ts, "modified": ts,+ "name": "Snitch local forensics export",+ "identity_class": "system",+ }]+ # EN: One indicator per flagged IP (alert node_id that looks like an+ # address) + one per process hash — STIX patterning expressions.+ # FR: Un indicateur par IP signalée (node_id d'alerte ressemblant à une+ # adresse) + un par hash de processus — expressions STIX patterning.+ seen: set[str] = set()+ for i, a in enumerate(bundle.get("alerts", [])):+ node = a.get("node_id") or ""+ try:+ ipaddress.ip_address(node)+ except ValueError:+ continue+ if node in seen:+ continue+ seen.add(node)+ objects.append({+ "type": "indicator", "spec_version": "2.1",+ "id": f"indicator--{_uid(node)}",+ "created": ts, "modified": ts,+ "name": f"Snitch alert: {a.get('type', 'ALERT')} → {node}",+ "description": a.get("message", "")[:500],+ "pattern": f"[ipv4-addr:value = '{node}']"+ if ":" not in node+ else f"[ipv6-addr:value = '{node}']",+ "pattern_type": "stix",+ "valid_from": ts,+ })+ if ip:+ try:+ ipaddress.ip_address(ip)+ objects.append({+ "type": "observed-data", "spec_version": "2.1",+ "id": f"observed-data--{_uid('obs/' + ip)}",+ "created": ts, "modified": ts,+ "first_observed": ts, "last_observed": ts,+ "number_observed": 1,+ "objects": {+ "0": {"type": "ipv4-addr" if ":" not in ip else "ipv6-addr",+ "value": ip},+ },+ })+ except ValueError:+ pass+ for i, p in enumerate(bundle.get("processes", [])):+ if not p.get("sha256"):+ continue+ objects.append({+ "type": "indicator", "spec_version": "2.1",+ "id": f"indicator--{_uid('sha256/' + p['sha256'])}",+ "created": ts, "modified": ts,+ "name": f"Snitch process: {p.get('name')}",+ "pattern": f"[file:hashes.'SHA-256' = '{p['sha256']}']",+ "pattern_type": "stix",+ "valid_from": ts,+ })+ return {+ "type": "bundle",+ "id": f"bundle--{_uid('bundle/' + ts)}",+ "objects": objects,+ }++# ── WebSocket ────────────────────────────────────────────────────────────────@app.websocket("/ws")diff --git a/backend/api/notify.py b/backend/api/notify.pynew file mode 100644index 0000000..6b2b19e--- /dev/null+++ b/backend/api/notify.py@@ -0,0 +1,87 @@+"""+EN: External alert webhooks — OPT-IN. When the user configures a webhook URL+ (Discord channel webhook, Slack incoming webhook, Telegram bot URL or any+ generic endpoint), warning/critical alerts are POSTed there in real time.+ This is an outbound network call made ONLY when explicitly configured —+ documented in PRIVACY.md.++ Payloads are auto-shaped:+ * Discord/Slack → {"content": "**[warning]** BEACON — …"}+ * Telegram → {"chat_id": <from `telegram_chat_id` setting>, "text": "…"}+ * generic → full alert JSON {"alert": {...}, "source": "snitch"}++FR: Webhooks d'alerte externes — OPT-IN. Quand l'utilisateur configure une+ URL (webhook de canal Discord, incoming webhook Slack, URL de bot+ Telegram ou endpoint générique), les alertes warning/critical y sont+ POSTées en temps réel. C'est un appel sortant fait UNIQUEMENT si+ explicitement configuré — documenté dans PRIVACY.md.+"""++from __future__ import annotations++import json+import logging+import threading+import urllib.request+from typing import Optional++logger = logging.getLogger("snitch.notify")++# EN: Only these severities are forwarded — info alerts would spam channels.+# FR: Seules ces sévérités sont relayées — les infos spammeraient les canaux.+_FORWARD = {"warning", "critical"}+_TIMEOUT_S = 8+++class WebhookNotifier:+ """EN: Holds webhook settings + dispatches alert payloads.+ FR: Définit les réglages webhook + envoie les payloads d'alerte."""++ def __init__(self):+ self._lock = threading.Lock()+ self._url = ""+ self._enabled = False+ self._chat_id = ""++ def configure(self, url: str, enabled: bool, chat_id: str = "") -> None:+ with self._lock:+ self._url = (url or "").strip()+ self._enabled = bool(enabled)+ self._chat_id = (chat_id or "").strip()++ def config(self) -> dict:+ with self._lock:+ return {"enabled": self._enabled,+ "url_set": bool(self._url),+ "url_masked": (self._url[:32] + "…") if len(self._url) > 32 else self._url,+ "chat_id_set": bool(self._chat_id)}++ def dispatch(self, alert: dict) -> None:+ """EN: Synchronous POST — must run in an executor, never on the event+ loop. Silent on failure: alerting must never break detection.+ FR: POST synchrone — à lancer dans un executor, jamais sur la boucle.+ Silencieux en échec : l'alerting ne doit jamais casser la détection."""+ with self._lock:+ url, enabled, chat_id = self._url, self._enabled, self._chat_id+ if not enabled or not url or alert.get("severity") not in _FORWARD:+ return+ text = f"[{alert.get('severity','').upper()}] {alert.get('type')}: {alert.get('message')}"+ if "discord.com" in url or "slack.com" in url:+ payload = {"content": f"**{text}**"}+ elif "api.telegram.org" in url:+ payload = {"text": text}+ if chat_id:+ payload["chat_id"] = chat_id+ else:+ payload = {"alert": alert, "source": "snitch", "text": text}+ try:+ req = urllib.request.Request(+ url, data=json.dumps(payload).encode(),+ headers={"Content-Type": "application/json"},+ )+ urllib.request.urlopen(req, timeout=_TIMEOUT_S).read()+ except Exception as e: # noqa: BLE001+ logger.debug("webhook dispatch failed: %s", e)+++notifier = WebhookNotifier()diff --git a/backend/detection/anomaly.py b/backend/detection/anomaly.pyindex 74d7885..5de19f3 100644--- a/backend/detection/anomaly.py+++ b/backend/detection/anomaly.py@@ -208,6 +208,45 @@ MAX_SEEN_PROC_CONNS = 50_000MAX_TRACKED_IPS = 10_000MAX_COOLDOWN_KEYS = 10_000+# ── DNS tunneling / Tunneling DNS ────────────────────────────────────────────+# EN: DNS tunnels hide payloads in hostnames (base32/base64-encoded data+# smuggled through a resolver). Heuristics: absurdly long full names or+# single labels — legit names almost never exceed ~50 chars or have a+# > 40-char label.+# FR: Les tunnels DNS cachent des données dans les noms d'hôtes (données+# encodées base32/base64 passées par un résolveur). Heuristiques : noms+# complets absurdement longs ou labels uniques longs — les noms légitimes+# dépassent rarement ~50 car. ou n'ont pas de label > 40 car.+DNS_NAME_MAX = 60+DNS_LABEL_MAX = 40++# ── Cleartext protocols / Protocoles en clair ────────────────────────────────+# EN: Remote ports whose traffic is unencrypted by design — useful for a+# "hardening" audit: any process still talking FTP/Telnet/HTTP/plain+# mail deserves a look.+# FR: Ports distants dont le trafic est non chiffré par nature — utile pour+# un audit « hardening » : tout processus parlant encore FTP/Telnet/HTTP+# ou mail en clair mérite un coup d'œil.+CLEARTEXT_PORTS = {+ 21: "FTP", 23: "Telnet", 25: "SMTP", 80: "HTTP",+ 110: "POP3", 143: "IMAP", 389: "LDAP",+}+CLEARTEXT_COOLDOWN = 3600++# ── Application baseline / Base applicative ──────────────────────────────────+# EN: Per-process learned profile — which countries a process normally talks+# to. The first BASELINE_LEARN_MIN packets teach the profile silently;+# afterwards a NEW country for a known process raises BASELINE_DEVIATION+# (e.g. Slack suddenly reaching a residential IP range abroad).+# FR: Profil appris par processus — les pays avec lesquels un processus+# parle normalement. Les BASELINE_LEARN_MIN premiers paquets enseignent+# le profil en silence ; ensuite un NOUVEAU pays pour un processus connu+# lève BASELINE_DEVIATION (ex. Slack qui joint soudain une IP+# résidentielle à l'étranger).+BASELINE_LEARN_MIN = 10+BASELINE_MAX_PROCS = 2_000+BASELINE_COOLDOWN = 900+class BoundedSet:"""@@ -307,6 +346,14 @@ class AnomalyDetector:self._watch_ips: set[str] = set()self._watch_domains: set[str] = set()+ # EN: Per-process baselines — proc → {"countries": set, "ports": set,+ # "seen": int}. Persisted via the settings table by the API layer+ # (dump_baselines/load_baselines). Bounded by BASELINE_MAX_PROCS.+ # FR: Bases par processus — proc → {"countries": set, "ports": set,+ # "seen": int}. Persistées via la table settings par la couche API+ # (dump_baselines/load_baselines). Bornées par BASELINE_MAX_PROCS.+ self._baselines: OrderedDict[str, dict] = OrderedDict()+# EN: User suppressions — persisted in the settings table, loaded at# startup. An entry is {"type": "BEACON"|None, "ip": "1.2.3.4"|None};# a packet is suppressed when BOTH non-None fields match.@@ -373,6 +420,31 @@ class AnomalyDetector:except ValueError:self._watch_domains.add(s)+ def load_baselines(self, data: dict) -> None:+ """EN: Restore persisted baselines (from settings). Values arrive as+ JSON lists — converted back to sets.+ FR: Restaurer les bases persistées — les listes JSON redeviennent des+ ensembles."""+ with self._lock:+ self._baselines = OrderedDict()+ for proc, prof in (data or {}).items():+ if not isinstance(prof, dict):+ continue+ self._baselines[proc] = {+ "countries": set(prof.get("countries", [])),+ "ports": set(prof.get("ports", [])),+ "seen": int(prof.get("seen", 0)),+ }++ def dump_baselines(self) -> dict:+ """EN: JSON-safe snapshot for persistence (called by the flush loop).+ FR: Instantané JSON pour la persistance (appelé par la boucle flush)."""+ with self._lock:+ return {proc: {"countries": sorted(p["countries"]),+ "ports": sorted(p["ports"]),+ "seen": p["seen"]}+ for proc, p in list(self._baselines.items())[:BASELINE_MAX_PROCS]}+def forget(self, ip: str) -> None:"""EN: Drop all runtime state for an IP (e.g. after it is whitelisted).@@ -439,6 +511,9 @@ class AnomalyDetector:alerts += self._check_media_exfil(pkt, remote_ip, geo)alerts += self._check_upload_spike(pkt, remote_ip, geo)alerts += self._check_watchlist(pkt, remote_ip, geo)+ alerts += self._check_dns_tunnel(pkt, remote_ip, geo)+ alerts += self._check_cleartext(pkt, remote_ip, geo)+ alerts += self._check_baseline(pkt, remote_ip, geo)# EN: Drop suppressed alerts before recording — persisted# "ignore this host/type" rules from the UI.# FR: Écarter les alertes supprimées avant l'enregistrement —@@ -837,6 +912,132 @@ class AnomalyDetector:# ── Helpers / Utilitaires ────────────────────────────────────────────────+ def _check_dns_tunnel(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:+ """+ EN: DNS-tunneling heuristic — data smuggled inside queried hostnames+ shows up as absurdly long names/labels (base32/base64 chunks).+ The parser hands us answer names, which echo the queried name,+ so responses are enough. One alert per offender per cooldown.+ FR: Heuristique de tunneling DNS — les données passées dans les noms+ interrogés donnent des noms/labels absurdement longs (chunks+ base32/base64). Le parseur fournit les noms des réponses, qui+ reflètent le nom interrogé — les réponses suffisent. Une alerte+ par contrevenant par cooldown.+ """+ if not pkt.dns:+ return []+ worst = ""+ for name, _ip, _ttl in pkt.dns:+ if not name or len(name) <= DNS_NAME_MAX and \+ all(len(lbl) <= DNS_LABEL_MAX for lbl in name.split(".")):+ continue+ if len(name) > len(worst):+ worst = name+ if not worst:+ return []+ if not self._cooldown_ok(f"dnstunnel:{remote_ip}", cooldown=600):+ return []+ proc = pkt.process_name or "unknown"+ return [Alert(+ type="DNS_TUNNEL",+ severity="warning",+ message=f"Possible DNS tunneling: oversized name '{worst[:60]}…' queried by {proc}",+ node_id=remote_ip,+ details={"ip": remote_ip, "name": worst, "process": proc,+ "length": len(worst)},+ )]++ def _check_cleartext(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:+ """+ EN: Unencrypted-by-design remote ports — flagged at INFO level for the+ hardening audit (a plaintext channel is a risk finding, not an+ attack). Once per destination per hour.+ FR: Ports distants non chiffrés par nature — signalés en INFO pour+ l'audit de durcissement (un canal en clair est un constat de+ risque, pas une attaque). Une fois par destination par heure.+ """+ if pkt.direction != "out" or pkt.protocol != "TCP":+ return []+ proto = CLEARTEXT_PORTS.get(pkt.dst_port or 0)+ if not proto:+ return []+ if not self._cooldown_ok(f"cleartext:{remote_ip}:{pkt.dst_port}",+ cooldown=CLEARTEXT_COOLDOWN):+ return []+ label = geo.get("hostname") or remote_ip+ proc = pkt.process_name or "unknown"+ return [Alert(+ type="CLEARTEXT",+ severity="info",+ message=f"Unencrypted {proto} connection to {label} by {proc}",+ node_id=remote_ip,+ details={"ip": remote_ip, "host": label, "port": pkt.dst_port,+ "proto": proto, "process": proc},+ )]++ def _check_baseline(self, pkt: Packet, remote_ip: str, geo: dict) -> list[Alert]:+ """+ EN: Application profiling — learn each process's normal destination+ countries during its first BASELINE_LEARN_MIN packets, then alert+ when a KNOWN process reaches a NEW country. Ports are learned+ silently (they legitimately vary); only geography deviates an+ alert — "Slack shouldn't talk to a residential IP abroad".+ FR: Profilage applicatif — apprendre les pays de destination+ normaux de chaque processus sur ses BASELINE_LEARN_MIN premiers+ paquets, puis alerter quand un processus CONNU joint un NOUVEAU+ pays. Les ports sont appris en silence (ils varient+ légitimement) — seule la géographie dévie en alerte.+ """+ proc = (pkt.process_name or "").strip()+ if not proc:+ return []+ key = proc.lower()+ if len(self._baselines) > BASELINE_MAX_PROCS and key not in self._baselines:+ return []++ prof = self._baselines.get(key)+ if prof is None:+ prof = {"countries": set(), "ports": set(), "seen": 0}+ self._baselines[key] = prof+ self._baselines.move_to_end(key)++ country = (geo.get("country_code") or geo.get("country") or "").strip().upper()+ port = pkt.dst_port if pkt.direction == "out" else pkt.src_port+ prof["seen"] += 1+ if port:+ prof["ports"].add(int(port))+ if len(prof["ports"]) > 64:+ prof["ports"] = set(list(prof["ports"])[-64:])++ # EN: Still learning — record, don't alert.+ # FR: Apprentissage en cours — enregistrer, ne pas alerter.+ if prof["seen"] <= BASELINE_LEARN_MIN or not country or country == "??":+ if country:+ prof["countries"].add(country)+ return []++ if country in prof["countries"]:+ return []+ # EN: Learn the new country too (it may be legitimate travel/CDN),+ # but alert once — the analyst decides.+ # FR: Apprendre aussi le nouveau pays (peut être un déplacement/CDN+ # légitime), mais alerter une fois — l'analyste décide.+ prof["countries"].add(country)+ if len(prof["countries"]) > 32:+ prof["countries"] = set(list(prof["countries"])[-32:])+ if not self._cooldown_ok(f"baseline:{key}:{country}",+ cooldown=BASELINE_COOLDOWN):+ return []+ label = geo.get("hostname") or remote_ip+ return [Alert(+ type="BASELINE_DEVIATION",+ severity="warning",+ message=f"{proc} contacted a new country: {country} ({label})",+ node_id=remote_ip,+ details={"ip": remote_ip, "host": label, "process": proc,+ "country": country, "known": sorted(prof["countries"])},+ )]+def _cooldown_ok(self, key: str, cooldown: int = COOLDOWN) -> bool:"""EN: True (and re-arm) if this key hasn't fired within `cooldown`diff --git a/backend/detection/firewall.py b/backend/detection/firewall.pynew file mode 100644index 0000000..952ef01--- /dev/null+++ b/backend/detection/firewall.py@@ -0,0 +1,445 @@+"""+EN: Firewall orchestration — Snitch does NOT filter packets in user-space;+ it drives the OS-native firewall instead:+ * Windows → `netsh advfirewall` (Windows Defender Firewall rules),+ * Linux → `iptables` OUTPUT chain (a dedicated SNITCH_LOCK chain for+ lockdown, per-destination DROP rules otherwise),+ * macOS → `pf` anchors (a generated ruleset loaded with pfctl).+ Rules are persisted in the settings table ("firewall_rules") so they+ survive restarts. Every apply/remove is best-effort: failures are+ recorded on the rule instead of raising — the backend often runs+ elevated already (packet capture requires it), but demo mode and+ unprivileged runs degrade gracefully to `applied=False`.++ Rule kinds: "ip" single remote IP+ "cidr" network (e.g. 185.0.0.0/8)+ "domain" resolved to IPs at apply time (best effort)+ "process" process name/path (netsh `program=` on Windows,+ owner match on Linux — name resolved to PIDs)+ "port" remote port+ "lockdown" drops ALL outbound traffic to non-private destinations —+ loopback and LAN stay up so the UI remains reachable.++FR: Orchestration du pare-feu — Snitch ne filtre PAS les paquets en+ user-space ; il pilote le pare-feu natif de l'OS :+ * Windows → `netsh advfirewall`,+ * Linux → `iptables` (chaîne dédiée SNITCH_LOCK pour le lockdown),+ * macOS → ancres `pf` (jeu de règles généré chargé avec pfctl).+ Les règles sont persistées dans la table settings (« firewall_rules »)+ donc elles survivent aux redémarrages. Chaque application/retrait est+ best-effort : les échecs sont enregistrés sur la règle plutôt que levés.+"""++from __future__ import annotations++import ipaddress+import os+import platform+import socket+import subprocess+import tempfile+import threading+import time+import uuid+from pathlib import Path+from typing import Optional++# EN: Cooldown between two BLOCKED_ATTEMPT alerts for the same rule.+# FR: Cooldown entre deux alertes BLOCKED_ATTEMPT pour une même règle.+_BLOCKED_COOLDOWN = 120++# EN: Private/LAN ranges exempted in lockdown mode so the machine keeps+# local connectivity (UI on loopback, DNS/DHCP on the LAN).+# FR: Plages privées/LAN exemptées en lockdown pour garder la connectivité+# locale (UI en loopback, DNS/DHCP sur le LAN).+_PRIVATE_NETS = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16",+ "169.254.0.0/16", "127.0.0.0/8", "::1/128", "fe80::/10"]+++class FirewallManager:+ """EN: Owns firewall rules, lockdown state and blocked-attempt counters.+ FR: Gère les règles pare-feu, l'état lockdown et les compteurs de+ tentatives bloquées."""++ def __init__(self, data_dir: str):+ self._lock = threading.Lock()+ self._platform = platform.system().lower() # 'windows'|'linux'|'darwin'+ self._demo = os.environ.get("SNITCH_DEMO") == "1"+ self._data_dir = Path(data_dir)+ # EN: The pf anchor file lives here — make sure it exists up-front.+ # FR: Le fichier d'ancre pf vit ici — s'assurer qu'il existe d'emblée.+ try:+ self._data_dir.mkdir(parents=True, exist_ok=True)+ except OSError:+ pass+ self._rules: list[dict] = []+ self._lockdown = False+ # EN: rule_id → last alert ts / FR: rule_id → dernier ts d'alerte+ self._block_alerts: dict[str, float] = {}+ # EN: rule_id → count of matching packets seen / FR: paquets vus par règle+ self._blocked_counts: dict[str, int] = {}++ # ── Introspection / Introspection ────────────────────────────────────────++ def supported(self) -> bool:+ """EN: Firewall orchestration needs a known OS; demo mode pretends+ everything works (rules apply in-memory only).+ FR: L'orchestration exige un OS connu ; le mode démo simule+ (règles appliquées en mémoire seulement)."""+ return self._demo or self._platform in ("windows", "linux", "darwin")++ def status(self) -> dict:+ with self._lock:+ return {+ "supported": self.supported(),+ "platform": self._platform,+ "demo": self._demo,+ "lockdown": self._lockdown,+ "rules": [dict(r) for r in self._rules],+ "blocked_counts": dict(self._blocked_counts),+ }++ # ── Persistence / Persistance ────────────────────────────────────────────++ def load(self, rules: list[dict], lockdown: bool) -> None:+ """EN: Restore persisted rules at startup and re-apply enabled ones+ silently (host firewall state may have been cleared meanwhile).+ FR: Restaurer les règles persistées au démarrage et réappliquer les+ actives en silence (l'état du pare-feu hôte a pu être vidé)."""+ with self._lock:+ self._rules = [dict(r) for r in rules if isinstance(r, dict) and r.get("kind")]+ self._lockdown = bool(lockdown)+ for r in list(self._rules):+ if r.get("enabled", True):+ self._apply(r)+ if self._lockdown:+ self._lockdown_apply(True)++ def _serialized_rules(self) -> list[dict]:+ return [dict(r) for r in self._rules]++ # ── Public rule ops / Opérations publiques ───────────────────────────────++ def add_rule(self, kind: str, value: str) -> dict:+ """EN: Create + apply a rule. `value` depends on kind (see module doc).+ Returns the persisted rule dict including its apply result.+ FR: Créer + appliquer une règle. Retourne la règle persistée avec le+ résultat d'application."""+ kind = kind.lower().strip()+ value = str(value).strip()+ if kind not in ("ip", "cidr", "domain", "process", "port"):+ raise ValueError(f"unknown rule kind: {kind}")+ rule = {+ "id": uuid.uuid4().hex[:10],+ "kind": kind,+ "value": value,+ "enabled": True,+ "applied": False,+ "error": None,+ "resolved": [], # EN: domain→IPs / FR: domaine→IP+ "created": time.time(),+ }+ if kind in ("ip", "cidr"):+ ipaddress.ip_network(value, strict=False) # EN: raises if invalid / FR: lève si invalide+ if kind == "domain":+ rule["resolved"] = self._resolve_domain(value)+ self._apply(rule)+ with self._lock:+ self._rules.append(rule)+ return rule++ def remove_rule(self, rule_id: str) -> bool:+ with self._lock:+ rule = next((r for r in self._rules if r["id"] == rule_id), None)+ if not rule:+ return False+ self._rules.remove(rule)+ self._remove(rule)+ return True++ def toggle_rule(self, rule_id: str, enabled: bool) -> Optional[dict]:+ with self._lock:+ rule = next((r for r in self._rules if r["id"] == rule_id), None)+ if not rule:+ return None+ rule["enabled"] = enabled+ if enabled:+ self._apply(rule)+ else:+ self._remove(rule)+ return rule++ def serialized(self) -> tuple[list[dict], bool]:+ with self._lock:+ return self._serialized_rules(), self._lockdown++ # ── Lockdown / Confinement ───────────────────────────────────────────────++ def set_lockdown(self, on: bool) -> dict:+ """EN: Global panic switch — drop all outbound traffic to public IPs,+ keep loopback + LAN so the Snitch UI/API stays reachable.+ FR: Bouton panique — coupe tout le trafic sortant vers les IP+ publiques, conserve loopback + LAN pour garder l'UI joignable."""+ ok, err = self._lockdown_apply(on)+ with self._lock:+ self._lockdown = on if ok else self._lockdown+ if ok:+ self._lockdown = on+ return {"ok": ok, "lockdown": self._lockdown, "error": err}++ # ── Packet matching / Correspondance paquets ─────────────────────────────++ def check_packet(self, pkt) -> Optional[dict]:+ """EN: First enabled rule matching this packet (remote IP/CIDR, port,+ process name). Used to emit BLOCKED_ATTEMPT alerts — the OS firewall+ already drops the traffic, this is only visibility.+ FR: Première règle active correspondant au paquet (IP/CIDR, port,+ processus). Sert à émettre les alertes BLOCKED_ATTEMPT — le pare-feu+ OS droppe déjà le trafic, ceci n'est que de la visibilité."""+ remote = pkt.dst_ip if pkt.direction == "out" else pkt.src_ip+ port = pkt.dst_port if pkt.direction == "out" else pkt.src_port+ proc = (pkt.process_name or "").lower()+ try:+ rip = ipaddress.ip_address(remote)+ except ValueError:+ return None++ # EN: Lockdown flags every outbound packet to a public destination —+ # private/LAN traffic stays exempt so the UI remains reachable.+ # FR: Le lockdown signale chaque paquet sortant vers une destination+ # publique — le trafic privé/LAN reste exempt pour garder l'UI.+ with self._lock:+ lockdown = self._lockdown+ rules = [r for r in self._rules if r.get("enabled", True)]+ if lockdown and pkt.direction == "out" and not rip.is_private \+ and not rip.is_loopback and not rip.is_link_local:+ return {"id": "__lockdown__", "kind": "lockdown", "value": "*"}+ for r in rules:+ k, v = r["kind"], r["value"]+ hit = False+ if k in ("ip", "cidr"):+ try:+ hit = rip in ipaddress.ip_network(v, strict=False)+ except ValueError:+ hit = False+ elif k == "domain":+ for resolved in r.get("resolved", []):+ try:+ if rip in ipaddress.ip_network(resolved, strict=False):+ hit = True+ break+ except ValueError:+ continue+ elif k == "process":+ hit = proc == v.lower() or proc.endswith("/" + v.lower()) \+ or proc.endswith("\\" + v.lower())+ elif k == "port":+ try:+ hit = int(v) == int(port or 0)+ except (TypeError, ValueError):+ hit = False+ if hit:+ return r+ return None++ def note_blocked(self, rule_id: str) -> Optional[dict]:+ """EN: Increment the seen-blocked counter; returns alert context when+ the cooldown allows a new BLOCKED_ATTEMPT notification.+ FR: Incrémente le compteur de blocages ; retourne le contexte+ d'alerte quand le cooldown autorise une notification."""+ with self._lock:+ self._blocked_counts[rule_id] = self._blocked_counts.get(rule_id, 0) + 1+ now = time.time()+ last = self._block_alerts.get(rule_id, 0)+ if now - last < _BLOCKED_COOLDOWN:+ return None+ self._block_alerts[rule_id] = now+ rule = next((r for r in self._rules if r["id"] == rule_id), None)+ return {"rule": dict(rule) if rule else None,+ "count": self._blocked_counts[rule_id]}++ # ── OS plumbing / Plomberie OS ───────────────────────────────────────────++ def _run(self, args: list[str]) -> tuple[bool, str]:+ """EN: Run one firewall command, never through a shell. Returns+ (success, stderr). / FR: Exécute une commande pare-feu sans shell."""+ try:+ p = subprocess.run(args, capture_output=True, text=True, timeout=15)+ err = (p.stderr or p.stdout or "").strip()+ return p.returncode == 0, err[:300]+ except Exception as e: # noqa: BLE001 — report, don't crash+ return False, str(e)[:300]++ def _apply(self, rule: dict) -> None:+ if self._demo:+ rule["applied"], rule["error"] = True, None+ return+ kind, value, rid = rule["kind"], rule["value"], rule["id"]+ targets = rule.get("resolved") if kind == "domain" else [value]+ if kind == "domain" and not targets:+ rule["applied"], rule["error"] = False, "domain did not resolve"+ return+ ok_all, err_all = True, ""+ for t in targets:+ ok, err = self._apply_one(kind, t, rid)+ ok_all = ok_all and ok+ err_all = err or err_all+ rule["applied"], rule["error"] = ok_all, err_all or None++ def _apply_one(self, kind: str, target: str, rid: str) -> tuple[bool, str]:+ if self._platform == "windows":+ name = f"SnitchRule-{rid}"+ if kind == "process":+ return self._run(["netsh", "advfirewall", "firewall", "add", "rule",+ f"name={name}", "dir=out", "action=block",+ f"program={target}", "enable=yes"])+ key = "remoteip" if kind in ("ip", "cidr", "domain") else "remoteport"+ return self._run(["netsh", "advfirewall", "firewall", "add", "rule",+ f"name={name}-{abs(hash(target)) % 10**6}",+ "dir=out", "action=block", f"{key}={target}", "enable=yes"])+ if self._platform == "linux":+ if kind == "process":+ # EN: owner match works for locally generated packets by PID.+ # Names are resolved to PIDs lazily — best effort.+ # FR: Le match owner fonctionne par PID sur paquets locaux.+ return self._block_linux_process(target, rid)+ args = ["iptables", "-w", "-I", "OUTPUT"]+ if kind in ("ip", "cidr", "domain"):+ args += ["-d", target]+ elif kind == "port":+ args += ["-p", "tcp", "--dport", target]+ args += ["-j", "DROP", "-m", "comment", "--comment", f"snitch-{rid}"]+ return self._run(args)+ if self._platform == "darwin":+ return self._pf_apply()+ return False, f"unsupported platform {self._platform}"++ def _remove(self, rule: dict) -> None:+ if self._demo:+ return+ rid, kind = rule["id"], rule["kind"]+ if self._platform == "windows":+ self._run(["netsh", "advfirewall", "firewall", "delete", "rule",+ f"name=SnitchRule-{rid}"])+ # EN: per-target suffixed copies / FR: copies suffixées par cible+ self._run(["netsh", "advfirewall", "firewall", "delete", "rule",+ "name=all", "program=" + rule["value"]]) if kind == "process" else None+ elif self._platform == "linux":+ targets = rule.get("resolved") if kind == "domain" else [rule["value"]]+ for t in targets:+ args = ["iptables", "-w", "-D", "OUTPUT"]+ if kind in ("ip", "cidr", "domain"):+ args += ["-d", t]+ elif kind == "port":+ args += ["-p", "tcp", "--dport", t]+ elif kind == "process":+ continue+ args += ["-j", "DROP", "-m", "comment", "--comment", f"snitch-{rid}"]+ self._run(args)+ elif self._platform == "darwin":+ self._pf_apply() # EN: regenerates the anchor without this rule / FR: régénère l'ancre sans la règle++ # ── Linux process block / Blocage processus Linux ────────────────────────++ def _block_linux_process(self, proc_name: str, rid: str) -> tuple[bool, str]:+ """EN: iptables `owner` matches by PID — resolve the name to current+ PIDs via psutil. Only locally generated packets match; still useful+ for an instant kill-switch on a known process.+ FR: `owner` matche par PID — on résout le nom en PID via psutil."""+ try:+ import psutil+ pids = [p.pid for p in psutil.process_iter(["name"])+ if (p.info.get("name") or "").lower() == proc_name.lower()]+ except Exception as e: # noqa: BLE001+ return False, str(e)[:200]+ if not pids:+ return False, f"no running process named {proc_name}"+ ok_all = True+ for pid in pids[:8]: # EN: cap / FR: borne+ ok, _ = self._run(["iptables", "-w", "-I", "OUTPUT", "-m", "owner",+ "--pid-owner", str(pid), "-j", "DROP"])+ ok_all = ok_all and ok+ return ok_all, "" if ok_all else "owner match failed"++ # ── macOS pf / pf macOS ──────────────────────────────────────────────────++ def _pf_apply(self) -> tuple[bool, str]:+ """EN: Regenerate the com.snitch anchor from enabled rules + lockdown+ and load it with pfctl. The anchor file lives in the data dir.+ FR: Régénère l'ancre com.snitch depuis les règles actives + lockdown+ et la charge avec pfctl."""+ dests, procs_note = [], []+ with self._lock:+ rules = [r for r in self._rules if r.get("enabled", True)]+ lockdown = self._lockdown+ for r in rules:+ if r["kind"] in ("ip", "cidr"):+ dests.append(r["value"])+ elif r["kind"] == "domain":+ dests += r.get("resolved", [])+ elif r["kind"] == "port":+ dests.append(f"port {r['value']}")+ elif r["kind"] == "process":+ procs_note.append(r["value"]) # EN: pf can't match processes / FR: pf ne filtre pas par processus+ lines = [f'table <snitch_block> const {{ {", ".join(d for d in dests if "/" in d or ":" not in d)} }}']+ lines.append("block drop out quick inet from any to <snitch_block>")+ port_rules = [r["value"] for r in rules if r["kind"] == "port"]+ for p in port_rules:+ lines.append(f"block drop out quick inet proto tcp from any to any port {p}")+ if lockdown:+ nets = ", ".join(_PRIVATE_NETS)+ lines.append(f"block drop out quick inet from any to ! {{ {nets} }}")+ anchor = self._data_dir / "pf-snitch.anchor"+ anchor.write_text("\n".join(lines) + "\n")+ return self._run(["pfctl", "-a", "com.snitch", "-f", str(anchor)])++ # ── Lockdown internals / Internes lockdown ───────────────────────────────++ def _lockdown_apply(self, on: bool) -> tuple[bool, str]:+ if self._demo:+ return True, ""+ if self._platform == "windows":+ if on:+ return self._run(["netsh", "advfirewall", "set", "allprofiles",+ "firewallpolicy", "blockinbound,blockoutbound"])+ return self._run(["netsh", "advfirewall", "set", "allprofiles",+ "firewallpolicy", "blockinbound,allowoutbound"])+ if self._platform == "linux":+ if on:+ self._run(["iptables", "-w", "-N", "SNITCH_LOCK"])+ self._run(["iptables", "-w", "-F", "SNITCH_LOCK"])+ for net in _PRIVATE_NETS[:5]:+ self._run(["iptables", "-w", "-A", "SNITCH_LOCK", "-d", net, "-j", "ACCEPT"])+ self._run(["iptables", "-w", "-A", "SNITCH_LOCK", "-o", "lo", "-j", "ACCEPT"])+ ok, err = self._run(["iptables", "-w", "-A", "SNITCH_LOCK", "-j", "DROP"])+ self._run(["iptables", "-w", "-I", "OUTPUT", "1", "-j", "SNITCH_LOCK"])+ return ok, err+ self._run(["iptables", "-w", "-D", "OUTPUT", "-j", "SNITCH_LOCK"])+ ok, err = self._run(["iptables", "-w", "-F", "SNITCH_LOCK"])+ return ok, err+ if self._platform == "darwin":+ with self._lock:+ self._lockdown = on+ return self._pf_apply()+ return False, f"unsupported platform {self._platform}"++ # ── DNS resolution for domain rules / Résolution DNS ────────────────────++ @staticmethod+ def _resolve_domain(domain: str) -> list[str]:+ """EN: Resolve a domain rule to concrete IPs now (firewalls match IPs,+ not names). Re-resolved on each apply — best effort.+ FR: Résout une règle domaine en IP concrètes (les pare-feux matchent+ des IP, pas des noms)."""+ ips: set[str] = set()+ try:+ for info in socket.getaddrinfo(domain, None):+ ip = info[4][0]+ try:+ ipaddress.ip_address(ip)+ ips.add(ip + ("/128" if ":" in ip else "/32"))+ except ValueError:+ continue+ except socket.gaierror:+ pass+ return sorted(ips)diff --git a/backend/detection/threatintel.py b/backend/detection/threatintel.pynew file mode 100644index 0000000..2131998--- /dev/null+++ b/backend/detection/threatintel.py@@ -0,0 +1,206 @@+"""+EN: Threat-intel reputation checks — strictly OPT-IN. Disabled by default;+ when the user provides a personal API key, outbound IPs are checked+ against the chosen provider and malicious verdicts raise THREAT_HIT+ alerts. This IS an outbound network call (documented in PRIVACY.md):+ only the remote IP is sent to the provider, nothing else.++ Providers:+ * abuseipdb → https://api.abuseipdb.com/api/v2/check (abuseConfidenceScore)+ * otx → https://otx.alienvault.com/api/v1/indicators/IPv4/{ip}/general+ (pulse_info.count)+ * virustotal → https://www.virustotal.com/api/v3/ip_addresses/{ip}+ (last_analysis_stats.malicious/suspicious)++ Results are cached in a bounded LRU map — one provider call per IP per+ session, negative/errored results cached too so a flaky network can't+ stall the capture loop.++FR: Vérification de réputation threat-intel — strictement OPT-IN. Désactivé+ par défaut ; avec une clé API personnelle, les IP sortantes sont+ vérifiées auprès du fournisseur choisi et les verdicts malveillants+ lèvent des alertes THREAT_HIT. C'est un appel sortant (documenté dans+ PRIVACY.md) : seule l'IP distante est envoyée au fournisseur.+"""++from __future__ import annotations++import json+import threading+import time+import urllib.request+from collections import OrderedDict+from typing import Optional++# EN: Cache bounds + verdict TTL (re-check daily at most).+# FR: Bornes du cache + durée de vie d'un verdict (revérif max 1×/jour).+_MAX_CACHE = 4_000+_TTL_S = 86_400+_TIMEOUT_S = 8++_ABUSEIPDB_URL = "https://api.abuseipdb.com/api/v2/check"+_OTX_URL = "https://otx.alienvault.com/api/v1/indicators/IPv4/{ip}/general"+_VT_URL = "https://www.virustotal.com/api/v3/ip_addresses/{ip}"++# EN: abuseConfidenceScore threshold treated as malicious.+# FR: Seuil abuseConfidenceScore considéré malveillant.+_MALICIOUS_SCORE = 50+++class ThreatIntel:+ """EN: Provider-agnostic reputation client with bounded LRU cache.+ FR: Client de réputation agnostique avec cache LRU borné."""++ def __init__(self):+ self._lock = threading.Lock()+ self._provider = "none" # 'abuseipdb' | 'otx' | 'virustotal' | 'none'+ self._api_key = ""+ self._cache: OrderedDict[str, tuple[float, dict]] = OrderedDict()+ self._inflight: set[str] = set()++ def configure(self, provider: str, api_key: str) -> None:+ """EN: Point the client at a provider ('none' disables checks).+ Changing provider/key clears the cache so verdicts refresh.+ FR: Pointer le client vers un fournisseur (« none » désactive).+ Changer fournisseur/clé vide le cache pour rafraîchir les verdicts."""+ provider = (provider or "none").lower()+ api_key = (api_key or "").strip()+ with self._lock:+ if provider != self._provider or api_key != self._api_key:+ self._cache.clear()+ self._provider = provider if provider in (+ "abuseipdb", "otx", "virustotal") else "none"+ self._api_key = api_key++ @property+ def enabled(self) -> bool:+ return self._provider != "none" and bool(self._api_key)++ def config(self) -> dict:+ """EN: Settings surface — api_key is masked for display.+ FR: Surface de réglages — la clé API est masquée pour l'affichage."""+ k = self._api_key+ return {+ "enabled": self.enabled,+ "provider": self._provider,+ "api_key_masked": (k[:4] + "…" + k[-4:]) if len(k) > 8 else ("…" if k else ""),+ "cached": len(self._cache),+ }++ def begin_check(self, ip: str) -> bool:+ """EN: Dedup guard — caller should spawn check() in an executor only+ if this returns True. / FR: Garde anti-doublon — ne lancer check()+ dans un executor que si True."""+ if not self.enabled:+ return False+ with self._lock:+ if ip in self._inflight:+ return False+ if ip in self._cache:+ ts, verdict = self._cache[ip]+ if time.time() - ts < _TTL_S:+ return False+ self._inflight.add(ip)+ return True++ def check(self, ip: str) -> Optional[dict]:+ """EN: Synchronous provider call — run inside an executor, never on+ the event loop. Returns the verdict dict (or None on hard failure),+ caches it, clears the inflight mark.+ FR: Appel fournisseur synchrone — à lancer dans un executor, jamais+ sur la boucle. Retourne le verdict (ou None), le cache, lève la+ marque inflight."""+ # EN: Serve a fresh cached verdict first — callers like the manual+ # /security/threat_check may call check() without begin_check().+ # FR: Servir d'abord un verdict en cache frais — des appelants comme+ # /security/threat_check peuvent appeler check() sans begin_check().+ with self._lock:+ cached = self._cache.get(ip)+ if cached and time.time() - cached[0] < _TTL_S:+ return cached[1]+ try:+ verdict = self._fetch(ip)+ finally:+ with self._lock:+ self._inflight.discard(ip)+ if verdict:+ with self._lock:+ self._cache[ip] = (time.time(), verdict)+ self._cache.move_to_end(ip)+ while len(self._cache) > _MAX_CACHE:+ self._cache.popitem(last=False)+ return verdict++ def _fetch(self, ip: str) -> Optional[dict]:+ """EN: One HTTP call to the configured provider. Returns a verdict+ dict: {ip, provider, verdict: malicious|suspicious|clean, score, detail}.+ FR: Un appel HTTP au fournisseur configuré → verdict dict."""+ if self._provider == "abuseipdb":+ req = urllib.request.Request(+ f"{_ABUSEIPDB_URL}?ipAddress={ip}&maxAgeInDays=90",+ headers={"Key": self._api_key, "Accept": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=_TIMEOUT_S) as r:+ data = json.loads(r.read(1 << 20))+ except Exception as e: # noqa: BLE001+ return {"ip": ip, "provider": "abuseipdb", "verdict": "error",+ "score": 0, "detail": str(e)[:200]}+ d = data.get("data", {})+ score = int(d.get("abuseConfidenceScore", 0))+ verdict = "malicious" if score >= _MALICIOUS_SCORE else \+ "suspicious" if score >= 25 else "clean"+ return {"ip": ip, "provider": "abuseipdb", "verdict": verdict,+ "score": score,+ "detail": f"confidence {score}%, {d.get('totalReports', 0)} reports, "+ f"{d.get('countryCode') or '?'}, {d.get('usageType') or ''}"}++ if self._provider == "otx":+ req = urllib.request.Request(+ _OTX_URL.format(ip=ip),+ headers={"X-OTX-API-KEY": self._api_key, "Accept": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=_TIMEOUT_S) as r:+ data = json.loads(r.read(1 << 20))+ except Exception as e: # noqa: BLE001+ return {"ip": ip, "provider": "otx", "verdict": "error",+ "score": 0, "detail": str(e)[:200]}+ pulses = data.get("pulse_info", {}).get("count", 0)+ verdict = "malicious" if pulses >= 3 else \+ "suspicious" if pulses >= 1 else "clean"+ names = [p.get("name", "") for p in data.get("pulse_info", {}).get("pulses", [])][:3]+ return {"ip": ip, "provider": "otx", "verdict": verdict,+ "score": pulses,+ "detail": f"{pulses} pulses" + (f" — {', '.join(names)}" if names else "")}++ # EN: VirusTotal v3 — free public API (4 req/min) still needs the+ # user's own key. last_analysis_stats counts engines flagging+ # the IP; a couple of hits already deserve a suspicious mark.+ # FR: VirusTotal v3 — l'API publique gratuite (4 req/min) exige la+ # clé de l'utilisateur. last_analysis_stats compte les moteurs+ # signalant l'IP ; quelques signalements méritent déjà un+ # verdict suspect.+ if self._provider == "virustotal":+ req = urllib.request.Request(+ _VT_URL.format(ip=ip),+ headers={"x-apikey": self._api_key, "Accept": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=_TIMEOUT_S) as r:+ data = json.loads(r.read(1 << 20))+ except Exception as e: # noqa: BLE001+ return {"ip": ip, "provider": "virustotal", "verdict": "error",+ "score": 0, "detail": str(e)[:200]}+ stats = data.get("data", {}).get("attributes", {}) \+ .get("last_analysis_stats", {})+ hits = int(stats.get("malicious", 0))+ sus = int(stats.get("suspicious", 0))+ verdict = "malicious" if hits >= 3 else \+ "suspicious" if hits >= 1 or sus >= 2 else "clean"+ total = sum(int(v) for v in stats.values())+ return {"ip": ip, "provider": "virustotal", "verdict": verdict,+ "score": hits,+ "detail": f"{hits} malicious / {sus} suspicious of {total} engines"}++ return Nonediff --git a/backend/tests/test_security_features.py b/backend/tests/test_security_features.pynew file mode 100644index 0000000..a9a6bbe--- /dev/null+++ b/backend/tests/test_security_features.py@@ -0,0 +1,256 @@+"""+Snitch — security-features tests (firewall, threat intel, new detectors).++EN: Covers the FirewallManager rule matching/lockdown/counters (OS commands+ are never executed — _apply is monkeypatched or the rules stay in demo+ mode), the opt-in ThreatIntel client (default-off, dedup, caching) and+ the new anomaly checks: DNS_TUNNEL, CLEARTEXT, BASELINE_DEVIATION.+FR: Couvre le FirewallManager (matching/lockdown/compteurs — les commandes+ OS ne sont jamais exécutées, _apply est monkeypatché), le client+ ThreatIntel opt-in (désactivé par défaut, dédup, cache) et les nouveaux+ checks d'anomalie : DNS_TUNNEL, CLEARTEXT, BASELINE_DEVIATION.+"""++import time+from datetime import datetime, timezone++from capture.sniffer import Packet+from detection.anomaly import AnomalyDetector, BASELINE_LEARN_MIN+from detection.firewall import FirewallManager+from detection.threatintel import ThreatIntel++PUBLIC_IP = "91.198.174.192"+PRIVATE_IP = "192.168.1.55"+++def pkt(remote=PUBLIC_IP, direction="out", port=443, size=500,+ process=None, proto="TCP", dns=None):+ """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,+ remote_port=port,+ protocol=proto,+ size=size,+ timestamp=datetime.now(timezone.utc).isoformat(),+ direction=direction,+ process_name=process,+ dns=dns or [],+ )+++# ── Firewall / Pare-feu ──────────────────────────────────────────────────────++def _fw(tmp_path, monkeypatch):+ """EN: FirewallManager with OS commands stubbed out — 'applied' is always+ True so tests exercise rule logic, not privileges.+ FR: FirewallManager avec commandes OS stubées — « applied » vaut toujours+ True pour tester la logique de règles, pas les privilèges."""+ fw = FirewallManager(str(tmp_path))+ monkeypatch.setattr(fw, "_apply_one", lambda k, t, rid: (True, ""))+ monkeypatch.setattr(fw, "_remove", lambda rule: None)+ monkeypatch.setattr(fw, "_lockdown_apply", lambda on: (True, ""))+ monkeypatch.setattr(FirewallManager, "_resolve_domain",+ staticmethod(lambda d: ["203.0.113.9/32"]))+ return fw+++def test_firewall_rule_lifecycle(tmp_path, monkeypatch):+ """EN: add → serialized → toggle → remove. / FR: ajouter → sérialiser →+ basculer → supprimer."""+ fw = _fw(tmp_path, monkeypatch)+ rule = fw.add_rule("ip", PUBLIC_IP)+ assert rule["applied"] is True+ rules, lockdown = fw.serialized()+ assert len(rules) == 1 and lockdown is False+ assert fw.toggle_rule(rule["id"], False)+ assert fw.serialized()[0][0]["enabled"] is False+ assert fw.remove_rule(rule["id"])+ assert fw.serialized()[0] == []+++def test_firewall_rejects_bad_rule(tmp_path, monkeypatch):+ """EN: Unknown kind → ValueError. / FR: Type inconnu → ValueError."""+ fw = _fw(tmp_path, monkeypatch)+ try:+ fw.add_rule("bogus", "x")+ except ValueError:+ return+ raise AssertionError("expected ValueError")+++def test_firewall_check_packet_matches_ip(tmp_path, monkeypatch):+ """EN: A packet to a ruled IP is reported. / FR: Un paquet vers une IP en+ règle est rapporté."""+ fw = _fw(tmp_path, monkeypatch)+ fw.add_rule("ip", PUBLIC_IP)+ assert fw.check_packet(pkt())["value"] == PUBLIC_IP+ assert fw.check_packet(pkt(remote="8.8.8.8")) is None+++def test_firewall_check_packet_matches_process_and_port(tmp_path, monkeypatch):+ """EN: Process + port rules hit too. / FR: Les règles processus et port+ matchent aussi."""+ fw = _fw(tmp_path, monkeypatch)+ fw.add_rule("process", "evil.exe")+ fw.add_rule("port", "4444")+ assert fw.check_packet(pkt(process="evil.exe"))["kind"] == "process"+ assert fw.check_packet(pkt(port=4444))["kind"] == "port"+++def test_firewall_lockdown_flags_public_outbound(tmp_path, monkeypatch):+ """EN: Lockdown → every public outbound packet flagged; LAN stays exempt.+ FR: Lockdown → tout paquet sortant public signalé ; le LAN reste exempt."""+ fw = _fw(tmp_path, monkeypatch)+ fw.set_lockdown(True)+ hit = fw.check_packet(pkt())+ assert hit and hit["kind"] == "lockdown"+ assert fw.check_packet(pkt(remote=PRIVATE_IP)) is None+ fw.set_lockdown(False)+ assert fw.check_packet(pkt()) is None+++def test_firewall_blocked_count_and_cooldown(tmp_path, monkeypatch):+ """EN: note_blocked counts and rate-limits alert contexts.+ FR: note_blocked compte et limite les contextes d'alerte."""+ fw = _fw(tmp_path, monkeypatch)+ rule = fw.add_rule("ip", PUBLIC_IP)+ ctx1 = fw.note_blocked(rule["id"])+ ctx2 = fw.note_blocked(rule["id"])+ assert ctx1 and ctx1["count"] == 1 and ctx2 is None # cooldown+ assert fw.status()["blocked_counts"][rule["id"]] == 2+++def test_firewall_domain_rule_matches_resolved_ip(tmp_path, monkeypatch):+ """EN: Domain rules match packets to the resolved IPs.+ FR: Les règles de domaine matchent les paquets vers les IP résolues."""+ fw = _fw(tmp_path, monkeypatch)+ fw.add_rule("domain", "evil.example")+ assert fw.check_packet(pkt(remote="203.0.113.9")) is not None+++# ── Threat intel / Renseignement sur les menaces ────────────────────────────++def test_ti_disabled_by_default():+ """EN: No provider → disabled, check() is a no-op → NO outbound call.+ FR: Pas de fournisseur → désactivé, check() ne fait rien → AUCUN appel."""+ ti = ThreatIntel()+ assert not ti.enabled+ assert ti.check(PUBLIC_IP) is None+ assert ti.config()["provider"] == "none"+++def test_ti_enabled_requires_provider_and_key():+ """EN: A provider without a key stays OFF — no half-configured leak.+ FR: Un fournisseur sans clé reste inactif — pas de fuite à moitié configurée."""+ ti = ThreatIntel()+ ti.configure("abuseipdb", "")+ assert not ti.enabled+ ti.configure("abuseipdb", "secretkey123")+ assert ti.enabled+++def test_ti_check_uses_cache_and_dedup(monkeypatch):+ """EN: One live fetch; repeat calls hit the cache — the provider sees+ each IP at most once per TTL. / FR: Un appel réel ; les suivants lisent+ le cache — le fournisseur voit chaque IP au plus une fois par TTL."""+ ti = ThreatIntel()+ ti.configure("otx", "key")+ calls = []++ def fake_fetch(ip):+ calls.append(ip)+ return {"ip": ip, "provider": "otx", "verdict": "malicious",+ "score": 10, "detail": "pulses"}++ monkeypatch.setattr(ti, "_fetch", fake_fetch)+ assert ti.begin_check(PUBLIC_IP) # first time → go+ assert not ti.begin_check(PUBLIC_IP) # in-flight → dedup+ v = ti.check(PUBLIC_IP)+ assert v["verdict"] == "malicious"+ assert not ti.begin_check(PUBLIC_IP) # cached → dedup+ ti.check(PUBLIC_IP)+ assert calls == [PUBLIC_IP] # only ONE fetch total+++# ── New anomaly checks / Nouveaux checks d'anomalie ─────────────────────────++def test_dns_tunnel_alerts_on_oversized_name():+ """EN: A >100-char DNS name with a >60-char label → DNS_TUNNEL once.+ FR: Un nom DNS >100 car. avec label >60 → DNS_TUNNEL une fois."""+ det = AnomalyDetector()+ name = "a" * 65 + "." + "b" * 45 + ".example.com"+ p = pkt(dns=[(name, PUBLIC_IP, 60)])+ alerts = det.analyze_packet(p, {})+ assert any(a.type == "DNS_TUNNEL" for a in alerts)+ # EN: Cooldown — a second oversized name must not re-alert.+ # FR: Cooldown — un second nom surdimensionné ne doit pas re-alerter.+ alerts2 = det.analyze_packet(pkt(dns=[(name, PUBLIC_IP, 60)]), {})+ assert not any(a.type == "DNS_TUNNEL" for a in alerts2)+++def test_dns_tunnel_ignores_normal_names():+ """EN: Everyday hostnames stay quiet. / FR: Les noms usuels restent muets."""+ det = AnomalyDetector()+ p = pkt(dns=[("www.example.com", PUBLIC_IP, 300)])+ alerts = det.analyze_packet(p, {})+ assert "DNS_TUNNEL" not in [a.type for a in alerts]+++def test_cleartext_flags_port80_once():+ """EN: Outbound TCP/80 → CLEARTEXT info alert, once per destination.+ FR: TCP/80 sortant → alerte info CLEARTEXT, une fois par destination."""+ det = AnomalyDetector()+ alerts = det.analyze_packet(pkt(port=80), {"hostname": "news.example"})+ assert any(a.type == "CLEARTEXT" and a.severity == "info" for a in alerts)+ alerts2 = det.analyze_packet(pkt(port=80), {"hostname": "news.example"})+ assert "CLEARTEXT" not in [a.type for a in alerts2]+++def test_cleartext_ignores_https_and_inbound():+ """EN: 443 is never 'cleartext'; inbound 80 doesn't count (server side).+ FR: 443 n'est jamais « en clair » ; le 80 entrant ne compte pas."""+ det = AnomalyDetector()+ a1 = det.analyze_packet(pkt(port=443), {})+ a2 = det.analyze_packet(pkt(port=80, direction="in"), {})+ assert "CLEARTEXT" not in [a.type for a in a1 + a2]+++def test_baseline_deviation_alerts_on_new_country():+ """EN: After the learning window, a NEW destination country for a KNOWN+ process → BASELINE_DEVIATION. / FR: Après la fenêtre d'apprentissage, un+ NOUVEAU pays pour un processus CONNU → BASELINE_DEVIATION."""+ det = AnomalyDetector()+ geo_fr = {"country_code": "FR"}+ for _ in range(BASELINE_LEARN_MIN + 1):+ det.analyze_packet(pkt(process="slack"), geo_fr)+ alerts = det.analyze_packet(pkt(process="slack"), {"country_code": "RU"})+ assert any(a.type == "BASELINE_DEVIATION" and a.details["country"] == "RU"+ for a in alerts)+++def test_baseline_no_alert_during_learning():+ """EN: Countries seen during the learn phase are absorbed silently.+ FR: Les pays vus en phase d'apprentissage sont absorbés en silence."""+ det = AnomalyDetector()+ alerts = []+ for i in range(BASELINE_LEARN_MIN):+ alerts += det.analyze_packet(+ pkt(process="app"), {"country_code": "FR" if i % 2 else "DE"})+ assert "BASELINE_DEVIATION" not in [a.type for a in alerts]+++def test_baselines_persist_roundtrip():+ """EN: dump → load keeps learned countries (survives restarts).+ FR: dump → load conserve les pays appris (survit aux redémarrages)."""+ det = AnomalyDetector()+ for _ in range(BASELINE_LEARN_MIN + 1):+ det.analyze_packet(pkt(process="app"), {"country_code": "FR"})+ dump = det.dump_baselines()+ det2 = AnomalyDetector()+ det2.load_baselines(dump)+ alerts = det2.analyze_packet(pkt(process="app"), {"country_code": "CN"})+ assert any(a.type == "BASELINE_DEVIATION" for a in alerts)diff --git a/docs/FIREWALL.md b/docs/FIREWALL.mdnew file mode 100644index 0000000..d1f9fef--- /dev/null+++ b/docs/FIREWALL.md@@ -0,0 +1,175 @@+# Security features / Fonctionnalités de sécurité++## English++Snitch ships a threat-hunting layer on top of passive observation. **What it+does and — just as important — what it does not do:**++### Outbound firewall orchestration++Snitch does **not** filter packets in user-space. Rules you create are+applied to the OS-native firewall, best-effort:++| OS | Mechanism |+|---|---|+| Windows | `netsh advfirewall` outbound block rules |+| Linux | `iptables -A OUTPUT -j DROP` (dedicated `SNITCH_LOCK` chain for lockdown) |+| macOS | generated `pf` anchor loaded with `pfctl` |++Rule kinds: `ip`, `cidr`, `domain` (resolved once at apply time), `process`,+`port`. Rules persist in `snitch.db` and are re-applied at startup.++**Honest limits:**++- Applying rules needs the same privileges as packet capture. If the+ backend is not elevated, `applied=False` is recorded on the rule — the+ UI shows *"visibility only"*. Matching still works: packets violating a+ rule raise `BLOCKED_ATTEMPT` alerts with per-rule counters.+- macOS `pf` can't match a *process* — process rules on macOS are+ visibility-only by design.+- `domain` rules resolve the name once when created; a CDN moving IPs+ outruns the rule until it is re-created.+- **Lockdown** drops outbound traffic to *public* IPs only — loopback and+ LAN stay up so the UI remains reachable.++### Incident response++- `POST /processes/kill` / `POST /processes/suspend` — by PID, refuses+ PIDs ≤ 3 and Snitch itself. Normal OS privileges apply (you can't kill a+ root process as a normal user).+- `POST /firewall/rules`, `DELETE /firewall/rules/{id}`,+ `POST /firewall/rules/{id}/toggle`, `POST /firewall/lockdown` —+ authenticated like every endpoint.+- `GET /forensics/export?process=<name>&ip=<ip>` — investigation bundle:+ process tree (up to 8 ancestors), SHA-256 of the executable, cmdline,+ matching alerts, per-minute traffic history. `format=json|csv|stix` picks the+ output (STIX = minimal 2.1 bundle for SIEM import). Local data only;+ export is a download, never an upload.++### Threat intelligence — opt-in, off by default++`Settings → Threat intelligence` accepts a provider (`abuseipdb`, `otx`, `virustotal`)+plus **your own API key**. When enabled, newly-seen public IPs are checked+once per 24 h TTL; verdicts are cached and a `THREAT_HIT` alert fires on+`suspicious`/`malicious` verdicts. With provider `none` or an empty key,+**zero outbound calls** are made. `GET /security/ti` reports the masked+configuration; `POST /security/threat_check` runs a manual check (also+cache-aware).++### Webhooks — opt-in, off by default++`Settings → External webhook` accepts a URL and a switch. Warning and+critical alerts are POSTed live: Discord/Slack `{content}`, Telegram+`{chat_id, text}` (chat ID field shown when a telegram URL is used), any+other endpoint gets `{alert, source, text}`. Failures are logged, never+fatal.++### Detection additions++- `DNS_TUNNEL` — oversized DNS names/labels (>60 chars / label >40),+ classic exfiltration pattern; once per host per 10 min.+- `CLEARTEXT` — outbound TCP to ports that are unencrypted by design+ (80, 21, 23, 25, 110, 143…), INFO level, feeds the audit.+- `BASELINE_DEVIATION` — each process learns its usual destination+ countries over its first packets, then warns once when it reaches a new+ one. Baselines persist across restarts (`app_baselines` setting).+- `BEACON` — already shipped: regular-interval detection (CV of+ inter-arrival times) works even for tiny keep-alive traffic.+- `BLOCKED_ATTEMPT`, `LOCKDOWN`, `THREAT_HIT` — alert types added by the+ modules above.++### Security audit++`GET /security/audit` computes a 0–100 score from the last 500 alerts plus+the live graph: alert-type counts, contacts to high-risk countries,+unresolved hosts, firewall posture — and returns plain-language+recommendations. It is a *finding report*, not a certification.++---++## Français++Snitch embarque une couche de chasse aux menaces au-dessus de+l'observation passive. **Ce qu'elle fait — et, aussi important, ce qu'elle+ne fait pas :**++### Orchestration du pare-feu sortant++Snitch ne filtre **pas** les paquets en user-space. Les règles créées sont+appliquées au pare-feu natif de l'OS, au mieux :++| OS | Mécanisme |+|---|---|+| Windows | règles de blocage sortantes `netsh advfirewall` |+| Linux | `iptables -A OUTPUT -j DROP` (chaîne dédiée `SNITCH_LOCK` pour le lockdown) |+| macOS | ancre `pf` générée chargée avec `pfctl` |++Types de règles : `ip`, `cidr`, `domain` (résolu une fois à l'application),+`process`, `port`. Les règles persistent dans `snitch.db` et sont+réappliquées au démarrage.++**Limites honnêtes :**++- Appliquer les règles exige les mêmes privilèges que la capture. Sans+ élévation, `applied=False` est enregistré sur la règle — l'UI affiche+ *« visibilité seule »*. Le matching reste actif : les paquets violant une+ règle lèvent des alertes `BLOCKED_ATTEMPT` avec compteurs par règle.+- `pf` sur macOS ne peut pas matcher un *processus* — les règles processus+ y sont par conception de la visibilité seule.+- Les règles `domain` résolvent le nom une fois à la création ; un CDN qui+ change d'IP échappe à la règle jusqu'à sa recréation.+- **Lockdown** ne coupe le trafic sortant que vers les IP *publiques* —+ loopback et LAN restent actifs pour garder l'UI joignable.++### Réponse à incident++- `POST /processes/kill` / `POST /processes/suspend` — par PID, refuse les+ PID ≤ 3 et Snitch lui-même. Privilèges OS usuels (on ne tue pas un+ processus root en simple utilisateur).+- `POST /firewall/rules`, `DELETE /firewall/rules/{id}`,+ `POST /firewall/rules/{id}/toggle`, `POST /firewall/lockdown` —+ authentifiés comme tous les endpoints.+- `GET /forensics/export?process=<nom>&ip=<ip>` — paquet d'investigation :+ arbre de processus (jusqu'à 8 ancêtres), SHA-256 de l'exécutable, ligne+ de commande, alertes associées, historique par minute. `format=json|csv|stix`+ choisit la sortie (STIX = bundle 2.1 minimal pour SIEM). Données locales+ uniquement ; l'export est un téléchargement, jamais un envoi.++### Threat intelligence — opt-in, désactivé par défaut++*Réglages → Threat intelligence* accepte un fournisseur (`abuseipdb`,+`otx`, `virustotal`) plus **votre propre clé API**. Activé, chaque nouvelle IP publique+est vérifiée une fois par TTL de 24 h ; les verdicts sont cachés et une+alerte `THREAT_HIT` est émise sur verdict `suspicious`/`malicious`.+Sans fournisseur ni clé, **zéro appel sortant**. `GET /security/ti`+rapporte la configuration masquée ; `POST /security/threat_check` lance+une vérification manuelle (aussi consciente du cache).++### Webhooks — opt-in, désactivés par défaut++*Réglages → Webhook externe* accepte une URL et un interrupteur. Les+alertes warning et critiques sont POSTées en direct : Discord/Slack+`{content}`, Telegram `{chat_id, text}` (champ chat ID affiché si URL+telegram), tout autre endpoint reçoit `{alert, source, text}`. Les échecs+sont journalisés, jamais fatals.++### Ajouts de détection++- `DNS_TUNNEL` — noms/labels DNS surdimensionnés (>60 car. / label >40),+ motif classique d'exfiltration ; une fois par hôte par 10 min.+- `CLEARTEXT` — TCP sortant vers des ports non chiffrés par nature+ (80, 21, 23, 25, 110, 143…), niveau INFO, alimente l'audit.+- `BASELINE_DEVIATION` — chaque processus apprend ses pays de destination+ usuels sur ses premiers paquets, puis avertit une fois à l'atteinte d'un+ nouveau pays. Les baselines persistent (`app_baselines`).+- `BEACON` — déjà livré : détection d'intervalles réguliers (CV des+ inter-arrivées) même pour un trafic minime.+- `BLOCKED_ATTEMPT`, `LOCKDOWN`, `THREAT_HIT` — types d'alertes ajoutés+ par les modules ci-dessus.++### Audit de sécurité++`GET /security/audit` calcule un score 0–100 depuis les 500 dernières+alertes et le graphe : comptes par type, contacts vers pays à risque,+hôtes non résolus, posture pare-feu — et renvoie des recommandations en+langage clair. C'est un *rapport de constats*, pas une certification.diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 1fdcafb..933af3e 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -22,6 +22,7 @@ import Sidebar, { matchesFilter } from './components/Sidebar'import SearchBar from './components/SearchBar'import { AlertBell, AlertPanel, AlertToasts } from './components/AlertPanel'import { SettingsButton, SettingsPanel } from './components/Settings'+import { FirewallButton, FirewallPanel } from './components/Firewall'import Onboarding from './components/Onboarding'import Timeline from './components/Timeline'import Dropdown from './components/Dropdown'@@ -30,7 +31,7 @@ import { useWebSocket } from './hooks/useWebSocket'import { computePrivacyScore } from './scoring/privacy'// EN: WS URL is resolved dynamically (port + ws/wss) via api.js wsBase().// FR: L'URL WS est résolue dynamiquement (port + ws/wss) via wsBase() d'api.js.-import { useT } from './i18n'+import { useT, LANGS, LANG_NAMES } from './i18n'export default function App() {const { nodes, edges, lanDevices, packets, alerts, unread, clearUnread, status, bandwidth, capturing, toggleCapture, portFilter, updatePortFilter, excludedProcesses, updateProcessFilter, whitelistedIps, updateIpWhitelist, media, ssid, iface, watchlist, updateWatchlist } = useWebSocket(null) // EN: null → resolves the dynamic port/scheme via wsBase()@@ -39,6 +40,8 @@ export default function App() {const [view, setView] = useState('graph')const [showAlerts, setShowAlerts] = useState(false)const [showSettings, setShowSettings] = useState(false)+ const [showFirewall, setShowFirewall] = useState(false)+ const [lockdown, setLockdown] = useState(false)// EN: First-run explainer — shown once, flag persisted in localStorage.// FR: Explications de premier lancement — affichées une fois, drapeau// persisté en localStorage.@@ -199,6 +202,7 @@ export default function App() {<ProcessFilter excluded={excludedProcesses} onChange={updateProcessFilter} nodes={nodes} /><PortFilter ports={portFilter} onUpdate={updatePortFilter} /><IPWhitelist ips={whitelistedIps} onUpdate={updateIpWhitelist} />+ <FirewallButton onClick={() => setShowFirewall(v => !v)} lockdown={lockdown} /><CaptureToggle capturing={capturing} onToggle={toggleCapture} /><AlertBell unread={unread} onClick={handleBell} /><SettingsButton onClick={() => setShowSettings(v => !v)} />@@ -214,6 +218,10 @@ export default function App() {watchlist={watchlist} onWatchlist={updateWatchlist} iface={iface} />)}+ {showFirewall && (+ <FirewallPanel onClose={() => setShowFirewall(false)} onLockdownChange={setLockdown} />+ )}+{showOnboarding && <Onboarding onDone={() => setShowOnboarding(false)} />}{/* EN: Floating toasts for warning/critical alerts.@@ -752,28 +760,23 @@ function ThemeToggle() {)}-/** EN: EN/FR/ES language toggle — the headline feature.- * FR: Bascule de langue EN/FR/ES — la fonctionnalité vedette. */+/** EN: Language picker — a compact dropdown now that eight locales exist.+ * FR: Sélecteur de langue — menu déroulant compact désormais que huit+ * locales existent. */function LangToggle() {const { lang, setLang } = useT()return (- <div style={{- display: 'flex', background: 'var(--surface)',- border: '1px solid var(--border)', borderRadius: 20, overflow: 'hidden',- }}>- {['en', 'fr', 'es'].map(l => (- <button key={l} onClick={() => setLang(l)} style={{- background: lang === l ? '#3b82f6' : 'transparent',- border: 'none', cursor: 'pointer',- color: lang === l ? '#fff' : 'var(--text-muted)',- padding: '5px 12px', fontSize: 11, fontWeight: 600,- textTransform: 'uppercase',- transition: 'background 0.15s',- }}>- {l}- </button>+ <select value={lang} onChange={e => setLang(e.target.value)}+ aria-label="Language / Langue" style={{+ background: 'var(--surface)', border: '1px solid var(--border)',+ borderRadius: 20, color: 'var(--text-muted)',+ padding: '5px 10px', fontSize: 11, fontWeight: 600,+ cursor: 'pointer', outline: 'none',+ }}>+ {LANGS.map(l => (+ <option key={l} value={l}>{LANG_NAMES[l]}</option>))}- </div>+ </select>)}diff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsxindex 56e9aae..add3d97 100644--- a/frontend/src/components/AlertPanel.jsx+++ b/frontend/src/components/AlertPanel.jsx@@ -42,6 +42,12 @@ const TYPE_ICONS = {PORT_SCAN: ScanLine,UPLOAD_SPIKE: TrendingUp,WATCHLIST_HIT: ShieldAlert,+ BLOCKED_ATTEMPT: ShieldAlert,+ THREAT_HIT: ShieldAlert,+ DNS_TUNNEL: ScanLine,+ CLEARTEXT: Unlock,+ BASELINE_DEVIATION: Activity,+ LOCKDOWN: AlertTriangle,}export function AlertBell({ unread, onClick }) {diff --git a/frontend/src/components/Firewall.jsx b/frontend/src/components/Firewall.jsxnew file mode 100644index 0000000..67df600--- /dev/null+++ b/frontend/src/components/Firewall.jsx@@ -0,0 +1,313 @@+/**+ * Snitch — firewall & security panel.+ *+ * EN: Slide-over panel for the outbound-firewall orchestration: a lockdown+ * panic switch, user rules (IP / domain / process / port) with+ * enable-toggle and delete, blocked-attempt counters, and the security+ * audit report (score + findings + recommendations). Rules are applied+ * to the OS firewall best-effort by the backend — an un-applied rule is+ * marked honestly instead of pretending enforcement.+ * FR: Panneau latéral pour l'orchestration du pare-feu sortant : bouton+ * panique lockdown, règles utilisateur (IP / domaine / processus / port)+ * avec bascule et suppression, compteurs de tentatives bloquées, et le+ * rapport d'audit sécurité (score + constats + recommandations). Les+ * règles sont appliquées au pare-feu OS au mieux par le backend — une+ * règle non appliquée est marquée honnêtement au lieu de simuler.+ */+import { useState, useEffect, useCallback } from 'react'+import { ShieldCheck, X, Trash2, RefreshCw, Lock, Plus, AlertTriangle } from 'lucide-react'+import { useT } from '../i18n'+import { apiBase, authHeaders } from '../api'++const RULE_KINDS = ['ip', 'domain', 'process', 'port']++export function FirewallButton({ onClick, lockdown }) {+ const { t } = useT()+ return (+ <button onClick={onClick} aria-label="Firewall / Pare-feu"+ title={t('fw_title')} style={{+ display: 'flex', alignItems: 'center', gap: 6,+ background: lockdown ? 'var(--danger-active)' : 'var(--surface)',+ border: `1px solid ${lockdown ? '#ef4444' : 'var(--border)'}`,+ borderRadius: 20, padding: '5px 14px',+ cursor: 'pointer', color: lockdown ? 'var(--red-text)' : 'var(--text-muted)',+ fontSize: 11, fontWeight: 600,+ }}>+ <ShieldCheck size={11} />+ {lockdown ? t('fw_lockdown_on') : 'FW'}+ </button>+ )+}++export function FirewallPanel({ onClose, onLockdownChange }) {+ const { t } = useT()+ const [rules, setRules] = useState([])+ const [lockdown, setLockdown] = useState(false)+ const [status, setStatus] = useState(null)+ const [kind, setKind] = useState('ip')+ const [value, setValue] = useState('')+ const [err, setErr] = useState('')+ const [audit, setAudit] = useState(null)++ const refresh = useCallback(async () => {+ const base = await apiBase()+ const headers = await authHeaders()+ try {+ const [r, s] = await Promise.all([+ fetch(`${base}/firewall/rules`, { headers }).then(x => x.json()),+ fetch(`${base}/firewall/status`, { headers }).then(x => x.json()),+ ])+ setRules(r.rules || [])+ setLockdown(!!r.lockdown)+ setStatus(s)+ onLockdownChange?.(!!r.lockdown)+ } catch { /* leave previous state */ }+ }, [onLockdownChange])++ const refreshAudit = useCallback(async () => {+ const base = await apiBase()+ try {+ setAudit(await fetch(`${base}/security/audit`, { headers: await authHeaders() }).then(r => r.json()))+ } catch { setAudit(null) }+ }, [])++ useEffect(() => { refresh(); refreshAudit() }, [refresh, refreshAudit])++ async function post(path, body, method = 'POST') {+ const base = await apiBase()+ const res = await fetch(`${base}${path}`, {+ method,+ headers: await authHeaders({ 'Content-Type': 'application/json' }),+ body: body ? JSON.stringify(body) : undefined,+ })+ if (!res.ok) {+ const j = await res.json().catch(() => ({}))+ throw new Error(j.detail || res.statusText)+ }+ return res.json()+ }++ async function addRule(e) {+ e.preventDefault()+ const v = value.trim()+ if (!v) return+ setErr('')+ try {+ await post('/firewall/rules', { kind, value: v })+ setValue('')+ refresh()+ } catch (ex) { setErr(String(ex.message || ex)) }+ }++ async function toggleRule(id, enabled) {+ await post(`/firewall/rules/${encodeURIComponent(id)}/toggle`, { enabled })+ refresh()+ }++ async function deleteRule(id) {+ await post(`/firewall/rules/${encodeURIComponent(id)}`, null, 'DELETE')+ refresh()+ }++ async function exportForensics(format) {+ // EN: Authenticated download — fetch the bundle, then hand it to the+ // browser as a blob (a bare <a href> can't carry the token header).+ // FR: Téléchargement authentifié — fetch du bundle puis remise au+ // navigateur en blob (un <a href> nu ne porte pas le token).+ const base = await apiBase()+ const res = await fetch(`${base}/forensics/export?format=${format}`,+ { headers: await authHeaders() })+ if (!res.ok) { setErr(res.statusText); return }+ const blob = await res.blob()+ const a = document.createElement('a')+ a.href = URL.createObjectURL(blob)+ a.download = `snitch-forensics.${format === 'stix' ? 'stix.json' : format}`+ a.click()+ URL.revokeObjectURL(a.href)+ }++ async function toggleLockdown() {+ const on = !lockdown+ // EN: Engaging lockdown is disruptive — a confirmation is mandatory.+ // FR: Activer le lockdown est perturbant — une confirmation est requise.+ if (on && !window.confirm(t('fw_lockdown_confirm'))) return+ try {+ await post('/firewall/lockdown', { on })+ setLockdown(on)+ onLockdownChange?.(on)+ refresh()+ } catch (ex) { setErr(String(ex.message || ex)) }+ }++ const row = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '1px solid var(--bg)' }+ const label = { fontSize: 12, color: 'var(--text)', fontWeight: 600 }+ const hint = { fontSize: 10, color: 'var(--text-muted)', marginTop: 2 }+ const input = {+ background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6,+ color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none',+ }++ return (+ <div role="dialog" aria-label="Firewall / Pare-feu" style={{+ position: 'absolute', top: 56, right: 16, zIndex: 200,+ width: 400, maxHeight: 'calc(100vh - 80px)',+ background: 'var(--surface)', border: '1px solid var(--border)',+ borderRadius: 12, overflow: 'hidden auto',+ boxShadow: '0 8px 40px rgba(0,0,0,0.6)',+ }}>+ <div style={{+ padding: '14px 18px', borderBottom: '1px solid var(--border)',+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',+ position: 'sticky', top: 0, background: 'var(--surface)', zIndex: 1,+ }}>+ <span style={{ fontWeight: 700, fontSize: 13, color: 'var(--text)' }}>{t('fw_title')}</span>+ <button onClick={onClose} aria-label={t('close')} style={{ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer' }}>+ <X size={16} />+ </button>+ </div>++ <div style={{ padding: '4px 18px 16px' }}>+ {/* Lockdown / Confinement */}+ <div style={row}>+ <div>+ <div style={{ ...label, display: 'flex', alignItems: 'center', gap: 6 }}>+ <Lock size={11} /> {t('fw_lockdown')}+ </div>+ <div style={hint}>{t('fw_lockdown_hint')}</div>+ </div>+ <button onClick={toggleLockdown} role="switch" aria-checked={lockdown} style={{+ width: 36, height: 20, borderRadius: 10, border: 'none',+ background: lockdown ? '#ef4444' : 'var(--bg)',+ outline: `1px solid ${lockdown ? '#ef4444' : 'var(--border)'}`,+ cursor: 'pointer', position: 'relative', flexShrink: 0,+ }}>+ <div style={{+ width: 14, height: 14, borderRadius: '50%', background: 'var(--text)',+ position: 'absolute', top: 3, left: lockdown ? 19 : 3,+ transition: 'left 0.15s',+ }} />+ </button>+ </div>++ {/* EN: Platform honesty — the backend reports whether native+ enforcement is available on this OS/privilege level.+ FR: Honnêteté plateforme — le backend rapporte si l'application+ native est disponible sur cet OS/niveau de privilège. */}+ {status && (+ <div style={{ ...hint, marginBottom: 4 }}>+ {status.supported+ ? t('fw_supported', status.platform)+ : t('fw_unsupported')}+ {status.demo && ` · ${t('fw_demo')}`}+ </div>+ )}++ {/* Add rule / Ajouter une règle */}+ <form onSubmit={addRule} style={{ display: 'flex', gap: 6, margin: '10px 0 4px' }}>+ <select value={kind} onChange={e => setKind(e.target.value)} aria-label={t('fw_kind')} style={{ ...input, maxWidth: 110 }}>+ {RULE_KINDS.map(k => <option key={k} value={k}>{t(`fw_kind_${k}`)}</option>)}+ </select>+ <input value={value} onChange={e => setValue(e.target.value)}+ placeholder={t(`fw_ph_${kind}`)} aria-label={t('fw_value')}+ style={{ ...input, flex: 1 }} />+ <button type="submit" style={{+ background: '#3b82f6', border: 'none', borderRadius: 6,+ color: '#fff', padding: '6px 10px', cursor: 'pointer',+ display: 'flex', alignItems: 'center',+ }}><Plus size={12} /></button>+ </form>+ {err && <div style={{ fontSize: 10, color: '#ef4444', marginBottom: 4 }}>{err}</div>}++ {/* Rules list / Liste des règles */}+ <div style={{ ...label, marginTop: 10, marginBottom: 4 }}>{t('fw_rules')}</div>+ {rules.length === 0 && <div style={{ ...hint, padding: '6px 0' }}>{t('fw_empty')}</div>}+ {rules.map(r => (+ <div key={r.id} style={{ ...row, gap: 8 }}>+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <span style={{+ fontSize: 9, fontWeight: 700, textTransform: 'uppercase',+ color: r.enabled ? 'var(--blue-text)' : 'var(--text-faint)',+ background: 'var(--bg)', borderRadius: 4, padding: '1px 5px',+ }}>{r.kind}</span>+ <span style={{ fontSize: 11, color: r.enabled ? 'var(--text)' : 'var(--text-faint)', fontFamily: 'monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {r.value}+ </span>+ </div>+ <div style={hint}>+ {r.blocked > 0 && `${t('fw_blocked', r.blocked)} · `}+ {r.applied ? t('fw_applied') : t('fw_not_applied')}+ </div>+ </div>+ <button onClick={() => toggleRule(r.id, !r.enabled)} title={r.enabled ? t('fw_disable') : t('fw_enable')} style={{+ width: 30, height: 17, borderRadius: 9, border: 'none', flexShrink: 0,+ background: r.enabled ? '#3b82f6' : 'var(--bg)',+ outline: '1px solid var(--border)', cursor: 'pointer', position: 'relative',+ }}>+ <div style={{+ width: 11, height: 11, borderRadius: '50%', background: 'var(--text)',+ position: 'absolute', top: 3, left: r.enabled ? 16 : 3,+ }} />+ </button>+ <button onClick={() => deleteRule(r.id)} aria-label={t('fw_delete')} style={{+ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', padding: 2,+ }}><Trash2 size={12} /></button>+ </div>+ ))}++ {/* Security audit / Audit de sécurité */}+ <div style={{ ...row, display: 'block', borderTop: '1px solid var(--border)', marginTop: 12 }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div style={label}>{t('audit_title')}</div>+ <button onClick={refreshAudit} aria-label={t('audit_refresh')} style={{+ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', padding: 2,+ }}><RefreshCw size={12} /></button>+ </div>+ {audit ? (+ <>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, margin: '6px 0' }}>+ <span style={{+ fontSize: 26, fontWeight: 700,+ color: audit.score >= 80 ? '#4ade80' : audit.score >= 50 ? '#f59e0b' : '#ef4444',+ }}>{audit.score}</span>+ <span style={{ fontSize: 10, color: 'var(--text-muted)' }}>/100 · {audit.period}</span>+ </div>+ {audit.critical + audit.warning > 0 && (+ <div style={{ fontSize: 10, color: 'var(--text-muted)', marginBottom: 6 }}>+ {audit.critical} {t('audit_critical')} · {audit.warning} {t('audit_warning')}+ </div>+ )}+ {audit.findings?.high_risk_countries?.length > 0 && (+ <div style={{ fontSize: 10, color: '#f59e0b', marginBottom: 4 }}>+ <AlertTriangle size={10} style={{ verticalAlign: -1 }} /> {t('audit_risky', audit.findings.high_risk_countries.length)}+ </div>+ )}+ {(audit.recommendations || []).map((r, i) => (+ <div key={i} style={{+ fontSize: 10, lineHeight: 1.5, marginBottom: 4,+ color: { high: '#f87171', medium: '#fbbf24', low: 'var(--text-muted)', info: 'var(--text-muted)' }[r.level] || 'var(--text-muted)',+ }}>+ • {r.text}+ </div>+ ))}+ </>+ ) : (+ <div style={hint}>{t('audit_loading')}</div>+ )}+ {/* Forensics export / Export forensique */}+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>+ <span style={hint}>{t('fw_forensics')}</span>+ {['json', 'csv', 'stix'].map(f => (+ <button key={f} onClick={() => exportForensics(f)} style={{+ background: 'var(--bg)', border: '1px solid var(--border)',+ borderRadius: 5, color: 'var(--text-muted)', fontSize: 9,+ fontWeight: 700, padding: '3px 8px', cursor: 'pointer',+ textTransform: 'uppercase',+ }}>{f}</button>+ ))}+ </div>+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/components/Settings.jsx b/frontend/src/components/Settings.jsxindex c7c91a5..a8510fa 100644--- a/frontend/src/components/Settings.jsx+++ b/frontend/src/components/Settings.jsx@@ -14,7 +14,7 @@*/import { useState, useEffect } from 'react'import { Settings as SettingsIcon, X, FolderOpen, Download, ShieldCheck } from 'lucide-react'-import { useT } from '../i18n'+import { useT, LANGS, LANG_NAMES } from '../i18n'import { apiBase, authHeaders } from '../api'export function SettingsButton({ onClick }) {@@ -168,17 +168,13 @@ export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchl{/* Language / Langue */}<div style={row}><div><div style={label}>{t('settings_language')}</div></div>- <div style={{ display: 'flex', gap: 4 }}>- {['en', 'fr', 'es'].map(l => (- <button key={l} onClick={() => { setLang(l); save('language', l) }} style={{- background: lang === l ? '#3b82f6' : 'var(--bg)',- border: '1px solid var(--border)', borderRadius: 6,- color: lang === l ? '#fff' : 'var(--text-muted)',- padding: '4px 12px', fontSize: 11, cursor: 'pointer',- textTransform: 'uppercase', fontWeight: 600,- }}>{l}</button>- ))}- </div>+ <select+ value={lang}+ onChange={e => { setLang(e.target.value); save('language', e.target.value) }}+ style={{ background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '4px 8px', fontSize: 11 }}+ >+ {LANGS.map(l => <option key={l} value={l}>{LANG_NAMES[l]}</option>)}+ </select></div>{/* Retention / Rétention */}@@ -305,6 +301,106 @@ export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchl)}</div>+ {/* Threat intelligence / Renseignement sur les menaces */}+ <div style={{ ...row, display: 'block' }}>+ <div style={label}>{t('ti_title')}</div>+ <div style={hint}>{t('ti_hint')}</div>+ <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>+ <select+ value={settings?.ti_provider ?? 'none'}+ onChange={e => {+ const v = e.target.value+ setSettings(s => ({ ...s, ti_provider: v }))+ save('ti_provider', v)+ }}+ style={{ background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '4px 8px', fontSize: 11 }}+ >+ <option value="none">{t('ti_none')}</option>+ <option value="abuseipdb">AbuseIPDB</option>+ <option value="otx">AlienVault OTX</option>+ <option value="virustotal">VirusTotal</option>+ </select>+ <form onSubmit={e => {+ e.preventDefault()+ const v = e.target.elements.tikey.value.trim()+ save('ti_api_key', v)+ }} style={{ flex: 1, display: 'flex', gap: 6 }}>+ <input+ name="tikey"+ type="password"+ defaultValue={settings?.ti_api_key ?? ''}+ placeholder={t('ti_key_ph')}+ aria-label={t('ti_key')}+ autoComplete="off"+ style={{ flex: 1, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '4px 8px', fontSize: 11, outline: 'none' }}+ />+ <button type="submit" style={{+ background: 'var(--bg)', border: '1px solid var(--border)',+ borderRadius: 6, color: 'var(--text-dim)', padding: '4px 10px',+ fontSize: 10, cursor: 'pointer',+ }}>{t('save')}</button>+ </form>+ </div>+ <div style={{ ...hint, marginTop: 4 }}>{t('ti_privacy')}</div>+ </div>++ {/* External webhook / Webhook externe */}+ <div style={{ ...row, display: 'block' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div>+ <div style={label}>{t('wh_title')}</div>+ <div style={hint}>{t('wh_hint')}</div>+ </div>+ <button+ onClick={() => {+ const v = !settings?.webhook_enabled+ setSettings(s => ({ ...s, webhook_enabled: v }))+ save('webhook_enabled', v)+ }}+ role="switch" aria-checked={!!settings?.webhook_enabled}+ style={{+ width: 36, height: 20, borderRadius: 10, border: 'none',+ background: settings?.webhook_enabled ? '#3b82f6' : 'var(--bg)',+ outline: '1px solid var(--border)', cursor: 'pointer',+ position: 'relative', flexShrink: 0,+ }}>+ <div style={{+ width: 14, height: 14, borderRadius: '50%', background: 'var(--text)',+ position: 'absolute', top: 3, left: settings?.webhook_enabled ? 19 : 3,+ transition: 'left 0.15s',+ }} />+ </button>+ </div>+ <form onSubmit={e => {+ e.preventDefault()+ save('webhook_url', e.target.elements.whurl.value.trim())+ save('telegram_chat_id', e.target.elements.whchat?.value.trim() || '')+ }} style={{ display: 'flex', gap: 6, marginTop: 8 }}>+ <input+ name="whurl"+ defaultValue={settings?.webhook_url ?? ''}+ placeholder={t('wh_url_ph')}+ aria-label={t('wh_url')}+ style={{ flex: 1, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none' }}+ />+ {(settings?.webhook_url || '').includes('telegram') && (+ <input+ name="whchat"+ defaultValue={settings?.telegram_chat_id ?? ''}+ placeholder={t('wh_chat_ph')}+ aria-label={t('wh_chat')}+ style={{ width: 90, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none' }}+ />+ )}+ <button type="submit" style={{+ background: 'var(--bg)', border: '1px solid var(--border)',+ borderRadius: 6, color: 'var(--text-dim)', padding: '6px 12px',+ fontSize: 10, cursor: 'pointer',+ }}>{t('save')}</button>+ </form>+ <div style={{ ...hint, marginTop: 4 }}>{t('wh_privacy')}</div>+ </div>+{/* Updates (Electron only) / Mises à jour (Electron seul) */}{window.snitch?.getUpdateStatus && (<div style={{ ...row, display: 'block' }}>diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsxindex 00af28c..04d017d 100644--- a/frontend/src/components/Sidebar.jsx+++ b/frontend/src/components/Sidebar.jsx@@ -9,10 +9,11 @@* listes déroulantes appareils LAN + hôtes externes, et le flux de* paquets récents.*/-import { Wifi, Smartphone, Monitor, Tv, Cpu, HelpCircle, ShieldOff } from 'lucide-react'+import { Wifi, Smartphone, Monitor, Tv, Cpu, HelpCircle, ShieldOff, Shield, Skull, PauseCircle } from 'lucide-react'import PrivacyScore from './PrivacyScore'import BandwidthChart from './BandwidthChart'import { useT } from '../i18n'+import { apiBase, authHeaders } from '../api'// EN: Lucide icon per LAN device type. / FR: Icône Lucide par type d'appareil LAN.const DEVICE_ICONS = {@@ -288,8 +289,40 @@ function NodeRow({ node }) {)}-/** EN: Selected-node fields + top processes + whitelist action.- * FR: Champs du nœud sélectionné + top processus + action de whitelist. */+/**+ * EN: Incident-response actions — block a remote IP via /firewall/rules and+ * kill/suspend a process via /processes/*. Both are authenticated POSTs;+ * failures are ignored silently (the backend returns 400 with detail).+ * FR: Actions de réponse à incident — bloquer une IP via /firewall/rules et+ * tuer/suspendre un processus via /processes/*. POSTs authentifiés ; les+ * échecs sont ignorés en silence (le backend renvoie 400 avec détail).+ */+async function blockIp(ip) {+ if (!ip) return+ const base = await apiBase()+ try {+ await fetch(`${base}/firewall/rules`, {+ method: 'POST',+ headers: await authHeaders({ 'Content-Type': 'application/json' }),+ body: JSON.stringify({ kind: 'ip', value: ip }),+ })+ } catch { /* best effort */ }+}++async function procAction(action, pid) {+ if (!pid) return+ const base = await apiBase()+ try {+ await fetch(`${base}/processes/${action}`, {+ method: 'POST',+ headers: await authHeaders({ 'Content-Type': 'application/json' }),+ body: JSON.stringify({ pid }),+ })+ } catch { /* best effort */ }+}++/** EN: Selected-node fields + top processes + whitelist/block actions.+ * FR: Champs du nœud sélectionné + top processus + actions whitelist/blocage. */function NodeDetail({ node, onWhitelist }) {const { t } = useT()const fields = [@@ -355,27 +388,58 @@ function NodeDetail({ node, onWhitelist }) {</div>{processes.map(([name, stats]) => (<div key={name} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 3, alignItems: 'center' }}>- <span style={{ fontSize: 10, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 150 }}>+ <span style={{ fontSize: 10, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 130 }}>{name}</span>- <span style={{ fontSize: 9, color: 'var(--text-faint)', flexShrink: 0 }}>{fmt(stats.bytes)}</span>+ <span style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>+ <span style={{ fontSize: 9, color: 'var(--text-faint)' }}>{fmt(stats.bytes)}</span>+ {/* EN: Kill/suspend — only when a PID is known for the process.+ FR: Tuer/suspendre — seulement si un PID est connu. */}+ {stats.pid && (+ <>+ <button onClick={() => procAction('suspend', stats.pid)}+ title={t('proc_suspend')} aria-label={t('proc_suspend')}+ style={{ background: 'none', border: 'none', color: '#f59e0b', cursor: 'pointer', padding: 0, display: 'flex' }}>+ <PauseCircle size={11} />+ </button>+ <button onClick={() => procAction('kill', stats.pid)}+ title={t('proc_kill')} aria-label={t('proc_kill')}+ style={{ background: 'none', border: 'none', color: '#ef4444', cursor: 'pointer', padding: 0, display: 'flex' }}>+ <Skull size={11} />+ </button>+ </>+ )}+ </span></div>))}</>)}- {/* EN: "Mark as trusted" — sends the IP to the whitelist endpoint.- FR: « Marquer comme fiable » — envoie l'IP à l'endpoint de whitelist. */}- {node.id !== 'local' && node.ip && onWhitelist && (- <button onClick={() => onWhitelist(node.ip)} style={{- marginTop: 10, width: '100%', display: 'flex', alignItems: 'center',- justifyContent: 'center', gap: 6,- background: 'none', border: '1px solid #22c55e', borderRadius: 6,- padding: '5px 0', color: 'var(--green-text)', fontSize: 10, cursor: 'pointer',- }}>- <ShieldOff size={11} />- {t('whitelist_action')}- </button>+ {/* EN: "Mark as trusted" + "Block" — whitelist and firewall rule.+ FR: « Marquer comme fiable » + « Bloquer » — whitelist et règle pare-feu. */}+ {node.id !== 'local' && node.ip && (+ <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>+ {onWhitelist && (+ <button onClick={() => onWhitelist(node.ip)} style={{+ flex: 1, display: 'flex', alignItems: 'center',+ justifyContent: 'center', gap: 6,+ background: 'none', border: '1px solid #22c55e', borderRadius: 6,+ padding: '5px 0', color: 'var(--green-text)', fontSize: 10, cursor: 'pointer',+ }}>+ <ShieldOff size={11} />+ {t('whitelist_action')}+ </button>+ )}+ <button onClick={() => blockIp(node.ip || node.id)} style={{+ flex: 1, display: 'flex', alignItems: 'center',+ justifyContent: 'center', gap: 6,+ background: 'none', border: '1px solid #ef4444', borderRadius: 6,+ padding: '5px 0', color: 'var(--red-text)', fontSize: 10, cursor: 'pointer',+ }}>+ <Shield size={11} />+ {t('block_action')}+ </button>+ </div>)}</div>)diff --git a/frontend/src/i18n.jsx b/frontend/src/i18n.jsxindex 48c428b..ae99f95 100644--- a/frontend/src/i18n.jsx+++ b/frontend/src/i18n.jsx@@ -1,818 +1,60 @@/**- * Snitch — internationalization (English / Français).+ * Snitch — internationalization.*- * EN: Tiny homemade i18n layer. Two flat dictionaries (`en` / `fr`) keyed by- * string. Values can be plain strings or functions for interpolation,- * e.g. t('lan_devices', 3) → "3 devices LAN" / "3 devices LAN".- * `useT()` returns { lang, t, setLang } to any component.- * FR: Petite couche i18n maison. Deux dictionnaires plats (`en` / `fr`) indexés- * par chaîne. Les valeurs peuvent être des chaînes simples ou des fonctions- * pour l'interpolation, ex. t('lan_devices', 3) → "3 devices LAN".- * `useT()` renvoie { lang, t, setLang } à tout composant.+ * EN: Tiny homemade i18n layer. Dictionaries live in isolated files under+ * `src/locales/` — one per language — so the community can contribute+ * translations with a simple pull request (see CONTRIBUTING.md).+ * Values can be plain strings or functions for interpolation, e.g.+ * t('lan_devices', 3). `useT()` returns { lang, t, setLang }.+ * FR: Petite couche i18n maison. Les dictionnaires vivent dans des fichiers+ * isolés sous `src/locales/` — un par langue — pour que la communauté+ * contribue des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation, ex.+ * t('lan_devices', 3). `useT()` renvoie { lang, t, setLang }.*/import { createContext, useContext, useState } from 'react'--// ── English dictionary / Dictionnaire anglais ────────────────────────────────-const en = {- // Navigation- nav_graph: 'Graph',- nav_map: 'Map',-- // Status badge / Badge de statut- status_connected: 'Live',- status_connecting: 'Connecting…',- status_disconnected: 'Disconnected',- status_error: 'Error',- lan_devices: n => `${n} device${n > 1 ? 's' : ''} LAN`,-- // Legend / Légende- legend_alert: 'Alert',- legend_unknown: 'Unknown',- 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',- tagline: "Track every hidden flow.",- footer_credit: 'Developed by aiXis',- stat_lan: 'LAN Devices',- stat_ext: 'Ext. hosts',- stat_traffic: 'Traffic',-- // Sidebar sections / Sections de la barre latérale- section_lan: n => `LAN Devices (${n})`,- section_ext: (n, total) => total ? `External hosts (${n}/${total})` : `External hosts (${n})`,- section_packets: 'Recent traffic',-- // Node detail field labels / Étiquettes des champs de détail de nœud- field_ip: 'IP',- field_mac: 'MAC',- field_hostname: 'Hostname',- field_vendor: 'Vendor',- field_type: 'Type',- field_country: 'Country',- field_city: 'City',- field_org: 'Org',- field_category: 'Category',- field_traffic: 'Traffic',- field_packets: 'Packets',- processes: 'Processes',- online: 'online',- offline: 'offline',-- // Search / Recherche- search_placeholder: 'Search host, IP, country…',- cat_all: 'All',- cat_unknown: 'Unknown',- cat_alerted: 'Alerts',- cat_safe: 'Safe',- cat_tracking: 'Tracking',- cat_cdn: 'CDN',- cat_dns: 'DNS',- cat_admin: 'Admin',- cat_local: 'Local',- cat_lan_device: 'LAN device',- cat_other: 'Other',-- // EN: Node names + identification hints shown to the user.- // FR: Noms de nœuds + indices d'identification affichés à l'utilisateur.- node_local: 'This Device',- hint_local: 'This is THIS machine — the one running Snitch. Everything it sends or receives radiates from the center of the graph.',- unidentified: 'unidentified',- devtype_router: 'Router',- devtype_phone: 'Phone',- devtype_pc: 'Computer',- devtype_tv: 'TV',- devtype_iot: 'IoT device',- devtype_unknown: 'Unknown type',- hint_unidentified: "Not identified yet — its name appears when it announces itself (DNS/mDNS) or its MAC vendor is known. If you don't recognize it, check your router's client list.",- hint_unresolved: 'Not yet named — the domain appears when a DNS answer or TLS handshake reveals it.',- hint_private_mac: 'Private (randomized) MAC address — iOS/Android/Windows hide the real one, so the vendor can\'t be identified. This is normal privacy behavior.',- hint_gateway: 'This is your internet box/router — ALL your traffic physically passes through it, so seeing it communicate is normal and expected.',- hint_lan_idle: 'Seen on your network via the neighbour table — no data exchanged. A dashed edge means "present", not "talking".',- hint_lan_active: b => `${b} exchanged — usually automatic announcements (Bonjour/mDNS, file sharing). Watch it if the volume climbs.`,- ext_empty: "No external connections yet — anything your machine talks to will appear here.",- legend_edge_solid: 'solid line = traffic',- legend_edge_dashed: 'dashed = seen, no data',- legend_ring_safe: 'green ring = identified, safe',- legend_ring_warn: 'amber ring = suspicious',- legend_ring_crit: 'red ring = alert',- legend_ring_none: 'no ring = unidentified, neutral',- legend_perimeter: 'LAN perimeter',- perim_lan: 'LOCAL NETWORK',-- // Alert panel / Panneau d'alertes- alerts_title: 'Alerts',- alerts_total: 'total',- alerts_empty: 'No alerts yet',- alert_NEW_HOST: 'New host',- alert_SUSPICIOUS_PROCESS: 'Suspicious process',- alert_SUSPICIOUS_PORT: 'Suspicious port',- alert_BEACON: 'Beacon C2',- alert_VOLUME_SPIKE: 'Traffic spike',- alert_NEW_LAN_DEVICE: 'New device',- alert_DEVICE_OFFLINE: 'Device offline',- alert_MEDIA_EXFIL: 'Media exfiltration',- alert_PORT_SCAN: 'Port scan',- alert_UPLOAD_SPIKE: 'Upload spike',- alert_WATCHLIST_HIT: 'Watchlist hit',- // EN: Full alert messages built from backend codes + details — the backend- // only sends type + params, never prose.- // FR: Messages d'alerte complets construits depuis les codes + détails du- // 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 => `Data spike to ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} KB in ${d.window_s}s`,- alertmsg_MEDIA_EXFIL: d => `Suspected ${d.device} exfiltration: ${d.process} → ${d.host || d.ip}`,- alertmsg_NEW_LAN_DEVICE: d => `New device on the network: ${d.host || d.ip}`,- alertmsg_DEVICE_OFFLINE: d => `Device went offline: ${d.host || d.ip}`,- alertmsg_PORT_SCAN: d => `Port scan: ${d.source || d.ip} touched ${d.ports}+ ports in ${d.window_s}s`,- alertmsg_UPLOAD_SPIKE: d => `Upload spike: ${d.process} sent ${d.mb} MB in ${d.window_s}s`,- alertmsg_WATCHLIST_HIT: d => `Watchlist hit: ${d.match} (${d.host || d.ip}) — ${d.process || 'unknown process'}`,- time_just_now: 'just now',- time_seconds: n => `${n}s ago`,- time_minutes: n => `${n}min ago`,- time_hours: n => `${n}h ago`,-- // Privacy score / Score de confidentialité- privacy_title: 'Privacy Score',- privacy_critical_label: 'Critical',- privacy_excellent_label: 'Excellent',- privacy_risk_factors: n => `${n} risk factor${n !== 1 ? 's' : ''}`,- privacy_more_factors: n => `+${n} more factor${n > 1 ? 's' : ''}`,- privacy_label_excellent: 'Excellent',- privacy_label_good: 'Good',- privacy_label_average: 'Average',- privacy_label_weak: 'Weak',- privacy_label_critical: 'Critical',-- // Timeline- timeline_packets: n => `${n.toLocaleString()} packets`,- timeline_alerts: n => `${n} alert${n > 1 ? 's' : ''}`,- timeline_live: 'Live',-- // Capture toggle / Bascule de capture- capture_stop: 'Stop',- capture_start: 'Start',- capture_stopping: 'Stopping…',- capture_starting: 'Starting…',-- // Port filter / Filtre de ports- port_filter: 'Ports',- port_all: 'All ports',- port_placeholder: 'Add port (e.g. 443)',- port_invalid: 'Invalid port',-- // Export- export_btn: 'Export',- export_graph_json: 'Graph (JSON)',- export_graph_csv: 'Graph (CSV)',- export_alerts_json: 'Alerts (JSON)',- export_alerts_csv: 'Alerts (CSV)',-- // Process filter / Filtre de processus- process_filter: 'Apps',- process_filter_hint: 'Click to hide app from graph',- process_none: 'No processes detected yet',- process_clear: 'Show all apps',-- // IP whitelist / Liste blanche d'IP- ip_whitelist: 'Trusted',- ip_whitelist_hint: 'Trusted IPs are no longer captured or shown',- ip_placeholder: 'Add IP (e.g. 1.1.1.1)',- ip_invalid: 'Invalid IP address',- ip_clear: 'Clear whitelist',- whitelist_action: 'Mark as trusted',-- // Map / Carte- map_you: 'You',- map_located: n => `${n} located host${n !== 1 ? 's' : ''}`,- map_no_geo: 'no geo',-- // Scoring factor labels / Libellés des facteurs de score- score_trackers: n => `${n} tracker${n > 1 ? 's' : ''} contacted`,- score_tracker_traffic: pct => `${pct}% traffic to trackers`,- score_ad_networks: n => `${n} ad network${n > 1 ? 's' : ''}`,- score_beacons: n => `${n} beacon behavior${n > 1 ? 's' : ''}`,- score_susp_proc: n => `${n} suspicious process${n > 1 ? 'es' : ''}`,- score_susp_ports: n => `${n} dangerous port${n > 1 ? 's' : ''}`,- score_critical_alerts: n => `${n} critical alert${n > 1 ? 's' : ''}`,- score_warnings: n => `${n} warnings`,- score_https_ratio: pct => `${pct}% HTTPS traffic`,- score_no_trackers: 'No trackers detected',-- // Settings / Réglages- settings_title: 'Settings',- settings_saved: 'Saved',- close: 'Close',- settings_language: 'Language / Langue',- theme_toggle: 'Light / dark theme',- settings_retention: 'History retention',- settings_retention_hint: 'How long traffic & alert history is kept',- settings_interface: 'Capture interface',- settings_interface_hint: 'Which network adapter is sniffed (restart capture to apply)',- settings_interface_auto: 'Auto (first non-loopback)',- settings_upload: 'Upload alert threshold',- settings_upload_hint: 'Warn when one process uploads more than this per minute',- settings_off: 'Off',- watchlist_title: 'Watchlist',- watchlist_hint: 'Get alerted whenever traffic touches these IPs or domains',- watchlist_placeholder: '203.0.113.7 or example.com',- watchlist_add: 'Add',- watchlist_remove: 'Remove',- update_title: 'Updates',- update_checking: 'Checking for updates…',- update_available: v => `Update available: v${v} — downloading`,- update_downloading: p => `Downloading update… ${p}%`,- update_ready: v => `v${v} downloaded — restart to install`,- update_none: 'Snitch is up to date',- update_error: 'Update check failed',- update_idle: 'No check yet',- update_restart: 'Restart & install',- update_check_btn: 'Check now',- update_auto: 'Check automatically',- update_privacy: 'Checks github.com for new releases — the only outbound call besides the GeoIP download.',- geo_title: 'Geolocation database',- geo_present: dbs => `Installed: ${dbs}`,- geo_none: 'Not installed — IPs are not geolocated',- geo_download_btn: 'Download DB-IP Lite (free)',- geo_consent: 'Downloads ~50 MB from db-ip.com (CC BY 4.0). This is the only outbound call Snitch can make.',- geo_downloading: 'Downloading…',- geo_done: n => `Downloaded ${n} database(s)`,- geo_failed: 'Download failed — check your connection',- diag_title: 'Diagnostics',- diag_hint: 'Logs and system info for bug reports',- diag_open_logs: 'Logs',- diag_export: 'Export',- settings_note: 'All settings are stored locally. Snitch never sends data to third parties.',- nav_apps: 'Apps',- ignore_alert: 'Ignore this alert type/host',-- // Apps view / Vue applications- apps_empty: 'No process attributed yet',- apps_process: 'Process',- apps_destinations: 'Hosts',- apps_packets: 'Packets',- apps_volume: 'Volume',- apps_top_dest: 'Top destinations',- apps_history_60m: 'Last hour (bytes/min)',- alertmsg_NEW_HOSTS: n => `${n} new host${n > 1 ? 's' : ''} contacted`,- settings_autolaunch: 'Launch at login',- settings_autolaunch_hint: 'Start Snitch automatically when you sign in',-- // Onboarding / Premier lancement- onboard_title: 'Welcome to Snitch',- onboard_sub: 'Real-time network traffic visualizer — private by design.',- onboard_priv_title: 'Everything stays on this machine',- onboard_priv_body: 'Traffic metadata, alerts and history are stored in a local SQLite database. No account, no cloud, no telemetry.',- onboard_capture_title: 'What is captured',- onboard_capture_body: 'Packet headers only: destination IPs, ports, volumes, process names, DNS names and TLS server names (SNI). Payloads are never read.',- onboard_out_title: 'What leaves the machine',- onboard_out_body: 'Nothing by default. The only possible outbound call is the geolocation database download, which you trigger yourself in Settings.',- onboard_go: 'Got it',-}--// ── Dictionnaire français / French dictionary ────────────────────────────────-const fr = {- // Navigation- nav_graph: 'Graphe',- nav_map: 'Carte',-- // Badge de statut / Status badge- status_connected: 'En direct',- status_connecting: 'Connexion…',- status_disconnected: 'Déconnecté',- status_error: 'Erreur',- lan_devices: n => `${n} appareil${n > 1 ? 's' : ''} LAN`,-- // Légende / Legend- legend_alert: 'Alerte',- legend_unknown: 'Inconnu',- legend_router: 'Routeur',- legend_phone: 'Téléphone',- legend_pc: 'PC',- legend_iot: 'IoT',- legend_https: 'HTTPS',- legend_tracking: 'Pistage',- legend_cdn: 'CDN',- legend_dns: 'DNS',-- // En-tête de barre latérale + stats / Sidebar header + stats- app_name: 'SNITCH',- tagline: 'Traquez chaque flux masqué.',- footer_credit: 'Développé par aiXis',- stat_lan: 'Appareils LAN',- stat_ext: 'Hôtes ext.',- stat_traffic: 'Trafic',-- // Sections de la barre latérale / Sidebar sections- section_lan: n => `Appareils LAN (${n})`,- section_ext: (n, total) => total ? `Hôtes externes (${n}/${total})` : `Hôtes externes (${n})`,- section_packets: 'Flux récents',-- // Étiquettes des champs de détail de nœud / Node detail field labels- field_ip: 'IP',- field_mac: 'MAC',- field_hostname: 'Nom d\'hôte',- field_vendor: 'Fabricant',- field_type: 'Type',- field_country: 'Pays',- field_city: 'Ville',- field_org: 'Org',- field_category: 'Catégorie',- field_traffic: 'Trafic',- field_packets: 'Paquets',- processes: 'Processus',- online: 'en ligne',- offline: 'hors ligne',-- // Recherche / Search- search_placeholder: 'Rechercher hôte, IP, pays…',- cat_all: 'Tout',- cat_unknown: 'Inconnu',- cat_alerted: 'Alertes',- cat_safe: 'Sûr',- cat_tracking: 'Pistage',- cat_cdn: 'CDN',- cat_dns: 'DNS',- cat_admin: 'Admin',- cat_local: 'Local',- cat_lan_device: 'Appareil LAN',- cat_other: 'Autre',-- // FR: Noms de nœuds + indices d'identification affichés à l'utilisateur.- // EN: Node names + identification hints shown to the user.- node_local: 'Cet appareil',- hint_local: "C'est CETTE machine — celle qui fait tourner Snitch. Tout ce qu'elle envoie ou reçoit rayonne depuis le centre du graphe.",- unidentified: 'non identifié',- devtype_router: 'Routeur',- devtype_phone: 'Téléphone',- devtype_pc: 'Ordinateur',- devtype_tv: 'TV',- devtype_iot: 'Objet connecté',- devtype_unknown: 'Type inconnu',- hint_unidentified: "Pas encore identifié — son nom apparaîtra s'il s'annonce (DNS/mDNS) ou si son fabricant est connu. Si vous ne le reconnaissez pas, vérifiez la liste des clients de votre box/routeur.",- hint_unresolved: "Pas encore nommé — le domaine apparaîtra quand une réponse DNS ou un handshake TLS le révélera.",- hint_private_mac: "Adresse MAC privée (aléatoire) — iOS/Android/Windows masquent la vraie, le fabricant ne peut pas être identifié. C'est un comportement de confidentialité normal.",- hint_gateway: "C'est votre box/routeur — TOUT votre trafic internet passe physiquement par elle, donc la voir communiquer est normal et attendu.",- hint_lan_idle: "Vu sur votre réseau via la table de voisinage — aucune donnée échangée. Une arête en pointillés signifie « présent », pas « en train de communiquer ».",- hint_lan_active: b => `${b} échangés — le plus souvent des annonces automatiques (Bonjour/mDNS, partage de fichiers). À surveiller si le volume grimpe.`,- ext_empty: "Aucune connexion externe pour l'instant — tout hôte contacté par votre machine apparaîtra ici.",- legend_edge_solid: 'trait plein = trafic',- legend_edge_dashed: 'pointillés = vu, sans données',- legend_ring_safe: 'anneau vert = identifié, sûr',- legend_ring_warn: 'anneau orange = suspect',- legend_ring_crit: 'anneau rouge = alerte',- legend_ring_none: 'sans anneau = non identifié, neutre',- legend_perimeter: 'périmètre LAN',- perim_lan: 'RÉSEAU LOCAL',-- // Panneau d'alertes / Alert panel- alerts_title: 'Alertes',- alerts_total: 'total',- alerts_empty: "Aucune alerte pour l'instant",- alert_NEW_HOST: 'Nouvel hôte',- alert_SUSPICIOUS_PROCESS: 'Processus suspect',- alert_SUSPICIOUS_PORT: 'Port suspect',- alert_BEACON: 'Beacon C2',- alert_VOLUME_SPIKE: 'Pic de trafic',- alert_NEW_LAN_DEVICE: 'Nouvel appareil',- alert_DEVICE_OFFLINE: 'Appareil hors ligne',- alert_MEDIA_EXFIL: 'Exfiltration média',- alert_PORT_SCAN: 'Scan de ports',- alert_UPLOAD_SPIKE: 'Pic d\'envoi',- alert_WATCHLIST_HIT: 'Correspondance watchlist',- alertmsg_NEW_HOST: d => `Nouvel hôte contacté : ${d.host || d.ip}`,- alertmsg_SUSPICIOUS_PROCESS: d => `Processus suspect : ${d.process} → ${d.host || d.ip}`,- alertmsg_SUSPICIOUS_PORT: d => `Port suspect ${d.port} (${d.reason}) → ${d.host || d.ip}`,- alertmsg_BEACON: d => `Régularité type beacon : intervalle ~${d.interval_s}s vers ${d.host || d.ip}`,- alertmsg_VOLUME_SPIKE: d => `Pic de données vers ${d.host || d.ip} : ${Math.round((d.bytes || 0) / 1024)} Ko en ${d.window_s}s`,- alertmsg_PORT_SCAN: d => `Scan de ports : ${d.source || d.ip} a touché ${d.ports}+ ports en ${d.window_s}s`,- alertmsg_MEDIA_EXFIL: d => `Exfiltration ${d.device === 'camera' ? 'caméra' : 'micro'} suspectée : ${d.process} → ${d.host || d.ip}`,- alertmsg_NEW_LAN_DEVICE: d => `Nouvel appareil sur le réseau : ${d.host || d.ip}`,- alertmsg_DEVICE_OFFLINE: d => `Appareil hors ligne : ${d.host || d.ip}`,- alertmsg_UPLOAD_SPIKE: d => `Pic d\'envoi : ${d.process} a envoyé ${d.mb} Mo en ${d.window_s}s`,- alertmsg_WATCHLIST_HIT: d => `Watchlist : ${d.match} (${d.host || d.ip}) — ${d.process || 'processus inconnu'}`,- time_just_now: "à l'instant",- time_seconds: n => `il y a ${n}s`,- time_minutes: n => `il y a ${n}min`,- time_hours: n => `il y a ${n}h`,-- // Score de confidentialité / Privacy score- privacy_title: 'Score de confidentialité',- privacy_critical_label: 'Critique',- privacy_excellent_label: 'Excellent',- privacy_risk_factors: n => `${n} facteur${n !== 1 ? 's' : ''} de risque`,- privacy_more_factors: n => `+${n} autre${n > 1 ? 's' : ''} facteur${n > 1 ? 's' : ''}`,- privacy_label_excellent: 'Excellent',- privacy_label_good: 'Bon',- privacy_label_average: 'Moyen',- privacy_label_weak: 'Faible',- privacy_label_critical: 'Critique',-- // Timeline- timeline_packets: n => `${n.toLocaleString('fr-FR')} paquets`,- timeline_alerts: n => `${n} alerte${n > 1 ? 's' : ''}`,- timeline_live: 'Direct',-- // Bascule de capture / Capture toggle- capture_stop: 'Arrêter',- capture_start: 'Démarrer',- capture_stopping: 'Arrêt…',- capture_starting: 'Démarrage…',-- // Filtre de ports / Port filter- port_filter: 'Ports',- port_all: 'Tous les ports',- port_placeholder: 'Ajouter un port (ex: 443)',- port_invalid: 'Port invalide',-- // Export- export_btn: 'Exporter',- export_graph_json: 'Graphe (JSON)',- export_graph_csv: 'Graphe (CSV)',- export_alerts_json: 'Alertes (JSON)',- export_alerts_csv: 'Alertes (CSV)',-- // Filtre de processus / Process filter- process_filter: 'Applications',- process_filter_hint: 'Cliquer pour masquer une app du graphe',- process_none: 'Aucun processus détecté pour l\'instant',- process_clear: 'Tout afficher',-- // Liste blanche d'IP / IP whitelist- ip_whitelist: 'Confiance',- ip_whitelist_hint: 'Les IP de confiance ne sont plus capturées ni affichées',- ip_placeholder: 'Ajouter une IP (ex: 1.1.1.1)',- ip_invalid: 'Adresse IP invalide',- ip_clear: 'Vider la liste',- whitelist_action: 'Marquer comme fiable',-- // Carte / Map- map_you: 'Vous',- map_located: n => `${n} hôte${n !== 1 ? 's' : ''} localisé${n !== 1 ? 's' : ''}`,- map_no_geo: 'sans géo',-- // Libellés des facteurs de score / Scoring factor labels- score_trackers: n => `${n} tracker${n > 1 ? 's' : ''} contacté${n > 1 ? 's' : ''}`,- score_tracker_traffic: pct => `${pct}% de trafic vers des trackers`,- score_ad_networks: n => `${n} régie${n > 1 ? 's' : ''} publicitaire${n > 1 ? 's' : ''}`,- score_beacons: n => `${n} comportement${n > 1 ? 's' : ''} beacon`,- score_susp_proc: n => `${n} processus suspect${n > 1 ? 's' : ''}`,- score_susp_ports: n => `${n} port${n > 1 ? 's' : ''} dangereux`,- score_critical_alerts: n => `${n} alerte${n > 1 ? 's' : ''} critique${n > 1 ? 's' : ''}`,- score_warnings: n => `${n} alertes`,- score_https_ratio: pct => `${pct}% de trafic HTTPS`,- score_no_trackers: 'Aucun tracker détecté',-- // Réglages / Settings- settings_title: 'Réglages',- settings_saved: 'Enregistré',- close: 'Fermer',- settings_language: 'Langue / Language',- theme_toggle: 'Thème clair / sombre',- settings_retention: 'Rétention de l\'historique',- settings_retention_hint: 'Durée de conservation du trafic et des alertes',- settings_interface: 'Interface de capture',- settings_interface_hint: 'Carte réseau écoutée (redémarre la capture)',- settings_interface_auto: 'Auto (première non-loopback)',- settings_upload: 'Seuil d\'alerte d\'envoi',- settings_upload_hint: 'Alerter quand un processus envoie plus que ceci par minute',- settings_off: 'Désactivé',- watchlist_title: 'Liste de surveillance',- watchlist_hint: 'Alerter dès qu\'un trafic touche ces IP ou domaines',- watchlist_placeholder: '203.0.113.7 ou example.com',- watchlist_add: 'Ajouter',- watchlist_remove: 'Retirer',- update_title: 'Mises à jour',- update_checking: 'Vérification des mises à jour…',- update_available: v => `Mise à jour disponible : v${v} — téléchargement`,- update_downloading: p => `Téléchargement de la mise à jour… ${p}%`,- update_ready: v => `v${v} téléchargée — redémarrer pour installer`,- update_none: 'Snitch est à jour',- update_error: 'Échec de la vérification',- update_idle: 'Pas encore de vérification',- update_restart: 'Redémarrer et installer',- update_check_btn: 'Vérifier',- update_auto: 'Vérifier automatiquement',- update_privacy: 'Vérifie github.com pour les nouvelles versions — le seul appel sortant avec le téléchargement GeoIP.',- geo_title: 'Base de géolocalisation',- geo_present: dbs => `Installée : ${dbs}`,- geo_none: 'Non installée — les IP ne sont pas géolocalisées',- geo_download_btn: 'Télécharger DB-IP Lite (gratuit)',- geo_consent: 'Télécharge ~50 Mo depuis db-ip.com (CC BY 4.0). C\'est le seul appel sortant possible de Snitch.',- geo_downloading: 'Téléchargement…',- geo_done: n => `${n} base(s) téléchargée(s)`,- geo_failed: 'Échec du téléchargement — vérifiez la connexion',- diag_title: 'Diagnostic',- diag_hint: 'Logs et infos système pour les rapports de bug',- diag_open_logs: 'Logs',- diag_export: 'Exporter',- settings_note: 'Tous les réglages sont stockés localement. Snitch n\'envoie rien à des tiers.',- nav_apps: 'Applications',- ignore_alert: 'Ignorer ce type/cet hôte',-- // Vue applications / Apps view- apps_empty: 'Aucun processus attribué pour l\'instant',- apps_process: 'Processus',- apps_destinations: 'Hôtes',- apps_packets: 'Paquets',- apps_volume: 'Volume',- apps_top_dest: 'Destinations principales',- apps_history_60m: 'Dernière heure (octets/min)',- alertmsg_NEW_HOSTS: n => `${n} nouvel${n > 1 ? 'x' : ''} hôte${n > 1 ? 's' : ''} contacté${n > 1 ? 's' : ''}`,- settings_autolaunch: 'Lancer à la connexion',- settings_autolaunch_hint: 'Démarrer Snitch automatiquement à l\'ouverture de session',-- // Premier lancement / Onboarding- onboard_title: 'Bienvenue dans Snitch',- onboard_sub: 'Visualiseur de trafic réseau en temps réel — privé par conception.',- onboard_priv_title: 'Tout reste sur cette machine',- onboard_priv_body: 'Métadonnées de trafic, alertes et historique sont stockés dans une base SQLite locale. Pas de compte, pas de cloud, pas de télémétrie.',- onboard_capture_title: 'Ce qui est capturé',- onboard_capture_body: 'Les en-têtes de paquets seulement : IP de destination, ports, volumes, noms de processus, noms DNS et SNI TLS. Les contenus ne sont jamais lus.',- onboard_out_title: 'Ce qui quitte la machine',- onboard_out_body: 'Rien par défaut. Le seul appel sortant possible est le téléchargement de la base de géolocalisation, que vous déclenchez vous-même dans les Réglages.',- onboard_go: 'Compris',-}--// ── Diccionario español / Spanish dictionary ─────────────────────────────────-// EN: Third UI language — kept structurally identical to `en` so every key-// resolves; missing keys would fall back to the raw key name.-// FR: Troisième langue d'UI — structure identique à `en` pour que chaque clé-// se résolve ; une clé absente retomberait sur le nom de clé brut.-const es = {- // Navegación- nav_graph: 'Grafo',- nav_map: 'Mapa',-- // Badge de estado- status_connected: 'En directo',- status_connecting: 'Conectando…',- status_disconnected: 'Desconectado',- status_error: 'Error',- lan_devices: n => `${n} dispositivo${n > 1 ? 's' : ''} LAN`,-- // Leyenda- legend_alert: 'Alerta',- legend_unknown: 'Desconocido',- legend_router: 'Router',- legend_phone: 'Teléfono',- legend_pc: 'PC',- legend_iot: 'IoT',- legend_https: 'HTTPS',- legend_tracking: 'Rastreo',- legend_cdn: 'CDN',- legend_dns: 'DNS',-- // Cabecera + estadísticas de la barra lateral- app_name: 'SNITCH',- tagline: 'Vigila cada flujo oculto.',- footer_credit: 'Desarrollado por aiXis',- stat_lan: 'Dispositivos LAN',- stat_ext: 'Hosts ext.',- stat_traffic: 'Tráfico',-- // Secciones de la barra lateral- section_lan: n => `Dispositivos LAN (${n})`,- section_ext: (n, total) => total ? `Hosts externos (${n}/${total})` : `Hosts externos (${n})`,- section_packets: 'Tráfico reciente',-- // Etiquetas de los campos de detalle de nodo- field_ip: 'IP',- field_mac: 'MAC',- field_hostname: 'Nombre de host',- field_vendor: 'Fabricante',- field_type: 'Tipo',- field_country: 'País',- field_city: 'Ciudad',- field_org: 'Org',- field_category: 'Categoría',- field_traffic: 'Tráfico',- field_packets: 'Paquetes',- processes: 'Procesos',- online: 'en línea',- offline: 'fuera de línea',-- // Búsqueda- search_placeholder: 'Buscar host, IP, país…',- cat_all: 'Todo',- cat_unknown: 'Desconocido',- cat_alerted: 'Alertas',- cat_safe: 'Seguro',- cat_tracking: 'Rastreo',- cat_cdn: 'CDN',- cat_dns: 'DNS',- cat_admin: 'Admin',- cat_local: 'Local',- cat_lan_device: 'Dispositivo LAN',- cat_other: 'Otro',-- node_local: 'Este dispositivo',- hint_local: 'Esta es ESTA máquina — la que ejecuta Snitch. Todo lo que envía o recibe irradia desde el centro del grafo.',- unidentified: 'sin identificar',- devtype_router: 'Router',- devtype_phone: 'Teléfono',- devtype_pc: 'Ordenador',- devtype_tv: 'TV',- devtype_iot: 'Dispositivo IoT',- devtype_unknown: 'Tipo desconocido',- hint_unidentified: 'Aún no identificado — su nombre aparece cuando se anuncia (DNS/mDNS) o se conoce el fabricante de su MAC. Si no lo reconoces, revisa la lista de clientes de tu router.',- hint_unresolved: 'Aún sin nombre — el dominio aparece cuando una respuesta DNS o un handshake TLS lo revela.',- hint_private_mac: 'Dirección MAC privada (aleatorizada) — iOS/Android/Windows ocultan la real, así que el fabricante no se puede identificar. Es un comportamiento de privacidad normal.',- hint_gateway: 'Esta es tu caja/router de internet — TODO tu tráfico pasa físicamente por él, así que verlo comunicar es normal y esperado.',- hint_lan_idle: 'Visto en tu red vía la tabla de vecinos — sin datos intercambiados. Una arista discontinua significa « presente », no « hablando ».',- hint_lan_active: b => `${b} intercambiados — normalmente anuncios automáticos (Bonjour/mDNS, compartición de archivos). Vigílalo si el volumen sube.`,- ext_empty: 'Sin conexiones externas todavía — todo lo que hable tu máquina aparecerá aquí.',- legend_edge_solid: 'línea sólida = tráfico',- legend_edge_dashed: 'discontinua = visto, sin datos',- legend_ring_safe: 'anillo verde = identificado, seguro',- legend_ring_warn: 'anillo ámbar = sospechoso',- legend_ring_crit: 'anillo rojo = alerta',- legend_ring_none: 'sin anillo = no identificado, neutro',- legend_perimeter: 'Perímetro LAN',- perim_lan: 'RED LOCAL',-- // Panel de alertas- alerts_title: 'Alertas',- alerts_total: 'total',- alerts_empty: 'Sin alertas por ahora',- alert_NEW_HOST: 'Host nuevo',- alert_SUSPICIOUS_PROCESS: 'Proceso sospechoso',- alert_SUSPICIOUS_PORT: 'Puerto sospechoso',- alert_BEACON: 'Beacon C2',- alert_VOLUME_SPIKE: 'Pico de tráfico',- alert_NEW_LAN_DEVICE: 'Dispositivo nuevo',- alert_DEVICE_OFFLINE: 'Dispositivo fuera de línea',- alert_MEDIA_EXFIL: 'Exfiltración de medios',- alert_PORT_SCAN: 'Escaneo de puertos',- alert_UPLOAD_SPIKE: 'Pico de subida',- alert_WATCHLIST_HIT: 'Coincidencia watchlist',- alertmsg_NEW_HOST: d => `Host nuevo contactado: ${d.host || d.ip}`,- alertmsg_SUSPICIOUS_PROCESS: d => `Proceso sospechoso: ${d.process} → ${d.host || d.ip}`,- alertmsg_SUSPICIOUS_PORT: d => `Puerto sospechoso ${d.port} (${d.reason}) → ${d.host || d.ip}`,- alertmsg_BEACON: d => `Regularidad tipo beacon: intervalo ~${d.interval_s}s hacia ${d.host || d.ip}`,- alertmsg_VOLUME_SPIKE: d => `Pico de datos hacia ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} KB en ${d.window_s}s`,- alertmsg_MEDIA_EXFIL: d => `Posible exfiltración de ${d.device === 'camera' ? 'cámara' : 'micrófono'}: ${d.process} → ${d.host || d.ip}`,- alertmsg_NEW_LAN_DEVICE: d => `Nuevo dispositivo en la red: ${d.host || d.ip}`,- alertmsg_DEVICE_OFFLINE: d => `Dispositivo desconectado: ${d.host || d.ip}`,- alertmsg_PORT_SCAN: d => `Escaneo de puertos: ${d.source || d.ip} tocó ${d.ports}+ puertos en ${d.window_s}s`,- alertmsg_UPLOAD_SPIKE: d => `Pico de subida: ${d.process} envió ${d.mb} MB en ${d.window_s}s`,- alertmsg_WATCHLIST_HIT: d => `Watchlist: ${d.match} (${d.host || d.ip}) — ${d.process || 'proceso desconocido'}`,- time_just_now: 'ahora mismo',- time_seconds: n => `hace ${n}s`,- time_minutes: n => `hace ${n}min`,- time_hours: n => `hace ${n}h`,-- // Puntuación de privacidad- privacy_title: 'Puntuación de privacidad',- privacy_critical_label: 'Crítica',- privacy_excellent_label: 'Excelente',- privacy_risk_factors: n => `${n} factor${n !== 1 ? 'es' : ''} de riesgo`,- privacy_more_factors: n => `+${n} factor${n > 1 ? 'es' : ''} más`,- privacy_label_excellent: 'Excelente',- privacy_label_good: 'Buena',- privacy_label_average: 'Media',- privacy_label_weak: 'Débil',- privacy_label_critical: 'Crítica',-- // Timeline- timeline_packets: n => `${n.toLocaleString()} paquetes`,- timeline_alerts: n => `${n} alerta${n > 1 ? 's' : ''}`,- timeline_live: 'En directo',-- // Botón de captura- capture_stop: 'Detener',- capture_start: 'Iniciar',- capture_stopping: 'Deteniendo…',- capture_starting: 'Iniciando…',-- // Filtro de puertos- port_filter: 'Puertos',- port_all: 'Todos los puertos',- port_placeholder: 'Añadir puerto (ej. 443)',- port_invalid: 'Puerto inválido',-- // Exportar- export_btn: 'Exportar',- export_graph_json: 'Grafo (JSON)',- export_graph_csv: 'Grafo (CSV)',- export_alerts_json: 'Alertas (JSON)',- export_alerts_csv: 'Alertas (CSV)',-- // Filtro de procesos- process_filter: 'Apps',- process_filter_hint: 'Clic para ocultar la app del grafo',- process_none: 'Sin procesos detectados aún',- process_clear: 'Mostrar todas las apps',-- // Lista blanca de IP- ip_whitelist: 'De confianza',- ip_whitelist_hint: 'Las IP de confianza ya no se capturan ni se muestran',- ip_placeholder: 'Añadir IP (ej. 1.1.1.1)',- ip_invalid: 'Dirección IP inválida',- ip_clear: 'Vaciar la lista',- whitelist_action: 'Marcar como de confianza',-- // Mapa- map_you: 'Tú',- map_located: n => `${n} host${n !== 1 ? 's' : ''} localizado${n !== 1 ? 's' : ''}`,- map_no_geo: 'sin geo',-- // Factores de la puntuación- score_trackers: n => `${n} rastreador${n > 1 ? 'es' : ''} contactado${n > 1 ? 's' : ''}`,- score_tracker_traffic: pct => `${pct}% del tráfico hacia rastreadores`,- score_ad_networks: n => `${n} red${n > 1 ? 'es' : ''} publicitaria${n > 1 ? 's' : ''}`,- score_beacons: n => `${n} comportamiento${n > 1 ? 's' : ''} tipo beacon`,- score_susp_proc: n => `${n} proceso${n > 1 ? 's' : ''} sospechoso${n > 1 ? 's' : ''}`,- score_susp_ports: n => `${n} puerto${n > 1 ? 's' : ''} peligroso${n > 1 ? 's' : ''}`,- score_critical_alerts: n => `${n} alerta${n > 1 ? 's' : ''} crítica${n > 1 ? 's' : ''}`,- score_warnings: n => `${n} avisos`,- score_https_ratio: pct => `${pct}% de tráfico HTTPS`,- score_no_trackers: 'Sin rastreadores detectados',-- // Ajustes- settings_title: 'Ajustes',- settings_saved: 'Guardado',- close: 'Cerrar',- settings_language: 'Idioma / Language',- theme_toggle: 'Tema claro / oscuro',- settings_retention: 'Retención del historial',- settings_retention_hint: 'Cuánto tiempo se conserva el tráfico y las alertas',- settings_interface: 'Interfaz de captura',- settings_interface_hint: 'Qué adaptador de red se escucha (reinicia la captura)',- settings_interface_auto: 'Auto (primera no-loopback)',- settings_upload: 'Umbral de alerta de subida',- settings_upload_hint: 'Avisar cuando un proceso suba más de esto por minuto',- settings_off: 'Desactivado',- watchlist_title: 'Lista de vigilancia',- watchlist_hint: 'Alertar en cuanto el tráfico toque estas IP o dominios',- watchlist_placeholder: '203.0.113.7 o example.com',- watchlist_add: 'Añadir',- watchlist_remove: 'Quitar',- update_title: 'Actualizaciones',- update_checking: 'Buscando actualizaciones…',- update_available: v => `Actualización disponible: v${v} — descargando`,- update_downloading: p => `Descargando actualización… ${p}%`,- update_ready: v => `v${v} descargada — reiniciar para instalar`,- update_none: 'Snitch está al día',- update_error: 'Falló la comprobación',- update_idle: 'Sin comprobación todavía',- update_restart: 'Reiniciar e instalar',- update_check_btn: 'Comprobar ahora',- update_auto: 'Comprobar automáticamente',- update_privacy: 'Consulta github.com para nuevas versiones — la única llamada saliente junto a la descarga GeoIP.',- geo_title: 'Base de geolocalización',- geo_present: dbs => `Instalada: ${dbs}`,- geo_none: 'No instalada — las IP no se geolocalizan',- geo_download_btn: 'Descargar DB-IP Lite (gratis)',- geo_consent: 'Descarga ~50 MB de db-ip.com (CC BY 4.0). Es la única llamada saliente posible de Snitch.',- geo_downloading: 'Descargando…',- geo_done: n => `${n} base(s) descargada(s)`,- geo_failed: 'Descarga fallida — revisa tu conexión',- diag_title: 'Diagnóstico',- diag_hint: 'Logs e info del sistema para informes de error',- diag_open_logs: 'Logs',- diag_export: 'Exportar',- settings_note: 'Todos los ajustes se guardan localmente. Snitch no envía nada a terceros.',- nav_apps: 'Aplicaciones',- ignore_alert: 'Ignorar este tipo/este host',-- // Vista de aplicaciones- apps_empty: 'Sin procesos atribuidos todavía',- apps_process: 'Proceso',- apps_destinations: 'Hosts',- apps_packets: 'Paquetes',- apps_volume: 'Volumen',- apps_top_dest: 'Destinos principales',- apps_history_60m: 'Última hora (bytes/min)',- alertmsg_NEW_HOSTS: n => `${n} host${n > 1 ? 's' : ''} nuevo${n > 1 ? 's' : ''} contactado${n > 1 ? 's' : ''}`,- settings_autolaunch: 'Iniciar al arrancar',- settings_autolaunch_hint: 'Arrancar Snitch automáticamente al iniciar sesión',-- // Onboarding- onboard_title: 'Bienvenido a Snitch',- onboard_sub: 'Visualizador de tráfico de red en tiempo real — privado por diseño.',- onboard_priv_title: 'Todo se queda en esta máquina',- onboard_priv_body: 'Metadatos de tráfico, alertas e historial se guardan en una base SQLite local. Sin cuenta, sin nube, sin telemetría.',- onboard_capture_title: 'Qué se captura',- onboard_capture_body: 'Solo cabeceras de paquetes: IP de destino, puertos, volúmenes, nombres de proceso, nombres DNS y SNI TLS. Los contenidos nunca se leen.',- onboard_out_title: 'Qué sale de la máquina',- onboard_out_body: 'Nada por defecto. La única llamada saliente posible es la descarga de la base de geolocalización, que tú mismo lanzas en Ajustes.',- onboard_go: 'Entendido',+import en from './locales/en'+import fr from './locales/fr'+import es from './locales/es'+import de from './locales/de'+import ru from './locales/ru'+import ja from './locales/ja'+import ptBR from './locales/pt-BR'+import zhCN from './locales/zh-CN'++// EN: Registry — code → dictionary. `LANGS` drives every language picker.+// FR: Registre — code → dictionnaire. `LANGS` pilote tous les sélecteurs.+export const LANGS = ['en', 'fr', 'es', 'de', 'ru', 'ja', 'pt-BR', 'zh-CN']+export const LANG_NAMES = {+ en: 'English', fr: 'Français', es: 'Español', de: 'Deutsch',+ ru: 'Русский', ja: '日本語', 'pt-BR': 'Português', 'zh-CN': '中文',}+const DICTS = { en, fr, es, de, ru, ja, 'pt-BR': ptBR, 'zh-CN': zhCN }// ── Context / Contexte ───────────────────────────────────────────────────────const I18nContext = createContext(null)+/**+ * EN: Detect the browser language on first run — saved choice wins, then the+ * browser's preferred language, then English. Region tags map to the+ * closest supported locale (pt → pt-BR, zh → zh-CN, otherwise the bare+ * language prefix).+ * FR: Détecter la langue du navigateur au premier lancement — le choix+ * sauvegardé prime, puis la langue préférée du navigateur, puis l'anglais.+ * Les tags de région mappent vers la locale la plus proche (pt → pt-BR,+ * zh → zh-CN, sinon le préfixe de langue nu).+ */+function detectLang() {+ const saved = localStorage.getItem('snitch_lang')+ if (saved && DICTS[saved]) return saved+ const nav = (navigator.language || 'en')+ if (DICTS[nav]) return nav+ const bare = nav.split('-')[0]+ if (bare === 'pt') return 'pt-BR'+ if (bare === 'zh') return 'zh-CN'+ return DICTS[bare] ? bare : 'en'+}+/*** EN: Provides { lang, t, setLang } to the whole tree. `t(key, ...args)`* resolves a dictionary entry — functions are called with args, strings@@ -824,13 +66,12 @@ const I18nContext = createContext(null)export function I18nProvider({ children }) {// EN: Persisted language — survives restarts (localStorage, not just RAM).// FR: Langue persistée — survit aux redémarrages (localStorage, pas juste la RAM).- const [lang, setLangState] = useState(- () => localStorage.getItem('snitch_lang') || 'en')+ const [lang, setLangState] = useState(detectLang)const setLang = (l) => {localStorage.setItem('snitch_lang', l)setLangState(l)}- const dict = { en, fr, es }[lang] || en+ const dict = DICTS[lang] || enfunction t(key, ...args) {// EN: Own-property check — without it, keys like "constructor" woulddiff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsnew file mode 100644index 0000000..8ca3c2e--- /dev/null+++ b/frontend/src/locales/de.js@@ -0,0 +1,335 @@+/**+ * Snitch — deutsches UI-Wörterbuch.+ *+ * EN: Isolated locale file — one per language, so community contributors can+ * add translations via a simple pull request (see CONTRIBUTING.md).+ * Values may be strings or functions for interpolation: t('key', arg).+ * FR: Fichier de locale isolé — un par langue, pour que la communauté puisse+ * ajouter des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation.+ */+export default {+ // Navigation+ nav_graph: 'Graph',+ nav_map: 'Karte',++ // Status badge+ status_connected: 'Live',+ status_connecting: 'Verbinde…',+ status_disconnected: 'Getrennt',+ status_error: 'Fehler',+ lan_devices: n => `${n} LAN-Gerät${n > 1 ? 'e' : ''}`,++ // Legend / Legende+ legend_alert: 'Alarm',+ legend_unknown: 'Unbekannt',+ legend_router: 'Router',+ legend_phone: 'Telefon',+ legend_pc: 'PC',+ legend_iot: 'IoT',+ legend_https: 'HTTPS',+ legend_tracking: 'Tracking',+ legend_cdn: 'CDN',+ legend_dns: 'DNS',++ // Sidebar header + stats+ app_name: 'SNITCH',+ tagline: 'Jeden verborgenen Datenfluss aufspüren.',+ footer_credit: 'Entwickelt von aiXis',+ stat_lan: 'LAN-Geräte',+ stat_ext: 'Ext. Hosts',+ stat_traffic: 'Verkehr',++ // Sidebar sections+ section_lan: n => `LAN-Geräte (${n})`,+ section_ext: (n, total) => total ? `Externe Hosts (${n}/${total})` : `Externe Hosts (${n})`,+ section_packets: 'Aktueller Verkehr',++ // Node detail field labels+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'Hostname',+ field_vendor: 'Hersteller',+ field_type: 'Typ',+ field_country: 'Land',+ field_city: 'Stadt',+ field_org: 'Organisation',+ field_category: 'Kategorie',+ field_traffic: 'Verkehr',+ field_packets: 'Pakete',+ processes: 'Prozesse',+ online: 'online',+ offline: 'offline',++ // Search / Suche+ search_placeholder: 'Host, IP, Land suchen…',+ cat_all: 'Alle',+ cat_unknown: 'Unbekannt',+ cat_alerted: 'Alarme',+ cat_safe: 'Sicher',+ cat_tracking: 'Tracking',+ cat_cdn: 'CDN',+ cat_dns: 'DNS',+ cat_admin: 'Admin',+ cat_local: 'Lokal',+ cat_lan_device: 'LAN-Gerät',+ cat_other: 'Sonstiges',++ // Node names + hints / Knotennamen + Hinweise+ node_local: 'Dieses Gerät',+ hint_local: 'Das ist DIESES Gerät — der Rechner, auf dem Snitch läuft. Alles, was es sendet oder empfängt, strahlt vom Zentrum des Graphen aus.',+ unidentified: 'nicht identifiziert',+ devtype_router: 'Router',+ devtype_phone: 'Telefon',+ devtype_pc: 'Computer',+ devtype_tv: 'Fernseher',+ devtype_iot: 'IoT-Gerät',+ devtype_unknown: 'Unbekannter Typ',+ hint_unidentified: 'Noch nicht identifiziert — der Name erscheint, sobald es sich meldet (DNS/mDNS) oder sein MAC-Hersteller bekannt ist. Wenn Sie es nicht kennen, prüfen Sie die Client-Liste Ihres Routers.',+ hint_unresolved: 'Noch unbenannt — die Domain erscheint, sobald eine DNS-Antwort oder ein TLS-Handshake sie verrät.',+ hint_private_mac: 'Private (zufällige) MAC-Adresse — iOS/Android/Windows verbergen die echte, daher kann der Hersteller nicht ermittelt werden. Normales Datenschutzverhalten.',+ hint_gateway: 'Das ist Ihre Internetbox/Ihr Router — IHR gesamter Verkehr läuft physisch darüber, es ist also normal, ihn kommunizieren zu sehen.',+ hint_lan_idle: 'Über die Nachbartabelle im Netz gesehen — keine Daten ausgetauscht. Eine gestrichelte Kante bedeutet „vorhanden“, nicht „spricht“.',+ hint_lan_active: b => `${b} ausgetauscht — meist automatische Meldungen (Bonjour/mDNS, Dateifreigabe). Beobachten, wenn das Volumen steigt.`,+ ext_empty: 'Noch keine externen Verbindungen — alles, womit Ihr Gerät spricht, erscheint hier.',+ legend_edge_solid: 'durchgezogene Linie = Verkehr',+ legend_edge_dashed: 'gestrichelt = gesehen, keine Daten',+ legend_ring_safe: 'grüner Ring = identifiziert, sicher',+ legend_ring_warn: 'gelber Ring = verdächtig',+ legend_ring_crit: 'roter Ring = Alarm',+ legend_ring_none: 'kein Ring = unidentifiziert, neutral',+ legend_perimeter: 'LAN-Perimeter',+ perim_lan: 'LOKALES NETZ',++ // Alert panel / Alarm-Panel+ alerts_title: 'Alarme',+ alerts_total: 'gesamt',+ alerts_empty: 'Noch keine Alarme',+ alert_NEW_HOST: 'Neuer Host',+ alert_SUSPICIOUS_PROCESS: 'Verdächtiger Prozess',+ alert_SUSPICIOUS_PORT: 'Verdächtiger Port',+ alert_BEACON: 'Beacon C2',+ alert_VOLUME_SPIKE: 'Verkehrsspitze',+ alert_NEW_LAN_DEVICE: 'Neues Gerät',+ alert_DEVICE_OFFLINE: 'Gerät offline',+ alert_MEDIA_EXFIL: 'Medien-Exfiltration',+ alert_PORT_SCAN: 'Port-Scan',+ alert_UPLOAD_SPIKE: 'Upload-Spitze',+ alert_WATCHLIST_HIT: 'Watchlist-Treffer',+ alertmsg_NEW_HOST: d => `Neuer Host kontaktiert: ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PROCESS: d => `Verdächtiger Prozess: ${d.process} → ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PORT: d => `Verdächtiger Port ${d.port} (${d.reason}) → ${d.host || d.ip}`,+ alertmsg_BEACON: d => `Beacon-ähnliche Regelmäßigkeit: Intervall ~${d.interval_s}s zu ${d.host || d.ip}`,+ alertmsg_VOLUME_SPIKE: d => `Datenspitze zu ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} KB in ${d.window_s}s`,+ alertmsg_MEDIA_EXFIL: d => `Vermutete ${d.device}-Exfiltration: ${d.process} → ${d.host || d.ip}`,+ alertmsg_NEW_LAN_DEVICE: d => `Neues Gerät im Netz: ${d.host || d.ip}`,+ alertmsg_DEVICE_OFFLINE: d => `Gerät offline gegangen: ${d.host || d.ip}`,+ alertmsg_PORT_SCAN: d => `Port-Scan: ${d.source || d.ip} berührte ${d.ports}+ Ports in ${d.window_s}s`,+ alertmsg_UPLOAD_SPIKE: d => `Upload-Spitze: ${d.process} sendete ${d.mb} MB in ${d.window_s}s`,+ alertmsg_WATCHLIST_HIT: d => `Watchlist-Treffer: ${d.match} (${d.host || d.ip}) — ${d.process || 'unbekannter Prozess'}`,+ time_just_now: 'gerade eben',+ time_seconds: n => `vor ${n}s`,+ time_minutes: n => `vor ${n} Min.`,+ time_hours: n => `vor ${n} Std.`,++ // Privacy score / Datenschutz-Score+ privacy_title: 'Datenschutz-Score',+ privacy_critical_label: 'Kritisch',+ privacy_excellent_label: 'Exzellent',+ privacy_risk_factors: n => `${n} Risikofaktor${n !== 1 ? 'en' : ''}`,+ privacy_more_factors: n => `+${n} weitere${n > 1 ? ' Faktoren' : 'r Faktor'}`,+ privacy_label_excellent: 'Exzellent',+ privacy_label_good: 'Gut',+ privacy_label_average: 'Mittel',+ privacy_label_weak: 'Schwach',+ privacy_label_critical: 'Kritisch',++ // Timeline+ timeline_packets: n => `${n.toLocaleString()} Pakete`,+ timeline_alerts: n => `${n} Alarm${n > 1 ? 'e' : ''}`,+ timeline_live: 'Live',++ // Capture toggle / Aufnahme-Schalter+ capture_stop: 'Stopp',+ capture_start: 'Start',+ capture_stopping: 'Stoppe…',+ capture_starting: 'Starte…',++ // Port filter / Port-Filter+ port_filter: 'Ports',+ port_all: 'Alle Ports',+ port_placeholder: 'Port hinzufügen (z. B. 443)',+ port_invalid: 'Ungültiger Port',++ // Export+ export_btn: 'Export',+ export_graph_json: 'Graph (JSON)',+ export_graph_csv: 'Graph (CSV)',+ export_alerts_json: 'Alarme (JSON)',+ export_alerts_csv: 'Alarme (CSV)',++ // Process filter / Prozess-Filter+ process_filter: 'Apps',+ process_filter_hint: 'Klicken, um App aus dem Graphen auszublenden',+ process_none: 'Noch keine Prozesse erkannt',+ process_clear: 'Alle Apps anzeigen',++ // IP whitelist / IP-Whitelist+ ip_whitelist: 'Vertrauenswürdig',+ ip_whitelist_hint: 'Vertrauenswürdige IPs werden nicht mehr aufgezeichnet oder angezeigt',+ ip_placeholder: 'IP hinzufügen (z. B. 1.1.1.1)',+ ip_invalid: 'Ungültige IP-Adresse',+ ip_clear: 'Whitelist leeren',+ whitelist_action: 'Als vertrauenswürdig markieren',++ // Map / Karte+ map_you: 'Sie',+ map_located: n => `${n} geolokalisierte${n !== 1 ? 'r' : ''} Host${n !== 1 ? 's' : ''}`,+ map_no_geo: 'keine Geo',++ // Scoring factor labels / Score-Faktoren+ score_trackers: n => `${n} Tracker kontaktiert`,+ score_tracker_traffic: pct => `${pct}% Verkehr zu Trackern`,+ score_ad_networks: n => `${n} Werbenetzwerk${n > 1 ? 'e' : ''}`,+ score_beacons: n => `${n} Beacon-Verhalten`,+ score_susp_proc: n => `${n} verdächtige${n > 1 ? 'r' : ''} Prozess${n > 1 ? 'e' : ''}`,+ score_susp_ports: n => `${n} gefährliche${n > 1 ? 'r' : ''} Port${n > 1 ? 's' : ''}`,+ score_critical_alerts: n => `${n} kritische${n > 1 ? 'r' : ''} Alarm${n > 1 ? 'e' : ''}`,+ score_warnings: n => `${n} Warnungen`,+ score_https_ratio: pct => `${pct}% HTTPS-Verkehr`,+ score_no_trackers: 'Keine Tracker erkannt',++ // Settings / Einstellungen+ settings_title: 'Einstellungen',+ settings_saved: 'Gespeichert',+ close: 'Schließen',+ settings_language: 'Sprache / Language',+ theme_toggle: 'Helles / dunkles Design',+ settings_retention: 'Verlaufs-Aufbewahrung',+ settings_retention_hint: 'Wie lange Verkehrs- & Alarmverlauf aufbewahrt wird',+ settings_interface: 'Aufnahme-Schnittstelle',+ settings_interface_hint: 'Welcher Netzwerkadapter abgehört wird (Aufnahme neu starten zum Anwenden)',+ settings_interface_auto: 'Auto (erste Nicht-Loopback)',+ settings_upload: 'Upload-Alarm-Schwelle',+ settings_upload_hint: 'Warnen, wenn ein Prozess pro Minute mehr hochlädt',+ settings_off: 'Aus',+ watchlist_title: 'Watchlist',+ watchlist_hint: 'Alarm erhalten, sobald Verkehr diese IPs oder Domains berührt',+ watchlist_placeholder: '203.0.113.7 oder example.com',+ watchlist_add: 'Hinzufügen',+ watchlist_remove: 'Entfernen',+ update_title: 'Updates',+ update_checking: 'Suche nach Updates…',+ update_available: v => `Update verfügbar: v${v} — wird geladen`,+ update_downloading: p => `Update wird geladen… ${p}%`,+ update_ready: v => `v${v} geladen — Neustart zum Installieren`,+ update_none: 'Snitch ist aktuell',+ update_error: 'Update-Prüfung fehlgeschlagen',+ update_idle: 'Noch keine Prüfung',+ update_restart: 'Neustart & installieren',+ update_check_btn: 'Jetzt prüfen',+ update_auto: 'Automatisch prüfen',+ update_privacy: 'Prüft github.com auf neue Versionen — unten abschaltbar; weitere Opt-in-Aufrufe in PRIVACY.md.',+ geo_title: 'Geolokalisierungs-Datenbank',+ geo_present: dbs => `Installiert: ${dbs}`,+ geo_none: 'Nicht installiert — IPs werden nicht geolokalisiert',+ geo_download_btn: 'DB-IP Lite herunterladen (kostenlos)',+ geo_consent: 'Lädt ~50 MB von db-ip.com herunter (CC BY 4.0). Weitere optionale ausgehende Aufrufe stehen in PRIVACY.md.',+ geo_downloading: 'Lade herunter…',+ geo_done: n => `${n} Datenbank(en) geladen`,+ geo_failed: 'Download fehlgeschlagen — Verbindung prüfen',+ diag_title: 'Diagnose',+ diag_hint: 'Logs und Systeminfo für Fehlerberichte',+ diag_open_logs: 'Logs',+ diag_export: 'Export',+ settings_note: 'Alle Einstellungen werden lokal gespeichert. Snitch sendet ohne dein explizites Opt-in nie Daten an Dritte.',+ nav_apps: 'Apps',+ ignore_alert: 'Diesen Alarmtyp/Host ignorieren',++ // Apps view / App-Ansicht+ apps_empty: 'Noch kein Prozess zugeordnet',+ apps_process: 'Prozess',+ apps_destinations: 'Hosts',+ apps_packets: 'Pakete',+ apps_volume: 'Volumen',+ apps_top_dest: 'Top-Ziele',+ apps_history_60m: 'Letzte Stunde (Bytes/min)',+ alertmsg_NEW_HOSTS: n => `${n} neue${n > 1 ? '' : 'r'} Host${n > 1 ? 's' : ''} kontaktiert`,+ settings_autolaunch: 'Beim Anmelden starten',+ settings_autolaunch_hint: 'Snitch automatisch beim Anmelden starten',++ // Onboarding+ onboard_title: 'Willkommen bei Snitch',+ onboard_sub: 'Echtzeit-Netzwerkverkehr-Visualisierer — datenschutzfreundlich von Grund auf.',+ onboard_priv_title: 'Alles bleibt auf diesem Gerät',+ onboard_priv_body: 'Verkehrs-Metadaten, Alarme und Verlauf werden in einer lokalen SQLite-Datenbank gespeichert. Kein Konto, keine Cloud, keine Telemetrie.',+ onboard_capture_title: 'Was aufgezeichnet wird',+ onboard_capture_body: 'Nur Paket-Header: Ziel-IPs, Ports, Volumen, Prozessnamen, DNS-Namen und TLS-Servernamen (SNI). Inhalte werden nie gelesen.',+ onboard_out_title: 'Was das Gerät verlässt',+ onboard_out_body: 'Standardmäßig nichts. Der einzige mögliche ausgehende Aufruf ist der Download der Geolokalisierungs-Datenbank, den Sie selbst in den Einstellungen auslösen.',+ onboard_go: 'Verstanden',++ // Firewall & security / Firewall & Sicherheit+ fw_title: 'Firewall & Sicherheit',+ fw_lockdown: 'Lockdown-Modus',+ fw_lockdown_hint: 'ALLEN ausgehenden Verkehr melden & blockieren (LAN bleibt aktiv)',+ fw_lockdown_confirm: 'Lockdown aktivieren? ALLER ausgehender Verkehr wird gemeldet und blockiert, bis Sie ihn ausschalten.',+ fw_lockdown_on: 'LOCKDOWN',+ fw_supported: p => `OS-Firewall-Orchestrierung auf ${p} — best effort, benötigt Rechte`,+ fw_unsupported: 'Native Firewall hier nicht unterstützt — Regeln sind nur Sichtbarkeit',+ fw_demo: 'Demo — nichts angewendet',+ fw_kind: 'Regeltyp',+ fw_value: 'Wert',+ fw_kind_ip: 'IP / CIDR',+ fw_kind_domain: 'Domain',+ fw_kind_process: 'Prozess',+ fw_kind_port: 'Port',+ fw_ph_ip: '203.0.113.7 oder 185.0.0.0/8',+ fw_ph_domain: 'evil.example',+ fw_ph_process: 'app.exe',+ fw_ph_port: 'z. B. 4444',+ fw_rules: 'Regeln',+ fw_empty: 'Keine Regeln — eine hinzufügen, um ausgehenden Verkehr zu härten',+ fw_blocked: n => `${n} Versuch${n > 1 ? 'e' : ''} gesehen`,+ fw_applied: 'auf OS-Firewall angewendet',+ fw_not_applied: 'nur Sichtbarkeit (benötigt Rechte)',+ fw_enable: 'Aktivieren',+ fw_disable: 'Deaktivieren',+ fw_delete: 'Regel löschen',+ audit_title: 'Sicherheitsaudit',+ audit_refresh: 'Aktualisieren',+ audit_critical: 'kritisch',+ audit_warning: 'Warnungen',+ audit_risky: n => `${n} Host(s) in Hochrisikoländern`,+ audit_loading: 'Lädt…',+ fw_forensics: 'Forensik-Export',+ block_action: 'Blockieren',+ proc_kill: 'Prozess beenden',+ proc_suspend: 'Anhalten / fortsetzen',+ save: 'Speichern',+ ti_title: 'Threat Intelligence (opt-in)',+ ti_hint: 'Neu gesehene Hosts gegen einen Reputationsanbieter prüfen',+ ti_none: 'Deaktiviert',+ ti_key: 'API-Schlüssel',+ ti_key_ph: 'Ihr API-Schlüssel',+ ti_privacy: 'Ausgehende Aufrufe an den Anbieter, nur für neu gesehene öffentliche Hosts. Standardmäßig deaktiviert — der Schlüssel bleibt lokal.',+ wh_title: 'Externer Webhook (opt-in)',+ wh_hint: 'Kritische/Warn-Alarme an Discord, Slack oder Telegram weiterleiten',+ wh_url: 'Webhook-URL',+ wh_url_ph: 'https://discord.com/api/webhooks/… oder beliebiger Endpoint',+ wh_chat: 'Chat-ID',+ wh_chat_ph: 'chat_id',+ wh_privacy: 'Alarmmeldungen werden bei Aktivierung per POST an Ihren Endpoint gesendet.',+ alert_BLOCKED_ATTEMPT: 'Blockierter Versuch',+ alert_THREAT_HIT: 'Threat Intel',+ alert_DNS_TUNNEL: 'DNS-Tunnel',+ alert_CLEARTEXT: 'Klartext',+ alert_BASELINE_DEVIATION: 'Baseline-Abweichung',+ alert_LOCKDOWN: 'Lockdown',+ alertmsg_BLOCKED_ATTEMPT: d => `Firewall-Regel getroffen: ${d.rule?.value || '?'} (${d.rule?.kind || '?'})${d.process ? ` von ${d.process}` : ''}`,+ alertmsg_THREAT_HIT: d => `Threat Intel: ${d.ip} als ${d.verdict} gemeldet (${d.provider}: ${d.detail || 'gemeldet'})`,+ alertmsg_DNS_TUNNEL: d => `Mögliches DNS-Tunneling: überlanger Name angefragt von ${d.process}`,+ alertmsg_CLEARTEXT: d => `Unverschlüsselte ${d.proto}-Verbindung zu ${d.host || d.ip} von ${d.process}`,+ alertmsg_BASELINE_DEVIATION: d => `${d.process} kontaktierte ein neues Land: ${d.country}`,+ alertmsg_LOCKDOWN: () => 'Lockdown-Modus AKTIVIERT — aller ausgehender Verkehr blockiert',+}diff --git a/frontend/src/locales/en.js b/frontend/src/locales/en.jsnew file mode 100644index 0000000..78caa51--- /dev/null+++ b/frontend/src/locales/en.js@@ -0,0 +1,339 @@+/**+ * Snitch — English UI dictionary.+ *+ * EN: Isolated locale file — one per language, so community contributors can+ * add translations via a simple pull request (see CONTRIBUTING.md).+ * Values may be strings or functions for interpolation: t('key', arg).+ * FR: Fichier de locale isolé — un par langue, pour que la communauté puisse+ * ajouter des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation.+ */+export default { // Navigation+ nav_graph: 'Graph',+ nav_map: 'Map',++ // Status badge / Badge de statut+ status_connected: 'Live',+ status_connecting: 'Connecting…',+ status_disconnected: 'Disconnected',+ status_error: 'Error',+ lan_devices: n => `${n} device${n > 1 ? 's' : ''} LAN`,++ // Legend / Légende+ legend_alert: 'Alert',+ legend_unknown: 'Unknown',+ 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',+ tagline: "Track every hidden flow.",+ footer_credit: 'Developed by aiXis',+ stat_lan: 'LAN Devices',+ stat_ext: 'Ext. hosts',+ stat_traffic: 'Traffic',++ // Sidebar sections / Sections de la barre latérale+ section_lan: n => `LAN Devices (${n})`,+ section_ext: (n, total) => total ? `External hosts (${n}/${total})` : `External hosts (${n})`,+ section_packets: 'Recent traffic',++ // Node detail field labels / Étiquettes des champs de détail de nœud+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'Hostname',+ field_vendor: 'Vendor',+ field_type: 'Type',+ field_country: 'Country',+ field_city: 'City',+ field_org: 'Org',+ field_category: 'Category',+ field_traffic: 'Traffic',+ field_packets: 'Packets',+ processes: 'Processes',+ online: 'online',+ offline: 'offline',++ // Search / Recherche+ search_placeholder: 'Search host, IP, country…',+ cat_all: 'All',+ cat_unknown: 'Unknown',+ cat_alerted: 'Alerts',+ cat_safe: 'Safe',+ cat_tracking: 'Tracking',+ cat_cdn: 'CDN',+ cat_dns: 'DNS',+ cat_admin: 'Admin',+ cat_local: 'Local',+ cat_lan_device: 'LAN device',+ cat_other: 'Other',++ // EN: Node names + identification hints shown to the user.+ // FR: Noms de nœuds + indices d'identification affichés à l'utilisateur.+ node_local: 'This Device',+ hint_local: 'This is THIS machine — the one running Snitch. Everything it sends or receives radiates from the center of the graph.',+ unidentified: 'unidentified',+ devtype_router: 'Router',+ devtype_phone: 'Phone',+ devtype_pc: 'Computer',+ devtype_tv: 'TV',+ devtype_iot: 'IoT device',+ devtype_unknown: 'Unknown type',+ hint_unidentified: "Not identified yet — its name appears when it announces itself (DNS/mDNS) or its MAC vendor is known. If you don't recognize it, check your router's client list.",+ hint_unresolved: 'Not yet named — the domain appears when a DNS answer or TLS handshake reveals it.',+ hint_private_mac: 'Private (randomized) MAC address — iOS/Android/Windows hide the real one, so the vendor can\'t be identified. This is normal privacy behavior.',+ hint_gateway: 'This is your internet box/router — ALL your traffic physically passes through it, so seeing it communicate is normal and expected.',+ hint_lan_idle: 'Seen on your network via the neighbour table — no data exchanged. A dashed edge means "present", not "talking".',+ hint_lan_active: b => `${b} exchanged — usually automatic announcements (Bonjour/mDNS, file sharing). Watch it if the volume climbs.`,+ ext_empty: "No external connections yet — anything your machine talks to will appear here.",+ legend_edge_solid: 'solid line = traffic',+ legend_edge_dashed: 'dashed = seen, no data',+ legend_ring_safe: 'green ring = identified, safe',+ legend_ring_warn: 'amber ring = suspicious',+ legend_ring_crit: 'red ring = alert',+ legend_ring_none: 'no ring = unidentified, neutral',+ legend_perimeter: 'LAN perimeter',+ perim_lan: 'LOCAL NETWORK',++ // Alert panel / Panneau d'alertes+ alerts_title: 'Alerts',+ alerts_total: 'total',+ alerts_empty: 'No alerts yet',+ alert_NEW_HOST: 'New host',+ alert_SUSPICIOUS_PROCESS: 'Suspicious process',+ alert_SUSPICIOUS_PORT: 'Suspicious port',+ alert_BEACON: 'Beacon C2',+ alert_VOLUME_SPIKE: 'Traffic spike',+ alert_NEW_LAN_DEVICE: 'New device',+ alert_DEVICE_OFFLINE: 'Device offline',+ alert_MEDIA_EXFIL: 'Media exfiltration',+ alert_PORT_SCAN: 'Port scan',+ alert_UPLOAD_SPIKE: 'Upload spike',+ alert_WATCHLIST_HIT: 'Watchlist hit',+ // EN: Full alert messages built from backend codes + details — the backend+ // only sends type + params, never prose.+ // FR: Messages d'alerte complets construits depuis les codes + détails du+ // 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 => `Data spike to ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} KB in ${d.window_s}s`,+ alertmsg_MEDIA_EXFIL: d => `Suspected ${d.device} exfiltration: ${d.process} → ${d.host || d.ip}`,+ alertmsg_NEW_LAN_DEVICE: d => `New device on the network: ${d.host || d.ip}`,+ alertmsg_DEVICE_OFFLINE: d => `Device went offline: ${d.host || d.ip}`,+ alertmsg_PORT_SCAN: d => `Port scan: ${d.source || d.ip} touched ${d.ports}+ ports in ${d.window_s}s`,+ alertmsg_UPLOAD_SPIKE: d => `Upload spike: ${d.process} sent ${d.mb} MB in ${d.window_s}s`,+ alertmsg_WATCHLIST_HIT: d => `Watchlist hit: ${d.match} (${d.host || d.ip}) — ${d.process || 'unknown process'}`,+ time_just_now: 'just now',+ time_seconds: n => `${n}s ago`,+ time_minutes: n => `${n}min ago`,+ time_hours: n => `${n}h ago`,++ // Privacy score / Score de confidentialité+ privacy_title: 'Privacy Score',+ privacy_critical_label: 'Critical',+ privacy_excellent_label: 'Excellent',+ privacy_risk_factors: n => `${n} risk factor${n !== 1 ? 's' : ''}`,+ privacy_more_factors: n => `+${n} more factor${n > 1 ? 's' : ''}`,+ privacy_label_excellent: 'Excellent',+ privacy_label_good: 'Good',+ privacy_label_average: 'Average',+ privacy_label_weak: 'Weak',+ privacy_label_critical: 'Critical',++ // Timeline+ timeline_packets: n => `${n.toLocaleString()} packets`,+ timeline_alerts: n => `${n} alert${n > 1 ? 's' : ''}`,+ timeline_live: 'Live',++ // Capture toggle / Bascule de capture+ capture_stop: 'Stop',+ capture_start: 'Start',+ capture_stopping: 'Stopping…',+ capture_starting: 'Starting…',++ // Port filter / Filtre de ports+ port_filter: 'Ports',+ port_all: 'All ports',+ port_placeholder: 'Add port (e.g. 443)',+ port_invalid: 'Invalid port',++ // Export+ export_btn: 'Export',+ export_graph_json: 'Graph (JSON)',+ export_graph_csv: 'Graph (CSV)',+ export_alerts_json: 'Alerts (JSON)',+ export_alerts_csv: 'Alerts (CSV)',++ // Process filter / Filtre de processus+ process_filter: 'Apps',+ process_filter_hint: 'Click to hide app from graph',+ process_none: 'No processes detected yet',+ process_clear: 'Show all apps',++ // IP whitelist / Liste blanche d'IP+ ip_whitelist: 'Trusted',+ ip_whitelist_hint: 'Trusted IPs are no longer captured or shown',+ ip_placeholder: 'Add IP (e.g. 1.1.1.1)',+ ip_invalid: 'Invalid IP address',+ ip_clear: 'Clear whitelist',+ whitelist_action: 'Mark as trusted',++ // Map / Carte+ map_you: 'You',+ map_located: n => `${n} located host${n !== 1 ? 's' : ''}`,+ map_no_geo: 'no geo',++ // Scoring factor labels / Libellés des facteurs de score+ score_trackers: n => `${n} tracker${n > 1 ? 's' : ''} contacted`,+ score_tracker_traffic: pct => `${pct}% traffic to trackers`,+ score_ad_networks: n => `${n} ad network${n > 1 ? 's' : ''}`,+ score_beacons: n => `${n} beacon behavior${n > 1 ? 's' : ''}`,+ score_susp_proc: n => `${n} suspicious process${n > 1 ? 'es' : ''}`,+ score_susp_ports: n => `${n} dangerous port${n > 1 ? 's' : ''}`,+ score_critical_alerts: n => `${n} critical alert${n > 1 ? 's' : ''}`,+ score_warnings: n => `${n} warnings`,+ score_https_ratio: pct => `${pct}% HTTPS traffic`,+ score_no_trackers: 'No trackers detected',++ // Settings / Réglages+ settings_title: 'Settings',+ settings_saved: 'Saved',+ close: 'Close',+ settings_language: 'Language / Langue',+ theme_toggle: 'Light / dark theme',+ settings_retention: 'History retention',+ settings_retention_hint: 'How long traffic & alert history is kept',+ settings_interface: 'Capture interface',+ settings_interface_hint: 'Which network adapter is sniffed (restart capture to apply)',+ settings_interface_auto: 'Auto (first non-loopback)',+ settings_upload: 'Upload alert threshold',+ settings_upload_hint: 'Warn when one process uploads more than this per minute',+ settings_off: 'Off',+ watchlist_title: 'Watchlist',+ watchlist_hint: 'Get alerted whenever traffic touches these IPs or domains',+ watchlist_placeholder: '203.0.113.7 or example.com',+ watchlist_add: 'Add',+ watchlist_remove: 'Remove',+ update_title: 'Updates',+ update_checking: 'Checking for updates…',+ update_available: v => `Update available: v${v} — downloading`,+ update_downloading: p => `Downloading update… ${p}%`,+ update_ready: v => `v${v} downloaded — restart to install`,+ update_none: 'Snitch is up to date',+ update_error: 'Update check failed',+ update_idle: 'No check yet',+ update_restart: 'Restart & install',+ update_check_btn: 'Check now',+ update_auto: 'Check automatically',+ update_privacy: 'Checks github.com for new releases — opt-out below; see PRIVACY.md for the other opt-in calls.',+ geo_title: 'Geolocation database',+ geo_present: dbs => `Installed: ${dbs}`,+ geo_none: 'Not installed — IPs are not geolocated',+ geo_download_btn: 'Download DB-IP Lite (free)',+ geo_consent: 'Downloads ~50 MB from db-ip.com (CC BY 4.0). Other opt-in outbound calls are listed in PRIVACY.md.',+ geo_downloading: 'Downloading…',+ geo_done: n => `Downloaded ${n} database(s)`,+ geo_failed: 'Download failed — check your connection',+ diag_title: 'Diagnostics',+ diag_hint: 'Logs and system info for bug reports',+ diag_open_logs: 'Logs',+ diag_export: 'Export',+ settings_note: 'All settings are stored locally. Snitch never sends data to third parties without your explicit opt-in.',+ nav_apps: 'Apps',+ ignore_alert: 'Ignore this alert type/host',++ // Apps view / Vue applications+ apps_empty: 'No process attributed yet',+ apps_process: 'Process',+ apps_destinations: 'Hosts',+ apps_packets: 'Packets',+ apps_volume: 'Volume',+ apps_top_dest: 'Top destinations',+ apps_history_60m: 'Last hour (bytes/min)',+ alertmsg_NEW_HOSTS: n => `${n} new host${n > 1 ? 's' : ''} contacted`,+ settings_autolaunch: 'Launch at login',+ settings_autolaunch_hint: 'Start Snitch automatically when you sign in',++ // Onboarding / Premier lancement+ onboard_title: 'Welcome to Snitch',+ onboard_sub: 'Real-time network traffic visualizer — private by design.',+ onboard_priv_title: 'Everything stays on this machine',+ onboard_priv_body: 'Traffic metadata, alerts and history are stored in a local SQLite database. No account, no cloud, no telemetry.',+ onboard_capture_title: 'What is captured',+ onboard_capture_body: 'Packet headers only: destination IPs, ports, volumes, process names, DNS names and TLS server names (SNI). Payloads are never read.',+ onboard_out_title: 'What leaves the machine',+ onboard_out_body: 'Nothing by default. The only possible outbound call is the geolocation database download, which you trigger yourself in Settings.',+ onboard_go: 'Got it',++ // Firewall & security / Pare-feu & sécurité+ fw_title: 'Firewall & Security',+ fw_lockdown: 'Lockdown mode',+ fw_lockdown_hint: 'Flag & block ALL outbound traffic (LAN stays up)',+ fw_lockdown_confirm: 'Enable lockdown? ALL outbound traffic will be flagged and blocked until you turn it off.',+ fw_lockdown_on: 'LOCKDOWN',+ fw_supported: p => `OS firewall orchestration on ${p} — best effort, needs privileges`,+ fw_unsupported: 'Native firewall not supported here — rules are visibility only',+ fw_demo: 'demo — nothing applied',+ fw_kind: 'Rule type',+ fw_value: 'Value',+ fw_kind_ip: 'IP / CIDR',+ fw_kind_domain: 'Domain',+ fw_kind_process: 'Process',+ fw_kind_port: 'Port',+ fw_ph_ip: '203.0.113.7 or 185.0.0.0/8',+ fw_ph_domain: 'evil.example',+ fw_ph_process: 'app.exe',+ fw_ph_port: 'e.g. 4444',+ fw_rules: 'Rules',+ fw_empty: 'No rules — add one to harden outbound traffic',+ fw_blocked: n => `${n} attempt${n > 1 ? 's' : ''} seen`,+ fw_applied: 'applied to OS firewall',+ fw_not_applied: 'visibility only (needs privileges)',+ fw_enable: 'Enable',+ fw_disable: 'Disable',+ fw_delete: 'Delete rule',+ audit_title: 'Security audit',+ audit_refresh: 'Refresh',+ audit_critical: 'critical',+ audit_warning: 'warnings',+ audit_risky: n => `${n} host(s) in high-risk countries`,+ audit_loading: 'Loading…',+ fw_forensics: 'Forensics export',+ block_action: 'Block',+ proc_kill: 'Kill process',+ proc_suspend: 'Suspend / resume',+ save: 'Save',+ ti_title: 'Threat intelligence (opt-in)',+ ti_hint: 'Check newly-seen hosts against a reputation provider',+ ti_none: 'Disabled',+ ti_key: 'API key',+ ti_key_ph: 'Your API key',+ ti_privacy: 'Outbound calls to the provider, only for newly-seen public hosts. Disabled by default — the key is stored locally.',+ wh_title: 'External webhook (opt-in)',+ wh_hint: 'Forward critical/warning alerts to Discord, Slack or Telegram',+ wh_url: 'Webhook URL',+ wh_url_ph: 'https://discord.com/api/webhooks/… or any endpoint',+ wh_chat: 'Chat ID',+ wh_chat_ph: 'chat_id',+ wh_privacy: 'Alert messages are POSTed to your endpoint when enabled.',+ alert_BLOCKED_ATTEMPT: 'Blocked attempt',+ alert_THREAT_HIT: 'Threat intel',+ alert_DNS_TUNNEL: 'DNS tunnel',+ alert_CLEARTEXT: 'Cleartext',+ alert_BASELINE_DEVIATION: 'Baseline deviation',+ alert_LOCKDOWN: 'Lockdown',+ alertmsg_BLOCKED_ATTEMPT: d => `Firewall rule matched: ${d.rule?.value || '?'} (${d.rule?.kind || '?'})${d.process ? ` by ${d.process}` : ''}`,+ alertmsg_THREAT_HIT: d => `Threat intel: ${d.ip} flagged ${d.verdict} (${d.provider}: ${d.detail || 'reported'})`,+ alertmsg_DNS_TUNNEL: d => `Possible DNS tunneling: oversized name queried by ${d.process}`,+ alertmsg_CLEARTEXT: d => `Unencrypted ${d.proto} connection to ${d.host || d.ip} by ${d.process}`,+ alertmsg_BASELINE_DEVIATION: d => `${d.process} contacted a new country: ${d.country}`,+ alertmsg_LOCKDOWN: () => 'Lockdown mode ENABLED — all outbound traffic blocked',+}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsnew file mode 100644index 0000000..b83d87f--- /dev/null+++ b/frontend/src/locales/es.js@@ -0,0 +1,333 @@+/**+ * Snitch — Español UI dictionary.+ *+ * EN: Isolated locale file — one per language, so community contributors can+ * add translations via a simple pull request (see CONTRIBUTING.md).+ * Values may be strings or functions for interpolation: t('key', arg).+ * FR: Fichier de locale isolé — un par langue, pour que la communauté puisse+ * ajouter des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation.+ */+export default { // Navegación+ nav_graph: 'Grafo',+ nav_map: 'Mapa',++ // Badge de estado+ status_connected: 'En directo',+ status_connecting: 'Conectando…',+ status_disconnected: 'Desconectado',+ status_error: 'Error',+ lan_devices: n => `${n} dispositivo${n > 1 ? 's' : ''} LAN`,++ // Leyenda+ legend_alert: 'Alerta',+ legend_unknown: 'Desconocido',+ legend_router: 'Router',+ legend_phone: 'Teléfono',+ legend_pc: 'PC',+ legend_iot: 'IoT',+ legend_https: 'HTTPS',+ legend_tracking: 'Rastreo',+ legend_cdn: 'CDN',+ legend_dns: 'DNS',++ // Cabecera + estadísticas de la barra lateral+ app_name: 'SNITCH',+ tagline: 'Vigila cada flujo oculto.',+ footer_credit: 'Desarrollado por aiXis',+ stat_lan: 'Dispositivos LAN',+ stat_ext: 'Hosts ext.',+ stat_traffic: 'Tráfico',++ // Secciones de la barra lateral+ section_lan: n => `Dispositivos LAN (${n})`,+ section_ext: (n, total) => total ? `Hosts externos (${n}/${total})` : `Hosts externos (${n})`,+ section_packets: 'Tráfico reciente',++ // Etiquetas de los campos de detalle de nodo+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'Nombre de host',+ field_vendor: 'Fabricante',+ field_type: 'Tipo',+ field_country: 'País',+ field_city: 'Ciudad',+ field_org: 'Org',+ field_category: 'Categoría',+ field_traffic: 'Tráfico',+ field_packets: 'Paquetes',+ processes: 'Procesos',+ online: 'en línea',+ offline: 'fuera de línea',++ // Búsqueda+ search_placeholder: 'Buscar host, IP, país…',+ cat_all: 'Todo',+ cat_unknown: 'Desconocido',+ cat_alerted: 'Alertas',+ cat_safe: 'Seguro',+ cat_tracking: 'Rastreo',+ cat_cdn: 'CDN',+ cat_dns: 'DNS',+ cat_admin: 'Admin',+ cat_local: 'Local',+ cat_lan_device: 'Dispositivo LAN',+ cat_other: 'Otro',++ node_local: 'Este dispositivo',+ hint_local: 'Esta es ESTA máquina — la que ejecuta Snitch. Todo lo que envía o recibe irradia desde el centro del grafo.',+ unidentified: 'sin identificar',+ devtype_router: 'Router',+ devtype_phone: 'Teléfono',+ devtype_pc: 'Ordenador',+ devtype_tv: 'TV',+ devtype_iot: 'Dispositivo IoT',+ devtype_unknown: 'Tipo desconocido',+ hint_unidentified: 'Aún no identificado — su nombre aparece cuando se anuncia (DNS/mDNS) o se conoce el fabricante de su MAC. Si no lo reconoces, revisa la lista de clientes de tu router.',+ hint_unresolved: 'Aún sin nombre — el dominio aparece cuando una respuesta DNS o un handshake TLS lo revela.',+ hint_private_mac: 'Dirección MAC privada (aleatorizada) — iOS/Android/Windows ocultan la real, así que el fabricante no se puede identificar. Es un comportamiento de privacidad normal.',+ hint_gateway: 'Esta es tu caja/router de internet — TODO tu tráfico pasa físicamente por él, así que verlo comunicar es normal y esperado.',+ hint_lan_idle: 'Visto en tu red vía la tabla de vecinos — sin datos intercambiados. Una arista discontinua significa « presente », no « hablando ».',+ hint_lan_active: b => `${b} intercambiados — normalmente anuncios automáticos (Bonjour/mDNS, compartición de archivos). Vigílalo si el volumen sube.`,+ ext_empty: 'Sin conexiones externas todavía — todo lo que hable tu máquina aparecerá aquí.',+ legend_edge_solid: 'línea sólida = tráfico',+ legend_edge_dashed: 'discontinua = visto, sin datos',+ legend_ring_safe: 'anillo verde = identificado, seguro',+ legend_ring_warn: 'anillo ámbar = sospechoso',+ legend_ring_crit: 'anillo rojo = alerta',+ legend_ring_none: 'sin anillo = no identificado, neutro',+ legend_perimeter: 'Perímetro LAN',+ perim_lan: 'RED LOCAL',++ // Panel de alertas+ alerts_title: 'Alertas',+ alerts_total: 'total',+ alerts_empty: 'Sin alertas por ahora',+ alert_NEW_HOST: 'Host nuevo',+ alert_SUSPICIOUS_PROCESS: 'Proceso sospechoso',+ alert_SUSPICIOUS_PORT: 'Puerto sospechoso',+ alert_BEACON: 'Beacon C2',+ alert_VOLUME_SPIKE: 'Pico de tráfico',+ alert_NEW_LAN_DEVICE: 'Dispositivo nuevo',+ alert_DEVICE_OFFLINE: 'Dispositivo fuera de línea',+ alert_MEDIA_EXFIL: 'Exfiltración de medios',+ alert_PORT_SCAN: 'Escaneo de puertos',+ alert_UPLOAD_SPIKE: 'Pico de subida',+ alert_WATCHLIST_HIT: 'Coincidencia watchlist',+ alertmsg_NEW_HOST: d => `Host nuevo contactado: ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PROCESS: d => `Proceso sospechoso: ${d.process} → ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PORT: d => `Puerto sospechoso ${d.port} (${d.reason}) → ${d.host || d.ip}`,+ alertmsg_BEACON: d => `Regularidad tipo beacon: intervalo ~${d.interval_s}s hacia ${d.host || d.ip}`,+ alertmsg_VOLUME_SPIKE: d => `Pico de datos hacia ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} KB en ${d.window_s}s`,+ alertmsg_MEDIA_EXFIL: d => `Posible exfiltración de ${d.device === 'camera' ? 'cámara' : 'micrófono'}: ${d.process} → ${d.host || d.ip}`,+ alertmsg_NEW_LAN_DEVICE: d => `Nuevo dispositivo en la red: ${d.host || d.ip}`,+ alertmsg_DEVICE_OFFLINE: d => `Dispositivo desconectado: ${d.host || d.ip}`,+ alertmsg_PORT_SCAN: d => `Escaneo de puertos: ${d.source || d.ip} tocó ${d.ports}+ puertos en ${d.window_s}s`,+ alertmsg_UPLOAD_SPIKE: d => `Pico de subida: ${d.process} envió ${d.mb} MB en ${d.window_s}s`,+ alertmsg_WATCHLIST_HIT: d => `Watchlist: ${d.match} (${d.host || d.ip}) — ${d.process || 'proceso desconocido'}`,+ time_just_now: 'ahora mismo',+ time_seconds: n => `hace ${n}s`,+ time_minutes: n => `hace ${n}min`,+ time_hours: n => `hace ${n}h`,++ // Puntuación de privacidad+ privacy_title: 'Puntuación de privacidad',+ privacy_critical_label: 'Crítica',+ privacy_excellent_label: 'Excelente',+ privacy_risk_factors: n => `${n} factor${n !== 1 ? 'es' : ''} de riesgo`,+ privacy_more_factors: n => `+${n} factor${n > 1 ? 'es' : ''} más`,+ privacy_label_excellent: 'Excelente',+ privacy_label_good: 'Buena',+ privacy_label_average: 'Media',+ privacy_label_weak: 'Débil',+ privacy_label_critical: 'Crítica',++ // Timeline+ timeline_packets: n => `${n.toLocaleString()} paquetes`,+ timeline_alerts: n => `${n} alerta${n > 1 ? 's' : ''}`,+ timeline_live: 'En directo',++ // Botón de captura+ capture_stop: 'Detener',+ capture_start: 'Iniciar',+ capture_stopping: 'Deteniendo…',+ capture_starting: 'Iniciando…',++ // Filtro de puertos+ port_filter: 'Puertos',+ port_all: 'Todos los puertos',+ port_placeholder: 'Añadir puerto (ej. 443)',+ port_invalid: 'Puerto inválido',++ // Exportar+ export_btn: 'Exportar',+ export_graph_json: 'Grafo (JSON)',+ export_graph_csv: 'Grafo (CSV)',+ export_alerts_json: 'Alertas (JSON)',+ export_alerts_csv: 'Alertas (CSV)',++ // Filtro de procesos+ process_filter: 'Apps',+ process_filter_hint: 'Clic para ocultar la app del grafo',+ process_none: 'Sin procesos detectados aún',+ process_clear: 'Mostrar todas las apps',++ // Lista blanca de IP+ ip_whitelist: 'De confianza',+ ip_whitelist_hint: 'Las IP de confianza ya no se capturan ni se muestran',+ ip_placeholder: 'Añadir IP (ej. 1.1.1.1)',+ ip_invalid: 'Dirección IP inválida',+ ip_clear: 'Vaciar la lista',+ whitelist_action: 'Marcar como de confianza',++ // Mapa+ map_you: 'Tú',+ map_located: n => `${n} host${n !== 1 ? 's' : ''} localizado${n !== 1 ? 's' : ''}`,+ map_no_geo: 'sin geo',++ // Factores de la puntuación+ score_trackers: n => `${n} rastreador${n > 1 ? 'es' : ''} contactado${n > 1 ? 's' : ''}`,+ score_tracker_traffic: pct => `${pct}% del tráfico hacia rastreadores`,+ score_ad_networks: n => `${n} red${n > 1 ? 'es' : ''} publicitaria${n > 1 ? 's' : ''}`,+ score_beacons: n => `${n} comportamiento${n > 1 ? 's' : ''} tipo beacon`,+ score_susp_proc: n => `${n} proceso${n > 1 ? 's' : ''} sospechoso${n > 1 ? 's' : ''}`,+ score_susp_ports: n => `${n} puerto${n > 1 ? 's' : ''} peligroso${n > 1 ? 's' : ''}`,+ score_critical_alerts: n => `${n} alerta${n > 1 ? 's' : ''} crítica${n > 1 ? 's' : ''}`,+ score_warnings: n => `${n} avisos`,+ score_https_ratio: pct => `${pct}% de tráfico HTTPS`,+ score_no_trackers: 'Sin rastreadores detectados',++ // Ajustes+ settings_title: 'Ajustes',+ settings_saved: 'Guardado',+ close: 'Cerrar',+ settings_language: 'Idioma / Language',+ theme_toggle: 'Tema claro / oscuro',+ settings_retention: 'Retención del historial',+ settings_retention_hint: 'Cuánto tiempo se conserva el tráfico y las alertas',+ settings_interface: 'Interfaz de captura',+ settings_interface_hint: 'Qué adaptador de red se escucha (reinicia la captura)',+ settings_interface_auto: 'Auto (primera no-loopback)',+ settings_upload: 'Umbral de alerta de subida',+ settings_upload_hint: 'Avisar cuando un proceso suba más de esto por minuto',+ settings_off: 'Desactivado',+ watchlist_title: 'Lista de vigilancia',+ watchlist_hint: 'Alertar en cuanto el tráfico toque estas IP o dominios',+ watchlist_placeholder: '203.0.113.7 o example.com',+ watchlist_add: 'Añadir',+ watchlist_remove: 'Quitar',+ update_title: 'Actualizaciones',+ update_checking: 'Buscando actualizaciones…',+ update_available: v => `Actualización disponible: v${v} — descargando`,+ update_downloading: p => `Descargando actualización… ${p}%`,+ update_ready: v => `v${v} descargada — reiniciar para instalar`,+ update_none: 'Snitch está al día',+ update_error: 'Falló la comprobación',+ update_idle: 'Sin comprobación todavía',+ update_restart: 'Reiniciar e instalar',+ update_check_btn: 'Comprobar ahora',+ update_auto: 'Comprobar automáticamente',+ update_privacy: 'Consulta github.com para nuevas versiones — desactivable abajo; ver PRIVACY.md para las demás llamadas opt-in.',+ geo_title: 'Base de geolocalización',+ geo_present: dbs => `Instalada: ${dbs}`,+ geo_none: 'No instalada — las IP no se geolocalizan',+ geo_download_btn: 'Descargar DB-IP Lite (gratis)',+ geo_consent: 'Descarga ~50 MB de db-ip.com (CC BY 4.0). Las demás llamadas salientes opt-in están en PRIVACY.md.',+ geo_downloading: 'Descargando…',+ geo_done: n => `${n} base(s) descargada(s)`,+ geo_failed: 'Descarga fallida — revisa tu conexión',+ diag_title: 'Diagnóstico',+ diag_hint: 'Logs e info del sistema para informes de error',+ diag_open_logs: 'Logs',+ diag_export: 'Exportar',+ settings_note: 'Todos los ajustes se guardan localmente. Snitch no envía nada a terceros sin tu consentimiento explícito.',+ nav_apps: 'Aplicaciones',+ ignore_alert: 'Ignorar este tipo/este host',++ // Vista de aplicaciones+ apps_empty: 'Sin procesos atribuidos todavía',+ apps_process: 'Proceso',+ apps_destinations: 'Hosts',+ apps_packets: 'Paquetes',+ apps_volume: 'Volumen',+ apps_top_dest: 'Destinos principales',+ apps_history_60m: 'Última hora (bytes/min)',+ alertmsg_NEW_HOSTS: n => `${n} host${n > 1 ? 's' : ''} nuevo${n > 1 ? 's' : ''} contactado${n > 1 ? 's' : ''}`,+ settings_autolaunch: 'Iniciar al arrancar',+ settings_autolaunch_hint: 'Arrancar Snitch automáticamente al iniciar sesión',++ // Onboarding+ onboard_title: 'Bienvenido a Snitch',+ onboard_sub: 'Visualizador de tráfico de red en tiempo real — privado por diseño.',+ onboard_priv_title: 'Todo se queda en esta máquina',+ onboard_priv_body: 'Metadatos de tráfico, alertas e historial se guardan en una base SQLite local. Sin cuenta, sin nube, sin telemetría.',+ onboard_capture_title: 'Qué se captura',+ onboard_capture_body: 'Solo cabeceras de paquetes: IP de destino, puertos, volúmenes, nombres de proceso, nombres DNS y SNI TLS. Los contenidos nunca se leen.',+ onboard_out_title: 'Qué sale de la máquina',+ onboard_out_body: 'Nada por defecto. La única llamada saliente posible es la descarga de la base de geolocalización, que tú mismo lanzas en Ajustes.',+ onboard_go: 'Entendido',++ // Cortafuegos y seguridad / Firewall & security+ fw_title: 'Cortafuegos y Seguridad',+ fw_lockdown: 'Modo lockdown',+ fw_lockdown_hint: 'Señalar y bloquear TODO el tráfico saliente (la LAN sigue activa)',+ fw_lockdown_confirm: '¿Activar lockdown? TODO el tráfico saliente será señalado y bloqueado hasta desactivarlo.',+ fw_lockdown_on: 'LOCKDOWN',+ fw_supported: p => `Orquestación del cortafuegos del SO en ${p} — a mejor esfuerzo, requiere privilegios`,+ fw_unsupported: 'Cortafuegos nativo no soportado aquí — las reglas son solo visibilidad',+ fw_demo: 'demo — nada aplicado',+ fw_kind: 'Tipo de regla',+ fw_value: 'Valor',+ fw_kind_ip: 'IP / CIDR',+ fw_kind_domain: 'Dominio',+ fw_kind_process: 'Proceso',+ fw_kind_port: 'Puerto',+ fw_ph_ip: '203.0.113.7 o 185.0.0.0/8',+ fw_ph_domain: 'evil.example',+ fw_ph_process: 'app.exe',+ fw_ph_port: 'ej. 4444',+ fw_rules: 'Reglas',+ fw_empty: 'Sin reglas — añade una para endurecer las salidas',+ fw_blocked: n => `${n} intento${n > 1 ? 's' : ''} visto${n > 1 ? 's' : ''}`,+ fw_applied: 'aplicada al cortafuegos del SO',+ fw_not_applied: 'solo visibilidad (requiere privilegios)',+ fw_enable: 'Activar',+ fw_disable: 'Desactivar',+ fw_delete: 'Eliminar regla',+ audit_title: 'Auditoría de seguridad',+ audit_refresh: 'Actualizar',+ audit_critical: 'críticas',+ audit_warning: 'avisos',+ audit_risky: n => `${n} host(s) en países de riesgo`,+ audit_loading: 'Cargando…',+ fw_forensics: 'Exportación forense',+ block_action: 'Bloquear',+ proc_kill: 'Matar proceso',+ proc_suspend: 'Suspender / reanudar',+ save: 'Guardar',+ ti_title: 'Inteligencia de amenazas (opt-in)',+ ti_hint: 'Comprobar hosts nuevos contra un proveedor de reputación',+ ti_none: 'Desactivado',+ ti_key: 'Clave API',+ ti_key_ph: 'Tu clave API',+ ti_privacy: 'Llamadas salientes al proveedor, solo para hosts públicos nuevos. Desactivado por defecto — la clave se guarda localmente.',+ wh_title: 'Webhook externo (opt-in)',+ wh_hint: 'Reenviar alertas warning/críticas a Discord, Slack o Telegram',+ wh_url: 'URL del webhook',+ wh_url_ph: 'https://discord.com/api/webhooks/… o cualquier endpoint',+ wh_chat: 'Chat ID',+ wh_chat_ph: 'chat_id',+ wh_privacy: 'Los mensajes de alerta se envían por POST a tu endpoint cuando está activado.',+ alert_BLOCKED_ATTEMPT: 'Intento bloqueado',+ alert_THREAT_HIT: 'Threat intel',+ alert_DNS_TUNNEL: 'Túnel DNS',+ alert_CLEARTEXT: 'En claro',+ alert_BASELINE_DEVIATION: 'Desviación de baseline',+ alert_LOCKDOWN: 'Lockdown',+ alertmsg_BLOCKED_ATTEMPT: d => `Regla de cortafuegos coincidente: ${d.rule?.value || '?'} (${d.rule?.kind || '?'})${d.process ? ` por ${d.process}` : ''}`,+ alertmsg_THREAT_HIT: d => `Threat intel: ${d.ip} marcado ${d.verdict} (${d.provider}: ${d.detail || 'reportado'})`,+ alertmsg_DNS_TUNNEL: d => `Posible túnel DNS: nombre sobredimensionado consultado por ${d.process}`,+ alertmsg_CLEARTEXT: d => `Conexión ${d.proto} sin cifrar hacia ${d.host || d.ip} por ${d.process}`,+ alertmsg_BASELINE_DEVIATION: d => `${d.process} contactó un país nuevo: ${d.country}`,+ alertmsg_LOCKDOWN: () => 'Modo lockdown ACTIVADO — todo el tráfico saliente bloqueado',+}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsnew file mode 100644index 0000000..c670a1b--- /dev/null+++ b/frontend/src/locales/fr.js@@ -0,0 +1,335 @@+/**+ * Snitch — Français UI dictionary.+ *+ * EN: Isolated locale file — one per language, so community contributors can+ * add translations via a simple pull request (see CONTRIBUTING.md).+ * Values may be strings or functions for interpolation: t('key', arg).+ * FR: Fichier de locale isolé — un par langue, pour que la communauté puisse+ * ajouter des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation.+ */+export default { // Navigation+ nav_graph: 'Graphe',+ nav_map: 'Carte',++ // Badge de statut / Status badge+ status_connected: 'En direct',+ status_connecting: 'Connexion…',+ status_disconnected: 'Déconnecté',+ status_error: 'Erreur',+ lan_devices: n => `${n} appareil${n > 1 ? 's' : ''} LAN`,++ // Légende / Legend+ legend_alert: 'Alerte',+ legend_unknown: 'Inconnu',+ legend_router: 'Routeur',+ legend_phone: 'Téléphone',+ legend_pc: 'PC',+ legend_iot: 'IoT',+ legend_https: 'HTTPS',+ legend_tracking: 'Pistage',+ legend_cdn: 'CDN',+ legend_dns: 'DNS',++ // En-tête de barre latérale + stats / Sidebar header + stats+ app_name: 'SNITCH',+ tagline: 'Traquez chaque flux masqué.',+ footer_credit: 'Développé par aiXis',+ stat_lan: 'Appareils LAN',+ stat_ext: 'Hôtes ext.',+ stat_traffic: 'Trafic',++ // Sections de la barre latérale / Sidebar sections+ section_lan: n => `Appareils LAN (${n})`,+ section_ext: (n, total) => total ? `Hôtes externes (${n}/${total})` : `Hôtes externes (${n})`,+ section_packets: 'Flux récents',++ // Étiquettes des champs de détail de nœud / Node detail field labels+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'Nom d\'hôte',+ field_vendor: 'Fabricant',+ field_type: 'Type',+ field_country: 'Pays',+ field_city: 'Ville',+ field_org: 'Org',+ field_category: 'Catégorie',+ field_traffic: 'Trafic',+ field_packets: 'Paquets',+ processes: 'Processus',+ online: 'en ligne',+ offline: 'hors ligne',++ // Recherche / Search+ search_placeholder: 'Rechercher hôte, IP, pays…',+ cat_all: 'Tout',+ cat_unknown: 'Inconnu',+ cat_alerted: 'Alertes',+ cat_safe: 'Sûr',+ cat_tracking: 'Pistage',+ cat_cdn: 'CDN',+ cat_dns: 'DNS',+ cat_admin: 'Admin',+ cat_local: 'Local',+ cat_lan_device: 'Appareil LAN',+ cat_other: 'Autre',++ // FR: Noms de nœuds + indices d'identification affichés à l'utilisateur.+ // EN: Node names + identification hints shown to the user.+ node_local: 'Cet appareil',+ hint_local: "C'est CETTE machine — celle qui fait tourner Snitch. Tout ce qu'elle envoie ou reçoit rayonne depuis le centre du graphe.",+ unidentified: 'non identifié',+ devtype_router: 'Routeur',+ devtype_phone: 'Téléphone',+ devtype_pc: 'Ordinateur',+ devtype_tv: 'TV',+ devtype_iot: 'Objet connecté',+ devtype_unknown: 'Type inconnu',+ hint_unidentified: "Pas encore identifié — son nom apparaîtra s'il s'annonce (DNS/mDNS) ou si son fabricant est connu. Si vous ne le reconnaissez pas, vérifiez la liste des clients de votre box/routeur.",+ hint_unresolved: "Pas encore nommé — le domaine apparaîtra quand une réponse DNS ou un handshake TLS le révélera.",+ hint_private_mac: "Adresse MAC privée (aléatoire) — iOS/Android/Windows masquent la vraie, le fabricant ne peut pas être identifié. C'est un comportement de confidentialité normal.",+ hint_gateway: "C'est votre box/routeur — TOUT votre trafic internet passe physiquement par elle, donc la voir communiquer est normal et attendu.",+ hint_lan_idle: "Vu sur votre réseau via la table de voisinage — aucune donnée échangée. Une arête en pointillés signifie « présent », pas « en train de communiquer ».",+ hint_lan_active: b => `${b} échangés — le plus souvent des annonces automatiques (Bonjour/mDNS, partage de fichiers). À surveiller si le volume grimpe.`,+ ext_empty: "Aucune connexion externe pour l'instant — tout hôte contacté par votre machine apparaîtra ici.",+ legend_edge_solid: 'trait plein = trafic',+ legend_edge_dashed: 'pointillés = vu, sans données',+ legend_ring_safe: 'anneau vert = identifié, sûr',+ legend_ring_warn: 'anneau orange = suspect',+ legend_ring_crit: 'anneau rouge = alerte',+ legend_ring_none: 'sans anneau = non identifié, neutre',+ legend_perimeter: 'périmètre LAN',+ perim_lan: 'RÉSEAU LOCAL',++ // Panneau d'alertes / Alert panel+ alerts_title: 'Alertes',+ alerts_total: 'total',+ alerts_empty: "Aucune alerte pour l'instant",+ alert_NEW_HOST: 'Nouvel hôte',+ alert_SUSPICIOUS_PROCESS: 'Processus suspect',+ alert_SUSPICIOUS_PORT: 'Port suspect',+ alert_BEACON: 'Beacon C2',+ alert_VOLUME_SPIKE: 'Pic de trafic',+ alert_NEW_LAN_DEVICE: 'Nouvel appareil',+ alert_DEVICE_OFFLINE: 'Appareil hors ligne',+ alert_MEDIA_EXFIL: 'Exfiltration média',+ alert_PORT_SCAN: 'Scan de ports',+ alert_UPLOAD_SPIKE: 'Pic d\'envoi',+ alert_WATCHLIST_HIT: 'Correspondance watchlist',+ alertmsg_NEW_HOST: d => `Nouvel hôte contacté : ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PROCESS: d => `Processus suspect : ${d.process} → ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PORT: d => `Port suspect ${d.port} (${d.reason}) → ${d.host || d.ip}`,+ alertmsg_BEACON: d => `Régularité type beacon : intervalle ~${d.interval_s}s vers ${d.host || d.ip}`,+ alertmsg_VOLUME_SPIKE: d => `Pic de données vers ${d.host || d.ip} : ${Math.round((d.bytes || 0) / 1024)} Ko en ${d.window_s}s`,+ alertmsg_PORT_SCAN: d => `Scan de ports : ${d.source || d.ip} a touché ${d.ports}+ ports en ${d.window_s}s`,+ alertmsg_MEDIA_EXFIL: d => `Exfiltration ${d.device === 'camera' ? 'caméra' : 'micro'} suspectée : ${d.process} → ${d.host || d.ip}`,+ alertmsg_NEW_LAN_DEVICE: d => `Nouvel appareil sur le réseau : ${d.host || d.ip}`,+ alertmsg_DEVICE_OFFLINE: d => `Appareil hors ligne : ${d.host || d.ip}`,+ alertmsg_UPLOAD_SPIKE: d => `Pic d\'envoi : ${d.process} a envoyé ${d.mb} Mo en ${d.window_s}s`,+ alertmsg_WATCHLIST_HIT: d => `Watchlist : ${d.match} (${d.host || d.ip}) — ${d.process || 'processus inconnu'}`,+ time_just_now: "à l'instant",+ time_seconds: n => `il y a ${n}s`,+ time_minutes: n => `il y a ${n}min`,+ time_hours: n => `il y a ${n}h`,++ // Score de confidentialité / Privacy score+ privacy_title: 'Score de confidentialité',+ privacy_critical_label: 'Critique',+ privacy_excellent_label: 'Excellent',+ privacy_risk_factors: n => `${n} facteur${n !== 1 ? 's' : ''} de risque`,+ privacy_more_factors: n => `+${n} autre${n > 1 ? 's' : ''} facteur${n > 1 ? 's' : ''}`,+ privacy_label_excellent: 'Excellent',+ privacy_label_good: 'Bon',+ privacy_label_average: 'Moyen',+ privacy_label_weak: 'Faible',+ privacy_label_critical: 'Critique',++ // Timeline+ timeline_packets: n => `${n.toLocaleString('fr-FR')} paquets`,+ timeline_alerts: n => `${n} alerte${n > 1 ? 's' : ''}`,+ timeline_live: 'Direct',++ // Bascule de capture / Capture toggle+ capture_stop: 'Arrêter',+ capture_start: 'Démarrer',+ capture_stopping: 'Arrêt…',+ capture_starting: 'Démarrage…',++ // Filtre de ports / Port filter+ port_filter: 'Ports',+ port_all: 'Tous les ports',+ port_placeholder: 'Ajouter un port (ex: 443)',+ port_invalid: 'Port invalide',++ // Export+ export_btn: 'Exporter',+ export_graph_json: 'Graphe (JSON)',+ export_graph_csv: 'Graphe (CSV)',+ export_alerts_json: 'Alertes (JSON)',+ export_alerts_csv: 'Alertes (CSV)',++ // Filtre de processus / Process filter+ process_filter: 'Applications',+ process_filter_hint: 'Cliquer pour masquer une app du graphe',+ process_none: 'Aucun processus détecté pour l\'instant',+ process_clear: 'Tout afficher',++ // Liste blanche d'IP / IP whitelist+ ip_whitelist: 'Confiance',+ ip_whitelist_hint: 'Les IP de confiance ne sont plus capturées ni affichées',+ ip_placeholder: 'Ajouter une IP (ex: 1.1.1.1)',+ ip_invalid: 'Adresse IP invalide',+ ip_clear: 'Vider la liste',+ whitelist_action: 'Marquer comme fiable',++ // Carte / Map+ map_you: 'Vous',+ map_located: n => `${n} hôte${n !== 1 ? 's' : ''} localisé${n !== 1 ? 's' : ''}`,+ map_no_geo: 'sans géo',++ // Libellés des facteurs de score / Scoring factor labels+ score_trackers: n => `${n} tracker${n > 1 ? 's' : ''} contacté${n > 1 ? 's' : ''}`,+ score_tracker_traffic: pct => `${pct}% de trafic vers des trackers`,+ score_ad_networks: n => `${n} régie${n > 1 ? 's' : ''} publicitaire${n > 1 ? 's' : ''}`,+ score_beacons: n => `${n} comportement${n > 1 ? 's' : ''} beacon`,+ score_susp_proc: n => `${n} processus suspect${n > 1 ? 's' : ''}`,+ score_susp_ports: n => `${n} port${n > 1 ? 's' : ''} dangereux`,+ score_critical_alerts: n => `${n} alerte${n > 1 ? 's' : ''} critique${n > 1 ? 's' : ''}`,+ score_warnings: n => `${n} alertes`,+ score_https_ratio: pct => `${pct}% de trafic HTTPS`,+ score_no_trackers: 'Aucun tracker détecté',++ // Réglages / Settings+ settings_title: 'Réglages',+ settings_saved: 'Enregistré',+ close: 'Fermer',+ settings_language: 'Langue / Language',+ theme_toggle: 'Thème clair / sombre',+ settings_retention: 'Rétention de l\'historique',+ settings_retention_hint: 'Durée de conservation du trafic et des alertes',+ settings_interface: 'Interface de capture',+ settings_interface_hint: 'Carte réseau écoutée (redémarre la capture)',+ settings_interface_auto: 'Auto (première non-loopback)',+ settings_upload: 'Seuil d\'alerte d\'envoi',+ settings_upload_hint: 'Alerter quand un processus envoie plus que ceci par minute',+ settings_off: 'Désactivé',+ watchlist_title: 'Liste de surveillance',+ watchlist_hint: 'Alerter dès qu\'un trafic touche ces IP ou domaines',+ watchlist_placeholder: '203.0.113.7 ou example.com',+ watchlist_add: 'Ajouter',+ watchlist_remove: 'Retirer',+ update_title: 'Mises à jour',+ update_checking: 'Vérification des mises à jour…',+ update_available: v => `Mise à jour disponible : v${v} — téléchargement`,+ update_downloading: p => `Téléchargement de la mise à jour… ${p}%`,+ update_ready: v => `v${v} téléchargée — redémarrer pour installer`,+ update_none: 'Snitch est à jour',+ update_error: 'Échec de la vérification',+ update_idle: 'Pas encore de vérification',+ update_restart: 'Redémarrer et installer',+ update_check_btn: 'Vérifier',+ update_auto: 'Vérifier automatiquement',+ update_privacy: 'Vérifie github.com pour les nouvelles versions — désactivable ci-dessous ; voir PRIVACY.md pour les autres appels opt-in.',+ geo_title: 'Base de géolocalisation',+ geo_present: dbs => `Installée : ${dbs}`,+ geo_none: 'Non installée — les IP ne sont pas géolocalisées',+ geo_download_btn: 'Télécharger DB-IP Lite (gratuit)',+ geo_consent: 'Télécharge ~50 Mo depuis db-ip.com (CC BY 4.0). Les autres appels sortants opt-in sont listés dans PRIVACY.md.',+ geo_downloading: 'Téléchargement…',+ geo_done: n => `${n} base(s) téléchargée(s)`,+ geo_failed: 'Échec du téléchargement — vérifiez la connexion',+ diag_title: 'Diagnostic',+ diag_hint: 'Logs et infos système pour les rapports de bug',+ diag_open_logs: 'Logs',+ diag_export: 'Exporter',+ settings_note: 'Tous les réglages sont stockés localement. Snitch n\'envoie rien à des tiers sans votre accord explicite.',+ nav_apps: 'Applications',+ ignore_alert: 'Ignorer ce type/cet hôte',++ // Vue applications / Apps view+ apps_empty: 'Aucun processus attribué pour l\'instant',+ apps_process: 'Processus',+ apps_destinations: 'Hôtes',+ apps_packets: 'Paquets',+ apps_volume: 'Volume',+ apps_top_dest: 'Destinations principales',+ apps_history_60m: 'Dernière heure (octets/min)',+ alertmsg_NEW_HOSTS: n => `${n} nouvel${n > 1 ? 'x' : ''} hôte${n > 1 ? 's' : ''} contacté${n > 1 ? 's' : ''}`,+ settings_autolaunch: 'Lancer à la connexion',+ settings_autolaunch_hint: 'Démarrer Snitch automatiquement à l\'ouverture de session',++ // Premier lancement / Onboarding+ onboard_title: 'Bienvenue dans Snitch',+ onboard_sub: 'Visualiseur de trafic réseau en temps réel — privé par conception.',+ onboard_priv_title: 'Tout reste sur cette machine',+ onboard_priv_body: 'Métadonnées de trafic, alertes et historique sont stockés dans une base SQLite locale. Pas de compte, pas de cloud, pas de télémétrie.',+ onboard_capture_title: 'Ce qui est capturé',+ onboard_capture_body: 'Les en-têtes de paquets seulement : IP de destination, ports, volumes, noms de processus, noms DNS et SNI TLS. Les contenus ne sont jamais lus.',+ onboard_out_title: 'Ce qui quitte la machine',+ onboard_out_body: 'Rien par défaut. Le seul appel sortant possible est le téléchargement de la base de géolocalisation, que vous déclenchez vous-même dans les Réglages.',+ onboard_go: 'Compris',++ // Pare-feu & sécurité / Firewall & security+ fw_title: 'Pare-feu & Sécurité',+ fw_lockdown: 'Mode lockdown',+ fw_lockdown_hint: 'Signaler & bloquer TOUT le trafic sortant (le LAN reste actif)',+ fw_lockdown_confirm: 'Activer le lockdown ? TOUT le trafic sortant sera signalé et bloqué jusqu\'à désactivation.',+ fw_lockdown_on: 'LOCKDOWN',+ fw_supported: p => `Orchestration du pare-feu OS sur ${p} — au mieux, exige des privilèges`,+ fw_unsupported: 'Pare-feu natif non géré ici — les règles sont de la visibilité seulement',+ fw_demo: 'démo — rien d\'appliqué',+ fw_kind: 'Type de règle',+ fw_value: 'Valeur',+ fw_kind_ip: 'IP / CIDR',+ fw_kind_domain: 'Domaine',+ fw_kind_process: 'Processus',+ fw_kind_port: 'Port',+ fw_ph_ip: '203.0.113.7 ou 185.0.0.0/8',+ fw_ph_domain: 'evil.example',+ fw_ph_process: 'app.exe',+ fw_ph_port: 'ex. 4444',+ fw_rules: 'Règles',+ fw_empty: 'Aucune règle — en ajouter une pour durcir les sorties',+ fw_blocked: n => `${n} tentative${n > 1 ? 's' : ''} vue${n > 1 ? 's' : ''}`,+ fw_applied: 'appliquée au pare-feu OS',+ fw_not_applied: 'visibilité seule (exige des privilèges)',+ fw_enable: 'Activer',+ fw_disable: 'Désactiver',+ fw_delete: 'Supprimer la règle',+ audit_title: 'Audit de sécurité',+ audit_refresh: 'Rafraîchir',+ audit_critical: 'critiques',+ audit_warning: 'avertissements',+ audit_risky: n => `${n} hôte(s) dans des pays à risque`,+ audit_loading: 'Chargement…',+ fw_forensics: 'Export forensique',+ block_action: 'Bloquer',+ proc_kill: 'Tuer le processus',+ proc_suspend: 'Suspendre / reprendre',+ save: 'Enregistrer',+ ti_title: 'Renseignement sur les menaces (opt-in)',+ ti_hint: 'Vérifier les nouveaux hôtes auprès d\'un fournisseur de réputation',+ ti_none: 'Désactivé',+ ti_key: 'Clé API',+ ti_key_ph: 'Votre clé API',+ ti_privacy: 'Appels sortants vers le fournisseur, uniquement pour les nouveaux hôtes publics. Désactivé par défaut — la clé est stockée localement.',+ wh_title: 'Webhook externe (opt-in)',+ wh_hint: 'Relayer les alertes warning/critiques vers Discord, Slack ou Telegram',+ wh_url: 'URL du webhook',+ wh_url_ph: 'https://discord.com/api/webhooks/… ou tout endpoint',+ wh_chat: 'Chat ID',+ wh_chat_ph: 'chat_id',+ wh_privacy: 'Les messages d\'alerte sont POSTés vers votre endpoint quand activé.',+ alert_BLOCKED_ATTEMPT: 'Tentative bloquée',+ alert_THREAT_HIT: 'Threat intel',+ alert_DNS_TUNNEL: 'Tunnel DNS',+ alert_CLEARTEXT: 'En clair',+ alert_BASELINE_DEVIATION: 'Déviation de baseline',+ alert_LOCKDOWN: 'Lockdown',+ alertmsg_BLOCKED_ATTEMPT: d => `Règle pare-feu correspondante : ${d.rule?.value || '?'} (${d.rule?.kind || '?'})${d.process ? ` par ${d.process}` : ''}`,+ alertmsg_THREAT_HIT: d => `Threat intel : ${d.ip} signalé ${d.verdict} (${d.provider} : ${d.detail || 'rapporté'})`,+ alertmsg_DNS_TUNNEL: d => `Tunnel DNS possible : nom surdimensionné interrogé par ${d.process}`,+ alertmsg_CLEARTEXT: d => `Connexion ${d.proto} non chiffrée vers ${d.host || d.ip} par ${d.process}`,+ alertmsg_BASELINE_DEVIATION: d => `${d.process} a contacté un nouveau pays : ${d.country}`,+ alertmsg_LOCKDOWN: () => 'Mode lockdown ACTIVÉ — tout le trafic sortant est bloqué',+}diff --git a/frontend/src/locales/ja.js b/frontend/src/locales/ja.jsnew file mode 100644index 0000000..648c85f--- /dev/null+++ b/frontend/src/locales/ja.js@@ -0,0 +1,335 @@+/**+ * Snitch — 日本語UI辞書。+ *+ * EN: Isolated locale file — one per language, so community contributors can+ * add translations via a simple pull request (see CONTRIBUTING.md).+ * Values may be strings or functions for interpolation: t('key', arg).+ * FR: Fichier de locale isolé — un par langue, pour que la communauté puisse+ * ajouter des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation.+ */+export default {+ // ナビゲーション+ nav_graph: 'グラフ',+ nav_map: 'マップ',++ // ステータスバッジ+ status_connected: 'ライブ',+ status_connecting: '接続中…',+ status_disconnected: '切断',+ status_error: 'エラー',+ lan_devices: n => `LANデバイス ${n} 台`,++ // 凡例+ legend_alert: 'アラート',+ legend_unknown: '不明',+ legend_router: 'ルーター',+ legend_phone: 'スマホ',+ legend_pc: 'PC',+ legend_iot: 'IoT',+ legend_https: 'HTTPS',+ legend_tracking: 'トラッキング',+ legend_cdn: 'CDN',+ legend_dns: 'DNS',++ // サイドバーヘッダー + 統計+ app_name: 'SNITCH',+ tagline: '隠れた通信をすべて追跡。',+ footer_credit: 'aiXis 開発',+ stat_lan: 'LANデバイス',+ stat_ext: '外部ホスト',+ stat_traffic: 'トラフィック',++ // サイドバーセクション+ section_lan: n => `LANデバイス (${n})`,+ section_ext: (n, total) => total ? `外部ホスト (${n}/${total})` : `外部ホスト (${n})`,+ section_packets: '最近のトラフィック',++ // ノード詳細フィールド+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'ホスト名',+ field_vendor: 'ベンダー',+ field_type: 'タイプ',+ field_country: '国',+ field_city: '都市',+ field_org: '組織',+ field_category: 'カテゴリ',+ field_traffic: 'トラフィック',+ field_packets: 'パケット',+ processes: 'プロセス',+ online: 'オンライン',+ offline: 'オフライン',++ // 検索+ search_placeholder: 'ホスト、IP、国を検索…',+ cat_all: 'すべて',+ cat_unknown: '不明',+ cat_alerted: 'アラート',+ cat_safe: '安全',+ cat_tracking: 'トラッキング',+ cat_cdn: 'CDN',+ cat_dns: 'DNS',+ cat_admin: '管理',+ cat_local: 'ローカル',+ cat_lan_device: 'LANデバイス',+ cat_other: 'その他',++ // ノード名 + ヒント+ node_local: 'このデバイス',+ hint_local: 'これはこのマシン — Snitch が動作しているマシンです。送受信するすべてがグラフの中心から放射されます。',+ unidentified: '未識別',+ devtype_router: 'ルーター',+ devtype_phone: 'スマホ',+ devtype_pc: 'コンピューター',+ devtype_tv: 'テレビ',+ devtype_iot: 'IoTデバイス',+ devtype_unknown: '不明なタイプ',+ hint_unidentified: 'まだ識別されていません — 自己申告(DNS/mDNS)または MAC ベンダーが判明すると名前が表示されます。心当たりがなければルーターのクライアント一覧を確認してください。',+ hint_unresolved: 'まだ名前なし — DNS 応答または TLS ハンドシェイクでドメインが判明すると表示されます。',+ hint_private_mac: 'プライベート(ランダム化)MAC アドレス — iOS/Android/Windows が実アドレスを隠すためベンダー識別不可。正常なプライバシー動作です。',+ hint_gateway: 'これはあなたのインターネットボックス/ルーターです — すべてのトラフィックが物理的にここを通るため、通信しているのは正常です。',+ hint_lan_idle: '近隣テーブル経由でネットワーク上に検出 — データ交換なし。破線エッジは「存在」を意味し「通信中」ではありません。',+ hint_lan_active: b => `${b} 交換済み — 通常は自動アナウンス(Bonjour/mDNS、ファイル共有)。量が増えたら注視してください。`,+ ext_empty: '外部接続はまだありません — このマシンが通信するものはすべてここに表示されます。',+ legend_edge_solid: '実線 = トラフィックあり',+ legend_edge_dashed: '破線 = 検出のみ、データなし',+ legend_ring_safe: '緑リング = 識別済み・安全',+ legend_ring_warn: '黄リング = 不審',+ legend_ring_crit: '赤リング = アラート',+ legend_ring_none: 'リングなし = 未識別・中立',+ legend_perimeter: 'LAN境界',+ perim_lan: 'ローカルネットワーク',++ // アラートパネル+ alerts_title: 'アラート',+ alerts_total: '合計',+ alerts_empty: 'アラートはまだありません',+ alert_NEW_HOST: '新規ホスト',+ alert_SUSPICIOUS_PROCESS: '不審なプロセス',+ alert_SUSPICIOUS_PORT: '不審なポート',+ alert_BEACON: 'ビーコン C2',+ alert_VOLUME_SPIKE: 'トラフィックスパイク',+ alert_NEW_LAN_DEVICE: '新規デバイス',+ alert_DEVICE_OFFLINE: 'デバイスオフライン',+ alert_MEDIA_EXFIL: 'メディア流出',+ alert_PORT_SCAN: 'ポートスキャン',+ alert_UPLOAD_SPIKE: 'アップロードスパイク',+ alert_WATCHLIST_HIT: 'ウォッチリスト一致',+ alertmsg_NEW_HOST: d => `新規ホストへ接続: ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PROCESS: d => `不審なプロセス: ${d.process} → ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PORT: d => `不審なポート ${d.port}(${d.reason})→ ${d.host || d.ip}`,+ alertmsg_BEACON: d => `ビーコン的な周期性: ${d.host || d.ip} へ約 ${d.interval_s} 秒間隔`,+ alertmsg_VOLUME_SPIKE: d => `${d.host || d.ip} へのデータスパイク: ${d.window_s} 秒で ${Math.round((d.bytes || 0) / 1024)} KB`,+ alertmsg_MEDIA_EXFIL: d => `${d.device} の流出疑い: ${d.process} → ${d.host || d.ip}`,+ alertmsg_NEW_LAN_DEVICE: d => `ネットワーク上の新規デバイス: ${d.host || d.ip}`,+ alertmsg_DEVICE_OFFLINE: d => `デバイスがオフライン: ${d.host || d.ip}`,+ alertmsg_PORT_SCAN: d => `ポートスキャン: ${d.source || d.ip} が ${d.window_s} 秒で ${d.ports}+ ポートに接触`,+ alertmsg_UPLOAD_SPIKE: d => `アップロードスパイク: ${d.process} が ${d.window_s} 秒で ${d.mb} MB 送信`,+ alertmsg_WATCHLIST_HIT: d => `ウォッチリスト一致: ${d.match}(${d.host || d.ip})— ${d.process || '不明なプロセス'}`,+ time_just_now: 'たった今',+ time_seconds: n => `${n} 秒前`,+ time_minutes: n => `${n} 分前`,+ time_hours: n => `${n} 時間前`,++ // プライバシースコア+ privacy_title: 'プライバシースコア',+ privacy_critical_label: '危険',+ privacy_excellent_label: '優秀',+ privacy_risk_factors: n => `リスク要因 ${n} 件`,+ privacy_more_factors: n => `他 ${n} 件`,+ privacy_label_excellent: '優秀',+ privacy_label_good: '良好',+ privacy_label_average: '普通',+ privacy_label_weak: '弱い',+ privacy_label_critical: '危険',++ // タイムライン+ timeline_packets: n => `${n.toLocaleString()} パケット`,+ timeline_alerts: n => `アラート ${n} 件`,+ timeline_live: 'ライブ',++ // キャプチャ切替+ capture_stop: '停止',+ capture_start: '開始',+ capture_stopping: '停止中…',+ capture_starting: '開始中…',++ // ポートフィルター+ port_filter: 'ポート',+ port_all: '全ポート',+ port_placeholder: 'ポート追加(例: 443)',+ port_invalid: '無効なポート',++ // エクスポート+ export_btn: 'エクスポート',+ export_graph_json: 'グラフ (JSON)',+ export_graph_csv: 'グラフ (CSV)',+ export_alerts_json: 'アラート (JSON)',+ export_alerts_csv: 'アラート (CSV)',++ // プロセスフィルター+ process_filter: 'アプリ',+ process_filter_hint: 'クリックでグラフからアプリを非表示',+ process_none: 'まだプロセスが検出されていません',+ process_clear: 'すべてのアプリを表示',++ // IP ホワイトリスト+ ip_whitelist: '信頼済み',+ ip_whitelist_hint: '信頼済み IP はキャプチャ・表示されなくなります',+ ip_placeholder: 'IP追加(例: 1.1.1.1)',+ ip_invalid: '無効なIPアドレス',+ ip_clear: 'ホワイトリストをクリア',+ whitelist_action: '信頼済みにする',++ // マップ+ map_you: 'あなた',+ map_located: n => `${n} ホストを位置特定`,+ map_no_geo: '位置情報なし',++ // スコア要因+ score_trackers: n => `トラッカー ${n} 件へ接続`,+ score_tracker_traffic: pct => `トラッカーへのトラフィック ${pct}%`,+ score_ad_networks: n => `広告ネットワーク ${n} 件`,+ score_beacons: n => `ビーコン挙動 ${n} 件`,+ score_susp_proc: n => `不審なプロセス ${n} 件`,+ score_susp_ports: n => `危険なポート ${n} 件`,+ score_critical_alerts: n => `重大アラート ${n} 件`,+ score_warnings: n => `警告 ${n} 件`,+ score_https_ratio: pct => `HTTPS トラフィック ${pct}%`,+ score_no_trackers: 'トラッカー未検出',++ // 設定+ settings_title: '設定',+ settings_saved: '保存済み',+ close: '閉じる',+ settings_language: '言語 / Language',+ theme_toggle: 'ライト / ダークテーマ',+ settings_retention: '履歴保持期間',+ settings_retention_hint: 'トラフィックとアラート履歴の保持期間',+ settings_interface: 'キャプチャインターフェース',+ settings_interface_hint: 'スキャンするネットワークアダプター(適用にはキャプチャ再起動)',+ settings_interface_auto: '自動(最初の非ループバック)',+ settings_upload: 'アップロード警告しきい値',+ settings_upload_hint: 'プロセスが1分あたりこれ以上送信したら警告',+ settings_off: 'オフ',+ watchlist_title: 'ウォッチリスト',+ watchlist_hint: 'これらの IP やドメインへの通信でアラートを受け取る',+ watchlist_placeholder: '203.0.113.7 または example.com',+ watchlist_add: '追加',+ watchlist_remove: '削除',+ update_title: 'アップデート',+ update_checking: 'アップデート確認中…',+ update_available: v => `アップデートあり: v${v} — ダウンロード中`,+ update_downloading: p => `アップデートをダウンロード中… ${p}%`,+ update_ready: v => `v${v} ダウンロード済み — 再起動でインストール`,+ update_none: 'Snitch は最新です',+ update_error: 'アップデート確認に失敗',+ update_idle: 'まだ確認していません',+ update_restart: '再起動してインストール',+ update_check_btn: '今すぐ確認',+ update_auto: '自動で確認',+ update_privacy: 'github.com で新しいリリースを確認 — 下で無効化可。他のオプトイン呼び出しは PRIVACY.md 参照。',+ geo_title: 'ジオロケーションデータベース',+ geo_present: dbs => `インストール済み: ${dbs}`,+ geo_none: '未インストール — IP の位置特定なし',+ geo_download_btn: 'DB-IP Lite をダウンロード(無料)',+ geo_consent: 'db-ip.com から約 50 MB をダウンロード(CC BY 4.0)。他のオプトイン外向き呼び出しは PRIVACY.md に記載。',+ geo_downloading: 'ダウンロード中…',+ geo_done: n => `${n} 個のデータベースをダウンロード`,+ geo_failed: 'ダウンロード失敗 — 接続を確認',+ diag_title: '診断',+ diag_hint: 'バグ報告用のログとシステム情報',+ diag_open_logs: 'ログ',+ diag_export: 'エクスポート',+ settings_note: '設定はすべてローカルに保存されます。Snitch は明示的なオプトインなしに第三者へデータを送信しません。',+ nav_apps: 'アプリ',+ ignore_alert: 'このアラート種別/ホストを無視',++ // アプリビュー+ apps_empty: 'まだプロセスが関連付けられていません',+ apps_process: 'プロセス',+ apps_destinations: 'ホスト',+ apps_packets: 'パケット',+ apps_volume: '量',+ apps_top_dest: '主な宛先',+ apps_history_60m: '直近1時間(バイト/分)',+ alertmsg_NEW_HOSTS: n => `新規ホスト ${n} 件へ接続`,+ settings_autolaunch: 'ログイン時に起動',+ settings_autolaunch_hint: 'サインイン時に Snitch を自動起動',++ // オンボーディング+ onboard_title: 'Snitch へようこそ',+ onboard_sub: 'リアルタイム・ネットワークトラフィック可視化ツール — 設計からプライバシー重視。',+ onboard_priv_title: 'すべてこのマシンに留まる',+ onboard_priv_body: 'トラフィックのメタデータ、アラート、履歴はローカル SQLite データベースに保存。アカウントもクラウドもテレメトリもなし。',+ onboard_capture_title: 'キャプチャ対象',+ onboard_capture_body: 'パケットヘッダのみ: 宛先 IP、ポート、量、プロセス名、DNS 名、TLS サーバー名(SNI)。ペイロードは読みません。',+ onboard_out_title: 'マシンから出ていくもの',+ onboard_out_body: 'デフォルトでは何も。可能な外向き呼び出しは設定で自分で起動するジオロケーションデータベースのダウンロードのみ。',+ onboard_go: 'OK',++ // ファイアウォール & セキュリティ+ fw_title: 'ファイアウォール & セキュリティ',+ fw_lockdown: 'ロックダウンモード',+ fw_lockdown_hint: 'すべての外向きトラフィックを検出・ブロック(LANは維持)',+ fw_lockdown_confirm: 'ロックダウンを有効化しますか?オフにするまですべての外向きトラフィックが検出・ブロックされます。',+ fw_lockdown_on: 'LOCKDOWN',+ fw_supported: p => `${p} 上の OS ファイアウォール連携 — ベストエフォート、権限が必要`,+ fw_unsupported: 'このプラットフォームではネイティブファイアウォール非対応 — ルールは可視化のみ',+ fw_demo: 'デモ — 何も適用されません',+ fw_kind: 'ルール種別',+ fw_value: '値',+ fw_kind_ip: 'IP / CIDR',+ fw_kind_domain: 'ドメイン',+ fw_kind_process: 'プロセス',+ fw_kind_port: 'ポート',+ fw_ph_ip: '203.0.113.7 または 185.0.0.0/8',+ fw_ph_domain: 'evil.example',+ fw_ph_process: 'app.exe',+ fw_ph_port: '例: 4444',+ fw_rules: 'ルール',+ fw_empty: 'ルールなし — 外向き通信を強化するには追加してください',+ fw_blocked: n => `${n} 件の試行を検出`,+ fw_applied: 'OS ファイアウォールに適用済み',+ fw_not_applied: '可視化のみ(権限が必要)',+ fw_enable: '有効化',+ fw_disable: '無効化',+ fw_delete: 'ルール削除',+ audit_title: 'セキュリティ監査',+ audit_refresh: '更新',+ audit_critical: '重大',+ audit_warning: '警告',+ audit_risky: n => `高リスク国のホスト ${n} 件`,+ audit_loading: '読み込み中…',+ fw_forensics: 'フォレンジックエクスポート',+ block_action: 'ブロック',+ proc_kill: 'プロセスを終了',+ proc_suspend: '一時停止 / 再開',+ save: '保存',+ ti_title: '脅威インテリジェンス(オプトイン)',+ ti_hint: '新規ホストを評判プロバイダで照合',+ ti_none: '無効',+ ti_key: 'API キー',+ ti_key_ph: 'API キーを入力',+ ti_privacy: 'プロバイダへの外向き呼び出しは新規パブリックホストのみ。デフォルト無効 — キーはローカル保存。',+ wh_title: '外部 Webhook(オプトイン)',+ wh_hint: '警告/重大アラートを Discord、Slack、Telegram へ転送',+ wh_url: 'Webhook URL',+ wh_url_ph: 'https://discord.com/api/webhooks/… または任意のエンドポイント',+ wh_chat: 'Chat ID',+ wh_chat_ph: 'chat_id',+ wh_privacy: '有効時、アラートメッセージがエンドポイントへ POST されます。',+ alert_BLOCKED_ATTEMPT: 'ブロック試行',+ alert_THREAT_HIT: '脅威情報',+ alert_DNS_TUNNEL: 'DNS トンネル',+ alert_CLEARTEXT: '平文通信',+ alert_BASELINE_DEVIATION: 'ベースライン逸脱',+ alert_LOCKDOWN: 'ロックダウン',+ alertmsg_BLOCKED_ATTEMPT: d => `ファイアウォールルール一致: ${d.rule?.value || '?'}(${d.rule?.kind || '?'})${d.process ? ` by ${d.process}` : ''}`,+ alertmsg_THREAT_HIT: d => `脅威情報: ${d.ip} が ${d.verdict} と報告(${d.provider}: ${d.detail || '報告あり'})`,+ alertmsg_DNS_TUNNEL: d => `DNS トンネリングの可能性: ${d.process} が異常に長い名前を照会`,+ alertmsg_CLEARTEXT: d => `${d.process} による ${d.host || d.ip} への平文 ${d.proto} 接続`,+ alertmsg_BASELINE_DEVIATION: d => `${d.process} が新しい国へ接続: ${d.country}`,+ alertmsg_LOCKDOWN: () => 'ロックダウンモード有効 — すべての外向きトラフィックをブロック',+}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsnew file mode 100644index 0000000..c59758d--- /dev/null+++ b/frontend/src/locales/pt-BR.js@@ -0,0 +1,335 @@+/**+ * Snitch — dicionário da UI em português (Brasil).+ *+ * EN: Isolated locale file — one per language, so community contributors can+ * add translations via a simple pull request (see CONTRIBUTING.md).+ * Values may be strings or functions for interpolation: t('key', arg).+ * FR: Fichier de locale isolé — un par langue, pour que la communauté puisse+ * ajouter des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation.+ */+export default {+ // Navegação+ nav_graph: 'Grafo',+ nav_map: 'Mapa',++ // Status+ status_connected: 'Ao vivo',+ status_connecting: 'Conectando…',+ status_disconnected: 'Desconectado',+ status_error: 'Erro',+ lan_devices: n => `${n} dispositivo${n > 1 ? 's' : ''} LAN`,++ // Legenda+ legend_alert: 'Alerta',+ legend_unknown: 'Desconhecido',+ legend_router: 'Roteador',+ legend_phone: 'Celular',+ legend_pc: 'PC',+ legend_iot: 'IoT',+ legend_https: 'HTTPS',+ legend_tracking: 'Rastreamento',+ legend_cdn: 'CDN',+ legend_dns: 'DNS',++ // Cabeçalho da barra lateral + estatísticas+ app_name: 'SNITCH',+ tagline: 'Rastreie cada fluxo oculto.',+ footer_credit: 'Desenvolvido por aiXis',+ stat_lan: 'Dispositivos LAN',+ stat_ext: 'Hosts ext.',+ stat_traffic: 'Tráfego',++ // Seções da barra lateral+ section_lan: n => `Dispositivos LAN (${n})`,+ section_ext: (n, total) => total ? `Hosts externos (${n}/${total})` : `Hosts externos (${n})`,+ section_packets: 'Tráfego recente',++ // Campos do detalhe do nó+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'Hostname',+ field_vendor: 'Fabricante',+ field_type: 'Tipo',+ field_country: 'País',+ field_city: 'Cidade',+ field_org: 'Org',+ field_category: 'Categoria',+ field_traffic: 'Tráfego',+ field_packets: 'Pacotes',+ processes: 'Processos',+ online: 'online',+ offline: 'offline',++ // Busca+ search_placeholder: 'Buscar host, IP, país…',+ cat_all: 'Todos',+ cat_unknown: 'Desconhecido',+ cat_alerted: 'Alertas',+ cat_safe: 'Seguro',+ cat_tracking: 'Rastreamento',+ cat_cdn: 'CDN',+ cat_dns: 'DNS',+ cat_admin: 'Admin',+ cat_local: 'Local',+ cat_lan_device: 'Dispositivo LAN',+ cat_other: 'Outro',++ // Nomes de nós + dicas+ node_local: 'Este dispositivo',+ hint_local: 'Esta é ESTA máquina — a que roda o Snitch. Tudo que ela envia ou recebe irradia do centro do grafo.',+ unidentified: 'não identificado',+ devtype_router: 'Roteador',+ devtype_phone: 'Celular',+ devtype_pc: 'Computador',+ devtype_tv: 'TV',+ devtype_iot: 'Dispositivo IoT',+ devtype_unknown: 'Tipo desconhecido',+ hint_unidentified: 'Ainda não identificado — o nome aparece quando ele se anuncia (DNS/mDNS) ou o fabricante do MAC é conhecido. Se não reconhecer, verifique a lista de clientes do roteador.',+ hint_unresolved: 'Ainda sem nome — o domínio aparece quando uma resposta DNS ou handshake TLS o revela.',+ hint_private_mac: 'Endereço MAC privado (aleatório) — iOS/Android/Windows ocultam o real, então o fabricante não pode ser identificado. Comportamento normal de privacidade.',+ hint_gateway: 'Este é seu modem/roteador — TODO o seu tráfego passa fisicamente por ele, então vê-lo se comunicando é normal e esperado.',+ hint_lan_idle: 'Visto na rede via tabela de vizinhança — sem troca de dados. Uma aresta tracejada significa "presente", não "conversando".',+ hint_lan_active: b => `${b} trocados — geralmente anúncios automáticos (Bonjour/mDNS, compartilhamento). Observe se o volume subir.`,+ ext_empty: 'Nenhuma conexão externa ainda — tudo com que sua máquina conversa aparecerá aqui.',+ legend_edge_solid: 'linha sólida = tráfego',+ legend_edge_dashed: 'tracejado = visto, sem dados',+ legend_ring_safe: 'anel verde = identificado, seguro',+ legend_ring_warn: 'anel âmbar = suspeito',+ legend_ring_crit: 'anel vermelho = alerta',+ legend_ring_none: 'sem anel = não identificado, neutro',+ legend_perimeter: 'Perímetro LAN',+ perim_lan: 'REDE LOCAL',++ // Painel de alertas+ alerts_title: 'Alertas',+ alerts_total: 'total',+ alerts_empty: 'Nenhum alerta ainda',+ alert_NEW_HOST: 'Novo host',+ alert_SUSPICIOUS_PROCESS: 'Processo suspeito',+ alert_SUSPICIOUS_PORT: 'Porta suspeita',+ alert_BEACON: 'Beacon C2',+ alert_VOLUME_SPIKE: 'Pico de tráfego',+ alert_NEW_LAN_DEVICE: 'Novo dispositivo',+ alert_DEVICE_OFFLINE: 'Dispositivo offline',+ alert_MEDIA_EXFIL: 'Exfiltração de mídia',+ alert_PORT_SCAN: 'Varredura de portas',+ alert_UPLOAD_SPIKE: 'Pico de upload',+ alert_WATCHLIST_HIT: 'Hit na watchlist',+ alertmsg_NEW_HOST: d => `Novo host contatado: ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PROCESS: d => `Processo suspeito: ${d.process} → ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PORT: d => `Porta suspeita ${d.port} (${d.reason}) → ${d.host || d.ip}`,+ alertmsg_BEACON: d => `Regularidade tipo beacon: intervalo ~${d.interval_s}s para ${d.host || d.ip}`,+ alertmsg_VOLUME_SPIKE: d => `Pico de dados para ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} KB em ${d.window_s}s`,+ alertmsg_MEDIA_EXFIL: d => `Suspeita de exfiltração de ${d.device}: ${d.process} → ${d.host || d.ip}`,+ alertmsg_NEW_LAN_DEVICE: d => `Novo dispositivo na rede: ${d.host || d.ip}`,+ alertmsg_DEVICE_OFFLINE: d => `Dispositivo ficou offline: ${d.host || d.ip}`,+ alertmsg_PORT_SCAN: d => `Varredura de portas: ${d.source || d.ip} tocou ${d.ports}+ portas em ${d.window_s}s`,+ alertmsg_UPLOAD_SPIKE: d => `Pico de upload: ${d.process} enviou ${d.mb} MB em ${d.window_s}s`,+ alertmsg_WATCHLIST_HIT: d => `Hit na watchlist: ${d.match} (${d.host || d.ip}) — ${d.process || 'processo desconhecido'}`,+ time_just_now: 'agora mesmo',+ time_seconds: n => `há ${n}s`,+ time_minutes: n => `há ${n} min`,+ time_hours: n => `há ${n}h`,++ // Score de privacidade+ privacy_title: 'Score de Privacidade',+ privacy_critical_label: 'Crítico',+ privacy_excellent_label: 'Excelente',+ privacy_risk_factors: n => `${n} fator${n !== 1 ? 'es' : ''} de risco`,+ privacy_more_factors: n => `+${n} fator${n > 1 ? 'es' : ''} a mais`,+ privacy_label_excellent: 'Excelente',+ privacy_label_good: 'Bom',+ privacy_label_average: 'Médio',+ privacy_label_weak: 'Fraco',+ privacy_label_critical: 'Crítico',++ // Timeline+ timeline_packets: n => `${n.toLocaleString()} pacotes`,+ timeline_alerts: n => `${n} alerta${n > 1 ? 's' : ''}`,+ timeline_live: 'Ao vivo',++ // Toggle de captura+ capture_stop: 'Parar',+ capture_start: 'Iniciar',+ capture_stopping: 'Parando…',+ capture_starting: 'Iniciando…',++ // Filtro de portas+ port_filter: 'Portas',+ port_all: 'Todas as portas',+ port_placeholder: 'Adicionar porta (ex.: 443)',+ port_invalid: 'Porta inválida',++ // Exportar+ export_btn: 'Exportar',+ export_graph_json: 'Grafo (JSON)',+ export_graph_csv: 'Grafo (CSV)',+ export_alerts_json: 'Alertas (JSON)',+ export_alerts_csv: 'Alertas (CSV)',++ // Filtro de processos+ process_filter: 'Apps',+ process_filter_hint: 'Clique para ocultar o app do grafo',+ process_none: 'Nenhum processo detectado ainda',+ process_clear: 'Mostrar todos os apps',++ // Whitelist de IP+ ip_whitelist: 'Confiáveis',+ ip_whitelist_hint: 'IPs confiáveis não são mais capturados nem exibidos',+ ip_placeholder: 'Adicionar IP (ex.: 1.1.1.1)',+ ip_invalid: 'Endereço IP inválido',+ ip_clear: 'Limpar whitelist',+ whitelist_action: 'Marcar como confiável',++ // Mapa+ map_you: 'Você',+ map_located: n => `${n} host${n !== 1 ? 's' : ''} localizado${n !== 1 ? 's' : ''}`,+ map_no_geo: 'sem geo',++ // Fatores do score+ score_trackers: n => `${n} rastreador${n > 1 ? 'es' : ''} contatado${n > 1 ? 's' : ''}`,+ score_tracker_traffic: pct => `${pct}% do tráfego para rastreadores`,+ score_ad_networks: n => `${n} rede${n > 1 ? 's' : ''} de anúncios`,+ score_beacons: n => `${n} comportamento${n > 1 ? 's' : ''} de beacon`,+ score_susp_proc: n => `${n} processo${n > 1 ? 's' : ''} suspeito${n > 1 ? 's' : ''}`,+ score_susp_ports: n => `${n} porta${n > 1 ? 's' : ''} perigosa${n > 1 ? 's' : ''}`,+ score_critical_alerts: n => `${n} alerta${n > 1 ? 's' : ''} crítico${n > 1 ? 's' : ''}`,+ score_warnings: n => `${n} avisos`,+ score_https_ratio: pct => `${pct}% de tráfego HTTPS`,+ score_no_trackers: 'Nenhum rastreador detectado',++ // Configurações+ settings_title: 'Configurações',+ settings_saved: 'Salvo',+ close: 'Fechar',+ settings_language: 'Idioma / Language',+ theme_toggle: 'Tema claro / escuro',+ settings_retention: 'Retenção do histórico',+ settings_retention_hint: 'Por quanto tempo o histórico de tráfego e alertas é mantido',+ settings_interface: 'Interface de captura',+ settings_interface_hint: 'Qual adaptador de rede é escutado (reinicie a captura para aplicar)',+ settings_interface_auto: 'Auto (primeira não-loopback)',+ settings_upload: 'Limiar de alerta de upload',+ settings_upload_hint: 'Avisar quando um processo enviar mais que isto por minuto',+ settings_off: 'Desligado',+ watchlist_title: 'Watchlist',+ watchlist_hint: 'Seja alertado quando o tráfego tocar estes IPs ou domínios',+ watchlist_placeholder: '203.0.113.7 ou example.com',+ watchlist_add: 'Adicionar',+ watchlist_remove: 'Remover',+ update_title: 'Atualizações',+ update_checking: 'Verificando atualizações…',+ update_available: v => `Atualização disponível: v${v} — baixando`,+ update_downloading: p => `Baixando atualização… ${p}%`,+ update_ready: v => `v${v} baixada — reinicie para instalar`,+ update_none: 'Snitch está atualizado',+ update_error: 'Falha na verificação de atualização',+ update_idle: 'Nenhuma verificação ainda',+ update_restart: 'Reiniciar e instalar',+ update_check_btn: 'Verificar agora',+ update_auto: 'Verificar automaticamente',+ update_privacy: 'Verifica github.com por novas versões — desativável abaixo; outras chamadas opt-in no PRIVACY.md.',+ geo_title: 'Base de geolocalização',+ geo_present: dbs => `Instalada: ${dbs}`,+ geo_none: 'Não instalada — IPs não são geolocalizados',+ geo_download_btn: 'Baixar DB-IP Lite (grátis)',+ geo_consent: 'Baixa ~50 MB de db-ip.com (CC BY 4.0). Outras chamadas externas opt-in estão no PRIVACY.md.',+ geo_downloading: 'Baixando…',+ geo_done: n => `${n} base(s) baixada(s)`,+ geo_failed: 'Download falhou — verifique sua conexão',+ diag_title: 'Diagnóstico',+ diag_hint: 'Logs e informações do sistema para relatórios de bug',+ diag_open_logs: 'Logs',+ diag_export: 'Exportar',+ settings_note: 'Todas as configurações são armazenadas localmente. O Snitch nunca envia dados a terceiros sem o seu opt-in explícito.',+ nav_apps: 'Apps',+ ignore_alert: 'Ignorar este tipo de alerta/host',++ // Visão de apps+ apps_empty: 'Nenhum processo atribuído ainda',+ apps_process: 'Processo',+ apps_destinations: 'Hosts',+ apps_packets: 'Pacotes',+ apps_volume: 'Volume',+ apps_top_dest: 'Principais destinos',+ apps_history_60m: 'Última hora (bytes/min)',+ alertmsg_NEW_HOSTS: n => `${n} novo${n > 1 ? 's' : ''} host${n > 1 ? 's' : ''} contatado${n > 1 ? 's' : ''}`,+ settings_autolaunch: 'Iniciar ao fazer login',+ settings_autolaunch_hint: 'Iniciar o Snitch automaticamente ao entrar',++ // Onboarding+ onboard_title: 'Bem-vindo ao Snitch',+ onboard_sub: 'Visualizador de tráfego de rede em tempo real — privado por design.',+ onboard_priv_title: 'Tudo fica nesta máquina',+ onboard_priv_body: 'Metadados de tráfego, alertas e histórico são armazenados em um banco SQLite local. Sem conta, sem nuvem, sem telemetria.',+ onboard_capture_title: 'O que é capturado',+ onboard_capture_body: 'Apenas cabeçalhos de pacotes: IPs de destino, portas, volumes, nomes de processos, nomes DNS e SNI TLS. Conteúdos nunca são lidos.',+ onboard_out_title: 'O que sai da máquina',+ onboard_out_body: 'Nada por padrão. A única chamada externa possível é o download da base de geolocalização, que você mesmo aciona nas Configurações.',+ onboard_go: 'Entendi',++ // Firewall & segurança+ fw_title: 'Firewall & Segurança',+ fw_lockdown: 'Modo lockdown',+ fw_lockdown_hint: 'Sinalizar e bloquear TODO o tráfego de saída (LAN continua ativa)',+ fw_lockdown_confirm: 'Ativar lockdown? TODO o tráfego de saída será sinalizado e bloqueado até você desligar.',+ fw_lockdown_on: 'LOCKDOWN',+ fw_supported: p => `Orquestração do firewall do SO em ${p} — best effort, exige privilégios`,+ fw_unsupported: 'Firewall nativo não suportado aqui — regras são apenas visibilidade',+ fw_demo: 'demo — nada aplicado',+ fw_kind: 'Tipo de regra',+ fw_value: 'Valor',+ fw_kind_ip: 'IP / CIDR',+ fw_kind_domain: 'Domínio',+ fw_kind_process: 'Processo',+ fw_kind_port: 'Porta',+ fw_ph_ip: '203.0.113.7 ou 185.0.0.0/8',+ fw_ph_domain: 'evil.example',+ fw_ph_process: 'app.exe',+ fw_ph_port: 'ex.: 4444',+ fw_rules: 'Regras',+ fw_empty: 'Sem regras — adicione uma para endurecer as saídas',+ fw_blocked: n => `${n} tentativa${n > 1 ? 's' : ''} vista${n > 1 ? 's' : ''}`,+ fw_applied: 'aplicada ao firewall do SO',+ fw_not_applied: 'só visibilidade (exige privilégios)',+ fw_enable: 'Ativar',+ fw_disable: 'Desativar',+ fw_delete: 'Excluir regra',+ audit_title: 'Auditoria de segurança',+ audit_refresh: 'Atualizar',+ audit_critical: 'críticos',+ audit_warning: 'avisos',+ audit_risky: n => `${n} host(s) em países de alto risco`,+ audit_loading: 'Carregando…',+ fw_forensics: 'Exportação forense',+ block_action: 'Bloquear',+ proc_kill: 'Matar processo',+ proc_suspend: 'Suspender / retomar',+ save: 'Salvar',+ ti_title: 'Inteligência de ameaças (opt-in)',+ ti_hint: 'Verificar hosts novos contra um provedor de reputação',+ ti_none: 'Desativado',+ ti_key: 'Chave API',+ ti_key_ph: 'Sua chave API',+ ti_privacy: 'Chamadas externas ao provedor, só para hosts públicos novos. Desativado por padrão — a chave fica local.',+ wh_title: 'Webhook externo (opt-in)',+ wh_hint: 'Encaminhar alertas warning/críticos para Discord, Slack ou Telegram',+ wh_url: 'URL do webhook',+ wh_url_ph: 'https://discord.com/api/webhooks/… ou qualquer endpoint',+ wh_chat: 'Chat ID',+ wh_chat_ph: 'chat_id',+ wh_privacy: 'Mensagens de alerta são enviadas por POST ao seu endpoint quando ativado.',+ alert_BLOCKED_ATTEMPT: 'Tentativa bloqueada',+ alert_THREAT_HIT: 'Threat intel',+ alert_DNS_TUNNEL: 'Túnel DNS',+ alert_CLEARTEXT: 'Em claro',+ alert_BASELINE_DEVIATION: 'Desvio de baseline',+ alert_LOCKDOWN: 'Lockdown',+ alertmsg_BLOCKED_ATTEMPT: d => `Regra de firewall correspondente: ${d.rule?.value || '?'} (${d.rule?.kind || '?'})${d.process ? ` por ${d.process}` : ''}`,+ alertmsg_THREAT_HIT: d => `Threat intel: ${d.ip} marcado como ${d.verdict} (${d.provider}: ${d.detail || 'reportado'})`,+ alertmsg_DNS_TUNNEL: d => `Possível tunelamento DNS: nome longo demais consultado por ${d.process}`,+ alertmsg_CLEARTEXT: d => `Conexão ${d.proto} não criptografada para ${d.host || d.ip} por ${d.process}`,+ alertmsg_BASELINE_DEVIATION: d => `${d.process} contatou um país novo: ${d.country}`,+ alertmsg_LOCKDOWN: () => 'Modo lockdown ATIVADO — todo o tráfego de saída bloqueado',+}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsnew file mode 100644index 0000000..c780c54--- /dev/null+++ b/frontend/src/locales/ru.js@@ -0,0 +1,335 @@+/**+ * Snitch — русский словарь интерфейса.+ *+ * EN: Isolated locale file — one per language, so community contributors can+ * add translations via a simple pull request (see CONTRIBUTING.md).+ * Values may be strings or functions for interpolation: t('key', arg).+ * FR: Fichier de locale isolé — un par langue, pour que la communauté puisse+ * ajouter des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation.+ */+export default {+ // Навигация+ nav_graph: 'Граф',+ nav_map: 'Карта',++ // Индикатор статуса+ status_connected: 'В эфире',+ status_connecting: 'Подключение…',+ status_disconnected: 'Отключено',+ status_error: 'Ошибка',+ lan_devices: n => `LAN-устройств: ${n}`,++ // Легенда+ legend_alert: 'Тревога',+ legend_unknown: 'Неизвестно',+ legend_router: 'Роутер',+ legend_phone: 'Телефон',+ legend_pc: 'ПК',+ legend_iot: 'IoT',+ legend_https: 'HTTPS',+ legend_tracking: 'Трекинг',+ legend_cdn: 'CDN',+ legend_dns: 'DNS',++ // Заголовок боковой панели + статистика+ app_name: 'SNITCH',+ tagline: 'Отслеживайте каждый скрытый поток.',+ footer_credit: 'Разработано aiXis',+ stat_lan: 'LAN-устройства',+ stat_ext: 'Внешние хосты',+ stat_traffic: 'Трафик',++ // Разделы панели+ section_lan: n => `LAN-устройства (${n})`,+ section_ext: (n, total) => total ? `Внешние хосты (${n}/${total})` : `Внешние хосты (${n})`,+ section_packets: 'Недавний трафик',++ // Поля карточки узла+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: 'Имя хоста',+ field_vendor: 'Производитель',+ field_type: 'Тип',+ field_country: 'Страна',+ field_city: 'Город',+ field_org: 'Организация',+ field_category: 'Категория',+ field_traffic: 'Трафик',+ field_packets: 'Пакеты',+ processes: 'Процессы',+ online: 'в сети',+ offline: 'офлайн',++ // Поиск+ search_placeholder: 'Поиск хоста, IP, страны…',+ cat_all: 'Все',+ cat_unknown: 'Неизвестно',+ cat_alerted: 'Тревоги',+ cat_safe: 'Безопасно',+ cat_tracking: 'Трекинг',+ cat_cdn: 'CDN',+ cat_dns: 'DNS',+ cat_admin: 'Админ',+ cat_local: 'Локальный',+ cat_lan_device: 'LAN-устройство',+ cat_other: 'Прочее',++ // Имена узлов + подсказки+ node_local: 'Это устройство',+ hint_local: 'Это ЭТА машина — та, где работает Snitch. Всё, что она отправляет или получает, исходит из центра графа.',+ unidentified: 'не опознано',+ devtype_router: 'Роутер',+ devtype_phone: 'Телефон',+ devtype_pc: 'Компьютер',+ devtype_tv: 'Телевизор',+ devtype_iot: 'IoT-устройство',+ devtype_unknown: 'Неизвестный тип',+ hint_unidentified: 'Пока не опознано — имя появится, когда устройство представится (DNS/mDNS) или станет известен производитель MAC. Если не узнаёте его, проверьте список клиентов роутера.',+ hint_unresolved: 'Имени пока нет — домен появится, когда его раскроет DNS-ответ или TLS-рукопожатие.',+ hint_private_mac: 'Приватный (случайный) MAC-адрес — iOS/Android/Windows скрывают настоящий, поэтому производитель не определяется. Нормальное поведение для приватности.',+ hint_gateway: 'Это ваш роутер/модем — ВЕСЬ ваш трафик физически проходит через него, так что видеть его активность нормально и ожидаемо.',+ hint_lan_idle: 'Замечено в сети через таблицу соседей — данные не передавались. Пунктирная связь означает «присутствует», а не «общается».',+ hint_lan_active: b => `Передано: ${b} — обычно автоматические анонсы (Bonjour/mDNS, общий доступ). Следите, если объём растёт.`,+ ext_empty: 'Внешних подключений пока нет — всё, с чем говорит ваша машина, появится здесь.',+ legend_edge_solid: 'сплошная линия = трафик',+ legend_edge_dashed: 'пунктир = замечен, без данных',+ legend_ring_safe: 'зелёное кольцо = опознан, безопасен',+ legend_ring_warn: 'янтарное кольцо = подозрителен',+ legend_ring_crit: 'красное кольцо = тревога',+ legend_ring_none: 'без кольца = не опознан, нейтрален',+ legend_perimeter: 'Периметр LAN',+ perim_lan: 'ЛОКАЛЬНАЯ СЕТЬ',++ // Панель тревог+ alerts_title: 'Тревоги',+ alerts_total: 'всего',+ alerts_empty: 'Тревог пока нет',+ alert_NEW_HOST: 'Новый хост',+ alert_SUSPICIOUS_PROCESS: 'Подозрительный процесс',+ alert_SUSPICIOUS_PORT: 'Подозрительный порт',+ alert_BEACON: 'Маячок C2',+ alert_VOLUME_SPIKE: 'Всплеск трафика',+ alert_NEW_LAN_DEVICE: 'Новое устройство',+ alert_DEVICE_OFFLINE: 'Устройство офлайн',+ alert_MEDIA_EXFIL: 'Утечка медиа',+ alert_PORT_SCAN: 'Скан портов',+ alert_UPLOAD_SPIKE: 'Всплеск отгрузки',+ alert_WATCHLIST_HIT: 'Совпадение watchlist',+ alertmsg_NEW_HOST: d => `Новый хост: ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PROCESS: d => `Подозрительный процесс: ${d.process} → ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PORT: d => `Подозрительный порт ${d.port} (${d.reason}) → ${d.host || d.ip}`,+ alertmsg_BEACON: d => `Периодичность маячка: интервал ~${d.interval_s}с к ${d.host || d.ip}`,+ alertmsg_VOLUME_SPIKE: d => `Всплеск данных к ${d.host || d.ip}: ${Math.round((d.bytes || 0) / 1024)} КБ за ${d.window_s}с`,+ alertmsg_MEDIA_EXFIL: d => `Подозрение на утечку ${d.device}: ${d.process} → ${d.host || d.ip}`,+ alertmsg_NEW_LAN_DEVICE: d => `Новое устройство в сети: ${d.host || d.ip}`,+ alertmsg_DEVICE_OFFLINE: d => `Устройство ушло офлайн: ${d.host || d.ip}`,+ alertmsg_PORT_SCAN: d => `Скан портов: ${d.source || d.ip} затронул ${d.ports}+ портов за ${d.window_s}с`,+ alertmsg_UPLOAD_SPIKE: d => `Всплеск отгрузки: ${d.process} отправил ${d.mb} МБ за ${d.window_s}с`,+ alertmsg_WATCHLIST_HIT: d => `Совпадение watchlist: ${d.match} (${d.host || d.ip}) — ${d.process || 'неизвестный процесс'}`,+ time_just_now: 'только что',+ time_seconds: n => `${n}с назад`,+ time_minutes: n => `${n} мин назад`,+ time_hours: n => `${n} ч назад`,++ // Оценка приватности+ privacy_title: 'Оценка приватности',+ privacy_critical_label: 'Критично',+ privacy_excellent_label: 'Отлично',+ privacy_risk_factors: n => `Факторов риска: ${n}`,+ privacy_more_factors: n => `+${n} ещё`,+ privacy_label_excellent: 'Отлично',+ privacy_label_good: 'Хорошо',+ privacy_label_average: 'Средне',+ privacy_label_weak: 'Слабо',+ privacy_label_critical: 'Критично',++ // Таймлайн+ timeline_packets: n => `${n.toLocaleString()} пакетов`,+ timeline_alerts: n => `тревог: ${n}`,+ timeline_live: 'В эфире',++ // Переключатель захвата+ capture_stop: 'Стоп',+ capture_start: 'Старт',+ capture_stopping: 'Остановка…',+ capture_starting: 'Запуск…',++ // Фильтр портов+ port_filter: 'Порты',+ port_all: 'Все порты',+ port_placeholder: 'Добавить порт (напр. 443)',+ port_invalid: 'Неверный порт',++ // Экспорт+ export_btn: 'Экспорт',+ export_graph_json: 'Граф (JSON)',+ export_graph_csv: 'Граф (CSV)',+ export_alerts_json: 'Тревоги (JSON)',+ export_alerts_csv: 'Тревоги (CSV)',++ // Фильтр процессов+ process_filter: 'Приложения',+ process_filter_hint: 'Нажмите, чтобы скрыть приложение с графа',+ process_none: 'Процессы пока не обнаружены',+ process_clear: 'Показать все приложения',++ // Белый список IP+ ip_whitelist: 'Доверенные',+ ip_whitelist_hint: 'Доверенные IP больше не захватываются и не показываются',+ ip_placeholder: 'Добавить IP (напр. 1.1.1.1)',+ ip_invalid: 'Неверный IP-адрес',+ ip_clear: 'Очистить список',+ whitelist_action: 'Пометить как доверенный',++ // Карта+ map_you: 'Вы',+ map_located: n => `Геолокализовано хостов: ${n}`,+ map_no_geo: 'нет гео',++ // Факторы оценки+ score_trackers: n => `Трекеров контактировано: ${n}`,+ score_tracker_traffic: pct => `${pct}% трафика к трекерам`,+ score_ad_networks: n => `Рекламных сетей: ${n}`,+ score_beacons: n => `Поведений маячка: ${n}`,+ score_susp_proc: n => `Подозрительных процессов: ${n}`,+ score_susp_ports: n => `Опасных портов: ${n}`,+ score_critical_alerts: n => `Критических тревог: ${n}`,+ score_warnings: n => `Предупреждений: ${n}`,+ score_https_ratio: pct => `${pct}% HTTPS-трафика`,+ score_no_trackers: 'Трекеры не обнаружены',++ // Настройки+ settings_title: 'Настройки',+ settings_saved: 'Сохранено',+ close: 'Закрыть',+ settings_language: 'Язык / Language',+ theme_toggle: 'Светлая / тёмная тема',+ settings_retention: 'Хранение истории',+ settings_retention_hint: 'Как долго хранится история трафика и тревог',+ settings_interface: 'Интерфейс захвата',+ settings_interface_hint: 'Какой сетевой адаптер прослушивается (перезапустите захват для применения)',+ settings_interface_auto: 'Авто (первый не-loopback)',+ settings_upload: 'Порог тревоги отгрузки',+ settings_upload_hint: 'Предупреждать, когда процесс отгружает больше этого за минуту',+ settings_off: 'Выкл',+ watchlist_title: 'Список наблюдения',+ watchlist_hint: 'Получать тревогу, когда трафик касается этих IP или доменов',+ watchlist_placeholder: '203.0.113.7 или example.com',+ watchlist_add: 'Добавить',+ watchlist_remove: 'Удалить',+ update_title: 'Обновления',+ update_checking: 'Проверка обновлений…',+ update_available: v => `Доступно обновление: v${v} — загрузка`,+ update_downloading: p => `Загрузка обновления… ${p}%`,+ update_ready: v => `v${v} загружена — перезапустите для установки`,+ update_none: 'Snitch обновлён',+ update_error: 'Проверка обновлений не удалась',+ update_idle: 'Проверок ещё не было',+ update_restart: 'Перезапуск и установка',+ update_check_btn: 'Проверить',+ update_auto: 'Проверять автоматически',+ update_privacy: 'Проверяет github.com на новые релизы — отключается ниже; прочие вызовы opt-in — в PRIVACY.md.',+ geo_title: 'База геолокации',+ geo_present: dbs => `Установлено: ${dbs}`,+ geo_none: 'Не установлена — IP не геолокализируются',+ geo_download_btn: 'Скачать DB-IP Lite (бесплатно)',+ geo_consent: 'Скачивает ~50 МБ с db-ip.com (CC BY 4.0). Прочие исходящие вызовы (opt-in) перечислены в PRIVACY.md.',+ geo_downloading: 'Загрузка…',+ geo_done: n => `Загружено баз: ${n}`,+ geo_failed: 'Загрузка не удалась — проверьте соединение',+ diag_title: 'Диагностика',+ diag_hint: 'Логи и данные системы для баг-репортов',+ diag_open_logs: 'Логи',+ diag_export: 'Экспорт',+ settings_note: 'Все настройки хранятся локально. Snitch никогда не отправляет данные третьим лицам без вашего явного согласия.',+ nav_apps: 'Приложения',+ ignore_alert: 'Игнорировать этот тип тревоги/хост',++ // Вид приложений+ apps_empty: 'Процессы пока не привязаны',+ apps_process: 'Процесс',+ apps_destinations: 'Хосты',+ apps_packets: 'Пакеты',+ apps_volume: 'Объём',+ apps_top_dest: 'Топ направлений',+ apps_history_60m: 'Последний час (байт/мин)',+ alertmsg_NEW_HOSTS: n => `Контактировано новых хостов: ${n}`,+ settings_autolaunch: 'Запускать при входе',+ settings_autolaunch_hint: 'Запускать Snitch автоматически при входе в систему',++ // Онбординг+ onboard_title: 'Добро пожаловать в Snitch',+ onboard_sub: 'Визуализатор сетевого трафика в реальном времени — приватный по устройству.',+ onboard_priv_title: 'Всё остаётся на этой машине',+ onboard_priv_body: 'Метаданные трафика, тревоги и история хранятся в локальной базе SQLite. Ни аккаунта, ни облака, ни телеметрии.',+ onboard_capture_title: 'Что захватывается',+ onboard_capture_body: 'Только заголовки пакетов: IP назначения, порты, объёмы, имена процессов, DNS-имена и TLS SNI. Полезная нагрузка никогда не читается.',+ onboard_out_title: 'Что покидает машину',+ onboard_out_body: 'По умолчанию — ничего. Единственный возможный исходящий вызов — загрузка базы геолокации, которую вы запускаете сами в Настройках.',+ onboard_go: 'Понятно',++ // Файрвол и безопасность+ fw_title: 'Файрвол и безопасность',+ fw_lockdown: 'Режим lockdown',+ fw_lockdown_hint: 'Помечать и блокировать ВЕСЬ исходящий трафик (LAN остаётся)',+ fw_lockdown_confirm: 'Включить lockdown? ВЕСЬ исходящий трафик будет помечаться и блокироваться до отключения.',+ fw_lockdown_on: 'LOCKDOWN',+ fw_supported: p => `Оркестрация файрвола ОС на ${p} — по возможности, нужны права`,+ fw_unsupported: 'Нативный файрвол здесь не поддерживается — правила только для видимости',+ fw_demo: 'демо — ничего не применено',+ fw_kind: 'Тип правила',+ fw_value: 'Значение',+ fw_kind_ip: 'IP / CIDR',+ fw_kind_domain: 'Домен',+ fw_kind_process: 'Процесс',+ fw_kind_port: 'Порт',+ fw_ph_ip: '203.0.113.7 или 185.0.0.0/8',+ fw_ph_domain: 'evil.example',+ fw_ph_process: 'app.exe',+ fw_ph_port: 'напр. 4444',+ fw_rules: 'Правила',+ fw_empty: 'Правил нет — добавьте одно для ужесточения исходящего трафика',+ fw_blocked: n => `Попыток замечено: ${n}`,+ fw_applied: 'применено к файрволу ОС',+ fw_not_applied: 'только видимость (нужны права)',+ fw_enable: 'Включить',+ fw_disable: 'Отключить',+ fw_delete: 'Удалить правило',+ audit_title: 'Аудит безопасности',+ audit_refresh: 'Обновить',+ audit_critical: 'критических',+ audit_warning: 'предупреждений',+ audit_risky: n => `Хостов в странах высокого риска: ${n}`,+ audit_loading: 'Загрузка…',+ fw_forensics: 'Форензик-экспорт',+ block_action: 'Блокировать',+ proc_kill: 'Убить процесс',+ proc_suspend: 'Приостановить / возобновить',+ save: 'Сохранить',+ ti_title: 'Threat intelligence (opt-in)',+ ti_hint: 'Проверять новые хосты через провайдера репутации',+ ti_none: 'Отключено',+ ti_key: 'API-ключ',+ ti_key_ph: 'Ваш API-ключ',+ ti_privacy: 'Исходящие вызовы к провайдеру, только для новых публичных хостов. По умолчанию отключено — ключ хранится локально.',+ wh_title: 'Внешний webhook (opt-in)',+ wh_hint: 'Пересылать критические тревоги в Discord, Slack или Telegram',+ wh_url: 'URL webhook',+ wh_url_ph: 'https://discord.com/api/webhooks/… или любой endpoint',+ wh_chat: 'Chat ID',+ wh_chat_ph: 'chat_id',+ wh_privacy: 'Тексты тревог отправляются POST-запросом на ваш endpoint при включении.',+ alert_BLOCKED_ATTEMPT: 'Заблокированная попытка',+ alert_THREAT_HIT: 'Threat intel',+ alert_DNS_TUNNEL: 'DNS-туннель',+ alert_CLEARTEXT: 'Открытый текст',+ alert_BASELINE_DEVIATION: 'Отклонение от базы',+ alert_LOCKDOWN: 'Lockdown',+ alertmsg_BLOCKED_ATTEMPT: d => `Сработало правило файрвола: ${d.rule?.value || '?'} (${d.rule?.kind || '?'})${d.process ? ` от ${d.process}` : ''}`,+ alertmsg_THREAT_HIT: d => `Threat intel: ${d.ip} помечен как ${d.verdict} (${d.provider}: ${d.detail || 'сообщено'})`,+ alertmsg_DNS_TUNNEL: d => `Возможный DNS-туннель: слишком длинное имя запрошено процессом ${d.process}`,+ alertmsg_CLEARTEXT: d => `Незашифрованное ${d.proto}-соединение с ${d.host || d.ip} от ${d.process}`,+ alertmsg_BASELINE_DEVIATION: d => `${d.process} связался с новой страной: ${d.country}`,+ alertmsg_LOCKDOWN: () => 'Режим lockdown ВКЛЮЧЁН — весь исходящий трафик заблокирован',+}diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.jsnew file mode 100644index 0000000..8fef25c--- /dev/null+++ b/frontend/src/locales/zh-CN.js@@ -0,0 +1,335 @@+/**+ * Snitch — 简体中文界面词典。+ *+ * EN: Isolated locale file — one per language, so community contributors can+ * add translations via a simple pull request (see CONTRIBUTING.md).+ * Values may be strings or functions for interpolation: t('key', arg).+ * FR: Fichier de locale isolé — un par langue, pour que la communauté puisse+ * ajouter des traductions par simple pull request (cf. CONTRIBUTING.md).+ * Les valeurs sont des chaînes ou des fonctions d'interpolation.+ */+export default {+ // 导航+ nav_graph: '图',+ nav_map: '地图',++ // 状态徽标+ status_connected: '实时',+ status_connecting: '连接中…',+ status_disconnected: '已断开',+ status_error: '错误',+ lan_devices: n => `${n} 个局域网设备`,++ // 图例+ legend_alert: '警报',+ legend_unknown: '未知',+ legend_router: '路由器',+ legend_phone: '手机',+ legend_pc: '电脑',+ legend_iot: '物联网',+ legend_https: 'HTTPS',+ legend_tracking: '跟踪',+ legend_cdn: 'CDN',+ legend_dns: 'DNS',++ // 侧栏标题 + 统计+ app_name: 'SNITCH',+ tagline: '追踪每一个隐藏的流量。',+ footer_credit: '由 aiXis 开发',+ stat_lan: '局域网设备',+ stat_ext: '外部主机',+ stat_traffic: '流量',++ // 侧栏分区+ section_lan: n => `局域网设备 (${n})`,+ section_ext: (n, total) => total ? `外部主机 (${n}/${total})` : `外部主机 (${n})`,+ section_packets: '最近流量',++ // 节点详情字段+ field_ip: 'IP',+ field_mac: 'MAC',+ field_hostname: '主机名',+ field_vendor: '厂商',+ field_type: '类型',+ field_country: '国家',+ field_city: '城市',+ field_org: '组织',+ field_category: '类别',+ field_traffic: '流量',+ field_packets: '数据包',+ processes: '进程',+ online: '在线',+ offline: '离线',++ // 搜索+ search_placeholder: '搜索主机、IP、国家…',+ cat_all: '全部',+ cat_unknown: '未知',+ cat_alerted: '警报',+ cat_safe: '安全',+ cat_tracking: '跟踪',+ cat_cdn: 'CDN',+ cat_dns: 'DNS',+ cat_admin: '管理',+ cat_local: '本地',+ cat_lan_device: '局域网设备',+ cat_other: '其他',++ // 节点名称 + 提示+ node_local: '本设备',+ hint_local: '这就是本机 — 运行 Snitch 的机器。它收发的一切都从图的中心辐射出去。',+ unidentified: '未识别',+ devtype_router: '路由器',+ devtype_phone: '手机',+ devtype_pc: '电脑',+ devtype_tv: '电视',+ devtype_iot: 'IoT 设备',+ devtype_unknown: '未知类型',+ hint_unidentified: '尚未识别 — 当它通过 DNS/mDNS 自报或 MAC 厂商已知时会出现名称。如果不认识它,请检查路由器的客户端列表。',+ hint_unresolved: '尚未命名 — 当 DNS 应答或 TLS 握手揭示域名时会显示。',+ hint_private_mac: '私有(随机化)MAC 地址 — iOS/Android/Windows 隐藏真实地址,因此无法识别厂商。这是正常的隐私行为。',+ hint_gateway: '这是您的网络盒子/路由器 — 所有流量都物理经过它,因此看到它通信是正常的。',+ hint_lan_idle: '通过邻居表在网络中发现 — 未交换数据。虚线表示“存在”,而非“在通信”。',+ hint_lan_active: b => `已交换 ${b} — 通常是自动通告(Bonjour/mDNS、文件共享)。若流量上升请留意。`,+ ext_empty: '暂无外部连接 — 您的机器与任何对象的通信都会显示在这里。',+ legend_edge_solid: '实线 = 有流量',+ legend_edge_dashed: '虚线 = 已发现,无数据',+ legend_ring_safe: '绿环 = 已识别,安全',+ legend_ring_warn: '黄环 = 可疑',+ legend_ring_crit: '红环 = 警报',+ legend_ring_none: '无环 = 未识别,中立',+ legend_perimeter: '局域网边界',+ perim_lan: '本地网络',++ // 警报面板+ alerts_title: '警报',+ alerts_total: '总计',+ alerts_empty: '暂无警报',+ alert_NEW_HOST: '新主机',+ alert_SUSPICIOUS_PROCESS: '可疑进程',+ alert_SUSPICIOUS_PORT: '可疑端口',+ alert_BEACON: '信标 C2',+ alert_VOLUME_SPIKE: '流量突增',+ alert_NEW_LAN_DEVICE: '新设备',+ alert_DEVICE_OFFLINE: '设备离线',+ alert_MEDIA_EXFIL: '媒体外泄',+ alert_PORT_SCAN: '端口扫描',+ alert_UPLOAD_SPIKE: '上传突增',+ alert_WATCHLIST_HIT: '监视列表命中',+ alertmsg_NEW_HOST: d => `联系了新主机:${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PROCESS: d => `可疑进程:${d.process} → ${d.host || d.ip}`,+ alertmsg_SUSPICIOUS_PORT: d => `可疑端口 ${d.port}(${d.reason})→ ${d.host || d.ip}`,+ alertmsg_BEACON: d => `类信标周期性:向 ${d.host || d.ip} 约每 ${d.interval_s} 秒一次`,+ alertmsg_VOLUME_SPIKE: d => `向 ${d.host || d.ip} 的数据突增:${d.window_s} 秒内 ${Math.round((d.bytes || 0) / 1024)} KB`,+ alertmsg_MEDIA_EXFIL: d => `疑似 ${d.device} 外泄:${d.process} → ${d.host || d.ip}`,+ alertmsg_NEW_LAN_DEVICE: d => `网络上的新设备:${d.host || d.ip}`,+ alertmsg_DEVICE_OFFLINE: d => `设备已离线:${d.host || d.ip}`,+ alertmsg_PORT_SCAN: d => `端口扫描:${d.source || d.ip} 在 ${d.window_s} 秒内触及 ${d.ports}+ 个端口`,+ alertmsg_UPLOAD_SPIKE: d => `上传突增:${d.process} 在 ${d.window_s} 秒内发送 ${d.mb} MB`,+ alertmsg_WATCHLIST_HIT: d => `监视列表命中:${d.match}(${d.host || d.ip})— ${d.process || '未知进程'}`,+ time_just_now: '刚刚',+ time_seconds: n => `${n} 秒前`,+ time_minutes: n => `${n} 分钟前`,+ time_hours: n => `${n} 小时前`,++ // 隐私评分+ privacy_title: '隐私评分',+ privacy_critical_label: '危险',+ privacy_excellent_label: '优秀',+ privacy_risk_factors: n => `${n} 个风险因素`,+ privacy_more_factors: n => `还有 ${n} 个因素`,+ privacy_label_excellent: '优秀',+ privacy_label_good: '良好',+ privacy_label_average: '一般',+ privacy_label_weak: '较弱',+ privacy_label_critical: '危险',++ // 时间线+ timeline_packets: n => `${n.toLocaleString()} 个数据包`,+ timeline_alerts: n => `${n} 个警报`,+ timeline_live: '实时',++ // 捕获开关+ capture_stop: '停止',+ capture_start: '开始',+ capture_stopping: '停止中…',+ capture_starting: '启动中…',++ // 端口过滤+ port_filter: '端口',+ port_all: '全部端口',+ port_placeholder: '添加端口(如 443)',+ port_invalid: '无效端口',++ // 导出+ export_btn: '导出',+ export_graph_json: '图 (JSON)',+ export_graph_csv: '图 (CSV)',+ export_alerts_json: '警报 (JSON)',+ export_alerts_csv: '警报 (CSV)',++ // 进程过滤+ process_filter: '应用',+ process_filter_hint: '点击从图中隐藏该应用',+ process_none: '尚未检测到进程',+ process_clear: '显示全部应用',++ // IP 白名单+ ip_whitelist: '受信任',+ ip_whitelist_hint: '受信任的 IP 不再被捕获或显示',+ ip_placeholder: '添加 IP(如 1.1.1.1)',+ ip_invalid: '无效的 IP 地址',+ ip_clear: '清空白名单',+ whitelist_action: '标记为受信任',++ // 地图+ map_you: '您',+ map_located: n => `已定位 ${n} 个主机`,+ map_no_geo: '无地理信息',++ // 评分因素+ score_trackers: n => `已联系 ${n} 个跟踪器`,+ score_tracker_traffic: pct => `${pct}% 流量发往跟踪器`,+ score_ad_networks: n => `${n} 个广告网络`,+ score_beacons: n => `${n} 个信标行为`,+ score_susp_proc: n => `${n} 个可疑进程`,+ score_susp_ports: n => `${n} 个危险端口`,+ score_critical_alerts: n => `${n} 个严重警报`,+ score_warnings: n => `${n} 个警告`,+ score_https_ratio: pct => `${pct}% HTTPS 流量`,+ score_no_trackers: '未检测到跟踪器',++ // 设置+ settings_title: '设置',+ settings_saved: '已保存',+ close: '关闭',+ settings_language: '语言 / Language',+ theme_toggle: '浅色 / 深色主题',+ settings_retention: '历史保留',+ settings_retention_hint: '流量和警报历史的保留时长',+ settings_interface: '捕获接口',+ settings_interface_hint: '监听哪个网卡(重启捕获后生效)',+ settings_interface_auto: '自动(第一个非回环)',+ settings_upload: '上传警报阈值',+ settings_upload_hint: '当进程每分钟上传超过此值时告警',+ settings_off: '关',+ watchlist_title: '监视列表',+ watchlist_hint: '当流量触及这些 IP 或域名时收到警报',+ watchlist_placeholder: '203.0.113.7 或 example.com',+ watchlist_add: '添加',+ watchlist_remove: '移除',+ update_title: '更新',+ update_checking: '正在检查更新…',+ update_available: v => `有可用更新:v${v} — 正在下载`,+ update_downloading: p => `正在下载更新… ${p}%`,+ update_ready: v => `v${v} 已下载 — 重启以安装`,+ update_none: 'Snitch 已是最新',+ update_error: '更新检查失败',+ update_idle: '尚未检查',+ update_restart: '重启并安装',+ update_check_btn: '立即检查',+ update_auto: '自动检查',+ update_privacy: '检查 github.com 上的新版本 — 可在下方关闭;其他可选调用见 PRIVACY.md。',+ geo_title: '地理定位数据库',+ geo_present: dbs => `已安装:${dbs}`,+ geo_none: '未安装 — IP 不会被地理定位',+ geo_download_btn: '下载 DB-IP Lite(免费)',+ geo_consent: '从 db-ip.com 下载约 50 MB(CC BY 4.0)。其他可选出站调用见 PRIVACY.md。',+ geo_downloading: '下载中…',+ geo_done: n => `已下载 ${n} 个数据库`,+ geo_failed: '下载失败 — 请检查网络连接',+ diag_title: '诊断',+ diag_hint: '用于错误报告的日志和系统信息',+ diag_open_logs: '日志',+ diag_export: '导出',+ settings_note: '所有设置均存储在本地。未经您明确启用,Snitch 从不向第三方发送数据。',+ nav_apps: '应用',+ ignore_alert: '忽略此类警报/主机',++ // 应用视图+ apps_empty: '尚未有进程归属',+ apps_process: '进程',+ apps_destinations: '主机',+ apps_packets: '数据包',+ apps_volume: '流量',+ apps_top_dest: '主要目的地',+ apps_history_60m: '最近一小时(字节/分钟)',+ alertmsg_NEW_HOSTS: n => `联系了 ${n} 个新主机`,+ settings_autolaunch: '登录时启动',+ settings_autolaunch_hint: '登录时自动启动 Snitch',++ // 新手引导+ onboard_title: '欢迎使用 Snitch',+ onboard_sub: '实时网络流量可视化工具 — 隐私设计。',+ onboard_priv_title: '一切留在本机',+ onboard_priv_body: '流量元数据、警报和历史存储在本地 SQLite 数据库。无账号、无云端、无遥测。',+ onboard_capture_title: '捕获内容',+ onboard_capture_body: '仅数据包头:目标 IP、端口、流量、进程名、DNS 名称和 TLS 服务器名(SNI)。绝不读取载荷。',+ onboard_out_title: '什么会离开本机',+ onboard_out_body: '默认什么都没有。唯一可能的出站调用是您在设置中自行触发的地理定位数据库下载。',+ onboard_go: '明白了',++ // 防火墙与安全+ fw_title: '防火墙与安全',+ fw_lockdown: '锁定模式',+ fw_lockdown_hint: '标记并阻断所有出站流量(局域网保持正常)',+ fw_lockdown_confirm: '启用锁定模式?所有出站流量将被标记并阻断,直到您关闭。',+ fw_lockdown_on: 'LOCKDOWN',+ fw_supported: p => `${p} 上的系统防火墙编排 — 尽力而为,需要权限`,+ fw_unsupported: '此平台不支持原生防火墙 — 规则仅作可视化',+ fw_demo: '演示模式 — 未实际应用',+ fw_kind: '规则类型',+ fw_value: '值',+ fw_kind_ip: 'IP / CIDR',+ fw_kind_domain: '域名',+ fw_kind_process: '进程',+ fw_kind_port: '端口',+ fw_ph_ip: '203.0.113.7 或 185.0.0.0/8',+ fw_ph_domain: 'evil.example',+ fw_ph_process: 'app.exe',+ fw_ph_port: '如 4444',+ fw_rules: '规则',+ fw_empty: '暂无规则 — 添加一条以加固出站流量',+ fw_blocked: n => `已发现 ${n} 次尝试`,+ fw_applied: '已应用到系统防火墙',+ fw_not_applied: '仅可视化(需要权限)',+ fw_enable: '启用',+ fw_disable: '停用',+ fw_delete: '删除规则',+ audit_title: '安全审计',+ audit_refresh: '刷新',+ audit_critical: '严重',+ audit_warning: '警告',+ audit_risky: n => `${n} 个主机位于高风险国家`,+ audit_loading: '加载中…',+ fw_forensics: '取证导出',+ block_action: '阻断',+ proc_kill: '结束进程',+ proc_suspend: '挂起 / 恢复',+ save: '保存',+ ti_title: '威胁情报(可选)',+ ti_hint: '将新主机与信誉服务商比对',+ ti_none: '已禁用',+ ti_key: 'API 密钥',+ ti_key_ph: '您的 API 密钥',+ ti_privacy: '仅对新发现的公网主机向服务商发出调用。默认禁用 — 密钥保存在本地。',+ wh_title: '外部 Webhook(可选)',+ wh_hint: '将警告/严重警报转发到 Discord、Slack 或 Telegram',+ wh_url: 'Webhook URL',+ wh_url_ph: 'https://discord.com/api/webhooks/… 或任意端点',+ wh_chat: 'Chat ID',+ wh_chat_ph: 'chat_id',+ wh_privacy: '启用后,警报消息将以 POST 发送到您的端点。',+ alert_BLOCKED_ATTEMPT: '被阻断的尝试',+ alert_THREAT_HIT: '威胁情报',+ alert_DNS_TUNNEL: 'DNS 隧道',+ alert_CLEARTEXT: '明文通信',+ alert_BASELINE_DEVIATION: '基线偏离',+ alert_LOCKDOWN: '锁定',+ alertmsg_BLOCKED_ATTEMPT: d => `命中防火墙规则:${d.rule?.value || '?'}(${d.rule?.kind || '?'})${d.process ? ` 由 ${d.process}` : ''}`,+ alertmsg_THREAT_HIT: d => `威胁情报:${d.ip} 被标记为 ${d.verdict}(${d.provider}:${d.detail || '已报告'})`,+ alertmsg_DNS_TUNNEL: d => `疑似 DNS 隧道:${d.process} 查询了超长域名`,+ alertmsg_CLEARTEXT: d => `${d.process} 与 ${d.host || d.ip} 的未加密 ${d.proto} 连接`,+ alertmsg_BASELINE_DEVIATION: d => `${d.process} 联系了新国家:${d.country}`,+ alertmsg_LOCKDOWN: () => '锁定模式已启用 — 所有出站流量被阻断',+}