diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..0c89828 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,15 @@ +name: Wydanie WGTools-Extended +on: + push: + tags: + - 'v*' + +jobs: + release: + runs-on: docker-builder + steps: + - uses: actions/checkout@v4 + - name: Utwórz wydanie i załącz pakiet + env: + GITEA_RELEASE_TOKEN: ${{ secrets.GITEA_RELEASE_TOKEN || vars.GITEA_RELEASE_TOKEN }} + run: python3 scripts/gitea_release.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40a8253 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# Python +__pycache__/ +*.py[cod] +*.pyo +.venv/ +venv/ + +# Runtime/state — never commit secrets +*.db +*.db-shm +*.db-wal +*.key +*.conf +*.wgtbackup +*.tar.gz +*.zip +.env +.env.* + +# Editor / OS +.vscode/ +.idea/ +.DS_Store +Thumbs.db + +# Local test output +coverage.xml +.coverage +htmlcov/ +.pytest_cache/ +.test-deps/ +.mypy_cache/ +.ruff_cache/ +*.log diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c55b852 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,761 @@ +# Changelog + +## v0.40.5 + +- Added an Audit shortcut to the top bar; the audit dialog can now open on any page. +- Replaced the redundant sidebar branding with a persistent expand/collapse control, synchronized with Settings. +- Removed the duplicate sidebar update alert while retaining the top-bar update badge. +- Removed the duplicate native/browser theme tooltip. +- Telegram bot now appends navigation and action messages to the chat history rather than overwriting them. +- Added read-only Telegram Audit pages of 20 records with newer/older navigation and a quick `/audit` command. +- Restricted action confirmations to their own prompt to prevent stale-button replay. + +## v0.40.4 + +- Added complete German, French, Italian, Spanish and Polish interface translations alongside English and Russian, with English fallback for future keys. +- Added translated Help documentation in all five new languages, covering the four Help sections and 40 topics per language. +- Added a quick light/dark theme toggle in the top bar, synchronized with Appearance settings. +- Improved update detection and visibility: GitHub release metadata is refreshed every 15 minutes and available updates are surfaced in the top bar. +- Improved Audit records for WireGuard client deletion: events now identify the deleted client and interface rather than displaying only `client`. +- Preserved existing native-install settings during upgrades and excluded the test suite from installed runtime files. +- Extended localization and regression checks without changing WireGuard tunnel or routing behavior. + +## v0.40.0 + +Major feature release focused on stronger administrator authentication and practical network-path diagnostics for VPS and remote WireGuard deployments. + +### MFA and account security + +- Added optional per-user TOTP multi-factor authentication compatible with **Google Authenticator**, 2FAS, Aegis and other standard authenticator apps. +- MFA enrollment uses a QR code with a manual setup-key fallback and generates one-time recovery codes for emergency access. +- Recovery codes are stored only as hashes; regenerating or disabling MFA invalidates the previous recovery set. +- Enabling/disabling MFA invalidates older web sessions for that account, and the MFA challenge is rate/attempt limited. +- Added root CLI emergency recovery: `wgtools disable-mfa [username]` disables MFA for a selected user if the authenticator device and recovery codes are lost. +- MFA-related Audit events never record TOTP secrets, authentication codes or recovery codes. + +### Traceroute, ping and interactive route map + +- Added a dedicated **Server → Route** tab for IPv4 network-path diagnostics to a VPS/server by IP address or hostname. +- Added four-packet ping summary, hop-by-hop traceroute, average RTT, hop-to-hop RTT delta and real partial response-loss information. +- Added an optional interactive OpenStreetMap route map with drag/pan, mouse-wheel and `+`/`−` zoom, automatic route fitting, numbered hops and clickable hop details. +- Public responding hop IPs are geolocated through `ipwho.is` only when map display is enabled; private/local addresses are never sent for geolocation and lookups are cached for 24 hours. +- Route segments and corresponding table hops are colored by RTT growth: green for normal growth, amber for increased latency and red for sharp jumps. +- Unanswered traceroute probes now use a neutral **No reply** state instead of misleading `100% loss`; unanswered trailing hops after the last responding router are hidden from the table. +- If the destination still answers normal ping while final traceroute hops are filtered, WGTools reports that neutrally instead of implying the target is unreachable. +- Increased traceroute probe depth to 30 hops while keeping the visible result compact. + +### UI and reliability + +- Static CSS/JavaScript/image assets now include a per-process revision so browsers cannot keep stale assets after a same-version redeploy/service restart. +- Fixed the MFA login transition after asynchronous password validation. +- Fixed the compact-sidebar update indicator dimensions so it no longer jumps when sidebar collapse is toggled quickly. +- Shortened the pre-update Audit action to **Pre-update backup** / **Резервная копия перед обновлением** because the result column already reports creation status. +- Installer runtime packages now include `iputils-ping` and `traceroute` for the network-path diagnostic. + +## v0.30.0 + +Public release focused on a complete self-hosted WireGuard management workflow and safer day-to-day administration. + +- Added multi-interface WireGuard management with interface-aware Dashboard, Server, Clients and raw configuration views. +- Added normal clients and Site-to-Site peers, reusable groups/policies, client isolation, PSK/key rotation, route presets, expiration and recurring schedules. +- Added managed routing, NAT/MASQUERADE, source policy routing, access rules, live reconciliation and safe raw `wg*.conf` editing with backup/rollback. +- Added durable handshake/RX/TX history, CPU/RAM/network monitoring, 24-hour graphs and quick search. +- Added VPS Relay for NAT-restricted servers, including protected transport, reconnect/reuse and migration recovery. +- Added WGTools Nodes (HUB/Spoke) with protected TCP pairing on the Nodes port, in-tunnel synchronization, explicit published-network allow-lists, overlap protection, return-path NAT and network-change warnings. +- Added complete `.wgtbackup` migration/restore for WGTools state, users, clients/keys, WireGuard configs, Relay metadata and Nodes identity. +- Added built-in Let’s Encrypt HTTPS for domain/public IP, custom HTTPS port, private panel path, automatic renewal and guided certificate-first activation. +- Added local users, SMTP password recovery, Telegram administration, audit history and persistent last-seen information. +- Added safe opt-in GitHub Release updates with pre-update backup and automatic rollback. +- Added the root `wgtools` management CLI with panel controls, detailed WireGuard peer status, start/stop/restart, logs, HTTP rescue, soft uninstall and protected FULL CLEANUP. +- Reworked built-in Help for beginners, refreshed RU/EN copy and screenshots, and added search-engine discovery guidance for the public project while explicitly preventing indexing of the private admin panel. +- Optimized Dashboard, Clients, Server and Nodes loading paths and background snapshots for faster navigation. + +## v0.20.55 + +- WireGuard CLI `Status` now prints the full peer Endpoint instead of shortening the address. +- The one-row-per-peer layout remains; table columns adapt to the actual data and use the available terminal width. + +## v0.20.54 + +- Reworked root CLI WireGuard `Status` into a compact one-row-per-peer table sized for the default 67-column WGTools/MobaXterm console. +- Each peer row now shows name, VPN IP, Online/Offline state, handshake age, endpoint and compact RX/TX; long endpoint/name values are shortened in-place instead of wrapping onto extra lines. +- Interface status is condensed to one summary line above its peer table. + +## v0.20.53 + +- Aligned the root `wgtools` status box and action-menu box to the same terminal width. +- Simplified Panel and WireGuard action labels inside their sections to `Start`, `Stop`, `Restart`, and `Status` without repeating the section name. +- Expanded WireGuard `Status` into a practical peer/client view: per-interface state/address/port/total+online counts plus each peer name, VPN IP, Online/Offline state, handshake age, endpoint, and RX/TX traffic. +- WireGuard status reuses WGTools client metadata and accumulated traffic; for offline peers it falls back to the audit database for the last known handshake/endpoint when available. + +## v0.20.52 + +- Expanded the root `wgtools` CLI WireGuard section with **Status**, **Start**, **Stop**, and **Restart** actions. +- WireGuard status shows each configured interface, runtime state, IPv4 address, listen port, peer count, and most recent handshake age. +- When multiple WireGuard interfaces exist, interactive Start/Stop/Restart asks which interface to control; direct CLI subcommands `status-wg`, `start-wg`, `stop-wg`, and `restart-wg` are also available. +- Renumbered logs/recovery and removal actions while keeping soft uninstall and FULL CLEANUP behavior unchanged. + +## v0.20.51 + +- Tightened the root `wgtools` console menu by removing blank spacer rows above/below each section while keeping the boxed single-column layout. +- Section titles (Panel, WireGuard, Logs & recovery, Removal) are now highlighted in a dark WGTools-style red on compatible terminals; menu actions remain uncolored for readability. + +## v0.20.50 + +- FULL CLEANUP now also removes systemd timer timestamp files (`/var/lib/systemd/timers/stamp-wgtools-*`) so expiry/certificate timer history does not remain after a destructive wipe. + +## v0.20.49 + +- Refined the root `wgtools` console layout for terminal compatibility: retained the boxed design while fixing three misaligned right-border lines caused by multibyte separator characters in padded status rows. +- Reworked the action menu into a single-column layout with one action per line and blank spacing between Panel, WireGuard, Logs & recovery and Removal sections for easier reading in MobaXterm and other SSH terminals. + +## v0.20.48 + +- Reworked the root `wgtools` terminal console into a boxed status/menu layout with grouped Panel, WireGuard, Logs & recovery and Removal actions. +- Added menu action **9. Uninstall WGTools** for removing the application/services/CLI and internal Nodes/local Relay-home transports while intentionally preserving normal WireGuard, `/var/lib/wgtools`, certificates and remote Relay tenants for reinstall/recovery. +- Added menu action **10. FULL CLEANUP** with an explicit `DELETE ALL` confirmation. It wipes WGTools state/backups, Nodes, local Relay Agent/tenant state, all WireGuard interfaces/configs on the host, the WGTools Let's Encrypt certificate and WireGuard packages; remote Relay hosts are never contacted. +- The standalone uninstaller now also stops/removes local `wgtools-relay-home-*` services so uninstalling the panel cannot leave an active home-side Relay transport behind. +- Added `scripts/full-clean.sh` as the reusable destructive cleanup implementation used by the CLI and deploy fallback script. + +## v0.20.47 + +- Server Settings now automatically recalculates the server VPN address to the first usable address when the VPN pool is changed, matching first-run and Add Interface behavior. Manual server-address edits remain respected. +- Localized WireGuard server validation errors in the web UI, including VPN pool/address mismatch, invalid prefixes, reserved addresses, listen-port and MTU validation. + +## v0.20.46 + +- Added direct Nodes VPN-pool publication consistency checking. If a managed WireGuard VPN pool changes while the explicit Nodes allow-list still publishes the previously observed pool, the Nodes page now reports the exact old and current pools instead of relying only on generic discovery drift. +- The direct mismatch check is migration-aware and works with v0.20.44/v0.20.45 state, while deliberate omission of a VPN pool without a stale previously published pool does not trigger a false warning. +- Node Settings now shows only networks that are actually detected at the moment in the “Currently detected” helper; remembered/stale published networks remain in the editable allow-list but are no longer mislabeled as currently detected. + +## v0.20.45 + +- Fixed Nodes network-change detection after a managed WireGuard VPN pool changes (for example `10.0.1.0/24` to `10.0.2.0/24`). Configured WireGuard interfaces are no longer misclassified as directly routed LAN candidates. +- Nodes now stores separate user-confirmed baselines for automatically discovered WireGuard/Site-to-Site networks and directly routed LANs, while retaining a compatibility fallback for v0.20.44 state. +- Server → Nodes now highlights stale publication state with a **Review networks** badge and warning; Node Settings also highlights the published-network field until the administrator reviews and saves the allow-list. + +## v0.20.44 + +- Added authoritative Nodes network-conflict protection. Pairing and publication changes are rejected when a selected network overlaps the Nodes transport network or a network already published by another Node; the one-time join code is not consumed by a conflict. +- Nodes now remembers the locally detected network set when the publication allow-list is saved. If a VPN pool, Site-to-Site network or directly routed LAN later changes, Server → Nodes shows a warning with newly detected and no-longer-detected networks instead of silently rewriting the allow-list. +- Node settings remain explicit: the warning is cleared after the administrator reviews/saves the published networks; remote HUB validation remains authoritative for Spoke changes. +- Replaced the personal test-domain example in the Russian Nodes UI with the neutral documentation endpoint `vpn.example.com`. +- Updated Help to explain unique/non-overlapping Node networks, conflict blocking and network-change warnings. + +## v0.20.43 + +- Reworked built-in HTTPS setup into an explicit guided sequence: certificate first, HTTPS enable second. +- The **Enable built-in HTTPS** checkbox stays disabled until a valid certificate exists for the currently entered domain/public IP; changing the target or using an expired certificate disables activation again. +- **Obtain / renew certificate** now also saves the entered HTTPS settings while HTTPS is disabled, so failed issuance does not discard the form values. +- Added localized Russian/English guidance and client-side handling for missing, expired or mismatched certificates instead of exposing the previous English helper error in the Russian UI. +- Updated Help to document the new certificate → enable → save workflow. + +## v0.20.42 + +- Polished public-release UI copy: removed implementation details, roadmap/test wording and redundant helper text from Nodes, raw config, Mail, Telegram and HTTPS screens. +- Reworked built-in Help as a beginner-friendly user guide with practical examples and plain-language explanations of VPN pools, routes, NAT, Site-to-Site, Nodes, VPS Relay, client policies, backups, HTTPS, Telegram and updates. +- Moved VPS Relay documentation into the Server help section so Help navigation now mirrors the main WGTools structure: Dashboard, Server, Clients and Settings. +- Added a dedicated Nodes guide, including HUB/connected-node roles, published-network allow-lists and a practical two-site example. + +## v0.20.41 + +- Removed the standalone sidebar `<`/`>` collapse control. Sidebar collapse is now an Appearance preference under Settings → General: **Collapse sidebar** (RU: **Свернуть панель**). The existing local browser preference is preserved, so upgrades keep the user's current sidebar state. + +## v0.20.40 + +- Speed up Server page loading with a dedicated lightweight snapshot that skips client metadata, traffic persistence, metrics, diagnostics and backup scans while retaining live WireGuard state, routing and firewall data. +- Fix deploy hanging at `[8/8] Running helper self-test...` after v0.20.39 by explicitly providing the snapshot view JSON on stdin; bound installer helper smoke tests with timeouts so deployment cannot wait forever. + +## 0.20.39 + +- Optimized initial loading and periodic refresh of **Clients** and **Dashboard** with page-specific snapshots. Clients no longer waits for host metrics, diagnostics, route/firewall descriptions or backup scans that are not used by that page. +- Dashboard no longer blocks first paint on full server diagnostics. The peer/traffic/resource snapshot renders first, while the diagnostic strip refreshes independently in the background. +- Interface inventory and the current-page snapshot now load in parallel instead of serially during page startup, reducing navigation latency across Dashboard and Clients. +- Snapshot generation reads client metadata and group definitions once per request instead of reopening the same files for each peer/group calculation. Historical last-seen merge now uses one SQLite session for all offline peers instead of reconnecting per peer. +- Added a lightweight peer-summary snapshot for background Nodes synchronization and WireGuard connection audit so those periodic workers no longer build a full management snapshot and compete with interactive page loads. +- The standalone diagnostics action now runs diagnostics directly rather than first constructing a full snapshot with metrics, client expansion, backups and server-management data. + +## 0.20.38 + +- Speed up Server → Nodes status loading by collecting WireGuard interface inventory and directly-routed LAN candidates once per request instead of repeatedly through topology/local-summary/export calculations. +- Opening the Nodes tab no longer snapshots all local WireGuard clients; client inventory continues to refresh through pairing/background Node synchronization where it is actually needed. +- HUB status rendering reuses one local summary for conflict/topology calculations, removing duplicate privileged helper calls while keeping live tunnel/service state checks. + +## 0.20.37 + +- Added a compact quick search to the read-only client table in **Server → Nodes → Details**, matching the Dashboard/Clients search control. It filters the currently displayed remote clients instantly by the visible row data (name, interface, VPN address, type and handshake text) and includes the same one-click clear control. +- Clarified the HTTPS-port behaviour found during testing: WGTools checks whether the port is locally usable on the WGTools host. A reverse proxy running on another LAN host does not occupy that host-local port; an occupied port reported with a process name (for example `nginx` on TCP 80) is a listener on the WGTools host itself. + +## 0.20.36 + +- Simplified the three configured-Nodes action buttons to **Settings / Synchronize / Disconnect** (RU: **Настройки / Синхронизировать / Отключить**) so all three remain compact single-line actions. The Node Settings modal title remains unchanged. +- HTTPS port detection now also inspects legacy `iptables-save`/`ip6tables-save` DNAT/REDIRECT rules and performs a last-resort TCP probe against the host's own addresses. This catches Nginx Proxy Manager/container published ports that are reachable but invisible to `ss`, Docker/Podman metadata or the native nftables view. + +## 0.20.35 + +- Node published-network text areas now resize vertically only, preventing the Node settings modal from being stretched horizontally. +- Renamed the Nodes action to **Synchronize nodes** / **Синхронизировать узлы** and sized it consistently with the neighbouring two-line Node action buttons. +- HTTPS port checks now detect container-published TCP ports (Docker/Podman) even when userland-proxy is disabled and no host LISTEN socket appears in `ss`. Added an nftables DNAT/redirect fallback, fixing false **Free** reports for ports such as TCP 443 already published by Nginx Proxy Manager. +- HTTPS status now labels a busy port as WGTools only when the listener is actually the WGTools Python/Uvicorn socket, rather than assuming every occupied configured HTTPS port belongs to WGTools. + +## 0.20.34 + +- Nodes publication is now an explicit per-node allow-list. The HUB-enable and Connect-to-HUB dialogs are pre-filled with every currently detected candidate network; remove any line that should not be advertised to the Nodes fabric. +- The publication picker includes WireGuard VPN pools, configured Site-to-Site remote networks (including offline peers), and conservatively detected directly-routed private LANs. The Nodes transport network and common container/virtual bridge routes are excluded from LAN auto-detection. +- Newly discovered networks after pairing are shown as available in Node settings but are not silently published. Add them explicitly when they should become reachable from other Nodes. +- Existing Nodes created before v0.20.34 keep their previous automatic-export behaviour until Node settings are saved, avoiding a surprise routing change during upgrade. +- Fixed Nodes modal operation-status spacing so progress/error messages no longer crowd or overlap the helper text below the network field. + +## 0.20.33 + +- Fixed Nodes HUB control service on panels using built-in HTTPS with a private access path. The private-path deployment mounts the WGTools FastAPI app below an outer application; mounted sub-application startup hooks were not being run, so background services (including the Nodes TCP pairing listener) could remain stopped even though the web UI and `wgnode0` worked. +- The outer private-path application now starts the same guarded background workers as normal HTTP mode: metrics sampling, update checks, WireGuard connection audit, Nodes sync and the Nodes TCP control service. +- Enabling HUB mode explicitly ensures the Node-control worker is alive, and the control loop now survives transient database/certificate/socket errors instead of silently dying. This makes HUB/Spoke role changes recover without requiring a full WGTools process restart. + +## 0.20.32 + +- Nodes now automatically publishes every configured Site-to-Site peer remote network in addition to each local WireGuard VPN pool. Publication is configuration-driven rather than handshake-driven, so an offline Site-to-Site peer (for example `10.10.5.0/24`) remains in the topology and becomes reachable again without route churn when it reconnects. +- Adding, editing or deleting a WGTools client, applying raw WireGuard config, or changing/creating/deleting a WireGuard interface now reconciles the Nodes tunnel automatically. New Site-to-Site networks therefore propagate on the next Nodes sync without a manual **Sync now** step. +- Added automatic return-path NAT for ordinary WireGuard clients of remote Nodes. A remote Node VPN pool (for example `10.0.7.0/24`) is MASQUERADEd only when accessing a network published by the receiving Node, so LAN routers do not need routes back to every remote client pool. +- Remote Site-to-Site/custom LAN sources are intentionally not NATed by the client return-path rule; routed inter-site traffic keeps its original source address. The new rules live in a separately managed `WGTOOLS-NODES-CLIENT-NAT` chain and are rebuilt with `wgnode0` to avoid stale entries. +- Node details now identify automatically discovered Site-to-Site exports as **Site-to-site network**. + +## 0.20.31 + +- Fixed Node-originated access to networks published by a WGTools node. Traffic from the internal Nodes transport network (for example `10.254.240.0/24`) is now automatically MASQUERADEd only when it exits toward a network published by the local WGTools instance, so LAN routers do not need a manual return route to `wgnode0`. +- The new NAT is source-scoped to the Nodes transport network and destination-scoped to local published networks. WGTools keeps it in the dedicated `WGTOOLS-NODES-NAT` chain, rebuilt with `wgnode0` so removed exports cannot leave stale rules behind. Ordinary LAN-to-LAN/site-to-site traffic keeps its original source address and is not NATed by this fix. +- This resolves the validated v0.20.30 case where the Node tunnel and routes were healthy, but ping from a remote Node transport IP reached the destination LAN and the reply could not return. + +## 0.20.30 + +- Reworked **Server → Nodes** pairing architecture from the v0.20.29 prototype. Nodes no longer use the WGTools web panel URL, HTTP/HTTPS scheme, web port, certificate or private panel path for pairing or steady-state synchronization. +- HUB now uses the same numeric Nodes port for two independent transports: **UDP** for WireGuard `wgnode0` and a dedicated pinned-TLS **TCP** control socket for initial pairing. If the HUB is behind NAT, forward that port for both TCP and UDP. +- Spoke setup is reduced to **Node name + HUB `host:port` + one-time connection code + additional networks**. The HUB hostname entered by the Spoke is also used as the WireGuard endpoint, so HUB setup no longer needs a separate public hostname field. +- One-time connection codes now embed the HUB control-certificate SHA-256 fingerprint. The Spoke pins that identity before sending the one-time secret, avoiding any dependency on the web-panel TLS certificate. +- After `wgnode0` is established, topology/status/version/read-only-client synchronization moves to the HUB transport address inside the WireGuard tunnel. Normal sync and leave requests are accepted only from the paired Node transport IP. +- The optional **Panel URL** remains only in Node settings as informational metadata for the **Open panel** button; changing HTTP/HTTPS, web port, hostname, certificate or private path no longer affects Nodes. +- Preserved the HUB control identity inside SQLite so full WGTools `.wgtbackup` migration/restore keeps existing Spoke trust. Failed local tunnel creation also revokes the just-created HUB peer through the pinned pairing channel when possible. +- Fixed the Nodes connection-code UI on dark theme and added a Clipboard API fallback so **Copy** works on ordinary HTTP/LAN panels where the modern clipboard API may be unavailable. + +## 0.20.29 + +- Added the first test version of **Server → Nodes**. Any WGTools installation can become a HUB; other WGTools panels pair to it with a one-time 15-minute code and establish a dedicated hidden `wgnode0` WireGuard transport. +- WGTools Nodes automatically publishes the VPN pools of local WGTools-managed interfaces and can additionally publish explicitly configured routed LAN/other IPv4 networks. The HUB distributes the topology and WGTools adds the corresponding routes, including routes in local numeric policy-routing tables used by WGTools interfaces. +- Added Hub-and-Spoke routing between connected panels, automatic conflict detection for overlapping published networks, per-node tunnel status/version/network/client counts, a read-only remote-client details dialog and an optional **Open panel** link. Remote private keys, PSKs, users and client-management actions are never shared. +- The initial Nodes test deliberately uses a simple trust model: all non-conflicting published networks are reachable by all connected nodes. Granular inter-node ACLs and remote administration are not part of this version. +- Node pairing/synchronization uses the configured HUB panel HTTP/HTTPS URL while WireGuard data traffic uses the separate `wgnode0` tunnel. A spoke now removes its HUB peer on clean disconnect; failed pairing/config changes roll back instead of leaving ghost topology state. +- Reserved `wgnode*` interfaces as internal WGTools transports so they do not appear as normal server interfaces. Normal WGTools uninstall removes the internal Node tunnel while preserving user WireGuard interfaces. +- Fixed the `wgtools` terminal console to discover and display the actual normal WireGuard interfaces instead of assuming stale `wg0`. A server with only `wg1` now shows/restarts `wg1`; internal `wgrly*`/`wgnode*` transports remain separate/hidden. + +## 0.20.28 + +- Fixed the last race during live built-in HTTPS changes. After saving a new HTTPS port or private panel path, the browser now waits for the restarted WGTools process to become healthy at the exact new HTTPS URL before navigating, instead of relying on a fixed delay that could briefly hit the old route (404) or a half-open TLS listener (`PR_END_OF_FILE_ERROR`). +- `/healthz` now exposes a per-process non-sensitive instance token and CORS only on that readiness endpoint, allowing a page on the old HTTPS port to verify that a genuinely new WGTools process is ready on the new port/path. The rest of the hidden-path surface remains unchanged. + +## 0.20.27 + +- Added a compact `wgtools` terminal console for remote administration. It shows WGTools/WireGuard/Telegram/timer states, the exact current panel URL and private HTTPS path, certificate expiry, and provides panel start/stop/restart, WireGuard restart, log viewing and an HTTP rescue action. +- Settings → HTTPS now has the same compact panel-address action used by client creation, so the current browser hostname/IP can be inserted without typing it manually. +- Hardened live HTTPS port/path changes: the service restart is delayed long enough for the API response to flush, the browser uses a keepalive request, and the UI reconnects explicitly to the requested HTTPS scheme/port/path instead of remaining on the old origin if the socket is interrupted during the switch. A guarded systemd hand-off verifies the new local health endpoint and automatically restores the previous web settings if WGTools fails to start after the change. +- The installer now exposes `wgtools` in `/usr/local/bin`; update validation/rollback and uninstall handling include the console command. + +## 0.20.26 + +- Built-in HTTPS can now listen on a user-selected TCP port instead of being fixed to `443`; port `80` remains reserved for Let’s Encrypt HTTP-01 validation. +- Added a required user-defined **Panel access path** for built-in HTTPS, for example `/MyPrivateWGToolsPath/`. When HTTPS is enabled, the WGTools application, API and static files exist only below this prefix; direct requests to `/`, `/login`, `/api`, `/static`, etc. return `404`. +- The configured path is preserved across WGTools restarts/updates and can be changed later from Settings → HTTPS. Authentication remains mandatory; the path is an additional scanner-noise reduction layer, not a replacement for credentials. +- Updated redirects, authentication flows, static assets and browser API requests so every WGTools function works correctly below the HTTPS path prefix. +- HTTPS port checks now validate TCP `80` plus the selected panel port and continue to leave unrelated listeners untouched. + +## 0.20.25 + +- Reorganized the first WireGuard server setup grid so **Interface / Listen port** are paired on the first row and **Display name / MTU** on the second, reducing unused horizontal space. +- Client creation keeps the server address field empty but adds a compact globe action that inserts the current panel hostname/IP from the browser URL; endpoint history/manual entry remain available. +- Added **Settings → HTTPS** with direct Uvicorn TLS on TCP 443 — no bundled Nginx/reverse proxy. WGTools can request Let’s Encrypt certificates for a domain or public IP using Certbot standalone validation. +- Added local TCP 80/443 conflict checks. WGTools never stops or overwrites an unrelated listener; TCP 80 must be reachable from the Internet for ACME issuance/renewal. +- Added automatic certificate renewal through a dedicated systemd timer and reload hook. IP certificates use Let’s Encrypt’s required short-lived profile. +- The HTTPS tab shows certificate expiry, Certbot/renewal status and copyable `fullchain.pem` / `privkey.pem` paths. Built-in HTTPS can be disabled to return WGTools to HTTP when an external reverse proxy is preferred. +- Updated install/update/rollback/uninstall plumbing so HTTPS state survives WGTools application updates while Let’s Encrypt certificate files remain independent under `/etc/letsencrypt`. + +## 0.20.24 + +- Reorganized **Settings → Mail** into a clearer two-column flow: SMTP server + encryption, port + sender name, SMTP login + password, with the test recipient kept as a single half-width field below. +- The sender e-mail is now taken from the SMTP login in the web UI, removing the duplicate sender-address field. The backend keeps compatibility with previously saved sender addresses. +- Changing SMTP encryption now automatically proposes the conventional port: STARTTLS → 587, TLS/SSL → 465, no encryption → 25. Custom ports can still be entered afterward. + +## 0.20.23 + +- Fixed the password-recovery form in Firefox: after a reset code was successfully mailed, the UI now advances to the code/new-password step instead of showing `event.currentTarget is null`. +- Password-reset and SMTP test emails now use the language selected in WGTools instead of combining Russian and English in one message. + +## 0.20.22 + +- Added **Settings → Mail** with SMTP server/port, STARTTLS/TLS/plain modes, optional SMTP authentication, sender identity, masked saved-password handling and test delivery. Mail can be enabled independently and the saved SMTP password can be removed without exposing it back to the browser. +- Added optional per-user **E-mail** addresses, including first-user setup, user creation and later editing. E-mail addresses are unique when present and are included in the full SQLite-backed `.wgtbackup`. +- Added self-service **Forgot password?** recovery on the login screen when Mail is enabled: users request a one-time 6-digit code by username or e-mail, then set a new password. Codes are salted PBKDF2 hashes, expire after 15 minutes, are one-time use, allow five attempts and are rate-limited. +- Password-recovery requests always return the same public response whether an account/e-mail exists or not, preventing username/e-mail enumeration. +- Added **Send reset** to Settings → Users so an authenticated administrator can send a recovery code to a user's registered e-mail. +- Password changes and successful recovery increment a per-user session version, invalidating older web sessions for that user. Sessions created before this feature are upgraded safely only until the account has changed credentials. +- Extended Audit with password-recovery, mail-settings/test and user-email/reset events. Failed logins now include the connecting IP in the Audit object; reset codes, SMTP passwords and other secrets are never logged. +- Password-reset rate counters are updated transactionally, and rate-limited public requests are not allowed to flood the Audit journal. + +## 0.20.21 + +- Polished the Telegram **Server** submenu: removed the mixed emoji/glyph icons from Start/Restart/Stop and kept the controls as plain localized text. +- Applied native Telegram inline-button styles where supported: **Start** uses `success` (green), **Restart** uses `primary` (blue), and **Stop** uses `danger` (red). The **Menu** button remains in the normal Telegram style. + +## 0.20.20 + +- Simplified the Telegram main menu: the top row is now split into **Interface** and **Server**, while WireGuard Start/Restart/Stop controls move into the dedicated Server submenu instead of occupying a permanent bottom row. +- Replaced the old button-only emoji controls with compact text actions (`▶ Start`, `↻ Restart`, `■ Stop`; localized in Russian) so the server controls are immediately understandable. +- Server control confirmations, success messages and errors now return to the Server submenu rather than unexpectedly jumping back to the main menu, keeping Telegram navigation consistently step-based. + +## 0.20.19 + +- Reduced the compact sidebar rail from 70 px to 56 px so icon-only navigation gives the content area more room on small displays. +- Replaced the previous collapse/expand glyph with a simple `<` / `>` control: `<` collapses the expanded sidebar and `>` expands the compact rail. + +## 0.20.18 + +- Reworked the main sidebar with clean line icons for Dashboard, Server, Clients and Settings. +- Added a persistent manual compact mode: the sidebar collapses to an icon-only rail and the content area expands; the choice is stored in the browser. On narrow screens the compact rail is used automatically so navigation remains available without consuming the full width. +- Replaced the old two-line footer version label with a compact WGTools logo + `WGTools - vX.Y.Z` GitHub link. The update-available notice also adapts to the compact sidebar. + +## 0.20.17 + +- Fixed Dashboard **Traffic → Reset**. The API route and privileged helper already supported `traffic_reset`, but the web application's helper-action allowlist did not, so the request was rejected before reaching the helper with `Unsupported helper action: traffic_reset`. +- Added a regression test that keeps the web helper wrapper and privileged helper action lists aligned for traffic reset. + +## 0.20.16 + +- Consolidated web client-config Audit events: opening the combined config + QR modal now produces one `client.config_viewed` row instead of separate config and QR rows. Existing historical `client.qr_viewed` rows remain readable. +- Telegram **Configs → client** re-issue now records the same `client.config_viewed` Audit action with Telegram actor identity, interface/client context and filename after both `.conf` and QR are delivered. No config, key or QR contents are stored. +- Telegram config re-issue failures now use the existing redacted failure Audit path while keeping the user inside the Configs flow. + +## 0.20.15 + +- Added a small breathing gap below the client-editor operation/status banner so progress and result messages no longer visually merge with the fixed modal action bar. +- The spacing is applied only while the status banner is visible, so the normal client editor layout is unchanged when there is no operation message. + +## 0.20.14 + +- Fixed client key rotation while the client is currently connected. Rotating credentials already replaces the old runtime WireGuard peer immediately; the UI now treats that disconnect as the expected result instead of turning a post-rotation refresh failure into a false `NetworkError`. +- The client editor reports rotation success before refreshing live state, and the follow-up snapshot refresh is best-effort so it cannot overwrite a completed rotation. +- Rotation confirmation/status text now explicitly says that an active client session will be forcibly disconnected and that the old config becomes invalid. +- Added a clear recovery message for the special case where the WGTools panel itself is being accessed through the client whose credentials are being rotated. + +## 0.20.13 + +- Added per-client VPN peer isolation for WGTools-managed normal clients. Isolation is symmetric inside the WireGuard address pool and leaves server/LAN/Internet/Site-to-site access to the existing policies. +- Replaced separate PSK and client key-pair rotation controls with one **Rotate keys** action. It always regenerates PrivateKey/PublicKey and also rotates PSK when PSK is enabled. +- Preserved client address, routes, group/policies, schedule/expiration, isolation, durable last-seen and traffic counters across key rotation. +- Added Audit event `client.credentials_rotated` without storing key material. + + +## 0.20.12 + +- Added optional per-interface **MTU** to first server setup, Add WireGuard Interface and Server Settings. Empty/0 keeps wg-quick automatic MTU; explicit values are validated and written as the standard `MTU = ...` interface directive. +- Added safe **client key-pair rotation** for WGTools-managed clients. A new PrivateKey/PublicKey replaces only that peer while preserving its VPN address, routes, policies, group, PSK, expiration/schedule settings, durable last-seen state and accumulated traffic. +- Client key rotation is transactional with the existing WireGuard config backup/rollback path. The old client config becomes invalid immediately and WGTools requires a newly issued `.conf`/QR. +- Added Audit event `client.keys_rotated` without storing key material. +- Added regression tests for MTU parsing/validation/config generation and managed-client key rotation state migration. + +## 0.20.11 + +- Reworked Telegram Bot navigation so each action returns to its logical parent screen instead of unexpectedly jumping to the main menu. +- Config/QR re-issue now retires the old picker, sends the `.conf` and QR, then places a fresh client-config picker **below** the files; the next actionable buttons are therefore always at the bottom of the conversation. +- Legacy/unavailable config selections stay inside the Configs screen, including useful error text, instead of replacing the flow with the main menu. +- Delete confirmation **No** now returns one step to the delete-client list; successful deletion and deletion errors also return to the refreshed delete list, with the removed client gone. +- Stale interface/group selections now keep the user in their respective picker with a useful message. Existing create flow still finishes with a fresh main menu below generated client files. +- Added Telegram navigation regression tests covering config delivery order, the existing create-flow bottom menu, legacy config selection and delete-flow parent navigation. +- Cyrillic client names now produce readable portable config filenames via transliteration instead of falling back to `wireguard-client.conf`; web and Telegram re-issue use the same generated filename. + +## 0.20.10 + +- Reworked the automatic configuration-backup card so its stored-count / last-backup block sits below the retention control at full card width; the timestamp is kept on one line instead of wrapping in the narrow right-hand column. +- Audit now refreshes automatically while its modal is open, using the saved **Settings → General → Status refresh interval** value (2–60 seconds). The existing background prefetch remains, and manual Refresh still forces an immediate fresh request. + +## 0.20.9 + +- Prefetch the Audit journal in the background when Settings loads, so opening **Audit** normally renders the already-fetched rows immediately instead of showing a visible loading pause first. Manual Refresh still requests fresh data. +- Shortened the automatic-backup status badge to **Enabled / Включено** and forced the pill to stay on one line in the compact backup card. + +## 0.20.8 + +- Matched the height of the two **Settings → Backups** cards on wide screens so the automatic configuration-backup card now aligns with the full migration/restore card instead of ending early. +- The **Save** action in the configuration-backup card stays anchored at the bottom of the equal-height card; narrow-screen stacked layout remains unchanged. + +## 0.20.7 + +- Reorganized Settings into persistent tabs matching the Server page: General, Backups, Telegram, Users and About. The Audit button remains a separate top-level tool. +- Split backup controls into two independent cards shown side by side on wide screens: automatic configuration backups and full migration/restore backups; they stack vertically on narrower displays. +- Settings tabs remember the last section for the browser session and support direct URL hashes such as `/settings#about`; the update notification therefore still opens About directly. + +## 0.20.6 + +- Added durable lifetime WireGuard traffic accounting. Per-client RX/TX and the Dashboard Traffic total now survive WireGuard interface restarts, WGTools restarts and host reboots instead of following resettable runtime counters from `wg show`. +- The Dashboard Traffic card now includes traffic from clients that were later deleted, so the interface total represents all traffic since the last manual reset. +- Added a compact gray **Reset** button to the Traffic card. Resetting establishes the current WireGuard runtime counters as a new baseline and starts both the interface and current client totals from zero without restarting WireGuard. +- Traffic resets are recorded in Audit. Existing historical bytes that were already lost before upgrading to v0.20.6 cannot be reconstructed; the durable counter starts from the runtime values available at first v0.20.6 sampling. +- Added regression tests for accumulation across runtime counter resets, stopped interfaces, deleted clients and manual reset baselines. + +## 0.20.5 + +- Fixed a regression in the Audit renderer introduced by the v0.20.4 layout change: the row color tone is now calculated for each audit item before rendering, eliminating the `tone is not defined` error and restoring all Audit rows. +- Kept the wider desktop Audit dialog, compact `ТГ` / `TG` Telegram actor labels, fixed responsive columns and existing search behavior from v0.20.4. + +## 0.20.4 + +- Improved the Audit modal layout to avoid unnecessary horizontal scrolling on normal desktop widths: the dialog is slightly wider, the table uses a fixed responsive column layout, and long cell content is clipped cleanly instead of expanding the table. +- Compact Telegram actors are now displayed as `ТГ · @username · ID ...` in Russian and `TG · @username · ID ...` in English. The stored audit actor remains unchanged, preserving existing history and search compatibility; hovering the actor badge still exposes the original full value. +- Audit quick search matches both the original stored Telegram actor and the compact localized display form. + +## 0.20.3 + +- Preserved each WireGuard peer's last successful handshake independently from the current runtime interface state. After a host/interface restart, Clients and Dashboard now show the real historical last connection instead of `Never`; `Never` is reserved for peers that truly never connected. +- Fixed durable last-seen pruning: a configured peer with runtime handshake `0` no longer loses its saved connection state. Existing installations affected by the old behavior can recover a recent last-seen value once from the 30-day Audit connection history, then keep it in durable state outside Audit retention. +- Completed the update Audit lifecycle. Background updates now record the pre-update full `.wgtbackup`, successful completion, useful update errors, successful rollback, and rollback failure without storing secrets. +- Added regression tests for last-seen persistence and migration from existing Audit connection history. + +## 0.20.2 + +- Renamed **Settings → Logs / Audit log** to the clearer **Audit / Аудит** label while keeping the existing searchable audit modal and retention rules. +- Added Telegram Bot state-change auditing to the same SQLite journal used by the web panel. Telegram audit actors always include the numeric Telegram user ID and include `@username` when Telegram provides it. +- Telegram client creation/deletion and WireGuard Start/Stop/Restart now record success events with interface/client context without storing generated client configuration, keys or PSKs. +- Added audit coverage for Telegram-side persistent endpoint changes, useful failed administrative operations and denied state-changing attempts; menu navigation, status/client-list views and config re-issue remain intentionally silent. +- Hardened audit text redaction so token/key-like values in error text are scrubbed before storage in addition to the existing secret-field redaction. +- Added focused regression tests proving Telegram client create/delete produces the expected actor/action events, read-only navigation stays quiet, denied mutation is logged and secret-like failure text is redacted. +- Updated built-in help and EN/RU README documentation for Audit and Telegram auditing. +- Reorganized the README uninstall section into three clear paths: the safe WGTools-only uninstall remains visible, while destructive full WGTools+WireGuard and full dedicated VPS Relay cleanup commands are placed under collapsible spoilers. + +## 0.20.1 + +- Local hotfix build prepared for testing; not published to GitHub. +- Fixed the sidebar update notice so a discovered newer release persists while navigating between Dashboard, Server, Clients and Settings, then disappears after a successful update or when WGTools is already current. +- Allowed the `update_notice` helper action in the web helper allow-list so `/api/update/notice` can return the cached release state instead of falling back to “no update”. +- Made the update flow explicitly show that WGTools creates an automatic full `.wgtbackup` before installing an update. The existing pre-update full backup and application rollback archive are preserved. +- Reduced false Telegram Bot test failures: if the direct `getMe` check times out with a TLS/timeout-style network error while the running bot has contacted Telegram recently, Settings reports the bot as working. +- Added a SQLite-backed audit log for panel activity with timestamp, username, action, object and result. Secret-bearing fields such as passwords, private keys, PSKs, Telegram tokens, `control_token` and SSH credentials are redacted. +- Added **Settings → Logs / Audit log** as a dedicated modal with quick search, localized event labels, color-coded action/result accents and a manual refresh button. +- Audit events are retained for 30 days with a 10,000-row safety cap. +- Added WireGuard client connection history to the audit log: WGTools records the client name, time and endpoint IP on the first active connection after a meaningful offline gap or when the endpoint IP changes, without logging every routine handshake or writing private configuration or keys. + +## 0.20.0 + +- Changed first-run WireGuard defaults to `wg0 = 10.0.0.0/24` with server address `10.0.0.1/24`; the next interface now naturally continues as `wg1 = 10.0.1.0/24`. +- VPS preflight now reports both the number of saved Relay tenants and the number currently active by recent protected-transport handshake, avoiding the ambiguous old “N connections” label. +- Made VPS working/error/success message spacing symmetrical: the top and bottom gaps now use the same compact spacing. +- Rewrote the English and Russian README for the current feature set, explicitly documenting Debian and Ubuntu support, multi-interface management, client groups/policies, schedules/expiration, VPS Relay behavior, backups, periodic release discovery and safe updates. +- Replaced public README screenshots with the current UI and moved all screenshots under collapsible `
` sections. +- Added explicit destructive full-cleanup commands for both a dedicated WGTools host and a VPS Relay host, including optional WireGuard package removal. +- Updated privacy/security documentation for the six-hour cached background GitHub Release metadata check; application updates remain strictly opt-in. + +## 0.19.15 + +- Fixed VPS wizard status spacing at the actual root cause: the shared JavaScript status helper no longer overwrites an element's complete `className`, so structural classes such as `vps-operation-status` and `migration-status` survive while working/error/success states change. +- VPS working/error/success messages now keep a deliberate gap below the Home ↔ VPS transport-port hint and a compact gap before the compatibility card. +- Added **Display name** to the first WireGuard server creation form (`wg0` on a clean install), matching the friendly-name capability already available when adding later interfaces. + +## 0.19.14 + +- Hid WGTools internal Relay transport interfaces (`wgrly*`) from the global WireGuard interface switcher and Server interface manager; they are implementation details of Home ↔ VPS Relay transport, not user-managed WireGuard servers. +- A stale browser cookie that previously selected a `wgrly*` interface now falls back automatically to the normal configured interface (typically `wg0`) instead of opening an empty “Not configured” Server view. +- Reserved the `wgrly*` namespace so user-facing interface create/rename/delete/helper actions cannot accidentally target or create a name that conflicts with Relay transport. +- Kept the internal transport visible only where it is useful: an installed VPS row now shows its `wgrly*` transport name alongside the published WireGuard interface and Home ↔ VPS transport addresses. + +## 0.19.13 + +- Fixed client create/update/delete when another WGTools-managed policy is currently blocked: the live iptables parser now accepts the canonical form emitted by `iptables -S`, including an omitted `-d 0.0.0.0/0` and the default `--reject-with icmp-port-unreachable` added to REJECT rules. +- Runtime policy reconciliation now removes the exact live WGTools-tagged rule returned by iptables before rebuilding the desired policy set, so stale/duplicate managed rules are healed without blocking further client changes. +- Kept strict validation for unexpected WGTools-tagged firewall shapes; unknown extra matches/options are still rejected instead of being silently rewritten. + +## 0.19.12 + +- Refined the VPS wizard operation-status spacing so working/success/error messages sit cleanly below the Home ↔ VPS transport-port hint with a tighter, balanced gap before the compatibility card. +- Expanded built-in RU/EN help with the current multi-interface, client policy/group, VPS Relay, Relay reconnect/disaster-recovery, backup and update workflows; moved raw-config guidance to Server → Config. +- Made full migration-backup coverage of VPS Relay state explicit: the SQLite backup carries controller/tenant identity, management token and home transport key used to reconnect to a preserved remote tenant; the backup manifest now reports saved Relay records. +- Added periodic update discovery: WGTools refreshes stable GitHub Release metadata in the background with a six-hour cache. +- Added a prominent sidebar update notice with the available version; clicking it opens Settings → About, where cached release details and the existing safe one-click updater are shown. + +## 0.19.11 + +- Fixed reconnecting a preserved VPS Relay when the home WireGuard ListenPort differs from the value stored in the remote tenant: WGTools now synchronizes the existing tenant to the current port instead of rejecting it or creating a new tenant. +- Reconnect still reuses the original Relay tenant, UDP Relay/transport ports, controller identity and client `relay_vps_id`. +- Moved VPS operation/error messages back directly below the public endpoint fields, with extra spacing so they no longer cover the Home ↔ VPS transport-port hint. + +## 0.19.10 + +- Fixed the VPS Relay install/reconnect button crash caused by the undefined `vpsCredentials` JavaScript reference. +- **Remove VPS** now detaches only the local transport and keeps a hidden local Relay identity record instead of deleting it, so adding the same VPS again reconnects to the same tenant. +- VPS preflight now recognizes an existing tenant created by the same WGTools controller and reuses its original Relay/transport UDP ports instead of allocating a second connection. +- Added recovery for VPS entries already removed by v0.19.9: WGTools can reclaim the preserved remote tenant over SSH, rotate only the home-side transport peer key when necessary, and reuse an orphaned client `relay_vps_id` so existing Relay clients reconnect without being recreated. +- The VPS wizard clearly reports when an existing Relay will be reconnected and changes the action to **Reconnect Relay / Подключить Relay**. +- Moved VPS operation/error messages below the compatibility result card for a cleaner wizard layout. + +## 0.19.9 + +- Added **Remove VPS** for installed Relay entries. The action detaches the VPS from the current WGTools instance, stops/removes only the local home-side Relay transport, and removes the local database record. +- Removing an installed VPS never connects to or deletes anything on the remote VPS: the Relay Agent, tenant, transport configuration, keys and management token are intentionally preserved for disaster recovery. +- Added an explicit confirmation warning that clients using the removed Relay will stop connecting through it until they are reconfigured or WGTools state is restored. +- Restoring a WGTools migration backup now reconciles installed Relay records from the restored SQLite state and recreates a missing home-side transport using the original tenant identity/keys, allowing WGTools to reconnect to the preserved VPS Relay instead of provisioning a new tenant. + +## 0.19.8 + +- Simplified VPS onboarding: after a successful SSH/preflight check the same wizard proceeds directly to Relay installation; the old visible “Save candidate” step is no longer part of the normal flow. +- Added the first real client-over-Relay path. When at least one installed Relay exists for the selected WireGuard interface, managed clients can choose **Directly to WGTools** or **VPS Relay** in the Configuration tab. +- Relay Endpoint is generated automatically from the selected VPS domain/IP and Relay UDP port; manual server endpoint fields become read-only while Relay mode is selected. +- Generated client configs/QR codes resolve the current Relay endpoint from WGTools state so the client profile is pointed at the VPS without changing the real server WireGuard peer. +- Relay controls stay completely hidden from client editing when no installed Relay exists for the active WireGuard interface. +- Clients using Relay show a compact Relay marker/name in the Clients list and are searchable by Relay endpoint/name. +- This stage intentionally keeps Internet egress on the home WGTools server; VPS Internet egress will be layered on only after the transparent client → VPS → Home path is validated on the test server. + +## 0.19.7 + +- Added the first installable WGTools VPS Relay Agent stage. +- Added a protected per-controller WireGuard transport tunnel between WGTools and VPS. +- Relay Agent is multi-tenant: one VPS can host independent isolated connections for multiple WGTools controllers. +- Existing Relay tenants are never overwritten when another WGTools connects to the same VPS; free UDP ports are selected automatically. +- Added Relay health checks over the protected management tunnel. +- VPS SSH credentials remain ephemeral and are requested again only for installation. +- Added SSH host-key pinning between preflight and installation. +- Test deploy package supports an explicit target-host override for isolated Relay development. + +## 0.19.6 + +- Reworked **Server** into compact tabs: Interface, Routing, VPS and Config. +- Moved the raw WireGuard editor from Settings to Server -> Config. +- Added the first safe VPS Relay stage: a real read-only SSH preflight for Debian/Ubuntu compatible VPS hosts. +- VPS preflight checks SSH access, sudo/root privileges, apt/systemd/network tooling, architecture and free Relay/transport UDP ports. +- Passwords and pasted SSH private keys are used only for the current preflight request and are never stored. +- Successful checks can be saved as non-secret VPS candidates in the WGTools database; remote installation is intentionally not enabled yet. +- VPS Relay client options remain absent until a Relay is actually installed/configured in a later test build. + +## v0.19.5 + +- Reworked Telegram Bot navigation so completed actions and confirmations always retire the old inline keyboard and return to the appropriate higher-level/main menu state. +- Fixed Telegram client deletion confirmation: after Yes the confirmation buttons are removed immediately, the peer is deleted once, and the same message returns to the main menu; repeated queued taps are handled safely. +- Hardened Telegram Start/Stop/Restart, config delivery, interface selection and client-create flows against stale inline buttons and duplicate callback presses. +- Telegram client/status lists now reflect schedule/expiration administrative blocks, and Telegram-created managed clients use PSK by default to match the web UI. +- Replaced the Clients per-column Filters UI with the same compact quick search used on Dashboard, including one-click clear. Search covers name, group, VPN address, remote networks, type, endpoint, Keepalive and current status. + +## v0.19.4 + +- Shortened the client table handshake column label to `Handshake` in both languages. +- Rebalanced client table column widths so compact action buttons stay inside the card in Russian UI. +- Added a one-click clear button to the Dashboard quick peer search field. + +## v0.19.3 + +- Added a compact quick-search field to the Dashboard Active peers card. Search matches peer name, VPN address, type, endpoint and status without adding the full Clients filter UI to the Dashboard. +- Replaced the long Delete action in the Clients table with a compact danger “−” button with tooltip/accessible label so all client actions stay on one row on normal desktop widths. +- Refined desktop client-table column widths and action spacing to avoid unnecessary wrapping while preserving horizontal scrolling on genuinely narrow screens. + +## v0.19.2 + +- Enabled PSK by default for newly created WGTools-managed clients while preserving the existing setting when editing or duplicating a client. +- Added per-column client filters with a compact toggle/reset UI for name, group, VPN address, remote networks, Keepalive and status. +- Custom expiration now pre-fills the browser's current local date/time when the date-time field is first opened. +- Reworked the client access timer to evaluate on exact minute boundaries instead of a relative one-minute interval. +- Added recurring per-client access schedules with selectable weekdays and start/end times. Outside the allowed window WGTools disables the peer without changing the client config, then restores the same peer automatically when access is allowed again. +- Access schedules use the WireGuard server's local time and support overnight windows such as 22:00–06:00. +- Scheduled/expired blocks now override the online indicator so the Clients/Dashboard status does not report an administratively blocked peer as online. +- Refined security checkboxes so the control stays left-aligned with its label instead of being stretched by the two-column form grid. +- Stabilized the Clients table/filter layout on desktop: opening and closing filters no longer leaves a stray horizontal scrollbar, while narrower screens keep normal horizontal scrolling. + +## v0.19.1 + +- Fixed tabbed-client validation: browser-native hidden-field validation no longer blocks the WGTools validator, so Save now opens the exact tab containing the missing required field and focuses it. +- Restored the post-create flow: after a managed client is created successfully, WGTools immediately opens its generated `.conf` and QR code. +- Added an expiration action for temporary normal clients. By default an expired client is deleted as before; administrators can instead keep the client and automatically disable its WireGuard access. +- Kept expired-but-disabled clients visible in the Clients list with an explicit status marker. Editing the client to a future/no-expiration lifetime and saving re-enables the same peer and existing client configuration. + +## v0.19.0 + +- Reworked the client editor into compact tabs: Basic, Policies, Configuration and Security. Validation now opens the tab containing the field that needs attention. +- Clarified client-group UX by separating **Server access policy** from the **Client configuration template**. +- Grouped clients now inherit Routes/AllowedIPs, DNS and Keepalive through an explicit configuration-source mode; inherited fields are read-only until **Override group template** is enabled. +- Existing inherited clients keep their saved configuration after a group-template change and show an explicit action to apply the current template before issuing a new config/QR. +- Added optional WireGuard `PresharedKey` support for WGTools-managed clients. PSK is generated securely, written to the server peer, stored in protected client metadata, and included in generated configs/QR codes. +- Added safe PSK rotation for existing managed clients with an explicit warning that the old installed client config stops working until a new config/QR is issued. +- Added temporary client lifetimes: no expiration, 1 hour, 3 hours, 6 hours, 1 day, or a custom local date/time. Expired peers are automatically deleted by a dedicated systemd timer, with the normal WireGuard configuration backup created first. +- Added PSK and expiration state to the Clients overview without adding more table columns. +- Preserves existing PSKs on unmanaged peers when editing other server-side peer fields, including correct parsing of an existing `PresharedKey` from the peer block. +- Fixed multi-interface policy reconciliation so updating/deleting rules on one WireGuard interface cannot remove WGTools-managed firewall rules belonging to another interface. + +## v0.18.1 + +- Fixed the client-management JavaScript bootstrap function name so the web UI initializes correctly after loading. +- No changes to WireGuard interfaces, client groups, policies, routing, or backup format. + +## v0.18.0 + +- Added client groups scoped to the currently selected WireGuard interface. Normal clients can belong to one group; Site-to-site peers remain separate. +- Added reusable group server policies for Internet access, local/Site-to-site access and address/network Allow/Deny exceptions. +- Added safe per-client policy overrides. Client-specific Allow/Deny exceptions take precedence over group exceptions without modifying the group itself. +- Added a fully custom client policy mode while keeping the client organizationally assigned to its group. +- Added reusable new-client defaults for route preset/AllowedIPs, DNS and PersistentKeepalive. +- New clients can inherit group defaults automatically; existing clients keep their current configuration unless an administrator explicitly applies the group defaults. +- Added a visible warning when a managed client's saved configuration differs from current group defaults, making deliberate `.conf`/QR re-issue clear. +- Added safe group deletion: clients can be unassigned or moved to another group and are never deleted with the group. +- Telegram client creation can now select an interface-scoped group and automatically uses that group's routes, DNS and Keepalive defaults. +- Group policy changes are reconciled into deterministic WGTools-managed firewall rules without restarting WireGuard. +- Portable `.wgtbackup` migration archives now use format v3 and include client-group metadata while remaining compatible with v1/v2 backups. +- Full Tunnel except local networks now keeps generated client `AllowedIPs` at `0.0.0.0/0`; the local restriction stays entirely server-side. + +## v0.17.1 + +- Added required-field validation for managed client configuration, including the server address/domain and client AllowedIPs. +- Site-to-site remote networks are now marked required while that client type is selected. +- Added safe WireGuard interface deletion from the Server interface list. WGTools backs up the interface configuration, stops/disables the service, removes managed client metadata for that interface and switches to another remaining interface. +- The last configured WireGuard interface cannot be deleted from the interface manager; full removal remains an explicit uninstall/admin operation. + +## v0.17.0 + +- Added multi-interface WireGuard management for `wg0`, `wg1` and additional interfaces from one WGTools installation. +- Added a global interface selector in the top bar; Dashboard, Server, Clients and raw WireGuard configuration follow the selected interface. +- Added a compact interface overview on Server with status, address, port, policy table and optional friendly display names. +- Added **Add interface** provisioning with automatic suggestions for the next interface name, non-overlapping VPN network, free WireGuard UDP port and policy-routing table when the existing topology uses policy routing. +- Added cross-interface validation to prevent overlapping VPN pools and duplicate WireGuard listen ports or policy-routing tables. +- WGTools-managed client metadata is now associated with its WireGuard interface while remaining compatible with legacy client metadata. +- Added per-user WireGuard interface selection to the Telegram bot. +- Upgraded portable migration backups to format v2 so all detected WireGuard interface configurations, interface states and friendly-name metadata are included; v1 backups remain restorable. +- Host CPU, memory and network history remains global and uses the host default uplink so switching WireGuard interfaces cannot mix different NICs in the 24-hour graph. + +## v0.16.3 + +- Added 24-hour minimum, average and maximum summaries above the CPU and memory history graphs. +- Added separate RX and TX minimum, average and maximum rate summaries above the network history graph. + +## v0.16.2 + +- Online peers are now highlighted with green status text and a subtle breathing green indicator on Dashboard and Clients. +- Respects the browser `prefers-reduced-motion` accessibility setting. + +## v0.16.1 + +- Changed allowed-local-address exceptions from a resizable textarea to a single-line input. +- Full Tunnel except local networks now keeps the generated client `AllowedIPs` at `0.0.0.0/0` only. +- Added a read-only reference block showing which local and Site-to-site networks are blocked by the server-side policy. + +## v0.16.0 + +- Added per-client local access exceptions for **Full tunnel except local networks**. Individual IPs/CIDRs can stay reachable inside otherwise blocked LAN/Site-to-site networks. +- Added managed ACCEPT exception rules ahead of broader managed REJECT policies while preserving automatic cleanup and runtime reconciliation. +- Route presets now expose current Site-to-site topology: Full tunnel except local networks shows the protected LAN/Site-to-site networks, VPN + local LAN includes them, and Custom routes starts empty when selected. +- Added WGTools application icon in the browser tab and header/login header based on the new project mark. + +## v0.15.1 + +- Moved the full backup create/select/restore controls to the bottom of the backup block for better visual alignment. + +## v0.15.0 + +- Redesigned full backup/restore controls into a compact Create / Select / filename / Restore row. +- Raw wg0.conf editor now closes after a successful apply and shows a clear bottom-right result notification. +- Added client duplication with automatic unique name/VPN address suggestions and duplicate validation. +- Added delayed contextual tooltips for buttons and controls. +- Telegram Bot can now resend existing managed client configs and QR codes; WireGuard service controls use compact icon buttons. +- Dashboard CPU, memory and network cards now keep and display rolling 24-hour history graphs. +- Simplified multi-destination firewall guidance to comma-separated values. + +All notable public changes to WGTools are documented here. + +## v0.14.0 + +- Added an opt-in update checker under **Settings → About** using official published GitHub Releases. +- Added one-click WGTools updates with release metadata/changelog display. +- Updates run in a separate transient systemd job so the web service can safely replace and restart itself. +- Added pre-update full `.wgtbackup` state backup plus a separate application rollback archive. +- Added automatic application rollback when update installation fails. +- Added a neutral Project / GitHub link in About. +- Expanded uninstall documentation and uninstaller output to make it explicit that WireGuard is preserved, with optional full WireGuard cleanup commands. +- Added sanitized public interface screenshots to the README. + +## v0.13.2 + +- Reconciles the live `iptables` FORWARD chain against active WGTools-managed client policy after managed configuration transactions. +- Removes stale tagged `wgtools-protect-*` rules no longer present in `wg0.conf`. +- Collapses duplicate tagged policy rules and removes all exact copies when a restriction is deleted. +- Raw `wg0.conf` apply/restart performs the same reconciliation after WireGuard returns. +- Prevents a reused VPN address from inheriting a stale WGTools-generated REJECT rule from a deleted client. + +## v0.13.1 + +- Fixed live synchronization for **Full Tunnel except local networks** policies. +- Deleting one generated client-policy rule creates a per-client exception for that destination while remaining restrictions continue to synchronize. +- Deleting a client removes its WGTools-generated policy rules in the same operation. +- User-created unrelated firewall rules are preserved. + +## v0.13.0 + +- Added multiple firewall destinations separated by commas/new lines. +- Added **Full Tunnel except local networks** client mode. +- Server LAN and Site-to-site remote networks are automatically protected for that mode. +- Site-to-site add/change/delete operations update generated client restrictions. + +## v0.12.1 + +- Removed personal developer/contact details from the About card. +- Removed redundant Read-only badges from Server summary cards. + +## v0.12.0 + +- Added portable `.wgtbackup` migration backup and restore. +- Added archive/database validation, pre-restore safety backup and rollback. +- Restore can install WireGuard when the backup contains a server configuration and the target has no WireGuard tools. +- Successful restore clears the current web session. + +## v0.11.2 + +- Fixed parser failure on mixed IPv4/IPv6 AllowedIPs such as `0.0.0.0/0, ::/0`. +- Parser errors no longer take down the whole dashboard/provisioning UI. + +## v0.11.x + +- Added built-in English/Russian help with fictional topology examples. +- Added project About information and later removed personal contact details before public release preparation. + +## v0.10.0 + +- Added optional Telegram Bot using the official Bot API and long polling. +- Added authorized Telegram user IDs and private-chat-only administration. +- Added server status, client list/create/delete and WireGuard Start/Restart/Stop actions. +- Telegram-created clients can receive generated `.conf` and QR data. + +## v0.9.0 + +- Added CPU, memory, server uptime and live uplink traffic metrics. +- Added compact Start/Restart/Stop controls. +- Added configurable refresh interval, online threshold and automatic backup retention. + +## v0.8.0 + +- Added managed custom routes and firewall/NAT access rules. +- Added ownership distinction between server settings, Site-to-site routes and user rules. + +## v0.7.0 + +- Added visual Server settings editor for VPN pool/address, port, uplink, LAN, forwarding, NAT and policy routing. +- Existing peers and unsupported custom rules are preserved. +- Added backup/apply/rollback protection for server changes. + +## v0.6.0 + +- Added first-run account creation and login/logout. +- Added multiple local WGTools users with equal administrative permissions. +- Passwords stored as salted PBKDF2-SHA256 hashes. + +## v0.5.1 + +- Fixed raw `wg0.conf` helper routing. +- Dashboard peer subtitle shows live Endpoint rather than repeating VPN address. + +## v0.5.0 + +- Improved client editor layout and Site-to-site field visibility. +- New clients default to Full Tunnel. +- Server address/domain and WireGuard port became separate client-generation fields. + +## Earlier development + +Earlier internal versions established the dashboard, server parser, client list/create/delete workflow and initial deployment scripts. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9410542 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,43 @@ +# Contributing to WGTools + +Thanks for helping improve WGTools. + +## Before opening an issue + +- Check whether the problem occurs on the latest release. +- Run the built-in Server diagnostics. +- Remove private keys, Telegram tokens, public endpoints and sensitive topology details from logs/screenshots. +- Never upload a `.wgtbackup` archive to a public issue. + +Useful diagnostic commands include: + +```bash +systemctl status wgtools --no-pager -l +systemctl status wgtools-telegram --no-pager -l +journalctl -u wgtools -n 100 --no-pager +journalctl -u wgtools-telegram -n 100 --no-pager +wg show +ip rule show +ip route show table all +iptables -S +iptables -t nat -S +``` + +Sanitize outputs before posting them publicly. + +## Pull requests + +Please keep changes focused and readable. + +For changes that touch routing, firewall, WireGuard configuration or backup/restore logic, describe: + +1. the previous behavior; +2. the new behavior; +3. how rollback/failure is handled; +4. how the change was tested. + +Do not commit generated databases, private keys, `.conf` files, `.wgtbackup` archives, `.venv`, `__pycache__` or production logs. + +## Language + +Source code, identifiers and primary documentation should remain English. User-facing UI text can be added to both English and Russian locale files. diff --git a/LICENSE b/LICENSE index cce5a47..a0f74c3 100644 --- a/LICENSE +++ b/LICENSE @@ -1,19 +1,23 @@ MIT License Copyright (c) 2026 Asmin Studios -Copyright (c) 2026 KindMich and WGTools contributors at https://github.com/KindMich/WGTools +Copyright (c) 2026 KindMich and WGTools contributors at https://github.com/KindMich/WGTools +Copyright (c) 2026 WGTools contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and -associated documentation files (the "Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the -following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial -portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO -EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/PRIVACY.md b/PRIVACY.md new file mode 100644 index 0000000..cd4c32f --- /dev/null +++ b/PRIVACY.md @@ -0,0 +1,59 @@ +# Privacy and Data Flow + +WGTools is designed as a self-hosted administration tool. + +## No application telemetry + +WGTools does not include analytics, advertising SDKs or background telemetry to the project maintainer. + +The application does not intentionally upload your: + +- WireGuard server private key; +- client private keys; +- peer list; +- local network topology; +- WGTools usernames, optional account e-mail addresses and password hashes; +- traffic counters; +- configuration backups. + +## External network connections + +### Let’s Encrypt / ACME + +If and only if an administrator requests a built-in HTTPS certificate, WGTools invokes the locally installed Certbot client to contact Let’s Encrypt ACME services for certificate issuance. While built-in HTTPS remains enabled, a systemd timer runs Certbot renewal automatically. The requested domain or public IP and Let’s Encrypt account e-mail are necessarily sent to the certificate authority as part of the ACME process. TCP port `80` must be reachable from the Internet for the standalone HTTP-01 validation used by WGTools. The resulting certificate and private key remain on the server under `/etc/letsencrypt/live/wgtools/`. + +### Mail / SMTP + +If and only if Mail is configured and used, WGTools connects to the administrator-supplied SMTP server to send test messages and password-recovery codes. SMTP host/login/sender settings and the optional SMTP password are stored locally in the WGTools SQLite database. The password is not returned by the settings API and is redacted from Audit. Password-reset codes are stored only as salted PBKDF2 hashes, expire after 15 minutes and are one-time use. + +### Telegram + +If and only if Telegram Bot integration is configured and enabled, WGTools connects to: + +```text +https://api.telegram.org +``` + +The bot uses long polling and sends the messages/files necessary for the actions requested by authorized Telegram users. + +### Optional traceroute map geolocation + +The **Server → Trace** diagnostic can optionally draw public route hops on an interactive map. Only when **Show route on map** is enabled, WGTools sends the public IP addresses returned by traceroute to `https://ipwho.is` to obtain approximate coordinates and network/location labels. Private/local hop addresses are not sent. Results are cached locally in `/run` for up to 24 hours to reduce repeated lookups. The browser also requests map tiles from OpenStreetMap (`tile.openstreetmap.org`), so that service can see the browser IP address and the map tile coordinates being viewed. Ping and traceroute themselves do not use either service. + +### Debian / Ubuntu package repositories + +When an administrator installs packages from the UI or runs the installer, `apt` contacts the Debian/Ubuntu repositories configured on the host. + +### Instalacja i aktualizacje + +Instalator uruchamia się z lokalnych plików projektu. Administrator ręcznie wgrywa pakiet aktualizacji; aplikacja nie sprawdza serwerów aktualizacyjnych oryginalnego projektu. + +## Local browser data + +The browser may store UI preferences and previously entered endpoint/domain values to make repeated client creation easier. These remain in the browser profile. + +## Local server data + +Persistent application state is stored under `/var/lib/wgtools` and `/etc/wgtools`. This includes WGTools-managed client metadata, client-group policy/default definitions, a rolling 24-hour CPU, memory and network-rate history used only for the local Dashboard graphs, durable per-peer/interface WireGuard traffic counters, and the local Audit journal. Audit records can contain the WGTools username, Telegram `@username` and numeric Telegram user ID for state-changing bot actions, and WireGuard client endpoint IP addresses for connection-history events. Audit events are retained for 30 days with a 10,000-row safety cap. Secret-bearing fields and key/token-like values are redacted or intentionally excluded. Login failures and password-recovery actions may record the connecting IP address for local security auditing. WireGuard configuration remains under `/etc/wireguard`. + +See [README.md](README.md) for the file layout. diff --git a/README.md b/README.md index a55e691..8eb53ad 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,311 @@ # WGTools-Extended -Production-ready fork of WGTools by Asmin Studios. \ No newline at end of file +Projekt jest w trakcie rozbudowy na podstawie WGTools. Aktualizator oryginalnego projektu jest odłączony. + +Konta istniejące przed rozbudową zachowują rolę administratora. Pierwsze konto jest administratorem, a kolejne są tworzone bez dostępu do sieci. Administrator przypisuje dostęp do sieci oraz osobno zezwala na dodawanie klientów, edycję klientów i zarządzanie przekierowaniami. Mechanizm uprawnień jest w trakcie weryfikacji i nie powinien jeszcze być używany jako zabezpieczenie produkcyjne. + +Na stronie serwera można ustawić podstawowy adres IPv4 SNAT dla wybranej sieci. Adres musi być przypisany do wskazanego interfejsu. Zapis restartuje działający interfejs WireGuard i może na chwilę rozłączyć klientów. + +Można też ograniczyć przychodzący ruch UDP WireGuard do adresu IPv4, interfejsu wejściowego albo obu jednocześnie. Przy aktywnym ograniczeniu ruch IPv6 na ten port jest blokowany. Zmiana restartuje działający interfejs. + +Workflow Gitea tworzy wydanie dla tagu `vX.Y.Z`, zgodnego z plikiem `VERSION`. Korzysta z runnera `docker-builder` oraz wymaga sekretu repozytorium `GITEA_RELEASE_TOKEN` z prawem tworzenia wydań. Plik `.bin` jest archiwum źródłowym gzip i można go wgrać w ustawieniach. Pakiety nie są podpisywane; administrator musi sam sprawdzić ich pochodzenie. Aktualizacja tworzy kopię zapasową i w razie błędu próbuje przywrócić poprzednią wersję. + +Administrator przypisuje publiczne IPv4 do grup i sieci. Użytkownicy danej sieci mogą przekierować TCP, UDP lub oba protokoły z przypisanego adresu na adres klienta tej sieci. Program odrzuca konflikty między swoimi przekierowaniami i sprawdza lokalne nasłuchujące usługi; ręczne reguły zapory trzeba sprawdzić osobno. Zmiana przekierowania restartuje działający interfejs. + +# WGTools — WireGuard Web UI & Server Management Panel + +**WGTools** is an open-source, self-hosted **WireGuard web UI and server management panel** for **Debian and Ubuntu**. It provides a browser-based WireGuard GUI for day-to-day administration without manually editing `wg-quick` configuration files for routine tasks. + +WGTools combines WireGuard installation and multi-interface management, clients and Site-to-Site peers, routing/NAT/firewall policy, VPS Relay, multi-server Nodes, monitoring, TOTP MFA, traceroute/ping route diagnostics, backups, scheduled access, HTTPS, Telegram administration and safe application updates in one UI. + +> **Security note:** WGTools performs privileged network administration and its services run as `root`. The bundled web service starts on HTTP port `8341` by default. For Internet-facing installations, enable **Settings → HTTPS** to obtain a Let’s Encrypt certificate and move WGTools directly to a selected HTTPS port and a private access path, or place `8341` behind your own reverse proxy. Do not expose plain HTTP `8341` directly to the public Internet. + +[Русская версия README](README.ru.md) + +## Supported systems + +WGTools supports **Debian and Ubuntu** hosts using `apt` and `systemd`. + +The installer and VPS Relay preflight expect the normal Debian/Ubuntu networking toolchain (`iproute2`, `iptables`, `wg`/`wg-quick`, Python 3 and systemd). WireGuard itself can be installed from the WGTools Server page on a clean host. + +## Screenshots + +
+Show WGTools screenshots + +
+ +### Getting started + +#### First-user setup + +![WGTools WireGuard web UI first-user setup](docs/screenshots/first-user-setup.png) + +### Dashboard and monitoring + +#### Dashboard with multiple WireGuard interfaces + +![WGTools WireGuard dashboard and interface selector](docs/screenshots/dashboard-interface-selector.png) + +### Server management + +#### Multiple WireGuard interfaces + +![WGTools server manager with multiple WireGuard interfaces](docs/screenshots/server-multi-interface.png) + +### Clients and Site-to-Site + +#### Client list + +![WGTools WireGuard clients and peer status](docs/screenshots/clients-list.png) + +#### Create a WireGuard client + +![WGTools create WireGuard client dialog](docs/screenshots/create-client.png) + +#### Create a Site-to-Site peer + +![WGTools create WireGuard Site-to-Site peer dialog](docs/screenshots/create-site-to-site.png) + +### Settings and CLI + +#### General settings + +![WGTools settings for theme language and status refresh](docs/screenshots/settings-general.png) + +#### Root management console + +![WGTools root CLI management console](docs/screenshots/wgtools-cli.png) + +
+ +> Screenshots contain lab/example values. Never publish private keys, real client configuration QR codes, passwords, tokens or `.wgtbackup` contents. + +## Highlights + +### WireGuard server and interfaces + +- Install WireGuard from the UI on a clean Debian/Ubuntu host. +- Create the first server (`wg0`) with an optional friendly **Display name**. +- Default first VPN pool: `10.0.0.0/24`, server address `10.0.0.1/24`. +- Add independent `wg1`, `wg2`, … interfaces with automatic suggestions for a non-overlapping pool, free UDP port and policy table. With the default layout, `wg1` is suggested as `10.0.1.0/24`. +- Global top-bar interface selector; Dashboard, Server, Clients and raw config follow the selected interface. +- Start, restart and stop the selected WireGuard interface. +- Internal Relay transport interfaces (`wgrly*`) are intentionally hidden from normal interface management. + +### Routing, NAT and firewall + +- IPv4 forwarding and NAT/MASQUERADE management. +- Uplink interface, gateway and local-network settings. +- Optional source policy-routing table per WireGuard interface. +- Managed static/site-to-site routes. +- Server access policy with tagged WGTools firewall rules and live reconciliation. +- Raw `/etc/wireguard/.conf` editor with validation, backup and rollback protection. + +### Clients and site-to-site peers + +- Normal WireGuard clients and site-to-site peers. +- Per-client VPN isolation from other WireGuard pool addresses without blocking access to the server itself, LAN, Site-to-site destinations or Internet allowed by the other policies. +- Automatic free VPN-address suggestion. +- Generated `.conf` files and QR codes for WGTools-managed clients. +- Optional PresharedKey (PSK). +- One safe **Rotate keys** action regenerates PrivateKey/PublicKey and also regenerates PSK when PSK is enabled; address, routes, group/policies, expiration/schedule, isolation, last seen and accumulated traffic are preserved, and a new config/QR must be issued afterward. +- PersistentKeepalive and DNS settings. +- Route presets: full tunnel, full tunnel except protected local networks, VPN + local networks, VPN only and custom routes. +- Per-client local-network exceptions and server-side access policy. +- Client groups with reusable policies/defaults and per-client overrides. +- Temporary clients with 1/3/6 hour, 1 day or custom expiration. +- Recurring access schedules by weekday and time, including overnight windows such as `22:00–06:00`. +- Live peer create/edit/delete via `wg syncconf` without restarting the whole interface during normal peer operations. + +### VPS Relay + +WGTools can use a public Debian/Ubuntu VPS as a WireGuard UDP Relay when the real WGTools server is behind NAT or otherwise hard to reach directly. + +```text +WireGuard client + │ encrypted client WireGuard packets + ▼ +Public VPS Relay Agent + │ protected Home ↔ VPS transport + ▼ +WGTools / real WireGuard server + ├── local networks + └── Internet (when the client policy allows it) +``` + +The Relay is a transport layer: it does **not** terminate the client's WireGuard session and does not become a separate Internet-exit VPN server. The real WireGuard server remains the WGTools host. + +Relay features: + +- SSH preflight before installation: OS, privileges, tools and UDP-port checks. +- Password and pasted SSH private key are used only for the current operation and are not stored by WGTools. +- One Relay Agent can keep multiple isolated tenants for different WGTools controllers. +- One WGTools installation can register multiple VPS Relay endpoints and assign clients to a selected Relay. +- Existing Relay Agent installations are reused instead of overwritten; free tenant UDP ports are selected automatically. +- Protected management/transport tunnel with health information. +- **Remove VPS** detaches the Relay from the local WGTools installation but intentionally leaves the remote tenant intact for disaster recovery. +- Adding the same VPS again can reconnect the existing tenant instead of creating another one. +- Migration restore can rebuild the home side of a preserved Relay from the restored WGTools state. + +### WGTools Nodes + +WGTools installations can be linked through a hidden `wgnode0` Hub-and-Spoke WireGuard network. The HUB uses one Nodes port number for **UDP WireGuard** and **protected TCP pairing**; when the HUB is behind NAT, forward that port for both protocols. + +- Spoke setup needs only a node name, HUB `host:port`, one-time code and optional additional routed networks. +- The one-time code pins the HUB Node-control certificate fingerprint before its secret is sent. +- After pairing, topology, status, version and read-only remote-client data synchronize only through `wgnode0`, not through the WGTools web URL. +- Local interface VPN pools and configured Site-to-Site peer remote networks are published automatically; Site-to-Site publication is based on configuration and does not disappear when that peer is offline. +- Ordinary WireGuard clients of a remote Node can access locally published networks without return routes on each LAN router; WGTools applies narrow return-path NAT only to remote VPN client pools. +- The optional panel URL is informational metadata for **Open panel** and may change independently without breaking Nodes. +- Full `.wgtbackup` migration/restore preserves the HUB Node-control identity used by already-paired Spokes. + +### Dashboard and monitoring + +- WireGuard state, selected-interface address/port, peer counts and durable lifetime handshake/RX/TX statistics. Traffic counters survive WireGuard/host restarts and can be reset manually from the Dashboard. +- CPU, memory and network-rate metrics. +- Rolling 24-hour graphs with minimum/average/maximum summaries. +- Search/filtering for peer lists. +- Dedicated **Server → Trace** diagnostics with ping + traceroute, per-hop RTT/loss, latency-jump highlighting and an interactive OpenStreetMap route view with pan/zoom and clickable hops. + +### Terminal console + +Run `wgtools` as root to open the local boxed management menu. It shows the current panel URL/private HTTPS path plus WGTools, WireGuard, Nodes, Telegram, timers and local Relay Agent status, and provides panel controls, WireGuard status/start/stop/restart actions, logs, HTTP rescue, emergency MFA disable for a selected user, and two clearly separated removal paths: a soft uninstall that preserves WireGuard/reusable data and a destructive FULL CLEANUP. + +### HTTPS + +- Optional built-in HTTPS without Nginx/Caddy/Traefik: WGTools can serve TLS directly with Uvicorn on a user-selected TCP port (`443` by default). +- Let’s Encrypt certificates can be requested for a domain or a public IP address. IP certificates use Let’s Encrypt’s short-lived profile and therefore depend on automatic renewal. +- Certificate issuance/renewal uses Certbot standalone validation, so TCP `80` must be reachable from the Internet while ACME validation runs. +- WGTools checks local TCP `80` plus the selected HTTPS port before issuance/enabling and never stops or replaces an unrelated web server. +- Automatic renewal is enabled with a dedicated systemd timer while built-in HTTPS is active; successful renewal reloads WGTools. +- Built-in HTTPS requires an administrator-defined panel path such as `/MyPrivateWGToolsPath/`. Requests outside that prefix receive `404`; authentication is still required normally inside the path. +- Settings shows the `fullchain.pem` and `privkey.pem` paths with copy buttons so the same certificate files can be referenced by other software on the host. +- Built-in HTTPS can be disabled to return WGTools to its normal HTTP port when a user prefers NPM, Caddy, Traefik or another reverse proxy. + +### Authentication, mail and Telegram + +- First-run admin creation and local WGTools user management with optional per-user e-mail addresses. +- Optional per-user TOTP MFA compatible with **Google Authenticator**, 2FAS, Aegis and other standard authenticator apps. Enrollment uses a QR code (with a manual setup key fallback), and WGTools generates one-time recovery codes. Root can emergency-disable MFA from the local `wgtools` CLI if the authenticator device and recovery codes are lost. +- Optional SMTP password recovery with STARTTLS/TLS/plain SMTP support, a one-time 6-digit code valid for 15 minutes, request/attempt limits, and identical public responses that do not reveal whether an account exists. Password changes invalidate older sessions for that user. +- Administrators can send a reset code directly from Settings → Users; SMTP configuration and test delivery live under Settings → Mail. +- Passwords stored as salted PBKDF2-HMAC-SHA256 hashes. +- Optional Telegram Bot with an allow-list of numeric Telegram user IDs. +- Telegram status, interface selection, client creation/removal and config/QR re-issue. WireGuard Start/Restart/Stop controls are grouped under a dedicated **Server** item beside **Interface**. Navigation appends new bot messages without overwriting earlier screens, keeping the recent history available for reuse. After sending a config/QR, the refreshed client picker appears below the files; destructive confirmations are bound to the current prompt. Cyrillic client names receive readable transliterated `.conf` filenames instead of the generic fallback. + +### Audit + +- **Settings → Audit** opens a searchable audit journal with timestamp, actor, action, object and result. +- Web changes record the local WGTools username. Telegram state-changing actions record `@username` when available and always include the numeric Telegram user ID. +- The Telegram menu has a read-only **Audit** shortcut and `/audit` command; browse the latest 20 events and older/newer pages (including changes made by other WGTools administrators). +- Telegram client create/delete, explicit config/QR re-issue and WireGuard Start/Stop/Restart actions are audited; meaningful failures and denied mutating attempts are recorded without logging ordinary menu navigation or read-only status views. +- WireGuard client connection history records client name, time and endpoint IP when a client connects after a meaningful offline gap or its endpoint IP changes. +- The last successful client handshake is kept as durable last-seen state, so restarting the host or WireGuard interface does not turn a previously connected client into `Never`. +- Application updates audit the safety `.wgtbackup`, successful completion, useful failures and automatic rollback results. +- Audit retention is 30 days with a 10,000-row safety cap. +- Passwords, reset codes, WireGuard private keys, PSKs, Telegram Bot tokens, SMTP passwords, Relay `control_token`, SSH credentials, full client configs and QR contents are redacted or never written. + +### Backups and disaster recovery + +WGTools has two backup layers: + +1. **Automatic configuration history** before configuration-changing operations. +2. **Portable `.wgtbackup` migration/disaster-recovery archive**. + +A full `.wgtbackup` can include: + +- all detected WireGuard interface configs and their running/stopped state; +- WGTools SQLite database with users/e-mail addresses, preferences, SMTP settings and VPS Relay records; +- managed client metadata, client private keys and PSKs; +- client groups, schedules/expiration state and interface display-name metadata; +- Telegram configuration/token and SMTP credentials when configured; +- forwarding sysctl state; +- Relay controller/tenant identity, management token and home transport key needed to reconnect a preserved remote Relay tenant. + +The remote VPS filesystem itself is not copied into `.wgtbackup`; for transparent Relay disaster recovery, the Relay Agent/tenant must still exist on that VPS. + +> Let’s Encrypt certificate lineages under `/etc/letsencrypt` are host-level files and are not copied into `.wgtbackup`. After migrating WGTools to another host, request the built-in HTTPS certificate again. A normal WGTools uninstall intentionally leaves `/etc/letsencrypt` untouched so an existing certificate can still be used by other software. + +> `.wgtbackup` files contain secrets, including saved SMTP credentials when configured. Protect them like passwords or private SSH keys and never attach one to a public issue. + +### Aktualizacje + +Administrator wgrywa zaufany pakiet `.bin` w ustawieniach. Przed instalacją powstają kopia danych i archiwum aplikacji. W razie błędu program próbuje przywrócić poprzednią wersję. Aktualizacje online oryginalnego projektu są odłączone. + +## Quick install + +```bash +sudo bash install.sh +``` + +The local installer runs [`scripts/install.sh`](scripts/install.sh) from the checked-out source tree. + +Open the printed URL (normally `http://SERVER-IP:8341`) and create the first WGTools account. + +WireGuard is intentionally not installed silently by the bootstrap installer. On a clean server, use **Server → Install WireGuard**. + +### Inspect before installing + +```bash +# Pobierz kod WGTools-Extended z własnego repozytorium. +cd WGTools +less install.sh +less scripts/install.sh +less scripts/wgtools-helper +sudo ./scripts/install.sh +``` + +To install a specific public release: + +```bash +git checkout v0.40.4 +sudo ./scripts/install.sh +``` + +## Installed paths + +| Path | Purpose | +|---|---| +| `/opt/wgtools` | Application source and Python virtual environment | +| `/var/lib/wgtools` | SQLite database, session secret, managed client state, backups and Relay home-side metadata | +| `/etc/wgtools/wgtools.env` | Runtime environment settings | +| `/usr/local/libexec/wgtools-helper` | Privileged helper used by the web application | +| `/etc/systemd/system/wgtools*.service` | WGTools web/Telegram/expiry services | +| `/etc/wireguard/*.conf` | User-managed WireGuard interface configurations | +| `/var/lib/wgtools-relay` | VPS Relay Agent state when this host is used as a Relay VPS | +| `/opt/wgtools-relay` | VPS Relay Agent code when this host is used as a Relay VPS | + +WGTools does not create an additional Linux user. The services run as root because they manage WireGuard, routes, firewall state and protected configuration files. + +## Network and privacy + +WGTools has no analytics, advertising or application telemetry to the project maintainer. It does not upload your WireGuard keys, peer list, local topology, users or traffic counters. + +Expected outbound connections are limited to enabled features: + +- **Gitea:** releases are published by the project workflow; updates are uploaded manually by the administrator. +- **Telegram:** only when Telegram Bot integration is enabled. +- **APT repositories:** package installation on Debian/Ubuntu. + +See [PRIVACY.md](PRIVACY.md) and [SECURITY.md](SECURITY.md). + +## Uninstall and complete cleanup + +Removal is built into the root `wgtools` console, so routine uninstall/cleanup does not require copying shell commands from the documentation. + +The CLI provides two deliberately separate actions: + +- **Uninstall WGTools** — removes the panel, services, CLI and internal Nodes/local Relay-home transports while preserving normal WireGuard and reusable WGTools state for reinstall/recovery. +- **FULL CLEANUP** — destructive cleanup for a dedicated host. It removes WGTools state/backups, Nodes, local Relay state, WireGuard interfaces/configuration and WireGuard packages. It requires typing `DELETE ALL` before execution. Remote Relay VPS hosts are never contacted automatically. + +Run the local management console as `root` with `wgtools` and choose the required removal action from the **Removal** section. + +## Security + +WGTools is a privileged administration application. Before exposing it outside a trusted network, read [SECURITY.md](SECURITY.md). + +For security reports, do not publish private keys, `.wgtbackup` archives, passwords, bot tokens or production configuration in a public issue. + +## License + +See [LICENSE](LICENSE). diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000..08aa9b1 --- /dev/null +++ b/README.ru.md @@ -0,0 +1,296 @@ +# WGTools — веб-панель управления WireGuard + +**WGTools** — open-source self-hosted **WireGuard Web UI / GUI и панель управления WireGuard-сервером** для **Debian и Ubuntu**. Она позволяет выполнять повседневное администрирование через браузер и не редактировать `wg-quick` конфиги вручную для обычных операций. + +В одном интерфейсе собраны установка и несколько WireGuard-интерфейсов, клиенты и Site-to-Site, маршрутизация/NAT/firewall, VPS Relay, связь нескольких серверов через Nodes, мониторинг, TOTP MFA, traceroute/ping с интерактивной картой маршрута, резервные копии, расписания доступа, HTTPS, Telegram и безопасные обновления. + +> **Важно по безопасности:** WGTools выполняет привилегированные сетевые операции, поэтому его службы работают от `root`. Встроенный web-сервис стартует на HTTP-порту `8341`. Для установки, доступной из Интернета, включите **Настройки → HTTPS**: WGTools получит сертификат Let’s Encrypt и перейдёт на выбранный HTTPS-порт с отдельным приватным путём доступа, либо оставьте `8341` за своим reverse proxy. Не публикуйте обычный HTTP `8341` напрямую в Интернет. + +[English README](README.md) + +## Поддерживаемые системы + +WGTools поддерживает **Debian и Ubuntu** с `apt` и `systemd`. + +Установщик и проверка VPS Relay рассчитывают на стандартный стек Debian/Ubuntu: `iproute2`, `iptables`, `wg`/`wg-quick`, Python 3 и systemd. На чистой машине WireGuard можно установить прямо со страницы **Сервер**. + +## Скриншоты + +
+Показать скриншоты WGTools + +
+ +### Первый запуск + +#### Создание первого пользователя + +![Первичная настройка пользователя в веб-панели WireGuard WGTools](docs/screenshots/first-user-setup.png) + +### Главная и мониторинг + +#### Главная с несколькими WireGuard-интерфейсами + +![Главная WGTools и переключатель WireGuard-интерфейсов](docs/screenshots/dashboard-interface-selector.png) + +### Управление сервером + +#### Несколько WireGuard-интерфейсов + +![Управление несколькими WireGuard-интерфейсами в WGTools](docs/screenshots/server-multi-interface.png) + +### Клиенты и Site-to-Site + +#### Список клиентов + +![Клиенты WireGuard и состояние peer в WGTools](docs/screenshots/clients-list.png) + +#### Создание WireGuard-клиента + +![Создание WireGuard-клиента в WGTools](docs/screenshots/create-client.png) + +#### Создание Site-to-Site peer + +![Создание WireGuard Site-to-Site подключения в WGTools](docs/screenshots/create-site-to-site.png) + +### Настройки и CLI + +#### Основные настройки + +![Настройки темы языка и обновления статуса WGTools](docs/screenshots/settings-general.png) + +#### Консоль управления root + +![Консоль управления WGTools для WireGuard](docs/screenshots/wgtools-cli.png) + +
+ +> На скриншотах используются лабораторные/примерные значения. Никогда не публикуйте приватные ключи, реальные QR-коды клиентских конфигураций, пароли, токены или содержимое `.wgtbackup`. + +## Основные возможности + +### WireGuard-сервер и интерфейсы + +- Установка WireGuard из UI на чистой Debian/Ubuntu машине. +- Создание первого сервера (`wg0`) с необязательным понятным **Display name**. +- Пул по умолчанию для первого интерфейса: `10.0.0.0/24`, адрес сервера `10.0.0.1/24`. +- Добавление независимых `wg1`, `wg2`, … с автоматическим предложением непересекающегося пула, свободного UDP-порта и policy table. При стандартной схеме для `wg1` предлагается `10.0.1.0/24`. +- Глобальный переключатель интерфейсов в верхней панели; Dashboard, Server, Clients и raw config работают с выбранным интерфейсом. +- Start / Restart / Stop выбранного WireGuard-интерфейса. +- Внутренние Relay-интерфейсы `wgrly*` скрыты из обычного пользовательского управления. + +### Маршрутизация, NAT и firewall + +- IPv4 forwarding и NAT/MASQUERADE. +- Uplink-интерфейс, gateway и локальная сеть. +- Необязательная отдельная таблица source policy routing для каждого WireGuard-интерфейса. +- Управляемые маршруты и Site-to-site сети. +- Серверные правила доступа с собственными тегами WGTools и синхронизацией live `iptables`. +- Raw-редактор `/etc/wireguard/.conf` с проверкой, backup и rollback. + +### Клиенты и Site-to-site + +- Обычные WireGuard-клиенты и Site-to-site peer'ы. +- Персональная изоляция VPN-клиента от других адресов WireGuard-пула без блокировки доступа к самому серверу, LAN, Site-to-site сетям или Интернету, разрешённым остальными политиками. +- Автоматическое предложение первого свободного VPN-адреса. +- Генерация `.conf` и QR-кода для WGTools-managed клиентов. +- Необязательный PresharedKey (PSK). +- Единая безопасная кнопка **«Сменить ключи»** создаёт новые PrivateKey/PublicKey и, если PSK включён, новый PSK; адрес, маршруты, группа/политики, срок/расписание, изоляция, last seen и накопленный трафик сохраняются, после чего требуется новый конфиг/QR. +- DNS и PersistentKeepalive. +- Пресеты маршрутов: весь трафик, весь трафик кроме защищённых локальных сетей, VPN + локальные сети, только VPN и Custom. +- Исключения доступа к отдельным локальным IP/CIDR и серверная политика доступа. +- Группы клиентов с общими политиками/defaults и индивидуальными override'ами. +- Временные клиенты: 1/3/6 часов, 1 день или произвольная дата/время. +- Повторяющиеся расписания доступа по дням недели и времени, включая окна через полночь, например `22:00–06:00`. +- Обычные операции с peer'ами применяются через `wg syncconf` без перезапуска всего интерфейса. + +### VPS Relay + +WGTools может использовать публичный Debian/Ubuntu VPS как UDP Relay, если реальный WGTools/WireGuard-сервер находится за NAT или напрямую недоступен извне. + +```text +WireGuard-клиент + │ зашифрованные WireGuard-пакеты клиента + ▼ +Публичный VPS Relay Agent + │ защищённый транспорт Home ↔ VPS + ▼ +WGTools / реальный WireGuard-сервер + ├── локальные сети + └── Интернет, если это разрешено политикой клиента +``` + +Relay является транспортом: он **не завершает клиентский WireGuard-туннель** и не превращается в отдельный VPN-шлюз для выхода в Интернет. Реальным WireGuard-сервером остаётся машина WGTools. + +Возможности Relay: + +- SSH preflight перед установкой: ОС, права, инструменты и свободные UDP-порты. +- Пароль и вставленный приватный SSH-ключ используются только для текущей операции и не сохраняются WGTools. +- Один Relay Agent хранит несколько изолированных tenant'ов для разных экземпляров WGTools. +- Один WGTools может иметь несколько VPS Relay и назначать клиенту конкретный Relay. +- Существующий Relay Agent не перезаписывается; для нового tenant автоматически выбираются свободные UDP-порты. +- Защищённый management/transport туннель и health-проверка. +- **Удалить VPS** отсоединяет Relay от текущего WGTools, но специально оставляет remote tenant на VPS для аварийного восстановления. +- Повторное добавление того же VPS умеет подключиться к существующему tenant, не создавая новый. +- Restore полной резервной копии может восстановить домашнюю сторону transport к сохранившемуся tenant на VPS. + +### Узлы WGTools + +Несколько установок WGTools можно связать через скрытую Hub-and-Spoke сеть `wgnode0`. HUB использует один номер порта одновременно для **UDP WireGuard** и **защищённого TCP pairing**; если HUB находится за NAT, этот порт нужно пробросить по обоим протоколам. + +- На Spoke нужны только имя узла, HUB `host:port`, одноразовый код и при необходимости дополнительные маршрутизируемые сети. +- Одноразовый код закрепляет fingerprint служебного сертификата HUB до отправки секрета подключения. +- После pairing топология, статусы, версии и read-only данные удалённых клиентов синхронизируются только внутри `wgnode0`, а не через адрес веб-панели WGTools. +- VPN-пулы локальных интерфейсов и настроенные удалённые сети Site-to-Site клиентов публикуются автоматически; Site-to-Site сеть остаётся в топологии даже когда соответствующий peer офлайн. +- Обычные WireGuard-клиенты удалённого узла могут ходить в локально опубликованные сети без ручных обратных маршрутов на LAN-роутерах; WGTools применяет узкий return-path NAT только к удалённым VPN-пулам клиентов. +- Необязательный адрес панели остаётся информационным полем для кнопки **«Открыть панель»** и может меняться независимо от Nodes. +- Полный `.wgtbackup` сохраняет служебную identity HUB, которой уже доверяют подключённые Spoke. + +### Dashboard и мониторинг + +- Состояние WireGuard, адрес/порт выбранного интерфейса, peer'ы и долговременная статистика handshake/RX/TX. Счётчики трафика переживают перезапуски WireGuard/сервера и вручную сбрасываются с Главной. +- CPU, RAM и скорость сети. +- 24-часовые графики с min/avg/max. +- Поиск по спискам peer'ов. +- Отдельная вкладка **Сервер → Маршрут**: ping + traceroute, RTT и потери по каждому узлу, подсветка скачков задержки и интерактивная карта OpenStreetMap с масштабированием, перемещением и деталями по узлам. + +### Консоль управления + +Команда `wgtools` от root открывает локальное меню управления со сводной таблицей состояний. В нём видны текущий URL/приватный HTTPS-путь, WGTools, WireGuard, Nodes, Telegram, таймеры и локальный Relay Agent; доступны управление панелью, статус/запуск/остановка/перезапуск WireGuard, логи, аварийный возврат на HTTP, аварийное отключение MFA для выбранного пользователя и два явно разделённых сценария удаления: мягкий uninstall с сохранением WireGuard/данных и разрушительный FULL CLEANUP. + +### HTTPS + +- Необязательный встроенный HTTPS без Nginx/Caddy/Traefik: WGTools может сам обслуживать TLS через Uvicorn на выбранном пользователем TCP-порту (`443` по умолчанию). +- Сертификат Let’s Encrypt можно получить для домена или публичного IP. Для IP используются короткоживущие сертификаты Let’s Encrypt, поэтому автопродление обязательно. +- Выпуск и продление идут через Certbot standalone, поэтому TCP-порт `80` должен быть доступен из Интернета во время ACME-проверки. +- Перед выпуском/включением WGTools проверяет локальный TCP `80` и выбранный HTTPS-порт и не останавливает/не перенастраивает чужой web-сервис. +- Пока встроенный HTTPS включён, отдельный systemd timer автоматически проверяет продление сертификата; после успешного renewal WGTools перечитывает сертификат. +- Для встроенного HTTPS администратор сам задаёт путь панели, например `/MyPrivateWGToolsPath/`. Запросы вне этого пути получают `404`; внутри пути обычная авторизация WGTools остаётся обязательной. +- Во вкладке HTTPS ненавязчиво показываются пути к `fullchain.pem` и `privkey.pem` с кнопками копирования — их можно использовать в других сервисах на этом же сервере. +- Встроенный HTTPS можно отключить и вернуть WGTools на обычный HTTP-порт, если пользователь предпочитает NPM, Caddy, Traefik или другой reverse proxy. + +### Пользователи, почта и Telegram + +- Создание первого администратора и локальное управление пользователями WGTools; для каждой учётной записи можно указать необязательный E-mail. +- Необязательная MFA для каждого пользователя по стандарту TOTP, совместимая с **Google Authenticator**, 2FAS, Aegis и другими приложениями. Подключение через QR-код (есть ключ для ручного ввода), при включении выдаются одноразовые резервные коды. Если устройство и резервные коды потеряны, root может аварийно отключить MFA через локальную команду `wgtools`. +- Необязательное восстановление пароля через SMTP: STARTTLS/TLS/обычный SMTP, одноразовый 6-значный код на 15 минут, лимиты запросов/попыток и одинаковый публичный ответ без раскрытия существования учётной записи. После смены или восстановления пароля старые web-сессии пользователя инвалидируются. +- Администратор может отправить код сброса прямо из **Настройки → Пользователи**; SMTP и тестовая отправка настраиваются во вкладке **Настройки → Почта**. +- Пароли хранятся как salted PBKDF2-HMAC-SHA256 hashes. +- Необязательный Telegram Bot с allow-list числовых Telegram user ID. +- Через Telegram доступны статус, выбор интерфейса, создание/удаление клиента и повторная выдача config/QR. Пуск/Перезапуск/Стоп WireGuard собраны в отдельном пункте «Сервер» рядом с выбором интерфейса. Навигация идёт по шагам: после отправки config/QR обновлённый список клиентов появляется ниже файлов, а вложенные подтверждения возвращают на родительский список. Кириллические имена клиентов получают читаемые транслитерированные имена `.conf`-файлов вместо общего имени по умолчанию. + +### Аудит + +- **Настройки → Аудит** открывает журнал с поиском: дата/время, источник/пользователь, действие, объект и результат. +- Для действий из web-панели сохраняется локальный пользователь WGTools. Для действий Telegram показывается `@username`, если он есть, и обязательно числовой Telegram user ID. +- В аудит попадают создание/удаление клиентов через Telegram, явная повторная выдача config/QR и Start/Stop/Restart WireGuard; полезные ошибки и запрещённые изменяющие действия тоже фиксируются, а обычная навигация по меню и просмотр статусов журнал не засоряют. +- История подключений WireGuard хранит имя клиента, время и endpoint IP при подключении после заметного перерыва или смене IP. +- Последний успешный handshake клиента хранится отдельно как долговременный `last seen`: после перезапуска сервера или WireGuard-интерфейса ранее подключавшийся клиент больше не превращается в «Никогда». +- Для обновлений в Аудите фиксируются созданная перед update полная `.wgtbackup`, успешное завершение, полезные ошибки и результат автоматического rollback. +- Срок хранения — 30 дней, дополнительный защитный лимит — 10 000 записей. +- Пароли, коды сброса, приватные ключи WireGuard, PSK, Telegram Bot token, SMTP-пароль, Relay `control_token`, SSH credentials, полные client config и QR в аудит не записываются. + +### Резервное копирование и восстановление + +WGTools использует два уровня backup: + +1. **Автоматическая история конфигурации** перед изменяющими конфиг операциями. +2. **Полная переносимая `.wgtbackup`** для миграции/аварийного восстановления. + +Полная `.wgtbackup` может содержать: + +- конфиги всех обнаруженных WireGuard-интерфейсов и их running/stopped state; +- SQLite WGTools с пользователями/E-mail, настройками, SMTP и записями VPS Relay; +- managed-client metadata, приватные клиентские ключи и PSK; +- группы, расписания/сроки действия и Display name интерфейсов; +- настройки/токен Telegram и SMTP credentials, если они настроены; +- sysctl-состояние forwarding; +- controller/tenant identity Relay, management token и домашний transport private key, необходимые для подключения к сохранившемуся remote tenant. + +Файловая система удалённого VPS внутрь `.wgtbackup` не копируется. Для бесшовного аварийного восстановления Relay Agent/tenant должен продолжать существовать на VPS. + +> Сертификаты Let’s Encrypt из `/etc/letsencrypt` относятся к самому хосту и не копируются в `.wgtbackup`. После переноса WGTools на другой сервер встроенный HTTPS нужно выпустить заново. Обычное удаление WGTools намеренно не трогает `/etc/letsencrypt`, чтобы существующий сертификат можно было продолжить использовать в других сервисах. + +> `.wgtbackup` содержит секреты, включая сохранённые SMTP credentials. Храните такой файл как пароль или приватный SSH-ключ и никогда не прикладывайте его к публичному issue. + +### Обновления + +Администратор загружает доверенный пакет `.bin` в настройках. Автоматическая проверка релизов исходного проекта отключена. + +## Быстрая установка + +```bash +sudo bash install.sh +``` + +Локальный установщик запускает `scripts/install.sh` из текущего каталога исходников. + +Откройте показанный установщиком адрес (обычно `http://IP-СЕРВЕРА:8341`) и создайте первого пользователя. + +WireGuard специально не ставится молча bootstrap-скриптом. На чистом сервере используйте **Сервер → Установить WireGuard**. + +### Проверить код до установки + +```bash +# Pobierz kod WGTools-Extended z własnego repozytorium. +cd WGTools +less install.sh +less scripts/install.sh +less scripts/wgtools-helper +sudo ./scripts/install.sh +``` + +Установка конкретного публичного релиза: + +```bash +git checkout v0.40.4 +sudo ./scripts/install.sh +``` + +## Что устанавливается + +| Путь | Назначение | +|---|---| +| `/opt/wgtools` | Исходники приложения и Python virtualenv | +| `/var/lib/wgtools` | SQLite, session secret, managed-client state, backup и домашние данные Relay | +| `/etc/wgtools/wgtools.env` | Runtime-настройки | +| `/usr/local/libexec/wgtools-helper` | Привилегированный helper веб-приложения | +| `/etc/systemd/system/wgtools*.service` | Web/Telegram/expiry службы WGTools | +| `/etc/wireguard/*.conf` | Пользовательские WireGuard-конфиги | +| `/var/lib/wgtools-relay` | Состояние VPS Relay Agent, если машина используется как Relay VPS | +| `/opt/wgtools-relay` | Код VPS Relay Agent, если машина используется как Relay VPS | + +Отдельный Linux-пользователь не создаётся. Службы работают от root, потому что управляют WireGuard, маршрутизацией, firewall и защищёнными конфигурационными файлами. + +## Сеть и приватность + +В WGTools нет аналитики, рекламы или телеметрии, отправляемой разработчику проекта. Приложение не выгружает ваши WireGuard-ключи, peer list, локальную топологию, пользователей или traffic counters. + +Ожидаемые исходящие соединения ограничены включёнными функциями: + +- **Gitea:** публикация релизов проекта; обновления загружаются администратором вручную. +- **Telegram:** только когда Telegram Bot включён. +- **APT repositories:** установка пакетов на Debian/Ubuntu. + +Подробнее: [PRIVACY.md](PRIVACY.md) и [SECURITY.md](SECURITY.md). + +## Удаление и полная очистка + +Удаление встроено в root-консоль `wgtools`, поэтому для обычного uninstall/cleanup не нужно копировать длинные shell-команды из документации. + +В CLI специально разделены два сценария: + +- **Uninstall WGTools** — удаляет панель, службы, CLI и внутренние Nodes/локальные Relay-home transport, но сохраняет обычный WireGuard и пригодное для повторной установки состояние WGTools. +- **FULL CLEANUP** — разрушительная полная очистка выделенного сервера: удаляются состояние и backup WGTools, Nodes, локальный Relay, WireGuard-интерфейсы/конфиги и пакеты WireGuard. Перед выполнением нужно вручную ввести `DELETE ALL`. Удалённые Relay VPS автоматически не затрагиваются. + +Запустите локальную консоль `wgtools` от `root` и выберите нужный вариант в разделе **Removal**. + +## Безопасность + +WGTools — привилегированное приложение администрирования. Перед публикацией веб-панели за пределами доверенной сети прочитайте [SECURITY.md](SECURITY.md). + +При сообщении об уязвимости не публикуйте приватные ключи, `.wgtbackup`, пароли, bot token или production-конфигурацию в открытом issue. + +## Лицензия + +См. [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..ffc407f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,19 @@ +# Bezpieczeństwo WGTools-Extended + +WGTools-Extended zarządza konfiguracją WireGuard, zaporą i routingiem. Usługi aplikacji działają jako root; uruchamiaj panel tylko w zaufanej sieci zarządzającej lub przez odpowiednio zabezpieczone HTTPS. Domyślne HTTP na porcie 8341 nie powinno być wystawiane bezpośrednio do internetu. + +## Konta i uprawnienia + +Pierwsze konto i konta z poprzedniej instalacji zachowują uprawnienia administratora. Nowe konta nie mają dostępu do żadnej sieci, dopóki administrator go nie przydzieli. Konta ograniczone mogą pracować tylko na przydzielonych sieciach. Zmiany uprawnień i reguł są zapisywane w dzienniku zdarzeń. Mechanizm wymaga dalszej weryfikacji przed zastosowaniem w środowisku produkcyjnym. + +Używaj silnych haseł i włącz MFA. Baza danych, klucz sesji, pliki klientów, konfiguracje WireGuard, kopie zapasowe oraz tokeny integracji zawierają dane wrażliwe i nie powinny być publikowane. + +## Aktualizacje i kopie + +Aktualizacje są inicjowane przez administratora przez wgranie pakietu `.bin`. Pakiet jest kodem wykonywanym jako root: wgrywaj wyłącznie pliki z zaufanego wydania WGTools-Extended. Program sprawdza strukturę i wersję archiwum, tworzy kopię stanu i kopię aplikacji oraz próbuje przywrócić poprzednią wersję w razie błędu. Pakiety nie są obecnie podpisywane kryptograficznie. Niezależna kopia serwera nadal jest potrzebna. + +Zmiany reguł SNAT, nasłuchiwania oraz przekierowań mogą na chwilę restartować WireGuard. Przed wdrożeniem sprawdź reguły zapory i konflikt z regułami zarządzanymi poza programem. + +## Zgłaszanie błędów + +Nie publikuj haseł, kluczy, tokenów, kopii `.wgtbackup` ani szczegółów umożliwiających wykorzystanie błędu. Skontaktuj się prywatnie z administratorem repozytorium projektu. diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..3eefcb9 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +1.0.0 diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/audit.py b/app/core/audit.py new file mode 100644 index 0000000..9aa05b9 --- /dev/null +++ b/app/core/audit.py @@ -0,0 +1,452 @@ +from __future__ import annotations + +import ipaddress +import json +import re +import sqlite3 +import time +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Iterator + +from .settings import DATABASE_PATH + +MAX_AUDIT_ROWS = 10000 +AUDIT_RETENTION_DAYS = 30 +AUDIT_RETENTION_SECONDS = AUDIT_RETENTION_DAYS * 24 * 60 * 60 +SECRET_KEYS = { + "password", + "new_password", + "bot_token", + "token", + "private_key", + "preshared_key", + "psk", + "control_token", + "ssh_password", + "ssh_private_key", + "key_passphrase", + "reset_code", + "verification_code", + "mfa_secret", + "mfa_code", + "totp_secret", + "totp_code", + "recovery_code", + "recovery_codes", +} + + +SECRET_TEXT_PATTERNS = ( + re.compile(r"\b\d{6,12}:[A-Za-z0-9_-]{20,}\b"), + re.compile(r"(? str: + text = str(value or "") + text = SECRET_TEXT_PATTERNS[0].sub("[redacted]", text) + text = SECRET_TEXT_PATTERNS[1].sub("[redacted]", text) + text = SECRET_TEXT_PATTERNS[2].sub(lambda match: f"{match.group(1)}{match.group(2)}[redacted]", text) + return text + + +def _connect() -> sqlite3.Connection: + Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + return conn + + +@contextmanager +def _connection() -> Iterator[sqlite3.Connection]: + conn = _connect() + try: + with conn: + yield conn + finally: + conn.close() + + +def _prune_audit(conn: sqlite3.Connection, now: int | None = None) -> None: + cutoff = int(now or time.time()) - AUDIT_RETENTION_SECONDS + conn.execute("DELETE FROM audit_log WHERE created_at None: + with _connection() as conn: + conn.executescript( + """ + CREATE TABLE IF NOT EXISTS audit_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at INTEGER NOT NULL, + username TEXT NOT NULL, + action TEXT NOT NULL, + object TEXT NOT NULL DEFAULT '', + result TEXT NOT NULL DEFAULT '', + details TEXT NOT NULL DEFAULT '' + ); + CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at DESC); + CREATE TABLE IF NOT EXISTS audit_wg_connection_state ( + interface TEXT NOT NULL, + public_key TEXT NOT NULL, + latest_handshake INTEGER NOT NULL DEFAULT 0, + endpoint TEXT NOT NULL DEFAULT '', + PRIMARY KEY(interface, public_key) + ); + """ + ) + _prune_audit(conn) + + +def _clean_text(value: Any, limit: int = 500) -> str: + text = _redact_text(value).strip() + text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]+", " ", text) + return text[:limit] + + +def _scrub(value: Any, key: str = "") -> Any: + key_l = key.lower() + if any(secret in key_l for secret in SECRET_KEYS): + return "[redacted]" + if isinstance(value, dict): + return {str(k): _scrub(v, str(k)) for k, v in value.items()} + if isinstance(value, list): + return [_scrub(item, key) for item in value[:50]] + if isinstance(value, str): + return _redact_text(value) + if isinstance(value, (int, float, bool)) or value is None: + return value + return str(value) + + +def write_audit( + username: str, + action: str, + *, + object: str = "", + result: str = "ok", + details: dict[str, Any] | None = None, +) -> None: + init_audit_database() + payload = "" + if details: + payload = json.dumps(_scrub(details), ensure_ascii=False, sort_keys=True)[:4000] + with _connection() as conn: + conn.execute( + "INSERT INTO audit_log(created_at,username,action,object,result,details) VALUES(?,?,?,?,?,?)", + ( + int(time.time()), + _clean_text(username, 120) or "system", + _clean_text(action, 160), + _clean_text(object, 240), + _clean_text(result, 240), + payload, + ), + ) + _prune_audit(conn) + + +def list_audit(limit: int = 500) -> list[dict[str, Any]]: + init_audit_database() + limit = min(max(int(limit or 500), 1), 1000) + with _connection() as conn: + rows = conn.execute( + """ + SELECT id,created_at,username,action,object,result,details + FROM audit_log + ORDER BY created_at DESC,id DESC + LIMIT ? + """, + (limit,), + ).fetchall() + return [dict(row) for row in rows] + + +def list_audit_page(*, before_id: int = 0, after_id: int = 0, limit: int = 20) -> dict[str, Any]: + """Read-only, cursor-based history for Telegram. No unredacted details are returned.""" + init_audit_database() + limit = min(max(int(limit), 1), 20) + before_id = max(int(before_id or 0), 0) + after_id = max(int(after_id or 0), 0) + if before_id and after_id: + raise ValueError("Choose one audit cursor") + with _connection() as conn: + if before_id: + rows = conn.execute( + "SELECT id,created_at,username,action,object,result FROM audit_log WHERE id < ? ORDER BY id DESC LIMIT ?", + (before_id, limit), + ).fetchall() + elif after_id: + # Fetch the closest newer records, not the newest records overall. + rows = list(reversed(conn.execute( + "SELECT id,created_at,username,action,object,result FROM audit_log WHERE id > ? ORDER BY id ASC LIMIT ?", + (after_id, limit), + ).fetchall())) + else: + rows = conn.execute( + "SELECT id,created_at,username,action,object,result FROM audit_log ORDER BY id DESC LIMIT ?", + (limit,), + ).fetchall() + items = [dict(row) for row in rows] + if not items: + return {"items": [], "has_older": False, "has_newer": False} + first, last = items[0]["id"], items[-1]["id"] + has_older = conn.execute("SELECT 1 FROM audit_log WHERE id < ? LIMIT 1", (last,)).fetchone() is not None + has_newer = conn.execute("SELECT 1 FROM audit_log WHERE id > ? LIMIT 1", (first,)).fetchone() is not None + return {"items": items, "has_older": has_older, "has_newer": has_newer} + + +def _endpoint_ip(endpoint: Any) -> str: + text = str(endpoint or "").strip() + if not text: + return "" + if text.startswith("[") and "]" in text: + candidate = text[1:text.index("]")] + else: + candidate = text.rsplit(":", 1)[0] if ":" in text else text + try: + return str(ipaddress.ip_address(candidate)) + except ValueError: + return candidate[:120] + + +def record_wireguard_connections( + interface: str, + peers: list[dict[str, Any]], + online_threshold_seconds: int = 180, +) -> None: + init_audit_database() + now = int(time.time()) + fresh_window = max(180, int(online_threshold_seconds or 180)) + reconnect_gap = max(300, fresh_window * 2) + seen_public_keys: set[str] = set() + with _connection() as conn: + for peer in peers: + public_key = str(peer.get("public_key") or "").strip() + if not public_key: + continue + # A configured peer must remain in the durable last-seen state even + # when wg(8) currently reports handshake=0 after an interface or host + # restart. Only remove state when the peer itself disappears. + seen_public_keys.add(public_key) + latest_handshake = int(peer.get("latest_handshake") or 0) + endpoint = str(peer.get("endpoint") or "").strip() + if latest_handshake <= 0 or not endpoint: + continue + previous = conn.execute( + """ + SELECT latest_handshake,endpoint + FROM audit_wg_connection_state + WHERE interface=? AND public_key=? + """, + (interface, public_key), + ).fetchone() + previous_handshake = int(previous["latest_handshake"] or 0) if previous else 0 + previous_endpoint_ip = _endpoint_ip(previous["endpoint"]) if previous else "" + endpoint_ip = _endpoint_ip(endpoint) + if previous and latest_handshake <= previous_handshake and endpoint_ip == previous_endpoint_ip: + continue + conn.execute( + """ + INSERT INTO audit_wg_connection_state(interface,public_key,latest_handshake,endpoint) + VALUES(?,?,?,?) + ON CONFLICT(interface,public_key) DO UPDATE SET + latest_handshake=excluded.latest_handshake, + endpoint=excluded.endpoint + """, + (interface, public_key, latest_handshake, endpoint), + ) + is_fresh = 0 <= now - latest_handshake <= fresh_window + endpoint_changed = bool(previous and endpoint_ip and endpoint_ip != previous_endpoint_ip) + reconnected = bool(previous and latest_handshake - previous_handshake > reconnect_gap) + if not is_fresh or (previous and not endpoint_changed and not reconnected): + continue + name = _clean_text(peer.get("name") or "WireGuard client", 160) + conn.execute( + """ + INSERT INTO audit_log(created_at,username,action,object,result,details) + VALUES(?,?,?,?,?,?) + """, + ( + now, + "system", + "wireguard.client_connected", + f"{interface} · {name}", + f"endpoint {endpoint_ip}" if endpoint_ip else "connected", + json.dumps({"endpoint_ip": endpoint_ip, "handshake_at": latest_handshake}, ensure_ascii=False), + ), + ) + state_rows = conn.execute( + "SELECT public_key FROM audit_wg_connection_state WHERE interface=?", + (interface,), + ).fetchall() + for state in state_rows: + if str(state["public_key"]) not in seen_public_keys: + conn.execute( + "DELETE FROM audit_wg_connection_state WHERE interface=? AND public_key=?", + (interface, str(state["public_key"])), + ) + _prune_audit(conn, now) + +def wireguard_last_seen(interface: str, public_key: str, name: str = "") -> dict[str, Any] | None: + """Return durable last-seen state for a configured WireGuard peer. + + audit_wg_connection_state is intentionally not subject to the 30-day audit + retention window. For installations affected by the old state-pruning bug, + a recent client_connected audit event is used once as a migration fallback + and is then promoted back into the durable state table. + """ + init_audit_database() + iface = str(interface or "").strip() + key = str(public_key or "").strip() + if not iface or not key: + return None + with _connection() as conn: + row = conn.execute( + """ + SELECT latest_handshake,endpoint + FROM audit_wg_connection_state + WHERE interface=? AND public_key=? + """, + (iface, key), + ).fetchone() + if row and int(row["latest_handshake"] or 0) > 0: + return { + "latest_handshake": int(row["latest_handshake"] or 0), + "endpoint": str(row["endpoint"] or ""), + "source": "state", + } + + peer_name = _clean_text(name, 160) + if not peer_name: + return None + event = conn.execute( + """ + SELECT created_at,details + FROM audit_log + WHERE action='wireguard.client_connected' AND object=? + ORDER BY created_at DESC,id DESC + LIMIT 1 + """, + (f"{iface} · {peer_name}",), + ).fetchone() + if not event: + return None + handshake_at = int(event["created_at"] or 0) + endpoint = "" + try: + details = json.loads(str(event["details"] or "{}")) + handshake_at = int(details.get("handshake_at") or handshake_at) + endpoint = str(details.get("endpoint_ip") or "") + except (TypeError, ValueError, json.JSONDecodeError): + pass + if handshake_at <= 0: + return None + conn.execute( + """ + INSERT INTO audit_wg_connection_state(interface,public_key,latest_handshake,endpoint) + VALUES(?,?,?,?) + ON CONFLICT(interface,public_key) DO UPDATE SET + latest_handshake=MAX(audit_wg_connection_state.latest_handshake, excluded.latest_handshake), + endpoint=CASE + WHEN excluded.latest_handshake>=audit_wg_connection_state.latest_handshake THEN excluded.endpoint + ELSE audit_wg_connection_state.endpoint + END + """, + (iface, key, handshake_at, endpoint), + ) + return {"latest_handshake": handshake_at, "endpoint": endpoint, "source": "audit"} + + +def merge_wireguard_last_seen(interface: str, peers: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Fill missing runtime handshakes from durable history in one DB session. + + The previous implementation opened/initialized SQLite once for every + offline peer. Clients and Dashboard call this on every refresh, so a + handful of offline peers could make navigation feel much heavier than the + actual WireGuard snapshot. + """ + missing = [ + peer for peer in peers + if int(peer.get("latest_handshake") or 0) <= 0 and str(peer.get("public_key") or "").strip() + ] + if not missing: + return peers + + init_audit_database() + iface = str(interface or "").strip() + if not iface: + return peers + + with _connection() as conn: + rows = conn.execute( + """ + SELECT public_key,latest_handshake,endpoint + FROM audit_wg_connection_state + WHERE interface=? + """, + (iface,), + ).fetchall() + states = {str(row["public_key"]): row for row in rows} + + for peer in missing: + key = str(peer.get("public_key") or "").strip() + row = states.get(key) + handshake_at = int(row["latest_handshake"] or 0) if row else 0 + endpoint = str(row["endpoint"] or "") if row else "" + + if handshake_at <= 0: + peer_name = _clean_text(peer.get("name") or "", 160) + if peer_name: + event = conn.execute( + """ + SELECT created_at,details + FROM audit_log + WHERE action='wireguard.client_connected' AND object=? + ORDER BY created_at DESC,id DESC + LIMIT 1 + """, + (f"{iface} · {peer_name}",), + ).fetchone() + if event: + handshake_at = int(event["created_at"] or 0) + try: + details = json.loads(str(event["details"] or "{}")) + handshake_at = int(details.get("handshake_at") or handshake_at) + endpoint = str(details.get("endpoint_ip") or "") + except (TypeError, ValueError, json.JSONDecodeError): + pass + if handshake_at > 0: + conn.execute( + """ + INSERT INTO audit_wg_connection_state(interface,public_key,latest_handshake,endpoint) + VALUES(?,?,?,?) + ON CONFLICT(interface,public_key) DO UPDATE SET + latest_handshake=MAX(audit_wg_connection_state.latest_handshake, excluded.latest_handshake), + endpoint=CASE + WHEN excluded.latest_handshake>=audit_wg_connection_state.latest_handshake THEN excluded.endpoint + ELSE audit_wg_connection_state.endpoint + END + """, + (iface, key, handshake_at, endpoint), + ) + + if handshake_at <= 0: + continue + peer["latest_handshake"] = handshake_at + peer["last_seen_historical"] = True + if endpoint: + peer["last_seen_endpoint"] = endpoint + return peers diff --git a/app/core/auth.py b/app/core/auth.py new file mode 100644 index 0000000..0080e1a --- /dev/null +++ b/app/core/auth.py @@ -0,0 +1,529 @@ +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import re +import secrets +import sqlite3 +import struct +import time +from pathlib import Path +from typing import Any +from urllib.parse import quote, urlencode + +from .mail_config import normalize_email +from .settings import DATABASE_PATH, SESSION_KEY_FILE + +PBKDF2_ITERATIONS = 390_000 +TOTP_DIGITS = 6 +TOTP_PERIOD = 30 +TOTP_WINDOW = 1 +RECOVERY_CODE_COUNT = 10 +RECOVERY_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" + + +def _connect() -> sqlite3.Connection: + Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA foreign_keys=ON") + return conn + + +def init_database() -> None: + with _connect() as conn: + conn.executescript( + """ + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL COLLATE NOCASE UNIQUE, + email TEXT NOT NULL DEFAULT '', + password_hash TEXT NOT NULL, + salt TEXT NOT NULL, + iterations INTEGER NOT NULL, + session_version INTEGER NOT NULL DEFAULT 1, + mfa_enabled INTEGER NOT NULL DEFAULT 0, + mfa_secret TEXT NOT NULL DEFAULT '', + mfa_recovery_codes TEXT NOT NULL DEFAULT '[]', + mfa_confirmed_at INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + last_login INTEGER + ); + """ + ) + columns = {str(row[1]) for row in conn.execute("PRAGMA table_info(users)").fetchall()} + if "email" not in columns: + conn.execute("ALTER TABLE users ADD COLUMN email TEXT NOT NULL DEFAULT ''") + if "session_version" not in columns: + conn.execute("ALTER TABLE users ADD COLUMN session_version INTEGER NOT NULL DEFAULT 1") + if "mfa_enabled" not in columns: + conn.execute("ALTER TABLE users ADD COLUMN mfa_enabled INTEGER NOT NULL DEFAULT 0") + if "mfa_secret" not in columns: + conn.execute("ALTER TABLE users ADD COLUMN mfa_secret TEXT NOT NULL DEFAULT ''") + if "mfa_recovery_codes" not in columns: + conn.execute("ALTER TABLE users ADD COLUMN mfa_recovery_codes TEXT NOT NULL DEFAULT '[]'") + if "mfa_confirmed_at" not in columns: + conn.execute("ALTER TABLE users ADD COLUMN mfa_confirmed_at INTEGER NOT NULL DEFAULT 0") + conn.execute( + "CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_unique ON users(lower(email)) WHERE email<>''" + ) + conn.execute("CREATE TABLE IF NOT EXISTS user_access (user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, role TEXT NOT NULL, interfaces TEXT NOT NULL DEFAULT '[]')") + access_columns = {str(row[1]) for row in conn.execute("PRAGMA table_info(user_access)")} + if 'permissions' not in access_columns: + conn.execute("ALTER TABLE user_access ADD COLUMN permissions TEXT NOT NULL DEFAULT '{}'") + + +def get_user_access(user_id: int) -> dict[str, Any]: + init_database() + with _connect() as conn: + row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone() + if row is None: + return {"role": "admin", "interfaces": [], "permissions": {}} # Existing installations keep their access. + interfaces = json.loads(row["interfaces"]) + permissions = json.loads(row["permissions"]) + # Accounts configured before per-action permissions retain their access. + if not permissions: + permissions = {iface: ['add', 'edit', 'forward'] for iface in interfaces} + return {"role": row["role"], "interfaces": interfaces, "permissions": permissions} + + +def set_user_access(user_id: int, role: str, interfaces: list[str], permissions: dict[str, list[str]] | None = None) -> dict[str, Any]: + if role not in {"admin", "user"}: + raise ValueError("Nieprawidłowa rola") + if len(interfaces) > 100 or any(not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", i) or i.lower().startswith(("wgrly", "wgnode")) for i in interfaces): + raise ValueError("Nieprawidłowa nazwa interfejsu") + if permissions is None: + permissions = {iface: ['add', 'edit', 'forward'] for iface in interfaces} + if set(permissions) != set(interfaces) or any(not isinstance(actions, list) or any(action not in {'add', 'edit', 'forward'} for action in actions) for actions in permissions.values()): + raise ValueError("Nieprawidłowe uprawnienia sieci") + init_database() + with _connect() as conn: + if not conn.execute("SELECT 1 FROM users WHERE id=?", (user_id,)).fetchone(): + raise ValueError("Użytkownik nie istnieje") + conn.execute("INSERT INTO user_access(user_id,role,interfaces,permissions) VALUES(?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET role=excluded.role,interfaces=excluded.interfaces,permissions=excluded.permissions", (user_id, role, json.dumps(sorted(set(interfaces))), json.dumps(permissions))) + return get_user_access(user_id) + + +def load_session_secret() -> str: + path = Path(SESSION_KEY_FILE) + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(secrets.token_hex(32), encoding="utf-8") + path.chmod(0o600) + value = path.read_text(encoding="utf-8").strip() + if len(value) < 32: + raise RuntimeError("WGTools session secret is invalid") + return value + + +def _normalize_username(username: str) -> str: + value = username.strip() + if not (3 <= len(value) <= 64): + raise ValueError("Username must contain 3 to 64 characters") + if any(ord(ch) < 32 for ch in value): + raise ValueError("Username contains invalid characters") + return value + + +def _derive_password(password: str, salt: bytes, iterations: int = PBKDF2_ITERATIONS) -> str: + digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations) + return base64.b64encode(digest).decode("ascii") + + +def _hash_password(password: str, salt: bytes, iterations: int = PBKDF2_ITERATIONS) -> str: + if len(password) < 8: + raise ValueError("Password must contain at least 8 characters") + return _derive_password(password, salt, iterations) + + +def _public_user(row: sqlite3.Row | dict[str, Any]) -> dict[str, Any]: + source = dict(row) + recovery = _load_recovery_hashes(str(source.get("mfa_recovery_codes") or "[]")) + return { + "id": int(source["id"]), + "username": str(source["username"]), + "email": str(source.get("email") or ""), + "session_version": int(source.get("session_version") or 1), + "mfa_enabled": bool(int(source.get("mfa_enabled") or 0)), + "mfa_recovery_remaining": len(recovery), + "mfa_confirmed_at": int(source.get("mfa_confirmed_at") or 0), + "created_at": int(source.get("created_at") or 0), + "last_login": int(source.get("last_login") or 0) or None, + } + + +def user_count() -> int: + init_database() + with _connect() as conn: + row = conn.execute("SELECT COUNT(*) AS c FROM users").fetchone() + return int(row["c"]) + + +def create_user(username: str, password: str, email: str = "") -> dict[str, Any]: + init_database() + username = _normalize_username(username) + email = normalize_email(email, allow_empty=True) + salt = secrets.token_bytes(18) + encoded_salt = base64.b64encode(salt).decode("ascii") + password_hash = _hash_password(password, salt) + now = int(time.time()) + try: + with _connect() as conn: + cur = conn.execute( + "INSERT INTO users(username,email,password_hash,salt,iterations,session_version,created_at) VALUES(?,?,?,?,?,?,?)", + (username, email, password_hash, encoded_salt, PBKDF2_ITERATIONS, 1, now), + ) + user_id = int(cur.lastrowid) + if conn.execute("SELECT COUNT(*) FROM users").fetchone()[0] > 1: + conn.execute("INSERT INTO user_access(user_id,role,interfaces) VALUES(?, 'user', '[]')", (user_id,)) + except sqlite3.IntegrityError as exc: + text = str(exc).lower() + if "email" in text or "idx_users_email_unique" in text: + raise ValueError("A user with this email already exists") from exc + raise ValueError("A user with this name already exists") from exc + return get_user(user_id) or { + "id": user_id, + "username": username, + "email": email, + "created_at": now, + "last_login": None, + "session_version": 1, + "mfa_enabled": False, + "mfa_recovery_remaining": 0, + "mfa_confirmed_at": 0, + } + + +def get_user(user_id: int) -> dict[str, Any] | None: + init_database() + with _connect() as conn: + row = conn.execute( + """ + SELECT id,username,email,session_version,mfa_enabled,mfa_recovery_codes,mfa_confirmed_at,created_at,last_login + FROM users WHERE id=? + """, + (int(user_id),), + ).fetchone() + return _public_user(row) if row else None + + +def list_users() -> list[dict[str, Any]]: + init_database() + with _connect() as conn: + rows = conn.execute( + """ + SELECT id,username,email,session_version,mfa_enabled,mfa_recovery_codes,mfa_confirmed_at,created_at,last_login + FROM users ORDER BY username COLLATE NOCASE + """ + ).fetchall() + return [_public_user(row) for row in rows] + + +def authenticate(username: str, password: str, *, record_login: bool = True) -> dict[str, Any] | None: + init_database() + with _connect() as conn: + row = conn.execute( + """ + SELECT id,username,email,password_hash,salt,iterations,session_version, + mfa_enabled,mfa_recovery_codes,mfa_confirmed_at,created_at,last_login + FROM users WHERE username=? COLLATE NOCASE + """, + (username.strip(),), + ).fetchone() + if not row: + # Keep the code path somewhat similar for unknown users. + hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), b"wgtools-invalid-user", PBKDF2_ITERATIONS) + return None + salt = base64.b64decode(row["salt"]) + candidate = _derive_password(password, salt, int(row["iterations"])) + if not hmac.compare_digest(candidate, row["password_hash"]): + return None + user = _public_user(row) + if record_login: + now = int(time.time()) + conn.execute("UPDATE users SET last_login=? WHERE id=?", (now, int(row["id"]))) + user["last_login"] = now + return user + + +def record_login_success(user_id: int) -> dict[str, Any]: + init_database() + now = int(time.time()) + with _connect() as conn: + cur = conn.execute("UPDATE users SET last_login=? WHERE id=?", (now, int(user_id))) + if cur.rowcount != 1: + raise ValueError("User not found") + user = get_user(user_id) + if not user: + raise ValueError("User not found") + user["last_login"] = now + return user + + +def verify_password(user_id: int, password: str) -> bool: + init_database() + with _connect() as conn: + row = conn.execute("SELECT password_hash,salt,iterations FROM users WHERE id=?", (int(user_id),)).fetchone() + if not row: + return False + salt = base64.b64decode(row["salt"]) + candidate = _derive_password(password, salt, int(row["iterations"])) + return hmac.compare_digest(candidate, row["password_hash"]) + + +def set_password(user_id: int, password: str) -> None: + init_database() + salt = secrets.token_bytes(18) + encoded_salt = base64.b64encode(salt).decode("ascii") + password_hash = _hash_password(password, salt) + with _connect() as conn: + cur = conn.execute( + "UPDATE users SET password_hash=?,salt=?,iterations=?,session_version=session_version+1 WHERE id=?", + (password_hash, encoded_salt, PBKDF2_ITERATIONS, int(user_id)), + ) + if cur.rowcount != 1: + raise ValueError("User not found") + reset_table = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='password_reset_codes'").fetchone() + if reset_table: + conn.execute( + "UPDATE password_reset_codes SET consumed_at=? WHERE user_id=? AND consumed_at=0", + (int(time.time()), int(user_id)), + ) + + +def find_user_by_identifier(identifier: str) -> dict[str, Any] | None: + init_database() + value = str(identifier or "").strip() + if not value: + return None + with _connect() as conn: + row = conn.execute( + """ + SELECT id,username,email,session_version,mfa_enabled,mfa_recovery_codes,mfa_confirmed_at,created_at,last_login + FROM users + WHERE username=? COLLATE NOCASE OR email=? COLLATE NOCASE + LIMIT 1 + """, + (value, value), + ).fetchone() + return _public_user(row) if row else None + + +def update_user_email(user_id: int, email: str) -> dict[str, Any]: + init_database() + normalized = normalize_email(email, allow_empty=True) + try: + with _connect() as conn: + cur = conn.execute("UPDATE users SET email=? WHERE id=?", (normalized, int(user_id))) + if cur.rowcount != 1: + raise ValueError("User not found") + reset_table = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='password_reset_codes'").fetchone() + if reset_table: + conn.execute( + "UPDATE password_reset_codes SET consumed_at=? WHERE user_id=? AND consumed_at=0", + (int(time.time()), int(user_id)), + ) + except sqlite3.IntegrityError as exc: + raise ValueError("A user with this email already exists") from exc + user = get_user(user_id) + if not user: + raise ValueError("User not found") + return user + + +def _normalize_totp_code(code: str) -> str: + return "".join(ch for ch in str(code or "") if ch.isdigit()) + + +def _decode_totp_secret(secret: str) -> bytes: + value = "".join(str(secret or "").split()).upper() + padding = "=" * ((8 - len(value) % 8) % 8) + return base64.b32decode(value + padding, casefold=True) + + +def _totp_at(secret: str, timestamp: int) -> str: + key = _decode_totp_secret(secret) + counter = int(timestamp) // TOTP_PERIOD + digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest() + offset = digest[-1] & 0x0F + binary = struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF + return str(binary % (10 ** TOTP_DIGITS)).zfill(TOTP_DIGITS) + + +def verify_totp(secret: str, code: str, *, now: int | None = None, window: int = TOTP_WINDOW) -> bool: + normalized = _normalize_totp_code(code) + if len(normalized) != TOTP_DIGITS: + return False + current = int(now or time.time()) + for offset in range(-abs(int(window)), abs(int(window)) + 1): + expected = _totp_at(secret, current + offset * TOTP_PERIOD) + if hmac.compare_digest(expected, normalized): + return True + return False + + +def generate_mfa_secret() -> str: + return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=") + + +def mfa_provisioning_uri(username: str, secret: str) -> str: + label = quote(f"WGTools:{username}", safe="") + query = urlencode( + { + "secret": secret, + "issuer": "WGTools", + "algorithm": "SHA1", + "digits": str(TOTP_DIGITS), + "period": str(TOTP_PERIOD), + } + ) + return f"otpauth://totp/{label}?{query}" + + +def _new_recovery_codes() -> list[str]: + codes: list[str] = [] + for _ in range(RECOVERY_CODE_COUNT): + raw = "".join(secrets.choice(RECOVERY_ALPHABET) for _ in range(12)) + codes.append(f"{raw[:4]}-{raw[4:8]}-{raw[8:]}") + return codes + + +def _normalize_recovery_code(code: str) -> str: + return "".join(ch for ch in str(code or "").upper() if ch.isalnum()) + + +def _recovery_hash(code: str) -> str: + return hashlib.sha256(_normalize_recovery_code(code).encode("ascii", errors="ignore")).hexdigest() + + +def _load_recovery_hashes(value: str) -> list[str]: + try: + data = json.loads(value or "[]") + except Exception: + return [] + if not isinstance(data, list): + return [] + return [str(item) for item in data if isinstance(item, str) and item] + + +def begin_mfa_setup(user_id: int) -> dict[str, Any]: + init_database() + secret = generate_mfa_secret() + with _connect() as conn: + row = conn.execute("SELECT username,mfa_enabled FROM users WHERE id=?", (int(user_id),)).fetchone() + if not row: + raise ValueError("User not found") + if bool(int(row["mfa_enabled"] or 0)): + raise ValueError("MFA is already enabled") + conn.execute( + "UPDATE users SET mfa_secret=?,mfa_recovery_codes='[]',mfa_confirmed_at=0 WHERE id=?", + (secret, int(user_id)), + ) + username = str(row["username"]) + return {"secret": secret, "uri": mfa_provisioning_uri(username, secret), "username": username} + + +def confirm_mfa_setup(user_id: int, code: str) -> dict[str, Any]: + init_database() + with _connect() as conn: + row = conn.execute("SELECT mfa_secret,mfa_enabled FROM users WHERE id=?", (int(user_id),)).fetchone() + if not row: + raise ValueError("User not found") + if bool(int(row["mfa_enabled"] or 0)): + raise ValueError("MFA is already enabled") + secret = str(row["mfa_secret"] or "") + if not secret: + raise ValueError("MFA setup has not been started") + if not verify_totp(secret, code): + raise ValueError("Invalid authentication code") + recovery_codes = _new_recovery_codes() + hashes = json.dumps([_recovery_hash(item) for item in recovery_codes], separators=(",", ":")) + now = int(time.time()) + conn.execute( + """ + UPDATE users + SET mfa_enabled=1,mfa_recovery_codes=?,mfa_confirmed_at=?,session_version=session_version+1 + WHERE id=? + """, + (hashes, now, int(user_id)), + ) + version = int(conn.execute("SELECT session_version FROM users WHERE id=?", (int(user_id),)).fetchone()[0]) + return {"recovery_codes": recovery_codes, "session_version": version} + + +def verify_user_mfa(user_id: int, code: str, *, consume_recovery: bool = True) -> dict[str, Any]: + init_database() + with _connect() as conn: + row = conn.execute( + "SELECT mfa_enabled,mfa_secret,mfa_recovery_codes FROM users WHERE id=?", (int(user_id),) + ).fetchone() + if not row: + raise ValueError("User not found") + if not bool(int(row["mfa_enabled"] or 0)): + return {"ok": True, "method": "disabled", "recovery_remaining": 0} + secret = str(row["mfa_secret"] or "") + if secret and verify_totp(secret, code): + hashes = _load_recovery_hashes(str(row["mfa_recovery_codes"] or "[]")) + return {"ok": True, "method": "totp", "recovery_remaining": len(hashes)} + normalized = _normalize_recovery_code(code) + if not normalized: + return {"ok": False, "method": "", "recovery_remaining": 0} + candidate = _recovery_hash(normalized) + hashes = _load_recovery_hashes(str(row["mfa_recovery_codes"] or "[]")) + matched = next((item for item in hashes if hmac.compare_digest(item, candidate)), None) + if not matched: + return {"ok": False, "method": "", "recovery_remaining": len(hashes)} + if consume_recovery: + remaining = [item for item in hashes if not hmac.compare_digest(item, candidate)] + conn.execute( + "UPDATE users SET mfa_recovery_codes=? WHERE id=?", + (json.dumps(remaining, separators=(",", ":")), int(user_id)), + ) + hashes = remaining + return {"ok": True, "method": "recovery", "recovery_remaining": len(hashes)} + + +def disable_mfa(user_id: int) -> dict[str, Any]: + init_database() + with _connect() as conn: + cur = conn.execute( + """ + UPDATE users + SET mfa_enabled=0,mfa_secret='',mfa_recovery_codes='[]',mfa_confirmed_at=0, + session_version=session_version+1 + WHERE id=? + """, + (int(user_id),), + ) + if cur.rowcount != 1: + raise ValueError("User not found") + version = int(conn.execute("SELECT session_version FROM users WHERE id=?", (int(user_id),)).fetchone()[0]) + return {"session_version": version} + + +def regenerate_mfa_recovery_codes(user_id: int) -> dict[str, Any]: + init_database() + recovery_codes = _new_recovery_codes() + hashes = json.dumps([_recovery_hash(item) for item in recovery_codes], separators=(",", ":")) + with _connect() as conn: + row = conn.execute("SELECT mfa_enabled FROM users WHERE id=?", (int(user_id),)).fetchone() + if not row: + raise ValueError("User not found") + if not bool(int(row["mfa_enabled"] or 0)): + raise ValueError("MFA is not enabled") + conn.execute("UPDATE users SET mfa_recovery_codes=? WHERE id=?", (hashes, int(user_id))) + return {"recovery_codes": recovery_codes} + + +def delete_user(user_id: int) -> None: + init_database() + with _connect() as conn: + count = int(conn.execute("SELECT COUNT(*) FROM users").fetchone()[0]) + if count <= 1: + raise ValueError("The last user cannot be deleted") + cur = conn.execute("DELETE FROM users WHERE id=?", (int(user_id),)) + if cur.rowcount != 1: + raise ValueError("User not found") diff --git a/app/core/help_content.py b/app/core/help_content.py new file mode 100644 index 0000000..bf820b2 --- /dev/null +++ b/app/core/help_content.py @@ -0,0 +1,841 @@ +from __future__ import annotations + + +HELP = {'ru': [{'id': 'dashboard', + 'title': 'Главная', + 'intro': 'Главная — это быстрый ответ на три вопроса: работает ли WireGuard, кто сейчас подключён и всё ли нормально с самим сервером.', + 'topics': [{'title': 'С чего начать', + 'paragraphs': ['В верхней панели выбран текущий интерфейс WireGuard. Если интерфейсов несколько, все страницы WGTools работают ' + 'именно с выбранным интерфейсом.'], + 'bullets': ['«Пуск» запускает WireGuard, «Стоп» останавливает его, «Перезапуск» быстро перезапускает интерфейс.', + 'После перезапуска телефоны и компьютеры обычно подключаются снова автоматически.', + 'Если WireGuard остановлен, клиенты этого интерфейса не смогут подключиться.'], + 'example_title': 'Пример', + 'example_lines': ['wg0 · Home · 10.0.0.1/24 · UDP 51820'], + 'warning': ''}, + {'title': 'CPU, память, сеть и время работы', + 'paragraphs': ['Эти показатели относятся ко всей машине Debian, на которой установлен WGTools.'], + 'bullets': ['CPU показывает текущую загрузку процессора.', + 'Память показывает занятую и доступную RAM.', + 'Сеть показывает текущую скорость приёма и передачи на внешнем интерфейсе.', + 'Uptime показывает, сколько сервер работает после последней перезагрузки.', + 'Суточные графики помогают заметить необычную нагрузку или постоянный сетевой трафик.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Кто подключён', + 'paragraphs': ['WireGuard не держит постоянную «сессию» как обычный веб-сайт. WGTools считает клиента онлайн, если его ' + 'последний handshake был недавно.'], + 'bullets': ['Handshake — последний успешный обмен служебными пакетами WireGuard.', + 'Endpoint — внешний IP и порт, с которого клиент сейчас выходит в Интернет.', + '«Никогда» означает, что сервер ещё не видел успешного подключения этого клиента.', + 'Быстрый поиск фильтрует список по имени, VPN-адресу, типу и Endpoint.'], + 'example_title': 'Пример', + 'example_lines': ['Телефон · 10.0.0.3/32', 'Endpoint: 203.0.113.25:63275', 'Handshake: 18 сек назад'], + 'warning': ''}, + {'title': 'Трафик', + 'paragraphs': ['WGTools хранит накопленные RX/TX отдельно от мгновенных счётчиков WireGuard, поэтому статистика не пропадает ' + 'после перезапуска интерфейса или сервера.'], + 'bullets': ['Карточка «Трафик» показывает общий объём данных выбранного интерфейса.', + 'У каждого клиента также хранится его накопленный RX/TX.', + '«Сбросить» начинает общий и клиентские счётчики заново с текущего момента.', + 'RX/TX в карточке «Сеть» — это скорость прямо сейчас, а не накопленный объём.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Несколько WireGuard-интерфейсов', + 'paragraphs': ['На одном сервере можно держать несколько независимых VPN, например домашний и рабочий.'], + 'bullets': ['Переключение в верхней панели не изменяет конфигурацию — оно только выбирает, с каким интерфейсом сейчас работают ' + 'Главная, Сервер и Клиенты.', + 'У каждого интерфейса свои адреса, порт, клиенты, маршруты и правила доступа.'], + 'example_title': 'Пример', + 'example_lines': ['wg0 · Home · 10.0.0.1/24', 'wg1 · Work · 10.0.1.1/24'], + 'warning': ''}]}, + {'id': 'server', + 'title': 'Сервер', + 'intro': 'Раздел «Сервер» отвечает за сам WireGuard: интерфейсы, маршруты, доступ к сетям, объединение нескольких WGTools через Nodes и ' + 'работу через публичный VPS Relay.', + 'topics': [{'title': 'Что такое VPN-сеть и интерфейс WireGuard', + 'paragraphs': ['Интерфейс WireGuard можно представить как отдельную виртуальную сетевую карту. У неё есть своя маленькая ' + 'VPN-сеть, а каждому клиенту выдаётся адрес из этой сети.'], + 'bullets': ['Системное имя обычно выглядит как wg0, wg1 и т. д.', + 'Понятное имя, например Home или Office, нужно только для удобства.', + 'ListenPort — UDP-порт, на который подключаются клиенты.', + 'MTU обычно можно оставить «Авто»; вручную его меняют только при проблемах с конкретной сетью, LTE или PPPoE.'], + 'example_title': 'Пример', + 'example_lines': ['VPN-сеть: 10.0.0.0/24', 'Адрес сервера: 10.0.0.1/24', 'Клиенты: 10.0.0.2, 10.0.0.3, ...', 'Порт: UDP 51820'], + 'warning': ''}, + {'title': 'Первый запуск и новые интерфейсы', + 'paragraphs': ['На чистой Debian WGTools может установить WireGuard и создать первый интерфейс через мастер. После этого можно ' + 'добавить wg1, wg2 и другие.'], + 'bullets': ['WGTools предлагает свободную VPN-сеть, UDP-порт и таблицу policy routing.', + 'Перед созданием проверяются пересечения сетей и занятые порты.', + 'Для каждого интерфейса создаются собственные ключи и конфигурация.', + 'Удаление интерфейса сначала делает резервную копию и очищает связанные управляемые данные.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'NAT простыми словами', + 'paragraphs': ['NAT/MASQUERADE нужен, когда VPN-клиент должен выходить в локальную сеть или Интернет от имени самого ' + 'WireGuard-сервера. Для домашней установки это обычно самый простой вариант.'], + 'bullets': ['Если NAT включён, домашнему роутеру обычно не нужен отдельный маршрут обратно к VPN-пулу.', + 'Если NAT выключен и вы хотите настоящую маршрутизацию без подмены адресов, на соседних роутерах должны быть ' + 'обратные маршруты.'], + 'example_title': 'Пример', + 'example_lines': ['Телефон 10.0.0.3 → WGTools 192.168.1.10 → Интернет', 'Домашний роутер видит источник 192.168.1.10'], + 'warning': ''}, + {'title': 'Маршруты и policy routing', + 'paragraphs': ['Маршрут говорит Linux, через какой интерфейс или шлюз искать определённую сеть. Policy routing добавляет ' + 'отдельную таблицу правил для трафика VPN-клиентов.'], + 'bullets': ['Обычной домашней установке отдельная policy table часто не нужна.', + 'Она полезна, если VPN-клиенты должны выходить через конкретный шлюз, другой VPN или отдельный WAN.', + 'WGTools показывает системные маршруты, маршруты Site-to-Site и созданные вручную маршруты отдельно.', + 'Пользовательские маршруты можно добавлять, изменять и удалять из интерфейса.'], + 'example_title': 'Пример', + 'example_lines': ['Источник: 10.0.0.0/24', 'Таблица: 200', 'Default via: 192.168.1.1 dev eth0'], + 'warning': ''}, + {'title': 'Firewall и доступ к сетям', + 'paragraphs': ['Firewall определяет не куда отправлять пакет, а разрешён ли ему доступ. Это отдельная вещь от маршрутов.'], + 'bullets': ['Можно разрешать или запрещать доступ конкретному VPN-клиенту или сети.', + 'Правила групп и индивидуальные исключения клиентов собираются WGTools автоматически.', + 'Перед изменениями WGTools делает backup и откатывает конфигурацию, если WireGuard не смог запуститься.'], + 'example_title': 'Пример', + 'example_lines': ['10.0.0.6/32 → запретить → 192.168.1.0/24', 'Остальным клиентам локальная сеть доступна'], + 'warning': ''}, + {'title': 'Site-to-Site: соединяем две обычные сети', + 'paragraphs': ['Site-to-Site нужен, когда через WireGuard подключается не один телефон, а целая удалённая сеть за роутером или ' + 'сервером.'], + 'bullets': ['У такого peer указываются «Удалённые сети». WGTools автоматически создаёт для них маршруты.', + 'Статус online/offline peer не удаляет его маршруты из конфигурации.', + 'На удалённой стороне также должна быть настроена маршрутизация обратно через WireGuard.'], + 'example_title': 'Пример', + 'example_lines': ['Дом: 192.168.1.0/24', + 'Офисный peer: 10.0.0.20/32', + 'Сеть за офисом: 192.168.50.0/24', + 'Результат: устройства дома могут обращаться к 192.168.50.x'], + 'warning': ''}, + {'title': 'WGTools Nodes: связываем несколько WGTools', + 'paragraphs': ['Nodes соединяет несколько установок WGTools отдельным служебным WireGuard-туннелем. Один сервер становится HUB, ' + 'остальные подключаются к нему по одноразовому коду.'], + 'bullets': ['HUB использует один номер порта: UDP для WireGuard и TCP для первоначального защищённого подключения.', + 'После подключения служебная синхронизация идёт внутри интерфейса wgnode0 и не зависит от адреса веб-панели, ' + 'HTTPS-порта или private path.', + 'При подключении WGTools предлагает найденные VPN-, Site-to-Site и локальные сети. Оставьте только те, которые ' + 'действительно хотите опубликовать.', + 'Новая найденная сеть позже не публикуется сама — её нужно явно добавить в «Настройках узла». Если VPN-пул, Site-to-Site или LAN изменились после сохранения, WGTools покажет предупреждение и предложит проверить список.', + 'Опубликованные сети разных узлов не должны пересекаться. Если, например, Home и VPS оба публикуют 10.0.0.0/24, WGTools не даст сохранить такое подключение и покажет конфликт.', + 'В «Подробнее» можно посмотреть сети и клиентов удалённой панели в режиме только чтения.', + 'Публикация сети делает её доступной связанным узлам, поэтому не публикуйте сети, которым не нужен межсайтовый ' + 'доступ.'], + 'example_title': 'Пример: дом + VPS', + 'example_lines': ['HUB: vpn.example.com:51950', + 'Home публикует: 192.168.1.0/24', + 'VPS публикует: 10.20.0.0/24', + 'После pairing обе стороны получают маршруты через wgnode0'], + 'warning': ''}, + {'title': 'VPS Relay: когда у дома нет белого IP', + 'paragraphs': ['VPS Relay нужен, если клиенты не могут напрямую достучаться до WGTools из Интернета, например из-за CGNAT. ' + 'Публичный VPS становится точкой входа, а сам WireGuard-сервер и правила доступа остаются на вашей машине ' + 'WGTools.'], + 'bullets': ['Добавьте VPS по SSH: WGTools сначала проверит ОС, доступ и порты, затем установит Relay Agent.', + 'Один Relay Agent может обслуживать несколько независимых WGTools — подключения и ключи изолированы.', + 'После установки у поддерживаемых клиентов можно выбрать прямое подключение или подключение через Relay.', + 'Удаление VPS из WGTools отключает локальную связь, но оставляет Relay Agent и сохранённый tenant на VPS, поэтому ' + 'его можно подключить повторно.', + 'VPS Relay и Nodes решают разные задачи: Relay даёт публичную точку входа клиентам, Nodes связывает между собой ' + 'несколько WGTools и их сети.'], + 'example_title': 'Пример', + 'example_lines': ['Телефон → публичный VPS → защищённый Relay-транспорт → WGTools дома → нужная сеть'], + 'warning': ''}, + {'title': 'Диагностика', + 'paragraphs': ['Диагностика проверяет состояние WireGuard, IP forwarding, порты, маршруты и связанные системные службы. Она ' + 'полезна, когда клиент не подключается или сеть за VPN недоступна.'], + 'bullets': ['Сначала смотрите, запущен ли интерфейс и есть ли свежий handshake.', + 'Если handshake есть, но адрес не пингуется, обычно проблема уже в маршруте, firewall или обратном пути.', + 'Во вкладке Сервер → Маршрут traceroute показывает каждый отвечающий узел, средний RTT и скачок задержки относительно предыдущего отвечающего hop. Цвет линии и строки помогает сразу увидеть участок, где задержка выросла; неотвечающие служебным пробам узлы показываются нейтрально.', + 'Интерактивную карту можно масштабировать и перетаскивать; нажатие на узел показывает IP, расположение, ASN/провайдера и RTT.', + 'При включённой карте публичные IP узлов геолокируются через ipwho.is, тайлы загружаются с OpenStreetMap; локальные адреса на геолокацию не отправляются.', + 'Traceroute измеряет задержку, а не реальную пропускную способность канала в Мбит/с.', + 'Диагностика не изменяет конфигурацию сама.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Безопасное применение изменений', + 'paragraphs': ['Настройки сервера, маршрутов и firewall применяются с коротким перезапуском WireGuard.'], + 'bullets': ['Перед изменением создаётся резервная копия конфигурации.', + 'Если новая конфигурация не запускается, WGTools старается вернуть предыдущую автоматически.', + 'Активные клиенты во время перезапуска кратковременно отключатся и затем переподключатся.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Вкладка «Конфиг»', + 'paragraphs': ['Это прямой редактор файла /etc/wireguard/<интерфейс>.conf для случаев, которые нельзя выразить обычными формами ' + 'WGTools.'], + 'bullets': ['Используйте его только если понимаете синтаксис WireGuard и команды PostUp/PostDown.', + 'Перед сохранением WGTools проверяет конфигурацию и создаёт backup.', + 'Если WGTools обнаружит нестандартную конфигурацию, часть автоматического редактирования может быть ограничена, ' + 'чтобы не повредить ваши ручные правила.'], + 'example_title': 'Пример', + 'example_lines': ['[Interface]', 'Address = 10.0.0.1/24', 'ListenPort = 51820', '', '[Peer]', 'AllowedIPs = 10.0.0.2/32'], + 'warning': 'PrivateKey, PresharedKey и другие секреты не публикуйте и не отправляйте посторонним.'}]}, + {'id': 'clients', + 'title': 'Клиенты', + 'intro': 'Клиент — это телефон, ноутбук, роутер или другой WireGuard-peer. Здесь создаются конфиги, права доступа, сроки, расписания и ' + 'Site-to-Site подключения.', + 'topics': [{'title': 'Обычный клиент', + 'paragraphs': ['Для телефона или компьютера выбирайте тип «Клиент». WGTools выдаст свободный VPN-адрес и создаст ключи.'], + 'bullets': ['Имя нужно только для удобства в панели.', + 'Endpoint в готовом конфиге — адрес, по которому устройство находит ваш WireGuard-сервер.', + 'DNS можно задать отдельно для клиента или получить из шаблона группы.'], + 'example_title': 'Пример', + 'example_lines': ['Имя: Phone', 'VPN-адрес: 10.0.0.3/32', 'Endpoint: vpn.example.com:51820'], + 'warning': ''}, + {'title': '«Трафик через VPN» и AllowedIPs', + 'paragraphs': ['AllowedIPs в клиентском конфиге определяет, какой трафик устройство отправит в туннель. Это не то же самое, что ' + 'серверные права доступа.'], + 'bullets': ['«Весь трафик» отправляет через VPN и Интернет, и удалённые сети.', + 'Можно отправлять через VPN только нужные сети.', + 'Пресет с исключением локальных сетей удобен, когда клиенту нужен VPN-Интернет, но домашний принтер или роутер ' + 'должны оставаться доступными напрямую.', + 'Серверная политика WGTools всё равно может запретить доступ к сети, даже если она есть в AllowedIPs.'], + 'example_title': 'Пример', + 'example_lines': ['0.0.0.0/0 — весь IPv4-трафик через VPN', '192.168.50.0/24 — только одна удалённая сеть'], + 'warning': ''}, + {'title': 'Группы клиентов', + 'paragraphs': ['Группа позволяет один раз настроить правила и шаблон, а затем использовать их для нескольких клиентов.'], + 'bullets': ['Группа может задавать доступ в Интернет, локальные сети, дополнительные разрешения и запреты.', + 'Также группа хранит шаблон клиентского конфига: маршруты, DNS и Keepalive.', + 'Изменение политики группы применяется на сервере сразу, а уже установленный конфиг на телефоне не меняется сам.', + 'Если нужно обновить клиентский конфиг по новому шаблону группы, примените шаблон и выдайте новый файл или QR.'], + 'example_title': 'Пример', + 'example_lines': ['Группа «Гости»', 'Интернет: разрешён', 'Локальная сеть: запрещена', 'Клиенты: Phone-1, Tablet-1'], + 'warning': ''}, + {'title': 'Индивидуальные права клиента', + 'paragraphs': ['Для отдельного клиента можно наследовать политику группы или задать собственные исключения.'], + 'bullets': ['Разрешение или запрет конкретного адреса у клиента имеет приоритет над общим исключением группы.', + 'Так удобно открыть одному сотруднику сервер, который закрыт остальным членам группы.'], + 'example_title': 'Пример', + 'example_lines': ['Группа запрещает 192.168.1.0/24', 'Клиенту дополнительно разрешено 192.168.1.50/32'], + 'warning': ''}, + {'title': 'Site-to-Site клиент', + 'paragraphs': ['Выбирайте Site-to-Site, если за peer находится целая сеть. В поле удалённых сетей перечислите сети, доступные ' + 'через этот peer.'], + 'bullets': ['WGTools добавит эти сети в серверные маршруты автоматически.', + 'Такие сети затем могут быть опубликованы через Nodes.', + 'Обычному телефону или ноутбуку Site-to-Site не нужен.'], + 'example_title': 'Пример', + 'example_lines': ['Peer роутера: 10.0.0.20/32', 'Удалённая сеть: 192.168.50.0/24'], + 'warning': ''}, + {'title': 'Прямое подключение и VPS Relay', + 'paragraphs': ['Если для текущего интерфейса настроен VPS Relay, клиент можно направить к серверу напрямую или через Relay.'], + 'bullets': ['«Напрямую» подходит, когда WireGuard-порт сервера доступен из Интернета.', + 'Relay полезен за CGNAT или когда прямой входящий UDP недоступен.', + 'Права клиента и его VPN-адрес при этом остаются теми же.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'PSK, изоляция и смена ключей', + 'paragraphs': ['WireGuard уже использует ключи шифрования. Дополнительный PSK добавляет ещё один общий секрет между сервером и ' + 'клиентом.'], + 'bullets': ['Изоляция клиента запрещает ему общаться с другими VPN-адресами того же WireGuard-пула.', + '«Сменить ключи» создаёт новую ключевую пару и новый PSK, если он включён.', + 'После смены ключей старый конфиг перестаёт работать — нужно выдать новый файл или QR.', + 'VPN-адрес, группа, расписание и статистика при смене ключей сохраняются.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Временный доступ', + 'paragraphs': ['Клиенту можно задать срок: 1, 3, 6 часов, 1 день или своё время.'], + 'bullets': ['После окончания срока WGTools либо отключит доступ, сохранив клиента, либо выполнит выбранное действие.', + 'Проверка сроков выполняется автоматически отдельной службой.', + 'Чтобы вернуть сохранённому отключённому клиенту доступ, задайте новый срок или «Без ограничения».'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Расписание доступа', + 'paragraphs': ['Расписание автоматически разрешает и блокирует клиента в выбранные дни и часы без замены его конфига.'], + 'bullets': ['Используется локальное время WireGuard-сервера.', + 'Можно задавать интервалы через полночь, например 22:00–06:00.', + 'Когда разрешённый интервал начинается снова, WGTools возвращает тот же peer.'], + 'example_title': 'Пример', + 'example_lines': ['Пн–Пт: 08:00–19:00'], + 'warning': ''}, + {'title': 'Статус, Endpoint и трафик', + 'paragraphs': ['В таблице видны последний handshake, Endpoint и накопленный RX/TX.'], + 'bullets': ['Свежий handshake означает, что клиент недавно связывался с сервером.', + 'Endpoint может меняться у мобильного телефона при переходе между Wi-Fi и LTE — это нормально.', + 'Быстрый поиск помогает найти клиента по имени, адресу, группе или состоянию.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Конфиг и QR', + 'paragraphs': ['Файл .conf подходит для компьютеров и роутеров, QR удобен для приложения WireGuard на телефоне.'], + 'bullets': ['PrivateKey клиента находится внутри конфига и QR — относитесь к ним как к паролю.', + 'Повторная выдача управляемого клиента использует сохранённые WGTools ключи.', + 'После смены ключей обязательно выдайте новый конфиг.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Изменение и удаление', + 'paragraphs': ['WGTools делает резервную копию перед изменением WireGuard-конфига и применяет изменения через безопасный ' + 'sync/restart.'], + 'bullets': ['При удалении управляемого клиента удаляются его peer, сохранённые ключи и связанные управляемые правила.', + 'Удаление клиента не стирает конфиг, который уже сохранён на телефоне, но этот конфиг больше не сможет ' + 'подключиться.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}]}, + {'id': 'settings', + 'title': 'Настройки', + 'intro': 'Здесь находятся внешний вид WGTools, резервные копии, Telegram, почта, HTTPS, пользователи, аудит и обновления.', + 'topics': [{'title': 'Оформление и язык', + 'paragraphs': ['Можно выбрать светлую, тёмную или системную тему и язык интерфейса.'], + 'bullets': ['«Свернуть панель» оставляет в боковом меню только значки.', + 'Состояние боковой панели хранится в текущем браузере и применяется сразу.', + 'Язык интерфейса сохраняется в WGTools.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Частота обновления статуса', + 'paragraphs': ['Интервал определяет, как часто страницы обновляют состояние клиентов и сервера. Порог Online определяет, ' + 'сколько времени после handshake клиент считается подключённым.'], + 'bullets': [], + 'example_title': 'Пример', + 'example_lines': ['Обновление: 5 сек', 'Online: 180 сек'], + 'warning': ''}, + {'title': 'Автоматические резервные копии', + 'paragraphs': ['Перед опасными изменениями WGTools сохраняет историю WireGuard-конфигураций. Это быстрый способ откатить ' + 'неудачное изменение одного интерфейса.'], + 'bullets': ['Можно настроить количество хранимых копий.', 'Эта история не заменяет полный переносимый backup всего WGTools.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Полный backup и восстановление', + 'paragraphs': ['Файл .wgtbackup предназначен для переезда на новый сервер или аварийного восстановления.'], + 'bullets': ['В него входят конфигурации WireGuard, база пользователей и настроек, группы, данные управляемых клиентов, ' + 'Telegram/SMTP и состояние VPS Relay/Nodes, необходимое для восстановления.', + 'Перед restore WGTools проверяет архив и создаёт страховочную копию текущего состояния.', + 'Если применение восстановленных данных не удалось, выполняется автоматический откат.', + 'После успешного восстановления текущая веб-сессия завершается — войдите пользователем из восстановленной базы.'], + 'example_title': '', + 'example_lines': [], + 'warning': 'В .wgtbackup находятся приватные ключи, PSK, хэши паролей, Telegram-токен и SMTP-пароль. Храните файл как пароль.'}, + {'title': 'Telegram Bot', + 'paragraphs': ['Telegram позволяет проверить сервер и управлять WireGuard без открытия веб-панели.'], + 'bullets': ['Создайте бота через @BotFather и вставьте Bot Token.', + 'Включите бота и отправьте ему /start.', + 'Если ваш Telegram user ID ещё не разрешён, бот покажет числовой ID. Добавьте его в список разрешённых ID.', + 'Бот принимает команды управления только в личном чате.', + 'Через бот доступны состояние сервера, клиенты, создание/удаление, выдача конфига/QR и управление WireGuard.'], + 'example_title': 'Пример', + 'example_lines': ['Endpoint по умолчанию: vpn.example.com', 'DNS: 1.1.1.1, 8.8.8.8'], + 'warning': ''}, + {'title': 'Почта / SMTP и восстановление пароля', + 'paragraphs': ['SMTP нужен для функции «Забыли пароль?» на странице входа.'], + 'bullets': ['Поддерживаются STARTTLS, TLS/SSL и SMTP без шифрования для доверенной локальной сети.', + 'Логин может быть пустым, если ваш SMTP-сервер не требует авторизации.', + 'Пароль сохраняется локально и обратно в браузер не возвращается.', + 'Кнопка теста отправляет письмо на указанный тестовый адрес.', + 'Код восстановления одноразовый, хранится в виде хэша, действует 15 минут и имеет ограничение числа попыток.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Встроенный HTTPS', + 'paragraphs': ['WGTools может сам обслуживать HTTPS без Nginx, Caddy или другого reverse proxy.'], + 'bullets': ['Сначала заполните домен/публичный IP, e-mail, HTTPS-порт и private path, затем нажмите «Получить / обновить сертификат». Эта кнопка одновременно сохраняет введённые настройки.', + 'Пока подходящего сертификата нет, флажок «Включить встроенный HTTPS» недоступен. После успешного выпуска сертификата включите его и нажмите «Сохранить».', + 'Если изменить домен или публичный IP, WGTools попросит получить сертификат для нового адреса перед включением HTTPS.', + 'Для выпуска и автопродления Let’s Encrypt TCP 80 должен быть доступен из Интернета до этого сервера.', + 'Панель работает на выбранном HTTPS-порту, например 443 или 8443.', + 'Private path задаёт адрес панели, например /MyWGTools/. При включённом HTTPS запросы к другим путям получают 404.', + 'WGTools показывает локальную занятость портов и не останавливает чужой веб-сервер.', + 'Сертификат автоматически продлевается отдельным systemd timer.'], + 'example_title': 'Пример', + 'example_lines': ['https://wg.example.com/MyWGTools/'], + 'warning': 'Private path не заменяет пароль. Не публикуйте адрес панели без необходимости и используйте сильные учётные ' + 'данные.'}, + {'title': 'Пользователи', + 'paragraphs': ['Первый пользователь создаётся при первом запуске WGTools. Дополнительных пользователей можно добавить в ' + 'Настройках.'], + 'bullets': ['Сейчас пользователи имеют одинаковые права управления.', + 'Можно менять E-mail и пароль, а также удалять пользователей.', + 'Для своей учётной записи можно включить MFA через Google Authenticator или другое TOTP-приложение. При включении WGTools показывает одноразовый набор резервных кодов.', + 'Если устройство с Authenticator потеряно, root может аварийно отключить MFA для выбранного пользователя через CLI wgtools.', + 'Текущего пользователя и последнего оставшегося пользователя удалить нельзя.', + 'Смена или восстановление пароля, включение или отключение MFA завершает старые веб-сессии этого пользователя.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Аудит', + 'paragraphs': ['Аудит показывает важные действия в панели, Telegram и историю значимых подключений WireGuard.'], + 'bullets': ['Для веб-действий сохраняется имя пользователя WGTools.', + 'Для Telegram сохраняются @username, если доступен, и числовой Telegram ID.', + 'Отмечаются изменения конфигурации, выдача клиентского конфига/QR, обновления и полезные ошибки.', + 'Пароли, приватные ключи, PSK, токены и содержимое конфигов в аудит не записываются.', + 'Журнал хранится ограниченное время и очищается автоматически.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Обновления WGTools', + 'paragraphs': ['WGTools периодически проверяет стабильные GitHub Releases, но никогда не устанавливает обновление без вашего ' + 'подтверждения.'], + 'bullets': ['При наличии новой версии появляется уведомление в боковой панели.', + 'Перед обновлением создаётся полный .wgtbackup и отдельный архив приложения для rollback.', + 'Если новая версия не запустилась, WGTools пытается автоматически вернуть предыдущую.', + 'Версию можно увидеть в шапке/боковой панели и в разделе «О программе».'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Команда wgtools и аварийный доступ', + 'paragraphs': ['После установки доступна команда wgtools от root. Она полезна, если веб-панель недоступна.'], + 'bullets': ['Команда показывает состояние WGTools, WireGuard, Nodes, Telegram, таймеров, локального Relay Agent и текущий URL панели.', + 'Из неё можно запустить, остановить или перезапустить панель и WireGuard, посмотреть логи.', + 'Если ошиблись с HTTPS-портом или private path, CLI позволяет отключить встроенный HTTPS и вернуть HTTP-доступ.', + 'В разделе Security можно аварийно отключить MFA для выбранного пользователя, если потерян доступ к Google Authenticator и резервным кодам.', + 'Пункт «Uninstall WGTools» удаляет панель и её службы, но сохраняет обычный WireGuard и данные для возможной переустановки.', + 'Пункт «FULL CLEANUP» полностью очищает этот сервер от WGTools, локального Relay и WireGuard; перед выполнением требуется ввести DELETE ALL. Удалённые Relay на других VPS не затрагиваются.'], + 'example_title': 'Пример', + 'example_lines': ['root@server:~# wgtools'], + 'warning': ''}, + {'title': 'Где хранятся данные', + 'paragraphs': ['Обычно вручную редактировать эти файлы не требуется, но пути полезны для диагностики и резервного копирования.'], + 'bullets': [], + 'example_title': 'Основные пути', + 'example_lines': ['/etc/wireguard/wg0.conf — конфигурация WireGuard', + '/var/lib/wgtools/wgtools.db — пользователи и настройки', + '/var/lib/wgtools/clients/ — данные управляемых клиентов', + '/var/lib/wgtools/backups/ — история конфигураций', + '/var/lib/wgtools/update-backups/ — rollback-копии обновлений'], + 'warning': ''}]}], + 'en': [{'id': 'dashboard', + 'title': 'Dashboard', + 'intro': 'Dashboard answers three quick questions: is WireGuard running, who is connected, and is the server itself healthy?', + 'topics': [{'title': 'Where to start', + 'paragraphs': ['The top bar shows the currently selected WireGuard interface. If several interfaces exist, the main WGTools ' + 'pages work with the selected one.'], + 'bullets': ['Start brings WireGuard up, Stop takes it down, and Restart briefly restarts the interface.', + 'Phones and computers normally reconnect automatically after a restart.', + 'When the interface is stopped, its clients cannot connect.'], + 'example_title': 'Example', + 'example_lines': ['wg0 · Home · 10.0.0.1/24 · UDP 51820'], + 'warning': ''}, + {'title': 'CPU, memory, network and uptime', + 'paragraphs': ['These values describe the whole Debian host, not just WireGuard.'], + 'bullets': ['CPU shows current processor load.', + 'Memory shows used and total RAM.', + 'Network shows current receive/transmit rate on the external interface.', + 'Uptime is the time since the operating system last booted.', + 'Rolling daily charts help spot unusual load or sustained network activity.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Who is connected', + 'paragraphs': ['WireGuard does not keep a traditional web-style session. WGTools considers a client online when its latest ' + 'handshake is recent enough.'], + 'bullets': ['Handshake is the latest successful WireGuard control exchange.', + 'Endpoint is the public IP and port the client currently uses.', + 'Never means the server has not yet seen a successful handshake from that peer.', + 'Quick search filters by name, VPN address, type and Endpoint.'], + 'example_title': 'Example', + 'example_lines': ['Phone · 10.0.0.3/32', 'Endpoint: 203.0.113.25:63275', 'Handshake: 18 s ago'], + 'warning': ''}, + {'title': 'Traffic', + 'paragraphs': ['WGTools keeps persistent RX/TX totals separately from the temporary counters exposed by WireGuard, so ' + 'statistics survive interface and server restarts.'], + 'bullets': ['The Traffic card shows accumulated data for the selected interface.', + 'Each client also has its own accumulated RX/TX.', + 'Reset starts the interface and client totals again from the current moment.', + 'RX/TX on the Network card is the current speed, not the accumulated total.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Multiple WireGuard interfaces', + 'paragraphs': ['One server can host several independent VPNs, for example Home and Work.'], + 'bullets': ['Switching the top selector does not change configuration; it only chooses what Dashboard, Server and Clients ' + 'currently display.', + 'Every interface has its own addresses, port, clients, routes and access rules.'], + 'example_title': 'Example', + 'example_lines': ['wg0 · Home · 10.0.0.1/24', 'wg1 · Work · 10.0.1.1/24'], + 'warning': ''}]}, + {'id': 'server', + 'title': 'Server', + 'intro': 'Server controls WireGuard itself: interfaces, routing, network access, linking multiple WGTools installations with Nodes, and ' + 'public access through VPS Relay.', + 'topics': [{'title': 'VPN networks and WireGuard interfaces', + 'paragraphs': ['Think of a WireGuard interface as a virtual network card with its own small VPN subnet. Each client receives an ' + 'address from that subnet.'], + 'bullets': ['System names are usually wg0, wg1 and so on.', + 'A display name such as Home or Office is only for convenience.', + 'ListenPort is the UDP port clients connect to.', + 'MTU can normally stay on Auto; set it manually only when a particular network, LTE connection or PPPoE requires ' + 'it.'], + 'example_title': 'Example', + 'example_lines': ['VPN network: 10.0.0.0/24', + 'Server address: 10.0.0.1/24', + 'Clients: 10.0.0.2, 10.0.0.3, ...', + 'Port: UDP 51820'], + 'warning': ''}, + {'title': 'First setup and additional interfaces', + 'paragraphs': ['On a clean Debian host, WGTools can install WireGuard and create the first interface with a guided form. You ' + 'can later add wg1, wg2 and more.'], + 'bullets': ['WGTools suggests a free VPN subnet, UDP port and policy-routing table.', + 'Overlapping networks and occupied ports are checked before creation.', + 'Every interface receives its own keys and configuration.', + 'Deleting an interface creates a backup first and removes its managed data.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'NAT in plain language', + 'paragraphs': ['NAT/MASQUERADE is useful when a VPN client should reach the LAN or Internet using the WireGuard server as its ' + 'visible source. For a typical home setup this is often the simplest option.'], + 'bullets': ['With NAT enabled, the home router normally does not need a separate return route to the VPN subnet.', + 'With NAT disabled, true routed networking requires return routes on the neighboring routers.'], + 'example_title': 'Example', + 'example_lines': ['Phone 10.0.0.3 → WGTools 192.168.1.10 → Internet', 'Home router sees source 192.168.1.10'], + 'warning': ''}, + {'title': 'Routes and policy routing', + 'paragraphs': ['A route tells Linux which interface or gateway leads to a network. Policy routing adds a separate routing table ' + 'for selected traffic, such as traffic from VPN clients.'], + 'bullets': ['A simple home installation often does not need a separate policy table.', + 'It is useful when VPN clients must use a specific gateway, another VPN or a dedicated WAN.', + 'WGTools distinguishes system routes, Site-to-Site routes and manually created routes.', + 'Custom routes can be added, edited and deleted in the UI.'], + 'example_title': 'Example', + 'example_lines': ['Source: 10.0.0.0/24', 'Table: 200', 'Default via: 192.168.1.1 dev eth0'], + 'warning': ''}, + {'title': 'Firewall and network access', + 'paragraphs': ['Firewall rules decide whether traffic is allowed. Routing only decides where traffic goes; these are separate ' + 'concerns.'], + 'bullets': ['You can allow or block a particular VPN client or network.', + 'Group policy and per-client exceptions are generated by WGTools automatically.', + 'Before applying changes, WGTools backs up the configuration and rolls back if WireGuard cannot start.'], + 'example_title': 'Example', + 'example_lines': ['10.0.0.6/32 → block → 192.168.1.0/24', 'Other clients can still reach the LAN'], + 'warning': ''}, + {'title': 'Site-to-Site: connect two normal networks', + 'paragraphs': ['Site-to-Site is for a peer that represents an entire remote network instead of a single phone or laptop.'], + 'bullets': ['Enter the networks behind that peer as Remote Networks and WGTools creates the routes automatically.', + 'A peer going offline does not remove those configured routes.', + 'The remote side also needs a return route through WireGuard.'], + 'example_title': 'Example', + 'example_lines': ['Home: 192.168.1.0/24', + 'Office peer: 10.0.0.20/32', + 'Office LAN: 192.168.50.0/24', + 'Result: home devices can reach 192.168.50.x'], + 'warning': ''}, + {'title': 'WGTools Nodes: link several WGTools servers', + 'paragraphs': ['Nodes connects several WGTools installations through a dedicated internal WireGuard tunnel. One installation ' + 'becomes the HUB and the others join it with a one-time code.'], + 'bullets': ['The HUB uses one port number: UDP for WireGuard and TCP for the initial protected pairing.', + 'After pairing, service synchronization stays inside wgnode0 and does not depend on the web-panel URL, HTTPS port ' + 'or private path.', + 'WGTools pre-fills detected VPN, Site-to-Site and local networks. Keep only the networks you actually want to ' + 'publish.', + 'A network discovered later is not published silently; add it explicitly in Node settings. If a VPN pool, Site-to-Site network or LAN changes after saving, WGTools shows a warning to review the list.', + 'Published networks on different Nodes must not overlap. For example, if Home and VPS both publish 10.0.0.0/24, WGTools blocks the change and identifies the conflict.', + 'Details shows remote networks and clients in read-only mode.', + 'Publishing a network makes it reachable to connected nodes, so publish only what is required.'], + 'example_title': 'Example: home + VPS', + 'example_lines': ['HUB: vpn.example.com:51950', + 'Home publishes: 192.168.1.0/24', + 'VPS publishes: 10.20.0.0/24', + 'After pairing both sides route through wgnode0'], + 'warning': ''}, + {'title': 'VPS Relay: when home has no public IP', + 'paragraphs': ['VPS Relay helps when clients cannot reach WGTools directly from the Internet, for example behind CGNAT. A ' + 'public VPS becomes the entry point while the WireGuard server and access policy stay on your WGTools host.'], + 'bullets': ['Add the VPS over SSH: WGTools checks the host and ports first, then installs the Relay Agent.', + 'One Relay Agent can serve several independent WGTools controllers with isolated connections and keys.', + 'Supported clients can then use a direct connection or VPS Relay.', + 'Removing a VPS from WGTools detaches the local transport but leaves the Relay Agent and saved tenant on the VPS so ' + 'it can be reconnected.', + 'VPS Relay and Nodes solve different problems: Relay provides a public entry point for clients; Nodes links WGTools ' + 'servers and their networks.'], + 'example_title': 'Example', + 'example_lines': ['Phone → public VPS → protected Relay transport → home WGTools → required network'], + 'warning': ''}, + {'title': 'Diagnostics', + 'paragraphs': ['Diagnostics checks WireGuard state, IP forwarding, ports, routes and related system services. It is useful when ' + 'a client cannot connect or a routed network is unreachable.'], + 'bullets': ['First check whether the interface is running and a fresh handshake exists.', + 'If the handshake works but the destination does not, the remaining issue is usually routing, firewall or the ' + 'return path.', + 'The Server → Trace tab shows each responding traceroute hop, average RTT and latency increase versus the previous responding hop. Route/table colors make sharp latency growth easy to spot, while hops that simply do not answer traceroute probes are shown neutrally.', + 'The interactive map supports pan and zoom; clicking a hop shows its IP, approximate location, ASN/provider and RTT.', + 'When the map is enabled, public hop IPs are geolocated through ipwho.is and tiles are loaded from OpenStreetMap; private addresses are not sent for geolocation.', + 'Traceroute measures latency, not real link throughput in Mbit/s.', + 'Diagnostics does not change configuration by itself.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Safe apply', + 'paragraphs': ['Server, route and firewall changes briefly restart WireGuard when needed.'], + 'bullets': ['WGTools creates a configuration backup first.', + 'If the new configuration fails to start, WGTools attempts to restore the previous one automatically.', + 'Connected clients briefly disconnect and normally reconnect on their own.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Config tab', + 'paragraphs': ['This is a direct editor for /etc/wireguard/.conf when you need something the normal WGTools forms do ' + 'not expose.'], + 'bullets': ['Use it only if you understand WireGuard syntax and PostUp/PostDown commands.', + 'WGTools validates and backs up the file before applying it.', + 'When a non-standard configuration is detected, some automatic editing can be limited to avoid damaging manual ' + 'rules.'], + 'example_title': 'Example', + 'example_lines': ['[Interface]', 'Address = 10.0.0.1/24', 'ListenPort = 51820', '', '[Peer]', 'AllowedIPs = 10.0.0.2/32'], + 'warning': 'Do not publish or share PrivateKey, PresharedKey or other secrets.'}]}, + {'id': 'clients', + 'title': 'Clients', + 'intro': 'A client can be a phone, laptop, router or any other WireGuard peer. This page creates configurations, access policies, ' + 'expiration rules, schedules and Site-to-Site links.', + 'topics': [{'title': 'Normal client', + 'paragraphs': ['Use Client for a phone or computer. WGTools allocates a free VPN address and creates the keys.'], + 'bullets': ['The name is only a label inside WGTools.', + 'Endpoint in the generated configuration is the address the device uses to find your WireGuard server.', + 'DNS can be set per client or inherited from a group template.'], + 'example_title': 'Example', + 'example_lines': ['Name: Phone', 'VPN address: 10.0.0.3/32', 'Endpoint: vpn.example.com:51820'], + 'warning': ''}, + {'title': 'Traffic through VPN and AllowedIPs', + 'paragraphs': ['AllowedIPs in the client configuration decides what the device sends into the tunnel. It is separate from ' + 'server-side access policy.'], + 'bullets': ['All traffic sends both Internet and remote-network traffic through the VPN.', + 'You can send only selected networks through the VPN.', + 'The local-network exclusion preset is useful when VPN Internet is wanted but a local printer/router should remain ' + 'direct.', + 'Server policy can still block a destination even when it appears in AllowedIPs.'], + 'example_title': 'Example', + 'example_lines': ['0.0.0.0/0 — all IPv4 traffic through VPN', '192.168.50.0/24 — only one remote network'], + 'warning': ''}, + {'title': 'Client groups', + 'paragraphs': ['A group lets you define policy and a configuration template once and reuse it for several clients.'], + 'bullets': ['Groups can control Internet access, local-network access and additional allow/deny exceptions.', + 'They can also provide default routes, DNS and Keepalive for new client configurations.', + 'Changing group server policy applies immediately, but a configuration already installed on a phone is not silently ' + 'rewritten.', + 'Apply the current group template and issue a new file/QR when the device configuration itself must change.'], + 'example_title': 'Example', + 'example_lines': ['Group “Guests”', 'Internet: allowed', 'LAN: blocked', 'Members: Phone-1, Tablet-1'], + 'warning': ''}, + {'title': 'Per-client policy', + 'paragraphs': ['A client can inherit the group policy or add its own exceptions.'], + 'bullets': ['A per-client allow or deny exception takes priority over the matching group exception.', + 'This is useful when one employee needs a server that remains blocked for the rest of the group.'], + 'example_title': 'Example', + 'example_lines': ['Group blocks 192.168.1.0/24', 'Client additionally allows 192.168.1.50/32'], + 'warning': ''}, + {'title': 'Site-to-Site client', + 'paragraphs': ['Use Site-to-Site when a peer represents an entire network. Enter the networks reachable behind that peer as ' + 'Remote Networks.'], + 'bullets': ['WGTools adds those networks to server routing automatically.', + 'They can later be selected for publication through Nodes.', + 'A normal phone or laptop does not need Site-to-Site mode.'], + 'example_title': 'Example', + 'example_lines': ['Router peer: 10.0.0.20/32', 'Remote network: 192.168.50.0/24'], + 'warning': ''}, + {'title': 'Direct connection and VPS Relay', + 'paragraphs': ['When VPS Relay is installed for the selected interface, a supported client can connect directly or through ' + 'Relay.'], + 'bullets': ['Direct is best when the server WireGuard port is reachable from the Internet.', + 'Relay helps behind CGNAT or when direct inbound UDP is unavailable.', + 'The client VPN address and access policy remain unchanged.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'PSK, isolation and key rotation', + 'paragraphs': ['WireGuard already uses public/private keys. An optional PSK adds another shared secret between server and ' + 'client.'], + 'bullets': ['Client isolation blocks this client from talking to other VPN addresses in the same WireGuard pool.', + 'Rotate keys creates a new key pair and a new PSK when PSK is enabled.', + 'The old configuration stops working after rotation, so issue a new file or QR.', + 'VPN address, group, schedule and traffic history are preserved.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Temporary access', + 'paragraphs': ['A client can expire after 1, 3 or 6 hours, one day, or a custom date/time.'], + 'bullets': ['When the time is reached, WGTools performs the selected expiration action.', + 'Expiration is enforced automatically by a background service.', + 'To re-enable a saved expired client, set a new expiration time or No limit.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Access schedule', + 'paragraphs': ['A schedule automatically enables and blocks a client on selected days and times without replacing its ' + 'configuration.'], + 'bullets': ['It uses the WireGuard server local time.', + 'Intervals can cross midnight, for example 22:00–06:00.', + 'When the allowed period starts again, WGTools restores the same peer.'], + 'example_title': 'Example', + 'example_lines': ['Mon–Fri: 08:00–19:00'], + 'warning': ''}, + {'title': 'Status, Endpoint and traffic', + 'paragraphs': ['The table shows latest handshake, Endpoint and accumulated RX/TX.'], + 'bullets': ['A recent handshake means the client communicated with the server recently.', + 'A mobile phone Endpoint can change when moving between Wi-Fi and LTE; that is normal.', + 'Quick search filters by name, address, group and state.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Configuration and QR', + 'paragraphs': ['A .conf file is convenient for computers and routers; QR is convenient for the WireGuard mobile app.'], + 'bullets': ['The client PrivateKey is inside the file and QR, so treat them like a password.', + 'Reissuing a managed client configuration uses keys stored by WGTools.', + 'After rotating keys, always issue a new configuration.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Edit and delete', + 'paragraphs': ['WGTools backs up the WireGuard configuration before managed changes and applies them safely.'], + 'bullets': ['Deleting a managed client removes its peer, saved keys and related managed rules.', + 'A configuration already saved on the device is not erased remotely, but it can no longer connect.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}]}, + {'id': 'settings', + 'title': 'Settings', + 'intro': 'Settings contains appearance, backups, Telegram, mail, HTTPS, users, audit and application updates.', + 'topics': [{'title': 'Appearance and language', + 'paragraphs': ['Choose light, dark or system theme and the interface language.'], + 'bullets': ['Collapse sidebar keeps only icons in the left navigation.', + 'Sidebar state is stored in the current browser and changes immediately.', + 'The interface language is saved by WGTools.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Status refresh', + 'paragraphs': ['Refresh interval controls how often pages update server/client status. Online threshold controls how long after ' + 'a handshake a peer is considered connected.'], + 'bullets': [], + 'example_title': 'Example', + 'example_lines': ['Refresh: 5 s', 'Online: 180 s'], + 'warning': ''}, + {'title': 'Automatic configuration backups', + 'paragraphs': ['Before risky changes, WGTools keeps a history of WireGuard configurations. This is a quick rollback mechanism ' + 'for one interface.'], + 'bullets': ['You can choose how many copies are retained.', 'This history is different from the full portable WGTools backup.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Full backup and restore', + 'paragraphs': ['A .wgtbackup file is for migration to a new server or disaster recovery.'], + 'bullets': ['It contains WireGuard configurations, users/settings database, groups, managed-client data, Telegram/SMTP settings ' + 'and the state needed to restore VPS Relay/Nodes.', + 'Before restore, WGTools validates the archive and makes a safety backup of the current state.', + 'If applying restored data fails, WGTools automatically attempts to roll back.', + 'After a successful restore the current web session is cleared; sign in with an account from the restored ' + 'database.'], + 'example_title': '', + 'example_lines': [], + 'warning': 'A .wgtbackup contains private keys, PSKs, password hashes, Telegram token and SMTP password. Store it like a ' + 'password.'}, + {'title': 'Telegram Bot', + 'paragraphs': ['Telegram can check and manage WireGuard without opening the web panel.'], + 'bullets': ['Create a bot with @BotFather and paste its Bot Token.', + 'Enable it and send /start.', + 'If your Telegram user ID is not authorized yet, the bot shows the numeric ID. Add it to the allowed list.', + 'Management commands are accepted only in private chats.', + 'Available actions include server status, clients, create/delete, configuration/QR reissue and WireGuard controls.'], + 'example_title': 'Example', + 'example_lines': ['Default Endpoint: vpn.example.com', 'DNS: 1.1.1.1, 8.8.8.8'], + 'warning': ''}, + {'title': 'Mail / SMTP and password recovery', + 'paragraphs': ['SMTP powers the Forgot password? flow on the sign-in page.'], + 'bullets': ['STARTTLS, TLS/SSL and plain SMTP for a trusted local network are supported.', + 'Username can be empty when the SMTP server does not require authentication.', + 'The password is stored locally and is never returned to the browser.', + 'The test button sends a message to the chosen test recipient.', + 'Recovery codes are one-time, hashed, valid for 15 minutes and rate-limited.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Built-in HTTPS', + 'paragraphs': ['WGTools can serve HTTPS directly without Nginx, Caddy or another reverse proxy.'], + 'bullets': ['First enter the domain/public IP, e-mail, HTTPS port and private path, then click Obtain / renew certificate. That action also saves the entered HTTPS settings.', + 'Until a suitable certificate exists, Enable built-in HTTPS stays unavailable. After successful issuance, enable it and click Save.', + 'If the domain or public IP changes, WGTools requires a certificate for the new address before HTTPS can be enabled.', + 'For issuance and renewal, TCP 80 must be reachable from the Internet to this server.', + 'The panel uses the chosen HTTPS port, such as 443 or 8443.', + 'Private path sets the panel URL, for example /MyWGTools/. Other paths return 404 while built-in HTTPS is enabled.', + 'WGTools reports local port usage and never stops an unrelated web server.', + 'A systemd timer renews the certificate automatically.'], + 'example_title': 'Example', + 'example_lines': ['https://wg.example.com/MyWGTools/'], + 'warning': 'A private path does not replace authentication. Avoid exposing the panel unnecessarily and use strong credentials.'}, + {'title': 'Users', + 'paragraphs': ['The first user is created during initial WGTools setup. Additional users can be added in Settings.'], + 'bullets': ['Users currently have equal management rights.', + 'E-mail and password can be changed and users can be removed.', + 'Each user can enable MFA for their own account with Google Authenticator or another TOTP-compatible app. WGTools shows a one-time set of recovery codes when MFA is enabled.', + 'If the authenticator device is lost, root can disable MFA for a selected user from the wgtools CLI.', + 'The current user and the last remaining user cannot be deleted.', + 'Password change/recovery and enabling/disabling MFA invalidate older web sessions for that user.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'Audit', + 'paragraphs': ['Audit shows meaningful web/Telegram administration actions and useful WireGuard connection history.'], + 'bullets': ['Web actions record the WGTools username.', + 'Telegram actions record @username when available and the numeric Telegram ID.', + 'Configuration changes, client configuration/QR disclosure, updates and useful failures are recorded.', + 'Passwords, private keys, PSKs, tokens and full configuration contents are not written to Audit.', + 'The journal has limited retention and is cleaned automatically.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'WGTools updates', + 'paragraphs': ['WGTools periodically checks stable GitHub Releases but never installs an update without explicit confirmation.'], + 'bullets': ['An update notice appears in the sidebar when a newer version exists.', + 'Before updating, WGTools creates a full .wgtbackup and a separate application rollback archive.', + 'If the new application does not start, WGTools attempts to restore the previous version automatically.', + 'The current version is shown in the UI and under About.'], + 'example_title': '', + 'example_lines': [], + 'warning': ''}, + {'title': 'wgtools command and emergency access', + 'paragraphs': ['The root command wgtools is installed with the application and is useful when the web panel is unreachable.'], + 'bullets': ['It shows WGTools, WireGuard, Nodes, Telegram, timer and local Relay Agent status plus the current panel URL.', + 'It can start/stop/restart the panel and WireGuard and show logs.', + 'If an HTTPS port or private path was configured incorrectly, the CLI can disable built-in HTTPS and restore HTTP access.', + 'The Security section can emergency-disable MFA for a selected user if Google Authenticator and recovery codes are unavailable.', + 'Uninstall WGTools removes the panel and its services while keeping normal WireGuard and reusable WGTools data for a later reinstall.', + 'FULL CLEANUP wipes WGTools, local Relay and WireGuard from this host after an explicit DELETE ALL confirmation; Relay Agents on other VPS hosts are never touched.'], + 'example_title': 'Example', + 'example_lines': ['root@server:~# wgtools'], + 'warning': ''}, + {'title': 'Where data is stored', + 'paragraphs': ['Manual editing is normally unnecessary, but these paths are useful for troubleshooting and backup planning.'], + 'bullets': [], + 'example_title': 'Main paths', + 'example_lines': ['/etc/wireguard/wg0.conf — WireGuard configuration', + '/var/lib/wgtools/wgtools.db — users and settings', + '/var/lib/wgtools/clients/ — managed client data', + '/var/lib/wgtools/backups/ — configuration history', + '/var/lib/wgtools/update-backups/ — update rollback archives'], + 'warning': ''}]}]} + + +# Larger help articles are localized separately from short UI translation keys. +# The original Russian and English help above is retained as the reference/fallback. +import json as _help_json +from pathlib import Path as _HelpPath + +_HELP_TRANSLATION_PATH = _HelpPath(__file__).with_name('help_locales') +for _help_lang in ('de', 'fr', 'it', 'es', 'pl'): + _help_file = _HELP_TRANSLATION_PATH / f'{_help_lang}.json' + # Missing/corrupt optional language resources must not break panel startup. + try: + _help_sections = _help_json.loads(_help_file.read_text(encoding='utf-8')) + if ([s['id'] for s in _help_sections] != [s['id'] for s in HELP['en']] + or any(len(s['topics']) != len(reference['topics']) + for s, reference in zip(_help_sections, HELP['en']))): + raise ValueError('help sections do not match reference') + HELP[_help_lang] = _help_sections + except (OSError, ValueError, KeyError, TypeError): + # Keep English as a safe fallback; release tests require every file to be valid. + pass + +def get_help_sections(language: str) -> list[dict]: + return HELP.get(language) or HELP["en"] diff --git a/app/core/help_locales/de.json b/app/core/help_locales/de.json new file mode 100644 index 0000000..1ff3655 --- /dev/null +++ b/app/core/help_locales/de.json @@ -0,0 +1,663 @@ +[ + { + "id": "dashboard", + "title": "Übersicht", + "intro": "Die Übersicht beantwortet drei Fragen: Läuft WireGuard, wer ist verbunden und arbeitet der Server fehlerfrei?", + "topics": [ + { + "title": "Erste Schritte", + "paragraphs": [ + "Oben wird die ausgewählte WireGuard-Schnittstelle angezeigt. Bei mehreren Schnittstellen beziehen sich die WGTools-Seiten auf die jeweils ausgewählte." + ], + "bullets": [ + "Start aktiviert WireGuard, Stopp hält es an und Neustart startet die Schnittstelle kurz neu.", + "Telefone und Computer verbinden sich danach normalerweise automatisch erneut.", + "Bei angehaltener Schnittstelle können ihre Clients keine Verbindung aufbauen." + ], + "example_title": "Beispiel", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24 · UDP 51820" + ], + "warning": "" + }, + { + "title": "CPU, Arbeitsspeicher, Netzwerk und Laufzeit", + "paragraphs": [ + "Diese Angaben beziehen sich auf den gesamten Debian-Server, nicht nur auf WireGuard." + ], + "bullets": [ + "CPU zeigt die aktuelle Prozessorlast, Arbeitsspeicher den belegten und gesamten RAM.", + "Netzwerk zeigt die momentane Empfangs- und Senderate der externen Schnittstelle.", + "Laufzeit ist die Zeit seit dem letzten Systemstart. Diagramme der letzten 24 Stunden helfen, auffällige Last und dauerhaften Datenverkehr zu erkennen." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Wer ist verbunden?", + "paragraphs": [ + "WireGuard unterhält keine Sitzung wie eine Webseite. WGTools betrachtet einen Client als online, wenn sein letzter Handshake noch nicht zu lange zurückliegt." + ], + "bullets": [ + "Handshake ist der letzte erfolgreiche WireGuard-Kontrollaustausch; Endpoint bezeichnet öffentliche IP-Adresse und Port des Clients.", + "„Nie“ bedeutet, dass der Server noch keinen erfolgreichen Handshake dieses Peers gesehen hat.", + "Die Schnellsuche filtert nach Name, VPN-Adresse, Typ und Endpoint." + ], + "example_title": "Beispiel", + "example_lines": [ + "Telefon · 10.0.0.3/32", + "Endpoint: 203.0.113.25:63275", + "Handshake: vor 18 s" + ], + "warning": "" + }, + { + "title": "Datenverkehr", + "paragraphs": [ + "WGTools speichert kumulierte RX/TX-Werte unabhängig von den temporären WireGuard-Zählern; Statistiken bleiben daher nach Neustarts von Schnittstelle oder Server erhalten." + ], + "bullets": [ + "Die Datenverkehr-Karte zeigt das Gesamtvolumen der ausgewählten Schnittstelle; jeder Client hat eigene RX/TX-Summen.", + "Zurücksetzen beginnt die Zählung ab diesem Zeitpunkt erneut.", + "RX/TX auf der Netzwerk-Karte ist die momentane Geschwindigkeit, nicht das Gesamtvolumen." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Mehrere WireGuard-Schnittstellen", + "paragraphs": [ + "Ein Server kann mehrere unabhängige VPNs bereitstellen, etwa für Zuhause und Büro." + ], + "bullets": [ + "Der Wechsel oben verändert keine Konfiguration, sondern wählt nur, welche Schnittstelle Übersicht, Server und Clients anzeigen.", + "Jede Schnittstelle besitzt eigene Adressen, Ports, Clients, Routen und Zugriffsregeln." + ], + "example_title": "Beispiel", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24", + "wg1 · Arbeit · 10.0.1.1/24" + ], + "warning": "" + } + ] + }, + { + "id": "server", + "title": "Server", + "intro": "Hier werden WireGuard-Schnittstellen, Routing, Netzwerkzugriff, verknüpfte WGTools-Server über Nodes und der öffentliche Zugriff über VPS Relay verwaltet.", + "topics": [ + { + "title": "VPN-Netze und WireGuard-Schnittstellen", + "paragraphs": [ + "Eine WireGuard-Schnittstelle ist wie eine virtuelle Netzwerkkarte mit eigenem VPN-Subnetz. Jeder Client erhält daraus eine Adresse." + ], + "bullets": [ + "Systemnamen heißen gewöhnlich wg0, wg1 usw.; ein Anzeigename wie Home oder Office dient nur der Übersicht.", + "ListenPort ist der UDP-Port, über den Clients den Server erreichen.", + "MTU kann normalerweise auf Auto bleiben. Eine manuelle Einstellung ist nur bei Problemen mit bestimmten Netzen, LTE oder PPPoE sinnvoll." + ], + "example_title": "Beispiel", + "example_lines": [ + "VPN-Netz: 10.0.0.0/24", + "Serveradresse: 10.0.0.1/24", + "Clients: 10.0.0.2, 10.0.0.3, ...", + "Port: UDP 51820" + ], + "warning": "" + }, + { + "title": "Ersteinrichtung und weitere Schnittstellen", + "paragraphs": [ + "Auf einem frischen Debian-System kann WGTools WireGuard installieren und die erste Schnittstelle per Assistent anlegen. Weitere wie wg1 und wg2 lassen sich später hinzufügen." + ], + "bullets": [ + "WGTools schlägt ein freies VPN-Subnetz, einen UDP-Port und eine Policy-Routing-Tabelle vor.", + "Überschneidungen von Netzen und bereits belegte Ports werden vorab geprüft.", + "Jede Schnittstelle bekommt eigene Schlüssel und Konfiguration. Vor dem Löschen wird eine Sicherung erstellt und die zugehörigen verwalteten Daten werden entfernt." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "NAT einfach erklärt", + "paragraphs": [ + "NAT/MASQUERADE ist hilfreich, wenn ein VPN-Client LAN oder Internet mit der Quelladresse des WireGuard-Servers erreichen soll. Für Heimnetze ist das oft die einfachste Lösung." + ], + "bullets": [ + "Mit NAT benötigt der Heimrouter normalerweise keine gesonderte Rückroute zum VPN-Subnetz.", + "Ohne NAT müssen benachbarte Router die Rückroute für das VPN-Netz kennen." + ], + "example_title": "Beispiel", + "example_lines": [ + "Telefon 10.0.0.3 → WGTools 192.168.1.10 → Internet", + "Heimrouter sieht Quelladresse 192.168.1.10" + ], + "warning": "" + }, + { + "title": "Routen und Policy Routing", + "paragraphs": [ + "Eine Route legt fest, über welche Schnittstelle oder welches Gateway Linux ein Netz erreicht. Policy Routing ermöglicht gesonderte Routing-Tabellen, zum Beispiel für VPN-Clientverkehr." + ], + "bullets": [ + "Einfache Heiminstallationen benötigen häufig keine eigene Policy-Tabelle.", + "Sie ist nützlich bei einem bestimmten Gateway, einem weiteren VPN oder einem eigenen WAN.", + "WGTools trennt System-, Site-to-Site- und manuelle Routen. Eigene Routen können angelegt, bearbeitet und gelöscht werden." + ], + "example_title": "Beispiel", + "example_lines": [ + "Quelle: 10.0.0.0/24", + "Tabelle: 200", + "Default via: 192.168.1.1 dev eth0" + ], + "warning": "" + }, + { + "title": "Firewall und Netzwerkzugriff", + "paragraphs": [ + "Die Firewall entscheidet, ob Verkehr erlaubt ist; Routing bestimmt lediglich den Weg. Das sind unterschiedliche Funktionen." + ], + "bullets": [ + "Der Zugang einzelner VPN-Clients zu bestimmten Netzen kann erlaubt oder gesperrt werden.", + "WGTools erzeugt Gruppenregeln und clientbezogene Ausnahmen automatisch.", + "Vor Änderungen wird die Konfiguration gesichert; wenn WireGuard nicht startet, wird die vorherige Version wiederhergestellt." + ], + "example_title": "Beispiel", + "example_lines": [ + "10.0.0.6/32 → sperren → 192.168.1.0/24", + "Andere Clients können das LAN weiterhin erreichen" + ], + "warning": "" + }, + { + "title": "Site-to-Site: zwei Netze verbinden", + "paragraphs": [ + "Site-to-Site eignet sich für einen Peer, hinter dem ein ganzes entferntes Netz liegt, statt nur ein Telefon oder Laptop." + ], + "bullets": [ + "Trage diese Netze unter Entfernte Netze ein; WGTools legt die Routen automatisch an.", + "Wenn der Peer offline geht, bleiben die konfigurierten Routen bestehen.", + "Auch die Gegenseite benötigt eine Rückroute über WireGuard." + ], + "example_title": "Beispiel", + "example_lines": [ + "Home: 192.168.1.0/24", + "Büro-Peer: 10.0.0.20/32", + "Büro-LAN: 192.168.50.0/24", + "Ergebnis: Heimgeräte erreichen 192.168.50.x" + ], + "warning": "" + }, + { + "title": "Nodes: WGTools-Server verknüpfen", + "paragraphs": [ + "Nodes verbindet mehrere WGTools-Installationen über einen eigenen internen WireGuard-Tunnel. Ein Server ist der HUB; andere werden mit einem einmaligen Code gekoppelt." + ], + "bullets": [ + "Der HUB verwendet dieselbe Portnummer für UDP (WireGuard) und TCP (geschützte Erstkopplung). Danach erfolgt die Synchronisierung über wgnode0, unabhängig von Panel-URL, HTTPS-Port oder privatem Pfad.", + "WGTools erkennt VPN-, Site-to-Site- und lokale Netze. Veröffentliche nur benötigte Netze. Später erkannte Netze müssen ausdrücklich hinzugefügt werden; Änderungen bestehender Netze lösen einen Hinweis zur Überprüfung aus.", + "Veröffentlichte Netze unterschiedlicher Nodes dürfen sich nicht überschneiden, z. B. 10.0.0.0/24 an zwei Standorten. Bei Konflikten wird die Änderung blockiert.", + "Details zeigt entfernte Netze und Clients schreibgeschützt. Jede Veröffentlichung macht das Netz für verbundene Nodes erreichbar — gib nur das Nötige frei." + ], + "example_title": "Beispiel: home + VPS", + "example_lines": [ + "HUB: vpn.example.com:51950", + "Heimnetz veröffentlicht: 192.168.1.0/24", + "VPS veröffentlicht: 10.20.0.0/24", + "Nach der Kopplung routen beide Seiten über wgnode0" + ], + "warning": "" + }, + { + "title": "VPS Relay: wenn zuhause eine öffentliche IP fehlt", + "paragraphs": [ + "VPS Relay hilft bei CGNAT oder wenn Clients den Heimserver nicht direkt erreichen. Ein öffentlicher VPS dient als Einstiegspunkt; WireGuard-Server und Zugriffsregeln bleiben auf dem WGTools-Host." + ], + "bullets": [ + "VPS über SSH hinzufügen: WGTools prüft Host und Ports und installiert anschließend den Relay Agent.", + "Ein Agent kann mehrere unabhängige WGTools-Controller mit getrennten Schlüsseln und Verbindungen bedienen.", + "Unterstützte Clients können direkt oder über Relay verbinden. Wird der VPS aus WGTools entfernt, wird nur der lokale Transport getrennt; Agent und gespeicherter Mandant bleiben für eine spätere Wiederverbindung bestehen.", + "Relay bietet einen öffentlichen Zugang für Clients, Nodes verknüpft dagegen WGTools-Server und deren Netze." + ], + "example_title": "Beispiel", + "example_lines": [ + "Telefon → öffentlicher VPS → geschützter Relay-Transport → WGTools zuhause → gewünschtes Netz" + ], + "warning": "" + }, + { + "title": "Diagnose", + "paragraphs": [ + "Die Diagnose kontrolliert WireGuard, IP-Weiterleitung, Ports, Routen und Dienste. Sie hilft, wenn ein Client nicht verbinden oder ein Zielnetz nicht erreichen kann." + ], + "bullets": [ + "Prüfe zuerst die laufende Schnittstelle und einen aktuellen Handshake. Klappt der Handshake, liegt das Problem häufig bei Routing, Firewall oder Rückweg.", + "Server → Route zeigt Traceroute-Hops, mittlere RTT und die Zunahme der Verzögerung. Fehlende Traceroute-Antworten werden neutral angezeigt, nicht als eindeutiger Ausfall.", + "Die interaktive Karte lässt sich verschieben und zoomen; ein Klick zeigt IP, ungefähren Standort, ASN/Anbieter und RTT.", + "Bei aktivierter Karte werden öffentliche Hop-IPs über ipwho.is geolokalisiert und Kartenkacheln von OpenStreetMap geladen; private IPs werden nicht zur Geolokalisierung gesendet. Traceroute misst keine Bandbreite in Mbit/s.", + "Die Diagnose selbst ändert keine Konfiguration." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Änderungen sicher anwenden", + "paragraphs": [ + "Änderungen an Server, Routen und Firewall können WireGuard kurz neu starten." + ], + "bullets": [ + "WGTools erstellt zuerst eine Konfigurationssicherung.", + "Falls die neue Konfiguration nicht startet, versucht WGTools automatisch zur vorherigen zurückzukehren.", + "Clients können kurz getrennt werden und verbinden sich üblicherweise selbst wieder." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Registerkarte Konfiguration", + "paragraphs": [ + "Hier kannst du /etc/wireguard/.conf direkt bearbeiten, falls die normalen Formulare eine Einstellung nicht anbieten." + ], + "bullets": [ + "Verwende diesen Editor nur mit Kenntnissen der WireGuard-Syntax und PostUp/PostDown-Befehle.", + "Vor Anwendung validiert und sichert WGTools die Datei.", + "Bei ungewöhnlichen Konfigurationen kann die automatische Bearbeitung eingeschränkt sein, um manuelle Regeln zu schützen. PrivateKey, PresharedKey und andere Geheimnisse niemals veröffentlichen." + ], + "example_title": "Beispiel", + "example_lines": [ + "[Interface]", + "Address = 10.0.0.1/24", + "ListenPort = 51820", + "", + "[Peer]", + "AllowedIPs = 10.0.0.2/32" + ], + "warning": "PrivateKey, PresharedKey und andere Geheimnisse niemals veröffentlichen." + } + ] + }, + { + "id": "clients", + "title": "Clients", + "intro": "Ein Client kann ein Telefon, Laptop, Router oder anderer WireGuard-Peer sein. Hier verwaltest du Konfigurationen, Zugriff, Ablaufzeiten, Zeitpläne und Site-to-Site-Verbindungen.", + "topics": [ + { + "title": "Normaler Client", + "paragraphs": [ + "Für ein Telefon oder einen Computer wähle Client. WGTools vergibt eine freie VPN-Adresse und erstellt die Schlüssel." + ], + "bullets": [ + "Der Name ist nur eine Bezeichnung innerhalb von WGTools.", + "Der Endpoint in der erzeugten Konfiguration ist die Adresse, unter der das Gerät deinen WireGuard-Server findet.", + "DNS kann pro Client angegeben oder aus einer Gruppenvorlage übernommen werden." + ], + "example_title": "Beispiel", + "example_lines": [ + "Name: Telefon", + "VPN-Adresse: 10.0.0.3/32", + "Endpoint: vpn.example.com:51820" + ], + "warning": "" + }, + { + "title": "VPN-Verkehr und AllowedIPs", + "paragraphs": [ + "AllowedIPs in der Clientkonfiguration legt fest, welche Ziele das Gerät durch den Tunnel sendet. Dies ist unabhängig von der Zugriffsregel auf dem Server." + ], + "bullets": [ + "Gesamter Verkehr leitet Internet- und entfernten Netzverkehr durch das VPN; alternativ lassen sich einzelne Netze auswählen.", + "Mit der Ausnahme für lokale Netze bleiben Drucker und Router vor Ort direkt erreichbar, obwohl der Internetverkehr durch das VPN läuft.", + "Serverregeln können Ziele auch dann sperren, wenn sie in AllowedIPs enthalten sind." + ], + "example_title": "Beispiel", + "example_lines": [ + "0.0.0.0/0 — gesamter IPv4-Verkehr über VPN", + "192.168.50.0/24 — nur ein entferntes Netz" + ], + "warning": "" + }, + { + "title": "Clientgruppen", + "paragraphs": [ + "Eine Gruppe bündelt gemeinsame Zugriffsregeln und eine Konfigurationsvorlage für mehrere Clients." + ], + "bullets": [ + "Gruppen steuern Internet-/LAN-Zugriff und individuelle Erlaubnis-/Sperrausnahmen.", + "Außerdem können sie Standardrouten, DNS und Keepalive für neue Konfigurationen vorgeben.", + "Serverseitige Gruppenregeln wirken sofort. Eine bereits auf dem Telefon installierte Konfiguration wird aber nicht stillschweigend geändert; bei Bedarf Vorlage anwenden und eine neue Datei oder einen QR-Code ausgeben." + ], + "example_title": "Beispiel", + "example_lines": [ + "Gruppe „Gäste“", + "Internet: erlaubt", + "LAN: gesperrt", + "Mitglieder: Telefon-1, Tabellet-1" + ], + "warning": "" + }, + { + "title": "Regeln pro Client", + "paragraphs": [ + "Ein Client kann die Gruppenregeln übernehmen oder eigene Ausnahmen festlegen." + ], + "bullets": [ + "Eine clientbezogene Erlaubnis oder Sperre hat Vorrang vor der entsprechenden Gruppenausnahme.", + "So kann beispielsweise ein Mitarbeiter einen Server erreichen, der für die restliche Gruppe gesperrt ist." + ], + "example_title": "Beispiel", + "example_lines": [ + "Gruppe sperrt 192.168.1.0/24", + "Client erlaubt zusätzlich 192.168.1.50/32" + ], + "warning": "" + }, + { + "title": "Site-to-Site-Client", + "paragraphs": [ + "Wähle Site-to-Site, wenn ein Peer ein ganzes Netz repräsentiert. Trage die dahinterliegenden Netze als Entfernte Netze ein." + ], + "bullets": [ + "WGTools ergänzt die nötigen Serverrouten automatisch.", + "Diese Netze können später über Nodes veröffentlicht werden.", + "Ein gewöhnliches Telefon oder Laptop benötigt keinen Site-to-Site-Modus." + ], + "example_title": "Beispiel", + "example_lines": [ + "Router-Peer: 10.0.0.20/32", + "Entferntes Netz: 192.168.50.0/24" + ], + "warning": "" + }, + { + "title": "Direkte Verbindung und VPS Relay", + "paragraphs": [ + "Ist VPS Relay für die Schnittstelle installiert, können unterstützte Clients direkt oder über Relay verbinden." + ], + "bullets": [ + "Direkt ist ideal, wenn der WireGuard-Port aus dem Internet erreichbar ist.", + "Relay hilft bei CGNAT und wenn eingehendes UDP nicht möglich ist.", + "VPN-Adresse und Zugriffsregeln des Clients bleiben gleich." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "PSK, Isolation und Schlüsselwechsel", + "paragraphs": [ + "WireGuard nutzt ohnehin öffentliche und private Schlüssel. Ein optionaler PSK ergänzt ein weiteres gemeinsames Geheimnis." + ], + "bullets": [ + "Clientisolation verhindert Verbindungen zu anderen VPN-Adressen desselben WireGuard-Pools.", + "Schlüsselwechsel erzeugt ein neues Schlüsselpaar und bei aktivem PSK auch einen neuen PSK. Die alte Konfiguration funktioniert danach nicht mehr: Neue Datei oder QR ausgeben.", + "VPN-Adresse, Gruppe, Zeitplan und Verkehrsstatistik bleiben erhalten." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Zeitlich begrenzter Zugriff", + "paragraphs": [ + "Ein Client kann nach 1, 3 oder 6 Stunden, einem Tag oder zu einem frei gewählten Zeitpunkt ablaufen." + ], + "bullets": [ + "Zum Ablaufzeitpunkt führt der Hintergrunddienst die gewählte Aktion aus.", + "Zum Reaktivieren eines gespeicherten abgelaufenen Clients eine neue Ablaufzeit oder Ohne Begrenzung einstellen." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Zugriffszeitplan", + "paragraphs": [ + "Ein Zeitplan erlaubt oder sperrt einen Client automatisch an ausgewählten Tagen und Uhrzeiten, ohne seine Konfiguration auszutauschen." + ], + "bullets": [ + "Maßgeblich ist die lokale Uhrzeit des WireGuard-Servers.", + "Zeitfenster können über Mitternacht reichen, etwa 22:00–06:00.", + "Mit Beginn des nächsten erlaubten Zeitfensters stellt WGTools denselben Peer wieder her." + ], + "example_title": "Beispiel", + "example_lines": [ + "Mo–Fr: 08:00–19:00" + ], + "warning": "" + }, + { + "title": "Status, Endpoint und Verkehr", + "paragraphs": [ + "Die Tabelle zeigt den letzten Handshake, Endpoint und die kumulierten RX/TX-Werte." + ], + "bullets": [ + "Ein neuer Handshake zeigt, dass der Client kürzlich mit dem Server kommuniziert hat.", + "Der Endpoint eines Smartphones kann beim Wechsel zwischen WLAN und LTE wechseln; das ist normal.", + "Die Schnellsuche filtert nach Name, Adresse, Gruppe und Status." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Konfigurationsdatei und QR-Code", + "paragraphs": [ + "Eine .conf-Datei eignet sich für Computer und Router; QR-Codes für die WireGuard-App auf Smartphones." + ], + "bullets": [ + "Der PrivateKey des Clients steht sowohl in der Datei als auch im QR-Code. Beides wie ein Passwort schützen.", + "Erneutes Ausgeben einer verwalteten Clientkonfiguration verwendet die in WGTools gespeicherten Schlüssel.", + "Nach einem Schlüsselwechsel immer eine neue Konfiguration ausgeben." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Bearbeiten und Löschen", + "paragraphs": [ + "Vor verwalteten Änderungen sichert WGTools die WireGuard-Konfiguration und übernimmt Änderungen kontrolliert." + ], + "bullets": [ + "Das Löschen eines verwalteten Clients entfernt Peer, gespeicherte Schlüssel und zugehörige Regeln.", + "Eine bereits auf dem Gerät gespeicherte Datei wird nicht aus der Ferne gelöscht, kann aber keine Verbindung mehr aufbauen." + ], + "example_title": "", + "example_lines": [], + "warning": "" + } + ] + }, + { + "id": "settings", + "title": "Einstellungen", + "intro": "Hier findest du Darstellung, Sicherungen, Telegram, E-Mail, HTTPS, Benutzer, Audit und Anwendungsupdates.", + "topics": [ + { + "title": "Darstellung und Sprache", + "paragraphs": [ + "Wähle helles, dunkles oder systemabhängiges Design sowie die Sprache." + ], + "bullets": [ + "Die eingeklappte Seitenleiste zeigt nur Navigationssymbole.", + "Die Seitenleistenansicht wird im aktuellen Browser gespeichert und sofort aktualisiert.", + "Die gewählte Sprache speichert WGTools." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Statusaktualisierung", + "paragraphs": [ + "Das Aktualisierungsintervall bestimmt, wie häufig Server- und Clientstatus neu geladen werden. Die Online-Schwelle legt fest, wie lange nach einem Handshake ein Peer als verbunden gilt." + ], + "bullets": [], + "example_title": "Beispiel", + "example_lines": [ + "Aktualisierung: 5 s", + "Online: 180 s" + ], + "warning": "" + }, + { + "title": "Automatische Konfigurationssicherungen", + "paragraphs": [ + "WGTools legt vor riskanten Änderungen eine Historie der WireGuard-Konfigurationen an, um einzelne Änderungen schnell zurückzunehmen." + ], + "bullets": [ + "Du kannst die Anzahl aufbewahrter Versionen bestimmen.", + "Diese Historie ist nicht mit der vollständigen portablen WGTools-Sicherung identisch." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Vollständige Sicherung und Wiederherstellung", + "paragraphs": [ + "Eine .wgtbackup-Datei dient dem Umzug auf einen anderen Server oder der Wiederherstellung nach Ausfällen." + ], + "bullets": [ + "Sie enthält WireGuard-Konfigurationen, Benutzer-/Einstellungsdatenbank, Gruppen, verwaltete Clients, Telegram-/SMTP-Einstellungen sowie Daten zum Wiederherstellen von VPS Relay und Nodes.", + "WGTools prüft das Archiv und erstellt vor dem Import eine Sicherheitssicherung. Schlägt das Einspielen fehl, versucht es einen Rollback.", + "Nach erfolgreicher Wiederherstellung endet die aktuelle Websitzung; melde dich mit einem Konto aus der wiederhergestellten Datenbank an." + ], + "example_title": "", + "example_lines": [], + "warning": ".wgtbackup enthält private Schlüssel, PSKs, Passwort-Hashes, Telegram-Token und SMTP-Passwort. Wie ein Passwort aufbewahren." + }, + { + "title": "Telegram-Bot", + "paragraphs": [ + "Telegram erlaubt WireGuard-Abfragen und Verwaltungsaktionen, ohne die Weboberfläche zu öffnen." + ], + "bullets": [ + "Erstelle mit @BotFather einen Bot, füge den Token ein, aktiviere ihn und sende /start.", + "Ist deine Telegram-Benutzer-ID noch nicht freigegeben, zeigt der Bot die numerische ID an. Füge sie zur Freigabeliste hinzu.", + "Administrative Befehle funktionieren nur in privaten Chats: Status, Clients, Anlegen/Löschen, Datei-/QR-Ausgabe und WireGuard-Steuerung." + ], + "example_title": "Beispiel", + "example_lines": [ + "Standard-Endpoint: vpn.example.com", + "DNS: 1.1.1.1, 8.8.8.8" + ], + "warning": "" + }, + { + "title": "E-Mail / SMTP und Passwortwiederherstellung", + "paragraphs": [ + "SMTP ermöglicht „Passwort vergessen?“ auf der Anmeldeseite." + ], + "bullets": [ + "Unterstützt werden STARTTLS, TLS/SSL und unverschlüsseltes SMTP in einem vertrauenswürdigen LAN. Der Benutzername darf leer bleiben, wenn der SMTP-Server keine Authentifizierung braucht.", + "Das Kennwort bleibt lokal und wird nie an den Browser zurückgegeben. Die Testschaltfläche versendet eine E-Mail an die angegebene Testadresse.", + "Wiederherstellungscodes sind einmalig, gehasht, 15 Minuten gültig und gegen zu viele Versuche geschützt." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Integriertes HTTPS", + "paragraphs": [ + "WGTools kann HTTPS ohne Nginx, Caddy oder externen Reverse-Proxy selbst bereitstellen." + ], + "bullets": [ + "Gib Domain/öffentliche IP, E-Mail, HTTPS-Port und privaten Pfad ein und wähle Zertifikat anfordern/erneuern. Dabei werden die HTTPS-Einstellungen gespeichert.", + "HTTPS lässt sich erst mit einem passenden Zertifikat aktivieren. Nach erfolgreicher Ausstellung die Option einschalten und Speichern wählen; bei geänderter Domain/IP wird ein neues Zertifikat benötigt.", + "TCP 80 muss für Ausstellung und Erneuerung aus dem Internet erreichbar sein. Das Panel läuft auf dem ausgewählten HTTPS-Port (z. B. 443 oder 8443). Ein privater Pfad wie /MyWGTools/ bestimmt die URL; andere Pfade liefern bei aktiviertem HTTPS 404.", + "WGTools zeigt lokale Portbelegung und stoppt keine fremden Webserver; ein systemd-Timer erneuert Zertifikate automatisch.", + "Der private Pfad ersetzt keine Anmeldung. Panel nicht unnötig öffentlich freigeben und starke Zugangsdaten verwenden." + ], + "example_title": "Beispiel", + "example_lines": [ + "https://wg.example.com/MyWGTools/" + ], + "warning": "Ein privater Pfad ersetzt keine Anmeldung. Stelle das Panel nicht unnötig öffentlich bereit und verwende sichere Zugangsdaten." + }, + { + "title": "Benutzer", + "paragraphs": [ + "Das erste Konto wird bei der WGTools-Einrichtung erstellt; weitere lassen sich unter Einstellungen hinzufügen." + ], + "bullets": [ + "Derzeit haben alle Benutzer dieselben Verwaltungsrechte. E-Mail und Passwort können geändert und Konten entfernt werden.", + "Jeder Benutzer kann MFA über Google Authenticator oder eine kompatible TOTP-App aktivieren. Dabei werden einmalig Wiederherstellungscodes angezeigt.", + "Geht der Authenticator verloren, kann root MFA für den Benutzer über die wgtools-CLI deaktivieren. Das eigene und das letzte verbliebene Konto können nicht gelöscht werden.", + "Passwortänderung/-wiederherstellung und Änderung des MFA-Status machen ältere Websitzungen ungültig." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Audit-Protokoll", + "paragraphs": [ + "Audit protokolliert wichtige Web- und Telegram-Verwaltungsaktionen sowie die WireGuard-Verbindungshistorie." + ], + "bullets": [ + "Webaktionen enthalten den WGTools-Benutzernamen; Telegram-Aktionen wenn verfügbar @username und die numerische Telegram-ID.", + "Konfigurationsänderungen, Abrufe von Clientdateien/QR, Updates und relevante Fehler werden protokolliert.", + "Passwörter, private Schlüssel, PSKs, Tokens und komplette Konfigurationen werden nicht erfasst. Das Protokoll wird nach der Aufbewahrungsfrist automatisch bereinigt." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "WGTools-Updates", + "paragraphs": [ + "WGTools prüft regelmäßig stabile GitHub-Releases und installiert Updates nur nach ausdrücklicher Bestätigung." + ], + "bullets": [ + "Bei neuer Version erscheint eine Benachrichtigung.", + "Vor dem Update entstehen eine vollständige .wgtbackup und ein gesondertes Archiv für den Rückweg zur alten Anwendungsversion.", + "Startet die neue Version nicht, versucht WGTools die vorherige wiederherzustellen. Die installierte Version steht in der Oberfläche und unter Über." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Der Befehl wgtools und Notfallzugriff", + "paragraphs": [ + "Der root-Befehl wgtools hilft, wenn das Webpanel nicht erreichbar ist." + ], + "bullets": [ + "Er zeigt WGTools-, WireGuard-, Nodes-, Telegram-, Timer- und lokalen Relay-Agent-Status sowie die aktuelle Panel-URL.", + "Er kann Panel und WireGuard starten, stoppen und neu starten sowie Logs anzeigen. Bei falschem HTTPS-Port oder privatem Pfad kann er integriertes HTTPS abschalten und HTTP wiederherstellen.", + "Bei Verlust von Authenticator und Codes lässt sich die MFA eines Benutzers notfallmäßig deaktivieren.", + "Deinstallieren entfernt Panel und Dienste, erhält aber normales WireGuard und Daten für eine spätere Neuinstallation. FULL CLEANUP löscht nach Bestätigung mit DELETE ALL WGTools, lokales Relay und WireGuard; fremde VPS-Relay-Agents bleiben unberührt." + ], + "example_title": "Beispiel", + "example_lines": [ + "root@server:~# wgtools" + ], + "warning": "" + }, + { + "title": "Wo Daten gespeichert werden", + "paragraphs": [ + "Manuelles Bearbeiten ist meist unnötig. Die Pfade helfen aber bei Fehlersuche und Backupplanung." + ], + "bullets": [], + "example_title": "Wichtige Pfade", + "example_lines": [ + "/etc/wireguard/wg0.conf — WireGuard-Konfiguration", + "/var/lib/wgtools/wgtools.db — Benutzer und Einstellungen", + "/var/lib/wgtools/clients/ — verwaltete Clientdaten", + "/var/lib/wgtools/backups/ — Konfigurationsverlauf", + "/var/lib/wgtools/update-backups/ — Archive für Update-Rollback" + ], + "warning": "" + } + ] + } +] diff --git a/app/core/help_locales/es.json b/app/core/help_locales/es.json new file mode 100644 index 0000000..86a3611 --- /dev/null +++ b/app/core/help_locales/es.json @@ -0,0 +1,663 @@ +[ + { + "id": "dashboard", + "title": "Panel principal", + "intro": "El panel principal responde a tres preguntas: ¿está funcionando WireGuard, quién está conectado y se encuentra bien el servidor?", + "topics": [ + { + "title": "Primeros pasos", + "paragraphs": [ + "La barra superior muestra la interfaz WireGuard seleccionada. Si hay varias, las páginas de WGTools trabajan con la interfaz activa." + ], + "bullets": [ + "Iniciar activa WireGuard, Detener lo desactiva y Reiniciar reinicia brevemente la interfaz.", + "Los teléfonos y equipos suelen reconectarse automáticamente después de un reinicio.", + "Cuando la interfaz está detenida, sus clientes no pueden conectarse." + ], + "example_title": "Ejemplo", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24 · UDP 51820" + ], + "warning": "" + }, + { + "title": "CPU, memoria, red y tiempo activo", + "paragraphs": [ + "Estos indicadores describen todo el servidor Debian, no solo WireGuard." + ], + "bullets": [ + "CPU muestra la carga actual del procesador y Memoria la RAM utilizada y total.", + "Red indica las velocidades actuales de recepción y envío de la interfaz externa.", + "El tiempo activo cuenta desde el último arranque del sistema; las gráficas de 24 horas ayudan a detectar carga anómala o tráfico sostenido." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Quién está conectado", + "paragraphs": [ + "WireGuard no mantiene una sesión como una página web. WGTools considera que un cliente está en línea si su último handshake es suficientemente reciente." + ], + "bullets": [ + "Handshake es el último intercambio de control WireGuard correcto; Endpoint representa la IP pública y el puerto del cliente.", + "«Nunca» indica que el servidor aún no ha visto un handshake válido de ese peer.", + "La búsqueda rápida filtra por nombre, dirección VPN, tipo y Endpoint." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Teléfono · 10.0.0.3/32", + "Endpoint: 203.0.113.25:63275", + "Handshake: hace 18 s" + ], + "warning": "" + }, + { + "title": "Tráfico", + "paragraphs": [ + "WGTools guarda los totales RX/TX por separado de los contadores temporales de WireGuard, por lo que las estadísticas sobreviven a reinicios de la interfaz o del servidor." + ], + "bullets": [ + "La tarjeta Tráfico muestra el volumen acumulado de la interfaz elegida y cada cliente mantiene sus propios totales RX/TX.", + "Restablecer inicia un nuevo conteo desde el momento actual.", + "RX/TX en la tarjeta Red representa la velocidad instantánea, no los datos acumulados." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Varias interfaces WireGuard", + "paragraphs": [ + "Un mismo servidor puede alojar varias VPN independientes, como la de casa y la del trabajo." + ], + "bullets": [ + "Cambiar el selector superior no modifica la configuración: solo elige qué interfaz muestran las páginas Panel, Servidor y Clientes.", + "Cada interfaz tiene sus direcciones, puerto, clientes, rutas y reglas de acceso." + ], + "example_title": "Ejemplo", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24", + "wg1 · Trabajo · 10.0.1.1/24" + ], + "warning": "" + } + ] + }, + { + "id": "server", + "title": "Servidor", + "intro": "Aquí se gestiona WireGuard: interfaces, rutas, acceso a redes, conexión entre servidores mediante Nodes y acceso público con VPS Relay.", + "topics": [ + { + "title": "Redes VPN e interfaces WireGuard", + "paragraphs": [ + "Una interfaz WireGuard es como una tarjeta de red virtual con su propia subred VPN. Cada cliente recibe una dirección de esa red." + ], + "bullets": [ + "Los nombres del sistema suelen ser wg0, wg1, etc. Un nombre visible como Home u Office solo facilita identificarlos.", + "ListenPort es el puerto UDP al que se conectan los clientes.", + "Normalmente se puede dejar MTU en Auto; solo conviene cambiarlo a mano por problemas con ciertas redes, LTE o PPPoE." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Red VPN: 10.0.0.0/24", + "Dirección del servidor: 10.0.0.1/24", + "Clientes: 10.0.0.2, 10.0.0.3, ...", + "Puerto: UDP 51820" + ], + "warning": "" + }, + { + "title": "Configuración inicial y nuevas interfaces", + "paragraphs": [ + "En un Debian limpio, WGTools puede instalar WireGuard y crear la primera interfaz mediante un asistente. Después puedes añadir wg1, wg2 y otras." + ], + "bullets": [ + "WGTools sugiere una subred VPN libre, un puerto UDP y una tabla de enrutamiento por políticas.", + "Comprueba las subredes superpuestas y los puertos ocupados antes de crearla.", + "Cada interfaz obtiene sus propias claves y configuración. Al eliminarla se crea antes una copia de seguridad y se retiran los datos gestionados relacionados." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "NAT explicado de forma sencilla", + "paragraphs": [ + "NAT/MASQUERADE permite que un cliente VPN acceda a la LAN o a Internet usando la dirección del servidor WireGuard como origen. Suele ser la opción más simple en casa." + ], + "bullets": [ + "Con NAT activado, el router doméstico normalmente no necesita una ruta de retorno específica hacia la subred VPN.", + "Sin NAT, el enrutamiento real requiere rutas de retorno en los routers vecinos." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Teléfono 10.0.0.3 → WGTools 192.168.1.10 → Internet", + "El router de casa ve el origen 192.168.1.10" + ], + "warning": "" + }, + { + "title": "Rutas y enrutamiento por políticas", + "paragraphs": [ + "Una ruta indica a Linux qué interfaz o puerta de enlace utilizar para llegar a una red. El enrutamiento por políticas permite elegir otra tabla para tráfico concreto, como los clientes VPN." + ], + "bullets": [ + "Una instalación doméstica sencilla generalmente no necesita una tabla independiente.", + "Es útil si los clientes deben usar una puerta de enlace determinada, otra VPN o una WAN separada.", + "WGTools distingue rutas del sistema, Site-to-Site y manuales. Las rutas personalizadas pueden crearse, editarse y eliminarse." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Origen: 10.0.0.0/24", + "Tabla: 200", + "Default via: 192.168.1.1 dev eth0" + ], + "warning": "" + }, + { + "title": "Cortafuegos y acceso a la red", + "paragraphs": [ + "El cortafuegos determina si el tráfico está permitido; el enrutamiento solo establece adónde enviarlo. Son funciones distintas." + ], + "bullets": [ + "Puedes permitir o bloquear el acceso de un cliente VPN a determinadas redes.", + "WGTools genera automáticamente reglas de grupos y excepciones individuales.", + "Antes de aplicar cambios crea una copia de seguridad y restaura la anterior si WireGuard no arranca." + ], + "example_title": "Ejemplo", + "example_lines": [ + "10.0.0.6/32 → bloquear → 192.168.1.0/24", + "Los demás clientes aún pueden acceder a la LAN" + ], + "warning": "" + }, + { + "title": "Site-to-Site: unir dos redes", + "paragraphs": [ + "Site-to-Site sirve para un peer que representa una red remota completa en lugar de un teléfono o portátil." + ], + "bullets": [ + "Indica las redes detrás del peer en Redes remotas y WGTools creará las rutas automáticamente.", + "Si el peer pasa a offline, esas rutas configuradas no desaparecen.", + "El lado remoto también debe tener una ruta de retorno por WireGuard." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Home: 192.168.1.0/24", + "Peer de oficina: 10.0.0.20/32", + "LAN de oficina: 192.168.50.0/24", + "Resultado: los equipos de casa pueden acceder a 192.168.50.x" + ], + "warning": "" + }, + { + "title": "Nodes: conectar servidores WGTools", + "paragraphs": [ + "Nodes conecta varias instalaciones WGTools mediante un túnel WireGuard interno dedicado. Una actúa como HUB y las demás se unen con un código de un solo uso." + ], + "bullets": [ + "El HUB utiliza el mismo número de puerto en UDP para WireGuard y TCP para el emparejamiento inicial seguro. Después la sincronización viaja por wgnode0 sin depender de la URL del panel, el puerto HTTPS o la ruta privada.", + "WGTools detecta redes VPN, Site-to-Site y LAN: publica solo las necesarias. Las redes detectadas posteriormente deben añadirse expresamente; cualquier cambio genera un aviso para revisar la lista.", + "Las redes publicadas por diferentes Nodes no deben superponerse (por ejemplo 10.0.0.0/24 en dos ubicaciones); WGTools bloquea los conflictos.", + "Detalles muestra las redes y los clientes remotos en modo de solo lectura. Publicar una red la hace accesible a los nodos conectados: comparte solo lo imprescindible." + ], + "example_title": "Ejemplo: home + VPS", + "example_lines": [ + "HUB: vpn.example.com:51950", + "Casa publica: 192.168.1.0/24", + "VPS publica: 10.20.0.0/24", + "Tras vincularlos ambos lados enrutan por wgnode0" + ], + "warning": "" + }, + { + "title": "VPS Relay: sin IP pública en casa", + "paragraphs": [ + "VPS Relay ayuda cuando los clientes no pueden llegar directamente al servidor, por ejemplo detrás de CGNAT. Un VPS público actúa como entrada, mientras el servidor WireGuard y sus reglas permanecen en el host WGTools." + ], + "bullets": [ + "Añade el VPS por SSH: WGTools comprueba el host y los puertos e instala Relay Agent.", + "Un mismo agente puede servir a varios controladores WGTools independientes con claves y conexiones aisladas.", + "Los clientes compatibles pueden elegir conexión directa o Relay. Quitar un VPS de WGTools desconecta el transporte local, pero deja el agente y el tenant guardados para reconectarlos después.", + "Relay proporciona una entrada pública a los clientes; Nodes enlaza servidores WGTools y sus redes. Son funciones diferentes." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Teléfono → VPS público → transporte Relay protegido → WGTools doméstico → red necesaria" + ], + "warning": "" + }, + { + "title": "Diagnóstico", + "paragraphs": [ + "El diagnóstico comprueba WireGuard, reenvío de IP, puertos, rutas y servicios. Es útil cuando un cliente no conecta o no alcanza una red remota." + ], + "bullets": [ + "Comprueba primero que la interfaz está funcionando y que existe un handshake reciente. Si el handshake funciona, revisa rutas, cortafuegos y camino de retorno.", + "Servidor → Ruta muestra los saltos de traceroute, RTT medio y aumentos de latencia. Los saltos sin respuesta aparecen de forma neutral y no implican por sí solos una avería.", + "El mapa permite desplazarse y hacer zoom; al pulsar un salto aparecen IP, ubicación aproximada, ASN/proveedor y RTT.", + "Con el mapa activado, las IP públicas se geolocalizan mediante ipwho.is y los mapas se cargan desde OpenStreetMap; las IP privadas no se envían. Traceroute no mide el ancho de banda real en Mbit/s.", + "El diagnóstico por sí mismo no modifica la configuración." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Aplicar cambios de forma segura", + "paragraphs": [ + "Los cambios del servidor, las rutas y el cortafuegos pueden reiniciar brevemente WireGuard." + ], + "bullets": [ + "WGTools crea primero una copia de la configuración.", + "Si la nueva configuración no arranca, intenta restaurar la anterior automáticamente.", + "Los clientes pueden desconectarse un momento y normalmente se reconectan solos." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Pestaña Configuración", + "paragraphs": [ + "Es un editor directo de /etc/wireguard/.conf para opciones que no aparecen en los formularios normales." + ], + "bullets": [ + "Úsalo únicamente si conoces la sintaxis de WireGuard y los comandos PostUp/PostDown.", + "WGTools valida el archivo y crea una copia antes de aplicarlo.", + "Una configuración no estándar puede limitar la edición automática para proteger reglas manuales. Nunca compartas PrivateKey, PresharedKey ni otros secretos." + ], + "example_title": "Ejemplo", + "example_lines": [ + "[Interface]", + "Address = 10.0.0.1/24", + "ListenPuerto = 51820", + "", + "[Peer]", + "AllowedIPs = 10.0.0.2/32" + ], + "warning": "Nunca compartas PrivateKey, PresharedKey ni otros secretos." + } + ] + }, + { + "id": "clients", + "title": "Clientes", + "intro": "Un cliente puede ser un teléfono, portátil, router o cualquier peer WireGuard. Aquí gestionas configuraciones, permisos, caducidades, horarios y conexiones Site-to-Site.", + "topics": [ + { + "title": "Cliente normal", + "paragraphs": [ + "Elige Cliente para teléfonos y equipos. WGTools asigna una dirección VPN libre y genera las claves." + ], + "bullets": [ + "El nombre es solo una etiqueta en WGTools.", + "Endpoint en el archivo generado es la dirección que el dispositivo utiliza para encontrar el servidor WireGuard.", + "DNS puede establecerse por cliente o heredarse de una plantilla de grupo." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Nombre: Teléfono", + "Dirección VPN: 10.0.0.3/32", + "Endpoint: vpn.example.com:51820" + ], + "warning": "" + }, + { + "title": "Tráfico VPN y AllowedIPs", + "paragraphs": [ + "AllowedIPs en la configuración del cliente define qué destinos envía el dispositivo por el túnel. No equivale a la política de acceso del servidor." + ], + "bullets": [ + "Todo el tráfico envía tanto Internet como redes remotas por VPN; también puedes elegir únicamente ciertas redes.", + "Excluir la red local conserva acceso directo a la impresora o al router mientras Internet va por la VPN.", + "El servidor puede bloquear un destino aunque aparezca en AllowedIPs." + ], + "example_title": "Ejemplo", + "example_lines": [ + "0.0.0.0/0 — todo el tráfico IPv4 por VPN", + "192.168.50.0/24 — solo una red remota" + ], + "warning": "" + }, + { + "title": "Grupos de clientes", + "paragraphs": [ + "Un grupo permite definir una plantilla y reglas de acceso una sola vez para varios clientes." + ], + "bullets": [ + "Los grupos controlan acceso a Internet, LAN y excepciones de permitir/bloquear.", + "También pueden ofrecer rutas, DNS y Keepalive predeterminados para configuraciones nuevas.", + "Los cambios de reglas del servidor se aplican enseguida, pero el archivo instalado en el teléfono no cambia automáticamente. Aplica la plantilla y entrega un nuevo archivo o QR si debe modificarse el dispositivo." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Grupo «Invitados»", + "Internet: permitido", + "LAN: bloqueada", + "Miembros: Teléfono-1, Tablat-1" + ], + "warning": "" + }, + { + "title": "Reglas por cliente", + "paragraphs": [ + "Un cliente puede heredar las reglas del grupo o añadir excepciones propias." + ], + "bullets": [ + "Una excepción individual de permitir o bloquear tiene prioridad sobre la excepción correspondiente del grupo.", + "Por ejemplo, un empleado puede acceder a un servidor prohibido para el resto de su grupo." + ], + "example_title": "Ejemplo", + "example_lines": [ + "El grupo bloquea 192.168.1.0/24", + "El cliente permite además 192.168.1.50/32" + ], + "warning": "" + }, + { + "title": "Cliente Site-to-Site", + "paragraphs": [ + "Utiliza Site-to-Site cuando un peer representa una red completa. Introduce las redes detrás de él como Redes remotas." + ], + "bullets": [ + "WGTools añade esas rutas al servidor automáticamente.", + "Más adelante puedes publicarlas mediante Nodes.", + "Un teléfono o portátil común no necesita Site-to-Site." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Peer router: 10.0.0.20/32", + "Red remota: 192.168.50.0/24" + ], + "warning": "" + }, + { + "title": "Conexión directa y VPS Relay", + "paragraphs": [ + "Con VPS Relay instalado en la interfaz, los clientes compatibles pueden conectarse directamente o mediante Relay." + ], + "bullets": [ + "La conexión directa es preferible cuando el puerto WireGuard es accesible desde Internet.", + "Relay ayuda detrás de CGNAT o si el UDP entrante no está disponible.", + "La dirección VPN y la política de acceso del cliente permanecen iguales." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "PSK, aislamiento y rotación de claves", + "paragraphs": [ + "WireGuard ya utiliza claves pública/privada. Un PSK opcional añade otro secreto compartido." + ], + "bullets": [ + "El aislamiento impide que un cliente alcance otras direcciones de la misma red VPN.", + "Rotar las claves crea un par nuevo y, si está habilitado, otro PSK. El archivo anterior deja de funcionar; entrega uno nuevo o un QR.", + "Dirección VPN, grupo, horarios e historial de tráfico se conservan." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Acceso temporal", + "paragraphs": [ + "Un cliente puede caducar después de 1, 3 o 6 horas, un día o en una fecha y hora personalizada." + ], + "bullets": [ + "Al cumplirse el plazo, un servicio en segundo plano ejecuta la acción de caducidad elegida.", + "Para reactivar un cliente caducado que sigue guardado, elige una nueva caducidad o Sin límite." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Horario de acceso", + "paragraphs": [ + "Un horario habilita y bloquea automáticamente al cliente en días y horas seleccionados sin sustituir su configuración." + ], + "bullets": [ + "Utiliza la hora local del servidor WireGuard.", + "Los intervalos pueden cruzar la medianoche, por ejemplo 22:00–06:00.", + "Al comenzar un nuevo período permitido, WGTools recupera el mismo peer." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Lun–Vie: 08:00–19:00" + ], + "warning": "" + }, + { + "title": "Estado, Endpoint y tráfico", + "paragraphs": [ + "La tabla muestra el último handshake, Endpoint y totales RX/TX." + ], + "bullets": [ + "Un handshake reciente significa que el cliente se ha comunicado con el servidor hace poco.", + "El Endpoint de un móvil puede cambiar al pasar entre Wi-Fi y LTE; es normal.", + "La búsqueda rápida filtra por nombre, dirección, grupo y estado." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Configuración y código QR", + "paragraphs": [ + "Un archivo .conf resulta práctico para ordenadores y routers; el QR para la aplicación móvil WireGuard." + ], + "bullets": [ + "PrivateKey del cliente se incluye tanto en el archivo como en el QR: protégelos como una contraseña.", + "Al volver a emitir la configuración de un cliente gestionado se utilizan las claves almacenadas en WGTools.", + "Después de rotar claves entrega siempre una nueva configuración." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Editar y eliminar", + "paragraphs": [ + "WGTools guarda una copia de la configuración WireGuard antes de los cambios gestionados y los aplica de manera segura." + ], + "bullets": [ + "Eliminar un cliente gestionado quita su peer, claves guardadas y reglas relacionadas.", + "Un archivo que ya esté en el dispositivo no se borra a distancia, pero ya no podrá conectarse." + ], + "example_title": "", + "example_lines": [], + "warning": "" + } + ] + }, + { + "id": "settings", + "title": "Ajustes", + "intro": "Aquí encontrarás apariencia, copias de seguridad, Telegram, correo, HTTPS, usuarios, auditoría y actualizaciones.", + "topics": [ + { + "title": "Apariencia e idioma", + "paragraphs": [ + "Selecciona tema claro, oscuro o del sistema y el idioma de la interfaz." + ], + "bullets": [ + "Contraer la barra lateral deja visibles solo los iconos.", + "Su estado se guarda en el navegador y cambia de inmediato.", + "WGTools guarda el idioma elegido." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Actualización del estado", + "paragraphs": [ + "El intervalo de actualización define cada cuánto se renuevan los estados del servidor y los clientes. El umbral online establece durante cuánto tiempo después del handshake se considera conectado un peer." + ], + "bullets": [], + "example_title": "Ejemplo", + "example_lines": [ + "Actualización: 5 s", + "En línea: 180 s" + ], + "warning": "" + }, + { + "title": "Copias automáticas de configuración", + "paragraphs": [ + "WGTools guarda un historial de configuraciones WireGuard antes de cambios delicados para poder revertirlos rápidamente." + ], + "bullets": [ + "Puedes elegir cuántas copias mantener.", + "Este historial es distinto de la copia completa y portátil de WGTools." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Copia completa y restauración", + "paragraphs": [ + "Un archivo .wgtbackup permite migrar a otro servidor o recuperar datos tras una avería." + ], + "bullets": [ + "Contiene configuraciones WireGuard, base de usuarios y ajustes, grupos, datos de clientes, configuración Telegram/SMTP y estado necesario para restaurar VPS Relay/Nodes.", + "Antes de restaurar, WGTools valida el archivo y guarda una copia de seguridad del estado actual. Si falla, intenta revertir los cambios.", + "Tras restaurar correctamente se cierra la sesión web actual; entra con una cuenta de la base restaurada." + ], + "example_title": "", + "example_lines": [], + "warning": ".wgtbackup contiene claves privadas, PSK, hashes de contraseñas, token de Telegram y contraseña SMTP. Guárdalo como si fuera una contraseña." + }, + { + "title": "Bot de Telegram", + "paragraphs": [ + "Telegram permite consultar y administrar WireGuard sin abrir la interfaz web." + ], + "bullets": [ + "Crea un bot con @BotFather, pega su token, actívalo y envía /start.", + "Si tu ID de Telegram aún no está autorizado, el bot muestra el número: añádelo a la lista permitida.", + "Los comandos de administración solo funcionan en chats privados: estado, clientes, creación/eliminación, nueva emisión de configuraciones/QR y controles WireGuard." + ], + "example_title": "Ejemplo", + "example_lines": [ + "Endpoint predeterminado: vpn.example.com", + "DNS: 1.1.1.1, 8.8.8.8" + ], + "warning": "" + }, + { + "title": "Correo SMTP y recuperación de contraseña", + "paragraphs": [ + "SMTP hace posible «¿Olvidaste tu contraseña?» en la pantalla de acceso." + ], + "bullets": [ + "Admite STARTTLS, TLS/SSL y SMTP sin cifrar en una LAN de confianza. El usuario puede quedar vacío si el servidor SMTP no exige autenticación.", + "La contraseña se almacena localmente y nunca se devuelve al navegador. El botón de prueba envía un mensaje al destinatario indicado.", + "Los códigos de recuperación son de un solo uso, se almacenan como hashes, duran 15 minutos y tienen límite de intentos." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "HTTPS integrado", + "paragraphs": [ + "WGTools puede servir HTTPS directamente, sin Nginx, Caddy ni otro proxy inverso." + ], + "bullets": [ + "Introduce dominio/IP pública, correo, puerto HTTPS y ruta privada; después pulsa Obtener / renovar certificado. La acción también guarda estos ajustes HTTPS.", + "HTTPS solo puede activarse si ya existe un certificado adecuado. Tras emitirlo, activa la opción y pulsa Guardar; un dominio/IP diferente necesita su propio certificado.", + "El puerto TCP 80 debe ser accesible desde Internet para emitir y renovar. El panel usa el puerto HTTPS elegido, como 443 u 8443. La ruta privada define la URL, por ejemplo /MyWGTools/; otras rutas devuelven 404 con HTTPS integrado.", + "WGTools informa de puertos locales ocupados y nunca detiene servidores web ajenos; un temporizador systemd renueva el certificado automáticamente.", + "La ruta privada no sustituye a la autenticación. Evita exponer el panel innecesariamente y utiliza credenciales robustas." + ], + "example_title": "Ejemplo", + "example_lines": [ + "https://wg.example.com/MyWGTools/" + ], + "warning": "Una ruta privada no sustituye la autenticación. Evita exponer el panel sin necesidad y usa credenciales seguras." + }, + { + "title": "Usuarios", + "paragraphs": [ + "La primera cuenta se crea durante la instalación de WGTools. Puedes añadir otras desde Ajustes." + ], + "bullets": [ + "Por ahora todos los usuarios tienen los mismos permisos. Se pueden cambiar correo y contraseña y eliminar cuentas.", + "Cada usuario puede activar MFA con Google Authenticator u otra aplicación TOTP y recibir una vez códigos de recuperación.", + "Si pierde el autenticador, root puede desactivar MFA con el comando wgtools. No se puede eliminar al usuario actual ni al último usuario existente.", + "Cambiar o recuperar la contraseña y activar/desactivar MFA invalidan las sesiones web anteriores de esa cuenta." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Registro de auditoría", + "paragraphs": [ + "Auditoría muestra acciones importantes de administración web/Telegram e historial útil de conexiones WireGuard." + ], + "bullets": [ + "Las acciones web registran el usuario WGTools; las de Telegram incluyen @username, si existe, y su ID numérico.", + "Se anotan cambios de configuración, acceso a archivos/QR, actualizaciones y fallos relevantes.", + "No se registran contraseñas, claves privadas, PSK, tokens ni configuraciones completas. El historial tiene retención limitada y se limpia automáticamente." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Actualizaciones WGTools", + "paragraphs": [ + "WGTools comprueba periódicamente las versiones estables de GitHub, pero no instala nada sin confirmación explícita." + ], + "bullets": [ + "Cuando existe una versión nueva aparece un aviso.", + "Antes de actualizar crea un .wgtbackup completo y otro archivo para restaurar la versión previa de la aplicación.", + "Si la versión nueva no inicia, WGTools intenta recuperar la anterior. La versión actual figura en el panel y en Acerca de." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Comando wgtools y acceso de emergencia", + "paragraphs": [ + "El comando root wgtools es útil si el panel web deja de estar disponible." + ], + "bullets": [ + "Muestra el estado de WGTools, WireGuard, Nodes, Telegram, temporizadores y Relay Agent local, además de la URL del panel.", + "Puede iniciar, detener y reiniciar panel o WireGuard y mostrar registros. Si el puerto HTTPS o la ruta privada se configuran mal, permite desactivar HTTPS integrado y recuperar HTTP.", + "También permite a root desactivar MFA cuando se pierden el autenticador y los códigos.", + "Desinstalar WGTools elimina panel y servicios, pero conserva WireGuard normal y datos reutilizables. FULL CLEANUP, tras confirmar DELETE ALL, elimina WGTools, Relay local y WireGuard de este host; no toca los agentes Relay de otros VPS." + ], + "example_title": "Ejemplo", + "example_lines": [ + "root@server:~# wgtools" + ], + "warning": "" + }, + { + "title": "Dónde se guardan los datos", + "paragraphs": [ + "Normalmente no hace falta editar estos archivos manualmente, pero sus rutas ayudan a solucionar problemas y planificar copias de seguridad." + ], + "bullets": [], + "example_title": "Rutas principales", + "example_lines": [ + "/etc/wireguard/wg0.conf — configuración WireGuard", + "/var/lib/wgtools/wgtools.db — usuarios y ajustes", + "/var/lib/wgtools/clients/ — datos de clientes gestionados", + "/var/lib/wgtools/backups/ — historial de configuración", + "/var/lib/wgtools/update-backups/ — archivos de reversión de actualización" + ], + "warning": "" + } + ] + } +] diff --git a/app/core/help_locales/fr.json b/app/core/help_locales/fr.json new file mode 100644 index 0000000..b0c4513 --- /dev/null +++ b/app/core/help_locales/fr.json @@ -0,0 +1,663 @@ +[ + { + "id": "dashboard", + "title": "Tableau de bord", + "intro": "Le tableau de bord permet de vérifier rapidement si WireGuard fonctionne, quels clients sont connectés et si le serveur est en bonne santé.", + "topics": [ + { + "title": "Par où commencer", + "paragraphs": [ + "La barre supérieure indique l'interface WireGuard sélectionnée. Si plusieurs interfaces existent, les pages WGTools utilisent celle qui est sélectionnée." + ], + "bullets": [ + "Démarrer active WireGuard, Arrêter le désactive et Redémarrer relance brièvement l'interface.", + "Les téléphones et ordinateurs se reconnectent normalement tout seuls après un redémarrage.", + "Quand l'interface est arrêtée, ses clients ne peuvent plus se connecter." + ], + "example_title": "Exemple", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24 · UDP 51820" + ], + "warning": "" + }, + { + "title": "Processeur, mémoire, réseau et disponibilité", + "paragraphs": [ + "Ces indicateurs concernent l'ensemble du serveur Debian, et pas seulement WireGuard." + ], + "bullets": [ + "CPU montre la charge actuelle du processeur et Mémoire la RAM utilisée et totale.", + "Réseau affiche les débits actuels de réception et d'émission de l'interface externe.", + "La durée de fonctionnement est mesurée depuis le dernier démarrage. Les graphiques sur 24 heures révèlent les charges anormales et les flux persistants." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Qui est connecté ?", + "paragraphs": [ + "WireGuard ne conserve pas de session comme un site web. WGTools considère un client en ligne si son dernier handshake est suffisamment récent." + ], + "bullets": [ + "Handshake désigne le dernier échange de contrôle WireGuard réussi ; Endpoint est l'adresse IP publique et le port utilisés par le client.", + "« Jamais » signifie que le serveur n'a encore reçu aucun handshake réussi de ce pair.", + "La recherche rapide filtre par nom, adresse VPN, type et Endpoint." + ], + "example_title": "Exemple", + "example_lines": [ + "Téléphone · 10.0.0.3/32", + "Endpoint: 203.0.113.25:63275", + "Handshake: il y a 18 s" + ], + "warning": "" + }, + { + "title": "Trafic", + "paragraphs": [ + "WGTools conserve les totaux RX/TX séparément des compteurs temporaires de WireGuard. Les statistiques survivent donc au redémarrage de l'interface ou du serveur." + ], + "bullets": [ + "La carte Trafic affiche le volume cumulé de l'interface choisie ; chaque client possède ses propres totaux RX/TX.", + "Réinitialiser recommence le comptage à partir de maintenant.", + "RX/TX dans la carte Réseau correspond au débit instantané, pas au volume total." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Plusieurs interfaces WireGuard", + "paragraphs": [ + "Un même serveur peut héberger plusieurs VPN indépendants, par exemple personnel et professionnel." + ], + "bullets": [ + "Changer l'interface en haut ne modifie aucune configuration : cela sélectionne seulement les données affichées sur Tableau de bord, Serveur et Clients.", + "Chaque interface a ses adresses, son port, ses clients, ses routes et ses règles d'accès." + ], + "example_title": "Exemple", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24", + "wg1 · Travail · 10.0.1.1/24" + ], + "warning": "" + } + ] + }, + { + "id": "server", + "title": "Serveur", + "intro": "Cette section gère WireGuard : interfaces, routage, accès réseau, liaison entre serveurs via Nodes et accès public via VPS Relay.", + "topics": [ + { + "title": "Réseaux VPN et interfaces WireGuard", + "paragraphs": [ + "Une interface WireGuard ressemble à une carte réseau virtuelle possédant son propre sous-réseau VPN. Chaque client reçoit une adresse de ce sous-réseau." + ], + "bullets": [ + "Les noms système sont généralement wg0, wg1, etc. Un nom affiché comme Home ou Office facilite simplement la lecture.", + "ListenPort est le port UDP auquel les clients se connectent.", + "Le MTU peut généralement rester sur Auto ; ne le modifier qu'en cas de problème spécifique avec un réseau, LTE ou PPPoE." + ], + "example_title": "Exemple", + "example_lines": [ + "Réseau VPN: 10.0.0.0/24", + "Adresse du serveur: 10.0.0.1/24", + "Clients: 10.0.0.2, 10.0.0.3, ...", + "Port: UDP 51820" + ], + "warning": "" + }, + { + "title": "Installation initiale et interfaces supplémentaires", + "paragraphs": [ + "Sur un Debian neuf, WGTools peut installer WireGuard et créer la première interface avec un assistant. Vous pouvez ensuite ajouter wg1, wg2, etc." + ], + "bullets": [ + "WGTools suggère un sous-réseau VPN libre, un port UDP et une table de routage par règles.", + "Les chevauchements de réseaux et les ports occupés sont vérifiés avant création.", + "Chaque interface reçoit ses propres clés et sa configuration. Sa suppression crée d'abord une sauvegarde, puis retire les données gérées associées." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Comprendre le NAT", + "paragraphs": [ + "NAT/MASQUERADE permet à un client VPN d'atteindre le LAN ou Internet en utilisant l'adresse du serveur WireGuard comme source visible. C'est souvent la solution la plus simple à domicile." + ], + "bullets": [ + "Avec NAT activé, le routeur domestique n'a généralement pas besoin d'une route retour vers le sous-réseau VPN.", + "Sans NAT, les routeurs voisins doivent disposer des routes de retour appropriées." + ], + "example_title": "Exemple", + "example_lines": [ + "Téléphone 10.0.0.3 → WGTools 192.168.1.10 → Internet", + "Le routeur domestique voit la source 192.168.1.10" + ], + "warning": "" + }, + { + "title": "Routes et routage par règles", + "paragraphs": [ + "Une route indique à Linux l'interface ou la passerelle vers un réseau. Le routage par règles permet de choisir une autre table, par exemple pour les clients VPN." + ], + "bullets": [ + "Une installation domestique simple n'a souvent pas besoin d'une table distincte.", + "Celle-ci est utile pour imposer une passerelle, un autre VPN ou une liaison WAN dédiée.", + "WGTools distingue les routes système, Site-to-Site et manuelles. Les routes personnalisées se créent, modifient et suppriment depuis l'interface." + ], + "example_title": "Exemple", + "example_lines": [ + "Source: 10.0.0.0/24", + "Table: 200", + "Default via: 192.168.1.1 dev eth0" + ], + "warning": "" + }, + { + "title": "Pare-feu et accès réseau", + "paragraphs": [ + "Le pare-feu décide si le trafic est autorisé ; le routage décide seulement de sa destination. Ce sont deux fonctions distinctes." + ], + "bullets": [ + "Vous pouvez autoriser ou bloquer l'accès d'un client VPN à un réseau donné.", + "WGTools génère automatiquement les règles de groupe et les exceptions par client.", + "Avant d'appliquer des changements, il sauvegarde la configuration et revient en arrière si WireGuard ne démarre plus." + ], + "example_title": "Exemple", + "example_lines": [ + "10.0.0.6/32 → bloquer → 192.168.1.0/24", + "Les autres clients peuvent toujours accéder au LAN" + ], + "warning": "" + }, + { + "title": "Site-to-Site : relier deux réseaux", + "paragraphs": [ + "Site-to-Site sert lorsqu'un pair représente un réseau distant entier, et non un simple téléphone ou ordinateur." + ], + "bullets": [ + "Indiquez les réseaux derrière ce pair dans Réseaux distants : WGTools crée automatiquement les routes.", + "La déconnexion du pair ne supprime pas ces routes configurées.", + "Le réseau distant doit également posséder une route de retour par WireGuard." + ], + "example_title": "Exemple", + "example_lines": [ + "Home: 192.168.1.0/24", + "Pair du bureau: 10.0.0.20/32", + "LAN du bureau: 192.168.50.0/24", + "Résultat : les appareils du domicile atteignent 192.168.50.x" + ], + "warning": "" + }, + { + "title": "Nodes : relier plusieurs serveurs WGTools", + "paragraphs": [ + "Nodes connecte plusieurs installations WGTools grâce à un tunnel WireGuard interne dédié. L'une devient HUB et les autres la rejoignent avec un code à usage unique." + ], + "bullets": [ + "Le HUB utilise le même numéro de port en UDP pour WireGuard et TCP pour l'association initiale protégée. Ensuite, la synchronisation passe par wgnode0, indépendamment de l'URL du panneau, du port HTTPS et du chemin privé.", + "WGTools détecte les réseaux VPN, Site-to-Site et LAN. Ne publiez que les réseaux nécessaires ; un nouveau réseau détecté n'est jamais publié sans action explicite. Une modification ultérieure entraîne un avertissement de vérification.", + "Les réseaux publiés par plusieurs Nodes ne doivent pas se chevaucher (par exemple 10.0.0.0/24 sur deux sites). WGTools bloque les conflits.", + "Les détails des réseaux et clients distants sont en lecture seule. Publier un réseau le rend accessible aux nœuds associés : limitez cette exposition." + ], + "example_title": "Exemple: home + VPS", + "example_lines": [ + "HUB: vpn.example.com:51950", + "Domicile publie: 192.168.1.0/24", + "VPS publie: 10.20.0.0/24", + "Après association, les deux côtés passent par wgnode0" + ], + "warning": "" + }, + { + "title": "VPS Relay : sans IP publique à domicile", + "paragraphs": [ + "VPS Relay aide lorsque le serveur n'est pas accessible directement depuis Internet, notamment derrière CGNAT. Un VPS public sert de point d'entrée ; le serveur WireGuard et ses règles restent sur l'hôte WGTools." + ], + "bullets": [ + "Ajoutez le VPS par SSH : WGTools vérifie l'hôte et les ports, puis installe Relay Agent.", + "Un même agent peut servir plusieurs contrôleurs WGTools indépendants avec clés et connexions isolées.", + "Les clients compatibles choisissent la connexion directe ou Relay. Supprimer un VPS dans WGTools détache le transport local mais conserve l'agent et le locataire enregistré pour une reconnexion.", + "Relay offre un point d'accès public aux clients, tandis que Nodes relie des serveurs WGTools et leurs réseaux." + ], + "example_title": "Exemple", + "example_lines": [ + "Téléphone → VPS public → transport Relay protégé → WGTools à domicile → réseau souhaité" + ], + "warning": "" + }, + { + "title": "Diagnostics", + "paragraphs": [ + "Les diagnostics contrôlent WireGuard, le transfert IP, les ports, les routes et les services. Ils aident lorsqu'un client ne se connecte pas ou qu'un réseau est inaccessible." + ], + "bullets": [ + "Vérifiez d'abord que l'interface fonctionne et qu'un handshake récent existe. Si celui-ci réussit, cherchez du côté des routes, du pare-feu ou du chemin retour.", + "Serveur → Itinéraire montre les sauts traceroute, le RTT moyen et les hausses de latence. Les sauts sans réponse sont affichés de façon neutre : ils ne prouvent pas une panne.", + "La carte permet de déplacer et zoomer la vue ; cliquer un saut affiche son IP, sa position approximative, son ASN/fournisseur et son RTT.", + "Lorsque la carte est activée, les IP publiques sont géolocalisées via ipwho.is et les tuiles viennent d'OpenStreetMap ; les adresses privées ne sont pas envoyées. Traceroute ne mesure pas le débit en Mbit/s.", + "Les diagnostics ne modifient pas la configuration." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Appliquer les changements en sécurité", + "paragraphs": [ + "Les changements au serveur, aux routes ou au pare-feu peuvent provoquer un bref redémarrage de WireGuard." + ], + "bullets": [ + "WGTools sauvegarde d'abord la configuration.", + "Si la nouvelle configuration échoue, WGTools tente de rétablir automatiquement l'ancienne.", + "Les clients peuvent se déconnecter quelques instants avant de se reconnecter seuls." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Onglet Configuration", + "paragraphs": [ + "Cet éditeur donne accès directement à /etc/wireguard/.conf pour les options absentes des formulaires habituels." + ], + "bullets": [ + "Utilisez-le uniquement si vous maîtrisez la syntaxe WireGuard et les commandes PostUp/PostDown.", + "WGTools valide et sauvegarde le fichier avant application.", + "Une configuration non standard peut limiter l'édition automatique pour préserver les règles manuelles. Ne partagez jamais PrivateKey, PresharedKey ni aucun secret." + ], + "example_title": "Exemple", + "example_lines": [ + "[Interface]", + "Address = 10.0.0.1/24", + "ListenPort = 51820", + "", + "[Peer]", + "AllowedIPs = 10.0.0.2/32" + ], + "warning": "Ne partagez jamais PrivateKey, PresharedKey ni aucun autre secret." + } + ] + }, + { + "id": "clients", + "title": "Clients", + "intro": "Un client peut être un téléphone, un ordinateur, un routeur ou tout autre pair WireGuard. Cette page gère configurations, règles d'accès, expirations, horaires et liens Site-to-Site.", + "topics": [ + { + "title": "Client classique", + "paragraphs": [ + "Choisissez Client pour un téléphone ou un ordinateur. WGTools attribue une adresse VPN libre et génère les clés." + ], + "bullets": [ + "Le nom est seulement une étiquette dans WGTools.", + "L'Endpoint du fichier généré indique où l'appareil doit joindre le serveur WireGuard.", + "Le DNS peut être défini par client ou hérité d'un modèle de groupe." + ], + "example_title": "Exemple", + "example_lines": [ + "Nom: Téléphone", + "Adresse VPN: 10.0.0.3/32", + "Endpoint: vpn.example.com:51820" + ], + "warning": "" + }, + { + "title": "Trafic VPN et AllowedIPs", + "paragraphs": [ + "Dans la configuration client, AllowedIPs détermine le trafic envoyé dans le tunnel. C'est différent des règles d'accès côté serveur." + ], + "bullets": [ + "Tout le trafic fait passer Internet et les réseaux distants par le VPN ; vous pouvez aussi choisir certains réseaux seulement.", + "Le mode d'exclusion du réseau local préserve l'accès direct à une imprimante ou un routeur lorsque Internet passe par le VPN.", + "Une règle serveur peut bloquer une destination même présente dans AllowedIPs." + ], + "example_title": "Exemple", + "example_lines": [ + "0.0.0.0/0 — tout le trafic IPv4 par le VPN", + "192.168.50.0/24 — un seul réseau distant" + ], + "warning": "" + }, + { + "title": "Groupes de clients", + "paragraphs": [ + "Un groupe permet de réutiliser les mêmes règles et modèles de configuration pour plusieurs clients." + ], + "bullets": [ + "Les groupes définissent l'accès Internet/LAN et les exceptions autorisées ou bloquées.", + "Ils peuvent fournir des routes, DNS et Keepalive par défaut aux nouvelles configurations.", + "Les règles côté serveur changent immédiatement, mais le fichier déjà installé sur le téléphone ne se modifie pas seul. Appliquez le modèle et remettez un fichier ou QR si nécessaire." + ], + "example_title": "Exemple", + "example_lines": [ + "Groupe « Invités »", + "Internet : autorisé", + "LAN : bloqué", + "Membres: Téléphone-1, Tablet-1" + ], + "warning": "" + }, + { + "title": "Règles individuelles", + "paragraphs": [ + "Un client peut hériter des règles du groupe ou définir ses propres exceptions." + ], + "bullets": [ + "Une exception autorisant ou bloquant un client prime sur l'exception correspondante du groupe.", + "Cela permet, par exemple, de donner à un salarié l'accès à un serveur bloqué pour son groupe." + ], + "example_title": "Exemple", + "example_lines": [ + "Le groupe bloque 192.168.1.0/24", + "Le client autorise en plus 192.168.1.50/32" + ], + "warning": "" + }, + { + "title": "Client Site-to-Site", + "paragraphs": [ + "Utilisez Site-to-Site lorsqu'un pair représente un réseau entier. Saisissez les réseaux derrière ce pair dans Réseaux distants." + ], + "bullets": [ + "WGTools ajoute automatiquement les routes correspondantes au serveur.", + "Ces réseaux peuvent ensuite être publiés via Nodes.", + "Un téléphone ou ordinateur normal n'a pas besoin du mode Site-to-Site." + ], + "example_title": "Exemple", + "example_lines": [ + "Pair routeur: 10.0.0.20/32", + "Réseau distant: 192.168.50.0/24" + ], + "warning": "" + }, + { + "title": "Connexion directe et VPS Relay", + "paragraphs": [ + "Lorsque VPS Relay est installé pour l'interface, les clients compatibles peuvent se connecter directement ou via Relay." + ], + "bullets": [ + "Le mode direct est préférable si le port WireGuard est accessible depuis Internet.", + "Relay est utile derrière CGNAT ou si l'UDP entrant est impossible.", + "Adresse VPN et règles d'accès du client restent inchangées." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "PSK, isolation et renouvellement des clés", + "paragraphs": [ + "WireGuard utilise déjà une paire clé publique/privée. Un PSK facultatif ajoute un secret partagé." + ], + "bullets": [ + "L'isolation empêche ce client de parler aux autres adresses du même réseau VPN.", + "Le renouvellement génère une nouvelle paire de clés et, si activé, un nouveau PSK. L'ancien fichier cesse de fonctionner : fournissez un nouveau fichier ou QR.", + "L'adresse VPN, le groupe, les horaires et l'historique du trafic sont conservés." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Accès temporaire", + "paragraphs": [ + "L'accès peut expirer après 1, 3 ou 6 heures, un jour ou à une date/heure personnalisée." + ], + "bullets": [ + "À l'échéance, un service en arrière-plan applique l'action d'expiration choisie.", + "Pour réactiver un client expiré conservé, choisissez une nouvelle date ou Sans limite." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Horaires d'accès", + "paragraphs": [ + "Un calendrier autorise ou bloque automatiquement un client certains jours et heures sans modifier son fichier de configuration." + ], + "bullets": [ + "Il utilise l'heure locale du serveur WireGuard.", + "Une plage peut traverser minuit, par exemple 22:00–06:00.", + "Au retour d'une plage autorisée, WGTools réactive le même pair." + ], + "example_title": "Exemple", + "example_lines": [ + "Lun–Ven: 08:00–19:00" + ], + "warning": "" + }, + { + "title": "État, Endpoint et trafic", + "paragraphs": [ + "Le tableau affiche le dernier handshake, l'Endpoint et les totaux RX/TX." + ], + "bullets": [ + "Un handshake récent indique que le client a communiqué avec le serveur récemment.", + "L'Endpoint d'un téléphone peut changer entre Wi-Fi et LTE ; c'est normal.", + "La recherche rapide filtre par nom, adresse, groupe et état." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Configuration et QR", + "paragraphs": [ + "Un fichier .conf convient aux ordinateurs et routeurs ; un QR à l'application mobile WireGuard." + ], + "bullets": [ + "La PrivateKey du client figure dans le fichier et le QR : protégez-les comme un mot de passe.", + "Réexporter la configuration d'un client géré réutilise les clés enregistrées dans WGTools.", + "Après renouvellement des clés, fournissez toujours une nouvelle configuration." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Modifier et supprimer", + "paragraphs": [ + "WGTools sauvegarde la configuration WireGuard avant les changements gérés et les applique de façon sécurisée." + ], + "bullets": [ + "Supprimer un client géré retire son pair, ses clés enregistrées et les règles associées.", + "Un fichier conservé sur l'appareil n'est pas effacé à distance, mais il ne permet plus de se connecter." + ], + "example_title": "", + "example_lines": [], + "warning": "" + } + ] + }, + { + "id": "settings", + "title": "Paramètres", + "intro": "Vous trouverez ici l'apparence, les sauvegardes, Telegram, l'e-mail, HTTPS, les utilisateurs, l'audit et les mises à jour.", + "topics": [ + { + "title": "Apparence et langue", + "paragraphs": [ + "Choisissez un thème clair, sombre ou système et la langue de l'interface." + ], + "bullets": [ + "Réduire la barre latérale n'affiche que les icônes.", + "Son état est conservé dans le navigateur et appliqué immédiatement.", + "La langue est enregistrée par WGTools." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Actualisation de l'état", + "paragraphs": [ + "L'intervalle d'actualisation définit la fréquence de rafraîchissement des états serveur/client. Le seuil En ligne définit combien de temps après un handshake un pair est considéré connecté." + ], + "bullets": [], + "example_title": "Exemple", + "example_lines": [ + "Actualisation: 5 s", + "En ligne: 180 s" + ], + "warning": "" + }, + { + "title": "Sauvegardes automatiques de configuration", + "paragraphs": [ + "WGTools conserve un historique des configurations WireGuard avant les opérations risquées afin de revenir rapidement sur un changement." + ], + "bullets": [ + "Vous pouvez définir le nombre de copies conservées.", + "Cet historique diffère de la sauvegarde portable complète de WGTools." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Sauvegarde complète et restauration", + "paragraphs": [ + "Un fichier .wgtbackup sert aux migrations et à la reprise après incident." + ], + "bullets": [ + "Il inclut configurations WireGuard, base des utilisateurs et paramètres, groupes, données des clients, paramètres Telegram/SMTP et état nécessaire pour restaurer VPS Relay/Nodes.", + "Avant restauration, WGTools vérifie l'archive et sauvegarde l'état actuel. En cas d'échec, il tente un retour arrière automatique.", + "Après une restauration réussie, la session web actuelle est terminée : reconnectez-vous avec un compte de la base restaurée." + ], + "example_title": "", + "example_lines": [], + "warning": ".wgtbackup contient clés privées, PSK, empreintes des mots de passe, jeton Telegram et mot de passe SMTP. Conservez-le comme un mot de passe." + }, + { + "title": "Bot Telegram", + "paragraphs": [ + "Telegram permet de consulter et gérer WireGuard sans ouvrir le panneau web." + ], + "bullets": [ + "Créez un bot avec @BotFather, collez son jeton, activez-le et envoyez /start.", + "Si votre identifiant Telegram n'est pas autorisé, le bot indique son numéro : ajoutez-le à la liste autorisée.", + "Les commandes d'administration fonctionnent uniquement dans les discussions privées : état, clients, création/suppression, réédition des configurations/QR et commandes WireGuard." + ], + "example_title": "Exemple", + "example_lines": [ + "Endpoint par défaut: vpn.example.com", + "DNS: 1.1.1.1, 8.8.8.8" + ], + "warning": "" + }, + { + "title": "E-mail / SMTP et récupération du mot de passe", + "paragraphs": [ + "SMTP permet la fonction « Mot de passe oublié ? » sur la page de connexion." + ], + "bullets": [ + "STARTTLS, TLS/SSL et SMTP simple sur un réseau local de confiance sont pris en charge. Le nom d'utilisateur peut rester vide si le serveur n'exige pas d'authentification.", + "Le mot de passe reste local et n'est jamais renvoyé au navigateur. Le bouton Test envoie un e-mail au destinataire choisi.", + "Les codes de récupération sont à usage unique, stockés sous forme de hachage, valables 15 minutes et limités en tentatives." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "HTTPS intégré", + "paragraphs": [ + "WGTools peut servir HTTPS directement, sans Nginx, Caddy ou proxy inverse externe." + ], + "bullets": [ + "Saisissez domaine/IP publique, e-mail, port HTTPS et chemin privé, puis Obtenir / renouveler le certificat. Cette action enregistre également les paramètres HTTPS.", + "HTTPS ne peut être activé qu'avec un certificat approprié. Après émission, activez-le et Enregistrer ; toute nouvelle adresse nécessite son certificat.", + "Le port TCP 80 doit être accessible depuis Internet pour la délivrance et le renouvellement. Le panneau utilise le port HTTPS choisi (443 ou 8443, par exemple). Un chemin comme /MyWGTools/ définit son URL ; les autres chemins renvoient 404 lorsque HTTPS intégré est activé.", + "WGTools affiche les ports occupés et n'arrête pas les serveurs web tiers ; un timer systemd renouvelle le certificat automatiquement.", + "Le chemin privé ne remplace pas l'authentification : évitez d'exposer le panneau et utilisez des identifiants robustes." + ], + "example_title": "Exemple", + "example_lines": [ + "https://wg.example.com/MyWGTools/" + ], + "warning": "Un chemin privé ne remplace pas l’authentification. N'exposez pas inutilement le panneau et utilisez des identifiants robustes." + }, + { + "title": "Utilisateurs", + "paragraphs": [ + "Le premier compte est créé lors de l'installation ; d'autres peuvent être ajoutés dans Paramètres." + ], + "bullets": [ + "Tous les utilisateurs disposent actuellement des mêmes droits ; e-mail et mot de passe peuvent être modifiés et des comptes supprimés.", + "Chacun peut activer MFA avec Google Authenticator ou une application TOTP et recevoir une fois des codes de récupération.", + "En cas de perte du téléphone, root peut désactiver MFA pour un utilisateur avec la commande wgtools. Le compte courant et le dernier compte restant ne peuvent être supprimés.", + "Un changement ou une récupération de mot de passe, ainsi que l'activation/désactivation MFA, invalident les anciennes sessions web." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Journal d'audit", + "paragraphs": [ + "L'audit répertorie les opérations d'administration web/Telegram importantes et l'historique utile des connexions WireGuard." + ], + "bullets": [ + "Les actions web indiquent le nom WGTools ; celles de Telegram contiennent @username si disponible et l'identifiant numérique.", + "Changements de configuration, consultation de fichiers/QR, mises à jour et erreurs utiles sont enregistrés.", + "Mots de passe, clés privées, PSK, jetons et contenu complet des configurations ne sont jamais inscrits au journal. Celui-ci est automatiquement purgé selon sa durée de conservation." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Mises à jour WGTools", + "paragraphs": [ + "WGTools vérifie régulièrement les versions stables sur GitHub mais n'installe rien sans confirmation explicite." + ], + "bullets": [ + "Une nouvelle version entraîne l'affichage d'un avis.", + "Avant la mise à jour, WGTools crée une sauvegarde .wgtbackup complète et une archive séparée pour revenir à l'ancienne version.", + "Si la nouvelle application ne démarre pas, il tente de restaurer l'ancienne. La version actuelle apparaît dans l'interface et dans À propos." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Commande wgtools et accès d'urgence", + "paragraphs": [ + "La commande root wgtools est utile lorsque le panneau web n'est plus accessible." + ], + "bullets": [ + "Elle indique l'état de WGTools, WireGuard, Nodes, Telegram, des tâches et du Relay Agent local ainsi que l'URL du panneau.", + "Elle peut démarrer, arrêter, redémarrer le panneau ou WireGuard et consulter les journaux. En cas de port HTTPS ou chemin privé erroné, elle peut désactiver HTTPS intégré et rétablir HTTP.", + "Elle permet également à root de désactiver MFA pour un utilisateur ayant perdu l'authentificateur et les codes.", + "La désinstallation retire panneau et services sans supprimer WireGuard ni les données réutilisables. FULL CLEANUP, après confirmation DELETE ALL, efface WGTools, Relay local et WireGuard sur cet hôte seulement ; les agents des autres VPS ne sont pas touchés." + ], + "example_title": "Exemple", + "example_lines": [ + "root@server:~# wgtools" + ], + "warning": "" + }, + { + "title": "Emplacement des données", + "paragraphs": [ + "La modification manuelle est rarement nécessaire, mais connaître ces chemins aide au dépannage et aux sauvegardes." + ], + "bullets": [], + "example_title": "Chemins principaux", + "example_lines": [ + "/etc/wireguard/wg0.conf — configuration WireGuard", + "/var/lib/wgtools/wgtools.db — utilisateurs et paramètres", + "/var/lib/wgtools/clients/ — données des clients gérés", + "/var/lib/wgtools/backups/ — historique de configuration", + "/var/lib/wgtools/update-backups/ — archives de retour arrière" + ], + "warning": "" + } + ] + } +] diff --git a/app/core/help_locales/it.json b/app/core/help_locales/it.json new file mode 100644 index 0000000..56ea08e --- /dev/null +++ b/app/core/help_locales/it.json @@ -0,0 +1,663 @@ +[ + { + "id": "dashboard", + "title": "Panoramica", + "intro": "La panoramica risponde a tre domande: WireGuard funziona, chi è connesso e il server è in buone condizioni?", + "topics": [ + { + "title": "Da dove iniziare", + "paragraphs": [ + "La barra superiore mostra l'interfaccia WireGuard selezionata. Se ce ne sono più di una, le pagine WGTools utilizzano quella attiva." + ], + "bullets": [ + "Avvia attiva WireGuard, Arresta lo ferma e Riavvia riavvia brevemente l'interfaccia.", + "Telefoni e computer normalmente si riconnettono da soli dopo un riavvio.", + "Quando l'interfaccia è ferma, i suoi client non possono collegarsi." + ], + "example_title": "Esempio", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24 · UDP 51820" + ], + "warning": "" + }, + { + "title": "CPU, memoria, rete e tempo di attività", + "paragraphs": [ + "Questi dati si riferiscono all'intero host Debian, non soltanto a WireGuard." + ], + "bullets": [ + "CPU indica il carico attuale del processore; Memoria mostra RAM utilizzata e totale.", + "Rete indica la velocità corrente di ricezione e trasmissione sull'interfaccia esterna.", + "Il tempo di attività decorre dall'ultimo avvio del sistema; i grafici delle ultime 24 ore aiutano a individuare carichi anomali e traffico persistente." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Chi è connesso", + "paragraphs": [ + "WireGuard non mantiene una sessione come un sito web. WGTools considera un client online se l'ultimo handshake è abbastanza recente." + ], + "bullets": [ + "Handshake è l'ultimo scambio di controllo WireGuard riuscito; Endpoint è l'IP pubblico e la porta utilizzati dal client.", + "«Mai» significa che il server non ha ancora ricevuto un handshake valido da quel peer.", + "La ricerca rapida filtra per nome, indirizzo VPN, tipo ed Endpoint." + ], + "example_title": "Esempio", + "example_lines": [ + "Telefono · 10.0.0.3/32", + "Endpoint: 203.0.113.25:63275", + "Handshake: 18 s fa" + ], + "warning": "" + }, + { + "title": "Traffico", + "paragraphs": [ + "WGTools conserva i totali RX/TX separatamente dai contatori temporanei di WireGuard; le statistiche rimangono anche dopo il riavvio dell'interfaccia o del server." + ], + "bullets": [ + "Il riquadro Traffico mostra il volume accumulato dell'interfaccia scelta; ogni client ha i propri totali RX/TX.", + "Reimposta ricomincia il conteggio dal momento corrente.", + "RX/TX nel riquadro Rete indica la velocità istantanea, non il volume accumulato." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Più interfacce WireGuard", + "paragraphs": [ + "Un singolo server può gestire varie VPN indipendenti, per esempio casa e ufficio." + ], + "bullets": [ + "Cambiare la scelta nella barra superiore non modifica la configurazione: seleziona solo i dati visibili in Panoramica, Server e Client.", + "Ogni interfaccia possiede indirizzi, porta, client, percorsi e regole di accesso propri." + ], + "example_title": "Esempio", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24", + "wg1 · Lavoro · 10.0.1.1/24" + ], + "warning": "" + } + ] + }, + { + "id": "server", + "title": "Server", + "intro": "Questa sezione gestisce interfacce WireGuard, instradamento, accesso alle reti, collegamenti Nodes e accesso pubblico tramite VPS Relay.", + "topics": [ + { + "title": "Reti VPN e interfacce WireGuard", + "paragraphs": [ + "Un'interfaccia WireGuard si comporta come una scheda di rete virtuale con una propria sottorete VPN. Ogni client riceve un indirizzo di quella rete." + ], + "bullets": [ + "I nomi di sistema sono di solito wg0, wg1 e così via. Un nome descrittivo come Home o Office serve solo per comodità.", + "ListenPort è la porta UDP a cui si collegano i client.", + "Di norma MTU può restare su Auto; va modificato manualmente solo per problemi di rete particolari, LTE o PPPoE." + ], + "example_title": "Esempio", + "example_lines": [ + "Rete VPN: 10.0.0.0/24", + "Indirizzo server: 10.0.0.1/24", + "Client: 10.0.0.2, 10.0.0.3, ...", + "Porta: UDP 51820" + ], + "warning": "" + }, + { + "title": "Prima configurazione e altre interfacce", + "paragraphs": [ + "Su un Debian pulito WGTools può installare WireGuard e creare la prima interfaccia tramite procedura guidata. In seguito puoi aggiungere wg1, wg2 ecc." + ], + "bullets": [ + "WGTools propone una sottorete VPN libera, una porta UDP e una tabella di policy routing.", + "Prima della creazione controlla le sovrapposizioni tra reti e le porte già occupate.", + "Ogni interfaccia ha chiavi e configurazione proprie; prima dell'eliminazione viene effettuato un backup e vengono rimossi i dati gestiti correlati." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "NAT spiegato semplicemente", + "paragraphs": [ + "NAT/MASQUERADE consente a un client VPN di raggiungere LAN o Internet usando come sorgente l'indirizzo del server WireGuard. In casa è spesso la scelta più semplice." + ], + "bullets": [ + "Con NAT attivo, di solito il router domestico non ha bisogno di una rotta di ritorno specifica verso la VPN.", + "Senza NAT, il routing reale richiede rotte di ritorno sui router vicini." + ], + "example_title": "Esempio", + "example_lines": [ + "Telefono 10.0.0.3 → WGTools 192.168.1.10 → Internet", + "Il router di casa vede la sorgente 192.168.1.10" + ], + "warning": "" + }, + { + "title": "Rotte e policy routing", + "paragraphs": [ + "Una rotta indica a Linux quale interfaccia o gateway conduce a una rete. Il policy routing permette di scegliere una tabella separata per un traffico specifico, ad esempio quello dei client VPN." + ], + "bullets": [ + "Una semplice installazione domestica spesso non richiede una tabella dedicata.", + "È utile se i client devono usare un gateway specifico, un'altra VPN o una WAN separata.", + "WGTools distingue rotte di sistema, Site-to-Site e manuali. Le rotte personalizzate si possono aggiungere, modificare ed eliminare." + ], + "example_title": "Esempio", + "example_lines": [ + "Sorgente: 10.0.0.0/24", + "Tabella: 200", + "Default via: 192.168.1.1 dev eth0" + ], + "warning": "" + }, + { + "title": "Firewall e accesso alla rete", + "paragraphs": [ + "Il firewall stabilisce se un traffico è consentito; il routing determina soltanto dove inviarlo. Sono due aspetti diversi." + ], + "bullets": [ + "Puoi consentire o bloccare a un client VPN l'accesso a una determinata rete.", + "WGTools genera automaticamente le regole di gruppo e le eccezioni per singolo client.", + "Prima delle modifiche esegue un backup e ripristina la configurazione precedente se WireGuard non si avvia." + ], + "example_title": "Esempio", + "example_lines": [ + "10.0.0.6/32 → blocca → 192.168.1.0/24", + "Gli altri client possono ancora raggiungere la LAN" + ], + "warning": "" + }, + { + "title": "Site-to-Site: collegare due reti", + "paragraphs": [ + "Site-to-Site serve quando un peer rappresenta un'intera rete remota anziché un singolo telefono o laptop." + ], + "bullets": [ + "Indica le reti dietro al peer nel campo Reti remote: WGTools crea automaticamente le rotte.", + "Il passaggio del peer a offline non elimina le rotte configurate.", + "Anche il lato remoto deve avere una rotta di ritorno tramite WireGuard." + ], + "example_title": "Esempio", + "example_lines": [ + "Home: 192.168.1.0/24", + "Peer ufficio: 10.0.0.20/32", + "LAN ufficio: 192.168.50.0/24", + "Risultato: i dispositivi di casa raggiungono 192.168.50.x" + ], + "warning": "" + }, + { + "title": "Nodes: collegare server WGTools", + "paragraphs": [ + "Nodes collega più installazioni WGTools con un tunnel WireGuard interno dedicato. Un server diventa HUB e gli altri si associano con un codice monouso." + ], + "bullets": [ + "L'HUB usa lo stesso numero di porta in UDP per WireGuard e in TCP per l'associazione iniziale protetta. Poi la sincronizzazione passa dentro wgnode0, indipendentemente dall'URL del pannello, dalla porta HTTPS e dal percorso privato.", + "WGTools rileva reti VPN, Site-to-Site e LAN: pubblica solo quelle necessarie. Le reti individuate successivamente non vengono pubblicate automaticamente; vanno aggiunte esplicitamente. Le modifiche alle reti generano un avviso.", + "Le reti pubblicate su Nodes diversi non devono sovrapporsi (per esempio 10.0.0.0/24 in due siti). WGTools blocca i conflitti.", + "La vista Dettagli mostra reti e client remoti in sola lettura. Pubblicare una rete la rende raggiungibile dagli altri nodi: limita l'accesso al necessario." + ], + "example_title": "Esempio: home + VPS", + "example_lines": [ + "HUB: vpn.example.com:51950", + "Casa pubblica: 192.168.1.0/24", + "VPS pubblica: 10.20.0.0/24", + "Dopo l’associazione entrambi i lati passano da wgnode0" + ], + "warning": "" + }, + { + "title": "VPS Relay: casa senza IP pubblico", + "paragraphs": [ + "VPS Relay aiuta dietro CGNAT o quando i client non riescono a raggiungere direttamente il server. Un VPS pubblico diventa punto di ingresso; server WireGuard e regole rimangono sull'host WGTools." + ], + "bullets": [ + "Aggiungi il VPS via SSH: WGTools verifica host e porte e poi installa Relay Agent.", + "Un agente può servire diversi controller WGTools indipendenti con connessioni e chiavi separate.", + "I client supportati possono collegarsi direttamente o tramite Relay. Rimuovere il VPS dal pannello scollega il trasporto locale ma conserva agente e tenant sul VPS per una futura riconnessione.", + "Relay offre un ingresso pubblico ai client; Nodes collega i server WGTools e le loro reti. Sono funzioni diverse." + ], + "example_title": "Esempio", + "example_lines": [ + "Telefono → VPS pubblico → trasporto Relay protetto → WGTools di casa → rete necessaria" + ], + "warning": "" + }, + { + "title": "Diagnostica", + "paragraphs": [ + "La diagnostica controlla WireGuard, inoltro IP, porte, rotte e servizi, utile quando un client non si collega o una rete non risponde." + ], + "bullets": [ + "Verifica prima che l'interfaccia sia attiva e che esista un handshake recente. Se l'handshake funziona ma la destinazione no, controlla rotte, firewall e percorso di ritorno.", + "Server → Percorso mostra gli hop di traceroute che rispondono, RTT medio e aumento della latenza. Gli hop senza risposta vengono indicati in modo neutro, non come guasti accertati.", + "La mappa interattiva consente spostamento e zoom; toccando un hop appaiono IP, località approssimativa, ASN/provider e RTT.", + "Con la mappa attiva, gli IP pubblici vengono geolocalizzati tramite ipwho.is e le mappe caricate da OpenStreetMap; gli IP privati non vengono inviati. Traceroute non misura la banda in Mbit/s.", + "La diagnostica di per sé non cambia la configurazione." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Applicazione sicura delle modifiche", + "paragraphs": [ + "Le modifiche a server, rotte e firewall possono richiedere un breve riavvio di WireGuard." + ], + "bullets": [ + "WGTools salva prima una copia della configurazione.", + "Se la nuova configurazione non si avvia, tenta di ripristinare automaticamente quella precedente.", + "I client possono disconnettersi per poco e di norma si ricollegano da soli." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Scheda Configurazione", + "paragraphs": [ + "È un editor diretto di /etc/wireguard/.conf per opzioni non esposte dai moduli standard." + ], + "bullets": [ + "Usalo solo se conosci la sintassi WireGuard e i comandi PostUp/PostDown.", + "WGTools convalida ed esegue un backup del file prima di applicarlo.", + "Una configurazione insolita può limitare la modifica automatica per proteggere regole manuali. Non condividere PrivateKey, PresharedKey o altri segreti." + ], + "example_title": "Esempio", + "example_lines": [ + "[Interface]", + "Address = 10.0.0.1/24", + "ListenPorta = 51820", + "", + "[Peer]", + "AllowedIPs = 10.0.0.2/32" + ], + "warning": "Non condividere PrivateKey, PresharedKey o altri segreti." + } + ] + }, + { + "id": "clients", + "title": "Client", + "intro": "Un client può essere un telefono, laptop, router o altro peer WireGuard. Questa pagina gestisce configurazioni, criteri di accesso, scadenze, orari e Site-to-Site.", + "topics": [ + { + "title": "Client normale", + "paragraphs": [ + "Scegli Client per telefoni e computer. WGTools assegna un indirizzo VPN libero e crea le chiavi." + ], + "bullets": [ + "Il nome è soltanto un'etichetta dentro WGTools.", + "Endpoint nella configurazione generata è l'indirizzo usato dal dispositivo per trovare il server WireGuard.", + "Il DNS può essere specifico del client oppure ereditato da un modello di gruppo." + ], + "example_title": "Esempio", + "example_lines": [ + "Nome: Telefono", + "Indirizzo VPN: 10.0.0.3/32", + "Endpoint: vpn.example.com:51820" + ], + "warning": "" + }, + { + "title": "Traffico VPN e AllowedIPs", + "paragraphs": [ + "AllowedIPs nella configurazione del client definisce cosa il dispositivo invia nel tunnel. È diverso dai permessi configurati sul server." + ], + "bullets": [ + "Tutto il traffico inoltra sia Internet sia le reti remote nella VPN; puoi anche selezionare soltanto alcune reti.", + "L'esclusione della rete locale permette di raggiungere direttamente stampante o router pur usando Internet tramite VPN.", + "Il server può bloccare una destinazione anche se compare in AllowedIPs." + ], + "example_title": "Esempio", + "example_lines": [ + "0.0.0.0/0 — tutto il traffico IPv4 nella VPN", + "192.168.50.0/24 — solo una rete remota" + ], + "warning": "" + }, + { + "title": "Gruppi di client", + "paragraphs": [ + "Un gruppo permette di definire una volta sola regole e modello di configurazione da riutilizzare per diversi client." + ], + "bullets": [ + "I gruppi regolano accesso a Internet, LAN ed eccezioni di consenso o blocco.", + "Possono fornire rotte, DNS e Keepalive predefiniti alle nuove configurazioni.", + "Le modifiche dei criteri server sono immediate, ma un file già installato sul telefono non cambia da solo: applica il modello aggiornato e consegna un nuovo file o QR se necessario." + ], + "example_title": "Esempio", + "example_lines": [ + "Gruppo «Ospiti»", + "Internet: consentito", + "LAN: bloccata", + "Membri: Telefono-1, Tabellat-1" + ], + "warning": "" + }, + { + "title": "Criteri del singolo client", + "paragraphs": [ + "Un client può ereditare i criteri del gruppo oppure avere eccezioni proprie." + ], + "bullets": [ + "Un'eccezione per il singolo client, sia di consenso sia di blocco, prevale su quella di gruppo.", + "Per esempio, un dipendente può accedere a un server vietato agli altri membri del gruppo." + ], + "example_title": "Esempio", + "example_lines": [ + "Il gruppo blocca 192.168.1.0/24", + "Il client consente anche 192.168.1.50/32" + ], + "warning": "" + }, + { + "title": "Client Site-to-Site", + "paragraphs": [ + "Usa Site-to-Site quando un peer rappresenta un'intera rete. Inserisci le reti dietro al peer come Reti remote." + ], + "bullets": [ + "WGTools aggiunge automaticamente le relative rotte al server.", + "Successivamente possono essere pubblicate tramite Nodes.", + "Un normale telefono o laptop non richiede la modalità Site-to-Site." + ], + "example_title": "Esempio", + "example_lines": [ + "Peer router: 10.0.0.20/32", + "Rete remota: 192.168.50.0/24" + ], + "warning": "" + }, + { + "title": "Connessione diretta e VPS Relay", + "paragraphs": [ + "Quando VPS Relay è installato per l'interfaccia, i client compatibili possono scegliere la connessione diretta o tramite Relay." + ], + "bullets": [ + "La connessione diretta è preferibile quando la porta WireGuard è raggiungibile da Internet.", + "Relay aiuta con CGNAT o in assenza di UDP in ingresso.", + "Indirizzo VPN e criteri di accesso del client non cambiano." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "PSK, isolamento e rotazione delle chiavi", + "paragraphs": [ + "WireGuard usa già chiavi pubbliche/private. Un PSK opzionale aggiunge un segreto condiviso." + ], + "bullets": [ + "L'isolamento impedisce al client di comunicare con altri indirizzi della stessa rete VPN.", + "La rotazione crea una nuova coppia di chiavi e, se abilitato, un nuovo PSK. La vecchia configurazione smette di funzionare: consegna un nuovo file o QR.", + "Indirizzo VPN, gruppo, orari e statistiche del traffico restano invariati." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Accesso temporaneo", + "paragraphs": [ + "Un client può scadere dopo 1, 3 o 6 ore, un giorno oppure a una data e ora personalizzate." + ], + "bullets": [ + "Alla scadenza il servizio in background esegue l'azione scelta.", + "Per riattivare un client scaduto ma salvato, imposta una nuova scadenza oppure Nessun limite." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Programmazione degli accessi", + "paragraphs": [ + "Gli orari abilitano e bloccano automaticamente un client in giorni e fasce prestabilite senza sostituirne la configurazione." + ], + "bullets": [ + "Si utilizza l'ora locale del server WireGuard.", + "Le fasce possono attraversare la mezzanotte, per esempio 22:00–06:00.", + "Al successivo periodo consentito WGTools ripristina lo stesso peer." + ], + "example_title": "Esempio", + "example_lines": [ + "Lun–Ven: 08:00–19:00" + ], + "warning": "" + }, + { + "title": "Stato, Endpoint e traffico", + "paragraphs": [ + "La tabella mostra ultimo handshake, Endpoint e totali RX/TX." + ], + "bullets": [ + "Un handshake recente indica che il client ha comunicato da poco con il server.", + "L'Endpoint di un telefono può cambiare passando tra Wi-Fi e LTE: è normale.", + "La ricerca rapida filtra per nome, indirizzo, gruppo e stato." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Configurazione e QR", + "paragraphs": [ + "Un file .conf è adatto a computer e router, mentre il QR all'app mobile WireGuard." + ], + "bullets": [ + "La PrivateKey del client si trova sia nel file sia nel QR: proteggili come una password.", + "La nuova emissione della configurazione di un client gestito riutilizza le chiavi conservate in WGTools.", + "Dopo la rotazione delle chiavi fornisci sempre una nuova configurazione." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Modifica ed eliminazione", + "paragraphs": [ + "WGTools esegue un backup della configurazione WireGuard prima delle modifiche gestite e le applica in sicurezza." + ], + "bullets": [ + "Eliminare un client gestito rimuove peer, chiavi archiviate e relative regole.", + "Un file già salvato sul dispositivo non viene cancellato da remoto, ma non può più stabilire la connessione." + ], + "example_title": "", + "example_lines": [], + "warning": "" + } + ] + }, + { + "id": "settings", + "title": "Impostazioni", + "intro": "Qui trovi aspetto, backup, Telegram, e-mail, HTTPS, utenti, audit e aggiornamenti.", + "topics": [ + { + "title": "Aspetto e lingua", + "paragraphs": [ + "Scegli il tema chiaro, scuro o di sistema e la lingua dell'interfaccia." + ], + "bullets": [ + "Ridurre la barra laterale lascia visibili solo le icone.", + "Lo stato della barra viene memorizzato nel browser e cambia subito.", + "La lingua scelta viene salvata da WGTools." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Aggiornamento dello stato", + "paragraphs": [ + "L'intervallo di aggiornamento definisce la frequenza con cui vengono aggiornati i dati di server e client. La soglia online stabilisce per quanto tempo dopo un handshake un peer risulta connesso." + ], + "bullets": [], + "example_title": "Esempio", + "example_lines": [ + "Aggiornamento: 5 s", + "Online: 180 s" + ], + "warning": "" + }, + { + "title": "Backup automatici della configurazione", + "paragraphs": [ + "Prima delle modifiche rischiose WGTools conserva una cronologia delle configurazioni WireGuard per ripristinare rapidamente quella precedente." + ], + "bullets": [ + "Puoi scegliere il numero di copie conservate.", + "Questa cronologia è diversa dal backup completo e portabile di WGTools." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Backup completo e ripristino", + "paragraphs": [ + "Il file .wgtbackup serve per migrare su un nuovo server o recuperare dopo un guasto." + ], + "bullets": [ + "Include configurazioni WireGuard, database di utenti/impostazioni, gruppi, dati dei client, impostazioni Telegram/SMTP e stato necessario per ripristinare VPS Relay/Nodes.", + "WGTools verifica l'archivio e salva lo stato attuale prima del ripristino. Se l'operazione fallisce, tenta un rollback automatico.", + "Dopo il ripristino la sessione web corrente viene chiusa; accedi con un account del database ripristinato." + ], + "example_title": "", + "example_lines": [], + "warning": ".wgtbackup contiene chiavi private, PSK, hash delle password, token Telegram e password SMTP. Custodiscilo come una password." + }, + { + "title": "Bot Telegram", + "paragraphs": [ + "Telegram permette di controllare e gestire WireGuard senza aprire il pannello web." + ], + "bullets": [ + "Crea il bot con @BotFather, incolla il token, attivalo e invia /start.", + "Se il tuo ID Telegram non è autorizzato, il bot mostra l'ID numerico: aggiungilo alla lista consentita.", + "I comandi amministrativi sono accettati soltanto nelle chat private: stato, client, creazione/eliminazione, riconsegna configurazioni/QR e gestione WireGuard." + ], + "example_title": "Esempio", + "example_lines": [ + "Endpoint predefinito: vpn.example.com", + "DNS: 1.1.1.1, 8.8.8.8" + ], + "warning": "" + }, + { + "title": "E-mail / SMTP e recupero password", + "paragraphs": [ + "SMTP gestisce «Password dimenticata?» nella schermata di accesso." + ], + "bullets": [ + "Sono supportati STARTTLS, TLS/SSL e SMTP semplice su una LAN affidabile. Il nome utente può essere vuoto se il server SMTP non richiede autenticazione.", + "La password resta salvata localmente e non viene mai restituita al browser. Il pulsante Test invia un messaggio all'indirizzo scelto.", + "I codici di recupero sono monouso, memorizzati come hash, validi 15 minuti e limitati nei tentativi." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "HTTPS integrato", + "paragraphs": [ + "WGTools può fornire HTTPS senza Nginx, Caddy o proxy inversi esterni." + ], + "bullets": [ + "Inserisci dominio/IP pubblico, e-mail, porta HTTPS e percorso privato, poi scegli Ottieni / rinnova certificato. L'azione salva anche le impostazioni HTTPS.", + "HTTPS si può abilitare solo con un certificato appropriato. Dopo l'emissione attivalo e premi Salva; quando dominio o IP cambia serve un nuovo certificato.", + "La porta TCP 80 deve essere raggiungibile da Internet per emissione e rinnovo. Il pannello usa la porta scelta, per esempio 443 o 8443. Il percorso privato imposta l'URL, ad esempio /MyWGTools/; gli altri percorsi restituiscono 404 con HTTPS attivo.", + "WGTools indica le porte locali occupate e non arresta server web di terzi; un timer systemd rinnova automaticamente il certificato.", + "Un percorso privato non sostituisce l'autenticazione. Evita di esporre inutilmente il pannello e usa credenziali robuste." + ], + "example_title": "Esempio", + "example_lines": [ + "https://wg.example.com/MyWGTools/" + ], + "warning": "Un percorso privato non sostituisce l’autenticazione. Evita di esporre il pannello inutilmente e usa credenziali robuste." + }, + { + "title": "Utenti", + "paragraphs": [ + "Il primo utente viene creato durante la configurazione di WGTools. Altri utenti possono essere aggiunti da Impostazioni." + ], + "bullets": [ + "Attualmente tutti gli utenti hanno gli stessi permessi. È possibile cambiare e-mail/password ed eliminare account.", + "Ogni utente può abilitare MFA con Google Authenticator o app TOTP e ricevere una volta codici di recupero.", + "Se perde l'app di autenticazione, root può disattivare MFA tramite il comando wgtools. Non puoi eliminare l'utente corrente né l'ultimo account.", + "Modifiche o recupero password e attivazione/disattivazione MFA invalidano le vecchie sessioni web dell'utente." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Registro di audit", + "paragraphs": [ + "L'audit registra le operazioni di amministrazione web/Telegram e la cronologia utile delle connessioni WireGuard." + ], + "bullets": [ + "Le azioni web riportano il nome WGTools; quelle Telegram @username, se disponibile, e ID numerico.", + "Sono registrati cambiamenti di configurazione, visualizzazione di configurazioni/QR, aggiornamenti ed errori rilevanti.", + "Password, chiavi private, PSK, token e configurazioni complete non vengono registrati. Il registro viene cancellato automaticamente alla fine del periodo di conservazione." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Aggiornamenti WGTools", + "paragraphs": [ + "WGTools controlla periodicamente le versioni stabili su GitHub ma non installa aggiornamenti senza conferma esplicita." + ], + "bullets": [ + "Una nuova versione genera un avviso.", + "Prima di aggiornare crea un backup .wgtbackup completo e un archivio separato per il rollback dell'applicazione.", + "Se la nuova versione non parte, prova a ripristinare quella precedente. La versione corrente è mostrata nell'interfaccia e in Informazioni." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Comando wgtools e accesso di emergenza", + "paragraphs": [ + "Il comando root wgtools è utile quando il pannello web non è raggiungibile." + ], + "bullets": [ + "Mostra stato di WGTools, WireGuard, Nodes, Telegram, timer e Relay Agent locale e URL del pannello.", + "Può avviare, fermare e riavviare pannello e WireGuard e leggere i log. Con porta HTTPS o percorso privato errati permette di disabilitare HTTPS integrato e tornare a HTTP.", + "Consente a root di disabilitare MFA in emergenza se l'utente ha perso l'autenticatore e i codici.", + "Disinstallare WGTools rimuove pannello e servizi mantenendo WireGuard normale e dati riutilizzabili. FULL CLEANUP, dopo conferma DELETE ALL, cancella WGTools, Relay locale e WireGuard da questo host, senza toccare agenti Relay su altri VPS." + ], + "example_title": "Esempio", + "example_lines": [ + "root@server:~# wgtools" + ], + "warning": "" + }, + { + "title": "Dove sono archiviati i dati", + "paragraphs": [ + "Normalmente non occorre modificare i file a mano, ma i percorsi sono utili per diagnostica e pianificazione dei backup." + ], + "bullets": [], + "example_title": "Percorsi principali", + "example_lines": [ + "/etc/wireguard/wg0.conf — configurazione WireGuard", + "/var/lib/wgtools/wgtools.db — utenti e impostazioni", + "/var/lib/wgtools/clients/ — dati dei client gestiti", + "/var/lib/wgtools/backups/ — cronologia configurazioni", + "/var/lib/wgtools/update-backups/ — archivi rollback aggiornamento" + ], + "warning": "" + } + ] + } +] diff --git a/app/core/help_locales/pl.json b/app/core/help_locales/pl.json new file mode 100644 index 0000000..2909faa --- /dev/null +++ b/app/core/help_locales/pl.json @@ -0,0 +1,662 @@ +[ + { + "id": "dashboard", + "title": "Pulpit", + "intro": "Pulpit szybko pokazuje, czy WireGuard działa, kto jest połączony oraz czy serwer funkcjonuje prawidłowo.", + "topics": [ + { + "title": "Od czego zacząć", + "paragraphs": [ + "Górny pasek pokazuje wybrany interfejs WireGuard. Jeśli jest ich kilka, strony WGTools dotyczą właśnie wybranego interfejsu." + ], + "bullets": [ + "Uruchom włącza WireGuard, Zatrzymaj go wyłącza, a Uruchom ponownie wykonuje krótki restart.", + "Telefony i komputery zazwyczaj łączą się ponownie automatycznie.", + "Gdy interfejs jest zatrzymany, jego klienci nie mogą się połączyć." + ], + "example_title": "Przykład", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24 · UDP 51820" + ], + "warning": "" + }, + { + "title": "Procesor, pamięć, sieć i czas działania", + "paragraphs": [ + "Wskaźniki dotyczą całego serwera Debian, a nie tylko WireGuard." + ], + "bullets": [ + "CPU pokazuje bieżące obciążenie procesora, a pamięć — zajętą i łączną ilość RAM.", + "Sieć pokazuje aktualną szybkość odbioru i wysyłania danych przez interfejs zewnętrzny.", + "Czas działania liczy się od ostatniego uruchomienia systemu; wykresy z 24 godzin pomagają wykryć anomalie." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Kto jest połączony", + "paragraphs": [ + "WireGuard nie utrzymuje sesji tak jak strona WWW. WGTools uznaje klienta za online, gdy ostatni handshake jest dostatecznie świeży." + ], + "bullets": [ + "Handshake to ostatnia udana wymiana kontrolna WireGuard; Endpoint to publiczny adres IP i port klienta.", + "„Nigdy” oznacza, że serwer nie odnotował dotąd udanego handshake tego peera.", + "Szybkie wyszukiwanie filtruje po nazwie, adresie VPN, typie i Endpoint." + ], + "example_title": "Przykład", + "example_lines": [ + "Telefon · 10.0.0.3/32", + "Endpoint: 203.0.113.25:63275", + "Handshake: 18 s temu" + ], + "warning": "" + }, + { + "title": "Ruch sieciowy", + "paragraphs": [ + "WGTools przechowuje sumy RX/TX niezależnie od tymczasowych liczników WireGuard, dzięki czemu statystyki przetrwają ponowne uruchomienie interfejsu lub serwera." + ], + "bullets": [ + "Karta Ruch pokazuje łączną ilość danych wybranego interfejsu; każdy klient ma własne sumy RX/TX.", + "Reset rozpoczyna zliczanie od bieżącej chwili.", + "RX/TX na karcie Sieć oznacza bieżącą prędkość, nie łączną ilość danych." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Wiele interfejsów WireGuard", + "paragraphs": [ + "Na jednym serwerze można uruchomić kilka niezależnych sieci VPN, na przykład domową i firmową." + ], + "bullets": [ + "Zmiana interfejsu w górnym pasku nie modyfikuje konfiguracji; wybiera tylko dane widoczne na stronach Pulpit, Serwer i Klienci.", + "Każdy interfejs ma własne adresy, port, klientów, trasy i reguły dostępu." + ], + "example_title": "Przykład", + "example_lines": [ + "wg0 · Home · 10.0.0.1/24", + "wg1 · Praca · 10.0.1.1/24" + ], + "warning": "" + } + ] + }, + { + "id": "server", + "title": "Serwer", + "intro": "Tutaj zarządzasz interfejsami WireGuard, trasami, dostępem do sieci, połączeniami Nodes oraz publicznym dostępem przez VPS Relay.", + "topics": [ + { + "title": "Sieci VPN i interfejsy WireGuard", + "paragraphs": [ + "Interfejs WireGuard działa jak wirtualna karta sieciowa z własną podsiecią VPN. Każdy klient otrzymuje adres z tej podsieci." + ], + "bullets": [ + "Nazwy systemowe to zwykle wg0, wg1 itd.; nazwa opisowa, np. Home, służy jedynie wygodzie.", + "ListenPort to port UDP, na którym serwer oczekuje na klientów.", + "MTU zwykle pozostawia się na Auto; ręczna zmiana bywa potrzebna przy problemach z LTE, PPPoE lub konkretną siecią." + ], + "example_title": "Przykład", + "example_lines": [ + "Sieć VPN: 10.0.0.0/24", + "Adres serwera: 10.0.0.1/24", + "Klienci: 10.0.0.2, 10.0.0.3, ...", + "Port: UDP 51820" + ], + "warning": "" + }, + { + "title": "Pierwsza instalacja i dodatkowe interfejsy", + "paragraphs": [ + "Na czystym Debianie WGTools może zainstalować WireGuard i utworzyć pierwszy interfejs przez kreator. Później dodasz kolejne, np. wg1 i wg2." + ], + "bullets": [ + "WGTools proponuje wolną podsieć VPN, port UDP i tabelę routingu polityk.", + "Przed utworzeniem sprawdza nakładanie się podsieci oraz zajęte porty.", + "Każdy interfejs dostaje osobne klucze i konfigurację; przed usunięciem tworzona jest kopia zapasowa, a zarządzane dane są czyszczone." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "NAT w prostych słowach", + "paragraphs": [ + "NAT/MASQUERADE pozwala klientowi VPN korzystać z LAN lub Internetu przy użyciu adresu serwera WireGuard jako źródła. To często najprostsze rozwiązanie w domu." + ], + "bullets": [ + "Przy włączonym NAT router domowy zwykle nie wymaga osobnej trasy powrotnej do podsieci VPN.", + "Bez NAT konieczne jest prawidłowe wyznaczenie tras powrotnych na sąsiednich routerach." + ], + "example_title": "Przykład", + "example_lines": [ + "Telefon 10.0.0.3 → WGTools 192.168.1.10 → Internet", + "Router domowy widzi źródło 192.168.1.10" + ], + "warning": "" + }, + { + "title": "Trasy i routing oparty na regułach", + "paragraphs": [ + "Trasa wskazuje systemowi Linux interfejs lub bramę prowadzącą do danej sieci. Routing oparty na regułach może korzystać z osobnej tablicy dla określonego ruchu, np. klientów VPN." + ], + "bullets": [ + "Prosta instalacja domowa często nie potrzebuje osobnej tablicy.", + "Jest ona przydatna przy wymuszaniu konkretnej bramy, innego VPN lub odrębnego WAN.", + "WGTools rozdziela trasy systemowe, Site-to-Site i ręczne; własne trasy można dodawać, edytować i usuwać." + ], + "example_title": "Przykład", + "example_lines": [ + "Źródło: 10.0.0.0/24", + "Tabela: 200", + "Default via: 192.168.1.1 dev eth0" + ], + "warning": "" + }, + { + "title": "Zapora i dostęp do sieci", + "paragraphs": [ + "Zapora decyduje, czy ruch jest dozwolony; trasa określa jedynie, dokąd pakiet zostanie wysłany." + ], + "bullets": [ + "Możesz zezwalać lub blokować dostęp klienta VPN do konkretnych sieci.", + "WGTools automatycznie tworzy reguły grup i wyjątki klientów.", + "Przed zmianą tworzy kopię konfiguracji, a jeśli WireGuard nie uruchomi się, przywraca poprzednią wersję." + ], + "example_title": "Przykład", + "example_lines": [ + "10.0.0.6/32 → blokada → 192.168.1.0/24", + "Pozostali klienci nadal mają dostęp do LAN" + ], + "warning": "" + }, + { + "title": "Site-to-Site: łączenie dwóch sieci", + "paragraphs": [ + "Tryb Site-to-Site służy peerowi reprezentującemu całą sieć zdalną, a nie pojedynczy telefon czy komputer." + ], + "bullets": [ + "Podaj sieci za peerem w polu Sieci zdalne; WGTools utworzy trasy automatycznie.", + "Przejście peera w tryb offline nie usuwa skonfigurowanych tras.", + "Po stronie zdalnej również musi istnieć trasa powrotna przez WireGuard." + ], + "example_title": "Przykład", + "example_lines": [ + "Home: 192.168.1.0/24", + "Peer biurowy: 10.0.0.20/32", + "LAN biura: 192.168.50.0/24", + "Wynik: urządzenia domowe osiągają 192.168.50.x" + ], + "warning": "" + }, + { + "title": "Nodes: łączenie serwerów WGTools", + "paragraphs": [ + "Nodes łączy instalacje WGTools przez wewnętrzny tunel WireGuard. Jeden serwer jest HUB-em, pozostałe dołączają za pomocą jednorazowego kodu." + ], + "bullets": [ + "HUB używa jednego numeru portu: UDP dla WireGuard i TCP do bezpiecznego początkowego parowania. Później synchronizacja odbywa się przez wgnode0, niezależnie od adresu panelu, HTTPS i ścieżki prywatnej.", + "WGTools wykrywa sieci VPN, Site-to-Site i LAN, ale publikuj tylko potrzebne. Nowo wykryte sieci trzeba dodać ręcznie; zmiany sieci powodują ostrzeżenie.", + "Sieci publikowane przez różne węzły nie mogą na siebie zachodzić (np. 10.0.0.0/24 w dwóch lokalizacjach). Szczegóły pokazują zdalne sieci i klientów tylko do odczytu.", + "Publikacja sieci otwiera ją dla połączonych węzłów — udostępniaj wyłącznie niezbędne zasoby." + ], + "example_title": "Przykład: home + VPS", + "example_lines": [ + "HUB: vpn.example.com:51950", + "Dom publikuje: 192.168.1.0/24", + "VPS publikuje: 10.20.0.0/24", + "Po sparowaniu obie strony kierują ruch przez wgnode0" + ], + "warning": "" + }, + { + "title": "VPS Relay: gdy dom nie ma publicznego IP", + "paragraphs": [ + "VPS Relay pomaga za CGNAT lub tam, gdzie klienci nie mogą bezpośrednio dotrzeć do serwera. Publiczny VPS staje się punktem wejścia, a WireGuard i zasady dostępu pozostają na hoście WGTools." + ], + "bullets": [ + "Dodaj VPS przez SSH: WGTools sprawdzi serwer i porty, a potem zainstaluje Relay Agent.", + "Jeden agent może obsłużyć kilka niezależnych kontrolerów WGTools z oddzielnymi kluczami i połączeniami.", + "Obsługiwani klienci mogą używać połączenia bezpośredniego albo Relay. Usunięcie VPS z panelu odłącza transport lokalny, lecz pozostawia agenta i dzierżawcę do ponownego połączenia.", + "Relay daje klientom publiczny punkt wejścia; Nodes łączy serwery WGTools i ich sieci — to różne funkcje." + ], + "example_title": "Przykład", + "example_lines": [ + "Telefon → publiczny VPS → chroniony transport Relay → domowy WGTools → wymagana sieć" + ], + "warning": "" + }, + { + "title": "Diagnostyka", + "paragraphs": [ + "Diagnostyka sprawdza działanie WireGuard, przekazywanie IP, porty, trasy i usługi. Przydaje się, gdy klient nie może się połączyć lub osiągnąć sieci zdalnej." + ], + "bullets": [ + "Najpierw sprawdź stan interfejsu i ostatni handshake; jeśli handshake działa, szukaj problemu w trasach, zaporze albo drodze powrotnej.", + "Karta Serwer → Trasa pokazuje hop-y traceroute, średni RTT i przyrost opóźnienia. Brak odpowiedzi w traceroute nie oznacza automatycznie awarii.", + "Mapa pozwala przesuwać widok i przybliżać; kliknięcie hop-u pokazuje IP, przybliżoną lokalizację, ASN/operatora i RTT.", + "Przy włączonej mapie publiczne IP są geolokalizowane przez ipwho.is, a kafelki pobierane z OpenStreetMap; prywatne IP nie są wysyłane. Traceroute nie mierzy przepustowości Mbit/s.", + "Samo uruchomienie diagnostyki nie zmienia konfiguracji." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Bezpieczne stosowanie zmian", + "paragraphs": [ + "Zmiany serwera, tras i zapory mogą wymagać krótkiego restartu WireGuard." + ], + "bullets": [ + "WGTools najpierw zapisuje kopię konfiguracji.", + "Gdy nowa konfiguracja nie uruchamia się, program próbuje automatycznie przywrócić poprzednią.", + "Klienci mogą na chwilę utracić połączenie; zazwyczaj sami łączą się ponownie." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Karta Konfiguracja", + "paragraphs": [ + "To bezpośredni edytor pliku /etc/wireguard/.conf dla ustawień niedostępnych w zwykłych formularzach." + ], + "bullets": [ + "Korzystaj z niego wyłącznie ze znajomością składni WireGuard i poleceń PostUp/PostDown.", + "WGTools sprawdza plik i wykonuje kopię przed zastosowaniem zmian.", + "Nietypowa konfiguracja może ograniczać automatyczną edycję, aby chronić ręcznie dodane reguły. Nie ujawniaj PrivateKey, PresharedKey ani innych sekretów." + ], + "example_title": "Przykład", + "example_lines": [ + "[Interface]", + "Address = 10.0.0.1/24", + "ListenPort = 51820", + "", + "[Peer]", + "AllowedIPs = 10.0.0.2/32" + ], + "warning": "Nie ujawniaj PrivateKey, PresharedKey ani innych sekretów." + } + ] + }, + { + "id": "clients", + "title": "Klienci", + "intro": "Klientem może być telefon, laptop, router lub inny peer WireGuard. Tutaj tworzysz konfiguracje, zasady dostępu, terminy wygaśnięcia, harmonogramy i połączenia Site-to-Site.", + "topics": [ + { + "title": "Zwykły klient", + "paragraphs": [ + "Wybierz typ Klient dla telefonu lub komputera. WGTools przydzieli wolny adres VPN i utworzy klucze." + ], + "bullets": [ + "Nazwa jest tylko etykietą w WGTools.", + "Endpoint w utworzonym pliku to adres, pod którym urządzenie znajduje serwer WireGuard.", + "DNS może być własny dla klienta lub dziedziczony z szablonu grupy." + ], + "example_title": "Przykład", + "example_lines": [ + "Nazwa: Telefon", + "Adres VPN: 10.0.0.3/32", + "Endpoint: vpn.example.com:51820" + ], + "warning": "" + }, + { + "title": "Ruch przez VPN i AllowedIPs", + "paragraphs": [ + "AllowedIPs w konfiguracji klienta określa, co urządzenie wysyła do tunelu. To coś innego niż reguły dostępu po stronie serwera." + ], + "bullets": [ + "Tryb Cały ruch przesyła przez VPN zarówno Internet, jak i sieci zdalne; można też wybrać tylko określone sieci.", + "Wykluczenie sieci lokalnej pozwala zachować bezpośredni dostęp do drukarki czy routera przy korzystaniu z Internetu przez VPN.", + "Serwer może zablokować cel nawet wtedy, gdy znajduje się w AllowedIPs." + ], + "example_title": "Przykład", + "example_lines": [ + "0.0.0.0/0 — cały ruch IPv4 przez VPN", + "192.168.50.0/24 — tylko jedna sieć zdalna" + ], + "warning": "" + }, + { + "title": "Grupy klientów", + "paragraphs": [ + "Grupa pozwala raz skonfigurować zasady i szablon, a potem używać ich dla wielu klientów." + ], + "bullets": [ + "Grupy określają dostęp do Internetu, LAN oraz wyjątki zezwalające i blokujące.", + "Mogą też ustawiać domyślne trasy, DNS i Keepalive dla nowych klientów.", + "Zmiany zasad na serwerze działają od razu, ale istniejący plik na telefonie nie aktualizuje się sam. Zastosuj szablon i wydaj nowy plik lub QR, jeśli wymagane są zmiany w urządzeniu." + ], + "example_title": "Przykład", + "example_lines": [ + "Grupa „Goście”", + "Internet: dozwolony", + "LAN: zablokowany", + "Członkowie: Telefon-1, Tabelat-1" + ], + "warning": "" + }, + { + "title": "Zasady dla pojedynczego klienta", + "paragraphs": [ + "Klient może odziedziczyć politykę grupy albo mieć własne wyjątki." + ], + "bullets": [ + "Indywidualny wyjątek zezwalający lub blokujący ma pierwszeństwo przed odpowiednią regułą grupy.", + "Przykład: jeden pracownik może otrzymać dostęp do serwera zablokowanego dla reszty grupy." + ], + "example_title": "Przykład", + "example_lines": [ + "Grupa blokuje 192.168.1.0/24", + "Klient dodatkowo zezwala na 192.168.1.50/32" + ], + "warning": "" + }, + { + "title": "Klient Site-to-Site", + "paragraphs": [ + "Wybierz Site-to-Site, jeśli peer reprezentuje całą sieć. Wpisz sieci za peerem jako Sieci zdalne." + ], + "bullets": [ + "WGTools automatycznie doda te sieci do tras serwera.", + "Później można je opublikować przez Nodes.", + "Zwykły telefon lub laptop nie wymaga trybu Site-to-Site." + ], + "example_title": "Przykład", + "example_lines": [ + "Peer routera: 10.0.0.20/32", + "Sieć zdalna: 192.168.50.0/24" + ], + "warning": "" + }, + { + "title": "Połączenie bezpośrednie i VPS Relay", + "paragraphs": [ + "Gdy Relay działa dla danego interfejsu, obsługiwany klient może wybrać połączenie bezpośrednie albo pośrednie." + ], + "bullets": [ + "Połączenie bezpośrednie jest najlepsze, gdy port WireGuard jest osiągalny z Internetu.", + "Relay pomaga za CGNAT oraz gdy przychodzący UDP jest niedostępny.", + "Adres VPN i polityka dostępu klienta nie zmieniają się." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "PSK, izolacja i zmiana kluczy", + "paragraphs": [ + "WireGuard używa par kluczy publiczny/prywatny. Opcjonalny PSK dodaje współdzielony sekret." + ], + "bullets": [ + "Izolacja klienta blokuje jego komunikację z pozostałymi adresami tego samego VPN.", + "Zmiana kluczy tworzy nową parę i nowy PSK, jeśli jest włączony; poprzednia konfiguracja przestaje działać, więc trzeba przekazać nowy plik lub QR.", + "Adres VPN, grupa, harmonogram i historia ruchu pozostają bez zmian." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Dostęp tymczasowy", + "paragraphs": [ + "Dostęp klienta może wygasnąć po 1, 3 lub 6 godzinach, po jednym dniu albo w wybranym terminie." + ], + "bullets": [ + "Po upływie czasu usługa w tle wykonuje skonfigurowaną akcję wygaśnięcia.", + "Aby ponownie włączyć zachowanego klienta, ustaw nowy termin lub Brak limitu." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Harmonogram dostępu", + "paragraphs": [ + "Harmonogram automatycznie dopuszcza i blokuje klienta w wybrane dni i godziny bez zastępowania jego konfiguracji." + ], + "bullets": [ + "Korzysta z lokalnego czasu serwera WireGuard.", + "Okres może przechodzić przez północ, np. 22:00–06:00.", + "Gdy rozpoczyna się kolejny dozwolony okres, WGTools przywraca tego samego peera." + ], + "example_title": "Przykład", + "example_lines": [ + "Pon–Pt: 08:00–19:00" + ], + "warning": "" + }, + { + "title": "Status, Endpoint i ruch", + "paragraphs": [ + "Tabela pokazuje ostatni handshake, Endpoint oraz łączne RX/TX." + ], + "bullets": [ + "Świeży handshake oznacza niedawną komunikację klienta z serwerem.", + "Endpoint telefonu może zmieniać się przy przechodzeniu między Wi-Fi i LTE — to normalne.", + "Szybkie wyszukiwanie filtruje po nazwie, adresie, grupie i stanie." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Konfiguracja i kod QR", + "paragraphs": [ + "Plik .conf jest wygodny dla komputerów i routerów, a QR dla aplikacji mobilnej WireGuard." + ], + "bullets": [ + "PrivateKey klienta znajduje się w pliku i kodzie QR — chroń je jak hasło.", + "Ponowne wydanie konfiguracji klienta zarządzanego wykorzystuje klucze zapisane w WGTools.", + "Po zmianie kluczy zawsze wydaj nową konfigurację." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Edycja i usuwanie", + "paragraphs": [ + "WGTools tworzy kopię konfiguracji WireGuard przed zarządzanymi zmianami i bezpiecznie je stosuje." + ], + "bullets": [ + "Usunięcie klienta zarządzanego usuwa peera, zapisane klucze i związane reguły.", + "Plik już zapisany na urządzeniu nie znika zdalnie, ale nie pozwala się już połączyć." + ], + "example_title": "", + "example_lines": [], + "warning": "" + } + ] + }, + { + "id": "settings", + "title": "Ustawienia", + "intro": "Tutaj znajdują się wygląd, kopie zapasowe, Telegram, poczta, HTTPS, użytkownicy, dziennik audytu i aktualizacje.", + "topics": [ + { + "title": "Wygląd i język", + "paragraphs": [ + "Wybierz jasny, ciemny lub systemowy motyw oraz język interfejsu." + ], + "bullets": [ + "Zwężenie paska bocznego pozostawia w nawigacji tylko ikony.", + "Stan paska jest zapisywany w bieżącej przeglądarce i zmienia się od razu.", + "Język interfejsu zapisuje WGTools." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Odświeżanie statusu", + "paragraphs": [ + "Interwał odświeżania określa, jak często aktualizuje się stan serwera i klientów. Próg online określa, jak długo po handshake peer jest uznawany za połączonego." + ], + "bullets": [], + "example_title": "Przykład", + "example_lines": [ + "Odświeżanie: 5 s", + "Online: 180 s" + ], + "warning": "" + }, + { + "title": "Automatyczne kopie konfiguracji", + "paragraphs": [ + "Przed ryzykownymi zmianami WGTools zachowuje historię konfiguracji WireGuard, aby umożliwić szybkie cofnięcie zmian." + ], + "bullets": [ + "Możesz określić liczbę przechowywanych kopii.", + "Ta historia różni się od pełnej przenośnej kopii WGTools." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Pełna kopia i przywracanie", + "paragraphs": [ + "Plik .wgtbackup służy do migracji na nowy serwer i odzyskiwania po awarii." + ], + "bullets": [ + "Zawiera konfiguracje WireGuard, bazę użytkowników i ustawień, grupy, dane klientów, ustawienia Telegram/SMTP i stan potrzebny do odtworzenia VPS Relay/Nodes.", + "Przed przywracaniem WGTools sprawdza archiwum i zabezpiecza aktualny stan kopią. Jeśli przywrócenie się nie powiedzie, próbuje wycofać zmiany.", + "Po udanym przywróceniu sesja WWW zostaje wylogowana; zaloguj się kontem z przywróconej bazy." + ], + "example_title": "", + "example_lines": [], + "warning": "plik .wgtbackup zawiera klucze prywatne, PSK, skróty haseł, token Telegram i hasło SMTP. Chroń go jak hasło." + }, + { + "title": "Bot Telegram", + "paragraphs": [ + "Bot pozwala sprawdzać i zarządzać WireGuard bez otwierania panelu." + ], + "bullets": [ + "Utwórz bota przez @BotFather, wklej token, włącz go i wyślij /start.", + "Jeśli twój identyfikator Telegram nie jest jeszcze autoryzowany, bot pokaże numer ID; dodaj go do listy dozwolonych.", + "Polecenia administracyjne działają tylko w prywatnych czatach: stan, klienci, tworzenie/usuwanie, ponowne wydawanie konfiguracji/QR i sterowanie WireGuard." + ], + "example_title": "Przykład", + "example_lines": [ + "Domyślny Endpoint: vpn.example.com", + "DNS: 1.1.1.1, 8.8.8.8" + ], + "warning": "" + }, + { + "title": "Poczta SMTP i odzyskiwanie hasła", + "paragraphs": [ + "SMTP obsługuje funkcję „Nie pamiętasz hasła?” na stronie logowania." + ], + "bullets": [ + "Dostępne są STARTTLS, TLS/SSL i zwykły SMTP w zaufanej sieci lokalnej; nazwa użytkownika może być pusta, jeśli serwer nie wymaga logowania.", + "Hasło jest przechowywane lokalnie i nigdy nie wraca do przeglądarki; przycisk testowania wysyła wiadomość do odbiorcy testowego.", + "Kody odzyskiwania są jednorazowe, przechowywane jako skróty, ważne 15 minut i chronione limitem prób." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Wbudowane HTTPS", + "paragraphs": [ + "WGTools może sam udostępniać HTTPS bez Nginx, Caddy ani zewnętrznego reverse proxy." + ], + "bullets": [ + "Podaj domenę/publiczny IP, e-mail, port HTTPS i ścieżkę prywatną, a następnie wybierz Uzyskaj / odnów certyfikat. Ta operacja zapisuje również ustawienia HTTPS.", + "Włączenie HTTPS jest dostępne dopiero po uzyskaniu odpowiedniego certyfikatu. Po sukcesie włącz opcję i kliknij Zapisz; zmiana domeny/IP wymaga nowego certyfikatu.", + "Do wydawania i odnawiania certyfikatu TCP 80 musi być dostępny z Internetu. Panel działa na wybranym porcie (np. 443 lub 8443), a ścieżka prywatna określa URL (np. /MyWGTools/); pozostałe ścieżki zwracają 404.", + "WGTools pokazuje zajętość lokalnych portów i nie zatrzymuje obcego serwera WWW; timer systemd automatycznie odnawia certyfikat.", + "Ścieżka prywatna nie zastępuje uwierzytelnienia. Nie wystawiaj panelu bez potrzeby i używaj silnych haseł." + ], + "example_title": "Przykład", + "example_lines": [ + "https://wg.example.com/MyWGTools/" + ], + "warning": "Ścieżka prywatna nie zastępuje uwierzytelnienia. Nie udostępniaj panelu bez potrzeby i stosuj silne hasła." + }, + { + "title": "Użytkownicy", + "paragraphs": [ + "Pierwsze konto powstaje podczas konfiguracji WGTools. Kolejne dodasz w Ustawieniach." + ], + "bullets": [ + "Obecnie wszyscy użytkownicy mają takie same uprawnienia; można zmieniać e-mail i hasło oraz usuwać konta.", + "Każdy użytkownik może włączyć MFA za pomocą Google Authenticator lub aplikacji TOTP; przy włączaniu otrzyma jednorazowy zestaw kodów odzyskiwania.", + "Po utracie urządzenia administrator root może wyłączyć MFA użytkownika przez polecenie wgtools. Nie można usunąć zalogowanego ani ostatniego konta.", + "Zmiana lub odzyskiwanie hasła oraz zmiana MFA unieważniają starsze sesje WWW tego konta." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Dziennik audytu", + "paragraphs": [ + "Audit rejestruje istotne działania administracyjne WWW/Telegram oraz historię połączeń WireGuard." + ], + "bullets": [ + "Działania WWW zawierają nazwę użytkownika WGTools, a Telegram — @username (jeśli dostępny) oraz numeryczny ID.", + "Zapisywane są zmiany konfiguracji, wyświetlenie konfiguracji/QR, aktualizacje i istotne błędy.", + "Hasła, klucze prywatne, PSK, tokeny i pełne pliki konfiguracyjne nie trafiają do audytu. Historia ma ograniczony czas przechowywania i jest automatycznie czyszczona." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Aktualizacje WGTools-Extended", + "paragraphs": [ + "Administrator wgrywa zaufany pakiet .bin w ustawieniach." + ], + "bullets": [ + "Przed instalacją powstaje kopia danych i archiwum do wycofania wersji aplikacji.", + "W razie błędu program próbuje automatycznie przywrócić poprzednią wersję." + ], + "example_title": "", + "example_lines": [], + "warning": "" + }, + { + "title": "Polecenie wgtools i dostęp awaryjny", + "paragraphs": [ + "Polecenie wgtools dostępne dla roota pomaga, gdy panel WWW jest nieosiągalny." + ], + "bullets": [ + "Pokazuje stan WGTools, WireGuard, Nodes, Telegram, timerów i lokalnego Relay Agent oraz adres panelu.", + "Może uruchamiać, zatrzymywać i restartować panel lub WireGuard oraz pokazywać logi. Przy błędnym porcie HTTPS lub ścieżce prywatnej może wyłączyć wbudowane HTTPS i przywrócić dostęp HTTP.", + "Pozwala awaryjnie wyłączyć MFA użytkownika po utracie uwierzytelniacza i kodów.", + "Odinstalowanie usuwa panel i usługi, zachowując zwykły WireGuard oraz dane do ponownej instalacji. FULL CLEANUP po potwierdzeniu DELETE ALL usuwa lokalne WGTools, Relay i WireGuard; agentów Relay na innych VPS nie dotyka." + ], + "example_title": "Przykład", + "example_lines": [ + "root@server:~# wgtools" + ], + "warning": "" + }, + { + "title": "Gdzie przechowywane są dane", + "paragraphs": [ + "Ręczna edycja zwykle nie jest potrzebna, lecz znajomość ścieżek przydaje się przy diagnostyce i planowaniu kopii zapasowych." + ], + "bullets": [], + "example_title": "Główne ścieżki", + "example_lines": [ + "/etc/wireguard/wg0.conf — konfiguracja WireGuard", + "/var/lib/wgtools/wgtools.db — użytkownicy i ustawienia", + "/var/lib/wgtools/clients/ — dane zarządzanych klientów", + "/var/lib/wgtools/backups/ — historia konfiguracji", + "/var/lib/wgtools/update-backups/ — archiwa cofania aktualizacji" + ], + "warning": "" + } + ] + } +] diff --git a/app/core/helper.py b/app/core/helper.py new file mode 100644 index 0000000..d947973 --- /dev/null +++ b/app/core/helper.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import json +import subprocess +from typing import Any + +from .settings import HELPER_PATH, WG_INTERFACE + + +class HelperError(RuntimeError): + pass + + +ALLOWED_ACTIONS = { + "snapshot", + "interfaces_list", + "interface_meta_set", + "interface_delete", + "metrics_sample", + "metrics_history", + "diagnostics", + "network_trace", + "wireguard_start", + "wireguard_stop", + "wireguard_restart", + "install_wireguard", + "create_server", + "create_client", + "update_client", + "delete_client", + "rotate_client_credentials", + "client_config", + "group_create", + "group_update", + "group_delete", + "raw_config_get", + "raw_config_apply", + "server_settings_apply", + "extended_snat_get", + "extended_snat_apply", + "extended_listen_get", + "extended_listen_apply", + "extended_ip_groups_get", + "extended_ip_groups_set", + "extended_forward_get", + "extended_forward_add", + "extended_forward_delete", + "route_create", + "route_update", + "route_delete", + "access_rule_create", + "access_rule_update", + "access_rule_delete", + "migration_backup_create", + "migration_restore", + "update_check", + "update_notice", + "update_status", + "update_schedule", + "update_file_schedule", + "traffic_reset", + "https_status", + "https_ports", + "https_issue", + "https_enable", + "https_disable", +} + + +def run_helper(action: str, payload: dict[str, Any] | None = None, *, interface: str | None = None) -> dict[str, Any]: + if action not in ALLOWED_ACTIONS: + raise HelperError(f"Unsupported helper action: {action}") + + timeout = 8 + if action == "install_wireguard": + timeout = 430 + elif action == "create_server": + timeout = 60 + elif action == "network_trace": + timeout = 85 + elif action in {"wireguard_start", "wireguard_stop", "wireguard_restart", "interface_delete"}: + timeout = 45 + elif action in {"create_client", "update_client", "delete_client", "rotate_client_credentials", "group_create", "group_update", "group_delete"}: + # Group policy reconciliation may rebuild many WGTools-managed firewall + # rules on installations with a large peer count. Give the privileged + # helper enough time to finish its transactional rollback/commit path + # instead of killing it mid-update. + timeout = 120 + elif action in {"raw_config_apply", "server_settings_apply", "extended_snat_apply", "extended_listen_apply", "extended_forward_add", "extended_forward_delete", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete"}: + timeout = 90 + elif action == "migration_backup_create": + timeout = 45 + elif action == "migration_restore": + timeout = 480 + elif action == "update_check": + timeout = 20 + elif action == "update_notice": + timeout = 20 + elif action == "update_status": + timeout = 10 + elif action in {"update_schedule", "update_file_schedule"}: + timeout = 90 + elif action == "https_issue": + timeout = 260 + elif action in {"https_enable", "https_disable"}: + timeout = 40 + + iface = (interface or WG_INTERFACE).strip() + cmd = [HELPER_PATH, action, iface] + input_text = json.dumps(payload or {}) if payload is not None else None + try: + proc = subprocess.run( + cmd, + input=input_text, + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + except subprocess.TimeoutExpired as exc: + raise HelperError(f"Operation timed out after {timeout} seconds") from exc + + if proc.returncode != 0: + detail = (proc.stderr or proc.stdout or "helper failed").strip() + try: + parsed = json.loads(proc.stdout) + detail = parsed.get("error") or detail + except Exception: + pass + raise HelperError(detail) + + try: + data = json.loads(proc.stdout) + except json.JSONDecodeError as exc: + raise HelperError("Helper returned invalid JSON") from exc + if not data.get("ok", False): + raise HelperError(data.get("error", "Helper operation failed")) + return data diff --git a/app/core/mail_config.py b/app/core/mail_config.py new file mode 100644 index 0000000..efbf09f --- /dev/null +++ b/app/core/mail_config.py @@ -0,0 +1,270 @@ +from __future__ import annotations + +import re +import smtplib +import sqlite3 +import ssl +import time +from email.message import EmailMessage +from email.utils import formataddr +from pathlib import Path +from typing import Any + +from .settings import DATABASE_PATH + +EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") +SECURITY_MODES = {"starttls", "tls", "none"} + + +def _connect() -> sqlite3.Connection: + Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + return conn + + +def normalize_email(value: str, *, allow_empty: bool = True) -> str: + email = str(value or "").strip().lower() + if not email and allow_empty: + return "" + if len(email) > 254 or not EMAIL_RE.fullmatch(email): + raise ValueError("Enter a valid email address") + return email + + +def init_mail_settings() -> None: + with _connect() as conn: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS mail_settings ( + id INTEGER PRIMARY KEY CHECK(id=1), + enabled INTEGER NOT NULL DEFAULT 0, + smtp_host TEXT NOT NULL DEFAULT '', + smtp_port INTEGER NOT NULL DEFAULT 587, + security TEXT NOT NULL DEFAULT 'starttls', + username TEXT NOT NULL DEFAULT '', + password TEXT NOT NULL DEFAULT '', + from_email TEXT NOT NULL DEFAULT '', + from_name TEXT NOT NULL DEFAULT 'WGTools', + updated_at INTEGER NOT NULL DEFAULT 0 + ) + """ + ) + conn.execute( + """ + INSERT OR IGNORE INTO mail_settings( + id,enabled,smtp_host,smtp_port,security,username,password, + from_email,from_name,updated_at + ) VALUES(1,0,'',587,'starttls','','','','WGTools',0) + """ + ) + + +def _row() -> sqlite3.Row: + init_mail_settings() + with _connect() as conn: + row = conn.execute("SELECT * FROM mail_settings WHERE id=1").fetchone() + if row is None: + raise RuntimeError("Mail settings row is missing") + return row + + +def mask_password(password: str) -> str: + return "••••••••" if password else "" + + +def mask_email(value: str) -> str: + email = str(value or "").strip() + if "@" not in email: + return "" + local, domain = email.split("@", 1) + if not local: + return f"***@{domain}" + visible = local[0] + return f"{visible}***@{domain}" + + +def _is_configured(row: sqlite3.Row | dict[str, Any]) -> bool: + return bool( + str(row["smtp_host"] or "").strip() + and int(row["smtp_port"] or 0) > 0 + and str(row["from_email"] or "").strip() + ) + + +def get_mail_settings(*, include_password: bool = False) -> dict[str, Any]: + row = _row() + password = str(row["password"] or "") + result = { + "enabled": bool(row["enabled"]), + "configured": _is_configured(row), + "smtp_host": str(row["smtp_host"] or ""), + "smtp_port": int(row["smtp_port"] or 587), + "security": str(row["security"] or "starttls"), + "username": str(row["username"] or ""), + "password_configured": bool(password), + "password_masked": mask_password(password), + "from_email": str(row["from_email"] or ""), + "from_name": str(row["from_name"] or "WGTools"), + "updated_at": int(row["updated_at"] or 0), + } + if include_password: + result["password"] = password + return result + + +def update_mail_settings( + *, + enabled: bool, + smtp_host: str, + smtp_port: int, + security: str, + username: str, + password: str | None, + clear_password: bool, + from_email: str, + from_name: str, +) -> dict[str, Any]: + current = get_mail_settings(include_password=True) + host = str(smtp_host or "").strip() + if len(host) > 253 or any(ch.isspace() for ch in host): + raise ValueError("SMTP server is invalid") + port = int(smtp_port or 0) + if not 1 <= port <= 65535: + raise ValueError("SMTP port must be between 1 and 65535") + mode = str(security or "starttls").strip().lower() + if mode not in SECURITY_MODES: + raise ValueError("SMTP security must be STARTTLS, TLS or none") + login = str(username or "").strip() + if len(login) > 254 or any(ord(ch) < 32 for ch in login): + raise ValueError("SMTP username is invalid") + sender = normalize_email(from_email or login, allow_empty=True) + sender_name = str(from_name or "WGTools").strip() or "WGTools" + if len(sender_name) > 120 or any(ord(ch) < 32 for ch in sender_name): + raise ValueError("Sender name is invalid") + + saved_password = str(current.get("password") or "") + supplied = str(password or "") + if clear_password: + saved_password = "" + elif supplied: + if len(supplied) > 512: + raise ValueError("SMTP password is too long") + saved_password = supplied + + if enabled and (not host or not sender): + raise ValueError("Configure the SMTP server and sender email before enabling mail") + + with _connect() as conn: + conn.execute( + """ + UPDATE mail_settings SET + enabled=?,smtp_host=?,smtp_port=?,security=?,username=?,password=?, + from_email=?,from_name=?,updated_at=? + WHERE id=1 + """, + ( + 1 if enabled else 0, + host, + port, + mode, + login, + saved_password, + sender, + sender_name, + int(time.time()), + ), + ) + return get_mail_settings() + + +def password_recovery_available() -> bool: + settings = get_mail_settings() + return bool(settings.get("enabled") and settings.get("configured")) + + +def _smtp_connection(settings: dict[str, Any], timeout: float = 15.0): + host = str(settings.get("smtp_host") or "") + port = int(settings.get("smtp_port") or 0) + security = str(settings.get("security") or "starttls") + context = ssl.create_default_context() + if security == "tls": + client = smtplib.SMTP_SSL(host, port, timeout=timeout, context=context) + client.ehlo() + return client + client = smtplib.SMTP(host, port, timeout=timeout) + client.ehlo() + if security == "starttls": + client.starttls(context=context) + client.ehlo() + return client + + +def send_mail(recipient: str, subject: str, body: str, *, require_enabled: bool = True) -> None: + recipient = normalize_email(recipient, allow_empty=False) + settings = get_mail_settings(include_password=True) + if require_enabled and not settings.get("enabled"): + raise RuntimeError("Mail is disabled") + if not settings.get("configured"): + raise RuntimeError("Mail is not configured") + + message = EmailMessage() + message["Subject"] = str(subject) + message["From"] = formataddr((str(settings.get("from_name") or "WGTools"), str(settings.get("from_email") or ""))) + message["To"] = recipient + message.set_content(str(body), charset="utf-8") + + try: + with _smtp_connection(settings) as client: + username = str(settings.get("username") or "") + password = str(settings.get("password") or "") + if username: + client.login(username, password) + client.send_message(message) + except (OSError, smtplib.SMTPException) as exc: + raise RuntimeError(f"SMTP send failed: {exc}") from exc + + +def _mail_language(language: str) -> str: + return "ru" if str(language or "").strip().lower() == "ru" else "en" + + +def send_test_email(recipient: str, *, language: str = "en") -> dict[str, Any]: + recipient = normalize_email(recipient, allow_empty=False) + language = _mail_language(language) + if language == "ru": + subject = "WGTools — тестовое письмо" + body = "Настройки почты WGTools работают корректно.\n" + else: + subject = "WGTools — test email" + body = "WGTools mail settings are working correctly.\n" + send_mail(recipient, subject, body, require_enabled=False) + return {"ok": True, "recipient": recipient} + + +def send_password_reset_email( + recipient: str, + code: str, + *, + valid_minutes: int = 15, + language: str = "en", +) -> None: + language = _mail_language(language) + if language == "ru": + subject = "WGTools — сброс пароля" + body = ( + "WGTools — сброс пароля\n\n" + f"Код подтверждения: {code}\n" + f"Код действует {valid_minutes} минут.\n" + "Если вы не запрашивали сброс пароля, просто проигнорируйте это письмо.\n" + ) + else: + subject = "WGTools — password reset" + body = ( + "WGTools — password reset\n\n" + f"Verification code: {code}\n" + f"The code is valid for {valid_minutes} minutes.\n" + "If you did not request a password reset, ignore this email.\n" + ) + send_mail(recipient, subject, body) diff --git a/app/core/nodes.py b/app/core/nodes.py new file mode 100644 index 0000000..173e560 --- /dev/null +++ b/app/core/nodes.py @@ -0,0 +1,2193 @@ +from __future__ import annotations + +import hashlib +import ipaddress +import json +import os +import secrets +import socket +import sqlite3 +import ssl +import subprocess +import threading +import time +import urllib.parse +import uuid +from pathlib import Path +from typing import Any + +from .helper import HelperError, run_helper +from .settings import DATABASE_PATH, ONLINE_THRESHOLD_SECONDS, VERSION + +NODE_INTERFACE = "wgnode0" +DEFAULT_TRANSPORT_NETWORK = "10.254.240.0/24" +DEFAULT_LISTEN_PORT = 51950 +JOIN_TTL_SECONDS = 15 * 60 +SYNC_INTERVAL_SECONDS = 15 +MAX_EXPORTED_NETWORKS = 64 +MAX_CLIENT_SUMMARY = 1000 +NODE_CONTROL_DIR = Path("/etc/wgtools/nodes") +NODE_CONTROL_CERT_FILE = NODE_CONTROL_DIR / "control.crt" +NODE_CONTROL_KEY_FILE = NODE_CONTROL_DIR / "control.key" +NODE_CONTROL_PROTOCOL = "wgtools-nodes-v1" +NODE_CONTROL_MAX_BYTES = 2 * 1024 * 1024 + +_lock = threading.RLock() +_certificate_lock = threading.RLock() +_control_status_lock = threading.RLock() +_control_active_port = 0 +_control_last_error = "" + + +class NodeNetworkConflictError(ValueError): + """A published network overlaps the transport network or another Node.""" + + code = "network_conflict" + + def __init__(self, conflicts: list[dict[str, str]]): + self.conflicts = conflicts + parts: list[str] = [] + for item in conflicts: + network = str(item.get("network") or "") + owner_name = str(item.get("owner_name") or "") + owner_network = str(item.get("owner_network") or "") + if item.get("owner_type") == "transport": + parts.append(f"{network} overlaps Nodes transport network {owner_network}") + else: + parts.append(f"{network} overlaps {owner_network} on node {owner_name or 'WGTools'}") + super().__init__("Nodes network conflict: " + "; ".join(parts)) + + +def _connect() -> sqlite3.Connection: + Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH, timeout=15) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + return conn + + +def init_nodes_database() -> None: + with _connect() as conn: + conn.executescript( + """ + CREATE TABLE IF NOT EXISTS wg_node_state ( + id INTEGER PRIMARY KEY CHECK(id=1), + data TEXT NOT NULL, + updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS wg_node_peers ( + node_id TEXT PRIMARY KEY, + name TEXT NOT NULL, + public_key TEXT NOT NULL UNIQUE, + preshared_key TEXT NOT NULL, + secret TEXT NOT NULL UNIQUE, + transport_ip TEXT NOT NULL UNIQUE, + panel_url TEXT NOT NULL DEFAULT '', + version TEXT NOT NULL DEFAULT '', + exports_json TEXT NOT NULL DEFAULT '[]', + clients_json TEXT NOT NULL DEFAULT '[]', + connected_at INTEGER NOT NULL, + last_seen INTEGER NOT NULL DEFAULT 0, + last_error TEXT NOT NULL DEFAULT '' + ); + CREATE TABLE IF NOT EXISTS wg_node_join_codes ( + code_hash TEXT PRIMARY KEY, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS wg_node_cache ( + id INTEGER PRIMARY KEY CHECK(id=1), + data TEXT NOT NULL, + updated_at INTEGER NOT NULL + ); + """ + ) + + +def _json_load(raw: str | None, default: Any) -> Any: + try: + value = json.loads(raw or "") + return value + except Exception: + return default + + +def _load_state() -> dict[str, Any]: + init_nodes_database() + with _connect() as conn: + row = conn.execute("SELECT data FROM wg_node_state WHERE id=1").fetchone() + data = _json_load(row["data"] if row else None, {}) + return data if isinstance(data, dict) else {} + + +def _save_state(data: dict[str, Any]) -> None: + init_nodes_database() + now = int(time.time()) + encoded = json.dumps(data, ensure_ascii=False, separators=(",", ":")) + with _connect() as conn: + conn.execute( + "INSERT INTO wg_node_state(id,data,updated_at) VALUES(1,?,?) " + "ON CONFLICT(id) DO UPDATE SET data=excluded.data,updated_at=excluded.updated_at", + (encoded, now), + ) + + +def _load_cache() -> dict[str, Any]: + init_nodes_database() + with _connect() as conn: + row = conn.execute("SELECT data FROM wg_node_cache WHERE id=1").fetchone() + data = _json_load(row["data"] if row else None, {}) + return data if isinstance(data, dict) else {} + + +def _save_cache(data: dict[str, Any]) -> None: + now = int(time.time()) + encoded = json.dumps(data, ensure_ascii=False, separators=(",", ":")) + with _connect() as conn: + conn.execute( + "INSERT INTO wg_node_cache(id,data,updated_at) VALUES(1,?,?) " + "ON CONFLICT(id) DO UPDATE SET data=excluded.data,updated_at=excluded.updated_at", + (encoded, now), + ) + + +def _normalize_name(value: str, fallback: str = "WGTools") -> str: + text = " ".join(str(value or "").strip().split()) + if not text: + text = fallback + if len(text) > 64 or any(ord(ch) < 32 for ch in text): + raise ValueError("Node name must contain 1 to 64 printable characters") + return text + + +def _normalize_panel_url(value: str, *, allow_empty: bool = True) -> str: + text = str(value or "").strip() + if not text and allow_empty: + return "" + if len(text) > 512: + raise ValueError("Panel URL is too long") + parsed = urllib.parse.urlsplit(text) + if parsed.scheme not in {"http", "https"} or not parsed.netloc: + raise ValueError("Panel URL must start with http:// or https://") + path = parsed.path or "/" + if not path.endswith("/"): + path += "/" + return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, path, "", "")) + + +def _normalize_endpoint_host(value: str) -> str: + host = str(value or "").strip() + if not host or len(host) > 253 or any(ch.isspace() for ch in host): + raise ValueError("HUB endpoint host/domain is required") + if host.startswith("[") and host.endswith("]"): + host = host[1:-1] + return host + + +def _endpoint_text(host: str, port: int) -> str: + wrapped = f"[{host}]" if ":" in host and not host.startswith("[") else host + return f"{wrapped}:{int(port)}" + + +def _parse_endpoint(value: str, *, default_port: int = DEFAULT_LISTEN_PORT) -> tuple[str, int]: + text = str(value or "").strip() + if not text: + raise ValueError("HUB endpoint is required") + if "://" in text: + raise ValueError("Enter the HUB as host:port without http:// or https://") + host = "" + port = int(default_port) + if text.startswith("["): + end = text.find("]") + if end < 0: + raise ValueError("Invalid HUB endpoint") + host = text[1:end] + suffix = text[end + 1 :] + if suffix: + if not suffix.startswith(":") or not suffix[1:].isdigit(): + raise ValueError("Invalid HUB endpoint port") + port = int(suffix[1:]) + else: + # A single colon means host:port. Multiple colons are treated as a raw + # IPv6 literal and use the default port; bracket IPv6 when specifying a port. + if text.count(":") == 1: + possible_host, possible_port = text.rsplit(":", 1) + if possible_port.isdigit(): + host, port = possible_host, int(possible_port) + else: + host = text + else: + host = text + host = _normalize_endpoint_host(host) + if not 1 <= port <= 65535: + raise ValueError("Invalid HUB endpoint port") + return host, port + + +def _normalize_networks(values: list[str] | tuple[str, ...] | None, *, label: str = "Published networks") -> list[str]: + result: list[str] = [] + seen: set[str] = set() + for raw in list(values or []): + text = str(raw or "").strip() + if not text: + continue + try: + net = ipaddress.ip_network(text, strict=False) + except ValueError as exc: + raise ValueError(f"Invalid network in {label}: {text}") from exc + if net.version != 4: + raise ValueError("WGTools Nodes v1 supports IPv4 networks only") + if net.prefixlen == 0: + raise ValueError("0.0.0.0/0 cannot be published as a WGTools Node network") + canonical = str(net) + if canonical not in seen: + result.append(canonical) + seen.add(canonical) + if len(result) > MAX_EXPORTED_NETWORKS: + raise ValueError(f"Too many networks in {label}") + return result + + +def _run(cmd: list[str], *, input_text: str | None = None, timeout: int = 30) -> tuple[int, str, str]: + proc = subprocess.run(cmd, input=input_text, text=True, capture_output=True, timeout=timeout, check=False) + return proc.returncode, proc.stdout.strip(), proc.stderr.strip() + + +def _certificate_fingerprint(cert_file: Path | None = None) -> str: + cert_file = cert_file or NODE_CONTROL_CERT_FILE + try: + pem = cert_file.read_text(encoding="utf-8") + der = ssl.PEM_cert_to_DER_cert(pem) + except Exception as exc: + raise RuntimeError("Could not read WGTools Node control certificate") from exc + return hashlib.sha256(der).hexdigest() + + +def _ensure_control_certificate() -> tuple[Path, Path, str]: + """Create/restore the private certificate used only by the Node control socket. + + The PEM material is also kept in the SQLite Node state so WGTools full + backup/restore preserves the HUB identity pinned by already-connected spokes. + Files under /etc/wgtools/nodes are runtime copies with strict permissions. + """ + with _certificate_lock: + NODE_CONTROL_DIR.mkdir(parents=True, exist_ok=True) + state = _load_state() + saved_cert = str(state.get("control_cert_pem") or "") + saved_key = str(state.get("control_key_pem") or "") + + if saved_cert and saved_key: + if not NODE_CONTROL_CERT_FILE.exists() or NODE_CONTROL_CERT_FILE.read_text(encoding="utf-8", errors="replace") != saved_cert: + NODE_CONTROL_CERT_FILE.write_text(saved_cert, encoding="utf-8") + if not NODE_CONTROL_KEY_FILE.exists() or NODE_CONTROL_KEY_FILE.read_text(encoding="utf-8", errors="replace") != saved_key: + NODE_CONTROL_KEY_FILE.write_text(saved_key, encoding="utf-8") + elif NODE_CONTROL_CERT_FILE.exists() and NODE_CONTROL_KEY_FILE.exists(): + saved_cert = NODE_CONTROL_CERT_FILE.read_text(encoding="utf-8") + saved_key = NODE_CONTROL_KEY_FILE.read_text(encoding="utf-8") + state["control_cert_pem"] = saved_cert + state["control_key_pem"] = saved_key + _save_state(state) + else: + cert_tmp = NODE_CONTROL_CERT_FILE.with_suffix(".crt.tmp") + key_tmp = NODE_CONTROL_KEY_FILE.with_suffix(".key.tmp") + cert_tmp.unlink(missing_ok=True) + key_tmp.unlink(missing_ok=True) + rc, out, err = _run( + [ + "openssl", "req", "-x509", "-newkey", "rsa:2048", "-sha256", "-nodes", + "-days", "3650", "-subj", "/CN=WGTools Node Control", + "-keyout", str(key_tmp), "-out", str(cert_tmp), + ], + timeout=30, + ) + if rc != 0 or not cert_tmp.exists() or not key_tmp.exists(): + cert_tmp.unlink(missing_ok=True) + key_tmp.unlink(missing_ok=True) + raise RuntimeError(err or out or "Could not generate WGTools Node control certificate") + os.chmod(key_tmp, 0o600) + os.chmod(cert_tmp, 0o644) + key_tmp.replace(NODE_CONTROL_KEY_FILE) + cert_tmp.replace(NODE_CONTROL_CERT_FILE) + saved_cert = NODE_CONTROL_CERT_FILE.read_text(encoding="utf-8") + saved_key = NODE_CONTROL_KEY_FILE.read_text(encoding="utf-8") + state["control_cert_pem"] = saved_cert + state["control_key_pem"] = saved_key + _save_state(state) + + os.chmod(NODE_CONTROL_KEY_FILE, 0o600) + os.chmod(NODE_CONTROL_CERT_FILE, 0o644) + return NODE_CONTROL_CERT_FILE, NODE_CONTROL_KEY_FILE, _certificate_fingerprint() + + +def _join_code_fingerprint(code: str) -> str: + text = str(code or "").strip() + prefix = "WGTOOLS-NODE-v1." + if not text.startswith(prefix): + raise ValueError("Invalid WGTools Node connection code") + parts = text[len(prefix):].split(".", 1) + if len(parts) != 2 or len(parts[0]) != 64 or any(ch not in "0123456789abcdefABCDEF" for ch in parts[0]) or not parts[1]: + raise ValueError("Invalid WGTools Node connection code") + return parts[0].lower() + + +def _recv_control_json(sock: ssl.SSLSocket) -> dict[str, Any]: + chunks: list[bytes] = [] + total = 0 + while True: + chunk = sock.recv(min(65536, NODE_CONTROL_MAX_BYTES - total + 1)) + if not chunk: + break + chunks.append(chunk) + total += len(chunk) + if total > NODE_CONTROL_MAX_BYTES: + raise ValueError("WGTools Node control message is too large") + if b"\n" in chunk: + break + raw = b"".join(chunks).split(b"\n", 1)[0] + if not raw: + raise ValueError("Empty WGTools Node control message") + try: + value = json.loads(raw.decode("utf-8")) + except Exception as exc: + raise ValueError("Invalid WGTools Node control message") from exc + if not isinstance(value, dict): + raise ValueError("Invalid WGTools Node control message") + return value + + +def _send_control_json(sock: ssl.SSLSocket, payload: dict[str, Any]) -> None: + encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n" + if len(encoded) > NODE_CONTROL_MAX_BYTES: + raise ValueError("WGTools Node control response is too large") + sock.sendall(encoded) + + +def _control_json( + host: str, + port: int, + payload: dict[str, Any], + *, + expected_fingerprint: str, + timeout: int = 12, +) -> dict[str, Any]: + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + deadline = time.monotonic() + max(1, int(timeout)) + last_error: Exception | None = None + while time.monotonic() < deadline: + remaining = max(0.5, deadline - time.monotonic()) + try: + with socket.create_connection((host, int(port)), timeout=min(3.0, remaining)) as raw: + raw.settimeout(remaining) + with context.wrap_socket(raw, server_hostname=host) as tls: + certificate = tls.getpeercert(binary_form=True) + actual = hashlib.sha256(certificate or b"").hexdigest() + if not certificate or not secrets.compare_digest(actual, str(expected_fingerprint or "").lower()): + raise RuntimeError("HUB identity does not match the connection code") + _send_control_json(tls, {"protocol": NODE_CONTROL_PROTOCOL, **payload}) + result = _recv_control_json(tls) + if not result.get("ok"): + exc = RuntimeError(str(result.get("error") or "Invalid HUB control response")) + if result.get("error_code"): + setattr(exc, "error_code", str(result.get("error_code"))) + if isinstance(result.get("conflicts"), list): + setattr(exc, "conflicts", result.get("conflicts")) + raise exc + return result + except RuntimeError: + # Identity or application errors are deterministic; retrying them + # would only burn the full timeout and could consume a one-time code. + raise + except Exception as exc: + last_error = exc + if time.monotonic() >= deadline: + break + time.sleep(min(0.35, max(0.05, deadline - time.monotonic()))) + raise RuntimeError(f"Could not reach WGTools HUB control service: {last_error or 'connection timed out'}") from last_error + + +def _wg_available() -> bool: + return Path("/usr/bin/wg").exists() or subprocess.run(["sh", "-lc", "command -v wg >/dev/null 2>&1"], check=False).returncode == 0 + + +def _ensure_identity(state: dict[str, Any]) -> dict[str, Any]: + if state.get("private_key") and state.get("public_key"): + return state + if not _wg_available(): + raise RuntimeError("WireGuard is not installed. Install WireGuard before enabling WGTools Nodes.") + rc, private_key, err = _run(["wg", "genkey"]) + if rc != 0 or not private_key: + raise RuntimeError(err or "Could not generate WGTools Node private key") + rc, public_key, err = _run(["wg", "pubkey"], input_text=private_key + "\n") + if rc != 0 or not public_key: + raise RuntimeError(err or "Could not generate WGTools Node public key") + state["private_key"] = private_key + state["public_key"] = public_key + state.setdefault("node_id", uuid.uuid4().hex) + _save_state(state) + return state + + +def _interface_inventory() -> dict[str, Any]: + try: + data = run_helper("interfaces_list") + except HelperError: + return {"interfaces": []} + return data if isinstance(data, dict) else {"interfaces": []} + + +def _local_policy_tables() -> list[str]: + values: list[str] = [] + for item in _interface_inventory().get("interfaces") or []: + if not item.get("configured"): + continue + value = item.get("policy_table") + if value in (None, ""): + continue + text = str(value) + if text.isdigit() and text not in values: + values.append(text) + return values + + +def _automatic_exports(inventory: dict[str, Any] | None = None) -> list[dict[str, str]]: + """Networks WGTools can derive from its managed WireGuard configuration.""" + result: list[dict[str, str]] = [] + seen: set[str] = set() + + def add(raw: Any, kind: str, label: str) -> None: + text = str(raw or "").strip() + if not text: + return + try: + net = ipaddress.ip_network(text, strict=False) + except ValueError: + return + if net.version != 4 or net.prefixlen == 0: + return + canonical = str(net) + if canonical in seen or len(result) >= MAX_EXPORTED_NETWORKS: + return + seen.add(canonical) + result.append({"network": canonical, "kind": kind, "label": label or canonical}) + + inventory = inventory or _interface_inventory() + for item in inventory.get("interfaces") or []: + if not item.get("configured"): + continue + interface_label = str(item.get("display_name") or item.get("name") or "WireGuard") + add(item.get("vpn_network"), "vpn", interface_label) + for raw in item.get("remote_networks") or []: + add(raw, "site_to_site", interface_label) + return result + + +def _direct_private_networks( + state: dict[str, Any] | None = None, + *, + inventory: dict[str, Any] | None = None, +) -> list[dict[str, str]]: + """Conservatively discover directly-routed private LANs for the picker. + + These networks are *options*, not automatic exports. This lets the connect + dialog offer a local LAN such as 10.10.10.0/24 without silently publishing + Docker/Node/internal routes. + """ + state = state or _load_state() + transport_raw = str(state.get("transport_network") or DEFAULT_TRANSPORT_NETWORK) + try: + transport = ipaddress.ip_network(transport_raw, strict=False) + except ValueError: + transport = ipaddress.ip_network(DEFAULT_TRANSPORT_NETWORK) + rc, out, _err = _run(["ip", "-4", "route", "show", "scope", "link"], timeout=5) + if rc != 0: + return [] + result: list[dict[str, str]] = [] + seen: set[str] = set() + skipped_prefixes = ("docker", "br-", "veth", "virbr", "lxcbr", "cni", "flannel", "podman") + inventory = inventory or _interface_inventory() + wireguard_devices = { + str(item.get("name") or "").strip() + for item in (inventory.get("interfaces") or []) + if item.get("configured") and str(item.get("name") or "").strip() + } + for line in out.splitlines(): + parts = line.split() + if not parts or parts[0] in {"default", "broadcast", "local", "unreachable", "blackhole", "prohibit", "throw"}: + continue + try: + net = ipaddress.ip_network(parts[0], strict=False) + except ValueError: + continue + if net.version != 4 or net.prefixlen == 0 or net.prefixlen > 30 or not net.is_private or net.is_link_local: + continue + dev = parts[parts.index("dev") + 1] if "dev" in parts and parts.index("dev") + 1 < len(parts) else "" + # WireGuard routes are already represented by _automatic_exports(). + # Treating them as direct LAN candidates makes an old/current VPN pool + # look like a local LAN and hides pool-change warnings. + if dev == NODE_INTERFACE or dev == "lo" or dev in wireguard_devices or dev.startswith(skipped_prefixes): + continue + if net.overlaps(transport): + continue + canonical = str(net) + if canonical in seen or len(result) >= MAX_EXPORTED_NETWORKS: + continue + seen.add(canonical) + result.append({"network": canonical, "kind": "custom", "label": f"LAN · {dev}" if dev else canonical}) + return result + + +def _available_publish_networks( + state: dict[str, Any] | None = None, + *, + inventory: dict[str, Any] | None = None, + direct_networks: list[dict[str, str]] | None = None, + include_remembered: bool = True, +) -> list[dict[str, str]]: + """Return all currently known networks that the user may choose to publish.""" + state = state or _load_state() + result: list[dict[str, str]] = [] + seen: set[str] = set() + + def add_item(item: dict[str, str]) -> None: + raw = str(item.get("network") or "").strip() + if not raw: + return + try: + canonical = str(ipaddress.ip_network(raw, strict=False)) + except ValueError: + return + if canonical in seen or len(result) >= MAX_EXPORTED_NETWORKS: + return + seen.add(canonical) + result.append({**item, "network": canonical}) + + for item in _automatic_exports(inventory): + add_item(item) + if direct_networks is None: + direct_networks = _direct_private_networks(state, inventory=inventory) + for item in direct_networks: + add_item(item) + if include_remembered: + remembered = list(state.get("published_networks") or []) + list(state.get("extra_networks") or []) + for raw in _normalize_networks(remembered, label="Published networks"): + add_item({"network": raw, "kind": "custom", "label": raw}) + return result + + +def _selection_legacy_extras(selected: list[str]) -> list[str]: + automatic = {item["network"] for item in _automatic_exports()} + return [network for network in selected if network not in automatic] + + +def _apply_publication_payload(state: dict[str, Any], payload: dict[str, Any]) -> None: + """Apply the v0.20.34 explicit publication allow-list with API fallback.""" + if payload.get("published_networks") is not None: + selected = _normalize_networks(payload.get("published_networks") or [], label="Published networks") + state["published_networks"] = selected + # Keep non-WG-derived entries in the old key as a rollback-friendly + # compatibility copy. v0.20.34 itself uses published_networks. + state["extra_networks"] = _selection_legacy_extras(selected) + elif "published_networks" not in state: + state["extra_networks"] = _normalize_networks(payload.get("extra_networks") or [], label="Additional published networks") + + +def _remember_current_detection( + state: dict[str, Any], + *, + inventory: dict[str, Any] | None = None, + direct_networks: list[dict[str, str]] | None = None, +) -> list[dict[str, str]]: + """Remember the local networks visible when the publication list was accepted. + + Later discovery changes are surfaced to the user instead of silently + modifying the explicit Nodes allow-list. + """ + inventory = inventory or _interface_inventory() + if direct_networks is None: + direct_networks = _direct_private_networks(state, inventory=inventory) + automatic = _automatic_exports(inventory) + detected = _available_publish_networks( + state, + inventory=inventory, + direct_networks=direct_networks, + include_remembered=False, + ) + # Keep typed baselines. A WireGuard VPN/Site-to-Site network must not be + # confused with a directly routed LAN when routes change underneath Nodes. + state["publication_seen_automatic_networks"] = [item["network"] for item in automatic] + state["publication_seen_direct_networks"] = [item["network"] for item in direct_networks] + # Compatibility with v0.20.44 and older state. + state["publication_seen_networks"] = [item["network"] for item in detected] + return detected + + +def _network_detection_changes( + state: dict[str, Any], + *, + automatic_networks: list[str], + direct_networks: list[str], + detected_networks: list[str], +) -> dict[str, Any]: + """Compare current discovery with the last user-confirmed baseline.""" + has_typed_baseline = ( + "publication_seen_automatic_networks" in state + or "publication_seen_direct_networks" in state + ) + if has_typed_baseline: + seen_automatic = _normalize_networks( + state.get("publication_seen_automatic_networks") or [], + label="Previously detected WireGuard networks", + ) + seen_direct = _normalize_networks( + state.get("publication_seen_direct_networks") or [], + label="Previously detected LAN networks", + ) + auto_seen_set, auto_current_set = set(seen_automatic), set(automatic_networks) + direct_seen_set, direct_current_set = set(seen_direct), set(direct_networks) + added_automatic = [net for net in automatic_networks if net not in auto_seen_set] + removed_automatic = [net for net in seen_automatic if net not in auto_current_set] + added_direct = [net for net in direct_networks if net not in direct_seen_set] + removed_direct = [net for net in seen_direct if net not in direct_current_set] + added = list(dict.fromkeys(added_automatic + added_direct)) + removed = list(dict.fromkeys(removed_automatic + removed_direct)) + else: + seen_networks = _normalize_networks( + state.get("publication_seen_networks") or [], label="Previously detected networks" + ) + seen_set, current_set = set(seen_networks), set(detected_networks) + added = [net for net in detected_networks if net not in seen_set] + removed = [net for net in seen_networks if net not in current_set] + added_automatic = list(added) + removed_automatic = list(removed) + added_direct = [] + removed_direct = [] + return { + "changed": bool(added or removed), + "added": added, + "removed": removed, + "automatic_added": added_automatic, + "automatic_removed": removed_automatic, + "direct_added": added_direct, + "direct_removed": removed_direct, + } + + +def _vpn_pool_publication_mismatch( + state: dict[str, Any], + *, + inventory: dict[str, Any], + direct_networks: list[dict[str, str]], +) -> dict[str, Any]: + """Detect a managed VPN pool that changed while Nodes still publishes the old pool. + + This is intentionally separate from generic discovery drift. A user may + deliberately omit the current VPN pool from the Nodes allow-list, so that + alone is not an error. We only flag a pool-change mismatch when the + published list still contains a network that was previously observed as a + managed/local candidate and that candidate disappeared while a current VPN + pool is missing from the publication list. + + The legacy publication_seen_networks key is used as a migration hint for + v0.20.44/v0.20.45 state so an already stale 10.0.1.0/24 -> 10.0.2.0/24 + installation is detected immediately after upgrade. + """ + selected = _normalize_networks(state.get("published_networks") or [], label="Published networks") + if not selected: + return {"changed": False, "published_old": [], "current_vpn": []} + + automatic = _automatic_exports(inventory) + current_vpn = [item["network"] for item in automatic if item.get("kind") == "vpn"] + current_auto = {item["network"] for item in automatic} + current_direct = {item.get("network") for item in direct_networks if item.get("network")} + selected_set = set(selected) + missing_current = [net for net in current_vpn if net not in selected_set] + if not missing_current: + return {"changed": False, "published_old": [], "current_vpn": []} + + historical = _normalize_networks( + state.get("publication_seen_automatic_networks") + or state.get("publication_seen_networks") + or [], + label="Previously detected networks", + ) + historical_set = set(historical) + stale = [ + net for net in selected + if net in historical_set and net not in current_auto and net not in current_direct + ] + if not stale: + return {"changed": False, "published_old": [], "current_vpn": []} + + return { + "changed": True, + "published_old": stale, + "current_vpn": missing_current, + } + + +def _candidate_network_conflicts( + state: dict[str, Any], + candidate_exports: list[dict[str, str]], + *, + peers: list[dict[str, Any]] | None = None, + local_exports: list[dict[str, str]] | None = None, + exclude_node_id: str = "", + candidate_owner_id: str = "candidate", +) -> list[dict[str, str]]: + """Return detailed overlap conflicts for a proposed publication list.""" + peers = peers if peers is not None else _peer_rows() + owners: list[tuple[str, str, str, ipaddress.IPv4Network]] = [] + + if local_exports is not None and candidate_owner_id != "local": + local_name = _normalize_name(str(state.get("node_name") or "HUB"), "HUB") + local_id = str(state.get("node_id") or "hub") + for item in local_exports: + raw = str(item.get("network") if isinstance(item, dict) else item or "").strip() + try: + owners.append((local_id, local_name, raw, ipaddress.ip_network(raw, strict=False))) + except ValueError: + continue + + for peer in peers: + node_id = str(peer.get("node_id") or "") + if node_id and node_id == exclude_node_id: + continue + owner_name = str(peer.get("name") or node_id or "WGTools") + for item in peer.get("exports") or []: + raw = str(item.get("network") if isinstance(item, dict) else item or "").strip() + try: + owners.append((node_id, owner_name, raw, ipaddress.ip_network(raw, strict=False))) + except ValueError: + continue + + transport = _transport_network(state) + conflicts: list[dict[str, str]] = [] + seen: set[tuple[str, str, str]] = set() + for item in candidate_exports: + raw = str(item.get("network") if isinstance(item, dict) else item or "").strip() + try: + net = ipaddress.ip_network(raw, strict=False) + except ValueError: + continue + if net.overlaps(transport): + key = (str(net), "transport", str(transport)) + if key not in seen: + seen.add(key) + conflicts.append({ + "network": str(net), + "owner_type": "transport", + "owner_name": "WGTools Nodes", + "owner_network": str(transport), + }) + for owner_id, owner_name, owner_raw, owner_net in owners: + if owner_id == candidate_owner_id: + continue + if net.overlaps(owner_net): + key = (str(net), owner_id or owner_name, str(owner_net)) + if key in seen: + continue + seen.add(key) + conflicts.append({ + "network": str(net), + "owner_type": "node", + "owner_name": owner_name, + "owner_network": str(owner_net), + "owner_id": owner_id, + }) + return conflicts + + +def _raise_network_conflicts(conflicts: list[dict[str, str]]) -> None: + if conflicts: + raise NodeNetworkConflictError(conflicts) + + +def _local_exports( + state: dict[str, Any] | None = None, + *, + inventory: dict[str, Any] | None = None, + available_networks: list[dict[str, str]] | None = None, +) -> list[dict[str, str]]: + """Return the explicit network allow-list published into the Nodes fabric. + + New configurations store ``published_networks``: the connect/HUB dialog is + pre-filled with all detected VPN, Site-to-Site and local LAN candidates and + the user removes anything that should stay private. Legacy installations + without that key keep the v0.20.32 behaviour (all WG-derived networks plus + ``extra_networks``) until their Node settings are saved once. + """ + state = state or _load_state() + if "published_networks" in state: + selected = _normalize_networks(state.get("published_networks") or [], label="Published networks") + if available_networks is None: + available_networks = _available_publish_networks(state, inventory=inventory) + candidates = {item["network"]: item for item in available_networks} + result: list[dict[str, str]] = [] + for network in selected[:MAX_EXPORTED_NETWORKS]: + item = candidates.get(network) or {"network": network, "kind": "custom", "label": network} + result.append(item) + return result + + # Backward compatibility for Nodes created before explicit publication + # selection existed. Do not add newly discovered host LANs silently. + result = list(_automatic_exports(inventory)) + seen = {item["network"] for item in result} + for raw in _normalize_networks(state.get("extra_networks") or [], label="Additional published networks"): + if raw in seen or len(result) >= MAX_EXPORTED_NETWORKS: + continue + seen.add(raw) + result.append({"network": raw, "kind": "custom", "label": raw}) + return result + + +def _local_clients(inventory: dict[str, Any] | None = None) -> list[dict[str, Any]]: + result: list[dict[str, Any]] = [] + inventory = inventory or _interface_inventory() + for item in inventory.get("interfaces") or []: + iface = str(item.get("name") or "").strip() + if not iface or not item.get("configured"): + continue + try: + snap = run_helper("snapshot", {"view": "peers"}, interface=iface) + except HelperError: + continue + for peer in snap.get("peers") or []: + latest = int(peer.get("latest_handshake") or 0) + remote_networks = list(peer.get("remote_networks") or []) + result.append({ + "name": str(peer.get("name") or "Unnamed")[:64], + "interface": iface, + "vpn_address": str(peer.get("vpn_address") or "")[:64], + "type": "site_to_site" if remote_networks else "client", + "online": bool(latest and time.time() - latest <= ONLINE_THRESHOLD_SECONDS), + "last_seen": latest, + }) + if len(result) >= MAX_CLIENT_SUMMARY: + return result + return result + + +def local_summary( + state: dict[str, Any] | None = None, + *, + inventory: dict[str, Any] | None = None, + exports: list[dict[str, str]] | None = None, + clients: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + state = state or _load_state() + name = _normalize_name(str(state.get("node_name") or socket.gethostname() or "WGTools"), "WGTools") + return { + "node_id": str(state.get("node_id") or ""), + "name": name, + "role": str(state.get("mode") or "none"), + "version": VERSION, + "transport_ip": str(state.get("transport_ip") or ""), + "panel_url": str(state.get("panel_url") or ""), + "exports": exports if exports is not None else _local_exports(state, inventory=inventory), + "clients": clients if clients is not None else _local_clients(inventory), + "last_seen": int(time.time()), + } + + +def _peer_rows() -> list[dict[str, Any]]: + init_nodes_database() + with _connect() as conn: + rows = conn.execute("SELECT * FROM wg_node_peers ORDER BY connected_at,node_id").fetchall() + result: list[dict[str, Any]] = [] + for row in rows: + item = dict(row) + item["exports"] = _json_load(item.pop("exports_json", "[]"), []) + item["clients"] = _json_load(item.pop("clients_json", "[]"), []) + result.append(item) + return result + + +def _peer_by_id(node_id: str) -> dict[str, Any] | None: + for item in _peer_rows(): + if item.get("node_id") == node_id: + return item + return None + + +def _peer_by_public_key(public_key: str) -> dict[str, Any] | None: + for item in _peer_rows(): + if str(item.get("public_key") or "") == str(public_key or ""): + return item + return None + + +def _write_peer_record(peer: dict[str, Any]) -> None: + """Restore/insert one peer row from a normalized _peer_rows() record.""" + with _connect() as conn: + conn.execute( + "INSERT OR REPLACE INTO wg_node_peers(node_id,name,public_key,preshared_key,secret,transport_ip,panel_url,version,exports_json,clients_json,connected_at,last_seen,last_error) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", + ( + peer.get("node_id"), peer.get("name"), peer.get("public_key"), peer.get("preshared_key"), peer.get("secret"), + peer.get("transport_ip"), peer.get("panel_url") or "", peer.get("version") or "", + json.dumps(peer.get("exports") or [], ensure_ascii=False), json.dumps(peer.get("clients") or [], ensure_ascii=False), + int(peer.get("connected_at") or time.time()), int(peer.get("last_seen") or 0), str(peer.get("last_error") or ""), + ), + ) + + +def _transport_network(state: dict[str, Any]) -> ipaddress.IPv4Network: + raw = str(state.get("transport_network") or DEFAULT_TRANSPORT_NETWORK) + try: + net = ipaddress.ip_network(raw, strict=False) + except ValueError as exc: + raise ValueError("Invalid Node transport network") from exc + if net.version != 4 or net.prefixlen > 29 or net.prefixlen < 16: + raise ValueError("Node transport network must be an IPv4 /16 to /29 network") + if not net.is_private: + raise ValueError("Node transport network must use private IPv4 addressing") + if net.num_addresses < 8: + raise ValueError("Node transport network is too small") + return net + + +def _assign_transport_ip(state: dict[str, Any]) -> str: + net = _transport_network(state) + used = {str(item.get("transport_ip") or "") for item in _peer_rows()} + hosts = net.hosts() + try: + next(hosts) # hub owns the first host + except StopIteration as exc: + raise RuntimeError("Node transport network is too small") from exc + for ip in hosts: + if str(ip) not in used: + return str(ip) + raise RuntimeError("Node transport network has no free addresses") + + +def _network_conflicts( + state: dict[str, Any], + peers: list[dict[str, Any]], + *, + local: dict[str, Any] | None = None, +) -> tuple[dict[str, list[str]], dict[str, list[str]]]: + owners: list[tuple[str, str, ipaddress.IPv4Network]] = [] + local = local or local_summary(state) + local_id = str(local.get("node_id") or "hub") + for exp in local.get("exports") or []: + try: + owners.append((local_id, str(exp.get("network") or ""), ipaddress.ip_network(str(exp.get("network") or ""), strict=False))) + except ValueError: + continue + for peer in peers: + node_id = str(peer.get("node_id") or "") + for exp in peer.get("exports") or []: + raw = str(exp.get("network") if isinstance(exp, dict) else exp) + try: + owners.append((node_id, raw, ipaddress.ip_network(raw, strict=False))) + except ValueError: + continue + + conflicts: dict[str, list[str]] = {} + valid: dict[str, list[str]] = {} + transport = _transport_network(state) + for node_id, raw, net in owners: + bad = net.overlaps(transport) + if not bad: + for other_id, other_raw, other in owners: + if (other_id, other_raw) == (node_id, raw): + continue + if node_id != other_id and net.overlaps(other): + bad = True + break + if bad: + conflicts.setdefault(node_id, []).append(raw) + else: + valid.setdefault(node_id, []).append(raw) + for mapping in (conflicts, valid): + for key in list(mapping): + mapping[key] = sorted(set(mapping[key]), key=lambda x: (ipaddress.ip_network(x).network_address, ipaddress.ip_network(x).prefixlen)) + return conflicts, valid + + +def _node_runtime() -> dict[str, dict[str, Any]]: + if not _wg_available(): + return {} + rc, out, _ = _run(["wg", "show", NODE_INTERFACE, "dump"]) + if rc != 0 or not out: + return {} + lines = out.splitlines() + result: dict[str, dict[str, Any]] = {} + for line in lines[1:]: + parts = line.split("\t") + if len(parts) < 8: + continue + pub = parts[0] + try: + latest = int(parts[4] or 0) + rx = int(parts[5] or 0) + tx = int(parts[6] or 0) + except ValueError: + latest, rx, tx = 0, 0, 0 + result[pub] = {"endpoint": parts[2], "latest_handshake": latest, "rx_bytes": rx, "tx_bytes": tx} + return result + + +def _topology( + state: dict[str, Any] | None = None, + *, + local: dict[str, Any] | None = None, +) -> dict[str, Any]: + state = state or _load_state() + mode = str(state.get("mode") or "none") + if mode == "hub": + peers = _peer_rows() + hub = local or local_summary(state) + conflicts, valid = _network_conflicts(state, peers, local=hub) + runtime = _node_runtime() + hub["conflicts"] = conflicts.get(str(hub.get("node_id") or "hub"), []) + hub["valid_exports"] = valid.get(str(hub.get("node_id") or "hub"), []) + nodes = [hub] + now = int(time.time()) + for peer in peers: + rt = runtime.get(str(peer.get("public_key") or ""), {}) + latest = max(int(peer.get("last_seen") or 0), int(rt.get("latest_handshake") or 0)) + clients = peer.get("clients") if isinstance(peer.get("clients"), list) else [] + node_id = str(peer.get("node_id") or "") + handshake = int(rt.get("latest_handshake") or 0) + control_seen = int(peer.get("last_seen") or 0) + freshness = max(45, SYNC_INTERVAL_SECONDS * 4) + nodes.append({ + "node_id": node_id, + "name": peer.get("name"), + "role": "spoke", + "version": peer.get("version"), + "transport_ip": peer.get("transport_ip"), + "panel_url": peer.get("panel_url"), + "exports": peer.get("exports") or [], + "clients": clients, + "last_seen": latest, + "last_handshake": handshake, + "control_last_seen": control_seen, + "tunnel_online": bool(handshake and now - handshake <= freshness), + "control_online": bool(control_seen and now - control_seen <= freshness), + "online": bool(handshake and now - handshake <= freshness), + "endpoint": rt.get("endpoint") or "", + "rx_bytes": int(rt.get("rx_bytes") or 0), + "tx_bytes": int(rt.get("tx_bytes") or 0), + "conflicts": conflicts.get(node_id, []), + "valid_exports": valid.get(node_id, []), + "last_error": peer.get("last_error") or "", + }) + return {"generated_at": now, "hub_id": hub.get("node_id"), "nodes": nodes} + cache = _load_cache() + if isinstance(cache.get("topology"), dict): + return cache["topology"] + return {"generated_at": int(time.time()), "hub_id": "", "nodes": []} + + +def _remote_routes_for_spoke(state: dict[str, Any], topology: dict[str, Any]) -> list[str]: + own_id = str(state.get("node_id") or "") + result: list[str] = [] + for node in topology.get("nodes") or []: + if str(node.get("node_id") or "") == own_id: + continue + for raw in node.get("valid_exports") or []: + if raw not in result: + result.append(str(raw)) + return result + + +def _local_service_egress_networks(state: dict[str, Any], topology: dict[str, Any] | None = None) -> list[str]: + """Networks where Node transport addresses need a local return-path helper. + + A device in a published LAN normally has no route back to the internal Node + transport network. We therefore NAT only traffic whose *source* is the + Node transport network and whose *destination* is a network published by + this WGTools instance. Site-to-site LAN traffic keeps its original source + address and is not affected by these rules. + """ + own_id = str(state.get("node_id") or "") + if topology: + for node in topology.get("nodes") or []: + if str(node.get("node_id") or "") != own_id: + continue + values = [] + for raw in node.get("valid_exports") or []: + text = str(raw or "").strip() + if text and text not in values: + values.append(text) + return values + + transport = _transport_network(state) + result: list[str] = [] + for item in _local_exports(state): + raw = str(item.get("network") or "").strip() + if not raw: + continue + try: + network = ipaddress.ip_network(raw, strict=False) + except ValueError: + continue + if network.version != 4 or network.overlaps(transport): + continue + canonical = str(network) + if canonical not in result: + result.append(canonical) + return result + + +def _remote_vpn_source_networks(state: dict[str, Any], topology: dict[str, Any] | None = None) -> list[str]: + """Return valid VPN client pools published by other Nodes. + + Only remote exports explicitly typed as ``vpn`` are selected. Routed LAN + and Site-to-Site sources keep their original addresses end to end. + """ + topology = topology or _topology(state) + own_id = str(state.get("node_id") or "") + result: list[str] = [] + for node in topology.get("nodes") or []: + if str(node.get("node_id") or "") == own_id: + continue + valid = {str(raw or "").strip() for raw in node.get("valid_exports") or []} + for item in node.get("exports") or []: + if not isinstance(item, dict) or str(item.get("kind") or "") != "vpn": + continue + raw = str(item.get("network") or "").strip() + if raw not in valid: + continue + try: + canonical = str(ipaddress.ip_network(raw, strict=False)) + except ValueError: + continue + if canonical not in result: + result.append(canonical) + return result + + +def _config_text(state: dict[str, Any], topology: dict[str, Any] | None = None) -> str: + mode = str(state.get("mode") or "none") + if mode not in {"hub", "spoke"}: + raise ValueError("WGTools Nodes is not configured") + private_key = str(state.get("private_key") or "") + if not private_key: + raise RuntimeError("WGTools Node private key is missing") + transport = _transport_network(state) + lines = ["# Managed by WGTools Nodes. Do not edit manually.", "[Interface]"] + if mode == "hub": + address = str(state.get("transport_ip") or next(transport.hosts())) + lines += [f"Address = {address}/{transport.prefixlen}", f"ListenPort = {int(state.get('listen_port') or DEFAULT_LISTEN_PORT)}"] + else: + address = str(state.get("transport_ip") or "") + if not address: + raise RuntimeError("Spoke transport address is missing") + lines += [f"Address = {address}/32"] + lines += [f"PrivateKey = {private_key}", "SaveConfig = false"] + lines += [ + "PostUp = sysctl -w net.ipv4.ip_forward=1", + f"PostUp = iptables -C FORWARD -i {NODE_INTERFACE} -j ACCEPT 2>/dev/null || iptables -A FORWARD -i {NODE_INTERFACE} -j ACCEPT", + f"PostUp = iptables -C FORWARD -o {NODE_INTERFACE} -j ACCEPT 2>/dev/null || iptables -A FORWARD -o {NODE_INTERFACE} -j ACCEPT", + f"PostDown = iptables -D FORWARD -i {NODE_INTERFACE} -j ACCEPT 2>/dev/null || true", + f"PostDown = iptables -D FORWARD -o {NODE_INTERFACE} -j ACCEPT 2>/dev/null || true", + ] + + # Keep Node-service NAT in a dedicated chain. Besides keeping the user's + # POSTROUTING table tidy, this makes config changes safe: the chain is + # rebuilt on every wgnode0 start, so removed published networks cannot + # leave stale MASQUERADE rules behind. + service_nat_chain = "WGTOOLS-NODES-NAT" + service_nat_comment = "wgtools-nodes-service-egress" + transport_source = str(transport) + lines += [ + f"PostUp = iptables -t nat -N {service_nat_chain} 2>/dev/null || true", + f"PostUp = iptables -t nat -F {service_nat_chain}", + f"PostUp = iptables -t nat -C POSTROUTING -s {transport_source} -m comment --comment {service_nat_comment} -j {service_nat_chain} 2>/dev/null || iptables -t nat -A POSTROUTING -s {transport_source} -m comment --comment {service_nat_comment} -j {service_nat_chain}", + ] + for raw in _local_service_egress_networks(state, topology): + lines.append(f"PostUp = iptables -t nat -A {service_nat_chain} -d {raw} -j MASQUERADE") + lines += [ + f"PostDown = iptables -t nat -D POSTROUTING -s {transport_source} -m comment --comment {service_nat_comment} -j {service_nat_chain} 2>/dev/null || true", + f"PostDown = iptables -t nat -F {service_nat_chain} 2>/dev/null || true", + f"PostDown = iptables -t nat -X {service_nat_chain} 2>/dev/null || true", + ] + + # A normal WG client on a remote Node arrives with an address from that + # Node's VPN pool (for example 10.0.7.0/24). A LAN device published here + # normally has no return route to that remote client pool. Apply a narrow + # return-path NAT only for remote VPN pools -> locally published networks. + # Site-to-Site and custom LAN sources remain routed without NAT. + client_nat_chain = "WGTOOLS-NODES-CLIENT-NAT" + client_nat_comment = "wgtools-nodes-client-egress" + local_destinations = _local_service_egress_networks(state, topology) + remote_vpn_sources = _remote_vpn_source_networks(state, topology) + lines += [ + f"PostUp = iptables -t nat -N {client_nat_chain} 2>/dev/null || true", + f"PostUp = iptables -t nat -F {client_nat_chain}", + f"PostUp = iptables -t nat -C POSTROUTING -m comment --comment {client_nat_comment} -j {client_nat_chain} 2>/dev/null || iptables -t nat -A POSTROUTING -m comment --comment {client_nat_comment} -j {client_nat_chain}", + ] + for source in remote_vpn_sources: + for destination in local_destinations: + lines.append(f"PostUp = iptables -t nat -A {client_nat_chain} -s {source} -d {destination} -j MASQUERADE") + lines += [ + f"PostDown = iptables -t nat -D POSTROUTING -m comment --comment {client_nat_comment} -j {client_nat_chain} 2>/dev/null || true", + f"PostDown = iptables -t nat -F {client_nat_chain} 2>/dev/null || true", + f"PostDown = iptables -t nat -X {client_nat_chain} 2>/dev/null || true", + ] + + if mode == "hub": + peers = _peer_rows() + _conflicts, valid = _network_conflicts(state, peers) + local_id = str(state.get("node_id") or "") + remote_networks: list[str] = [] + for peer in peers: + remote_networks.extend(valid.get(str(peer.get("node_id") or ""), [])) + for table in _local_policy_tables(): + for raw in sorted(set(remote_networks)): + lines.append(f"PostUp = ip route replace {raw} dev {NODE_INTERFACE} table {table}") + lines.append(f"PostDown = ip route del {raw} dev {NODE_INTERFACE} table {table} 2>/dev/null || true") + for peer in peers: + allowed = [f"{peer['transport_ip']}/32"] + valid.get(str(peer.get("node_id") or ""), []) + lines += ["", f"# ---node:{peer['node_id']}---", "[Peer]", f"PublicKey = {peer['public_key']}", f"PresharedKey = {peer['preshared_key']}", f"AllowedIPs = {','.join(allowed)}"] + else: + if topology is None: + topology = _topology(state) + remote_routes = _remote_routes_for_spoke(state, topology) + for table in _local_policy_tables(): + for raw in remote_routes: + lines.append(f"PostUp = ip route replace {raw} dev {NODE_INTERFACE} table {table}") + lines.append(f"PostDown = ip route del {raw} dev {NODE_INTERFACE} table {table} 2>/dev/null || true") + allowed = [str(transport)] + remote_routes + lines += [ + "", + "# ---WGTools HUB---", + "[Peer]", + f"PublicKey = {state.get('hub_public_key')}", + f"PresharedKey = {state.get('preshared_key')}", + f"AllowedIPs = {','.join(dict.fromkeys(allowed))}", + f"Endpoint = {_endpoint_text(str(state.get('hub_endpoint_host') or ''), int(state.get('hub_endpoint_port') or DEFAULT_LISTEN_PORT))}", + "PersistentKeepalive = 25", + ] + return "\n".join(lines).rstrip() + "\n" + + +def _apply_config(state: dict[str, Any], topology: dict[str, Any] | None = None) -> dict[str, Any]: + text = _config_text(state, topology) + path = Path("/etc/wireguard") / f"{NODE_INTERFACE}.conf" + path.parent.mkdir(parents=True, exist_ok=True) + old = path.read_text(encoding="utf-8") if path.exists() else None + if old is not None and not old.startswith("# Managed by WGTools Nodes."): + raise RuntimeError(f"{NODE_INTERFACE}.conf already exists and is not managed by WGTools Nodes") + if old == text: + if subprocess.run(["systemctl", "is-active", "--quiet", f"wg-quick@{NODE_INTERFACE}.service"], check=False).returncode != 0: + rc, out, err = _run(["systemctl", "enable", "--now", f"wg-quick@{NODE_INTERFACE}.service"], timeout=45) + if rc != 0: + raise RuntimeError(err or out or "Could not start WGTools Node tunnel") + return {"changed": False} + + tmp = path.with_suffix(".conf.tmp") + tmp.write_text(text, encoding="utf-8") + os.chmod(tmp, 0o600) + tmp.replace(path) + os.chmod(path, 0o600) + rc, out, err = _run(["systemctl", "enable", f"wg-quick@{NODE_INTERFACE}.service"], timeout=30) + if rc != 0: + if old is None: + path.unlink(missing_ok=True) + else: + path.write_text(old, encoding="utf-8") + os.chmod(path, 0o600) + raise RuntimeError(err or out or "Could not enable WGTools Node tunnel") + action = "restart" if old is not None or subprocess.run(["systemctl", "is-active", "--quiet", f"wg-quick@{NODE_INTERFACE}.service"], check=False).returncode == 0 else "start" + rc, out, err = _run(["systemctl", action, f"wg-quick@{NODE_INTERFACE}.service"], timeout=45) + if rc != 0: + if old is None: + # A failed first start must not leave an enabled dead unit behind. + _run(["systemctl", "disable", "--now", f"wg-quick@{NODE_INTERFACE}.service"], timeout=30) + path.unlink(missing_ok=True) + else: + path.write_text(old, encoding="utf-8") + os.chmod(path, 0o600) + _run(["systemctl", "restart", f"wg-quick@{NODE_INTERFACE}.service"], timeout=45) + raise RuntimeError(err or out or "WGTools Node tunnel failed to start") + return {"changed": True} + + +def _remove_config() -> None: + _run(["systemctl", "disable", "--now", f"wg-quick@{NODE_INTERFACE}.service"], timeout=45) + _run(["ip", "link", "delete", NODE_INTERFACE], timeout=10) + Path(f"/etc/wireguard/{NODE_INTERFACE}.conf").unlink(missing_ok=True) + + +def _validate_hub_network(state: dict[str, Any], network: str) -> str: + net = ipaddress.ip_network(network, strict=False) + if net.version != 4 or net.prefixlen > 29 or net.prefixlen < 16 or not net.is_private: + raise ValueError("Transport network must be a private IPv4 /16 to /29 network") + for item in _interface_inventory().get("interfaces") or []: + raw = str(item.get("vpn_network") or "").strip() + if not raw: + continue + try: + other = ipaddress.ip_network(raw, strict=False) + except ValueError: + continue + if net.overlaps(other): + raise ValueError(f"Node transport network {net} overlaps WireGuard network {other}") + return str(net) + + +def enable_hub(payload: dict[str, Any]) -> dict[str, Any]: + with _lock: + state = _load_state() + current_mode = str(state.get("mode") or "none") + if current_mode == "spoke": + raise ValueError("Disconnect this WGTools instance from its current HUB before enabling HUB mode") + state = _ensure_identity(state) + previous_state = dict(state) + node_name = _normalize_name(str(payload.get("node_name") or socket.gethostname()), socket.gethostname()) + listen_port = int(payload.get("listen_port") or DEFAULT_LISTEN_PORT) + if not 1 <= listen_port <= 65535: + raise ValueError("Invalid HUB Node port") + inventory = _interface_inventory() + for item in inventory.get("interfaces") or []: + try: + if item.get("configured") and int(item.get("listen_port") or 0) == listen_port: + raise ValueError(f"UDP port {listen_port} is already used by {item.get('name')}") + except (TypeError, ValueError) as exc: + if isinstance(exc, ValueError) and "already used" in str(exc): + raise + if current_mode != "hub" or int(state.get("listen_port") or 0) != listen_port: + try: + probe = _open_control_listener(listen_port) + probe.close() + except Exception as exc: + raise ValueError(f"TCP port {listen_port} is not available for WGTools Nodes: {exc}") from exc + transport_network = _validate_hub_network(state, str(payload.get("transport_network") or DEFAULT_TRANSPORT_NETWORK)) + net = ipaddress.ip_network(transport_network) + state.update({ + "mode": "hub", + "node_name": node_name, + "listen_port": listen_port, + "transport_network": transport_network, + "transport_ip": str(next(net.hosts())), + "last_error": "", + }) + _apply_publication_payload(state, payload) + direct_networks = _direct_private_networks(state, inventory=inventory) + available_networks = _available_publish_networks( + state, inventory=inventory, direct_networks=direct_networks + ) + candidate_exports = _local_exports( + state, inventory=inventory, available_networks=available_networks + ) + _raise_network_conflicts( + _candidate_network_conflicts( + state, candidate_exports, peers=_peer_rows(), candidate_owner_id="local" + ) + ) + _remember_current_detection(state, inventory=inventory, direct_networks=direct_networks) + # v0.20.29 stored web/published endpoint data in the HUB state. The Node + # control plane no longer needs either value for pairing. panel_url is + # retained only when it was configured separately in Node settings. + state.pop("endpoint_host", None) + _save_state(state) + _ensure_control_certificate() + state = _load_state() + try: + _apply_config(state, _topology(state)) + except Exception: + # Keep the generated Node identity, but do not report HUB mode when + # its system tunnel could not be activated. + _save_state(previous_state) + raise + return get_nodes_status() + + +def update_local_settings(payload: dict[str, Any]) -> dict[str, Any]: + with _lock: + state = _load_state() + if str(state.get("mode") or "none") not in {"hub", "spoke"}: + raise ValueError("WGTools Nodes is not configured") + previous_state = dict(state) + if "node_name" in payload: + state["node_name"] = _normalize_name(str(payload.get("node_name") or "")) + if "panel_url" in payload: + state["panel_url"] = _normalize_panel_url(str(payload.get("panel_url") or ""), allow_empty=True) + _apply_publication_payload(state, payload) + + inventory = _interface_inventory() + direct_networks = _direct_private_networks(state, inventory=inventory) + available_networks = _available_publish_networks( + state, inventory=inventory, direct_networks=direct_networks + ) + candidate_exports = _local_exports( + state, inventory=inventory, available_networks=available_networks + ) + if state.get("mode") == "hub": + _raise_network_conflicts( + _candidate_network_conflicts( + state, candidate_exports, peers=_peer_rows(), candidate_owner_id="local" + ) + ) + _remember_current_detection(state, inventory=inventory, direct_networks=direct_networks) + _save_state(state) + + if state.get("mode") == "hub": + try: + _apply_config(state, _topology(state)) + except Exception: + _save_state(previous_state) + raise + else: + # The HUB is authoritative for conflicts because it knows every + # published network in the fabric. If it rejects the new allow-list, + # restore the previous local settings instead of leaving the UI and + # tunnel out of sync. + try: + sync_spoke_once() + except Exception as exc: + previous_state["last_error"] = str(exc)[:500] + _save_state(previous_state) + raise + return get_nodes_status() + + +def create_join_code() -> dict[str, Any]: + with _lock: + state = _load_state() + if str(state.get("mode") or "") != "hub": + raise ValueError("Enable HUB mode first") + _cert, _key, fingerprint = _ensure_control_certificate() + code = f"WGTOOLS-NODE-v1.{fingerprint}.{secrets.token_urlsafe(24)}" + digest = hashlib.sha256(code.encode("utf-8")).hexdigest() + now = int(time.time()) + expires = now + JOIN_TTL_SECONDS + with _connect() as conn: + conn.execute("DELETE FROM wg_node_join_codes WHERE expires_at None: + digest = hashlib.sha256(str(code or "").strip().encode("utf-8")).hexdigest() + now = int(time.time()) + with _connect() as conn: + row = conn.execute("SELECT expires_at FROM wg_node_join_codes WHERE code_hash=?", (digest,)).fetchone() + if not row or int(row["expires_at"]) < now: + conn.execute("DELETE FROM wg_node_join_codes WHERE code_hash=?", (digest,)) + raise ValueError("The WGTools Node connection code is invalid or expired") + conn.execute("DELETE FROM wg_node_join_codes WHERE code_hash=?", (digest,)) + + +def _clean_remote_exports(values: Any) -> list[dict[str, str]]: + result: list[dict[str, str]] = [] + networks: list[str] = [] + items = values if isinstance(values, list) else [] + for item in items: + raw = str(item.get("network") if isinstance(item, dict) else item).strip() + if raw: + networks.append(raw) + valid = _normalize_networks(networks, label="Remote Node networks") + by_net: dict[str, dict[str, str]] = {} + for item in items: + if not isinstance(item, dict): + continue + raw = str(item.get("network") or "").strip() + try: + canonical = str(ipaddress.ip_network(raw, strict=False)) + except ValueError: + continue + if canonical in valid: + by_net[canonical] = {"network": canonical, "kind": str(item.get("kind") or "remote")[:24], "label": str(item.get("label") or canonical)[:64]} + return [by_net.get(net, {"network": net, "kind": "remote", "label": net}) for net in valid] + + +def _clean_remote_clients(values: Any) -> list[dict[str, Any]]: + result: list[dict[str, Any]] = [] + for item in values if isinstance(values, list) else []: + if not isinstance(item, dict): + continue + result.append({ + "name": str(item.get("name") or "Unnamed")[:64], + "interface": str(item.get("interface") or "")[:15], + "vpn_address": str(item.get("vpn_address") or "")[:64], + "type": "site_to_site" if str(item.get("type") or "") == "site_to_site" else "client", + "online": bool(item.get("online")), + "last_seen": int(item.get("last_seen") or 0), + }) + if len(result) >= MAX_CLIENT_SUMMARY: + break + return result + + +def public_join(payload: dict[str, Any]) -> dict[str, Any]: + with _lock: + state = _load_state() + if str(state.get("mode") or "") != "hub": + raise ValueError("This WGTools instance is not operating as a HUB") + public_key = str(payload.get("public_key") or "").strip() + if len(public_key) < 40 or len(public_key) > 64: + raise ValueError("Invalid Node WireGuard public key") + name = _normalize_name(str(payload.get("node_name") or "WGTools Node")) + panel_url = _normalize_panel_url(str(payload.get("panel_url") or ""), allow_empty=True) + exports = _clean_remote_exports(payload.get("exports")) + clients = _clean_remote_clients(payload.get("clients")) + node_id = str(payload.get("node_id") or "").strip() + if not re_node_id(node_id): + node_id = uuid.uuid4().hex + + existing = _peer_by_id(node_id) + same_key = _peer_by_public_key(public_key) + displaced = same_key if same_key and str(same_key.get("node_id") or "") != node_id else None + replaced_ids = {node_id} + if displaced: + replaced_ids.add(str(displaced.get("node_id") or "")) + comparison_peers = [ + item for item in _peer_rows() + if str(item.get("node_id") or "") not in replaced_ids + ] + _raise_network_conflicts( + _candidate_network_conflicts( + state, + exports, + peers=comparison_peers, + local_exports=_local_exports(state), + candidate_owner_id=node_id, + ) + ) + preserved_peer = existing or displaced + transport_ip = str(preserved_peer.get("transport_ip") or _assign_transport_ip(state)) if preserved_peer else _assign_transport_ip(state) + + rc, psk, err = _run(["wg", "genpsk"]) + if rc != 0 or not psk: + raise RuntimeError(err or "Could not generate Node preshared key") + secret = secrets.token_urlsafe(32) + now = int(time.time()) + + # Consume only after all request validation and key generation succeeded. + _consume_join_code(str(payload.get("join_code") or "")) + if displaced: + with _connect() as conn: + conn.execute("DELETE FROM wg_node_peers WHERE node_id=?", (displaced.get("node_id"),)) + with _connect() as conn: + conn.execute( + "INSERT INTO wg_node_peers(node_id,name,public_key,preshared_key,secret,transport_ip,panel_url,version,exports_json,clients_json,connected_at,last_seen,last_error) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) " + "ON CONFLICT(node_id) DO UPDATE SET name=excluded.name,public_key=excluded.public_key,preshared_key=excluded.preshared_key,secret=excluded.secret,transport_ip=excluded.transport_ip,panel_url=excluded.panel_url,version=excluded.version,exports_json=excluded.exports_json,clients_json=excluded.clients_json,last_seen=excluded.last_seen,last_error=''", + (node_id, name, public_key, psk, secret, transport_ip, panel_url, str(payload.get("version") or "")[:32], json.dumps(exports, ensure_ascii=False), json.dumps(clients, ensure_ascii=False), now, now, ""), + ) + topology = _topology(state) + try: + _apply_config(state, topology) + except Exception: + # _apply_config already restored the previous on-disk tunnel. Match + # SQLite to that rollback as well so the topology is transactional. + with _connect() as conn: + conn.execute("DELETE FROM wg_node_peers WHERE node_id=?", (node_id,)) + if existing: + _write_peer_record(existing) + if displaced and (not existing or displaced.get("node_id") != existing.get("node_id")): + _write_peer_record(displaced) + raise + return { + "ok": True, + "node_id": node_id, + "node_secret": secret, + "transport_ip": transport_ip, + "transport_network": str(state.get("transport_network") or DEFAULT_TRANSPORT_NETWORK), + "hub": { + "node_id": state.get("node_id"), + "name": state.get("node_name"), + "public_key": state.get("public_key"), + "transport_ip": state.get("transport_ip"), + "panel_url": state.get("panel_url"), + }, + "preshared_key": psk, + "topology": _topology(state), + } + + +def re_node_id(value: str) -> bool: + return bool(value) and len(value) <= 64 and all(ch.isalnum() or ch in "-_" for ch in value) + + +def public_sync(node_id: str, secret: str, payload: dict[str, Any], *, defer_apply: bool = False) -> dict[str, Any]: + with _lock: + peer = _peer_by_id(node_id) + if not peer or not secrets.compare_digest(str(peer.get("secret") or ""), str(secret or "")): + raise PermissionError("Invalid WGTools Node credentials") + name = _normalize_name(str(payload.get("node_name") or peer.get("name") or "WGTools Node")) + panel_url = _normalize_panel_url(str(payload.get("panel_url") or peer.get("panel_url") or ""), allow_empty=True) + exports = _clean_remote_exports(payload.get("exports")) + clients = _clean_remote_clients(payload.get("clients")) + old_exports = peer.get("exports") or [] + state = _load_state() + comparison_peers = [ + item for item in _peer_rows() + if str(item.get("node_id") or "") != str(node_id or "") + ] + _raise_network_conflicts( + _candidate_network_conflicts( + state, + exports, + peers=comparison_peers, + local_exports=_local_exports(state), + exclude_node_id=node_id, + candidate_owner_id=node_id, + ) + ) + now = int(time.time()) + with _connect() as conn: + conn.execute( + "UPDATE wg_node_peers SET name=?,panel_url=?,version=?,exports_json=?,clients_json=?,last_seen=?,last_error='' WHERE node_id=?", + (name, panel_url, str(payload.get("version") or "")[:32], json.dumps(exports, ensure_ascii=False), json.dumps(clients, ensure_ascii=False), now, node_id), + ) + topology = _topology(state) + if old_exports != exports: + if defer_apply: + return {"ok": True, "topology": topology, "_deferred_previous_peer": peer} + try: + _apply_config(state, topology) + except Exception as exc: + # Keep DB exports aligned with the WireGuard config that + # _apply_config rolled back to. A later sync will retry. + _write_peer_record(peer) + with _connect() as conn: + conn.execute("UPDATE wg_node_peers SET last_error=? WHERE node_id=?", (str(exc)[:500], node_id)) + raise + return {"ok": True, "topology": topology} + + +def _finish_deferred_sync(previous_peer: dict[str, Any]) -> None: + """Apply HUB topology after the in-tunnel sync response is already sent. + + Restarting wgnode0 while a TCP response is still in flight can tear down + the very connection carrying that response. Pairing is public TCP, but + steady-state sync is intentionally inside wgnode0, so configuration changes + are committed immediately after the response has been flushed. + """ + with _lock: + node_id = str(previous_peer.get("node_id") or "") + try: + state = _load_state() + _apply_config(state, _topology(state)) + except Exception as exc: + _write_peer_record(previous_peer) + with _connect() as conn: + conn.execute("UPDATE wg_node_peers SET last_error=? WHERE node_id=?", (str(exc)[:500], node_id)) + + +def _finish_deferred_sync_later(previous_peer: dict[str, Any]) -> None: + # Give the TLS/TCP response a brief window to leave the interface before a + # possible wgnode0 restart removes and recreates the transport address. + time.sleep(0.25) + _finish_deferred_sync(previous_peer) + + +def public_leave(node_id: str, secret: str) -> dict[str, Any]: + """Remove a spoke from the HUB using its node-scoped secret.""" + with _lock: + state = _load_state() + if str(state.get("mode") or "") != "hub": + raise ValueError("This WGTools instance is not operating as a HUB") + peer = _peer_by_id(node_id) + if not peer or not secrets.compare_digest(str(peer.get("secret") or ""), str(secret or "")): + raise PermissionError("Invalid WGTools Node credentials") + with _connect() as conn: + conn.execute("DELETE FROM wg_node_peers WHERE node_id=?", (node_id,)) + try: + _apply_config(state, _topology(state)) + except Exception: + _write_peer_record(peer) + raise + return {"ok": True} + + +def _require_tunnel_source(node_id: str, source_ip: str) -> None: + peer = _peer_by_id(node_id) + source = str(source_ip or "") + try: + parsed = ipaddress.ip_address(source) + if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped: + source = str(parsed.ipv4_mapped) + else: + source = str(parsed) + except ValueError: + pass + if not peer or str(peer.get("transport_ip") or "") != source: + raise PermissionError("WGTools Node service requests must arrive through the Node tunnel") + + +def _serve_control_client(raw: socket.socket, address: tuple[Any, ...], context: ssl.SSLContext) -> None: + """TLS wrapper that can return application errors after the handshake.""" + source_ip = str(address[0] if address else "") + try: + raw.settimeout(20) + tls = context.wrap_socket(raw, server_side=True) + except Exception: + try: + raw.close() + except Exception: + pass + return + try: + request = _recv_control_json(tls) + if request.get("protocol") != NODE_CONTROL_PROTOCOL: + raise ValueError("Unsupported WGTools Node control protocol") + action = str(request.get("action") or "") + if action == "join": + result = public_join(request) + try: + from .audit import write_audit + write_audit("system", "nodes.peer_joined", object=str(result.get("node_id") or request.get("node_name") or "node"), result="joined") + except Exception: + pass + elif action == "sync": + node_id = str(request.get("node_id") or "") + _require_tunnel_source(node_id, source_ip) + result = public_sync(node_id, str(request.get("node_secret") or ""), request, defer_apply=True) + elif action == "leave": + node_id = str(request.get("node_id") or "") + _require_tunnel_source(node_id, source_ip) + result = public_leave(node_id, str(request.get("node_secret") or "")) + try: + from .audit import write_audit + write_audit("system", "nodes.peer_left", object=node_id, result="left") + except Exception: + pass + elif action == "cancel_join": + # Used only when the spoke received pairing data but failed to + # create its local wgnode0. The node-scoped secret is already + # required, and TLS remains pinned to the join-code fingerprint. + node_id = str(request.get("node_id") or "") + result = public_leave(node_id, str(request.get("node_secret") or "")) + else: + raise ValueError("Unknown WGTools Node control action") + deferred_peer = result.pop("_deferred_previous_peer", None) if isinstance(result, dict) else None + _send_control_json(tls, result) + if deferred_peer: + threading.Thread(target=_finish_deferred_sync_later, args=(deferred_peer,), name="wgtools-node-apply", daemon=True).start() + except Exception as exc: + try: + payload = {"ok": False, "error": str(exc)[:500]} + error_code = str(getattr(exc, "code", "") or getattr(exc, "error_code", "")) + if error_code: + payload["error_code"] = error_code + conflicts = getattr(exc, "conflicts", None) + if isinstance(conflicts, list): + payload["conflicts"] = conflicts[:64] + _send_control_json(tls, payload) + except Exception: + pass + finally: + try: + tls.close() + except Exception: + pass + + +def _open_control_listener(port: int) -> socket.socket: + errors: list[str] = [] + for family, address in ((socket.AF_INET6, ("::", port)), (socket.AF_INET, ("0.0.0.0", port))): + listener = socket.socket(family, socket.SOCK_STREAM) + try: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if family == socket.AF_INET6: + listener.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) + listener.bind(address) + listener.listen(32) + listener.settimeout(1) + return listener + except OSError as exc: + errors.append(str(exc)) + listener.close() + raise RuntimeError(f"Could not listen on Nodes TCP port {port}: {'; '.join(errors)}") + + +def node_control_server_loop() -> None: + """Serve pairing on HUB TCP port; sync/leave use the same socket via wgnode0. + + Keep the worker alive across transient SQLite/certificate/socket failures so a + HUB can recover without restarting the whole WGTools web process. + """ + global _control_active_port, _control_last_error + while True: + try: + state = _load_state() + if str(state.get("mode") or "") != "hub": + with _control_status_lock: + _control_active_port = 0 + _control_last_error = "" + time.sleep(1) + continue + port = int(state.get("listen_port") or DEFAULT_LISTEN_PORT) + cert_file, key_file, _fingerprint = _ensure_control_certificate() + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(str(cert_file), str(key_file)) + with _open_control_listener(port) as listener: + with _control_status_lock: + _control_active_port = port + _control_last_error = "" + while True: + current = _load_state() + if str(current.get("mode") or "") != "hub" or int(current.get("listen_port") or DEFAULT_LISTEN_PORT) != port: + break + try: + raw, address = listener.accept() + except socket.timeout: + continue + threading.Thread(target=_serve_control_client, args=(raw, address, context), name="wgtools-node-control-client", daemon=True).start() + except Exception as exc: + with _control_status_lock: + _control_active_port = 0 + _control_last_error = str(exc)[:500] + time.sleep(2) + + +def _leave_hub_best_effort(state: dict[str, Any], *, public_fallback: bool = False) -> None: + if str(state.get("mode") or "") != "spoke": + return + node_id = str(state.get("node_id") or "") + secret = str(state.get("node_secret") or "") + fingerprint = str(state.get("hub_control_fingerprint") or "") + hub_transport_ip = str(state.get("hub_transport_ip") or "") + hub_endpoint_host = str(state.get("hub_endpoint_host") or "") + hub_endpoint_port = int(state.get("hub_endpoint_port") or DEFAULT_LISTEN_PORT) + if not node_id or not secret or not fingerprint: + return + request = {"action": "leave", "node_id": node_id, "node_secret": secret} + if hub_transport_ip: + try: + _control_json(hub_transport_ip, hub_endpoint_port, request, expected_fingerprint=fingerprint, timeout=8) + return + except Exception: + pass + if public_fallback and hub_endpoint_host: + try: + _control_json( + hub_endpoint_host, + hub_endpoint_port, + {"action": "cancel_join", "node_id": node_id, "node_secret": secret}, + expected_fingerprint=fingerprint, + timeout=8, + ) + except Exception: + pass + + +def connect_to_hub(payload: dict[str, Any]) -> dict[str, Any]: + with _lock: + state = _load_state() + current_mode = str(state.get("mode") or "none") + if current_mode == "hub": + raise ValueError("Disable HUB mode before connecting this WGTools instance to another HUB") + if current_mode == "spoke": + raise ValueError("Disconnect this WGTools instance from its current HUB before connecting to another HUB") + state = _ensure_identity(state) + node_name = _normalize_name(str(payload.get("node_name") or socket.gethostname()), socket.gethostname()) + hub_endpoint_host, hub_endpoint_port = _parse_endpoint(str(payload.get("hub_endpoint") or "")) + join_code = str(payload.get("join_code") or "").strip() + fingerprint = _join_code_fingerprint(join_code) + # Panel URL is deliberately not part of pairing. It is optional metadata + # configured separately in Node settings and survives reconnects. + panel_url = _normalize_panel_url(str(state.get("panel_url") or ""), allow_empty=True) + state.update({"node_name": node_name, "panel_url": panel_url}) + _apply_publication_payload(state, payload) + inventory = _interface_inventory() + direct_networks = _direct_private_networks(state, inventory=inventory) + available_networks = _available_publish_networks( + state, inventory=inventory, direct_networks=direct_networks + ) + exports = _local_exports(state, inventory=inventory, available_networks=available_networks) + summary = local_summary(state, inventory=inventory, exports=exports) + response = _control_json( + hub_endpoint_host, + hub_endpoint_port, + { + "action": "join", + "join_code": join_code, + "node_id": state.get("node_id"), + "node_name": node_name, + "public_key": state.get("public_key"), + "panel_url": panel_url, + "version": VERSION, + "exports": summary.get("exports") or [], + "clients": summary.get("clients") or [], + }, + expected_fingerprint=fingerprint, + timeout=15, + ) + hub = response.get("hub") if isinstance(response.get("hub"), dict) else {} + state.update({ + "mode": "spoke", + "node_id": response.get("node_id") or state.get("node_id"), + "transport_ip": response.get("transport_ip"), + "transport_network": response.get("transport_network") or DEFAULT_TRANSPORT_NETWORK, + "hub_node_id": hub.get("node_id"), + "hub_name": hub.get("name"), + "hub_public_key": hub.get("public_key"), + "hub_transport_ip": hub.get("transport_ip"), + "hub_endpoint_host": hub_endpoint_host, + "hub_endpoint_port": hub_endpoint_port, + "hub_panel_url": hub.get("panel_url") or "", + "hub_control_fingerprint": fingerprint, + "node_secret": response.get("node_secret"), + "preshared_key": response.get("preshared_key"), + "last_sync": int(time.time()), + "last_error": "", + }) + _remember_current_detection( + state, inventory=inventory, direct_networks=_direct_private_networks(state, inventory=inventory) + ) + # Remove the obsolete v0.20.29 web-control state if this installation + # was previously used for the prototype. + state.pop("hub_url", None) + state.pop("verify_tls", None) + _save_state(state) + topology = response.get("topology") if isinstance(response.get("topology"), dict) else {} + _save_cache({"topology": topology, "updated_at": int(time.time())}) + try: + _apply_config(state, topology) + except Exception as exc: + # Pairing already created the peer on the HUB. Revoke it through the + # pinned public control socket because a failed local wgnode0 cannot + # carry the normal in-tunnel leave request. + _leave_hub_best_effort(state, public_fallback=True) + preserved = { + "private_key": state.get("private_key"), + "public_key": state.get("public_key"), + "node_id": state.get("node_id"), + "panel_url": state.get("panel_url"), + } + _save_state({k: v for k, v in preserved.items() if v}) + with _connect() as conn: + conn.execute("DELETE FROM wg_node_cache") + _remove_config() + raise RuntimeError(str(exc)) from exc + return get_nodes_status() + + +def sync_spoke_once() -> dict[str, Any]: + with _lock: + state = _load_state() + if str(state.get("mode") or "") != "spoke": + return {"ok": True, "skipped": True} + secret = str(state.get("node_secret") or "") + node_id = str(state.get("node_id") or "") + hub_transport_ip = str(state.get("hub_transport_ip") or "") + fingerprint = str(state.get("hub_control_fingerprint") or "") + hub_port = int(state.get("hub_endpoint_port") or DEFAULT_LISTEN_PORT) + if not secret or not node_id or not hub_transport_ip or not fingerprint: + if state.get("hub_url") and not fingerprint: + raise RuntimeError("This Node connection uses the v0.20.29 prototype. Disconnect it and pair again with a new connection code.") + raise RuntimeError("WGTools Node connection state is incomplete") + summary = local_summary(state) + try: + response = _control_json( + hub_transport_ip, + hub_port, + { + "action": "sync", + "node_id": node_id, + "node_secret": secret, + "node_name": summary.get("name"), + "panel_url": summary.get("panel_url"), + "version": VERSION, + "exports": summary.get("exports") or [], + "clients": summary.get("clients") or [], + }, + expected_fingerprint=fingerprint, + timeout=12, + ) + topology = response.get("topology") if isinstance(response.get("topology"), dict) else {} + old_topology = _load_cache().get("topology") + if old_topology != topology: + # Apply first. If it fails, keep the old cache so the next sync + # retries instead of considering an unapplied topology current. + _apply_config(state, topology) + _save_cache({"topology": topology, "updated_at": int(time.time())}) + state["last_sync"] = int(time.time()) + state["last_error"] = "" + _save_state(state) + return {"ok": True, "topology": topology} + except Exception as exc: + state["last_error"] = str(exc)[:500] + _save_state(state) + raise + + +def reconcile_node() -> None: + with _lock: + state = _load_state() + if str(state.get("mode") or "") not in {"hub", "spoke"}: + return + try: + state = _ensure_identity(state) + if "publication_seen_networks" not in state: + _remember_current_detection(state) + _apply_config(state, _topology(state)) + state["last_error"] = "" + _save_state(state) + except Exception as exc: + state["last_error"] = str(exc)[:500] + _save_state(state) + + +def remove_peer(node_id: str) -> dict[str, Any]: + with _lock: + state = _load_state() + if str(state.get("mode") or "") != "hub": + raise ValueError("Only a HUB can remove connected nodes") + peer = _peer_by_id(node_id) + if not peer: + raise ValueError("WGTools Node was not found") + with _connect() as conn: + conn.execute("DELETE FROM wg_node_peers WHERE node_id=?", (node_id,)) + try: + _apply_config(state, _topology(state)) + except Exception: + _write_peer_record(peer) + raise + return get_nodes_status() + + +def disable_nodes() -> dict[str, Any]: + with _lock: + state = _load_state() + mode = str(state.get("mode") or "none") + if mode == "none": + return get_nodes_status() + if mode == "hub": + with _connect() as conn: + conn.execute("DELETE FROM wg_node_peers") + conn.execute("DELETE FROM wg_node_join_codes") + elif mode == "spoke": + _leave_hub_best_effort(state) + with _connect() as conn: + conn.execute("DELETE FROM wg_node_cache") + preserved = {"private_key": state.get("private_key"), "public_key": state.get("public_key"), "node_id": state.get("node_id")} + _save_state({k: v for k, v in preserved.items() if v}) + _remove_config() + return get_nodes_status() + + +def get_nodes_status() -> dict[str, Any]: + state = _load_state() + mode = str(state.get("mode") or "none") + configured = mode in {"hub", "spoke"} + + # One status request must collect local WG/network discovery only once. + # Prior to v0.20.38 the same helpers were invoked repeatedly through + # local_summary -> topology -> exports -> available_networks, which made + # even a local HUB tab wait on several duplicate privileged subprocesses. + inventory = _interface_inventory() + direct_networks = _direct_private_networks(state, inventory=inventory) + detected_networks = _available_publish_networks( + state, + inventory=inventory, + direct_networks=direct_networks, + include_remembered=False, + ) + available_networks = _available_publish_networks( + state, + inventory=inventory, + direct_networks=direct_networks, + ) + local_exports = _local_exports( + state, + inventory=inventory, + available_networks=available_networks, + ) if configured else [] + # The status page does not render this node's client inventory. Remote + # Nodes receive that inventory through the background/pairing sync paths, + # where local_summary() still performs fresh snapshots. Avoiding snapshots + # here keeps opening Server -> Nodes responsive even with many WG peers. + local = local_summary( + state, + inventory=inventory, + exports=local_exports, + clients=[], + ) if configured else None + + service_active = False + if configured: + service_active = subprocess.run( + ["systemctl", "is-active", "--quiet", f"wg-quick@{NODE_INTERFACE}.service"], + check=False, + ).returncode == 0 + + topology = _topology(state, local=local) + own_id = str(state.get("node_id") or "") + remote_nodes: list[dict[str, Any]] = [] + now = int(time.time()) + spoke_runtime = _node_runtime() if mode == "spoke" else {} + for node in topology.get("nodes") or []: + if str(node.get("node_id") or "") == own_id: + continue + clients = node.get("clients") if isinstance(node.get("clients"), list) else [] + online_clients = sum(1 for item in clients if item.get("online")) + latest = int(node.get("last_seen") or 0) + node_online = bool(node.get("online", latest and now - latest <= max(45, SYNC_INTERVAL_SECONDS * 4))) + # A spoke has a direct WG peer only to its HUB, so use its own runtime + # handshake for that row instead of treating control sync as tunnel health. + if mode == "spoke" and str(node.get("node_id") or "") == str(state.get("hub_node_id") or ""): + rt = spoke_runtime.get(str(state.get("hub_public_key") or ""), {}) + handshake = int(rt.get("latest_handshake") or 0) + node_online = bool(handshake and now - handshake <= max(45, SYNC_INTERVAL_SECONDS * 4)) + node = {**node, "last_handshake": handshake, "tunnel_online": node_online} + remote_nodes.append({ + **node, + "client_count": len(clients), + "online_clients": online_clients, + "online": node_online, + }) + if local is not None: + local["service_active"] = service_active + local["last_error"] = str(state.get("last_error") or "") + current_automatic = [item.get("network") for item in _automatic_exports(inventory) if item.get("network")] + current_direct = [item.get("network") for item in direct_networks if item.get("network")] + current_detected = [item.get("network") for item in detected_networks if item.get("network")] + network_changes = _network_detection_changes( + state, + automatic_networks=current_automatic, + direct_networks=current_direct, + detected_networks=current_detected, + ) + vpn_pool_mismatch = _vpn_pool_publication_mismatch( + state, inventory=inventory, direct_networks=direct_networks + ) + + with _control_status_lock: + control_active = bool(mode == "hub" and _control_active_port == int(state.get("listen_port") or DEFAULT_LISTEN_PORT)) + control_error = str(_control_last_error or "") + return { + "ok": True, + "mode": mode, + "interface": NODE_INTERFACE, + "service_active": service_active, + "local": local, + "nodes": remote_nodes, + "hub": { + "endpoint_host": "" if mode == "hub" else state.get("hub_endpoint_host"), + "endpoint_port": state.get("listen_port") if mode == "hub" else state.get("hub_endpoint_port"), + "transport_network": state.get("transport_network") or DEFAULT_TRANSPORT_NETWORK, + "transport_ip": state.get("transport_ip") or "", + "hub_name": (state.get("node_name") or "") if mode == "hub" else (state.get("hub_name") or ""), + }, + "control_active": control_active, + "control_error": control_error, + "last_sync": int(state.get("last_sync") or 0), + "last_error": str(state.get("last_error") or ""), + "extra_networks": list(state.get("extra_networks") or []), + "published_networks": [item.get("network") for item in local_exports], + "available_networks": available_networks, + "detected_networks": detected_networks, + "network_changes": network_changes, + "vpn_pool_mismatch": vpn_pool_mismatch, + "topology_generated_at": int(topology.get("generated_at") or 0), + } + + +def node_details(node_id: str) -> dict[str, Any]: + status = get_nodes_status() + for node in status.get("nodes") or []: + if str(node.get("node_id") or "") == str(node_id or ""): + return {"ok": True, "node": node} + raise ValueError("WGTools Node was not found") diff --git a/app/core/password_reset.py b/app/core/password_reset.py new file mode 100644 index 0000000..89f979a --- /dev/null +++ b/app/core/password_reset.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +import base64 +import hashlib +import hmac +import secrets +import sqlite3 +import time +from pathlib import Path +from typing import Any + +from .auth import find_user_by_identifier, get_user, init_database, set_password +from .mail_config import mask_email, password_recovery_available, send_password_reset_email +from .settings import DATABASE_PATH + +RESET_TTL_SECONDS = 15 * 60 +RESET_ATTEMPTS = 5 +RESET_COOLDOWN_SECONDS = 60 +PUBLIC_IP_LIMIT = 10 +PUBLIC_IDENTIFIER_LIMIT = 5 +RATE_WINDOW_SECONDS = 15 * 60 +RESET_PBKDF2_ITERATIONS = 120_000 + + +def _connect() -> sqlite3.Connection: + Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA foreign_keys=ON") + return conn + + +def init_password_reset_database() -> None: + # The reset table has a foreign key to users. Keep this initializer safe even + # when it is called independently from the normal application startup order. + init_database() + with _connect() as conn: + conn.executescript( + """ + CREATE TABLE IF NOT EXISTS password_reset_codes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + code_hash TEXT NOT NULL, + salt TEXT NOT NULL, + iterations INTEGER NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + attempts_remaining INTEGER NOT NULL, + consumed_at INTEGER NOT NULL DEFAULT 0, + request_ip TEXT NOT NULL DEFAULT '', + FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE + ); + CREATE INDEX IF NOT EXISTS idx_password_reset_user + ON password_reset_codes(user_id, created_at DESC); + CREATE TABLE IF NOT EXISTS auth_rate_limits ( + rate_key TEXT PRIMARY KEY, + window_started INTEGER NOT NULL, + count INTEGER NOT NULL + ); + """ + ) + now = int(time.time()) + conn.execute("DELETE FROM password_reset_codes WHERE created_at str: + digest = hashlib.pbkdf2_hmac("sha256", code.encode("ascii"), salt, iterations) + return base64.b64encode(digest).decode("ascii") + + +def _rate_key(prefix: str, value: str) -> str: + digest = hashlib.sha256(str(value or "").strip().lower().encode("utf-8")).hexdigest() + return f"{prefix}:{digest}" + + +def _allow_rate(rate_key: str, limit: int, window_seconds: int, now: int) -> bool: + init_password_reset_database() + with _connect() as conn: + # Serialize increments so simultaneous public requests cannot all observe + # the same counter and slip past the limit. + conn.execute("BEGIN IMMEDIATE") + row = conn.execute( + "SELECT window_started,count FROM auth_rate_limits WHERE rate_key=?", + (rate_key,), + ).fetchone() + if not row or now - int(row["window_started"]) >= window_seconds: + conn.execute( + """ + INSERT INTO auth_rate_limits(rate_key,window_started,count) VALUES(?,?,1) + ON CONFLICT(rate_key) DO UPDATE SET window_started=excluded.window_started,count=1 + """, + (rate_key, now), + ) + return True + count = int(row["count"] or 0) + if count >= limit: + return False + conn.execute("UPDATE auth_rate_limits SET count=count+1 WHERE rate_key=?", (rate_key,)) + return True + + +def public_reset_request_allowed(identifier: str, request_ip: str) -> bool: + now = int(time.time()) + ip_ok = _allow_rate(_rate_key("reset-ip", request_ip or "unknown"), PUBLIC_IP_LIMIT, RATE_WINDOW_SECONDS, now) + identifier_ok = _allow_rate(_rate_key("reset-id", identifier), PUBLIC_IDENTIFIER_LIMIT, RATE_WINDOW_SECONDS, now) + return ip_ok and identifier_ok + + +def issue_password_reset(user_id: int, *, request_ip: str = "", language: str = "en") -> dict[str, Any]: + init_password_reset_database() + if not password_recovery_available(): + raise RuntimeError("Password recovery mail is not configured") + user = get_user(user_id) + if not user: + raise ValueError("User not found") + email = str(user.get("email") or "").strip() + if not email: + raise ValueError("User does not have an email address") + + now = int(time.time()) + code = f"{secrets.randbelow(1_000_000):06d}" + salt = secrets.token_bytes(18) + encoded_salt = base64.b64encode(salt).decode("ascii") + code_hash = _hash_code(code, salt) + with _connect() as conn: + conn.execute("BEGIN IMMEDIATE") + latest = conn.execute( + """ + SELECT created_at FROM password_reset_codes + WHERE user_id=? AND consumed_at=0 + ORDER BY created_at DESC LIMIT 1 + """, + (int(user_id),), + ).fetchone() + if latest and now - int(latest["created_at"] or 0) < RESET_COOLDOWN_SECONDS: + raise RuntimeError("A reset code was sent recently. Please wait before requesting another one") + conn.execute("UPDATE password_reset_codes SET consumed_at=? WHERE user_id=? AND consumed_at=0", (now, int(user_id))) + cur = conn.execute( + """ + INSERT INTO password_reset_codes( + user_id,code_hash,salt,iterations,created_at,expires_at, + attempts_remaining,consumed_at,request_ip + ) VALUES(?,?,?,?,?,?,?,?,?) + """, + ( + int(user_id), + code_hash, + encoded_salt, + RESET_PBKDF2_ITERATIONS, + now, + now + RESET_TTL_SECONDS, + RESET_ATTEMPTS, + 0, + str(request_ip or "")[:120], + ), + ) + reset_id = int(cur.lastrowid) + + try: + send_password_reset_email(email, code, valid_minutes=RESET_TTL_SECONDS // 60, language=language) + except Exception: + with _connect() as conn: + conn.execute("UPDATE password_reset_codes SET consumed_at=? WHERE id=?", (int(time.time()), reset_id)) + raise + return { + "ok": True, + "user_id": int(user_id), + "username": str(user.get("username") or ""), + "masked_email": mask_email(email), + "expires_in": RESET_TTL_SECONDS, + } + + +def request_password_reset(identifier: str, *, request_ip: str = "", rate_checked: bool = False, language: str = "en") -> dict[str, Any]: + identifier = str(identifier or "").strip() + if not identifier: + return {"ok": True, "delivered": False, "reason": "empty"} + if not rate_checked and not public_reset_request_allowed(identifier, request_ip): + return {"ok": True, "delivered": False, "reason": "rate_limited"} + user = find_user_by_identifier(identifier) + if not user or not str(user.get("email") or "").strip() or not password_recovery_available(): + return {"ok": True, "delivered": False, "reason": "unavailable"} + try: + result = issue_password_reset(int(user["id"]), request_ip=request_ip, language=language) + result["delivered"] = True + return result + except RuntimeError as exc: + if "sent recently" in str(exc): + return {"ok": True, "delivered": False, "reason": "cooldown", "user_id": int(user["id"]), "username": str(user["username"])} + raise + + +def confirm_password_reset(identifier: str, code: str, password: str) -> dict[str, Any]: + init_password_reset_database() + if len(str(password or "")) < 8: + raise ValueError("Password must contain at least 8 characters") + user = find_user_by_identifier(str(identifier or "").strip()) + code = str(code or "").strip() + if not user or not (len(code) == 6 and code.isdigit()): + # Keep a small amount of work on the unknown-user path. + hashlib.pbkdf2_hmac("sha256", code.encode("utf-8"), b"wgtools-reset-invalid", RESET_PBKDF2_ITERATIONS) + raise ValueError("Invalid or expired reset code") + + now = int(time.time()) + with _connect() as conn: + conn.execute("BEGIN IMMEDIATE") + row = conn.execute( + """ + SELECT * FROM password_reset_codes + WHERE user_id=? AND consumed_at=0 + ORDER BY created_at DESC LIMIT 1 + """, + (int(user["id"]),), + ).fetchone() + if not row or int(row["expires_at"] or 0) < now or int(row["attempts_remaining"] or 0) <= 0: + if row: + conn.execute("UPDATE password_reset_codes SET consumed_at=? WHERE id=?", (now, int(row["id"]))) + conn.commit() + raise ValueError("Invalid or expired reset code") + salt = base64.b64decode(str(row["salt"])) + candidate = _hash_code(code, salt, int(row["iterations"])) + if not hmac.compare_digest(candidate, str(row["code_hash"])): + remaining = max(0, int(row["attempts_remaining"]) - 1) + conn.execute( + "UPDATE password_reset_codes SET attempts_remaining=?,consumed_at=? WHERE id=?", + (remaining, now if remaining <= 0 else 0, int(row["id"])), + ) + conn.commit() + raise ValueError("Invalid or expired reset code") + conn.execute("UPDATE password_reset_codes SET consumed_at=? WHERE id=?", (now, int(row["id"]))) + + set_password(int(user["id"]), password) + return { + "ok": True, + "user_id": int(user["id"]), + "username": str(user.get("username") or ""), + "masked_email": mask_email(str(user.get("email") or "")), + } diff --git a/app/core/preferences.py b/app/core/preferences.py new file mode 100644 index 0000000..22d1e7d --- /dev/null +++ b/app/core/preferences.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +import sqlite3 +import time +import re +import base64 +from pathlib import Path +from typing import Any + +from .settings import DATABASE_PATH, ONLINE_THRESHOLD_SECONDS, REFRESH_SECONDS + +DEFAULT_BACKUP_RETENTION = 20 + + +def get_branding() -> dict[str, Any]: + return {"name": _get("brand_name", "WGTools-Extended"), + "color": _get("brand_color", "#8f1f27"), + "logo": _get("brand_logo", "")} + + +def update_branding(name: str, color: str, logo: str) -> dict[str, Any]: + name = name.strip() + if len(name) > 80 or any(ord(c) < 32 for c in name): + raise ValueError("Nieprawidłowa nazwa marki") + if not re.fullmatch(r"#[0-9a-fA-F]{6}", color): + raise ValueError("Nieprawidłowy kolor") + if logo: + prefix = "data:image/png;base64," + if not logo.startswith(prefix) or len(logo) > 400000: + raise ValueError("Logo musi być plikiem PNG o rozmiarze do 300 KB") + try: + raw = base64.b64decode(logo[len(prefix):], validate=True) + except ValueError as exc: + raise ValueError("Nieprawidłowy plik logo") from exc + if not raw.startswith(b"\x89PNG\r\n\x1a\n"): + raise ValueError("Logo musi być plikiem PNG") + _set("brand_name", name) + _set("brand_color", color) + _set("brand_logo", logo) + return get_branding() + + +def _connect() -> sqlite3.Connection: + Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + return conn + + +def init_preferences() -> None: + with _connect() as conn: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS app_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at INTEGER NOT NULL + ) + """ + ) + + +def _get(key: str, default: str) -> str: + init_preferences() + with _connect() as conn: + row = conn.execute("SELECT value FROM app_settings WHERE key=?", (key,)).fetchone() + return str(row["value"]) if row else default + + +def _set(key: str, value: str) -> None: + init_preferences() + with _connect() as conn: + conn.execute( + """ + INSERT INTO app_settings(key,value,updated_at) VALUES(?,?,?) + ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at + """, + (key, value, int(time.time())), + ) + + +def get_preferences() -> dict[str, Any]: + refresh = int(_get("refresh_seconds", str(REFRESH_SECONDS))) + threshold = int(_get("online_threshold_seconds", str(ONLINE_THRESHOLD_SECONDS))) + retention = int(_get("backup_retention", str(DEFAULT_BACKUP_RETENTION))) + return { + "refresh_seconds": max(2, min(refresh, 60)), + "online_threshold_seconds": max(30, min(threshold, 3600)), + "backup_retention": max(1, min(retention, 200)), + } + + +def update_preferences(*, refresh_seconds: int, online_threshold_seconds: int, backup_retention: int) -> dict[str, Any]: + if not 2 <= int(refresh_seconds) <= 60: + raise ValueError("Refresh interval must be between 2 and 60 seconds") + if not 30 <= int(online_threshold_seconds) <= 3600: + raise ValueError("Online threshold must be between 30 and 3600 seconds") + if not 1 <= int(backup_retention) <= 200: + raise ValueError("Backup retention must be between 1 and 200") + _set("refresh_seconds", str(int(refresh_seconds))) + _set("online_threshold_seconds", str(int(online_threshold_seconds))) + _set("backup_retention", str(int(backup_retention))) + return get_preferences() diff --git a/app/core/settings.py b/app/core/settings.py new file mode 100644 index 0000000..f51d92a --- /dev/null +++ b/app/core/settings.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +import os +from pathlib import Path + +APP_NAME = "WGTools-Extended" +VERSION = Path(__file__).resolve().parents[2].joinpath("VERSION").read_text().strip() +WG_INTERFACE = os.getenv("WGTOOLS_INTERFACE", "wg0") +HELPER_PATH = os.getenv("WGTOOLS_HELPER", "/usr/local/libexec/wgtools-helper") +REFRESH_SECONDS = int(os.getenv("WGTOOLS_REFRESH_SECONDS", "5")) +ONLINE_THRESHOLD_SECONDS = int(os.getenv("WGTOOLS_ONLINE_THRESHOLD_SECONDS", "180")) +DATABASE_PATH = os.getenv("WGTOOLS_DATABASE", "/var/lib/wgtools/wgtools.db") +SESSION_KEY_FILE = os.getenv("WGTOOLS_SESSION_KEY_FILE", "/var/lib/wgtools/session.key") +SESSION_MAX_AGE_SECONDS = int(os.getenv("WGTOOLS_SESSION_MAX_AGE_SECONDS", str(30 * 24 * 60 * 60))) diff --git a/app/core/telegram_config.py b/app/core/telegram_config.py new file mode 100644 index 0000000..b13ef46 --- /dev/null +++ b/app/core/telegram_config.py @@ -0,0 +1,305 @@ +from __future__ import annotations + +import ipaddress +import json +import re +import sqlite3 +import time +import urllib.error +import urllib.request +from pathlib import Path +from typing import Any + +from .settings import DATABASE_PATH + +TOKEN_RE = re.compile(r"^\d+:[A-Za-z0-9_-]{20,}$") + + +def _connect() -> sqlite3.Connection: + Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + return conn + + +def init_telegram_settings() -> None: + with _connect() as conn: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS telegram_settings ( + id INTEGER PRIMARY KEY CHECK(id=1), + enabled INTEGER NOT NULL DEFAULT 0, + bot_token TEXT NOT NULL DEFAULT '', + allowed_user_ids TEXT NOT NULL DEFAULT '[]', + default_endpoint TEXT NOT NULL DEFAULT '', + default_dns TEXT NOT NULL DEFAULT '[]', + language TEXT NOT NULL DEFAULT 'auto', + bot_username TEXT NOT NULL DEFAULT '', + last_error TEXT NOT NULL DEFAULT '', + last_poll_at INTEGER NOT NULL DEFAULT 0, + update_offset INTEGER NOT NULL DEFAULT 0, + updated_at INTEGER NOT NULL DEFAULT 0 + ) + """ + ) + conn.execute( + """ + INSERT OR IGNORE INTO telegram_settings( + id, enabled, bot_token, allowed_user_ids, default_endpoint, + default_dns, language, bot_username, last_error, last_poll_at, + update_offset, updated_at + ) VALUES(1,0,'','[]','','[]','auto','','',0,0,0) + """ + ) + + +def _row() -> sqlite3.Row: + init_telegram_settings() + with _connect() as conn: + row = conn.execute("SELECT * FROM telegram_settings WHERE id=1").fetchone() + if row is None: + raise RuntimeError("Telegram settings row is missing") + return row + + +def _loads_list(value: str) -> list[Any]: + try: + data = json.loads(value) + return data if isinstance(data, list) else [] + except Exception: + return [] + + +def mask_token(token: str) -> str: + if not token: + return "" + prefix = token.split(":", 1)[0] + return f"{prefix}:••••••••••••" + + +def get_telegram_settings(*, include_token: bool = False) -> dict[str, Any]: + row = _row() + ids: list[int] = [] + for item in _loads_list(str(row["allowed_user_ids"])): + try: + value = int(item) + except (TypeError, ValueError): + continue + if value > 0 and value not in ids: + ids.append(value) + dns = [str(x) for x in _loads_list(str(row["default_dns"])) if str(x).strip()] + token = str(row["bot_token"] or "") + result = { + "enabled": bool(row["enabled"]), + "token_configured": bool(token), + "token_masked": mask_token(token), + "allowed_user_ids": ids, + "default_endpoint": str(row["default_endpoint"] or ""), + "default_dns": dns, + "language": str(row["language"] or "auto"), + "bot_username": str(row["bot_username"] or ""), + "last_error": str(row["last_error"] or ""), + "last_poll_at": int(row["last_poll_at"] or 0), + "update_offset": int(row["update_offset"] or 0), + "updated_at": int(row["updated_at"] or 0), + } + if include_token: + result["bot_token"] = token + return result + + +def _normalize_allowed_user_ids(values: Any) -> list[int]: + if values is None: + return [] + if isinstance(values, str): + raw_items = [x.strip() for x in re.split(r"[\s,;]+", values) if x.strip()] + elif isinstance(values, list): + raw_items = values + else: + raise ValueError("Allowed Telegram user IDs must be a list") + result: list[int] = [] + for raw in raw_items: + try: + value = int(raw) + except (TypeError, ValueError) as exc: + raise ValueError(f"Invalid Telegram user ID: {raw}") from exc + if value <= 0: + raise ValueError("Telegram user IDs must be positive numbers") + if value not in result: + result.append(value) + return result + + +def _normalize_dns(values: Any) -> list[str]: + if values is None: + return [] + if isinstance(values, str): + raw_items = [x.strip() for x in re.split(r"[\s,;]+", values) if x.strip()] + elif isinstance(values, list): + raw_items = [str(x).strip() for x in values if str(x).strip()] + else: + raise ValueError("Default DNS must be a list of IPv4 addresses") + result: list[str] = [] + for raw in raw_items: + try: + ip = ipaddress.ip_address(raw) + except ValueError as exc: + raise ValueError(f"Invalid DNS address: {raw}") from exc + if ip.version != 4: + raise ValueError("Only IPv4 DNS addresses are supported") + text = str(ip) + if text not in result: + result.append(text) + return result + + +def _normalize_endpoint(value: str) -> str: + endpoint = str(value or "").strip() + if not endpoint: + return "" + if len(endpoint) > 253 or any(ch.isspace() for ch in endpoint): + raise ValueError("Server address/domain is invalid") + if "://" in endpoint or "/" in endpoint: + raise ValueError("Enter only the server IP address or domain, without protocol or path") + if ":" in endpoint: + raise ValueError("Do not include the WireGuard port here; WGTools reads it from the server configuration") + return endpoint + + +def update_telegram_settings( + *, + enabled: bool, + bot_token: str | None, + clear_token: bool, + allowed_user_ids: Any, + default_endpoint: str, + default_dns: Any, + language: str, +) -> dict[str, Any]: + current = get_telegram_settings(include_token=True) + token = str(current.get("bot_token") or "") + supplied = str(bot_token or "").strip() + if clear_token: + token = "" + elif supplied: + if not TOKEN_RE.fullmatch(supplied): + raise ValueError("Bot token does not look like a Telegram Bot API token") + token = supplied + + ids = _normalize_allowed_user_ids(allowed_user_ids) + dns = _normalize_dns(default_dns) + endpoint = _normalize_endpoint(default_endpoint) + language = str(language or "auto").strip().lower() + if language not in {"auto", "en", "ru"}: + raise ValueError("Bot language must be auto, en or ru") + if enabled and not token: + raise ValueError("Configure a BotFather token before enabling the Telegram bot") + + now = int(time.time()) + with _connect() as conn: + conn.execute( + """ + UPDATE telegram_settings SET + enabled=?, bot_token=?, allowed_user_ids=?, default_endpoint=?, + default_dns=?, language=?, updated_at=? + WHERE id=1 + """, + ( + 1 if enabled else 0, + token, + json.dumps(ids), + endpoint, + json.dumps(dns), + language, + now, + ), + ) + if supplied or clear_token: + conn.execute( + "UPDATE telegram_settings SET bot_username='', last_error='', last_poll_at=0, update_offset=0 WHERE id=1" + ) + return get_telegram_settings() + + +def update_telegram_runtime(*, bot_username: str | None = None, last_error: str | None = None, last_poll_at: int | None = None) -> None: + sets: list[str] = [] + values: list[Any] = [] + if bot_username is not None: + sets.append("bot_username=?") + values.append(str(bot_username)) + if last_error is not None: + sets.append("last_error=?") + values.append(str(last_error)[:1000]) + if last_poll_at is not None: + sets.append("last_poll_at=?") + values.append(int(last_poll_at)) + if not sets: + return + values.append(1) + with _connect() as conn: + conn.execute(f"UPDATE telegram_settings SET {', '.join(sets)} WHERE id=?", values) + + +def set_update_offset(offset: int) -> None: + with _connect() as conn: + conn.execute("UPDATE telegram_settings SET update_offset=? WHERE id=1", (max(0, int(offset)),)) + + +def set_default_endpoint(endpoint: str) -> None: + endpoint = _normalize_endpoint(endpoint) + with _connect() as conn: + conn.execute("UPDATE telegram_settings SET default_endpoint=?, updated_at=? WHERE id=1", (endpoint, int(time.time()))) + + +def telegram_api_call(token: str, method: str, payload: dict[str, Any] | None = None, *, timeout: float = 15.0) -> Any: + if not token: + raise RuntimeError("Telegram bot token is not configured") + url = f"https://api.telegram.org/bot{token}/{method}" + data = json.dumps(payload or {}).encode("utf-8") + req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json", "User-Agent": "WGTools/Telegram"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8", "replace") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace") + raise RuntimeError(f"Telegram HTTP {exc.code}: {detail[:500]}") from exc + except urllib.error.URLError as exc: + raise RuntimeError(f"Telegram connection failed: {exc.reason}") from exc + try: + result = json.loads(raw) + except json.JSONDecodeError as exc: + raise RuntimeError("Telegram returned invalid JSON") from exc + if not result.get("ok"): + raise RuntimeError(str(result.get("description") or "Telegram Bot API request failed")) + return result.get("result") + + +def test_telegram_connection() -> dict[str, Any]: + settings = get_telegram_settings(include_token=True) + token = str(settings.get("bot_token") or "") + try: + result = telegram_api_call(token, "getMe", {}, timeout=20) + except RuntimeError as exc: + last_poll_at = int(settings.get("last_poll_at") or 0) + if last_poll_at and time.time() - last_poll_at < 300: + text = str(exc).lower() + if "timed out" in text or "handshake" in text or "tls" in text: + return { + "ok": True, + "username": str(settings.get("bot_username") or ""), + "name": "", + "id": 0, + "verified_by_last_poll": True, + "last_poll_at": last_poll_at, + "warning": "The direct check timed out, but the bot is actively polling Telegram.", + } + raise + username = str((result or {}).get("username") or "") + update_telegram_runtime(bot_username=username, last_error="") + return { + "ok": True, + "username": username, + "name": str((result or {}).get("first_name") or ""), + "id": int((result or {}).get("id") or 0), + } diff --git a/app/core/vps.py b/app/core/vps.py new file mode 100644 index 0000000..ff79a0e --- /dev/null +++ b/app/core/vps.py @@ -0,0 +1,1262 @@ +from __future__ import annotations + +import contextlib +import ipaddress +import json +import os +import re +import secrets +import socket +import sqlite3 +import subprocess +import tempfile +import time +import uuid +from pathlib import Path +from typing import Any, Iterator + +from .settings import DATABASE_PATH + +_HOST_RE = re.compile(r"^[A-Za-z0-9._:-]+$") +RELAY_CONTROL_PORT = 8787 +RELAY_AGENT_SOURCE = Path(__file__).resolve().parents[2] / "relay" / "wgtools-relay-agent.py" +RELAY_AGENT_UNIT_SOURCE = Path(__file__).resolve().parents[2] / "relay" / "wgtools-relay-agent.service" +LOCAL_RELAY_DIR = Path(DATABASE_PATH).parent / "relay" + + +PUBLIC_COLUMNS = """id,name,host,ssh_port,ssh_user,endpoint_domain,relay_port, +transport_port,os_id,os_name,os_version,architecture,privilege_mode,status, +agent_id,tenant_id,controller_id,transport_interface,home_transport_ip, +relay_transport_ip,control_port,published_interface,home_wg_port,installed_at, +last_health,last_error,host_key_fingerprint,created_at,updated_at""" + + +def _connect_db() -> sqlite3.Connection: + Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA foreign_keys=ON") + return conn + + +def _ensure_columns(conn: sqlite3.Connection, table: str, definitions: dict[str, str]) -> None: + existing = {str(row[1]) for row in conn.execute(f"PRAGMA table_info({table})").fetchall()} + for name, definition in definitions.items(): + if name not in existing: + conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {definition}") + + +def init_vps_database() -> None: + with _connect_db() as conn: + conn.executescript( + """ + CREATE TABLE IF NOT EXISTS vps_relays ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + host TEXT NOT NULL, + ssh_port INTEGER NOT NULL, + ssh_user TEXT NOT NULL, + endpoint_domain TEXT NOT NULL DEFAULT '', + relay_port INTEGER NOT NULL, + transport_port INTEGER NOT NULL, + os_id TEXT NOT NULL DEFAULT '', + os_name TEXT NOT NULL DEFAULT '', + os_version TEXT NOT NULL DEFAULT '', + architecture TEXT NOT NULL DEFAULT '', + privilege_mode TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'candidate', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS vps_controller_identity ( + id TEXT PRIMARY KEY, + created_at INTEGER NOT NULL + ); + """ + ) + _ensure_columns( + conn, + "vps_relays", + { + "agent_id": "TEXT NOT NULL DEFAULT ''", + "tenant_id": "TEXT NOT NULL DEFAULT ''", + "controller_id": "TEXT NOT NULL DEFAULT ''", + "control_token": "TEXT NOT NULL DEFAULT ''", + "transport_interface": "TEXT NOT NULL DEFAULT ''", + "home_transport_ip": "TEXT NOT NULL DEFAULT ''", + "relay_transport_ip": "TEXT NOT NULL DEFAULT ''", + "control_port": f"INTEGER NOT NULL DEFAULT {RELAY_CONTROL_PORT}", + "published_interface": "TEXT NOT NULL DEFAULT ''", + "home_wg_port": "INTEGER NOT NULL DEFAULT 0", + "home_transport_private_key": "TEXT NOT NULL DEFAULT ''", + "relay_transport_public_key": "TEXT NOT NULL DEFAULT ''", + "installed_at": "INTEGER NOT NULL DEFAULT 0", + "last_health": "INTEGER NOT NULL DEFAULT 0", + "last_error": "TEXT NOT NULL DEFAULT ''", + "host_key_fingerprint": "TEXT NOT NULL DEFAULT ''", + }, + ) + + +def controller_id() -> str: + init_vps_database() + with _connect_db() as conn: + row = conn.execute("SELECT id FROM vps_controller_identity ORDER BY created_at LIMIT 1").fetchone() + if row: + return str(row["id"]) + value = uuid.uuid4().hex + conn.execute("INSERT INTO vps_controller_identity(id,created_at) VALUES(?,?)", (value, int(time.time()))) + return value + + +def list_vps() -> list[dict[str, Any]]: + init_vps_database() + with _connect_db() as conn: + rows = conn.execute(f"SELECT {PUBLIC_COLUMNS} FROM vps_relays WHERE status!='detached' ORDER BY created_at,id").fetchall() + return [dict(row) for row in rows] + + +def get_vps(vps_id: str, *, include_secrets: bool = False) -> dict[str, Any] | None: + init_vps_database() + columns = PUBLIC_COLUMNS + if include_secrets: + columns += ",control_token,home_transport_private_key,relay_transport_public_key" + with _connect_db() as conn: + row = conn.execute(f"SELECT {columns} FROM vps_relays WHERE id=?", (vps_id,)).fetchone() + return dict(row) if row else None + + +def save_vps_candidate(payload: dict[str, Any], preflight: dict[str, Any]) -> dict[str, Any]: + init_vps_database() + now = int(time.time()) + vps_id = str(payload.get("id") or preflight.get("reconnect_vps_id") or uuid.uuid4().hex) + name = str(payload.get("name") or "").strip() + host = str(payload.get("host") or "").strip() + ssh_user = str(payload.get("ssh_user") or "").strip() + endpoint_domain = str(payload.get("endpoint_domain") or "").strip() + ssh_port = int(payload.get("ssh_port") or 22) + # Preflight may move ports when an existing multi-tenant Relay Agent already + # owns the user's initial suggestion. Persist the verified suggestions. + relay_port = int(preflight.get("relay_port") or payload.get("relay_port") or 51820) + transport_port = int(preflight.get("transport_port") or payload.get("transport_port") or 51900) + if not name: + raise ValueError("VPS name is required") + with _connect_db() as conn: + existing = conn.execute("SELECT created_at,status FROM vps_relays WHERE id=?", (vps_id,)).fetchone() + created_at = int(existing["created_at"]) if existing else now + current_status = str(existing["status"]) if existing else "candidate" + if current_status == "installed": + raise ValueError("Installed Relay settings must be changed through Relay management") + target_status = "detached" if current_status == "detached" and preflight.get("reconnect_available") else "candidate" + conn.execute( + """INSERT INTO vps_relays( + id,name,host,ssh_port,ssh_user,endpoint_domain,relay_port,transport_port, + os_id,os_name,os_version,architecture,privilege_mode,status, + host_key_fingerprint,created_at,updated_at + ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + ON CONFLICT(id) DO UPDATE SET + name=excluded.name,host=excluded.host,ssh_port=excluded.ssh_port, + ssh_user=excluded.ssh_user,endpoint_domain=excluded.endpoint_domain, + relay_port=excluded.relay_port,transport_port=excluded.transport_port, + os_id=excluded.os_id,os_name=excluded.os_name,os_version=excluded.os_version, + architecture=excluded.architecture,privilege_mode=excluded.privilege_mode, + status=excluded.status,host_key_fingerprint=excluded.host_key_fingerprint, + updated_at=excluded.updated_at""", + ( + vps_id, name, host, ssh_port, ssh_user, endpoint_domain, relay_port, transport_port, + str(preflight.get("os_id") or ""), str(preflight.get("os_name") or ""), + str(preflight.get("os_version") or ""), str(preflight.get("architecture") or ""), + str(preflight.get("privilege_mode") or ""), target_status, + str(preflight.get("host_key_fingerprint") or ""), created_at, now, + ), + ) + return get_vps(vps_id) or {"id": vps_id} + + +def delete_vps_candidate(vps_id: str) -> None: + init_vps_database() + with _connect_db() as conn: + row = conn.execute("SELECT status FROM vps_relays WHERE id=?", (vps_id,)).fetchone() + if not row: + raise ValueError("VPS entry not found") + if str(row["status"]) != "candidate": + raise ValueError("Only a VPS candidate can be removed") + conn.execute("DELETE FROM vps_relays WHERE id=?", (vps_id,)) + + +def _validate_common(payload: dict[str, Any]) -> dict[str, Any]: + host = str(payload.get("host") or "").strip() + username = str(payload.get("ssh_user") or "").strip() + auth_method = str(payload.get("auth_method") or "password").strip().lower() + password = str(payload.get("password") or "") + private_key = str(payload.get("private_key") or "") + key_passphrase = str(payload.get("key_passphrase") or "") + try: + ssh_port = int(payload.get("ssh_port") or 22) + relay_port = int(payload.get("relay_port") or 51820) + transport_port = int(payload.get("transport_port") or 51900) + except (TypeError, ValueError) as exc: + raise ValueError("SSH and UDP ports must be numbers") from exc + if not host or len(host) > 255 or any(ch.isspace() for ch in host) or not _HOST_RE.fullmatch(host): + raise ValueError("VPS IP/hostname is invalid") + if not username or len(username) > 64 or any(ord(ch) < 33 for ch in username): + raise ValueError("SSH username is invalid") + for label, port in (("SSH", ssh_port), ("Relay", relay_port), ("Transport", transport_port)): + if not 1 <= port <= 65535: + raise ValueError(f"{label} port must be between 1 and 65535") + if relay_port == transport_port: + raise ValueError("Relay and transport UDP ports must be different") + if auth_method not in {"password", "key"}: + raise ValueError("SSH authentication method is invalid") + if auth_method == "password" and not password: + raise ValueError("SSH password is required") + if auth_method == "key" and not private_key.strip(): + raise ValueError("SSH private key is required") + return { + "host": host, "ssh_user": username, "auth_method": auth_method, + "password": password, "private_key": private_key, "key_passphrase": key_passphrase, + "ssh_port": ssh_port, "relay_port": relay_port, "transport_port": transport_port, + } + + +def _parse_os_release(raw: str) -> dict[str, str]: + result: dict[str, str] = {} + for line in raw.splitlines(): + if "=" not in line: + continue + key, value = line.split("=", 1) + result[key.strip()] = value.strip().strip('"').strip("'") + return result + + +def _run(cmd: list[str], *, input_text: str = "", env: dict[str, str] | None = None, timeout: int = 18) -> subprocess.CompletedProcess[str]: + try: + return subprocess.run( + cmd, input=input_text or None, text=True, capture_output=True, check=False, + env=env, timeout=timeout, + ) + except subprocess.TimeoutExpired as exc: + raise ValueError("Operation timed out") from exc + + +def shutil_which(command: str) -> str | None: + for directory in os.environ.get("PATH", "").split(os.pathsep): + path = os.path.join(directory, command) + if os.path.isfile(path) and os.access(path, os.X_OK): + return path + return None + + +def _ssh_base(cfg: dict[str, Any], known_hosts: str, key_path: str = "") -> tuple[list[str], dict[str, str]]: + env = os.environ.copy() + cmd: list[str] = [] + if cfg["auth_method"] == "password": + if not shutil_which("sshpass"): + raise ValueError("sshpass is not installed on the WGTools server") + env["SSHPASS"] = cfg["password"] + cmd += ["sshpass", "-e"] + cmd += [ + "ssh", "-p", str(cfg["ssh_port"]), + "-o", "ConnectTimeout=10", "-o", "ConnectionAttempts=1", + "-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=1", + "-o", f"UserKnownHostsFile={known_hosts}", "-o", "StrictHostKeyChecking=accept-new", + "-o", "LogLevel=ERROR", + ] + if cfg["auth_method"] == "password": + cmd += ["-o", "PreferredAuthentications=password,keyboard-interactive", "-o", "PubkeyAuthentication=no"] + else: + cmd += ["-o", "BatchMode=yes", "-i", key_path, "-o", "IdentitiesOnly=yes"] + cmd += [f"{cfg['ssh_user']}@{cfg['host']}"] + return cmd, env + + +def _ssh_exec( + cfg: dict[str, Any], command: str, known_hosts: str, key_path: str = "", *, + stdin_text: str = "", timeout: int = 18, +) -> tuple[int, str, str]: + base, env = _ssh_base(cfg, known_hosts, key_path) + proc = _run(base + [command], input_text=stdin_text, env=env, timeout=timeout) + return proc.returncode, proc.stdout.strip(), proc.stderr.strip() + + +def _root_exec( + cfg: dict[str, Any], command: str, known_hosts: str, key_path: str, privilege_mode: str, *, + stdin_text: str = "", timeout: int = 30, +) -> tuple[int, str, str]: + if privilege_mode == "root": + remote = command + data = stdin_text + elif privilege_mode == "sudo-nopasswd": + remote = f"sudo -n {command}" + data = stdin_text + elif privilege_mode == "sudo-password": + remote = f"sudo -S -p '' {command}" + data = cfg["password"] + "\n" + stdin_text + else: + raise ValueError("Remote root privileges are unavailable") + return _ssh_exec(cfg, remote, known_hosts, key_path, stdin_text=data, timeout=timeout) + + +def _host_key_fingerprint(known_hosts: str) -> str: + if not shutil_which("ssh-keygen"): + return "" + proc = _run(["ssh-keygen", "-lf", known_hosts, "-E", "sha256"], timeout=5) + if proc.returncode != 0 or not proc.stdout.strip(): + return "" + line = proc.stdout.splitlines()[0].strip().split() + return line[1] if len(line) > 1 else "" + + +@contextlib.contextmanager +def _ssh_session(payload: dict[str, Any]) -> Iterator[tuple[dict[str, Any], str, str, str]]: + cfg = _validate_common(payload) + for tool in ("ssh", "ssh-keygen"): + if not shutil_which(tool): + raise ValueError(f"{tool} is not installed on the WGTools server") + try: + socket.getaddrinfo(cfg["host"], cfg["ssh_port"], type=socket.SOCK_STREAM) + except OSError as exc: + raise ValueError(f"VPS hostname could not be resolved: {exc}") from exc + with tempfile.TemporaryDirectory(prefix="wgtools-vps-") as tmp: + known_hosts = str(Path(tmp) / "known_hosts") + key_path = "" + if cfg["auth_method"] == "key": + key = Path(tmp) / "id_vps" + key.write_text(cfg["private_key"].strip() + "\n", encoding="utf-8") + key.chmod(0o600) + key_path = str(key) + if cfg["key_passphrase"]: + proc = _run(["ssh-keygen", "-p", "-P", cfg["key_passphrase"], "-N", "", "-f", key_path], timeout=8) + if proc.returncode != 0: + raise ValueError("SSH private key passphrase is incorrect or the key format is unsupported") + code, uid_out, error = _ssh_exec(cfg, "id -u", known_hosts, key_path) + if code != 0: + raise ValueError(f"SSH connection failed: {error or uid_out or 'authentication failed'}") + if not uid_out.isdigit(): + raise ValueError("Could not determine the remote user privileges") + uid = int(uid_out) + privilege_mode = "root" if uid == 0 else "" + if uid != 0: + code, _, _ = _ssh_exec(cfg, "sudo -n true", known_hosts, key_path) + if code == 0: + privilege_mode = "sudo-nopasswd" + elif cfg["auth_method"] == "password": + code, _, _ = _ssh_exec(cfg, "sudo -S -p '' true", known_hosts, key_path, stdin_text=cfg["password"] + "\n") + if code == 0: + privilege_mode = "sudo-password" + if not privilege_mode: + raise ValueError("SSH login works, but root privileges are unavailable. Use root or a user with sudo access") + yield cfg, known_hosts, key_path, privilege_mode + + +def _remote_agent_info( + cfg: dict[str, Any], known_hosts: str, key_path: str, privilege_mode: str, +) -> dict[str, Any]: + # Secrets returned here stay inside the WGTools backend. preflight_vps() + # deliberately exposes only non-secret reconnect metadata to the browser. + script = r'''python3 - <<'PYREMOTE' +import json +import re +import subprocess +import time +from pathlib import Path +root=Path('/var/lib/wgtools-relay') +out={'installed':False,'agent':{},'tenants':[]} +agent=root/'agent.json' +if agent.is_file(): + out['installed']=True + try: out['agent']=json.loads(agent.read_text()) + except Exception: out['agent']={} + for p in sorted((root/'tenants').glob('*/config.json')) if (root/'tenants').exists() else []: + try: + d=json.loads(p.read_text()) + item={k:d.get(k) for k in ( + 'tenant_id','controller_id','relay_port','transport_port','transport_interface', + 'relay_transport_ip','home_transport_ip','published_interface','home_wg_port', + 'control_token','control_port','created_at' + )} + iface=str(d.get('transport_interface') or '') + if iface: + try: + q=subprocess.run(['wg','show',iface,'public-key'],text=True,capture_output=True,timeout=2,check=False) + if q.returncode==0 and q.stdout.strip(): item['relay_transport_public_key']=q.stdout.strip() + except Exception: pass + try: + q=subprocess.run(['wg','show',iface,'peers'],text=True,capture_output=True,timeout=2,check=False) + if q.returncode==0 and q.stdout.strip(): item['home_transport_public_key']=q.stdout.splitlines()[0].strip() + except Exception: pass + try: + q=subprocess.run(['wg','show',iface,'latest-handshakes'],text=True,capture_output=True,timeout=2,check=False) + latest=0 + if q.returncode==0: + for line in q.stdout.splitlines(): + parts=line.split() + if len(parts)>=2: + try: latest=max(latest,int(parts[1])) + except ValueError: pass + item['transport_handshake_age']=max(0,int(time.time())-latest) if latest>0 else None + except Exception: item['transport_handshake_age']=None + conf=p.parent/(iface+'.conf') + if conf.is_file(): + text=conf.read_text(errors='replace') + if not item.get('home_transport_public_key'): + m=re.search(r'(?mi)^PublicKey\s*=\s*(\S+)\s*$',text) + if m: item['home_transport_public_key']=m.group(1) + if not item.get('relay_transport_public_key'): + m=re.search(r'(?mi)^PrivateKey\s*=\s*(\S+)\s*$',text) + if m: + try: + q=subprocess.run(['wg','pubkey'],input=m.group(1)+'\n',text=True,capture_output=True,timeout=2,check=False) + if q.returncode==0 and q.stdout.strip(): item['relay_transport_public_key']=q.stdout.strip() + except Exception: pass + out['tenants'].append(item) + except Exception: pass +print(json.dumps(out,separators=(',',':'))) +PYREMOTE''' + code, out, _ = _root_exec(cfg, "bash -s", known_hosts, key_path, privilege_mode, stdin_text=script) + if code != 0 or not out.strip(): + return {"installed": False, "agent": {}, "tenants": []} + try: + data = json.loads(out.splitlines()[-1]) + return data if isinstance(data, dict) else {"installed": False, "agent": {}, "tenants": []} + except Exception: + return {"installed": False, "agent": {}, "tenants": []} + + +def _controller_remote_tenant(agent_info: dict[str, Any], *, preferred_tenant_id: str = "") -> dict[str, Any] | None: + controller = controller_id() + tenants = [ + dict(item) for item in list(agent_info.get("tenants") or []) + if str(item.get("controller_id") or "") == controller + ] + if preferred_tenant_id: + for item in tenants: + if str(item.get("tenant_id") or "") == preferred_tenant_id: + return item + if len(tenants) == 1: + return tenants[0] + if len(tenants) > 1: + raise ValueError("Several existing Relay connections from this WGTools were found on the VPS. Remove stale duplicates manually before reconnecting") + return None + + +def _detached_vps_id_for_tenant(tenant_id: str) -> str: + if not tenant_id: + return "" + with _connect_db() as conn: + row = conn.execute( + "SELECT id FROM vps_relays WHERE tenant_id=? AND status='detached' ORDER BY updated_at DESC LIMIT 1", + (tenant_id,), + ).fetchone() + return str(row["id"]) if row else "" + + +def _orphan_client_relay_vps_id() -> str: + """Recover the v0.19.9-deleted VPS id when clients still reference it. + + A detached Relay should keep its DB row in current releases. v0.19.9 + deleted that row, but managed client metadata still contains relay_vps_id. + Reusing the single unambiguous orphan id reconnects those clients without + editing or recreating them. + """ + client_dir = Path(DATABASE_PATH).parent / "clients" + if not client_dir.exists(): + return "" + with _connect_db() as conn: + existing = {str(row["id"]) for row in conn.execute("SELECT id FROM vps_relays").fetchall()} + orphaned: set[str] = set() + for path in client_dir.glob("*.json"): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception: + continue + if not isinstance(data, dict) or str(data.get("connection_mode") or "") != "relay": + continue + value = str(data.get("relay_vps_id") or "").strip() + if value and value not in existing: + orphaned.add(value) + return next(iter(orphaned)) if len(orphaned) == 1 else "" + + +def _wg_public_key(private_key: str) -> str: + wg = shutil_which("wg") + if not wg or not private_key.strip(): + return "" + proc = _run([wg, "pubkey"], input_text=private_key.strip() + "\n", timeout=5) + return proc.stdout.strip() if proc.returncode == 0 else "" + + +def _remote_set_home_public_key( + cfg: dict[str, Any], known_hosts: str, key_path: str, privilege_mode: str, + *, tenant: dict[str, Any], public_key: str, +) -> None: + tenant_id = str(tenant.get("tenant_id") or "") + iface = str(tenant.get("transport_interface") or "") + if not re.fullmatch(r"[0-9a-fA-F]{16,64}", tenant_id) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", iface): + raise ValueError("Existing Relay identity on the VPS is invalid") + if not public_key.strip(): + raise ValueError("New Relay transport public key is empty") + conf = f"/var/lib/wgtools-relay/tenants/{tenant_id}/{iface}.conf" + service = _remote_service_name(tenant_id) + script = rf'''set -euo pipefail +python3 - <<'PYREKEY' +import re +from pathlib import Path +p=Path({json.dumps(conf)}) +new={json.dumps(public_key.strip())} +text=p.read_text(encoding='utf-8') +updated,count=re.subn(r'(?mi)^PublicKey\s*=\s*\S+\s*$', 'PublicKey = '+new, text, count=1) +if count != 1: + raise SystemExit('Relay peer PublicKey was not found') +p.write_text(updated,encoding='utf-8') +p.chmod(0o600) +PYREKEY +systemctl restart {service} +''' + code, _out, err = _root_exec( + cfg, "bash -s", known_hosts, key_path, privilege_mode, + stdin_text=script, timeout=40, + ) + if code != 0: + raise ValueError("Could not reconnect existing Relay transport on VPS: " + (err or "remote rekey failed")) + + +def _remote_set_home_wg_port( + cfg: dict[str, Any], known_hosts: str, key_path: str, privilege_mode: str, + *, tenant: dict[str, Any], home_wg_port: int, +) -> None: + """Synchronize the preserved tenant with the current home WG listen port. + + The Relay Agent watches config.json and reloads only the changed tenant, so + this does not restart or disturb other tenants on the same VPS. + """ + tenant_id = str(tenant.get("tenant_id") or "") + if not re.fullmatch(r"[0-9a-fA-F]{16,64}", tenant_id): + raise ValueError("Existing Relay identity on the VPS is invalid") + port = int(home_wg_port) + if not 1 <= port <= 65535: + raise ValueError("The selected WireGuard interface has no valid listen port") + config_path = f"/var/lib/wgtools-relay/tenants/{tenant_id}/config.json" + script = rf'''set -euo pipefail +python3 - <<'PYPORT' +import json +import os +from pathlib import Path +p=Path({json.dumps(config_path)}) +port={port} +data=json.loads(p.read_text(encoding='utf-8')) +data['home_wg_port']=port +tmp=p.with_name(p.name+'.tmp') +tmp.write_text(json.dumps(data,separators=(',',':'))+'\n',encoding='utf-8') +tmp.chmod(0o600) +os.replace(tmp,p) +PYPORT +''' + code, _out, err = _root_exec( + cfg, "bash -s", known_hosts, key_path, privilege_mode, + stdin_text=script, timeout=20, + ) + if code != 0: + raise ValueError("Could not update existing Relay listen port on VPS: " + (err or "remote tenant update failed")) + + +def _pick_free_port(start: int, busy: set[int], avoid: set[int] | None = None) -> int: + avoid = avoid or set() + for offset in range(0, 2048): + port = start + offset + if port > 65535: + port = 1024 + (port - 65536) + if port >= 1024 and port not in busy and port not in avoid: + return port + raise ValueError("No free UDP port could be suggested on the VPS") + + +def _listener_ports(raw: str) -> set[int]: + result: set[int] = set() + for line in raw.splitlines(): + for match in re.finditer(r":(\d+)\b", line): + try: + result.add(int(match.group(1))) + except ValueError: + pass + return result + + +def preflight_vps(payload: dict[str, Any]) -> dict[str, Any]: + with _ssh_session(payload) as (cfg, known_hosts, key_path, privilege_mode): + _, os_raw, _ = _ssh_exec(cfg, "cat /etc/os-release 2>/dev/null || true", known_hosts, key_path) + os_data = _parse_os_release(os_raw) + os_id = os_data.get("ID", "").lower() + os_like = os_data.get("ID_LIKE", "").lower().split() + os_name = os_data.get("PRETTY_NAME") or os_data.get("NAME") or os_id or "Unknown Linux" + os_version = os_data.get("VERSION_ID", "") + _, arch, _ = _ssh_exec(cfg, "uname -m", known_hosts, key_path) + _, checks_raw, _ = _ssh_exec( + cfg, + "for c in apt-get systemctl ip ss python3; do command -v $c >/dev/null 2>&1 && echo $c=1 || echo $c=0; done; " + "command -v wg >/dev/null 2>&1 && echo wg=1 || echo wg=0; " + "command -v iptables >/dev/null 2>&1 && echo iptables=1 || echo iptables=0", + known_hosts, key_path, + ) + checks: dict[str, bool] = {} + for line in checks_raw.splitlines(): + if "=" in line: + key, value = line.split("=", 1) + checks[key.strip()] = value.strip() == "1" + compatible_os = os_id in {"debian", "ubuntu"} or "debian" in os_like or "ubuntu" in os_like + required = all(checks.get(name, False) for name in ("apt-get", "systemctl", "ip", "ss", "python3")) + if not compatible_os: + raise ValueError(f"Unsupported VPS operating system: {os_name}. Debian or Ubuntu is recommended") + if not required: + missing = [name for name in ("apt-get", "systemctl", "ip", "ss", "python3") if not checks.get(name, False)] + raise ValueError("VPS is missing required system tools: " + ", ".join(missing)) + + agent_info = _remote_agent_info(cfg, known_hosts, key_path, privilege_mode) + _, listeners, _ = _ssh_exec(cfg, "ss -H -lun 2>/dev/null || true", known_hosts, key_path) + busy = _listener_ports(listeners) + requested_relay = int(cfg["relay_port"]) + requested_transport = int(cfg["transport_port"]) + reconnect_tenant = _controller_remote_tenant(agent_info) if agent_info.get("installed") else None + if reconnect_tenant: + # This VPS already contains a tenant created by this WGTools controller. + # Re-use its actual ports instead of allocating a second connection. + relay_port = int(reconnect_tenant.get("relay_port") or requested_relay) + transport_port = int(reconnect_tenant.get("transport_port") or requested_transport) + elif agent_info.get("installed"): + # The Agent may serve another independent WGTools controller. + relay_port = _pick_free_port(requested_relay, busy) + transport_port = _pick_free_port(requested_transport, busy, {relay_port}) + else: + busy_requested = [port for port in (requested_relay, requested_transport) if port in busy] + if busy_requested: + raise ValueError("UDP port is already in use on the VPS: " + ", ".join(map(str, busy_requested))) + relay_port = requested_relay + transport_port = requested_transport + + agent = dict(agent_info.get("agent") or {}) + tenants = list(agent_info.get("tenants") or []) + reconnect_tenant_id = str((reconnect_tenant or {}).get("tenant_id") or "") + reconnect_vps_id = _detached_vps_id_for_tenant(reconnect_tenant_id) + if reconnect_tenant and not reconnect_vps_id: + reconnect_vps_id = _orphan_client_relay_vps_id() + return { + "ok": True, + "host": cfg["host"], "ssh_port": cfg["ssh_port"], "ssh_user": cfg["ssh_user"], + "os_id": os_id, "os_name": os_name, "os_version": os_version, + "architecture": arch, "privilege_mode": privilege_mode, + "host_key_fingerprint": _host_key_fingerprint(known_hosts), + "wireguard_installed": bool(checks.get("wg")), "iptables_installed": bool(checks.get("iptables")), + "relay_port": relay_port, "transport_port": transport_port, + "requested_relay_port": requested_relay, "requested_transport_port": requested_transport, + "ports_adjusted": relay_port != requested_relay or transport_port != requested_transport, + "relay_agent_installed": bool(agent_info.get("installed")), + "relay_agent_id": str(agent.get("agent_id") or ""), + "relay_agent_version": str(agent.get("version") or ""), + "relay_tenant_count": len(tenants), + "relay_active_tenant_count": sum(1 for item in tenants if isinstance(item.get("transport_handshake_age"), int) and int(item["transport_handshake_age"]) <= 180), + "reconnect_available": bool(reconnect_tenant), + "reconnect_tenant_id": reconnect_tenant_id, + "reconnect_vps_id": reconnect_vps_id, + "checks": { + "ssh": True, "os": True, "apt": True, "systemd": True, + "network_tools": True, "python": True, "ports_free": True, "root_access": True, + }, + } + + +def _wg_keypair() -> tuple[str, str]: + wg = shutil_which("wg") + if not wg: + raise ValueError("WireGuard tools are not installed on the WGTools server") + private = _run([wg, "genkey"], timeout=5) + if private.returncode != 0 or not private.stdout.strip(): + raise ValueError("Could not generate WireGuard transport key") + priv = private.stdout.strip() + public = _run([wg, "pubkey"], input_text=priv + "\n", timeout=5) + if public.returncode != 0 or not public.stdout.strip(): + raise ValueError("Could not derive WireGuard transport public key") + return priv, public.stdout.strip() + + +def _used_local_networks() -> list[ipaddress.IPv4Network]: + ip = shutil_which("ip") or "/usr/sbin/ip" + proc = _run([ip, "-4", "route", "show", "table", "all"], timeout=5) + result: list[ipaddress.IPv4Network] = [] + if proc.returncode != 0: + return result + for line in proc.stdout.splitlines(): + first = line.split()[0] if line.split() else "" + if first == "default": + continue + try: + result.append(ipaddress.ip_network(first, strict=False)) + except Exception: + pass + return result + + +def _allocate_transport_network(tenant_id: str, remote_tenants: list[dict[str, Any]]) -> ipaddress.IPv4Network: + used = _used_local_networks() + for tenant in remote_tenants: + for key in ("home_transport_ip", "relay_transport_ip"): + value = str(tenant.get(key) or "") + if value: + try: + used.append(ipaddress.ip_network(value + "/30", strict=False)) + except Exception: + pass + seed = int(tenant_id[:8], 16) % 16384 + base = int(ipaddress.ip_address("10.254.0.0")) + for step in range(16384): + index = (seed + step) % 16384 + network = ipaddress.ip_network((base + index * 4, 30)) + if all(not network.overlaps(other) for other in used): + return network + raise ValueError("Could not allocate a conflict-free Relay transport network") + + +def _transport_interface_name(tenant_id: str) -> str: + return "wgrly" + tenant_id[:6] + + +def _remote_service_name(tenant_id: str) -> str: + return "wgtools-relay-transport-" + tenant_id[:12] + ".service" + + +def _local_service_name(tenant_id: str) -> str: + return "wgtools-relay-home-" + tenant_id[:12] + ".service" + + +def _remote_install_script( + *, agent_id: str, tenant: dict[str, Any], relay_private_key: str, + home_public_key: str, agent_source: str, agent_unit: str, agent_preexisting: bool, +) -> str: + tenant_id = str(tenant["tenant_id"]) + iface = str(tenant["transport_interface"]) + root = f"/var/lib/wgtools-relay/tenants/{tenant_id}" + config = dict(tenant) + config["enabled"] = True + agent_json = json.dumps({"agent_id": agent_id, "version": "0.1", "created_at": int(time.time())}, separators=(",", ":")) + tenant_json = json.dumps(config, separators=(",", ":")) + wg_conf = f"""[Interface]\nAddress = {tenant['relay_transport_ip']}/30\nListenPort = {tenant['transport_port']}\nPrivateKey = {relay_private_key}\n\n[Peer]\nPublicKey = {home_public_key}\nAllowedIPs = {tenant['home_transport_ip']}/32\n""" + service = f"""[Unit]\nDescription=WGTools Relay transport {tenant_id}\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\nExecStart=/usr/bin/wg-quick up {root}/{iface}.conf\nExecStop=/usr/bin/wg-quick down {root}/{iface}.conf\n\n[Install]\nWantedBy=multi-user.target\n""" + # Content is transmitted through SSH stdin, not command-line arguments. + payloads = { + "/opt/wgtools-relay/wgtools-relay-agent.py": agent_source, + "/etc/systemd/system/wgtools-relay-agent.service": agent_unit, + f"{root}/config.json": tenant_json + "\n", + f"{root}/{iface}.conf": wg_conf, + f"/etc/systemd/system/{_remote_service_name(tenant_id)}": service, + } + encoded = json.dumps(payloads) + package_setup = "" if agent_preexisting else "apt-get update >/dev/null\napt-get install -y wireguard-tools iproute2 iptables python3 >/dev/null\n" + return f'''set -euo pipefail +export DEBIAN_FRONTEND=noninteractive +{package_setup}install -d -m 0755 /opt/wgtools-relay /var/lib/wgtools-relay/tenants +if [ ! -s /var/lib/wgtools-relay/agent.json ]; then + printf '%s\\n' {json.dumps(agent_json)} > /var/lib/wgtools-relay/agent.json + chmod 0600 /var/lib/wgtools-relay/agent.json +fi +python3 - <<'PYFILES' +import json +from pathlib import Path +files=json.loads({json.dumps(encoded)}) +for name,content in files.items(): + p=Path(name); p.parent.mkdir(parents=True,exist_ok=True); p.write_text(content,encoding='utf-8') + p.chmod(0o600 if name.endswith('.conf') or name.endswith('config.json') else (0o755 if name.endswith('.py') else 0o644)) +PYFILES +systemctl daemon-reload +systemctl enable --now {_remote_service_name(tenant_id)} >/dev/null +systemctl enable --now wgtools-relay-agent.service >/dev/null +systemctl restart wgtools-relay-agent.service +''' + + +def _local_transport_apply( + *, vps_id: str, tenant: dict[str, Any], home_private_key: str, relay_public_key: str, + vps_host: str, +) -> tuple[Path, str]: + tenant_id = str(tenant["tenant_id"]) + iface = str(tenant["transport_interface"]) + directory = LOCAL_RELAY_DIR / vps_id + directory.mkdir(parents=True, exist_ok=True) + directory.chmod(0o700) + conf = directory / f"{iface}.conf" + conf.write_text( + f"""[Interface]\nAddress = {tenant['home_transport_ip']}/30\nPrivateKey = {home_private_key}\n\n[Peer]\nPublicKey = {relay_public_key}\nAllowedIPs = {tenant['relay_transport_ip']}/32\nEndpoint = {vps_host}:{tenant['transport_port']}\nPersistentKeepalive = 25\n""", + encoding="utf-8", + ) + conf.chmod(0o600) + service_name = _local_service_name(tenant_id) + service_path = Path("/etc/systemd/system") / service_name + service_path.write_text( + f"""[Unit]\nDescription=WGTools Relay home transport {tenant_id}\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\nExecStart=/usr/bin/wg-quick up {conf}\nExecStop=/usr/bin/wg-quick down {conf}\n\n[Install]\nWantedBy=multi-user.target\n""", + encoding="utf-8", + ) + service_path.chmod(0o644) + systemctl = shutil_which("systemctl") or "/usr/bin/systemctl" + proc = _run([systemctl, "daemon-reload"], timeout=15) + if proc.returncode != 0: + raise ValueError(proc.stderr.strip() or "systemd daemon-reload failed") + proc = _run([systemctl, "enable", "--now", service_name], timeout=35) + if proc.returncode != 0: + raise ValueError(proc.stderr.strip() or f"Could not start {service_name}") + return conf, service_name + + +def _local_transport_rollback(conf: Path | None, service_name: str | None) -> None: + systemctl = shutil_which("systemctl") or "/usr/bin/systemctl" + if service_name: + _run([systemctl, "disable", "--now", service_name], timeout=20) + try: + (Path("/etc/systemd/system") / service_name).unlink(missing_ok=True) + except Exception: + pass + _run([systemctl, "daemon-reload"], timeout=10) + if conf: + try: + conf.unlink(missing_ok=True) + except Exception: + pass + + +def _local_transport_remove(item: dict[str, Any]) -> None: + """Detach only the local WGTools side of a Relay tenant. + + The remote VPS tenant is deliberately left untouched so a restored WGTools + backup can reconnect to the same Relay identity later. + """ + tenant_id = str(item.get("tenant_id") or "").strip() + vps_id = str(item.get("id") or "").strip() + iface = str(item.get("transport_interface") or "").strip() + if not tenant_id or not vps_id: + raise ValueError("Relay identity is incomplete") + + systemctl = shutil_which("systemctl") or "/usr/bin/systemctl" + service_name = _local_service_name(tenant_id) + service_path = Path("/etc/systemd/system") / service_name + directory = LOCAL_RELAY_DIR / vps_id + conf = directory / f"{iface}.conf" if iface else None + + # wg-quick is normally stopped by systemd. Continue if the unit or config + # was already missing, then make sure no stale local interface survives. + _run([systemctl, "disable", "--now", service_name], timeout=30) + if iface: + ip = shutil_which("ip") or "/usr/sbin/ip" + probe = _run([ip, "link", "show", "dev", iface], timeout=5) + if probe.returncode == 0: + if conf and conf.exists(): + wg_quick = shutil_which("wg-quick") or "/usr/bin/wg-quick" + _run([wg_quick, "down", str(conf)], timeout=20) + probe = _run([ip, "link", "show", "dev", iface], timeout=5) + if probe.returncode == 0: + _run([ip, "link", "delete", "dev", iface], timeout=10) + + try: + service_path.unlink(missing_ok=True) + except OSError as exc: + raise ValueError(f"Could not remove local Relay service: {exc}") from exc + + # This directory contains only the home-side private transport material for + # this WGTools record. The remote /var/lib/wgtools-relay tenant is not used. + if directory.exists(): + import shutil + try: + shutil.rmtree(directory) + except OSError as exc: + raise ValueError(f"Could not remove local Relay state: {exc}") from exc + + _run([systemctl, "daemon-reload"], timeout=15) + + +def detach_vps(vps_id: str) -> dict[str, Any]: + """Remove an installed VPS from this WGTools instance only. + + No SSH connection is made and nothing is deleted on the VPS. The remote + Relay Agent, tenant, keys and token remain available for disaster recovery. + """ + init_vps_database() + item = get_vps(vps_id, include_secrets=True) + if not item: + raise ValueError("VPS entry not found") + if str(item.get("status") or "") != "installed": + raise ValueError("Only an installed VPS Relay can be removed here") + + _local_transport_remove(item) + # Keep the Relay identity and home-side private key in SQLite, but hide the + # entry from the active VPS list. This makes a later re-add on the same + # WGTools instance a real reconnect rather than a new tenant provision. + now = int(time.time()) + with _connect_db() as conn: + conn.execute( + "UPDATE vps_relays SET status='detached',last_health=0,last_error='',updated_at=? WHERE id=?", + (now, vps_id), + ) + + return { + "ok": True, + "id": vps_id, + "name": str(item.get("name") or ""), + "tenant_id": str(item.get("tenant_id") or ""), + "remote_preserved": True, + } + + +def reconcile_local_relays() -> list[dict[str, Any]]: + """Recreate missing home-side Relay transports from restored DB state. + + Migration backups already contain the VPS Relay secrets in SQLite. This + makes a restored WGTools instance reconnect to the existing remote tenant + instead of provisioning a new one. + """ + init_vps_database() + results: list[dict[str, Any]] = [] + with _connect_db() as conn: + rows = conn.execute("SELECT id FROM vps_relays WHERE status='installed' ORDER BY created_at,id").fetchall() + for row in rows: + vps_id = str(row["id"]) + item = get_vps(vps_id, include_secrets=True) or {} + tenant_id = str(item.get("tenant_id") or "").strip() + iface = str(item.get("transport_interface") or "").strip() + home_private = str(item.get("home_transport_private_key") or "").strip() + relay_public = str(item.get("relay_transport_public_key") or "").strip() + host = str(item.get("host") or "").strip() + if not all((tenant_id, iface, home_private, relay_public, host)): + results.append({"id": vps_id, "ok": False, "error": "Relay restore data is incomplete"}) + continue + try: + directory = LOCAL_RELAY_DIR / vps_id + conf = directory / f"{iface}.conf" + service_name = _local_service_name(tenant_id) + service_path = Path("/etc/systemd/system") / service_name + ip = shutil_which("ip") or "/usr/sbin/ip" + interface_up = _run([ip, "link", "show", "dev", iface], timeout=5).returncode == 0 + changed = False + + if not conf.exists() or not service_path.exists(): + # Remove any partial local leftovers first. Remote state is never touched. + _local_transport_remove(item) + _local_transport_apply( + vps_id=vps_id, + tenant=item, + home_private_key=home_private, + relay_public_key=relay_public, + vps_host=host, + ) + changed = True + elif not interface_up: + systemctl = shutil_which("systemctl") or "/usr/bin/systemctl" + proc = _run([systemctl, "restart", service_name], timeout=35) + if proc.returncode != 0: + raise ValueError(proc.stderr.strip() or f"Could not restart {service_name}") + changed = True + + results.append({"id": vps_id, "ok": True, "changed": changed, "interface": iface}) + except Exception as exc: + results.append({"id": vps_id, "ok": False, "error": str(exc)}) + return results + + +def _relay_health_url(ip: str, port: int) -> str: + return f"http://{ip}:{port}/v1/health" + + +def _query_relay_health(item: dict[str, Any], *, timeout: float = 4.0) -> dict[str, Any]: + token = str(item.get("control_token") or "") + ip = str(item.get("relay_transport_ip") or "") + port = int(item.get("control_port") or RELAY_CONTROL_PORT) + if not token or not ip: + raise ValueError("Relay management connection is not configured") + request = ( + f"GET /v1/health HTTP/1.1\r\nHost: {ip}\r\nAuthorization: Bearer {token}\r\n" + "Connection: close\r\n\r\n" + ).encode("utf-8") + try: + with socket.create_connection((ip, port), timeout=timeout) as sock: + sock.settimeout(timeout) + sock.sendall(request) + chunks: list[bytes] = [] + while True: + chunk = sock.recv(65536) + if not chunk: + break + chunks.append(chunk) + if sum(map(len, chunks)) > 1024 * 1024: + raise ValueError("Relay response is too large") + raw = b"".join(chunks) + header, body = raw.split(b"\r\n\r\n", 1) + status_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace") + if " 200 " not in status_line: + raise ValueError(f"Relay returned {status_line}") + data = json.loads(body.decode("utf-8")) + except (OSError, ValueError, json.JSONDecodeError) as exc: + raise ValueError(f"Relay management tunnel is not responding: {exc}") from exc + if not isinstance(data, dict) or not data.get("ok"): + raise ValueError(str(data.get("error") if isinstance(data, dict) else "Invalid Relay response")) + return data + + +def relay_health(vps_id: str) -> dict[str, Any]: + item = get_vps(vps_id, include_secrets=True) + if not item: + raise ValueError("VPS entry not found") + if str(item.get("status")) != "installed": + raise ValueError("Relay is not installed") + now = int(time.time()) + try: + data = _query_relay_health(item) + with _connect_db() as conn: + conn.execute("UPDATE vps_relays SET last_health=?,last_error='',updated_at=? WHERE id=?", (now, now, vps_id)) + data["status"] = "installed" + return data + except ValueError as exc: + with _connect_db() as conn: + conn.execute("UPDATE vps_relays SET last_error=?,updated_at=? WHERE id=?", (str(exc), now, vps_id)) + raise + + +def install_relay( + vps_id: str, + credentials: dict[str, Any], + *, published_interface: str, + home_wg_port: int, +) -> dict[str, Any]: + init_vps_database() + current = get_vps(vps_id, include_secrets=True) + if not current: + raise ValueError("VPS candidate not found") + if str(current.get("status")) == "installed": + return {"ok": True, "item": get_vps(vps_id), "health": relay_health(vps_id), "changed": False} + if not published_interface or not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", published_interface): + raise ValueError("Invalid WireGuard interface selected for Relay") + if not 1 <= int(home_wg_port) <= 65535: + raise ValueError("The selected WireGuard interface has no valid listen port") + + payload = { + **credentials, + "name": current["name"], "host": current["host"], "ssh_port": current["ssh_port"], + "ssh_user": current["ssh_user"], "endpoint_domain": current["endpoint_domain"], + "relay_port": current["relay_port"], "transport_port": current["transport_port"], + } + preflight = preflight_vps(payload) + saved_fingerprint = str(current.get("host_key_fingerprint") or "") + current_fingerprint = str(preflight.get("host_key_fingerprint") or "") + if saved_fingerprint and current_fingerprint and saved_fingerprint != current_fingerprint: + raise ValueError("The VPS SSH host key changed since preflight. Remove and re-add this VPS only after verifying the server identity") + + controller = controller_id() + preferred_tenant_id = str(current.get("tenant_id") or "") + + with _ssh_session(payload) as (cfg, known_hosts, key_path, privilege_mode): + agent_info = _remote_agent_info(cfg, known_hosts, key_path, privilege_mode) + existing_tenant = _controller_remote_tenant(agent_info, preferred_tenant_id=preferred_tenant_id) + + if existing_tenant: + # Reconnect to the tenant already created by this WGTools controller. + # No second tenant or UDP port pair is created. + tenant = dict(existing_tenant) + tenant_id = str(tenant.get("tenant_id") or "") + transport_interface = str(tenant.get("transport_interface") or "") + relay_port = int(tenant.get("relay_port") or 0) + transport_port = int(tenant.get("transport_port") or 0) + home_ip = str(tenant.get("home_transport_ip") or "") + relay_ip = str(tenant.get("relay_transport_ip") or "") + control_token = str(tenant.get("control_token") or "") + control_port = int(tenant.get("control_port") or RELAY_CONTROL_PORT) + relay_public = str(tenant.get("relay_transport_public_key") or "") + remote_home_public = str(tenant.get("home_transport_public_key") or "") + remote_interface = str(tenant.get("published_interface") or "") + remote_home_wg_port = int(tenant.get("home_wg_port") or 0) + if not all((tenant_id, transport_interface, relay_port, transport_port, home_ip, relay_ip, control_token, relay_public)): + raise ValueError("Existing Relay tenant on the VPS is incomplete and cannot be reconnected safely") + if remote_interface and remote_interface != published_interface: + raise ValueError(f"Existing Relay belongs to WireGuard interface {remote_interface}, not {published_interface}") + + # The tenant identity belongs to this WGTools controller and the same + # published interface. A changed WireGuard ListenPort is a normal + # server setting change, not a reason to provision a second tenant. + # Synchronize the preserved VPS tenant to the current home port. + effective_home_wg_port = int(home_wg_port) + port_updated = remote_home_wg_port != effective_home_wg_port + if port_updated: + _remote_set_home_wg_port( + cfg, known_hosts, key_path, privilege_mode, + tenant=tenant, home_wg_port=effective_home_wg_port, + ) + tenant["home_wg_port"] = effective_home_wg_port + + # v0.19.10+ keeps this private key in a detached DB row. If v0.19.9 + # already deleted the row, recover the SAME tenant by rotating only + # its home-side transport peer key on the VPS. + home_private = "" + if preferred_tenant_id == tenant_id: + home_private = str(current.get("home_transport_private_key") or "") + home_public = _wg_public_key(home_private) if home_private else "" + rekeyed = False + old_remote_home_public = remote_home_public + if not home_private or not home_public or (remote_home_public and home_public != remote_home_public): + home_private, home_public = _wg_keypair() + _remote_set_home_public_key( + cfg, known_hosts, key_path, privilege_mode, + tenant=tenant, public_key=home_public, + ) + rekeyed = True + + conf: Path | None = None + local_service: str | None = None + try: + tenant.update({ + "control_token": control_token, + "control_port": control_port, + "home_wg_port": effective_home_wg_port, + "published_interface": remote_interface or published_interface, + }) + conf, local_service = _local_transport_apply( + vps_id=vps_id, tenant=tenant, home_private_key=home_private, + relay_public_key=relay_public, vps_host=str(current["host"]), + ) + health: dict[str, Any] | None = None + last_error = "" + for _ in range(15): + time.sleep(1) + try: + probe_item = {**current, **tenant, "control_token": control_token, "status": "installed"} + health = _query_relay_health(probe_item, timeout=2.0) + break + except ValueError as exc: + last_error = str(exc) + if health is None: + raise ValueError(last_error or "Relay management tunnel did not become ready") + except Exception: + _local_transport_rollback(conf, local_service) + if rekeyed and old_remote_home_public: + try: + _remote_set_home_public_key( + cfg, known_hosts, key_path, privilege_mode, + tenant=tenant, public_key=old_remote_home_public, + ) + except Exception: + pass + if port_updated and remote_home_wg_port: + try: + _remote_set_home_wg_port( + cfg, known_hosts, key_path, privilege_mode, + tenant=tenant, home_wg_port=remote_home_wg_port, + ) + except Exception: + pass + raise + + now = int(time.time()) + agent_id = str((agent_info.get("agent") or {}).get("agent_id") or "") + with _connect_db() as conn: + conn.execute( + """UPDATE vps_relays SET relay_port=?,transport_port=?,status='installed', + agent_id=?,tenant_id=?,controller_id=?,control_token=?,transport_interface=?, + home_transport_ip=?,relay_transport_ip=?,control_port=?,published_interface=?, + home_wg_port=?,home_transport_private_key=?,relay_transport_public_key=?, + installed_at=CASE WHEN installed_at>0 THEN installed_at ELSE ? END, + last_health=?,last_error='',updated_at=? WHERE id=?""", + ( + relay_port, transport_port, agent_id, tenant_id, controller, control_token, + transport_interface, home_ip, relay_ip, control_port, + remote_interface or published_interface, effective_home_wg_port, + home_private, relay_public, int(tenant.get("created_at") or now), + now, now, vps_id, + ), + ) + return { + "ok": True, "changed": True, "reconnected": True, + "item": get_vps(vps_id), "health": health, + } + + # No tenant from this controller exists on the VPS: provision a new one. + relay_port = int(preflight["relay_port"]) + transport_port = int(preflight["transport_port"]) + tenant_id = uuid.uuid4().hex + control_token = secrets.token_urlsafe(36) + transport_interface = _transport_interface_name(tenant_id) + remote_tenants = list(agent_info.get("tenants") or []) + network = _allocate_transport_network(tenant_id, remote_tenants) + home_ip = str(network.network_address + 1) + relay_ip = str(network.network_address + 2) + home_private, home_public = _wg_keypair() + relay_private, relay_public = _wg_keypair() + agent_id = str((agent_info.get("agent") or {}).get("agent_id") or uuid.uuid4().hex) + tenant = { + "tenant_id": tenant_id, + "controller_id": controller, + "relay_port": relay_port, + "transport_port": transport_port, + "transport_interface": transport_interface, + "home_transport_ip": home_ip, + "relay_transport_ip": relay_ip, + "home_wg_port": int(home_wg_port), + "published_interface": published_interface, + "control_token": control_token, + "control_port": RELAY_CONTROL_PORT, + "created_at": int(time.time()), + } + if not RELAY_AGENT_SOURCE.is_file() or not RELAY_AGENT_UNIT_SOURCE.is_file(): + raise ValueError("WGTools Relay Agent files are missing from this installation") + remote_script = _remote_install_script( + agent_id=agent_id, tenant=tenant, relay_private_key=relay_private, + home_public_key=home_public, + agent_source=RELAY_AGENT_SOURCE.read_text(encoding="utf-8"), + agent_unit=RELAY_AGENT_UNIT_SOURCE.read_text(encoding="utf-8"), + agent_preexisting=bool(agent_info.get("installed")), + ) + code, _out, err = _root_exec( + cfg, "bash -s", known_hosts, key_path, privilege_mode, + stdin_text=remote_script, timeout=300, + ) + if code != 0: + raise ValueError("Relay installation on VPS failed: " + (err or "remote installer failed")) + + conf: Path | None = None + local_service: str | None = None + try: + conf, local_service = _local_transport_apply( + vps_id=vps_id, tenant=tenant, home_private_key=home_private, + relay_public_key=relay_public, vps_host=str(current["host"]), + ) + health: dict[str, Any] | None = None + last_error = "" + for _ in range(15): + time.sleep(1) + try: + probe_item = {**current, **tenant, "control_token": control_token, "status": "installed"} + health = _query_relay_health(probe_item, timeout=2.0) + break + except ValueError as exc: + last_error = str(exc) + if health is None: + raise ValueError(last_error or "Relay management tunnel did not become ready") + except Exception: + _local_transport_rollback(conf, local_service) + rollback_script = f'''set -e +systemctl disable --now {_remote_service_name(tenant_id)} >/dev/null 2>&1 || true +rm -f /etc/systemd/system/{_remote_service_name(tenant_id)} +rm -rf /var/lib/wgtools-relay/tenants/{tenant_id} +systemctl daemon-reload +systemctl restart wgtools-relay-agent.service >/dev/null 2>&1 || true +''' + _root_exec(cfg, "bash -s", known_hosts, key_path, privilege_mode, stdin_text=rollback_script, timeout=30) + raise + + now = int(time.time()) + with _connect_db() as conn: + conn.execute( + """UPDATE vps_relays SET relay_port=?,transport_port=?,status='installed', + agent_id=?,tenant_id=?,controller_id=?,control_token=?,transport_interface=?, + home_transport_ip=?,relay_transport_ip=?,control_port=?,published_interface=?, + home_wg_port=?,home_transport_private_key=?,relay_transport_public_key=?, + installed_at=?,last_health=?,last_error='',updated_at=? WHERE id=?""", + ( + relay_port, transport_port, agent_id, tenant_id, controller, control_token, + transport_interface, home_ip, relay_ip, RELAY_CONTROL_PORT, published_interface, + int(home_wg_port), home_private, relay_public, now, now, now, vps_id, + ), + ) + return {"ok": True, "changed": True, "reconnected": False, "item": get_vps(vps_id), "health": health} diff --git a/app/locales/de.json b/app/locales/de.json new file mode 100644 index 0000000..492122e --- /dev/null +++ b/app/locales/de.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Benutzer erstellen", + "auth.login_subtitle": "Gib deinen WGTools-Benutzernamen und dein Passwort ein.", + "auth.login_title": "Bei WGTools anmelden", + "auth.password": "Passwort", + "auth.password_repeat": "Passwort wiederholen", + "auth.setup_help": "Das erste Konto erhält vollen Zugriff auf WGTools. Weitere Benutzer können später in den Einstellungen erstellt werden.", + "auth.setup_subtitle": "Vor der Serververwaltung muss ein WGTools-Konto eingerichtet werden.", + "auth.setup_title": "Ersten Benutzer erstellen", + "auth.sign_in": "Anmelden", + "auth.sign_out": "Abmelden", + "auth.username": "Benutzername", + "clients.actions": "Aktionen", + "clients.add": "+ Client hinzufügen", + "clients.address": "VPN-Adresse", + "clients.address_hint": "Die erste freie Adresse wird automatisch vorgeschlagen.", + "clients.allowed_ips_required": "Gib mindestens ein AllowedIPs-Netz für die Client-Konfiguration ein.", + "clients.basic_connection": "Verbindungseinstellungen", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs in Client-Konfiguration", + "clients.config_private_warning": "Diese Konfiguration enthält den privaten Client-Schlüssel. Bewahre sie sicher auf.", + "clients.config_title": "Client-Konfiguration", + "clients.config_unavailable": "Konfiguration nicht verfügbar", + "clients.connection_direct": "Direkt zu WGTools", + "clients.connection_path": "Verbindungsweg", + "clients.connection_relay": "VPS-Relay", + "clients.connection_via": "Verbinden über", + "clients.connection_via_hint": "Wähle den öffentlichen Zugang für diesen Client. Relay ist nur sichtbar, wenn es für die ausgewählte WireGuard-Schnittstelle installiert ist.", + "clients.copy_config": "Kopieren", + "clients.copy_done": "Konfiguration kopiert", + "clients.create_subtitle": "WireGuard-Peer erstellen und Client-Konfiguration erzeugen.", + "clients.create_title": "Client erstellen", + "clients.creating": "Schlüssel werden erstellt und Client angewendet…", + "clients.day_fri": "Fr", + "clients.day_mon": "Mo", + "clients.day_sat": "Sa", + "clients.day_sun": "So", + "clients.day_thu": "Do", + "clients.day_tue": "Di", + "clients.day_wed": "Mi", + "clients.delete_confirm": "Diesen Client aus WireGuard löschen? WGTools erstellt ein Backup und entfernt die automatisch generierten Richtlinienregeln dieses Clients.", + "clients.deleted": "Client gelöscht", + "clients.dns": "DNS (optional)", + "clients.dns_hint": "IPv4-DNS-Server durch Komma trennen.", + "clients.download_config": ".conf herunterladen", + "clients.duplicate": "Duplizieren", + "clients.duplicate_address_error": "Diese VPN-Adresse wird bereits von einem anderen Peer verwendet.", + "clients.duplicate_name_error": "Ein Peer mit diesem Namen existiert bereits.", + "clients.duplicate_ready": "Kopie bereit. WGTools hat einen neuen Namen und eine VPN-Adresse vergeben. Prüfe die Einstellungen vor dem Speichern.", + "clients.duplicate_site_hint": "Remote-Netze wurden entfernt, um doppelte Routen zu vermeiden. Gib die Netze für den neuen Site-to-site-Peer ein.", + "clients.duplicate_suffix": "Kopie", + "clients.edit_subtitle": "Serverseitigen Peer aktualisieren. Änderungen werden ohne WireGuard-Neustart angewendet.", + "clients.edit_title": "Client bearbeiten", + "clients.endpoint": "Server-Endpoint", + "clients.endpoint_hint": "Für Remote-Clients die öffentliche IP oder Domain verwenden, die den WireGuard-Port an diesen Server weiterleitet.", + "clients.existing": "Vorhandener Peer", + "clients.expiration": "Gültigkeitsdauer", + "clients.expiration_action": "Bei Ablauf", + "clients.expiration_action_hint": "Ohne Haken bleibt der Client in WGTools, aber WireGuard-Zugriff wird gesperrt. Neue Laufzeit oder „Kein Ablaufdatum“ wählen und speichern, um ihn freizugeben.", + "clients.expiration_datetime": "Läuft ab am", + "clients.expiration_datetime_hint": "Verwendet lokales Datum und Uhrzeit dieses Browsers.", + "clients.expiration_delete": "Client löschen", + "clients.expiration_future_required": "Wähle Datum und Uhrzeit in der Zukunft.", + "clients.expiration_hint": "Bei Ablauf führt WGTools die gewählte Aktion zur nächsten vollen Minute aus. Zuvor wird ein WireGuard-Backup erstellt.", + "clients.expire_1d": "1 Tag", + "clients.expire_1h": "1 Stunde", + "clients.expire_3h": "3 Stunden", + "clients.expire_6h": "6 Stunden", + "clients.expire_custom": "Eigenes Datum und Uhrzeit", + "clients.expire_never": "Kein Ablaufdatum", + "clients.expired": "Abgelaufen", + "clients.expired_disabled_hint": "Die Gültigkeit ist abgelaufen. Der Client bleibt erhalten, aber WireGuard-Zugriff ist gesperrt. Wähle eine neue Laufzeit oder „Kein Ablaufdatum“ und speichere.", + "clients.expired_disabled_short": "Abgelaufen · deaktiviert", + "clients.expired_disabled_status": "Abgelaufen", + "clients.expires_days": "Läuft in {n} Tagen ab", + "clients.expires_hours": "Läuft in {n} Std. ab", + "clients.expires_minutes": "Läuft in {n} Min. ab", + "clients.generated_config": "Erstellte Client-Konfiguration", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 Sekunden sind ein guter Standardwert für Clients hinter NAT.", + "clients.local_access_exceptions": "Erlaubte lokale Adressen", + "clients.local_access_exceptions_hint": "Optionale IPs oder CIDRs, die trotz Sperre ihres lokalen oder Site-to-site-Netzes erreichbar bleiben. Kommagetrennt eingeben.", + "clients.managed": "Von WGTools verwaltet", + "clients.name": "Name", + "clients.no_peers": "Keine Peers gefunden", + "clients.peers": "Peers", + "clients.peers_subtitle": "Änderungen werden gesichert und mit wg syncconf ohne Neustart der WireGuard-Schnittstelle angewendet.", + "clients.protected_networks_reference": "Gesperrte lokale Netze (Referenz)", + "clients.protected_networks_reference_hint": "Diese Netze erscheinen nicht in AllowedIPs. Der Zugriff wird durch WGTools-Serverregeln gesperrt; einzelne Adressen können oben erlaubt werden.", + "clients.psk": "Zusätzlicher Schlüssel (PSK)", + "clients.psk_enable": "Zusätzlichen WireGuard-PSK verwenden", + "clients.psk_hint": "Empfohlen. Fügt dem WireGuard-Handshake ein zusätzliches symmetrisches Geheimnis hinzu. Standard-Clients unterstützen es; WGTools fügt den PSK in Konfiguration und QR ein.", + "clients.psk_short": "PSK", + "clients.qr_loading": "QR-Code wird erstellt…", + "clients.quick_search": "Schnellsuche", + "clients.quick_search_clear": "Suche löschen", + "clients.quick_search_empty": "Keine passenden Clients gefunden", + "clients.relay_endpoint_note": "Die erstellte Client-Konfiguration verbindet sich mit {endpoint}. Der WireGuard-Server bleibt auf diesem WGTools-Host.", + "clients.relay_required": "Wähle einen VPS-Relay für diesen Client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "nicht verfügbar", + "clients.relay_vps": "VPS-Relay", + "clients.relay_vps_hint": "Der Client-Endpoint wird automatisch aus diesem Relay erstellt.", + "clients.remote_hint": "Netze hinter diesem Peer. Ein Netz pro Zeile oder durch Komma getrennt.", + "clients.remote_networks": "Entfernte Netzwerke", + "clients.remote_required": "Gib mindestens ein Remote-Netz für den Site-to-site-Peer an.", + "clients.required": "Name und VPN-Adresse sind erforderlich.", + "clients.route_custom": "Benutzerdefiniert", + "clients.route_full": "Vollständiger Tunnel", + "clients.route_full_except_local": "Vollständiger Tunnel außer lokalen Netzen", + "clients.route_hint": "Nur diese Netze werden in AllowedIPs der Client-Konfiguration geschrieben.", + "clients.route_preset": "Verkehr über VPN", + "clients.route_vpn": "Nur VPN-Netzwerk", + "clients.route_vpn_lan": "VPN + lokales LAN", + "clients.saved": "Client gespeichert", + "clients.schedule_blocked_short": "Zeitplan · gesperrt", + "clients.schedule_blocked_status": "Durch Zeitplan gesperrt", + "clients.schedule_days": "Erlaubte Tage", + "clients.schedule_days_required": "Wähle mindestens einen Tag für den Zeitplan.", + "clients.schedule_disabled_hint": "Dieser Client wird derzeit durch seinen Zeitplan gesperrt. WGTools stellt den Peer beim nächsten erlaubten Zeitfenster automatisch wieder her.", + "clients.schedule_enable": "Zugriff nach Zeitplan begrenzen", + "clients.schedule_from": "Zugriff ab", + "clients.schedule_hint": "WGTools kann diesen Client an ausgewählten Tagen und Zeiten automatisch sperren und wieder freigeben, ohne seine Konfiguration zu ändern.", + "clients.schedule_short": "Zeitplan", + "clients.schedule_time_required": "Lege Start- und Endzeit des Zeitplans fest.", + "clients.schedule_timezone_hint": "Der Zeitplan verwendet die lokale Uhrzeit des WireGuard-Servers. Zeitfenster über Mitternacht, z. B. 22:00–06:00, werden unterstützt.", + "clients.schedule_title": "Zugriffszeitplan", + "clients.schedule_to": "Zugriff bis", + "clients.security_access": "Sicherheit und Zugriffszeiten", + "clients.server_host": "Serveradresse / Domain", + "clients.server_host_hint": "Öffentliche IP oder Domain dieses Clients. Früher verwendete Werte werden vorgeschlagen.", + "clients.server_host_required": "Serveradresse / Domain ist für die Client-Konfiguration erforderlich.", + "clients.server_peer": "Server-Peer", + "clients.server_port": "WireGuard-Port", + "clients.server_port_hint": "Wird automatisch aus der Serverkonfiguration übernommen.", + "clients.site_to_site": "Standort-zu-Standort", + "clients.status": "Status", + "clients.subtitle": "WireGuard-Peers, Live-Status und Verwaltung der Client-Konfigurationen.", + "clients.tab_basic": "Grundlagen", + "clients.tab_config": "Konfiguration", + "clients.tab_policy": "Richtlinien", + "clients.tab_security": "Sicherheit", + "clients.title": "Clients", + "clients.type": "Typ", + "clients.unmanaged_note": "Dieser Peer existierte vor WGTools. Sein privater Client-Schlüssel kann nicht wiederhergestellt werden. WGTools kann den serverseitigen Peer bearbeiten, aber keine Client-Konfiguration oder QR erzeugen.", + "clients.updating": "Client wird aktualisiert…", + "common.actions": "Aktionen", + "common.ago": "vor", + "common.cancel": "Abbrechen", + "common.checking": "Prüfung läuft…", + "common.close": "Schließen", + "common.config": "Konfiguration", + "common.delete": "Löschen", + "common.disabled": "Deaktiviert", + "common.edit": "Bearbeiten", + "common.enabled": "Aktiviert", + "common.loading": "Wird geladen…", + "common.never": "Nie", + "common.no": "Nein", + "common.not_configured": "Nicht konfiguriert", + "common.not_installed": "Nicht installiert", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Aktualisieren", + "common.running": "Läuft", + "common.save": "Speichern", + "common.stopped": "Angehalten", + "common.total": "Gesamt", + "common.unknown": "Unbekannt", + "common.updated": "Aktualisiert", + "common.yes": "Ja", + "dashboard.active_peers": "Aktive Peers", + "dashboard.active_peers_subtitle": "Live-Daten aus wg show.", + "dashboard.activity": "Systemübersicht", + "dashboard.activity_subtitle": "Schreibgeschützte Prüfungen des laufenden WireGuard-Systems.", + "dashboard.cores": "Kerne", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Letzte 24 Std.", + "dashboard.history_avg": "Ø", + "dashboard.history_max": "Max.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "jetzt", + "dashboard.memory": "Arbeitsspeicher", + "dashboard.network": "Netzwerk", + "dashboard.peers": "Peers", + "dashboard.quick_search": "Schnellsuche", + "dashboard.quick_search_clear": "Suche löschen", + "dashboard.quick_search_empty": "Keine passenden Peers gefunden", + "dashboard.restart": "Neustart", + "dashboard.restart_confirm": "WireGuard neu starten? Aktive VPN-Clients werden automatisch wieder verbunden.", + "dashboard.restart_ok": "WireGuard neu gestartet.", + "dashboard.routing": "Routing", + "dashboard.site_to_site": "Standort-zu-Standort", + "dashboard.start": "Starten", + "dashboard.start_ok": "WireGuard gestartet.", + "dashboard.stop": "Stoppen", + "dashboard.stop_confirm": "WireGuard stoppen? Aktive VPN-Clients werden getrennt.", + "dashboard.stop_ok": "WireGuard gestoppt.", + "dashboard.subtitle": "WireGuard-Serverstatus, Peers und Live-Traffic.", + "dashboard.title": "Übersicht", + "dashboard.traffic": "Datenverkehr", + "dashboard.uptime": "Betriebszeit", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Server-Zugriffsregeln", + "groups.additional_allowed": "Zusätzlich erlaubte Adressen", + "groups.additional_blocked": "Zusätzlich gesperrte Adressen", + "groups.allow": "Erlauben", + "groups.allowed": "Erlaubt", + "groups.allowed_addresses": "Erlaubte Adressen / Netze", + "groups.apply_current_template": "Aktuelle Gruppenvorlage anwenden", + "groups.apply_defaults": "Aktuelle Gruppenvorlage anwenden", + "groups.apply_defaults_hint": "Übernimmt Routen, DNS und Keepalive der Gruppenvorlage für diesen Client. Client speichern und bei Bedarf neue Konfiguration oder QR ausgeben.", + "groups.basic": "Grunddaten", + "groups.block": "Sperren", + "groups.blocked": "Gesperrt", + "groups.blocked_addresses": "Gesperrte Adressen / Netze", + "groups.client_config_source": "Quelle der Client-Konfiguration", + "groups.client_defaults": "Client-Standardwerte", + "groups.client_group_hint": "Optionale Gruppe für wiederverwendbare Zugriffsregeln und Client-Standardwerte. Gruppen gelten nur für die ausgewählte WireGuard-Schnittstelle.", + "groups.config_differs": "Die Client-Konfiguration weicht von den aktuellen Gruppenvorgaben ab. Die Serverregeln sind aktuell; die Konfiguration auf Handy oder PC ändert sich erst nach Ausgabe einer neuen Konfiguration oder eines QR-Codes.", + "groups.config_differs_short": "Client-Konfiguration weicht von Gruppe ab", + "groups.create": "Gruppe erstellen", + "groups.create_title": "Gruppe erstellen", + "groups.created": "Gruppe erstellt", + "groups.creating": "Gruppe wird erstellt…", + "groups.defaults_applied": "Aktuelle Gruppenvorlage übernommen. Client zum Speichern sichern.", + "groups.defaults_hint": "Legt fest, welchen Traffic das Client-Gerät über WireGuard sendet. Die obigen Serverregeln bestimmen separat den erlaubten Zugriff. Änderungen an der Vorlage ändern nie heimlich bereits installierte Konfigurationen.", + "groups.delete_message": "„{name}“ löschen? Client-Konfigurationen werden beim Löschen einer Gruppe nie entfernt.", + "groups.delete_move": "Clients in andere Gruppe verschieben", + "groups.delete_title": "Client-Gruppe löschen", + "groups.delete_unassign": "Gruppenzuordnung der Clients entfernen", + "groups.deleted": "Gruppe gelöscht", + "groups.deleting": "Clients werden aktualisiert und Gruppe gelöscht…", + "groups.description": "Beschreibung", + "groups.edit_title": "Gruppe bearbeiten", + "groups.editor_subtitle": "Eine Gruppe kombiniert aktive Server-Zugriffsregeln mit einer Vorlage für neue Client-Konfigurationen.", + "groups.effective_allow": "Erlaubte Ausnahmen", + "groups.effective_deny": "Gesperrte Ausnahmen", + "groups.effective_policy": "Wirksame Serverregeln", + "groups.empty": "Noch keine Client-Gruppen. Erstelle eine Gruppe, um Zugriffsregeln und Client-Standardwerte wiederzuverwenden.", + "groups.group": "Gruppe", + "groups.inherit": "Übernehmen", + "groups.internet_access": "Internetzugriff", + "groups.internet_short": "Internet", + "groups.local_access": "Lokale Netzwerke", + "groups.local_short": "Lokal", + "groups.manage": "Gruppen", + "groups.members_count": "{count} Clients", + "groups.name": "Name", + "groups.name_required": "Gruppenname erforderlich.", + "groups.new_client_defaults": "Client-Konfigurationsvorlage", + "groups.new_clients_short": "Neue Clients", + "groups.no_group": "Keine Gruppe", + "groups.none": "Keine", + "groups.override_client_config": "Gruppenvorlage für diesen Client überschreiben", + "groups.override_client_config_hint": "Aus: Routen, DNS und Keepalive kommen aus der Gruppenvorlage. Ein: Dieser Client nutzt eigene Werte. Änderungen an den Serverregeln oben bleiben unabhängig.", + "groups.policy_addresses_hint": "IPv4-Adressen oder CIDRs, durch Komma getrennt. Client-Ausnahmen haben Vorrang vor Gruppenausnahmen.", + "groups.policy_custom": "Eigene Regeln", + "groups.policy_inherit": "Gruppenregeln verwenden", + "groups.policy_mode": "Regelquelle", + "groups.policy_mode_hint": "Standardmäßig gelten die Gruppenregeln. Client-Ausnahmen ändern nie die Gruppe selbst.", + "groups.routes_required": "Client-Routen dürfen nicht leer sein.", + "groups.subtitle": "Server-Zugriffsregeln und Standardwerte für normale Clients auf der gewählten WireGuard-Schnittstelle wiederverwenden.", + "groups.title": "Client-Gruppen", + "groups.traffic_through_vpn": "Verkehr über VPN", + "groups.updated": "Gruppe aktualisiert", + "groups.updating": "Gruppenregeln werden aktualisiert…", + "help.example_note": "Alle Adressen, Schnittstellen, Peer-Namen und Domains in der Hilfe sind fiktiv. Ersetze sie durch Werte aus deinem Netzwerk.", + "help.navigation": "Hilfe-Navigation", + "help.open": "Hilfe öffnen", + "help.subtitle": "Verständliche Hilfe für Dashboard, Server, Clients und Einstellungen mit kurzen Beispielen.", + "help.title": "WGTools-Hilfe", + "interfaces.add": "+ Schnittstelle hinzufügen", + "interfaces.create": "Schnittstelle erstellen", + "interfaces.create_confirm": "Schnittstelle {name} erstellen und starten?", + "interfaces.create_failed": "Schnittstelle konnte nicht erstellt werden", + "interfaces.create_hint": "WGTools prüft vor der Erstellung, dass VPN-Netz, UDP-Port und Policy-Routing-Tabelle nicht mit anderen WireGuard-Schnittstellen kollidieren.", + "interfaces.create_subtitle": "Eine unabhängige WireGuard-Schnittstelle mit eigenem Adresspool, UDP-Port und Routing-Einstellungen erstellen.", + "interfaces.create_title": "WireGuard-Schnittstelle hinzufügen", + "interfaces.created": "Schnittstelle erfolgreich erstellt.", + "interfaces.creating": "Schlüssel werden erzeugt, Konfiguration gespeichert und WireGuard gestartet…", + "interfaces.current": "Aktuell", + "interfaces.delete": "Löschen", + "interfaces.delete_confirm": "Schnittstelle {name} löschen? Ihre WireGuard-Konfiguration und alle Peers werden entfernt. Zuvor wird ein Backup erstellt.", + "interfaces.delete_failed": "Schnittstelle konnte nicht gelöscht werden", + "interfaces.delete_last": "Die letzte konfigurierte WireGuard-Schnittstelle kann hier nicht gelöscht werden.", + "interfaces.delete_tooltip": "Diese WireGuard-Schnittstelle löschen", + "interfaces.deleted": "Schnittstelle gelöscht. Backup: {backup}", + "interfaces.deleting": "WireGuard wird gestoppt und Schnittstelle gelöscht…", + "interfaces.display_name": "Anzeigename", + "interfaces.display_name_edit_hint": "Nur Anzeigename; der Linux-Schnittstellenname bleibt unverändert.", + "interfaces.display_name_hint": "Optionaler Anzeigename, z. B. Arbeit oder Auftragnehmer.", + "interfaces.identity": "Schnittstellenkennung", + "interfaces.none": "Keine WireGuard-Schnittstellen gefunden", + "interfaces.none_configured": "Noch keine WireGuard-Schnittstellen konfiguriert.", + "interfaces.peers_short": "Peers", + "interfaces.rename_failed": "Anzeigename der Schnittstelle konnte nicht gespeichert werden.", + "interfaces.select": "Auswählen", + "interfaces.subtitle": "Jede Schnittstelle hat ein eigenes VPN-Netz, einen Port, Peers und Regeln. Wähle eine, um sie in WGTools zu verwalten.", + "interfaces.switch_title": "WireGuard-Schnittstellen", + "interfaces.system_name": "Systemname", + "interfaces.system_name_hint": "Linux-Schnittstellenname, z. B. wg1. Nach der Erstellung unveränderbar.", + "interfaces.title": "WireGuard-Schnittstellen", + "interfaces.unique_port_hint": "Jede WireGuard-Schnittstelle auf diesem Server muss einen eigenen UDP-Port verwenden.", + "interfaces.unique_table_hint": "WGTools empfiehlt eine eigene Routing-Tabelle pro Schnittstelle. Für normales Routing leer lassen.", + "nav.clients": "Clients", + "nav.dashboard": "Übersicht", + "nav.server": "Server", + "nav.settings": "Einstellungen", + "server.access_apply_confirm": "Diese Firewall-Regel speichern und anwenden? WireGuard wird kurz neu gestartet und ein Backup erstellt.", + "server.access_rule_deleted": "Zugriffsregel gelöscht.", + "server.access_rule_help": "Allgemeine FORWARD-Zugriffsregel erstellen, ohne iptables-Befehle manuell zu bearbeiten.", + "server.access_rule_order_hint": "WGTools fügt Zugriffsregeln am Anfang der FORWARD-Kette ein, damit Einschränkungen vor allgemeinen VPN-ACCEPT-Regeln greifen.", + "server.access_rule_saved": "Zugriffsregel gespeichert und angewendet.", + "server.action": "Aktion", + "server.action_hint": "REJECT meldet dem Client die Ablehnung; DROP verwirft still; ACCEPT erlaubt ausdrücklich.", + "server.add_access_rule": "Zugriffsregel hinzufügen", + "server.add_route": "Route hinzufügen", + "server.address": "Adresse", + "server.any": "Beliebig", + "server.any_protocol": "Beliebig", + "server.apply_confirm": "Servereinstellungen speichern und anwenden? WireGuard wird kurz neu gestartet. Zuvor erstellt WGTools ein Backup und stellt bei Startfehlern automatisch die vorherige Konfiguration wieder her.", + "server.apply_settings": "Speichern und anwenden", + "server.applying_rule": "Backup wird erstellt und Änderungen angewendet…", + "server.applying_settings": "Einstellungen werden geprüft, Backup erstellt und angewendet…", + "server.basic_settings": "Grundeinstellungen", + "server.config_tab_help": "Rohkonfigurationseditor der ausgewählten WireGuard-Schnittstelle öffnen.", + "server.create_confirm": "WireGuard-Server mit diesen Einstellungen erstellen und starten?", + "server.create_server": "Server erstellen", + "server.create_step_conf": "Konfiguration der ausgewählten WireGuard-Schnittstelle mit Modus 600 erstellen.", + "server.create_step_forward": "Forwarding, NAT und optionales Policy-Routing einrichten.", + "server.create_step_key": "Neues Server-Schlüsselpaar erzeugen.", + "server.create_step_start": "Ausgewählte wg-quick-Schnittstelle aktivieren und starten.", + "server.create_subtitle": "WireGuard ist installiert, aber die ausgewählte Schnittstelle ist noch nicht konfiguriert.", + "server.create_success": "WireGuard-Server erfolgreich erstellt.", + "server.create_title": "WireGuard-Server erstellen", + "server.creating": "Schlüssel werden erzeugt, Konfiguration gespeichert und WireGuard gestartet…", + "server.custom_preserved": "Peer-Blöcke, Site-to-site-Routen und eigene PostUp/PostDown-Regeln außerhalb dieser Felder bleiben erhalten.", + "server.delete_access_confirm": "Diese Zugriffsregel löschen und Änderung anwenden?", + "server.delete_route_confirm": "Diese eigene Route löschen und Änderung anwenden?", + "server.destination": "Ziel", + "server.destination_hint": "Leer = beliebig. IP, CIDR oder IP-Bereich. Mehrere Ziele durch Komma trennen.", + "server.destination_port": "Zielport", + "server.destination_port_hint": "Optional. Port wie 443 oder Bereich wie 10000:20000. Erst TCP oder UDP auswählen.", + "server.details": "Details", + "server.dev_word": "dev", + "server.diagnostics": "Diagnose", + "server.diagnostics_done": "Diagnose abgeschlossen", + "server.diagnostics_subtitle": "Aktuelle Systemprüfungen. Keine Konfigurationsänderung.", + "server.direction": "Hook", + "server.edit_access_rule": "Zugriffsregel bearbeiten", + "server.edit_route": "Route bearbeiten", + "server.edit_server": "Server bearbeiten", + "server.edit_subtitle": "Allgemeine WireGuard-, Routing- und NAT-Einstellungen bearbeiten. Vorhandene Peers und eigene Regeln bleiben erhalten.", + "server.edit_title": "Servereinstellungen", + "server.edit_warning": "Beim Anwenden von Schnittstellen-, Routing- oder Firewall-Einstellungen wird WireGuard kurz neu gestartet. Aktive Peers verbinden sich automatisch neu.", + "server.enable_forwarding": "IPv4-Forwarding aktivieren", + "server.enable_nat": "NAT / Masquerade aktivieren", + "server.firewall": "Firewall & NAT", + "server.firewall_subtitle": "Erkannte Regeln aus WireGuard-Hooks.", + "server.firewall_subtitle_v08": "Allgemeine Forwarding-/NAT- und Zugriffsregeln der Schnittstelle. Einfache Regeln können hier bearbeitet werden, komplexe im Rohkonfigurationseditor.", + "server.forward_from_vpn": "Weiterleitung aus VPN erlauben", + "server.forward_to_vpn": "Weiterleitung ins VPN erlauben", + "server.forwarding_section": "Forwarding und NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Nur bei Verwendung einer Policy-Routing-Tabelle erforderlich.", + "server.install_success": "WireGuard erfolgreich installiert.", + "server.install_wireguard": "WireGuard installieren", + "server.install_wireguard_help": "Führt apt update aus und installiert WireGuard sowie benötigte Netzwerktools.", + "server.install_wireguard_title": "WireGuard installieren", + "server.installing": "WireGuard wird installiert… Kann eine Minute dauern.", + "server.interface": "Schnittstelle", + "server.interface_hint": "WGTools verwaltet derzeit diese Schnittstelle.", + "server.interface_name": "Schnittstelle", + "server.interface_section": "WireGuard-Schnittstelle", + "server.ip_forwarding": "IPv4-Forwarding", + "server.kind": "Art", + "server.listen_port": "Listen-Port", + "server.local_network": "Lokales Netz", + "server.local_network_hint": "Optionale Route zur Policy-Tabelle hinzufügen.", + "server.managed_automatically": "Automatisch verwaltet", + "server.nat": "NAT / Masquerade", + "server.network": "Netzwerk", + "server.network_settings": "Netzwerk und NAT", + "server.no_firewall": "Keine Firewall-Regeln gefunden", + "server.no_routes": "Keine Routen gefunden", + "server.not_configured": "Nicht konfiguriert", + "server.not_set": "Nicht gesetzt", + "server.policy_disabled_hint": "Für normales System-Routing deaktivieren. Nur aktivieren, wenn dieses VPN eine eigene quellbasierte Routing-Tabelle benötigt.", + "server.policy_enabled": "Policy-Routing aktivieren", + "server.policy_table": "Policy-Tabelle", + "server.policy_table_hint": "Für normales Routing leer lassen; für quellbasiertes Policy-Routing z. B. 200 verwenden.", + "server.port_word": "Port", + "server.private_hidden": "Konfiguriert (ausgeblendet)", + "server.private_key": "Privater Schlüssel", + "server.protocol": "Protokoll", + "server.route_apply_confirm": "Diese Route speichern und anwenden? WireGuard wird kurz neu gestartet und ein Backup erstellt.", + "server.route_custom": "Benutzerdefiniert", + "server.route_deleted": "Route gelöscht.", + "server.route_device_hint": "Optionale Ausgabeschnittstelle, z. B. wg0 oder enp6s18.", + "server.route_editor_help": "Route hinzufügen, die beim WireGuard-Start erstellt und beim Stoppen entfernt wird.", + "server.route_gateway_hint": "Optionales Next-Hop-Gateway. Gateway oder Schnittstelle ist erforderlich.", + "server.route_managed_peer": "Site-to-site-Peer", + "server.route_managed_server": "Servereinstellung", + "server.route_network_hint": "IPv4-Netz, z. B. 10.20.0.0/24, oder 'default'.", + "server.route_saved": "Route gespeichert und angewendet.", + "server.route_table_hint": "Für normales Routing 'main' oder eine numerische Tabelle wie 200 verwenden.", + "server.route_type": "Typ", + "server.routes": "Erkannte Routen", + "server.routes_subtitle": "Aus PostUp/PostDown und aktuellem Policy-Routing gelesene Routen.", + "server.routes_subtitle_v08": "Server-, Site-to-site- und eigene Routen der ausgewählten Schnittstelle. Eigene Routen können hier erstellt, bearbeitet und entfernt werden.", + "server.routing": "Routing", + "server.routing_section": "Routing", + "server.rule": "Regel", + "server.rule_access": "Zugriffsregel", + "server.rule_advanced": "Erweitert", + "server.rule_apply_warning": "Beim Anwenden einer Route oder Firewall-Regel wird WireGuard kurz neu gestartet. WGTools erstellt ein Backup und stellt die vorherige Konfiguration bei Startfehlern automatisch wieder her.", + "server.rule_client_exception": "Ausnahme für Client", + "server.rule_client_policy": "Client-Regel", + "server.rule_managed_server": "Servereinstellung", + "server.rule_type": "Typ", + "server.run_diagnostics": "Diagnose starten", + "server.save_apply": "Speichern und anwenden", + "server.save_config": "SaveConfig", + "server.server_address": "Server-VPN-Adresse", + "server.server_address_hint": "Gewöhnlich die erste nutzbare Adresse im VPN-Netz.", + "server.settings_applied": "Servereinstellungen erfolgreich gespeichert und angewendet.", + "server.settings_apply_failed": "Servereinstellungen konnten nicht angewendet werden", + "server.setup_required": "Einrichtung erforderlich", + "server.source": "Quelle", + "server.source_hint": "Leer = beliebig. IP, CIDR oder Bereich wie 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installation, Ersteinrichtung und aktuelle Konfiguration des WireGuard-Servers.", + "server.tab_config": "Konfiguration", + "server.tab_interface": "Schnittstelle", + "server.tab_routing": "Routing", + "server.tab_vps": "VPS", + "server.table": "Tabelle", + "server.tabs_aria": "Abschnitte der Servereinstellungen", + "server.title": "Server", + "server.uplink": "Uplink-Schnittstelle", + "server.use_raw_editor": "Rohkonfigurationseditor verwenden", + "server.via": "Über / Gerät", + "server.via_word": "via", + "server.vpn_network": "VPN-Netzwerk", + "server.vpn_network_hint": "Client-Adressen werden später aus diesem Netz vergeben.", + "server.vpn_pool": "VPN-Adresspool", + "server.wg_not_installed": "WireGuard ist nicht installiert", + "server.wg_not_installed_subtitle": "WGTools kann die benötigten Debian-Pakete automatisch installieren.", + "server.what_happens": "Was WGTools ausführt", + "settings.about": "Über", + "settings.add_user": "Benutzer hinzufügen", + "settings.advanced": "Erweitert", + "settings.advanced_subtitle": "Direkter Zugriff auf erweiterte WireGuard-Konfiguration.", + "settings.appearance": "Darstellung", + "settings.applying_config": "Konfiguration wird geprüft, Backup erstellt und angewendet…", + "settings.backup_count": "Gespeicherte Backups", + "settings.backup_retention": "Anzahl aufzubewahrender Backups", + "settings.backup_retention_help": "Alte automatische Backups werden nach Erstellung eines neuen Backups entfernt. 1–200 Dateien.", + "settings.backups": "Konfigurations-Backups", + "settings.backups_always_on": "Aktiviert", + "settings.backups_subtitle": "WGTools erstellt vor Änderungen an der Konfiguration automatisch ein Backup. Automatische Backups können nicht deaktiviert werden.", + "settings.change_password": "Passwort ändern", + "settings.check_updates": "Auf Updates prüfen", + "settings.config_applied": "Konfiguration erfolgreich gespeichert und angewendet.", + "settings.config_applied_restarted": "Konfiguration angewendet, WireGuard neu gestartet.", + "settings.config_applied_stopped": "Konfiguration gespeichert. WireGuard war gestoppt und bleibt gestoppt.", + "settings.config_apply_failed": "Konfiguration konnte nicht angewendet werden", + "settings.config_load_failed": "Konfiguration konnte nicht geladen werden", + "settings.current_user": "Aktueller Benutzer", + "settings.current_version": "Aktuelle Version", + "settings.audit_action": "Aktion", + "settings.audit_empty": "Noch keine Audit-Ereignisse", + "settings.audit_log": "Audit-Protokoll", + "settings.audit_log_subtitle": "Aktionen im Panel, Anmeldungen, Telegram und WireGuard-Verbindungsverlauf. Geheimnisse werden hier nie protokolliert.", + "settings.audit_object": "Objekt", + "settings.audit_result": "Ergebnis", + "settings.audit_retention_note": "Aufbewahrung: 30 Tage", + "settings.audit_search": "Schnellsuche", + "settings.audit_search_clear": "Suche löschen", + "settings.audit_search_empty": "Keine passenden Audit-Ereignisse", + "settings.audit_time": "Datum / Uhrzeit", + "settings.audit_user": "Benutzer", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Zugriffsregel erstellt", + "audit.action.access_rule.deleted": "Zugriffsregel gelöscht", + "audit.action.access_rule.updated": "Zugriffsregel geändert", + "audit.action.auth.first_user_created": "Erster Benutzer erstellt", + "audit.action.auth.login": "Angemeldet", + "audit.action.auth.login_failed": "Anmeldung fehlgeschlagen", + "audit.action.auth.logout": "Abgemeldet", + "audit.action.backup.full_created": "Vollständiges Backup erstellt", + "audit.action.backup.full_restored": "Vollständiges Backup wiederhergestellt", + "audit.action.client.config_downloaded": "Client-Konfiguration heruntergeladen", + "audit.action.client.config_viewed": "Client-Konfiguration angezeigt", + "audit.action.client.created": "Client erstellt", + "audit.action.client.deleted": "Client gelöscht", + "audit.action.client.qr_viewed": "Client-QR-Code angezeigt", + "audit.action.client.updated": "Client aktualisiert", + "audit.action.client_group.created": "Client-Gruppe erstellt", + "audit.action.client_group.deleted": "Client-Gruppe gelöscht", + "audit.action.client_group.updated": "Client-Gruppe aktualisiert", + "audit.action.interface.created": "Schnittstelle erstellt", + "audit.action.interface.deleted": "Schnittstelle gelöscht", + "audit.action.interface.renamed": "Schnittstelle umbenannt", + "audit.action.route.created": "Route erstellt", + "audit.action.route.deleted": "Route gelöscht", + "audit.action.route.updated": "Route aktualisiert", + "audit.action.server.created": "Server erstellt", + "audit.action.server.raw_config_applied": "Rohkonfiguration angewendet", + "audit.action.server.settings_applied": "Servereinstellungen angewendet", + "audit.action.settings.updated": "Panel-Einstellungen geändert", + "audit.action.telegram.action_denied": "Telegram-Aktion verweigert", + "audit.action.telegram.action_failed": "Telegram-Aktion fehlgeschlagen", + "audit.action.telegram.connection_test": "Telegram-Verbindungstest", + "audit.action.telegram.settings_updated": "Telegram-Einstellungen geändert", + "audit.action.update.checked": "Auf Update geprüft", + "audit.action.update.scheduled": "Update geplant", + "audit.action.update.backup_created": "Backup vor Update", + "audit.action.update.completed": "Update abgeschlossen", + "audit.action.update.failed": "Update fehlgeschlagen", + "audit.action.update.rollback_completed": "Vorherige Version wiederhergestellt", + "audit.action.update.rollback_failed": "Update-Rollback fehlgeschlagen", + "audit.action.user.created": "Benutzer erstellt", + "audit.action.user.deleted": "Benutzer gelöscht", + "audit.action.user.password_changed": "Benutzerpasswort geändert", + "audit.action.vps.candidate_deleted": "VPS-Kandidat gelöscht", + "audit.action.vps.candidate_saved": "VPS-Kandidat gespeichert", + "audit.action.vps.detached": "VPS-Relay getrennt", + "audit.action.vps.relay_installed": "VPS-Relay installiert", + "audit.action.wireguard.client_connected": "WireGuard-Client verbunden", + "audit.action.wireguard.installed": "WireGuard installiert", + "audit.action.wireguard.restarted": "WireGuard neu gestartet", + "audit.action.wireguard.started": "WireGuard gestartet", + "audit.action.wireguard.stopped": "WireGuard gestoppt", + "audit.result.applied": "angewendet", + "audit.result.available": "verfügbar", + "audit.result.changed": "geändert", + "audit.result.created": "erstellt", + "audit.result.current": "aktuell", + "audit.result.deleted": "gelöscht", + "audit.result.detached": "getrennt", + "audit.result.denied": "verweigert", + "audit.result.downloaded": "heruntergeladen", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Fehler", + "audit.result.installed": "installiert", + "audit.result.invalid_credentials": "ungültige Zugangsdaten", + "audit.result.ok": "OK", + "audit.result.queued": "in Warteschlange", + "audit.result.restarted": "neu gestartet", + "audit.result.restored": "wiederhergestellt", + "audit.result.rotated": "erneuert", + "audit.result.saved": "gespeichert", + "audit.result.shown": "angezeigt", + "audit.result.started": "gestartet", + "audit.result.stopped": "gestoppt", + "audit.result.updated": "aktualisiert", + "settings.delete_user": "Löschen", + "settings.delete_user_confirm": "Benutzer {name} löschen?", + "settings.edit_raw_config": "Schnittstellenkonfiguration bearbeiten", + "settings.expert_mode": "Experte", + "settings.full_backup_component_clients": "Von WGTools verwaltete Client-Metadaten, private Schlüssel, PSKs, Ablaufzeiten und Gruppenzuordnungen zur Wiederherstellung von Konfigurationen/QR-Codes.", + "settings.full_backup_component_db": "WGTools-Datenbank: Benutzer, App-Einstellungen, E-Mail/SMTP, Telegram und gespeicherter VPS-Relay-Status.", + "settings.full_backup_component_relay": "VPS-Relay-Wiederherstellungsdaten: Controller-/Tenant-IDs, Verwaltungstoken und Home-Transportschlüssel. Danach kann WGTools den lokalen Transport wieder aufbauen und sich mit dem bestehenden VPS-Tenant verbinden.", + "settings.full_backup_component_system": "WGTools-sysctl-Datei für IPv4-Forwarding, Anzeigenamen der Schnittstellen sowie Gruppenregeln und Standardvorlagen (falls vorhanden). Der automatische Konfigurationsverlauf je Schnittstelle ist absichtlich ausgeschlossen.", + "settings.full_backup_component_wg": "Alle erkannten WireGuard-Schnittstellenkonfigurationen aus /etc/wireguard/ samt Status (gestartet/gestoppt).", + "settings.full_backup_create_failed": "Vollständiges Backup konnte nicht erstellt werden", + "settings.full_backup_creating": "Vollständiges Backup wird erstellt…", + "settings.full_backup_download": "Erstellen", + "settings.full_backup_downloaded": "Backup erstellt und heruntergeladen. Sicher aufbewahren.", + "settings.full_backup_downloaded_short": "Vollständiges Backup heruntergeladen.", + "settings.full_backup_help": "Erstellt ein übertragbares WGTools-Backup für Umzug oder Notfall. Enthält WireGuard-Konfigurationen, Benutzer, Einstellungen, Gruppen, verwaltete Clients und Daten zum Wiederverbinden bestehender VPS-Relay-Tenants.", + "settings.full_backup_no_file": "Kein Backup ausgewählt", + "settings.full_backup_restore": "Wiederherstellen", + "settings.full_backup_restore_confirm": "Vollständiges WGTools-Backup wiederherstellen? Aktuelle Benutzer, Einstellungen, verwaltete Clients und alle im Backup enthaltenen WireGuard-Konfigurationen werden ersetzt. Schnittstellen können neu starten. WGTools erstellt vorher ein Sicherheitsbackup und stellt bei Fehlern den vorherigen Zustand wieder her.", + "settings.full_backup_restore_failed": "Wiederherstellung fehlgeschlagen", + "settings.full_backup_restored": "Backup erfolgreich wiederhergestellt. Melde dich mit einem Konto aus dem Backup an.", + "settings.full_backup_restored_short": "Backup wiederhergestellt.", + "settings.full_backup_restoring": "Backup wird geprüft, Sicherheitskopie erstellt und wiederhergestellt…", + "settings.full_backup_secret_warning": "Diese Datei enthält geheime Daten: private WireGuard- und Client-Schlüssel, PSKs, WGTools-Passworthashes, Telegram-Bot-Token und gespeichertes SMTP-Passwort. Wie ein Passwort schützen und niemals an öffentliche Issues oder Chats anhängen.", + "settings.full_backup_select": "Auswählen", + "settings.full_backup_title": "Vollständiges Backup und Wiederherstellung", + "settings.full_mode": "Server- und Client-Verwaltung aktiviert", + "settings.interface_help": "Die verwaltete WireGuard-Schnittstelle wird bei der WGTools-Installation ausgewählt.", + "settings.language": "Sprache", + "settings.last_backup": "Letztes Backup", + "settings.latest_version": "Neueste Version", + "settings.loading_config": "Konfiguration wird geladen…", + "settings.mode": "Modus", + "settings.never_logged_in": "Nie", + "settings.new_password": "Neues Passwort", + "settings.no_backups": "Noch keine Backups", + "settings.online_help": "Ein Peer gilt als online, wenn sein letzter Handshake jünger als dieser Wert ist. 30–3600 Sekunden.", + "settings.online_threshold": "Online-Schwelle", + "settings.open_release": "Release öffnen", + "settings.password_changed": "Passwort geändert.", + "settings.passwords_mismatch": "Passwörter stimmen nicht überein.", + "settings.project_github": "Projekt / GitHub", + "settings.raw_config_confirm": "WireGuard-Konfiguration speichern und anwenden? Die ausgewählte Schnittstelle wird neu gestartet. Zuvor wird ein Backup erstellt. Bei Startfehlern stellt WGTools den vorherigen Zustand automatisch wieder her.", + "settings.raw_config_help": "Quellkonfiguration der ausgewählten WireGuard-Schnittstelle öffnen.", + "settings.raw_config_title": "WireGuard-Rohkonfiguration", + "settings.raw_config_warning": "Expertenmodus: Dies ist die echte WireGuard-Serverkonfiguration einschließlich privatem Server-Schlüssel und Peer-PSKs. Speichern und Anwenden startet die Schnittstelle neu. WGTools erstellt vorher ein Backup und stellt bei Startfehlern automatisch wieder her.", + "settings.readonly_mode": "Client-Verwaltung aktiviert", + "settings.refresh_help": "Intervall der Live-Statusabfrage durch WGTools. 2–60 Sekunden.", + "settings.refresh_interval": "Aktualisierungsintervall", + "settings.release_notes": "Versionshinweise", + "settings.reload_config": "Von Datenträger neu laden", + "settings.save_apply": "Speichern und anwenden", + "settings.saved": "Einstellungen gespeichert.", + "settings.saved_reload": "Einstellungen gespeichert. Seite wird neu geladen…", + "settings.saving": "Einstellungen werden gespeichert…", + "settings.status": "Statusaktualisierung", + "settings.status_help": "Aktualisierungsintervall für Dashboard und Peer-Status.", + "settings.subtitle": "WGTools-Oberfläche und Status-Einstellungen.", + "settings.syntax_hint": "WireGuard-Abschnitte, Schlüssel, Werte und Kommentare werden beim Bearbeiten hervorgehoben.", + "settings.tab_about": "Über", + "settings.tab_backups": "Backups", + "settings.tab_general": "Allgemein", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Benutzer", + "settings.tabs_aria": "Einstellungsbereiche", + "settings.telegram": "Telegram-Bot", + "settings.telegram_allowed_ids": "Zugelassene Telegram-Benutzer-IDs", + "settings.telegram_allowed_ids_help": "Eine numerische Benutzer-ID pro Zeile. Ein nicht autorisierter /start-Aufruf zeigt die Telegram-ID des Absenders, die du hier hinzufügen kannst.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Verbunden", + "settings.telegram_disabled": "Deaktiviert", + "settings.telegram_dns": "Standard-Client-DNS", + "settings.telegram_dns_help": "Optionale IPv4-DNS-Adressen, durch Komma getrennt. Für vom Bot erstellte Clients.", + "settings.telegram_enabled": "Telegram-Bot aktivieren", + "settings.telegram_endpoint": "Standard-Serveradresse / Domain", + "settings.telegram_endpoint_help": "Für neue Client-Konfigurationen des Bots. Nur IP oder Domain eingeben; WireGuard-Port wird aus der Serverkonfiguration gelesen.", + "settings.telegram_language": "Bot-Sprache", + "settings.telegram_language_auto": "Automatisch (Telegram-Sprache)", + "settings.telegram_last_poll": "Letzter Telegram-Kontakt", + "settings.telegram_not_configured": "Nicht konfiguriert", + "settings.telegram_remove_token": "Token entfernen", + "settings.telegram_remove_token_confirm": "Gespeicherten Telegram-Bot-Token entfernen und Bot deaktivieren?", + "settings.telegram_save": "Telegram-Einstellungen speichern", + "settings.telegram_saved": "Telegram-Einstellungen gespeichert.", + "settings.telegram_setup_note": "Bot mit @BotFather erstellen, Token speichern, Bot aktivieren und /start senden. Falls deine Benutzer-ID nicht autorisiert ist, zeigt WGTools sie an — füge sie zur Liste zugelassener Telegram-IDs hinzu.", + "settings.telegram_status": "Bot-Status", + "settings.telegram_subtitle": "WireGuard-Verwaltung über Telegram: Serverstatus, Clients, Erstellen/Löschen und Start/Neustart/Stopp.", + "settings.telegram_test": "Verbindung testen", + "settings.telegram_test_ok": "Telegram-Verbindung funktioniert: @{username}", + "settings.telegram_test_recent_ok": "Telegram-Bot funktioniert. Direkte Prüfung hat Zeitlimit überschritten, aber Bot hat Telegram kürzlich erreicht.", + "settings.telegram_token": "Bot-Token", + "settings.telegram_token_help": "Bot mit @BotFather erstellen und Bot-API-Token hier einfügen. API ID und API Hash sind für die Telegram Bot API nicht nötig.", + "settings.telegram_token_keep": "Leer lassen, um gespeicherten Token zu behalten.", + "settings.telegram_waiting": "Konfiguriert, wartet auf Bot-Dienst", + "settings.theme": "Darstellung", + "settings.theme_dark": "Dunkel", + "settings.theme_light": "Hell", + "settings.theme_system": "System", + "settings.title": "Einstellungen", + "settings.update_available": "Update verfügbar", + "settings.update_backup_queued": "Update vorgemerkt. WGTools erstellt vor Installation automatisch ein vollständiges Backup…", + "settings.update_backup_running": "Vollständiges Backup vor Update wird erstellt…", + "settings.update_check_failed": "Prüfung auf Updates fehlgeschlagen", + "settings.update_checking": "Neueste veröffentlichte GitHub Release wird geprüft…", + "settings.update_confirm": "WGTools von v{current} auf v{latest} aktualisieren? Zuvor werden ein vollständiges Backup und eine Rollback-Kopie erstellt. Die Weboberfläche wird kurz neu gestartet.", + "settings.update_current": "Aktuell", + "settings.update_downloading": "GitHub-Release wird heruntergeladen und geprüft…", + "settings.update_failed": "WGTools-Update fehlgeschlagen.", + "settings.update_installing": "Update wird installiert. Die Weboberfläche kann kurz nicht erreichbar sein…", + "settings.update_no_update": "WGTools ist bereits auf dem neuesten Stand.", + "settings.update_not_checked": "Nicht geprüft", + "settings.update_queued": "Update vorgemerkt. Warte auf den Update-Dienst…", + "settings.update_rollback_ok": "Vorherige WGTools-Version wurde automatisch wiederhergestellt.", + "settings.update_rolling_back": "Update fehlgeschlagen. Vorherige WGTools-Version wird wiederhergestellt…", + "settings.update_running": "Sicherheits-Backups werden erstellt…", + "settings.update_safety_hint": "Updates erfolgen nur auf Wunsch. WGTools erstellt vor der Installation ein vollständiges Backup und eine Rollback-Kopie. Bei Fehlern wird die vorherige Anwendung automatisch wiederhergestellt. WireGuard selbst wird nur neu gestartet, wenn das neue Release ausdrücklich seine Konfiguration ändert.", + "settings.update_sidebar": "Neue Version verfügbar", + "settings.update_sidebar_hint": "Einstellungen → Über", + "settings.update_starting": "Update wird gestartet…", + "settings.update_status_unknown": "Update-Status nicht verfügbar. Neuer Versuch…", + "settings.update_subtitle": "Projektinformationen, automatische Release-Prüfung und sichere Updates über GitHub Releases.", + "settings.update_success": "WGTools erfolgreich auf v{version} aktualisiert. Seite wird neu geladen…", + "settings.update_wgtools": "WGTools aktualisieren", + "settings.user_actions": "Aktionen", + "settings.user_created": "Erstellt", + "settings.user_created_ok": "Benutzer erstellt.", + "settings.user_deleted": "Benutzer gelöscht.", + "settings.user_equal_rights": "Alle WGTools-Benutzer haben dieselben Berechtigungen.", + "settings.user_last_login": "Letzte Anmeldung", + "settings.user_name": "Benutzername", + "settings.users": "Benutzer", + "settings.users_subtitle": "Lokale WGTools-Konten. E-Mail ist optional und wird bei aktivierter E-Mail-Funktion nur für Passwortwiederherstellung genutzt.", + "vps.add": "VPS hinzufügen", + "vps.add_help": "WGTools prüft oder installiert Relay per SSH. Passwörter und private SSH-Schlüssel werden nie gespeichert.", + "vps.add_title": "VPS hinzufügen", + "vps.agent": "Relay-Agent", + "vps.agent_found": "Bereits installiert", + "vps.agent_will_install": "Wird installiert", + "vps.arch": "Architektur", + "vps.auth_method": "Authentifizierung", + "vps.authentication": "SSH-Authentifizierung", + "vps.check": "VPS prüfen", + "vps.check_failed": "VPS-Prüfung fehlgeschlagen", + "vps.check_link": "Verbindung prüfen", + "vps.check_ok": "VPS ist kompatibel", + "vps.checking": "SSH-Zugang und VPS-Kompatibilität werden geprüft…", + "vps.connections": "Verbindungen", + "vps.credentials_not_saved": "Nur für diese Prüfung verwendet und nicht von WGTools gespeichert.", + "vps.delete_candidate": "Entfernen", + "vps.delete_installed": "VPS entfernen", + "vps.delete_installed_confirm": "„{name}“ aus WGTools entfernen? Der lokale Relay-Transport wird getrennt, aber Relay-Agent und Tenant bleiben auf dem VPS erhalten. Wenn du den VPS erneut hinzufügst, verbindet sich WGTools mit dem bestehenden Relay, statt einen neuen zu erstellen. Clients dieses Relay können bis zur Wiederverbindung nicht darauf zugreifen.", + "vps.delete_installed_failed": "VPS konnte nicht aus WGTools entfernt werden", + "vps.delete_installed_ok": "VPS aus WGTools entfernt. Remote-Relay bleibt erhalten und kann wiederverbunden werden.", + "vps.empty_help": "Füge einen Debian- oder Ubuntu-VPS hinzu, um SSH-Zugang, Systemkompatibilität und erforderliche UDP-Ports zu prüfen.", + "vps.empty_title": "Kein VPS eingerichtet", + "vps.endpoint": "Öffentlicher Endpoint", + "vps.endpoint_domain": "Domain (empfohlen)", + "vps.endpoint_domain_hint": "Wenn du später den Haupt-VPS austauschst, können Client-Konfigurationen durch eine DNS-Änderung unverändert bleiben.", + "vps.health_failed": "Relay-Verbindungsprüfung fehlgeschlagen", + "vps.host": "IP / Hostname", + "vps.host_key": "SSH-Hostschlüssel", + "vps.identity": "VPS-Verbindung", + "vps.install_failed": "Relay-Installation fehlgeschlagen", + "vps.install_ok": "Relay installiert und geschützte Verwaltungsverbindung geprüft", + "vps.install_relay": "Relay installieren", + "vps.install_title": "VPS-Relay installieren", + "vps.installed": "Installiert", + "vps.installing": "Relay-Agent wird installiert und geschützter Transporttunnel aufgebaut…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Schlüssel-Passphrase", + "vps.link_ok": "Relay-Verbindung OK", + "vps.multi_tenant_note": "Auf diesem VPS läuft bereits ein WGTools-Relay-Agent. Er wird nicht ersetzt: Dieses WGTools erhält eine eigene isolierte Verbindung mit eigenen Schlüsseln und UDP-Ports.", + "vps.name": "Name", + "vps.no_domain": "IP-Endpoint", + "vps.not_installed": "Wird installiert", + "vps.os": "Betriebssystem", + "vps.password": "Passwort", + "vps.phase_note": "Relay-Agent unterstützt mehrere unabhängige WGTools-Controller auf einem VPS. Jeder Controller erhält isolierte Verbindung, Schlüssel und UDP-Ports; bestehende Verbindungen bleiben unberührt.", + "vps.port_pair": "UDP-Ports", + "vps.ports_adjusted": "freie Ports ausgewählt", + "vps.private_key": "Privater Schlüssel", + "vps.privilege": "Berechtigungen", + "vps.public_endpoint": "Künftiger öffentlicher Endpoint", + "vps.ready_help": "SSH-Zugangsdaten werden nur für Kompatibilitätsprüfung und direkte Relay-Installation verwendet; sie werden nicht gespeichert.", + "vps.reconnect_note": "Auf diesem VPS wurde eine bestehende Relay-Verbindung dieses WGTools gefunden. WGTools verbindet sich mit demselben Tenant; neue Tenants oder UDP-Ports werden nicht erstellt.", + "vps.reconnect_ok": "Bestehenden Relay erfolgreich wiederverbunden", + "vps.reconnect_relay": "Relay wiederverbinden", + "vps.relay_port": "Relay-UDP-Port", + "vps.remove_confirm": "Diesen VPS-Kandidaten entfernen? Es wurden keine Remote-Änderungen vorgenommen.", + "vps.save_candidate": "Kandidaten speichern", + "vps.saved": "VPS-Kandidat gespeichert", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH-Schlüssel", + "vps.ssh_port": "SSH-Port", + "vps.ssh_user": "SSH-Benutzer", + "vps.status_candidate": "Bereit zur Installation", + "vps.status_installed": "Relay verbunden", + "vps.subtitle": "Öffentlichen VPS für Remote-Zugriff vorbereiten, wenn dieser WGTools-Server keine öffentliche IP hat.", + "vps.tenant": "Verbindung", + "vps.title": "VPS-Relay", + "vps.transport_port": "Transport-UDP-Port", + "vps.transport_port_hint": "Separater UDP-Port für privaten Home-↔-VPS-Transporttunnel.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Gespeichert", + "vps.active_short": "Aktiv", + "dashboard.traffic_reset": "Zurücksetzen", + "dashboard.traffic_reset_confirm": "Aufgelaufene WireGuard-Traffic-Zähler dieser Schnittstelle zurücksetzen? Auch die Client-Zähler beginnen bei null.", + "dashboard.traffic_reset_done": "Traffic-Zähler zurückgesetzt", + "dashboard.traffic_reset_failed": "Traffic-Zähler konnten nicht zurückgesetzt werden", + "audit.action.traffic.reset": "Traffic-Zähler zurückgesetzt", + "audit.result.reset": "zurückgesetzt", + "server.mtu": "MTU", + "server.mtu_auto": "Automatisch", + "server.mtu_hint": "Optional. Für automatische MTU durch wg-quick leer lassen. Nur bei Bedarf, z. B. LTE oder PPPoE, 1380 oder 1420 einstellen.", + "clients.peer_isolation": "VPN-Client-Isolation", + "clients.peer_isolation_enable": "Von anderen VPN-Clients isolieren", + "clients.peer_isolation_hint": "Blockiert den Verkehr zwischen diesem Client und anderen Adressen im WireGuard-Pool. Der Zugriff auf Server, Internet, lokale und Site-to-site-Netze wird weiterhin durch andere Regeln gesteuert.", + "clients.credentials_rotate": "Client-Schlüssel", + "clients.credentials_rotate_button": "Schlüssel erneuern", + "clients.credentials_rotate_confirm": "Neue Schlüssel für diesen Client erzeugen? Bei aktiver Verbindung wird seine WireGuard-Sitzung sofort getrennt. Anschließend neue Konfiguration oder QR übermitteln.", + "clients.credentials_rotate_confirm_psk": "Neues Schlüsselpaar und neuen PSK für diesen Client erzeugen? Bei aktiver Verbindung wird seine WireGuard-Sitzung sofort getrennt. Anschließend neue Konfiguration oder QR senden.", + "clients.credentials_rotate_hint": "Erneuert PrivateKey/PublicKey und bei aktiviertem PSK auch diesen. Adresse, Routen, Gruppe, Zeitplan, Isolation und gespeicherte Statistiken bleiben erhalten.", + "clients.credentials_rotating": "Neue Schlüssel werden erstellt, alte Sitzung getrennt…", + "clients.credentials_rotated": "Client-Schlüssel geändert. Die alte Sitzung wurde gegebenenfalls getrennt. Die alte Konfiguration funktioniert nicht mehr; sende vor dem nächsten Verbindungsaufbau neue Konfiguration oder QR.", + "clients.credentials_rotated_short": "Client-Schlüssel geändert — neue Konfiguration nötig", + "audit.action.client.credentials_rotated": "Client-Schlüssel erneuert", + "clients.credentials_connection_lost": "Verbindung zu WGTools unterbrochen. Falls dieses Panel über den Client mit gerade erneuerten Schlüsseln geöffnet war, ist das normal: seine alte WireGuard-Sitzung wurde sofort getrennt. Verbinde dich über einen anderen Weg und erstelle neue Konfiguration oder QR.", + "nav.navigation": "Hauptnavigation", + "nav.project_github": "WGTools auf GitHub", + "auth.email": "E-Mail", + "auth.email_optional_help": "Jetzt optional. Kann nach Einrichtung der E-Mail-Funktion zur Passwortwiederherstellung dienen.", + "auth.forgot_password": "Passwort vergessen?", + "auth.reset_title": "Passwort zurücksetzen", + "auth.reset_subtitle": "Einmalcode per E-Mail erhalten und neues WGTools-Passwort festlegen.", + "auth.reset_identifier": "Benutzername oder E-Mail", + "auth.reset_identifier_help": "Zum Schutz der Privatsphäre zeigt WGTools immer dieselbe Antwort, ob das Konto existiert oder nicht.", + "auth.send_reset_code": "Code senden", + "auth.reset_code_sent_generic": "Wenn das Konto existiert und eine E-Mail-Adresse hat, wurde ein Reset-Code gesendet. Er ist 15 Minuten gültig.", + "auth.reset_code": "6-stelliger Code", + "auth.set_new_password": "Neues Passwort festlegen", + "auth.request_another_code": "Neuen Code anfordern", + "auth.back_to_login": "Zur Anmeldung", + "auth.reset_not_configured": "E-Mail-Passwortwiederherstellung ist nicht eingerichtet. Wende dich an den WGTools-Administrator.", + "settings.tab_mail": "E-Mail", + "settings.mail": "E-Mail / SMTP", + "settings.mail_subtitle": "SMTP dient zur Passwortwiederherstellung.", + "settings.mail_not_configured": "Nicht konfiguriert", + "settings.mail_enabled": "E-Mail und Passwortwiederherstellung aktivieren", + "settings.mail_smtp_host": "SMTP-Server", + "settings.mail_smtp_port": "SMTP-Port", + "settings.mail_security": "Verschlüsselung", + "settings.mail_security_none": "Keine Verschlüsselung", + "settings.mail_username": "SMTP-Benutzername", + "settings.mail_username_help": "Für SMTP-Anmeldung und als Absender-E-Mail-Adresse verwendet.", + "settings.mail_password": "SMTP-Passwort", + "settings.mail_password_keep": "Leer lassen, um gespeichertes Passwort beizubehalten.", + "settings.mail_from_email": "Absender-E-Mail", + "settings.mail_from_name": "Absendername", + "settings.mail_test_recipient": "Testempfänger", + "settings.mail_test_recipient_help": "Der Test verwendet die aktuell gespeicherten SMTP-Einstellungen.", + "settings.mail_remove_password": "Passwort entfernen", + "settings.mail_test": "Test senden", + "settings.mail_save": "E-Mail-Einstellungen speichern", + "settings.mail_enabled_badge": "Aktiviert", + "settings.mail_disabled_badge": "Deaktiviert", + "settings.mail_saved": "E-Mail-Einstellungen gespeichert.", + "settings.mail_remove_password_confirm": "Gespeichertes SMTP-Passwort entfernen und E-Mail deaktivieren?", + "settings.mail_password_removed": "SMTP-Passwort entfernt und E-Mail deaktiviert.", + "settings.mail_test_recipient_required": "E-Mail-Adresse des Testempfängers eingeben.", + "settings.mail_testing": "Test-E-Mail wird gesendet…", + "settings.mail_test_ok": "Test-E-Mail erfolgreich gesendet.", + "settings.user_email": "E-Mail", + "settings.user_email_help": "Optional. Nur für eigenständige Passwortwiederherstellung nötig.", + "settings.change_email": "E-Mail", + "settings.user_email_saved": "E-Mail gespeichert.", + "settings.send_password_reset": "Reset senden", + "settings.user_reset_mail_not_configured": "Zuerst E-Mail einrichten und aktivieren.", + "settings.user_reset_email_missing": "Zuerst E-Mail-Adresse hinzufügen.", + "settings.user_reset_confirm": "Passwort-Reset-Code an {name} unter {email} senden?", + "settings.user_reset_sent": "Passwort-Reset-Code an {email} gesendet.", + "audit.action.auth.password_reset_requested": "Passwortzurücksetzung angefordert", + "audit.action.auth.password_reset_code_sent": "Passwort-Reset-Code gesendet", + "audit.action.auth.password_reset_completed": "Passwort zurückgesetzt", + "audit.action.auth.password_reset_failed": "Passwortzurücksetzung fehlgeschlagen", + "audit.action.mail.settings_updated": "E-Mail-Einstellungen geändert", + "audit.action.mail.test_sent": "Test-E-Mail gesendet", + "audit.action.mail.test_failed": "Test-E-Mail fehlgeschlagen", + "audit.action.user.email_changed": "Benutzer-E-Mail geändert", + "audit.action.user.password_reset_sent": "Passwort-Reset an Benutzer gesendet", + "audit.action.user.password_reset_failed": "Benutzer-Passwort-Reset fehlgeschlagen", + "audit.result.accepted": "angenommen", + "audit.result.sent": "gesendet", + "audit.result.invalid_code": "ungültiger Code", + "common.copy": "Kopieren", + "common.copied": "Kopiert", + "clients.use_panel_host": "Paneladresse verwenden", + "clients.use_panel_host_done": "Paneladresse eingefügt: {host}", + "clients.use_panel_host_failed": "Paneladresse konnte nicht aus der Browser-URL ermittelt werden.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Integriertes Let’s-Encrypt-HTTPS für direkten WGTools-Zugriff ohne Reverse-Proxy.", + "settings.https_disabled": "Deaktiviert", + "settings.https_enabled": "Aktiviert", + "settings.https_enable": "Integriertes HTTPS aktivieren", + "settings.https_type": "Zertifikat für", + "settings.https_domain": "Domain", + "settings.https_public_ip": "Öffentliche IP", + "settings.https_target": "Domain oder öffentliche IP", + "settings.https_email": "Let’s-Encrypt-E-Mail", + "settings.https_port": "HTTPS-Port", + "settings.https_port80_note": "TCP-Port 80 muss für die Ausstellung und Verlängerung des Zertifikats aus dem Internet erreichbar sein. Den gewählten HTTPS-Port für das Panel ebenfalls öffnen.", + "settings.https_check_ports": "Ports prüfen", + "settings.https_certificate": "Zertifikat", + "settings.https_certificate_ready": "Bereit", + "settings.https_certificate_missing": "Nicht ausgestellt", + "settings.https_expires": "Gültig bis", + "settings.https_renewal": "Automatische Verlängerung", + "settings.https_renewal_enabled": "Aktiviert", + "settings.https_renewal_disabled": "Deaktiviert", + "settings.https_certificate_path": "Zertifikat", + "settings.https_private_key_path": "Privater Schlüssel", + "settings.https_issue": "Zertifikat anfordern / erneuern", + "settings.https_port_free": "Frei", + "settings.https_port_busy": "Belegt", + "settings.https_ports_checked": "Portprüfung abgeschlossen.", + "settings.https_target_email_required": "Domain/öffentliche IP und Let’s-Encrypt-E-Mail eingeben.", + "settings.https_issue_confirm": "Let’s-Encrypt-Zertifikat für {target} anfordern oder erneuern? Die HTTPS-Einstellungen werden gespeichert. TCP-Port 80 muss aus dem Internet erreichbar sein.", + "settings.https_issuing": "Let’s-Encrypt-Zertifikat wird angefordert…", + "settings.https_issue_ok": "Zertifikat bereit.", + "settings.https_already_enabled": "Integriertes HTTPS ist bereits aktiviert.", + "settings.https_already_disabled": "Integriertes HTTPS ist bereits deaktiviert.", + "settings.https_enable_confirm": "Integriertes HTTPS auf TCP {port} mit Pfad {path} aktivieren? WGTools wird neu gestartet und die Seite unter der neuen Adresse wiederverbunden.", + "settings.https_disable_confirm": "Integriertes HTTPS deaktivieren und WGTools wieder über HTTP öffnen?", + "settings.https_switching": "HTTPS wird aktiviert und WGTools neu gestartet…", + "settings.https_switching_http": "HTTPS wird deaktiviert und WGTools neu gestartet…", + "audit.action.https.certificate_issued": "HTTPS-Zertifikat ausgestellt", + "audit.action.https.certificate_failed": "HTTPS-Zertifikatsanfrage fehlgeschlagen", + "audit.action.https.enabled": "HTTPS aktiviert", + "audit.action.https.disabled": "HTTPS deaktiviert", + "audit.result.issued": "ausgestellt", + "audit.result.enabled": "aktiviert", + "audit.result.disabled": "deaktiviert", + "settings.https_access_path": "Panel-Zugriffspfad", + "settings.https_access_path_help": "Eigenen Pfad wählen. Bei integriertem HTTPS erhalten Anfragen außerhalb dieses Pfads einen 404-Fehler.", + "settings.https_enable_fields_required": "Domain/öffentliche IP, Let’s-Encrypt-E-Mail und Panel-Pfad eingeben.", + "settings.https_use_panel_host": "Paneladresse verwenden", + "settings.https_reconnecting": "WGTools wechselt zur neuen HTTPS-Adresse…", + "server.tab_nodes": "Knoten", + "common.type": "Typ", + "common.status": "Status", + "common.copy_failed": "Kopieren fehlgeschlagen", + "clients.vpn_address": "VPN-Adresse", + "nodes.title": "WGTools Nodes", + "nodes.subtitle": "Mehrere WGTools-Server sicher verbinden und nur die Netze veröffentlichen, die andere Nodes erreichen dürfen.", + "nodes.enable_hub": "HUB aktivieren", + "nodes.connect_hub": "Mit HUB verbinden", + "nodes.settings": "Node-Einstellungen", + "nodes.settings_action": "Einstellungen", + "nodes.sync_now": "Synchronisieren", + "nodes.disable": "Nodes deaktivieren", + "nodes.disable_action": "Trennen", + "nodes.join_title": "Neue Nodes verbinden", + "nodes.join_help": "Einmalcode erzeugen und zusammen mit dem HUB-Service-Endpoint (z. B. vpn.example.com:51950) in einer anderen WGTools-Oberfläche eingeben. Der Code ist 15 Minuten gültig und einmal verwendbar.", + "nodes.create_code": "Code erstellen", + "nodes.connected_nodes": "Verbundene Nodes", + "nodes.connected_nodes_help": "Informationen zu anderen Panels, veröffentlichten Netzen und Clients. Remote-Clients sind schreibgeschützt.", + "nodes.enable_hub_help": "Dieses Panel wird zum zentralen Node. Über denselben Port akzeptiert HUB WireGuard per UDP und die geschützte Erstkopplung per TCP.", + "nodes.node_name": "Node-Name", + "nodes.transport_network": "Node-Transportnetz", + "nodes.transport_help": "Eigenes privates Netz nur für die WGTools-zu-WGTools-Verbindung. Darf sich nicht mit VPN-/LAN-Netzen überschneiden.", + "nodes.panel_url": "Panel-URL", + "nodes.panel_url_help": "Optional. Nur ein Informationslink für „Panel öffnen“ auf anderen Nodes; wird nie für die Node-Verbindung genutzt.", + "nodes.extra_networks": "Zusätzliche Node-Netze", + "nodes.extra_networks_help": "Ein Netz pro Zeile. VPN-Netze der Schnittstellen und Remote-Netze von Site-to-site-Clients werden automatisch veröffentlicht. Hier nur weitere geroutete LAN-/Netze ergänzen, z. B. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools trägt erkannte VPN-, Site-to-site- und lokale geroutete LAN-Netze ein. Behalte nur die Netze, die dieser Node veröffentlichen soll. Ein Netz pro Zeile.", + "nodes.published_networks_settings_help": "Ein Netz pro Zeile. Dies ist die explizite Liste der von diesem Node veröffentlichten Netze. Entfernen einer Zeile beendet die Ankündigung an andere Nodes.", + "nodes.available_networks_help": "Aktuell erkannt: {networks}. Neue Netze werden nicht automatisch veröffentlicht; füge gewünschte oben hinzu.", + "nodes.available_networks_none": "Zurzeit keine weiteren lokalen Netze erkannt.", + "nodes.connect_help": "HUB-Service-Endpoint und Einmalcode eingeben. Panel-URL, HTTPS-Port, Zertifikat und privater Pfad werden für die Nodes-Kopplung nicht verwendet.", + "nodes.join_code": "Code zum Verbinden", + "nodes.connect_reachability_note": "Die Erstkopplung erfolgt über geschütztes TCP auf dem angegebenen Port. Nach Erstellung von wgnode0 werden Netze, Status, Versionen und schreibgeschützte Client-Daten über die interne WireGuard-Adresse mit HUB synchronisiert.", + "nodes.connect": "Verbinden", + "nodes.settings_help": "Node-Name, optionaler Link „Panel öffnen“ und Liste veröffentlichter Netze. Panel-URL wird weder zur Kopplung noch zur Synchronisierung verwendet.", + "nodes.details": "Details", + "nodes.not_configured": "WGTools Nodes nicht eingerichtet", + "nodes.not_configured_help": "Aktiviere HUB auf diesem Panel oder verbinde es mit einem bestehenden WGTools-HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Mit HUB verbunden", + "nodes.mode_none": "Nicht konfiguriert", + "nodes.role": "Rolle", + "nodes.tunnel": "Node-Tunnel", + "nodes.node_ip": "Node-Adresse", + "nodes.endpoint": "HUB-Endpoint", + "nodes.published_networks": "Veröffentlichte Netze", + "nodes.last_sync": "Letzte Synchronisierung", + "nodes.no_nodes_hub": "Noch keine Nodes verbunden. Erstelle einen Verbindungscode und verwende ihn auf einem anderen WGTools-Panel.", + "nodes.no_nodes_spoke": "Noch keine Informationen zu anderen Nodes empfangen.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Panel öffnen", + "nodes.route_conflict": "Routenkonflikt", + "nodes.no_published_networks": "Keine veröffentlichten Netze", + "nodes.load_failed": "WGTools Nodes konnte nicht geladen werden", + "nodes.enable_hub_confirm": "WGTools HUB aktivieren und internen WireGuard-Node-Tunnel erstellen?", + "nodes.applying": "WGTools-Node-Tunnel wird eingerichtet…", + "nodes.enable_failed": "HUB konnte nicht aktiviert werden", + "nodes.hub_enabled": "WGTools HUB aktiviert", + "nodes.connecting": "HUB-Code wird geprüft und geschützter Node-Tunnel erstellt…", + "nodes.connect_failed": "Verbindung mit HUB fehlgeschlagen", + "nodes.connected": "Mit WGTools HUB verbunden", + "nodes.settings_failed": "Node-Einstellungen konnten nicht gespeichert werden", + "nodes.settings_saved": "Node-Einstellungen gespeichert", + "nodes.code_failed": "Verbindungscode konnte nicht erstellt werden", + "nodes.code_expires": "Einmalcode. Gültig bis {time}.", + "nodes.code_copied": "Verbindungscode kopiert", + "nodes.network_vpn": "VPN-Clients", + "nodes.network_site_to_site": "Site-to-site-Netz", + "nodes.network_custom": "Zusätzliches Netz", + "nodes.conflict": "Konflikt", + "nodes.remote_clients": "Clients (schreibgeschützt)", + "nodes.no_clients": "Dieser Node meldet keine Clients", + "nodes.details_failed": "Node-Details konnten nicht geladen werden", + "nodes.remove_confirm": "Node „{name}“ aus HUB entfernen? Sein Zugang zum internen Tunnel wird widerrufen.", + "nodes.remove_failed": "Node konnte nicht entfernt werden", + "nodes.removed": "Node entfernt", + "nodes.disable_hub_confirm": "HUB deaktivieren und alle WGTools Nodes trennen? Der interne Node-Tunnel wird entfernt.", + "nodes.disconnect_confirm": "Dieses WGTools-Panel vom HUB trennen und internen Node-Tunnel entfernen?", + "nodes.disable_failed": "WGTools Nodes konnte nicht deaktiviert werden", + "nodes.disabled": "WGTools Nodes deaktiviert", + "nodes.sync_failed": "Node-Synchronisierung fehlgeschlagen", + "nodes.synced": "Node-Informationen synchronisiert", + "nodes.service_port": "Nodes-Port", + "nodes.service_port_help": "Dieselbe Portnummer wird gleichzeitig genutzt: UDP für WireGuard und TCP für die geschützte Erstkopplung.", + "nodes.hub_port_forward_note": "Liegt HUB hinter NAT, leite denselben Port für UDP und TCP an ihn weiter. WGTools-Webport, HTTPS und privater Panel-Pfad gehören nicht zu Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Nodes-Domain/IP und Port ohne http:// oder https://, z. B. vpn.example.com:51950.", + "settings.collapse_sidebar": "Seitenleiste einklappen", + "settings.expand_sidebar": "Seitenleiste ausklappen", + "settings.https_issue_fields_required": "Domain/öffentliche IP, Let’s-Encrypt-E-Mail und Panel-Pfad eingeben.", + "settings.https_issue_ok_saved": "Zertifikat bereit und HTTPS-Einstellungen gespeichert.", + "settings.https_enable_need_certificate": "Zuerst ein Zertifikat anfordern.", + "settings.https_enable_certificate_mismatch": "Zuerst Zertifikat für die aktuelle Domain oder IP anfordern.", + "settings.https_enable_certificate_expired": "Zertifikat abgelaufen. Vor HTTPS-Aktivierung erneuern.", + "settings.https_enable_certificate_ready": "Zertifikat bereit — integriertes HTTPS kann aktiviert werden.", + "settings.https_enable_active_help": "Haken entfernen und speichern, um zu HTTP zurückzukehren.", + "settings.https_certificate_expired": "Abgelaufen", + "settings.https_certificate_wrong_target": "Für andere Adresse", + "nodes.network_conflict_error": "Veröffentlichte Netze überschneiden sich mit anderem Node oder dem Nodes-Transportnetz: {conflicts}. Entferne oder ändere das betroffene Netz.", + "nodes.networks_changed": "Erkannte Netze haben sich seit dem Speichern geändert. Neu: {added}. Nicht mehr erkannt: {removed}. Prüfe die veröffentlichte Liste und speichere nach Kontrolle.", + "nodes.review_networks": "Netze prüfen", + "nodes.vpn_pool_mismatch": "VPN-Pool geändert: Nodes veröffentlicht weiterhin {old}, aktuell ist {current}. Öffne die Node-Einstellungen und aktualisiere die veröffentlichten Netze.", + "server.error_vpn_network_invalid": "VPN-Netz muss ein gültiges IPv4-Netz sein, z. B. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Nur IPv4-VPN-Netze werden unterstützt.", + "server.error_vpn_network_too_small": "Das VPN-Netz muss mindestens zwei nutzbare Adressen enthalten.", + "server.error_vpn_network_no_hosts": "Das gewählte VPN-Netz hat keine nutzbaren Serveradressen.", + "server.error_server_address_prefix": "Server-VPN-Adresse muss ein Präfix enthalten, z. B. 10.0.0.1/24.", + "server.error_server_address_network": "Die Server-VPN-Adresse muss zum gewählten Adresspool gehören und das gleiche Präfix verwenden.", + "server.error_server_address_reserved": "Die Server-VPN-Adresse darf nicht die Netz- oder Broadcast-Adresse sein.", + "server.error_listen_port_number": "Der WireGuard-Port muss eine Zahl sein.", + "server.error_listen_port_range": "Der WireGuard-Port muss zwischen 1 und 65535 liegen.", + "server.error_mtu_number": "MTU muss eine Zahl sein.", + "auth.mfa_title": "Zwei-Faktor-Authentifizierung", + "auth.mfa_login_help": "Gib den sechsstelligen Code aus Google Authenticator oder einen Wiederherstellungscode ein.", + "auth.mfa_code": "Authentifizierungscode", + "auth.mfa_verify": "Prüfen und anmelden", + "auth.mfa_back": "Zurück zum Passwort", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Zwei-Faktor-Authentifizierung (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Aktiviert", + "settings.mfa_disabled": "Deaktiviert", + "settings.mfa_google_help": "Schütze dieses Konto mit Google Authenticator oder einer anderen TOTP-App. Für die Einrichtung ist dein aktuelles Passwort nötig.", + "settings.current_password": "Aktuelles Passwort", + "settings.mfa_start": "Google Authenticator einrichten", + "settings.mfa_secret": "Manueller Einrichtungsschlüssel", + "settings.mfa_scan_help": "QR-Code mit Google Authenticator scannen und aktuellen sechsstelligen Code eingeben, um MFA zu aktivieren.", + "settings.mfa_code": "6-stelliger Code", + "settings.mfa_enable": "MFA aktivieren", + "settings.mfa_manage_help": "Zum Ändern von MFA aktuelles Passwort und Google-Authenticator-Code oder Wiederherstellungscode eingeben.", + "settings.mfa_code_or_recovery": "Authenticator- oder Wiederherstellungscode", + "settings.mfa_regenerate": "Neue Wiederherstellungscodes", + "settings.mfa_disable": "MFA deaktivieren", + "settings.mfa_recovery_title": "Wiederherstellungscodes", + "settings.mfa_recovery_help": "Speichere diese Codes jetzt. Jeder kann einmalig genutzt werden, wenn Google Authenticator nicht verfügbar ist. Sie werden nicht erneut angezeigt.", + "settings.mfa_recovery_remaining": "Verbleibende Wiederherstellungscodes: {count}", + "settings.mfa_enabled_ok": "MFA aktiviert.", + "settings.mfa_disabled_ok": "MFA deaktiviert.", + "settings.mfa_disable_confirm": "Zwei-Faktor-Authentifizierung für dieses Konto deaktivieren?", + "settings.mfa_regenerate_confirm": "Alle bestehenden Wiederherstellungscodes ersetzen?", + "settings.mfa_recovery_regenerated": "Neue Wiederherstellungscodes erstellt.", + "audit.action.auth.mfa_failed": "MFA-Prüfung fehlgeschlagen", + "audit.action.auth.mfa_recovery_used": "MFA-Wiederherstellungscode verwendet", + "audit.action.user.mfa_setup_started": "MFA-Einrichtung begonnen", + "audit.action.user.mfa_enabled": "MFA aktiviert", + "audit.action.user.mfa_disabled": "MFA deaktiviert", + "audit.action.user.mfa_disabled_cli": "MFA über CLI deaktiviert", + "audit.action.user.mfa_recovery_regenerated": "MFA-Wiederherstellungscodes erneuert", + "settings.mfa_error_password": "Aktuelles Passwort ungültig.", + "settings.mfa_error_code": "Authentifizierungscode ungültig.", + "settings.mfa_error_already_enabled": "MFA ist bereits aktiviert.", + "settings.mfa_error_not_enabled": "MFA ist nicht aktiviert.", + "settings.mfa_error_not_started": "MFA-Einrichtung erneut beginnen.", + "trace.title": "Traceroute, Ping und Routenkarte", + "trace.subtitle": "Latenz zu einem VPS oder Server messen und Verzögerungen entlang der Route erkennen.", + "trace.target": "Server-IP oder Hostname", + "trace.show_map": "Route auf Karte zeigen", + "trace.run": "Traceroute starten", + "trace.geo_note": "Geolokalisierung ist ungenau. Bei aktivierter Karte werden öffentliche Hop-IPs zur Standortabfrage an ipwho.is gesendet; Kartenkacheln stammen von OpenStreetMap.", + "trace.latency_note": "Traceroute misst die Latenz in Millisekunden, nicht den Durchsatz in Mbit/s.", + "trace.map": "Routenkarte", + "trace.map_hint": "Interaktive Karte: ziehen zum Verschieben, Mausrad oder +/− zum Zoomen, Hop anklicken für Details.", + "trace.hop": "Hop / IP", + "trace.location": "Standort", + "trace.avg_rtt": "Ø RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Verlust", + "trace.summary_target": "Ziel", + "trace.summary_ping": "Durchschnittlicher Ping", + "trace.summary_loss": "Ping-Verlust", + "trace.summary_hops": "Hops", + "trace.no_reply": "Keine Antwort", + "trace.private": "Privates Netzwerk", + "trace.unknown": "Unbekannt", + "trace.running": "Ping und Traceroute laufen… Das kann bis zu einer Minute dauern.", + "trace.done": "Netzwerktrace abgeschlossen.", + "trace.failed": "Netzwerktrace fehlgeschlagen", + "trace.partial_geo": "Einige öffentliche Hops konnten nicht geolokalisiert werden.", + "trace.not_reached": "Ziel per Traceroute nicht erreicht.", + "trace.reached": "Ziel erreicht", + "trace.ms": "ms", + "server.tab_trace": "Routenverfolgung", + "trace.map_controls": "Kartensteuerung", + "trace.zoom_in": "Vergrößern", + "trace.zoom_out": "Verkleinern", + "trace.fit_route": "Gesamte Route anzeigen", + "trace.fit": "Anpassen", + "trace.map_click_hint": "Für IP, Standort, ASN und RTT auf einen Hop klicken.", + "trace.route_path": "Route", + "trace.ping_ok_trace_filtered": "Ziel antwortet auf Ping, die letzten Traceroute-Hops nicht.", + "trace.latency_legend": "Latenzanstieg zwischen antwortenden Hops", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — erhöht", + "trace.latency_bad": "Δ RTT > 20 ms — starker Sprung" +} diff --git a/app/locales/en.json b/app/locales/en.json new file mode 100644 index 0000000..0c385e2 --- /dev/null +++ b/app/locales/en.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Create user", + "auth.login_subtitle": "Enter your WGTools username and password.", + "auth.login_title": "Sign in to WGTools", + "auth.password": "Password", + "auth.password_repeat": "Repeat password", + "auth.setup_help": "The first account has full WGTools access. Additional users can be created later in Settings.", + "auth.setup_subtitle": "WGTools requires an account before server management is available.", + "auth.setup_title": "Create the first user", + "auth.sign_in": "Sign in", + "auth.sign_out": "Sign out", + "auth.username": "Username", + "clients.actions": "Actions", + "clients.add": "+ Add client", + "clients.address": "VPN address", + "clients.address_hint": "The first free address is suggested automatically.", + "clients.allowed_ips_required": "Enter at least one AllowedIPs network for the client configuration.", + "clients.basic_connection": "Connection settings", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs in client config", + "clients.config_private_warning": "This configuration contains the client's private key. Store it securely.", + "clients.config_title": "Client configuration", + "clients.config_unavailable": "Configuration unavailable", + "clients.connection_direct": "Directly to WGTools", + "clients.connection_path": "Connection path", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Connect through", + "clients.connection_via_hint": "Choose the public entry point used by this client. Relay is shown only when one is installed for the selected WireGuard interface.", + "clients.copy_config": "Copy", + "clients.copy_done": "Configuration copied", + "clients.create_subtitle": "Create a WireGuard peer and generate its client configuration.", + "clients.create_title": "Create client", + "clients.creating": "Creating keys and applying client…", + "clients.day_fri": "Fri", + "clients.day_mon": "Mon", + "clients.day_sat": "Sat", + "clients.day_sun": "Sun", + "clients.day_thu": "Thu", + "clients.day_tue": "Tue", + "clients.day_wed": "Wed", + "clients.delete_confirm": "Delete this client from WireGuard? WGTools will create a backup and remove the automatically generated policy rules tied to this client.", + "clients.deleted": "Client deleted", + "clients.dns": "DNS (optional)", + "clients.dns_hint": "Comma-separated IPv4 DNS servers.", + "clients.download_config": "Download .conf", + "clients.duplicate": "Duplicate", + "clients.duplicate_address_error": "This VPN address is already used by another peer.", + "clients.duplicate_name_error": "A peer with this name already exists.", + "clients.duplicate_ready": "A copy is ready. WGTools assigned a new name and VPN address; review the settings before saving.", + "clients.duplicate_site_hint": "Remote networks were cleared to prevent duplicate routes. Enter the networks for the new Site-to-site peer.", + "clients.duplicate_suffix": "copy", + "clients.edit_subtitle": "Update the server-side peer. Changes are applied without restarting WireGuard.", + "clients.edit_title": "Edit client", + "clients.endpoint": "Server endpoint", + "clients.endpoint_hint": "For remote clients use the public IP/domain that forwards the WireGuard port to this server.", + "clients.existing": "Existing peer", + "clients.expiration": "Access lifetime", + "clients.expiration_action": "At expiration", + "clients.expiration_action_hint": "If unchecked, the client remains in WGTools but WireGuard access is disabled. Set a new lifetime or No expiration and save to restore access.", + "clients.expiration_datetime": "Expires at", + "clients.expiration_datetime_hint": "Uses the local date and time of this browser.", + "clients.expiration_delete": "Delete client", + "clients.expiration_future_required": "Choose a future expiration date and time.", + "clients.expiration_hint": "At expiration WGTools performs the selected action on the next minute boundary. A WireGuard config backup is created first.", + "clients.expire_1d": "1 day", + "clients.expire_1h": "1 hour", + "clients.expire_3h": "3 hours", + "clients.expire_6h": "6 hours", + "clients.expire_custom": "Custom date and time", + "clients.expire_never": "No expiration", + "clients.expired": "Expired", + "clients.expired_disabled_hint": "This access lifetime has expired. The client is kept, but WireGuard access is disabled. Choose a future lifetime or No expiration and save to restore access.", + "clients.expired_disabled_short": "Expired · disabled", + "clients.expired_disabled_status": "Expired", + "clients.expires_days": "Expires in {n}d", + "clients.expires_hours": "Expires in {n}h", + "clients.expires_minutes": "Expires in {n}m", + "clients.generated_config": "Generated client configuration", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 seconds is a good default for clients behind NAT.", + "clients.local_access_exceptions": "Allowed local addresses", + "clients.local_access_exceptions_hint": "Optional IPs or CIDRs that stay reachable even while their local or Site-to-site network is blocked. Separate values with commas.", + "clients.managed": "WGTools managed", + "clients.name": "Name", + "clients.no_peers": "No peers found", + "clients.peers": "Peers", + "clients.peers_subtitle": "Changes are backed up and applied with wg syncconf without restarting the WireGuard interface.", + "clients.protected_networks_reference": "Blocked local networks (reference)", + "clients.protected_networks_reference_hint": "These networks are not written to AllowedIPs. Access is blocked by the WGTools server policy; individual addresses can be allowed in the field above.", + "clients.psk": "Preshared key (PSK)", + "clients.psk_enable": "Use an additional WireGuard preshared key", + "clients.psk_hint": "Recommended. Adds an extra symmetric secret to the WireGuard handshake. Standard WireGuard clients support it; WGTools includes the PSK in the generated config and QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generating QR…", + "clients.quick_search": "Quick search", + "clients.quick_search_clear": "Clear search", + "clients.quick_search_empty": "No clients match the search", + "clients.relay_endpoint_note": "The generated client config will connect to {endpoint}. The WireGuard server itself remains on this WGTools host.", + "clients.relay_required": "Choose a VPS Relay for this client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "unavailable", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "The client Endpoint is generated automatically from this Relay.", + "clients.remote_hint": "Networks located behind this peer. One network per line or separated by commas.", + "clients.remote_networks": "Remote networks", + "clients.remote_required": "Enter at least one remote network for a Site-to-site peer.", + "clients.required": "Name and VPN address are required.", + "clients.route_custom": "Custom", + "clients.route_full": "Full tunnel", + "clients.route_full_except_local": "Full tunnel except local networks", + "clients.route_hint": "Only these networks are written to AllowedIPs in the generated client config.", + "clients.route_preset": "Traffic through VPN", + "clients.route_vpn": "VPN network only", + "clients.route_vpn_lan": "VPN + local LAN", + "clients.saved": "Client saved", + "clients.schedule_blocked_short": "Schedule · blocked", + "clients.schedule_blocked_status": "Blocked by schedule", + "clients.schedule_days": "Allowed days", + "clients.schedule_days_required": "Choose at least one day for the access schedule.", + "clients.schedule_disabled_hint": "This client is currently blocked by its access schedule. WGTools will restore the same peer automatically when the next allowed window begins.", + "clients.schedule_enable": "Limit access by schedule", + "clients.schedule_from": "Access from", + "clients.schedule_hint": "WGTools can automatically disable and restore this client on selected days and times without changing the client config.", + "clients.schedule_short": "Schedule", + "clients.schedule_time_required": "Set both start and end times for the access schedule.", + "clients.schedule_timezone_hint": "The schedule uses the WireGuard server local time. Overnight windows such as 22:00–06:00 are supported.", + "clients.schedule_title": "Access schedule", + "clients.schedule_to": "Access until", + "clients.security_access": "Security and access time", + "clients.server_host": "Server address / domain", + "clients.server_host_hint": "Public IP or domain used by this client. Previously entered values are available as suggestions.", + "clients.server_host_required": "Server address / domain is required for a generated client configuration.", + "clients.server_peer": "Server peer", + "clients.server_port": "WireGuard port", + "clients.server_port_hint": "Taken automatically from the server configuration.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Status", + "clients.subtitle": "WireGuard peers, live status and client configuration management.", + "clients.tab_basic": "Basic", + "clients.tab_config": "Configuration", + "clients.tab_policy": "Policies", + "clients.tab_security": "Security", + "clients.title": "Clients", + "clients.type": "Type", + "clients.unmanaged_note": "This peer existed before WGTools. Its client private key cannot be recovered, so WGTools can edit the server-side peer but cannot generate its client configuration or QR code.", + "clients.updating": "Updating client…", + "common.actions": "Actions", + "common.ago": "ago", + "common.cancel": "Cancel", + "common.checking": "Checking…", + "common.close": "Close", + "common.config": "Config", + "common.delete": "Delete", + "common.disabled": "Disabled", + "common.edit": "Edit", + "common.enabled": "Enabled", + "common.loading": "Loading…", + "common.never": "Never", + "common.no": "No", + "common.not_configured": "Not configured", + "common.not_installed": "Not installed", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Refresh", + "common.running": "Running", + "common.save": "Save", + "common.stopped": "Stopped", + "common.total": "Total", + "common.unknown": "Unknown", + "common.updated": "Updated", + "common.yes": "Yes", + "dashboard.active_peers": "Active peers", + "dashboard.active_peers_subtitle": "Live information from wg show.", + "dashboard.activity": "System overview", + "dashboard.activity_subtitle": "Read-only checks for the running WireGuard stack.", + "dashboard.cores": "cores", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Last 24 h", + "dashboard.history_avg": "Avg", + "dashboard.history_max": "Max", + "dashboard.history_min": "Min", + "dashboard.history_now": "now", + "dashboard.memory": "Memory", + "dashboard.network": "Network", + "dashboard.peers": "Peers", + "dashboard.quick_search": "Quick search", + "dashboard.quick_search_clear": "Clear search", + "dashboard.quick_search_empty": "No peers match the search", + "dashboard.restart": "Restart", + "dashboard.restart_confirm": "Restart WireGuard? Active VPN clients will reconnect automatically.", + "dashboard.restart_ok": "WireGuard restarted.", + "dashboard.routing": "Routing", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Start", + "dashboard.start_ok": "WireGuard started.", + "dashboard.stop": "Stop", + "dashboard.stop_confirm": "Stop WireGuard? Active VPN clients will be disconnected.", + "dashboard.stop_ok": "WireGuard stopped.", + "dashboard.subtitle": "WireGuard server status, peers and live traffic.", + "dashboard.title": "Dashboard", + "dashboard.traffic": "Traffic", + "dashboard.uptime": "Uptime", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Server access policy", + "groups.additional_allowed": "Additional allowed addresses", + "groups.additional_blocked": "Additional blocked addresses", + "groups.allow": "Allow", + "groups.allowed": "Allowed", + "groups.allowed_addresses": "Allowed addresses / networks", + "groups.apply_current_template": "Apply current group template", + "groups.apply_defaults": "Apply current group template", + "groups.apply_defaults_hint": "Copies the current group route, DNS and Keepalive template into this client. Save the client, then issue a new config or QR if the installed device must be updated.", + "groups.basic": "Basic information", + "groups.block": "Block", + "groups.blocked": "Blocked", + "groups.blocked_addresses": "Blocked addresses / networks", + "groups.client_config_source": "Client configuration source", + "groups.client_defaults": "Client defaults", + "groups.client_group_hint": "Optional group for reusable access policy and client defaults. Groups are scoped to the selected WireGuard interface.", + "groups.config_differs": "This client configuration differs from the current group defaults. Server policy is current, but the installed phone/PC configuration changes only when you issue a new config or QR.", + "groups.config_differs_short": "Client config differs from group defaults", + "groups.create": "Create group", + "groups.create_title": "Create group", + "groups.created": "Group created", + "groups.creating": "Creating group…", + "groups.defaults_applied": "Current group template applied. Save the client to keep it.", + "groups.defaults_hint": "Defines what the client device sends through WireGuard. The server policy above independently decides what that traffic may access. Changing the template later never silently changes configs already installed on devices.", + "groups.delete_message": "Delete “{name}”? Client configurations are never deleted with a group.", + "groups.delete_move": "Move its clients to another group", + "groups.delete_title": "Delete client group", + "groups.delete_unassign": "Remove the group assignment from its clients", + "groups.deleted": "Group deleted", + "groups.deleting": "Updating clients and deleting group…", + "groups.description": "Description", + "groups.edit_title": "Edit group", + "groups.editor_subtitle": "A group combines a live server access policy with a template used when creating client configurations.", + "groups.effective_allow": "Allowed exceptions", + "groups.effective_deny": "Blocked exceptions", + "groups.effective_policy": "Effective server policy", + "groups.empty": "No client groups yet. Create one to reuse access policies and client defaults.", + "groups.group": "Group", + "groups.inherit": "Inherit", + "groups.internet_access": "Internet access", + "groups.internet_short": "Internet", + "groups.local_access": "Local networks", + "groups.local_short": "Local", + "groups.manage": "Groups", + "groups.members_count": "{count} clients", + "groups.name": "Name", + "groups.name_required": "Group name is required.", + "groups.new_client_defaults": "Client configuration template", + "groups.new_clients_short": "New clients", + "groups.no_group": "No group", + "groups.none": "None", + "groups.override_client_config": "Override the group client template for this client", + "groups.override_client_config_hint": "Off: Routes, DNS and Keepalive come from the group template. On: this client keeps its own values. Server access-policy overrides above remain independent.", + "groups.policy_addresses_hint": "IPv4 addresses or CIDRs, comma separated. Client exceptions take priority over group exceptions.", + "groups.policy_custom": "Custom policy", + "groups.policy_inherit": "Use group policy", + "groups.policy_mode": "Policy source", + "groups.policy_mode_hint": "Group policy is inherited by default. Client overrides never modify the group itself.", + "groups.routes_required": "Client routes cannot be empty.", + "groups.subtitle": "Reuse server access policies and defaults for normal clients on the selected WireGuard interface.", + "groups.title": "Client groups", + "groups.traffic_through_vpn": "Traffic through VPN", + "groups.updated": "Group updated", + "groups.updating": "Updating group policy…", + "help.example_note": "All addresses, interface names, peer names and domains in Help examples are fictional documentation values. Replace them with values from your own network.", + "help.navigation": "Help navigation", + "help.open": "Open help", + "help.subtitle": "Plain-language help for Dashboard, Server, Clients and Settings with short practical examples.", + "help.title": "WGTools Help", + "interfaces.add": "+ Add interface", + "interfaces.create": "Create interface", + "interfaces.create_confirm": "Create and start interface {name}?", + "interfaces.create_failed": "Interface could not be created", + "interfaces.create_hint": "WGTools checks that the VPN network, UDP port and policy routing table do not conflict with other WireGuard interfaces before creating the configuration.", + "interfaces.create_subtitle": "Create an independent WireGuard interface with its own address pool, UDP port and routing settings.", + "interfaces.create_title": "Add WireGuard interface", + "interfaces.created": "Interface created successfully.", + "interfaces.creating": "Generating keys, writing the new configuration and starting WireGuard…", + "interfaces.current": "Current", + "interfaces.delete": "Delete", + "interfaces.delete_confirm": "Delete interface {name}? This removes its WireGuard configuration and all peers on this interface. A configuration backup is created first.", + "interfaces.delete_failed": "Interface could not be deleted", + "interfaces.delete_last": "The last configured WireGuard interface cannot be deleted here.", + "interfaces.delete_tooltip": "Delete this WireGuard interface", + "interfaces.deleted": "Interface deleted. Backup: {backup}", + "interfaces.deleting": "Stopping WireGuard and deleting the interface…", + "interfaces.display_name": "Display name", + "interfaces.display_name_edit_hint": "Friendly name only; the Linux interface name does not change.", + "interfaces.display_name_hint": "Optional friendly name, for example Work or Contractors.", + "interfaces.identity": "Interface identity", + "interfaces.none": "No WireGuard interfaces found", + "interfaces.none_configured": "No configured WireGuard interfaces yet.", + "interfaces.peers_short": "peers", + "interfaces.rename_failed": "Interface display name could not be saved.", + "interfaces.select": "Select", + "interfaces.subtitle": "Each interface has its own VPN network, listen port, peers and policies. Select one to manage it throughout WGTools.", + "interfaces.switch_title": "WireGuard interfaces", + "interfaces.system_name": "System name", + "interfaces.system_name_hint": "Linux interface name, for example wg1. It cannot be changed after creation.", + "interfaces.title": "WireGuard interfaces", + "interfaces.unique_port_hint": "Each WireGuard interface on this server must use its own UDP listen port.", + "interfaces.unique_table_hint": "WGTools recommends a separate policy table for each interface. Leave empty for normal system routing.", + "nav.clients": "Clients", + "nav.dashboard": "Dashboard", + "nav.server": "Server", + "nav.settings": "Settings", + "server.access_apply_confirm": "Save this firewall rule and apply it now? WireGuard will be restarted briefly and a backup will be created.", + "server.access_rule_deleted": "Access rule deleted.", + "server.access_rule_help": "Create a common FORWARD access rule without editing iptables commands manually.", + "server.access_rule_order_hint": "WGTools inserts access rules at the beginning of the FORWARD chain so restrictive rules take effect before the general VPN ACCEPT rules.", + "server.access_rule_saved": "Access rule saved and applied.", + "server.action": "Action", + "server.action_hint": "REJECT tells the client the traffic was refused; DROP silently discards it; ACCEPT explicitly allows it.", + "server.add_access_rule": "Add access rule", + "server.add_route": "Add route", + "server.address": "Address", + "server.any": "Any", + "server.any_protocol": "Any", + "server.apply_confirm": "Save these server settings and apply them now? WireGuard will be restarted briefly. A backup is created first and WGTools will roll back automatically if the new configuration does not start.", + "server.apply_settings": "Save and apply", + "server.applying_rule": "Creating backup and applying…", + "server.applying_settings": "Validating settings, creating backup and applying…", + "server.basic_settings": "Basic settings", + "server.config_tab_help": "Open the raw configuration editor for the currently selected WireGuard interface.", + "server.create_confirm": "Create and start the WireGuard server with these settings?", + "server.create_server": "Create server", + "server.create_step_conf": "Create the configuration for the selected WireGuard interface with mode 600.", + "server.create_step_forward": "Configure forwarding, NAT and optional policy routing.", + "server.create_step_key": "Generate a new server key pair.", + "server.create_step_start": "Enable and start the selected wg-quick interface.", + "server.create_subtitle": "WireGuard is installed, but the selected interface is not configured yet.", + "server.create_success": "WireGuard server created successfully.", + "server.create_title": "Create WireGuard server", + "server.creating": "Generating keys, writing configuration and starting WireGuard…", + "server.custom_preserved": "Peer blocks, site-to-site routes and custom PostUp/PostDown rules that are not managed by these fields are preserved.", + "server.delete_access_confirm": "Delete this access rule and apply the change?", + "server.delete_route_confirm": "Delete this custom route and apply the change?", + "server.destination": "Destination", + "server.destination_hint": "Empty = any. Accepts an IP, CIDR or IP range. Separate multiple destinations with commas.", + "server.destination_port": "Destination port", + "server.destination_port_hint": "Optional. Enter a port such as 443 or a range such as 10000:20000. Select TCP or UDP first.", + "server.details": "Details", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostics", + "server.diagnostics_done": "Diagnostics completed", + "server.diagnostics_subtitle": "Current system checks. No configuration is changed.", + "server.direction": "Hook", + "server.edit_access_rule": "Edit access rule", + "server.edit_route": "Edit route", + "server.edit_server": "Edit server", + "server.edit_subtitle": "Edit the common WireGuard, routing and NAT settings. Existing peers and custom rules are preserved.", + "server.edit_title": "Server settings", + "server.edit_warning": "Applying interface, routing or firewall settings briefly restarts the WireGuard interface. Active peers will reconnect automatically.", + "server.enable_forwarding": "Enable IPv4 forwarding", + "server.enable_nat": "Enable NAT / Masquerade", + "server.firewall": "Firewall & NAT", + "server.firewall_subtitle": "Detected rules from WireGuard hooks.", + "server.firewall_subtitle_v08": "Common forwarding/NAT rules and access rules from the selected interface configuration. Simple access rules can be managed here; advanced rules stay available in the raw editor.", + "server.forward_from_vpn": "Allow forwarding from VPN", + "server.forward_to_vpn": "Allow forwarding to VPN", + "server.forwarding_section": "Forwarding and NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Required only when a policy routing table is used.", + "server.install_success": "WireGuard installed successfully.", + "server.install_wireguard": "Install WireGuard", + "server.install_wireguard_help": "Runs apt update and installs WireGuard plus the networking tools needed by WGTools.", + "server.install_wireguard_title": "Install WireGuard", + "server.installing": "Installing WireGuard… This may take a minute.", + "server.interface": "Interface", + "server.interface_hint": "WGTools currently manages this interface.", + "server.interface_name": "Interface", + "server.interface_section": "WireGuard interface", + "server.ip_forwarding": "IPv4 forwarding", + "server.kind": "Kind", + "server.listen_port": "Listen port", + "server.local_network": "Local network", + "server.local_network_hint": "Optional route added to the policy table.", + "server.managed_automatically": "Managed automatically", + "server.nat": "NAT / Masquerade", + "server.network": "Network", + "server.network_settings": "Network and NAT", + "server.no_firewall": "No firewall rules detected", + "server.no_routes": "No routes detected", + "server.not_configured": "Not configured", + "server.not_set": "Not set", + "server.policy_disabled_hint": "Disable this for normal system routing. Enable it only when this VPN needs its own source policy routing table.", + "server.policy_enabled": "Enable policy routing", + "server.policy_table": "Policy table", + "server.policy_table_hint": "Leave empty for normal system routing; use e.g. 200 for source policy routing.", + "server.port_word": "port", + "server.private_hidden": "Configured (hidden)", + "server.private_key": "Private key", + "server.protocol": "Protocol", + "server.route_apply_confirm": "Save this route and apply it now? WireGuard will be restarted briefly and a backup will be created.", + "server.route_custom": "Custom", + "server.route_deleted": "Route deleted.", + "server.route_device_hint": "Optional output interface, for example wg0 or enp6s18.", + "server.route_editor_help": "Add a route that should be installed when WireGuard starts and removed when it stops.", + "server.route_gateway_hint": "Optional next-hop gateway. A gateway or interface is required.", + "server.route_managed_peer": "Site-to-site peer", + "server.route_managed_server": "Server setting", + "server.route_network_hint": "IPv4 network such as 10.20.0.0/24, or 'default'.", + "server.route_saved": "Route saved and applied.", + "server.route_table_hint": "Use 'main' for normal routing or a numeric table such as 200.", + "server.route_type": "Type", + "server.routes": "Detected routes", + "server.routes_subtitle": "Routes parsed from PostUp/PostDown and current policy routing state.", + "server.routes_subtitle_v08": "Server-managed, site-to-site and custom routes from the selected interface configuration. Custom routes can be added, edited and removed here.", + "server.routing": "Routing", + "server.routing_section": "Routing", + "server.rule": "Rule", + "server.rule_access": "Access rule", + "server.rule_advanced": "Advanced", + "server.rule_apply_warning": "Applying a route or firewall rule briefly restarts the WireGuard interface. WGTools creates a backup and rolls back automatically if startup fails.", + "server.rule_client_exception": "Client exception", + "server.rule_client_policy": "Client policy", + "server.rule_managed_server": "Server setting", + "server.rule_type": "Type", + "server.run_diagnostics": "Run diagnostics", + "server.save_apply": "Save and apply", + "server.save_config": "SaveConfig", + "server.server_address": "Server VPN address", + "server.server_address_hint": "Usually the first usable address in the VPN network.", + "server.settings_applied": "Server settings saved and applied successfully.", + "server.settings_apply_failed": "Server settings could not be applied", + "server.setup_required": "Setup required", + "server.source": "Source", + "server.source_hint": "Empty = any. Accepts an IP, CIDR or range such as 10.0.0.100-10.0.0.120.", + "server.subtitle": "WireGuard installation, initial setup and current server configuration.", + "server.tab_config": "Config", + "server.tab_interface": "Interface", + "server.tab_routing": "Routing", + "server.tab_vps": "VPS", + "server.table": "Table", + "server.tabs_aria": "Server settings sections", + "server.title": "Server", + "server.uplink": "Uplink interface", + "server.use_raw_editor": "Use raw editor", + "server.via": "Via / Device", + "server.via_word": "via", + "server.vpn_network": "VPN network", + "server.vpn_network_hint": "Client addresses will later be allocated from this network.", + "server.vpn_pool": "VPN address pool", + "server.wg_not_installed": "WireGuard is not installed", + "server.wg_not_installed_subtitle": "WGTools can install the required Debian packages automatically.", + "server.what_happens": "What WGTools will do", + "settings.about": "About", + "settings.add_user": "Add user", + "settings.advanced": "Advanced", + "settings.advanced_subtitle": "Direct access to expert WireGuard configuration tools.", + "settings.appearance": "Appearance", + "settings.applying_config": "Validating configuration, creating backup and applying…", + "settings.backup_count": "Stored backups", + "settings.backup_retention": "Backups to keep", + "settings.backup_retention_help": "Old automatic backups are removed after a new backup is created. 1–200 files.", + "settings.backups": "Configuration backups", + "settings.backups_always_on": "Enabled", + "settings.backups_subtitle": "WGTools automatically creates a backup before configuration-changing operations. Automatic backups cannot be disabled.", + "settings.change_password": "Change password", + "settings.check_updates": "Check for updates", + "settings.config_applied": "Configuration saved and applied successfully.", + "settings.config_applied_restarted": "Configuration applied and WireGuard restarted.", + "settings.config_applied_stopped": "Configuration saved. WireGuard was already stopped and remains stopped.", + "settings.config_apply_failed": "Configuration could not be applied", + "settings.config_load_failed": "Could not load configuration", + "settings.current_user": "Current user", + "settings.current_version": "Current version", + "settings.audit_action": "Action", + "settings.audit_empty": "No audit events yet", + "settings.audit_log": "Audit", + "settings.audit_log_subtitle": "Panel, authentication and Telegram actions plus WireGuard client connection history. Secrets are never written here.", + "settings.audit_object": "Object", + "settings.audit_result": "Result", + "settings.audit_retention_note": "Retention: 30 days", + "settings.audit_search": "Quick search", + "settings.audit_search_clear": "Clear search", + "settings.audit_search_empty": "No audit events match the search", + "settings.audit_time": "Date / time", + "settings.audit_user": "User", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Access rule created", + "audit.action.access_rule.deleted": "Access rule deleted", + "audit.action.access_rule.updated": "Access rule updated", + "audit.action.auth.first_user_created": "First user created", + "audit.action.auth.login": "Signed in", + "audit.action.auth.login_failed": "Sign-in failed", + "audit.action.auth.logout": "Signed out", + "audit.action.backup.full_created": "Full backup created", + "audit.action.backup.full_restored": "Full backup restored", + "audit.action.client.config_downloaded": "Client config downloaded", + "audit.action.client.config_viewed": "Client config viewed", + "audit.action.client.created": "Client created", + "audit.action.client.deleted": "Client deleted", + "audit.action.client.qr_viewed": "Client QR viewed", + "audit.action.client.updated": "Client updated", + "audit.action.client_group.created": "Client group created", + "audit.action.client_group.deleted": "Client group deleted", + "audit.action.client_group.updated": "Client group updated", + "audit.action.interface.created": "Interface created", + "audit.action.interface.deleted": "Interface deleted", + "audit.action.interface.renamed": "Interface renamed", + "audit.action.route.created": "Route created", + "audit.action.route.deleted": "Route deleted", + "audit.action.route.updated": "Route updated", + "audit.action.server.created": "Server created", + "audit.action.server.raw_config_applied": "Raw config applied", + "audit.action.server.settings_applied": "Server settings applied", + "audit.action.settings.updated": "Panel settings updated", + "audit.action.telegram.action_denied": "Telegram action denied", + "audit.action.telegram.action_failed": "Telegram action failed", + "audit.action.telegram.connection_test": "Telegram connection test", + "audit.action.telegram.settings_updated": "Telegram settings updated", + "audit.action.update.checked": "Update checked", + "audit.action.update.scheduled": "Update scheduled", + "audit.action.update.backup_created": "Pre-update backup", + "audit.action.update.completed": "Update completed", + "audit.action.update.failed": "Update failed", + "audit.action.update.rollback_completed": "Previous version restored", + "audit.action.update.rollback_failed": "Update rollback failed", + "audit.action.user.created": "User created", + "audit.action.user.deleted": "User deleted", + "audit.action.user.password_changed": "User password changed", + "audit.action.vps.candidate_deleted": "VPS candidate deleted", + "audit.action.vps.candidate_saved": "VPS candidate saved", + "audit.action.vps.detached": "VPS Relay detached", + "audit.action.vps.relay_installed": "VPS Relay installed", + "audit.action.wireguard.client_connected": "WireGuard client connected", + "audit.action.wireguard.installed": "WireGuard installed", + "audit.action.wireguard.restarted": "WireGuard restarted", + "audit.action.wireguard.started": "WireGuard started", + "audit.action.wireguard.stopped": "WireGuard stopped", + "audit.result.applied": "applied", + "audit.result.available": "available", + "audit.result.changed": "changed", + "audit.result.created": "created", + "audit.result.current": "current", + "audit.result.deleted": "deleted", + "audit.result.detached": "detached", + "audit.result.denied": "denied", + "audit.result.downloaded": "downloaded", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Error", + "audit.result.installed": "installed", + "audit.result.invalid_credentials": "invalid credentials", + "audit.result.ok": "ok", + "audit.result.queued": "queued", + "audit.result.restarted": "restarted", + "audit.result.restored": "restored", + "audit.result.rotated": "rotated", + "audit.result.saved": "saved", + "audit.result.shown": "shown", + "audit.result.started": "started", + "audit.result.stopped": "stopped", + "audit.result.updated": "updated", + "settings.delete_user": "Delete", + "settings.delete_user_confirm": "Delete user {name}?", + "settings.edit_raw_config": "Edit interface config", + "settings.expert_mode": "Expert", + "settings.full_backup_component_clients": "WGTools-managed client metadata, private keys, PSKs, expiration settings, and client-group assignments required to regenerate client configs/QR codes.", + "settings.full_backup_component_db": "WGTools database: users, application preferences, mail/SMTP, Telegram settings and saved VPS Relay state.", + "settings.full_backup_component_relay": "VPS Relay recovery data: controller/tenant IDs, management token and home transport key. After restore WGTools can rebuild the local transport and reconnect to the preserved VPS tenant.", + "settings.full_backup_component_system": "WGTools IPv4-forwarding sysctl file, interface display-name metadata, and client-group policy/default definitions, when present. Automatic per-interface configuration history is intentionally excluded.", + "settings.full_backup_component_wg": "All detected WireGuard interface configurations from /etc/wireguard/, including their running/stopped state.", + "settings.full_backup_create_failed": "Could not create the full backup", + "settings.full_backup_creating": "Creating a complete backup…", + "settings.full_backup_download": "Create", + "settings.full_backup_downloaded": "Backup created and downloaded. Store it securely.", + "settings.full_backup_downloaded_short": "Full backup downloaded.", + "settings.full_backup_help": "Creates a portable WGTools backup for migration or disaster recovery. It includes WireGuard configs, users, settings, groups, managed-client data and the state required to reconnect to preserved VPS Relay tenants.", + "settings.full_backup_no_file": "No backup selected", + "settings.full_backup_restore": "Restore", + "settings.full_backup_restore_confirm": "Restore this full WGTools backup? Current users, settings, managed client data and all WireGuard configurations included in the backup will be restored. WireGuard interfaces may restart. WGTools creates a safety backup first and rolls back automatically if applying the restored state fails.", + "settings.full_backup_restore_failed": "Restore failed", + "settings.full_backup_restored": "Backup restored successfully. Sign in with an account from the restored backup.", + "settings.full_backup_restored_short": "Backup restored.", + "settings.full_backup_restoring": "Validating backup, creating a safety copy and restoring…", + "settings.full_backup_secret_warning": "This file contains sensitive data: WireGuard private keys, client private keys, preshared keys (PSKs), WGTools password hashes, the Telegram Bot token and the saved SMTP password. Store it like a password and never attach it to public issues or chats.", + "settings.full_backup_select": "Select", + "settings.full_backup_title": "Full backup and restore", + "settings.full_mode": "Server and client management enabled", + "settings.interface_help": "The managed WireGuard interface is selected when WGTools is deployed.", + "settings.language": "Language", + "settings.last_backup": "Last backup", + "settings.latest_version": "Latest release", + "settings.loading_config": "Loading configuration…", + "settings.mode": "Mode", + "settings.never_logged_in": "Never", + "settings.new_password": "New password", + "settings.no_backups": "No backups yet", + "settings.online_help": "A peer is considered online while its latest handshake is newer than this value. 30–3600 seconds.", + "settings.online_threshold": "Online threshold", + "settings.open_release": "Open release", + "settings.password_changed": "Password changed.", + "settings.passwords_mismatch": "Passwords do not match.", + "settings.project_github": "Project / GitHub", + "settings.raw_config_confirm": "Save this WireGuard configuration and apply it now? The selected interface will be restarted. A backup is created first and WGTools will roll back automatically if the new configuration does not start.", + "settings.raw_config_help": "Open the source configuration of the selected WireGuard interface.", + "settings.raw_config_title": "Raw WireGuard configuration", + "settings.raw_config_warning": "Expert mode: this is the real WireGuard server configuration and includes the server private key and any peer PSKs. Saving and applying restarts the WireGuard interface. WGTools creates a backup first and automatically rolls back if the new configuration cannot start.", + "settings.readonly_mode": "Client management enabled", + "settings.refresh_help": "How often WGTools requests fresh status data. 2–60 seconds.", + "settings.refresh_interval": "Refresh interval", + "settings.release_notes": "Release notes", + "settings.reload_config": "Reload from disk", + "settings.save_apply": "Save & Apply", + "settings.saved": "Settings saved.", + "settings.saved_reload": "Settings saved. Reloading…", + "settings.saving": "Saving settings…", + "settings.status": "Status refresh", + "settings.status_help": "Live dashboard and peer status refresh settings.", + "settings.subtitle": "WGTools interface preferences and status settings.", + "settings.syntax_hint": "WireGuard sections, keys, values and comments are highlighted while you edit.", + "settings.tab_about": "About", + "settings.tab_backups": "Backups", + "settings.tab_general": "General", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Users", + "settings.tabs_aria": "Settings sections", + "settings.telegram": "Telegram Bot", + "settings.telegram_allowed_ids": "Allowed Telegram user IDs", + "settings.telegram_allowed_ids_help": "One numeric user ID per line. An unauthorized /start message will reply with the sender’s Telegram user ID so you can add it here.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connected", + "settings.telegram_disabled": "Disabled", + "settings.telegram_dns": "Default client DNS", + "settings.telegram_dns_help": "Optional IPv4 DNS addresses separated by commas. Used for clients created by the bot.", + "settings.telegram_enabled": "Enable Telegram bot", + "settings.telegram_endpoint": "Default server address / domain", + "settings.telegram_endpoint_help": "Used when the bot creates a new client configuration. Enter only an IP address or domain; the WireGuard port is read from the server configuration.", + "settings.telegram_language": "Bot language", + "settings.telegram_language_auto": "Auto (Telegram language)", + "settings.telegram_last_poll": "Last Telegram contact", + "settings.telegram_not_configured": "Not configured", + "settings.telegram_remove_token": "Remove token", + "settings.telegram_remove_token_confirm": "Remove the saved Telegram bot token and disable the bot?", + "settings.telegram_save": "Save Telegram settings", + "settings.telegram_saved": "Telegram settings saved.", + "settings.telegram_setup_note": "Create a bot with @BotFather, save its token, enable the bot and send /start. If your user ID is not authorized yet, WGTools will show it — add that ID to the Allowed Telegram user IDs list.", + "settings.telegram_status": "Bot status", + "settings.telegram_subtitle": "Remote WireGuard management from Telegram: server status, clients, client creation/deletion and WireGuard start/restart/stop.", + "settings.telegram_test": "Test connection", + "settings.telegram_test_ok": "Telegram connection is working: @{username}", + "settings.telegram_test_recent_ok": "Telegram bot is working. The direct check timed out, but the bot contacted Telegram recently.", + "settings.telegram_token": "Bot token", + "settings.telegram_token_help": "Create a bot with @BotFather and paste its Bot API token here. API ID and API Hash are not required for the Telegram Bot API.", + "settings.telegram_token_keep": "Leave empty to keep the saved token.", + "settings.telegram_waiting": "Configured, waiting for bot service", + "settings.theme": "Theme", + "settings.theme_dark": "Dark", + "settings.theme_light": "Light", + "settings.theme_system": "System", + "settings.title": "Settings", + "settings.update_available": "Update available", + "settings.update_backup_queued": "Update queued. WGTools will create an automatic full backup before installing it…", + "settings.update_backup_running": "Creating the automatic full backup before update…", + "settings.update_check_failed": "Could not check for updates", + "settings.update_checking": "Checking the latest published GitHub Release…", + "settings.update_confirm": "Update WGTools from v{current} to v{latest}? A full backup and application rollback copy will be created first. The web interface will restart briefly.", + "settings.update_current": "Up to date", + "settings.update_downloading": "Downloading and validating the GitHub release…", + "settings.update_failed": "WGTools update failed.", + "settings.update_installing": "Installing the update. The web interface may be unavailable briefly…", + "settings.update_no_update": "WGTools is already up to date.", + "settings.update_not_checked": "Not checked", + "settings.update_queued": "Update queued. Waiting for the updater service…", + "settings.update_rollback_ok": "The previous WGTools application was restored automatically.", + "settings.update_rolling_back": "Update failed. Restoring the previous WGTools application…", + "settings.update_running": "Creating safety backups…", + "settings.update_safety_hint": "Updates are opt-in. Before installation WGTools creates a full state backup and an application rollback copy. If installation fails, the previous application is restored automatically. WireGuard itself is not restarted by the updater unless the new release explicitly changes its configuration.", + "settings.update_sidebar": "New version available", + "settings.update_sidebar_hint": "Open Settings → About", + "settings.update_starting": "Starting the update…", + "settings.update_status_unknown": "Update status is unavailable. Retrying…", + "settings.update_subtitle": "Project information, automatic release checks and safe updates from GitHub Releases.", + "settings.update_success": "WGTools was updated successfully to v{version}. Reloading…", + "settings.update_wgtools": "Update WGTools", + "settings.user_actions": "Actions", + "settings.user_created": "Created", + "settings.user_created_ok": "User created.", + "settings.user_deleted": "User deleted.", + "settings.user_equal_rights": "All WGTools users have the same permissions.", + "settings.user_last_login": "Last login", + "settings.user_name": "Username", + "settings.users": "Users", + "settings.users_subtitle": "Local WGTools accounts. E-mail is optional and is used only for password recovery when mail is enabled.", + "vps.add": "Add VPS", + "vps.add_help": "WGTools uses SSH to check or install Relay. Passwords and private SSH keys are never stored.", + "vps.add_title": "Add VPS", + "vps.agent": "Relay Agent", + "vps.agent_found": "Already installed", + "vps.agent_will_install": "Will be installed", + "vps.arch": "Architecture", + "vps.auth_method": "Authentication", + "vps.authentication": "SSH authentication", + "vps.check": "Check VPS", + "vps.check_failed": "VPS check failed", + "vps.check_link": "Check link", + "vps.check_ok": "VPS is compatible", + "vps.checking": "Checking SSH access and VPS compatibility…", + "vps.connections": "connections", + "vps.credentials_not_saved": "Used only for this check and not stored by WGTools.", + "vps.delete_candidate": "Remove", + "vps.delete_installed": "Remove VPS", + "vps.delete_installed_confirm": "Remove “{name}” from WGTools? The local Relay transport will be disconnected, but the Relay Agent and tenant on the VPS will be preserved. You can add this VPS again and WGTools will reconnect to the existing Relay instead of creating a new one. Clients using this Relay cannot connect through it until the VPS is reconnected.", + "vps.delete_installed_failed": "Could not remove VPS from WGTools", + "vps.delete_installed_ok": "VPS removed from WGTools. The remote Relay was preserved and can be reconnected.", + "vps.empty_help": "Add a Debian or Ubuntu VPS to check SSH access, operating system compatibility and required UDP ports.", + "vps.empty_title": "No VPS configured", + "vps.endpoint": "Public endpoint", + "vps.endpoint_domain": "Domain (recommended)", + "vps.endpoint_domain_hint": "If you later replace the primary VPS, changing DNS can keep existing client configurations unchanged.", + "vps.health_failed": "Relay link check failed", + "vps.host": "IP / hostname", + "vps.host_key": "SSH host key", + "vps.identity": "VPS connection", + "vps.install_failed": "Relay installation failed", + "vps.install_ok": "Relay installed and protected management link verified", + "vps.install_relay": "Install Relay", + "vps.install_title": "Install VPS Relay", + "vps.installed": "Installed", + "vps.installing": "Installing Relay Agent and establishing the protected transport tunnel…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Key passphrase", + "vps.link_ok": "Relay link OK", + "vps.multi_tenant_note": "A WGTools Relay Agent is already running on this VPS. It will not be replaced: this WGTools will get a separate isolated connection with its own keys and UDP ports.", + "vps.name": "Name", + "vps.no_domain": "IP endpoint", + "vps.not_installed": "Will be installed", + "vps.os": "Operating system", + "vps.password": "Password", + "vps.phase_note": "Relay Agent supports multiple independent WGTools controllers on one VPS. Each controller gets an isolated connection, keys and UDP ports; existing connections are left untouched.", + "vps.port_pair": "UDP ports", + "vps.ports_adjusted": "free ports selected", + "vps.private_key": "Private key", + "vps.privilege": "Privileges", + "vps.public_endpoint": "Future public endpoint", + "vps.ready_help": "SSH credentials are used for the compatibility check and immediate Relay installation; they are never saved.", + "vps.reconnect_note": "An existing Relay connection created by this WGTools was found on the VPS. WGTools will reconnect to that same tenant; no new tenant or UDP ports will be created.", + "vps.reconnect_ok": "Existing Relay reconnected successfully", + "vps.reconnect_relay": "Reconnect Relay", + "vps.relay_port": "Relay UDP port", + "vps.remove_confirm": "Remove this VPS candidate? No remote changes have been made.", + "vps.save_candidate": "Save candidate", + "vps.saved": "VPS candidate saved", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH key", + "vps.ssh_port": "SSH port", + "vps.ssh_user": "SSH user", + "vps.status_candidate": "Ready for installation", + "vps.status_installed": "Relay connected", + "vps.subtitle": "Prepare a public VPS for remote access when this WGTools server has no public IP.", + "vps.tenant": "Connection", + "vps.title": "VPS Relay", + "vps.transport_port": "Transport UDP port", + "vps.transport_port_hint": "Separate UDP port for the private Home ↔ VPS transport tunnel.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Saved", + "vps.active_short": "Active", + "dashboard.traffic_reset": "Reset", + "dashboard.traffic_reset_confirm": "Reset accumulated WireGuard traffic counters for this interface? Client counters will also restart from zero.", + "dashboard.traffic_reset_done": "Traffic counters reset", + "dashboard.traffic_reset_failed": "Could not reset traffic counters", + "audit.action.traffic.reset": "Traffic counters reset", + "audit.result.reset": "reset", + "server.mtu": "MTU", + "server.mtu_auto": "Auto", + "server.mtu_hint": "Optional. Leave empty for wg-quick automatic MTU. Set a value such as 1380 or 1420 only when required by the network, LTE or PPPoE path.", + "clients.peer_isolation": "VPN client isolation", + "clients.peer_isolation_enable": "Isolate from other VPN clients", + "clients.peer_isolation_hint": "Blocks traffic between this client and other addresses in the WireGuard pool. Access to the server itself, Internet, local networks and Site-to-site networks is still controlled by the other policies.", + "clients.credentials_rotate": "Client keys", + "clients.credentials_rotate_button": "Rotate keys", + "clients.credentials_rotate_confirm": "Generate new keys for this client? If it is currently connected, its active WireGuard session will be forcibly disconnected. Send a new config or QR afterward.", + "clients.credentials_rotate_confirm_psk": "Generate a new key pair and a new PSK for this client? If it is currently connected, its active WireGuard session will be forcibly disconnected. Send a new config or QR afterward.", + "clients.credentials_rotate_hint": "One action rotates PrivateKey/PublicKey and, when PSK is enabled, the PSK as well. Address, routes, group, schedule, isolation and accumulated statistics are preserved.", + "clients.credentials_rotating": "Generating new keys and disconnecting the old client session…", + "clients.credentials_rotated": "Client keys changed. If the client was connected, its old session was forcibly disconnected. The old config no longer works; send a new config or QR before reconnecting.", + "clients.credentials_rotated_short": "Client keys changed — new config required", + "audit.action.client.credentials_rotated": "Client keys rotated", + "clients.credentials_connection_lost": "The connection to WGTools was interrupted. If this panel was opened through the client whose keys were just rotated, this is expected: its old WireGuard session is disconnected immediately. Reconnect to WGTools by another path and issue the new config or QR.", + "nav.navigation": "Main navigation", + "nav.project_github": "WGTools on GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Optional now. It can be used for password recovery after mail is configured.", + "auth.forgot_password": "Forgot password?", + "auth.reset_title": "Reset password", + "auth.reset_subtitle": "Receive a one-time code by email and set a new WGTools password.", + "auth.reset_identifier": "Username or e-mail", + "auth.reset_identifier_help": "For privacy, WGTools always shows the same response whether the account exists or not.", + "auth.send_reset_code": "Send reset code", + "auth.reset_code_sent_generic": "If the account exists and has an e-mail address, a reset code has been sent. The code is valid for 15 minutes.", + "auth.reset_code": "6-digit code", + "auth.set_new_password": "Set new password", + "auth.request_another_code": "Request another code", + "auth.back_to_login": "Back to sign in", + "auth.reset_not_configured": "Password recovery by e-mail is not configured. Contact the WGTools administrator.", + "settings.tab_mail": "Mail", + "settings.mail": "Mail / SMTP", + "settings.mail_subtitle": "SMTP is used for password recovery.", + "settings.mail_not_configured": "Not configured", + "settings.mail_enabled": "Enable mail and password recovery", + "settings.mail_smtp_host": "SMTP server", + "settings.mail_smtp_port": "SMTP port", + "settings.mail_security": "Encryption", + "settings.mail_security_none": "No encryption", + "settings.mail_username": "SMTP username", + "settings.mail_username_help": "Used for SMTP authentication and as the sender e-mail address.", + "settings.mail_password": "SMTP password", + "settings.mail_password_keep": "Leave empty to keep the saved password.", + "settings.mail_from_email": "Sender e-mail", + "settings.mail_from_name": "Sender name", + "settings.mail_test_recipient": "Test recipient", + "settings.mail_test_recipient_help": "The test uses the currently saved SMTP settings.", + "settings.mail_remove_password": "Remove password", + "settings.mail_test": "Send test", + "settings.mail_save": "Save mail settings", + "settings.mail_enabled_badge": "Enabled", + "settings.mail_disabled_badge": "Disabled", + "settings.mail_saved": "Mail settings saved.", + "settings.mail_remove_password_confirm": "Remove the saved SMTP password and disable mail?", + "settings.mail_password_removed": "SMTP password removed and mail disabled.", + "settings.mail_test_recipient_required": "Enter a test recipient e-mail address.", + "settings.mail_testing": "Sending a test e-mail…", + "settings.mail_test_ok": "Test e-mail sent successfully.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Optional. Required only for self-service password recovery.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail saved.", + "settings.send_password_reset": "Send reset", + "settings.user_reset_mail_not_configured": "Configure and enable mail first.", + "settings.user_reset_email_missing": "Add an e-mail address first.", + "settings.user_reset_confirm": "Send a password reset code to {name} at {email}?", + "settings.user_reset_sent": "Password reset code sent to {email}.", + "audit.action.auth.password_reset_requested": "Password reset requested", + "audit.action.auth.password_reset_code_sent": "Password reset code sent", + "audit.action.auth.password_reset_completed": "Password reset completed", + "audit.action.auth.password_reset_failed": "Password reset failed", + "audit.action.mail.settings_updated": "Mail settings updated", + "audit.action.mail.test_sent": "Test e-mail sent", + "audit.action.mail.test_failed": "Test e-mail failed", + "audit.action.user.email_changed": "User e-mail changed", + "audit.action.user.password_reset_sent": "User password reset sent", + "audit.action.user.password_reset_failed": "User password reset failed", + "audit.result.accepted": "accepted", + "audit.result.sent": "sent", + "audit.result.invalid_code": "invalid code", + "common.copy": "Copy", + "common.copied": "Copied", + "clients.use_panel_host": "Use panel address", + "clients.use_panel_host_done": "Panel address inserted: {host}", + "clients.use_panel_host_failed": "Could not determine the panel address from the browser URL.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Built-in Let’s Encrypt HTTPS for direct WGTools access without a reverse proxy.", + "settings.https_disabled": "Disabled", + "settings.https_enabled": "Enabled", + "settings.https_enable": "Enable built-in HTTPS", + "settings.https_type": "Certificate for", + "settings.https_domain": "Domain", + "settings.https_public_ip": "Public IP", + "settings.https_target": "Domain or public IP", + "settings.https_email": "Let’s Encrypt e-mail", + "settings.https_port": "HTTPS port", + "settings.https_port80_note": "TCP port 80 must be reachable from the Internet for certificate issuance and automatic renewal. Open the selected HTTPS port for the WGTools panel itself.", + "settings.https_check_ports": "Check ports", + "settings.https_certificate": "Certificate", + "settings.https_certificate_ready": "Ready", + "settings.https_certificate_missing": "Not issued", + "settings.https_expires": "Valid until", + "settings.https_renewal": "Automatic renewal", + "settings.https_renewal_enabled": "Enabled", + "settings.https_renewal_disabled": "Disabled", + "settings.https_certificate_path": "Certificate", + "settings.https_private_key_path": "Private key", + "settings.https_issue": "Obtain / renew certificate", + "settings.https_port_free": "Free", + "settings.https_port_busy": "Busy", + "settings.https_ports_checked": "Port check completed.", + "settings.https_target_email_required": "Enter the domain/public IP and Let’s Encrypt e-mail.", + "settings.https_issue_confirm": "Request or renew the Let’s Encrypt certificate for {target}? The entered HTTPS settings will be saved. TCP port 80 must be reachable from the Internet.", + "settings.https_issuing": "Requesting certificate from Let’s Encrypt…", + "settings.https_issue_ok": "Certificate is ready.", + "settings.https_already_enabled": "Built-in HTTPS is already enabled.", + "settings.https_already_disabled": "Built-in HTTPS is already disabled.", + "settings.https_enable_confirm": "Enable built-in HTTPS on TCP {port} with path {path}? WGTools will restart and this page will reconnect at the new address.", + "settings.https_disable_confirm": "Disable built-in HTTPS and return WGTools to HTTP?", + "settings.https_switching": "Enabling HTTPS and restarting WGTools…", + "settings.https_switching_http": "Disabling HTTPS and restarting WGTools…", + "audit.action.https.certificate_issued": "HTTPS certificate issued", + "audit.action.https.certificate_failed": "HTTPS certificate request failed", + "audit.action.https.enabled": "HTTPS enabled", + "audit.action.https.disabled": "HTTPS disabled", + "audit.result.issued": "issued", + "audit.result.enabled": "enabled", + "audit.result.disabled": "disabled", + "settings.https_access_path": "Panel access path", + "settings.https_access_path_help": "Choose your own path. With built-in HTTPS enabled, requests outside it receive 404.", + "settings.https_enable_fields_required": "Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.", + "settings.https_use_panel_host": "Use panel address", + "settings.https_reconnecting": "WGTools is switching to the new HTTPS address…", + "server.tab_nodes": "Nodes", + "common.type": "Type", + "common.status": "Status", + "common.copy_failed": "Could not copy", + "clients.vpn_address": "VPN address", + "nodes.title": "WGTools Nodes", + "nodes.subtitle": "Link multiple WGTools servers into one protected network and publish only the networks that other nodes should be able to reach.", + "nodes.enable_hub": "Enable HUB", + "nodes.connect_hub": "Connect to HUB", + "nodes.settings": "Node settings", + "nodes.settings_action": "Settings", + "nodes.sync_now": "Synchronize", + "nodes.disable": "Disable Nodes", + "nodes.disable_action": "Disconnect", + "nodes.join_title": "Connect new nodes", + "nodes.join_help": "Create a one-time code and enter it on another WGTools panel together with the HUB service endpoint, for example vpn.example.com:51950. The code is valid for 15 minutes and can be used once.", + "nodes.create_code": "Create code", + "nodes.connected_nodes": "Connected nodes", + "nodes.connected_nodes_help": "Information about other panels, their published networks and clients. Remote clients are read-only.", + "nodes.enable_hub_help": "This panel becomes the central node. On the same port number the HUB accepts WireGuard over UDP and protected initial pairing over TCP.", + "nodes.node_name": "Node name", + "nodes.transport_network": "Node transport network", + "nodes.transport_help": "A separate private network used only for WGTools ↔ WGTools transport. It must not overlap your VPN/LAN networks.", + "nodes.panel_url": "Panel URL", + "nodes.panel_url_help": "Optional. This is only an informational link for the “Open panel” button on other nodes and is never used by the Nodes connection itself.", + "nodes.extra_networks": "Additional node networks", + "nodes.extra_networks_help": "One network per line. Interface VPN networks and Site-to-site client remote networks are published automatically. Add only other routed LAN/networks here, for example 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools pre-fills detected VPN networks, Site-to-Site networks and locally routed LANs. Keep only the networks this node should publish into Nodes. One network per line.", + "nodes.published_networks_settings_help": "One network per line. This is the explicit list of networks this node publishes into Nodes. Removing a line stops advertising that network to other nodes.", + "nodes.available_networks_help": "Currently detected: {networks}. Newly detected networks are not published automatically; add the ones you want to the list above.", + "nodes.available_networks_none": "No additional local networks are currently detected.", + "nodes.connect_help": "Enter the HUB service endpoint and one-time code. The web panel URL, HTTPS port, certificate and private path are not used for Nodes pairing.", + "nodes.join_code": "Connection code", + "nodes.connect_reachability_note": "Initial pairing uses protected TCP on the specified port. After wgnode0 is created, networks, status, versions and read-only client data synchronize with the HUB over its internal WireGuard address.", + "nodes.connect": "Connect", + "nodes.settings_help": "Node name, optional “Open panel” link and the explicit published-network list. The panel URL is not used for Nodes pairing or synchronization.", + "nodes.details": "Details", + "nodes.not_configured": "WGTools Nodes is not configured", + "nodes.not_configured_help": "Enable HUB on this panel or connect it to an existing WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connected to HUB", + "nodes.mode_none": "Not configured", + "nodes.role": "Role", + "nodes.tunnel": "Node tunnel", + "nodes.node_ip": "Node address", + "nodes.endpoint": "HUB endpoint", + "nodes.published_networks": "Published networks", + "nodes.last_sync": "Last sync", + "nodes.no_nodes_hub": "No nodes are connected yet. Create a connection code and use it on another WGTools panel.", + "nodes.no_nodes_spoke": "No remote node information has been received yet.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Open panel", + "nodes.route_conflict": "Route conflict", + "nodes.no_published_networks": "No published networks", + "nodes.load_failed": "Could not load WGTools Nodes", + "nodes.enable_hub_confirm": "Enable WGTools HUB and create the internal Node WireGuard tunnel?", + "nodes.applying": "Configuring the WGTools Nodes tunnel…", + "nodes.enable_failed": "Could not enable HUB", + "nodes.hub_enabled": "WGTools HUB enabled", + "nodes.connecting": "Verifying the HUB code and creating the protected Node tunnel…", + "nodes.connect_failed": "Could not connect to HUB", + "nodes.connected": "Connected to WGTools HUB", + "nodes.settings_failed": "Could not save Node settings", + "nodes.settings_saved": "Node settings saved", + "nodes.code_failed": "Could not create connection code", + "nodes.code_expires": "One-time code. Valid until {time}.", + "nodes.code_copied": "Connection code copied", + "nodes.network_vpn": "VPN clients", + "nodes.network_site_to_site": "Site-to-site network", + "nodes.network_custom": "Additional network", + "nodes.conflict": "Conflict", + "nodes.remote_clients": "Clients (read-only)", + "nodes.no_clients": "No clients reported by this node", + "nodes.details_failed": "Could not load Node details", + "nodes.remove_confirm": "Remove node “{name}” from this HUB? Its internal tunnel access will be revoked.", + "nodes.remove_failed": "Could not remove Node", + "nodes.removed": "Node removed", + "nodes.disable_hub_confirm": "Disable HUB and disconnect all WGTools Nodes? The internal Node tunnel will be removed.", + "nodes.disconnect_confirm": "Disconnect this WGTools panel from its HUB and remove the internal Node tunnel?", + "nodes.disable_failed": "Could not disable WGTools Nodes", + "nodes.disabled": "WGTools Nodes disabled", + "nodes.sync_failed": "Node synchronization failed", + "nodes.synced": "Node information synchronized", + "nodes.service_port": "Nodes port", + "nodes.service_port_help": "The same port number is used simultaneously: UDP for WireGuard and TCP for protected initial pairing.", + "nodes.hub_port_forward_note": "If the HUB is behind NAT, forward the same port to it for both UDP and TCP. The WGTools web port, HTTPS and private panel path are unrelated to Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Nodes domain/IP and port without http:// or https://, for example vpn.example.com:51950.", + "settings.collapse_sidebar": "Collapse sidebar", + "settings.expand_sidebar": "Expand sidebar", + "settings.https_issue_fields_required": "Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.", + "settings.https_issue_ok_saved": "Certificate is ready and HTTPS settings are saved.", + "settings.https_enable_need_certificate": "First obtain a certificate.", + "settings.https_enable_certificate_mismatch": "Obtain a certificate for the current domain or public IP first.", + "settings.https_enable_certificate_expired": "The certificate has expired. Renew it before enabling HTTPS.", + "settings.https_enable_certificate_ready": "Certificate is ready — built-in HTTPS can now be enabled.", + "settings.https_enable_active_help": "Clear the checkbox and save to return to HTTP.", + "settings.https_certificate_expired": "Expired", + "settings.https_certificate_wrong_target": "For another address", + "nodes.network_conflict_error": "Published networks conflict with another Node or the Nodes transport network: {conflicts}. Remove or change the conflicting network.", + "nodes.networks_changed": "Detected networks changed after the published list was last saved. New: {added}. No longer detected: {removed}. Review the published network list and save the settings after checking it.", + "nodes.review_networks": "Review networks", + "nodes.vpn_pool_mismatch": "VPN pool changed: Nodes still publishes {old}, while the current WireGuard VPN pool is {current}. Open Node settings and update the published networks.", + "server.error_vpn_network_invalid": "VPN network must be a valid IPv4 network, for example 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Only IPv4 VPN networks are supported.", + "server.error_vpn_network_too_small": "The VPN network must contain at least two usable addresses.", + "server.error_vpn_network_no_hosts": "The selected VPN network has no usable server addresses.", + "server.error_server_address_prefix": "The server VPN address must include a prefix, for example 10.0.0.1/24.", + "server.error_server_address_network": "The server VPN address must belong to the selected VPN address pool and use the same prefix.", + "server.error_server_address_reserved": "The server VPN address cannot be the network or broadcast address.", + "server.error_listen_port_number": "The WireGuard port must be a number.", + "server.error_listen_port_range": "The WireGuard port must be between 1 and 65535.", + "server.error_mtu_number": "MTU must be a number.", + "auth.mfa_title": "Two-factor authentication", + "auth.mfa_login_help": "Enter the 6-digit code from Google Authenticator or one of your recovery codes.", + "auth.mfa_code": "Authentication code", + "auth.mfa_verify": "Verify and sign in", + "auth.mfa_back": "Back to password", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Two-factor authentication (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Enabled", + "settings.mfa_disabled": "Disabled", + "settings.mfa_google_help": "Protect this account with Google Authenticator or another TOTP-compatible authenticator. Your current password is required to start setup.", + "settings.current_password": "Current password", + "settings.mfa_start": "Set up Google Authenticator", + "settings.mfa_secret": "Manual setup key", + "settings.mfa_scan_help": "Scan the QR code in Google Authenticator, then enter the current 6-digit code to finish enabling MFA.", + "settings.mfa_code": "6-digit code", + "settings.mfa_enable": "Enable MFA", + "settings.mfa_manage_help": "To change MFA, enter your current password and a Google Authenticator code or recovery code.", + "settings.mfa_code_or_recovery": "Authenticator or recovery code", + "settings.mfa_regenerate": "New recovery codes", + "settings.mfa_disable": "Disable MFA", + "settings.mfa_recovery_title": "Recovery codes", + "settings.mfa_recovery_help": "Save these codes now. Each code can be used once if Google Authenticator is unavailable. They are not shown again.", + "settings.mfa_recovery_remaining": "Recovery codes remaining: {count}", + "settings.mfa_enabled_ok": "MFA enabled.", + "settings.mfa_disabled_ok": "MFA disabled.", + "settings.mfa_disable_confirm": "Disable two-factor authentication for this account?", + "settings.mfa_regenerate_confirm": "Replace all existing recovery codes?", + "settings.mfa_recovery_regenerated": "New recovery codes created.", + "audit.action.auth.mfa_failed": "MFA verification failed", + "audit.action.auth.mfa_recovery_used": "MFA recovery code used", + "audit.action.user.mfa_setup_started": "MFA setup started", + "audit.action.user.mfa_enabled": "MFA enabled", + "audit.action.user.mfa_disabled": "MFA disabled", + "audit.action.user.mfa_disabled_cli": "MFA disabled from CLI", + "audit.action.user.mfa_recovery_regenerated": "MFA recovery codes regenerated", + "settings.mfa_error_password": "Invalid current password.", + "settings.mfa_error_code": "Invalid authentication code.", + "settings.mfa_error_already_enabled": "MFA is already enabled.", + "settings.mfa_error_not_enabled": "MFA is not enabled.", + "settings.mfa_error_not_started": "Start MFA setup again.", + "trace.title": "Traceroute, ping and route map", + "trace.subtitle": "Measure latency to a VPS or other server and see where delay appears along the route.", + "trace.target": "Server IP or hostname", + "trace.show_map": "Show route on map", + "trace.run": "Run trace", + "trace.geo_note": "Geolocation is approximate. When the map is enabled, public hop IP addresses are sent to ipwho.is for location lookup; map tiles are loaded from OpenStreetMap.", + "trace.latency_note": "Traceroute measures latency in milliseconds, not throughput in Mbit/s.", + "trace.map": "Route map", + "trace.map_hint": "Interactive map: drag to pan, use the mouse wheel or +/− to zoom, and click a hop for details.", + "trace.hop": "Hop / IP", + "trace.location": "Location", + "trace.avg_rtt": "Avg RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Loss", + "trace.summary_target": "Target", + "trace.summary_ping": "Average ping", + "trace.summary_loss": "Ping loss", + "trace.summary_hops": "Hops", + "trace.no_reply": "No reply", + "trace.private": "Private network", + "trace.unknown": "Unknown", + "trace.running": "Running ping and traceroute… This can take up to a minute.", + "trace.done": "Network trace completed.", + "trace.failed": "Network trace failed", + "trace.partial_geo": "Some public hops could not be geolocated.", + "trace.not_reached": "Target was not reached by traceroute.", + "trace.reached": "Target reached", + "trace.ms": "ms", + "server.tab_trace": "Trace", + "trace.map_controls": "Map controls", + "trace.zoom_in": "Zoom in", + "trace.zoom_out": "Zoom out", + "trace.fit_route": "Fit route", + "trace.fit": "Fit", + "trace.map_click_hint": "Click a hop for IP, location, ASN and RTT details.", + "trace.route_path": "Route", + "trace.ping_ok_trace_filtered": "Target responds to ping; final traceroute hops do not reply.", + "trace.latency_legend": "Latency growth between responding hops", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — increased", + "trace.latency_bad": "Δ RTT > 20 ms — sharp jump" +} diff --git a/app/locales/es.json b/app/locales/es.json new file mode 100644 index 0000000..8c90bb0 --- /dev/null +++ b/app/locales/es.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Crear usuario", + "auth.login_subtitle": "Introduce tu usuario y contraseña de WGTools.", + "auth.login_title": "Iniciar sesión en WGTools", + "auth.password": "Contraseña", + "auth.password_repeat": "Repetir contraseña", + "auth.setup_help": "La primera cuenta tiene acceso completo a WGTools. Puedes crear más usuarios después en Ajustes.", + "auth.setup_subtitle": "Para gestionar el servidor, primero debes crear una cuenta de WGTools.", + "auth.setup_title": "Crear el primer usuario", + "auth.sign_in": "Iniciar sesión", + "auth.sign_out": "Cerrar sesión", + "auth.username": "Nombre de usuario", + "clients.actions": "Acciones", + "clients.add": "+ Añadir cliente", + "clients.address": "Dirección VPN", + "clients.address_hint": "Se sugiere automáticamente la primera dirección libre.", + "clients.allowed_ips_required": "Introduce al menos una red AllowedIPs para la configuración del cliente.", + "clients.basic_connection": "Ajustes de conexión", + "clients.basic_details": "Cliente", + "clients.client": "Cliente", + "clients.client_allowed_ips": "AllowedIPs en la configuración del cliente", + "clients.config_private_warning": "Esta configuración contiene la clave privada del cliente. Guárdala de forma segura.", + "clients.config_title": "Configuración del cliente", + "clients.config_unavailable": "Configuración no disponible", + "clients.connection_direct": "Directamente a WGTools", + "clients.connection_path": "Ruta de conexión", + "clients.connection_relay": "Relay VPS", + "clients.connection_via": "Conectar a través de", + "clients.connection_via_hint": "Elige la entrada pública usada por el cliente. Relay solo aparece si está instalado en la interfaz WireGuard seleccionada.", + "clients.copy_config": "Copiar", + "clients.copy_done": "Configuración copiada", + "clients.create_subtitle": "Crea un par WireGuard y genera su configuración de cliente.", + "clients.create_title": "Crear cliente", + "clients.creating": "Generando claves y aplicando cliente…", + "clients.day_fri": "Vie", + "clients.day_mon": "Lun", + "clients.day_sat": "Sáb", + "clients.day_sun": "Dom", + "clients.day_thu": "Jue", + "clients.day_tue": "Mar", + "clients.day_wed": "Mié", + "clients.delete_confirm": "¿Eliminar este cliente de WireGuard? WGTools creará una copia y eliminará las reglas automáticas asociadas.", + "clients.deleted": "Cliente eliminado", + "clients.dns": "DNS (opcional)", + "clients.dns_hint": "Servidores DNS IPv4 separados por comas.", + "clients.download_config": "Descargar .conf", + "clients.duplicate": "Duplicar", + "clients.duplicate_address_error": "Otro par ya usa esta dirección VPN.", + "clients.duplicate_name_error": "Ya existe un par con ese nombre.", + "clients.duplicate_ready": "Copia lista. WGTools asignó un nombre y una dirección VPN nuevos. Revisa los ajustes antes de guardar.", + "clients.duplicate_site_hint": "Se han borrado las redes remotas para evitar rutas duplicadas. Introduce las redes del nuevo par Site-to-site.", + "clients.duplicate_suffix": "copia", + "clients.edit_subtitle": "Actualiza el par del servidor. Los cambios se aplican sin reiniciar WireGuard.", + "clients.edit_title": "Editar cliente", + "clients.endpoint": "Endpoint del servidor", + "clients.endpoint_hint": "Para clientes remotos, usa la IP pública o el dominio que redirige el puerto WireGuard a este servidor.", + "clients.existing": "Par existente", + "clients.expiration": "Duración del acceso", + "clients.expiration_action": "Al caducar", + "clients.expiration_action_hint": "Si se desmarca, el cliente sigue en WGTools pero pierde acceso a WireGuard. Elige una nueva duración o Sin caducidad y guarda para restaurarlo.", + "clients.expiration_datetime": "Caduca el", + "clients.expiration_datetime_hint": "Usa la fecha y hora locales del navegador.", + "clients.expiration_delete": "Eliminar cliente", + "clients.expiration_future_required": "Elige una fecha y hora futuras.", + "clients.expiration_hint": "Al caducar, WGTools ejecuta la acción elegida en el siguiente minuto. Antes crea una copia de WireGuard.", + "clients.expire_1d": "1 día", + "clients.expire_1h": "1 hora", + "clients.expire_3h": "3 horas", + "clients.expire_6h": "6 horas", + "clients.expire_custom": "Fecha y hora personalizadas", + "clients.expire_never": "Sin caducidad", + "clients.expired": "Caducado", + "clients.expired_disabled_hint": "El acceso ha caducado. El cliente se conserva, pero WireGuard está deshabilitado. Elige otra duración o Sin caducidad y guarda.", + "clients.expired_disabled_short": "Caducado · desactivado", + "clients.expired_disabled_status": "Caducado", + "clients.expires_days": "Caduca en {n} d", + "clients.expires_hours": "Caduca en {n} h", + "clients.expires_minutes": "Caduca en {n} min", + "clients.generated_config": "Configuración del cliente generada", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 segundos es un buen valor por defecto para clientes tras NAT.", + "clients.local_access_exceptions": "Direcciones locales permitidas", + "clients.local_access_exceptions_hint": "IP o CIDR opcionales accesibles aunque su red local o Site-to-site esté bloqueada. Sepáralos por comas.", + "clients.managed": "Gestionado por WGTools", + "clients.name": "Nombre", + "clients.no_peers": "No se encontraron pares", + "clients.peers": "Pares", + "clients.peers_subtitle": "Los cambios se respaldan y aplican con wg syncconf sin reiniciar la interfaz WireGuard.", + "clients.protected_networks_reference": "Redes locales bloqueadas (referencia)", + "clients.protected_networks_reference_hint": "Estas redes no se escriben en AllowedIPs. La política del servidor WGTools bloquea su acceso; arriba pueden permitirse direcciones individuales.", + "clients.psk": "Clave precompartida (PSK)", + "clients.psk_enable": "Usar una clave WireGuard precompartida adicional", + "clients.psk_hint": "Recomendado. Añade un secreto simétrico al handshake WireGuard. Los clientes estándar lo admiten; WGTools incluye el PSK en la configuración y el QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generando QR…", + "clients.quick_search": "Búsqueda rápida", + "clients.quick_search_clear": "Borrar búsqueda", + "clients.quick_search_empty": "Ningún cliente coincide", + "clients.relay_endpoint_note": "La configuración generada se conectará a {endpoint}. El servidor WireGuard sigue en este host WGTools.", + "clients.relay_required": "Elige un Relay VPS para este cliente.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "no disponible", + "clients.relay_vps": "Relay VPS", + "clients.relay_vps_hint": "El endpoint del cliente se genera automáticamente desde este Relay.", + "clients.remote_hint": "Redes detrás de este par. Una por línea o separadas por comas.", + "clients.remote_networks": "Redes remotas", + "clients.remote_required": "Introduce al menos una red remota para el par Site-to-site.", + "clients.required": "Se requieren nombre y dirección VPN.", + "clients.route_custom": "Personalizada", + "clients.route_full": "Túnel completo", + "clients.route_full_except_local": "Túnel completo excepto redes locales", + "clients.route_hint": "Solo estas redes se escriben en AllowedIPs de la configuración del cliente.", + "clients.route_preset": "Tráfico por VPN", + "clients.route_vpn": "Solo red VPN", + "clients.route_vpn_lan": "VPN + LAN local", + "clients.saved": "Cliente guardado", + "clients.schedule_blocked_short": "Horario · bloqueado", + "clients.schedule_blocked_status": "Bloqueado por horario", + "clients.schedule_days": "Días permitidos", + "clients.schedule_days_required": "Elige al menos un día para el horario.", + "clients.schedule_disabled_hint": "Este cliente está bloqueado por su horario. WGTools restaurará el par automáticamente en el próximo periodo permitido.", + "clients.schedule_enable": "Limitar acceso por horario", + "clients.schedule_from": "Acceso desde", + "clients.schedule_hint": "WGTools puede deshabilitar y restaurar el cliente en días y horas seleccionados sin cambiar su configuración.", + "clients.schedule_short": "Horario", + "clients.schedule_time_required": "Define las horas de inicio y fin del horario.", + "clients.schedule_timezone_hint": "El horario usa la hora local del servidor WireGuard. Admite periodos nocturnos como 22:00–06:00.", + "clients.schedule_title": "Horario de acceso", + "clients.schedule_to": "Acceso hasta", + "clients.security_access": "Seguridad y horario de acceso", + "clients.server_host": "Dirección / dominio del servidor", + "clients.server_host_hint": "IP pública o dominio usado por el cliente. Se sugieren valores anteriores.", + "clients.server_host_required": "Se requiere dirección / dominio del servidor para generar la configuración.", + "clients.server_peer": "Par servidor", + "clients.server_port": "Puerto WireGuard", + "clients.server_port_hint": "Se obtiene automáticamente de la configuración del servidor.", + "clients.site_to_site": "Sitio a sitio", + "clients.status": "Estado", + "clients.subtitle": "Pares WireGuard, estado en directo y gestión de configuraciones de clientes.", + "clients.tab_basic": "Básico", + "clients.tab_config": "Configuración", + "clients.tab_policy": "Políticas", + "clients.tab_security": "Seguridad", + "clients.title": "Clientes", + "clients.type": "Tipo", + "clients.unmanaged_note": "Este par existía antes de WGTools. Su clave privada no se puede recuperar. WGTools puede editarlo en el servidor pero no generar su configuración de cliente ni QR.", + "clients.updating": "Actualizando cliente…", + "common.actions": "Acciones", + "common.ago": "hace", + "common.cancel": "Cancelar", + "common.checking": "Comprobando…", + "common.close": "Cerrar", + "common.config": "Configuración", + "common.delete": "Eliminar", + "common.disabled": "Desactivado", + "common.edit": "Editar", + "common.enabled": "Activado", + "common.loading": "Cargando…", + "common.never": "Nunca", + "common.no": "No", + "common.not_configured": "Sin configurar", + "common.not_installed": "No instalado", + "common.offline": "desconectado", + "common.online": "conectado", + "common.refresh": "Actualizar", + "common.running": "En ejecución", + "common.save": "Guardar", + "common.stopped": "Detenido", + "common.total": "Total", + "common.unknown": "Desconocido", + "common.updated": "Actualizado", + "common.yes": "Sí", + "dashboard.active_peers": "Pares activos", + "dashboard.active_peers_subtitle": "Datos en directo de wg show.", + "dashboard.activity": "Resumen del sistema", + "dashboard.activity_subtitle": "Comprobaciones de solo lectura de WireGuard en ejecución.", + "dashboard.cores": "núcleos", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Últimas 24 h", + "dashboard.history_avg": "Prom.", + "dashboard.history_max": "Máx.", + "dashboard.history_min": "Mín.", + "dashboard.history_now": "ahora", + "dashboard.memory": "Memoria", + "dashboard.network": "Red", + "dashboard.peers": "Pares", + "dashboard.quick_search": "Búsqueda rápida", + "dashboard.quick_search_clear": "Borrar búsqueda", + "dashboard.quick_search_empty": "Ningún par coincide con la búsqueda", + "dashboard.restart": "Reiniciar", + "dashboard.restart_confirm": "¿Reiniciar WireGuard? Los clientes VPN activos se reconectarán automáticamente.", + "dashboard.restart_ok": "WireGuard reiniciado.", + "dashboard.routing": "Enrutamiento", + "dashboard.site_to_site": "Sitio a sitio", + "dashboard.start": "Iniciar", + "dashboard.start_ok": "WireGuard iniciado.", + "dashboard.stop": "Detener", + "dashboard.stop_confirm": "¿Detener WireGuard? Se desconectarán los clientes VPN activos.", + "dashboard.stop_ok": "WireGuard detenido.", + "dashboard.subtitle": "Estado del servidor WireGuard, pares y tráfico en directo.", + "dashboard.title": "Panel principal", + "dashboard.traffic": "Tráfico", + "dashboard.uptime": "Tiempo de actividad", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Política de acceso al servidor", + "groups.additional_allowed": "Direcciones adicionales permitidas", + "groups.additional_blocked": "Direcciones adicionales bloqueadas", + "groups.allow": "Permitir", + "groups.allowed": "Permitido", + "groups.allowed_addresses": "Direcciones / redes permitidas", + "groups.apply_current_template": "Aplicar plantilla actual del grupo", + "groups.apply_defaults": "Aplicar plantilla actual del grupo", + "groups.apply_defaults_hint": "Copia rutas, DNS y Keepalive de la plantilla al cliente. Guarda el cliente y genera nueva configuración o QR si debes actualizar el dispositivo.", + "groups.basic": "Información básica", + "groups.block": "Bloquear", + "groups.blocked": "Bloqueado", + "groups.blocked_addresses": "Direcciones / redes bloqueadas", + "groups.client_config_source": "Origen de configuración del cliente", + "groups.client_defaults": "Valores predeterminados del cliente", + "groups.client_group_hint": "Grupo opcional para reutilizar políticas de acceso y valores del cliente. Los grupos corresponden a la interfaz WireGuard seleccionada.", + "groups.config_differs": "La configuración del cliente difiere de la plantilla del grupo. La política del servidor está actualizada, pero el dispositivo requiere una nueva configuración o QR.", + "groups.config_differs_short": "Configuración distinta de la del grupo", + "groups.create": "Crear grupo", + "groups.create_title": "Crear grupo", + "groups.created": "Grupo creado", + "groups.creating": "Creando grupo…", + "groups.defaults_applied": "Plantilla del grupo aplicada. Guarda el cliente para conservarla.", + "groups.defaults_hint": "Define qué tráfico envía el cliente mediante WireGuard. La política del servidor determina los accesos permitidos. Los cambios de plantilla nunca modifican configuraciones ya instaladas.", + "groups.delete_message": "¿Eliminar «{name}»? Las configuraciones de clientes nunca se borran con el grupo.", + "groups.delete_move": "Mover sus clientes a otro grupo", + "groups.delete_title": "Eliminar grupo de clientes", + "groups.delete_unassign": "Quitar la asignación de grupo a sus clientes", + "groups.deleted": "Grupo eliminado", + "groups.deleting": "Actualizando clientes y eliminando grupo…", + "groups.description": "Descripción", + "groups.edit_title": "Editar grupo", + "groups.editor_subtitle": "Un grupo combina una política de acceso activa con una plantilla de configuración de clientes.", + "groups.effective_allow": "Excepciones permitidas", + "groups.effective_deny": "Excepciones bloqueadas", + "groups.effective_policy": "Política efectiva del servidor", + "groups.empty": "Aún no hay grupos de clientes. Crea uno para reutilizar políticas y configuraciones predeterminadas.", + "groups.group": "Grupo", + "groups.inherit": "Heredar", + "groups.internet_access": "Acceso a Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Redes locales", + "groups.local_short": "Local", + "groups.manage": "Grupos", + "groups.members_count": "{count} clientes", + "groups.name": "Nombre", + "groups.name_required": "Se requiere el nombre del grupo.", + "groups.new_client_defaults": "Plantilla de configuración del cliente", + "groups.new_clients_short": "Clientes nuevos", + "groups.no_group": "Sin grupo", + "groups.none": "Ninguno", + "groups.override_client_config": "Anular la plantilla de grupo para este cliente", + "groups.override_client_config_hint": "Desactivado: rutas, DNS y Keepalive vienen del grupo. Activado: el cliente conserva sus valores. Las excepciones de política del servidor siguen independientes.", + "groups.policy_addresses_hint": "Direcciones IPv4 o CIDR separados por comas. Las excepciones del cliente prevalecen sobre las del grupo.", + "groups.policy_custom": "Política personalizada", + "groups.policy_inherit": "Usar política del grupo", + "groups.policy_mode": "Origen de la política", + "groups.policy_mode_hint": "La política del grupo se hereda por defecto. Las excepciones del cliente no modifican el grupo.", + "groups.routes_required": "Las rutas del cliente no pueden estar vacías.", + "groups.subtitle": "Reutiliza políticas de acceso y valores predeterminados para los clientes de la interfaz WireGuard elegida.", + "groups.title": "Grupos de clientes", + "groups.traffic_through_vpn": "Tráfico por VPN", + "groups.updated": "Grupo actualizado", + "groups.updating": "Actualizando política del grupo…", + "help.example_note": "Todas las direcciones, interfaces, nombres de pares y dominios de los ejemplos son ficticios. Sustitúyelos por los datos de tu red.", + "help.navigation": "Navegación de ayuda", + "help.open": "Abrir ayuda", + "help.subtitle": "Ayuda clara para Panel, Servidor, Clientes y Ajustes con ejemplos prácticos.", + "help.title": "Ayuda de WGTools", + "interfaces.add": "+ Añadir interfaz", + "interfaces.create": "Crear interfaz", + "interfaces.create_confirm": "¿Crear e iniciar la interfaz {name}?", + "interfaces.create_failed": "No se pudo crear la interfaz", + "interfaces.create_hint": "Antes de crear la configuración, WGTools comprueba que la red VPN, el puerto UDP y la tabla de enrutamiento no entren en conflicto con otras interfaces WireGuard.", + "interfaces.create_subtitle": "Crea una interfaz WireGuard independiente con su propio grupo de direcciones, puerto UDP y opciones de enrutamiento.", + "interfaces.create_title": "Añadir interfaz WireGuard", + "interfaces.created": "Interfaz creada correctamente.", + "interfaces.creating": "Generando claves, guardando configuración e iniciando WireGuard…", + "interfaces.current": "Actual", + "interfaces.delete": "Eliminar", + "interfaces.delete_confirm": "¿Eliminar la interfaz {name}? Se borrarán su configuración WireGuard y todos sus pares. Antes se creará una copia.", + "interfaces.delete_failed": "No se pudo eliminar la interfaz", + "interfaces.delete_last": "No se puede eliminar aquí la última interfaz WireGuard configurada.", + "interfaces.delete_tooltip": "Eliminar esta interfaz WireGuard", + "interfaces.deleted": "Interfaz eliminada. Copia: {backup}", + "interfaces.deleting": "Deteniendo WireGuard y eliminando interfaz…", + "interfaces.display_name": "Nombre visible", + "interfaces.display_name_edit_hint": "Solo nombre visible: el nombre de la interfaz Linux no cambia.", + "interfaces.display_name_hint": "Nombre opcional, p. ej. Trabajo o Contratistas.", + "interfaces.identity": "Identidad de la interfaz", + "interfaces.none": "No se encontraron interfaces WireGuard", + "interfaces.none_configured": "Aún no hay interfaces WireGuard configuradas.", + "interfaces.peers_short": "pares", + "interfaces.rename_failed": "No se pudo guardar el nombre de la interfaz.", + "interfaces.select": "Seleccionar", + "interfaces.subtitle": "Cada interfaz tiene su red VPN, puerto, pares y políticas. Selecciona una para gestionarla en WGTools.", + "interfaces.switch_title": "Interfaces WireGuard", + "interfaces.system_name": "Nombre del sistema", + "interfaces.system_name_hint": "Nombre de la interfaz Linux, p. ej. wg1. No se puede cambiar después.", + "interfaces.title": "Interfaces WireGuard", + "interfaces.unique_port_hint": "Cada interfaz WireGuard del servidor debe usar un puerto UDP distinto.", + "interfaces.unique_table_hint": "WGTools recomienda una tabla de rutas distinta por interfaz. Déjala vacía para el enrutamiento normal.", + "nav.clients": "Clientes", + "nav.dashboard": "Panel principal", + "nav.server": "Servidor", + "nav.settings": "Configuración", + "server.access_apply_confirm": "¿Guardar y aplicar esta regla de firewall? WireGuard se reiniciará brevemente y se creará una copia.", + "server.access_rule_deleted": "Regla de acceso eliminada.", + "server.access_rule_help": "Crea una regla FORWARD sin editar comandos iptables manualmente.", + "server.access_rule_order_hint": "WGTools inserta reglas al inicio de FORWARD para aplicar restricciones antes de las reglas VPN ACCEPT generales.", + "server.access_rule_saved": "Regla de acceso guardada y aplicada.", + "server.action": "Acción", + "server.action_hint": "REJECT notifica el rechazo al cliente; DROP descarta sin respuesta; ACCEPT permite explícitamente.", + "server.add_access_rule": "Añadir regla de acceso", + "server.add_route": "Añadir ruta", + "server.address": "Dirección", + "server.any": "Cualquiera", + "server.any_protocol": "Cualquiera", + "server.apply_confirm": "¿Guardar y aplicar los ajustes del servidor? WireGuard se reiniciará brevemente. Se creará una copia y, si falla el arranque, WGTools restaurará la configuración anterior.", + "server.apply_settings": "Guardar y aplicar", + "server.applying_rule": "Creando copia y aplicando…", + "server.applying_settings": "Validando ajustes, creando copia y aplicando…", + "server.basic_settings": "Ajustes básicos", + "server.config_tab_help": "Abrir el editor de configuración sin procesar de la interfaz WireGuard seleccionada.", + "server.create_confirm": "¿Crear e iniciar el servidor WireGuard con estos ajustes?", + "server.create_server": "Crear servidor", + "server.create_step_conf": "Crear configuración de la interfaz WireGuard con permisos 600.", + "server.create_step_forward": "Configurar reenvío, NAT y enrutamiento por políticas opcional.", + "server.create_step_key": "Generar nuevo par de claves del servidor.", + "server.create_step_start": "Habilitar e iniciar la interfaz wg-quick seleccionada.", + "server.create_subtitle": "WireGuard está instalado, pero la interfaz seleccionada aún no está configurada.", + "server.create_success": "Servidor WireGuard creado correctamente.", + "server.create_title": "Crear servidor WireGuard", + "server.creating": "Generando claves, escribiendo configuración e iniciando WireGuard…", + "server.custom_preserved": "Se conservan bloques de pares, rutas Site-to-site y reglas PostUp/PostDown no gestionadas por estos campos.", + "server.delete_access_confirm": "¿Eliminar esta regla de acceso y aplicar el cambio?", + "server.delete_route_confirm": "¿Eliminar esta ruta personalizada y aplicar el cambio?", + "server.destination": "Destino", + "server.destination_hint": "Vacío = cualquiera. Admite IP, CIDR o rango de IP. Separa destinos con comas.", + "server.destination_port": "Puerto de destino", + "server.destination_port_hint": "Opcional. Puerto como 443 o rango 10000:20000. Selecciona antes TCP o UDP.", + "server.details": "Detalles", + "server.dev_word": "dev", + "server.diagnostics": "Diagnóstico", + "server.diagnostics_done": "Diagnóstico completado", + "server.diagnostics_subtitle": "Comprobaciones actuales del sistema. No se cambia la configuración.", + "server.direction": "Hook", + "server.edit_access_rule": "Editar regla de acceso", + "server.edit_route": "Editar ruta", + "server.edit_server": "Editar servidor", + "server.edit_subtitle": "Editar ajustes generales WireGuard, rutas y NAT. Se conservan los pares y reglas personalizadas.", + "server.edit_title": "Ajustes del servidor", + "server.edit_warning": "Aplicar cambios de interfaz, rutas o firewall reinicia brevemente WireGuard. Los pares activos se reconectarán automáticamente.", + "server.enable_forwarding": "Habilitar reenvío IPv4", + "server.enable_nat": "Habilitar NAT / Masquerade", + "server.firewall": "Cortafuegos y NAT", + "server.firewall_subtitle": "Reglas detectadas de hooks WireGuard.", + "server.firewall_subtitle_v08": "Reglas de reenvío/NAT y acceso de la interfaz. Las simples se gestionan aquí y las avanzadas en el editor sin procesar.", + "server.forward_from_vpn": "Permitir reenvío desde VPN", + "server.forward_to_vpn": "Permitir reenvío hacia VPN", + "server.forwarding_section": "Reenvío y NAT", + "server.gateway": "Puerta de enlace", + "server.gateway_hint": "Solo necesario si se usa una tabla de enrutamiento por políticas.", + "server.install_success": "WireGuard instalado correctamente.", + "server.install_wireguard": "Instalar WireGuard", + "server.install_wireguard_help": "Ejecuta apt update e instala WireGuard y herramientas de red necesarias.", + "server.install_wireguard_title": "Instalar WireGuard", + "server.installing": "Instalando WireGuard… Puede tardar un minuto.", + "server.interface": "Interfaz", + "server.interface_hint": "WGTools gestiona actualmente esta interfaz.", + "server.interface_name": "Interfaz", + "server.interface_section": "Interfaz WireGuard", + "server.ip_forwarding": "Reenvío IPv4", + "server.kind": "Tipo", + "server.listen_port": "Puerto de escucha", + "server.local_network": "Red local", + "server.local_network_hint": "Ruta opcional añadida a la tabla de políticas.", + "server.managed_automatically": "Gestionado automáticamente", + "server.nat": "NAT / Masquerade", + "server.network": "Red", + "server.network_settings": "Red y NAT", + "server.no_firewall": "No se encontraron reglas de firewall", + "server.no_routes": "No se encontraron rutas", + "server.not_configured": "Sin configurar", + "server.not_set": "Sin definir", + "server.policy_disabled_hint": "Desactiva para rutas normales del sistema. Habilita solo si esta VPN necesita su tabla de rutas por origen.", + "server.policy_enabled": "Habilitar enrutamiento por políticas", + "server.policy_table": "Tabla de políticas", + "server.policy_table_hint": "Déjalo vacío para rutas normales; usa p. ej. 200 para rutas por origen.", + "server.port_word": "puerto", + "server.private_hidden": "Configurado (oculto)", + "server.private_key": "Clave privada", + "server.protocol": "Protocolo", + "server.route_apply_confirm": "¿Guardar y aplicar esta ruta? WireGuard se reiniciará brevemente tras crear una copia.", + "server.route_custom": "Personalizada", + "server.route_deleted": "Ruta eliminada.", + "server.route_device_hint": "Interfaz de salida opcional, p. ej. wg0 o enp6s18.", + "server.route_editor_help": "Añade una ruta instalada cuando inicia WireGuard y eliminada cuando se detiene.", + "server.route_gateway_hint": "Puerta de enlace de siguiente salto opcional. Se requiere puerta o interfaz.", + "server.route_managed_peer": "Par Site-to-site", + "server.route_managed_server": "Ajuste del servidor", + "server.route_network_hint": "Red IPv4 como 10.20.0.0/24 o 'default'.", + "server.route_saved": "Ruta guardada y aplicada.", + "server.route_table_hint": "Usa 'main' para rutas normales o una tabla numérica como 200.", + "server.route_type": "Tipo", + "server.routes": "Rutas detectadas", + "server.routes_subtitle": "Rutas extraídas de PostUp/PostDown y del estado actual de rutas por políticas.", + "server.routes_subtitle_v08": "Rutas del servidor, Site-to-site y personalizadas de la interfaz elegida. Aquí puedes añadir, editar o eliminar rutas propias.", + "server.routing": "Enrutamiento", + "server.routing_section": "Enrutamiento", + "server.rule": "Regla", + "server.rule_access": "Regla de acceso", + "server.rule_advanced": "Avanzado", + "server.rule_apply_warning": "Aplicar una ruta o regla de firewall reinicia brevemente WireGuard. WGTools crea una copia y restaura automáticamente si falla el arranque.", + "server.rule_client_exception": "Excepción de cliente", + "server.rule_client_policy": "Política del cliente", + "server.rule_managed_server": "Ajuste del servidor", + "server.rule_type": "Tipo", + "server.run_diagnostics": "Ejecutar diagnóstico", + "server.save_apply": "Guardar y aplicar", + "server.save_config": "SaveConfig", + "server.server_address": "Dirección VPN del servidor", + "server.server_address_hint": "Normalmente la primera dirección utilizable de la red VPN.", + "server.settings_applied": "Ajustes del servidor guardados y aplicados correctamente.", + "server.settings_apply_failed": "No se pudieron aplicar los ajustes del servidor", + "server.setup_required": "Configuración necesaria", + "server.source": "Origen", + "server.source_hint": "Vacío = cualquiera. Admite IP, CIDR o rango como 10.0.0.100-10.0.0.120.", + "server.subtitle": "Instalación, configuración inicial y configuración actual del servidor WireGuard.", + "server.tab_config": "Configuración", + "server.tab_interface": "Interfaz", + "server.tab_routing": "Enrutamiento", + "server.tab_vps": "VPS", + "server.table": "Tabla", + "server.tabs_aria": "Secciones de ajustes del servidor", + "server.title": "Servidor", + "server.uplink": "Interfaz de enlace ascendente", + "server.use_raw_editor": "Usar editor sin procesar", + "server.via": "Vía / Dispositivo", + "server.via_word": "via", + "server.vpn_network": "Red VPN", + "server.vpn_network_hint": "Las direcciones de clientes se asignarán desde esta red.", + "server.vpn_pool": "Grupo de direcciones VPN", + "server.wg_not_installed": "WireGuard no está instalado", + "server.wg_not_installed_subtitle": "WGTools puede instalar automáticamente los paquetes Debian necesarios.", + "server.what_happens": "Qué hará WGTools", + "settings.about": "Acerca de", + "settings.add_user": "Añadir usuario", + "settings.advanced": "Avanzado", + "settings.advanced_subtitle": "Acceso directo a herramientas avanzadas de configuración WireGuard.", + "settings.appearance": "Apariencia", + "settings.applying_config": "Validando configuración, creando copia y aplicando…", + "settings.backup_count": "Copias guardadas", + "settings.backup_retention": "Copias a conservar", + "settings.backup_retention_help": "Las copias automáticas antiguas se eliminan tras crear una nueva. De 1 a 200 archivos.", + "settings.backups": "Copias de configuración", + "settings.backups_always_on": "Activado", + "settings.backups_subtitle": "WGTools crea automáticamente una copia antes de modificar la configuración. Las copias automáticas no se pueden desactivar.", + "settings.change_password": "Cambiar contraseña", + "settings.check_updates": "Buscar actualizaciones", + "settings.config_applied": "Configuración guardada y aplicada correctamente.", + "settings.config_applied_restarted": "Configuración aplicada y WireGuard reiniciado.", + "settings.config_applied_stopped": "Configuración guardada. WireGuard estaba detenido y sigue detenido.", + "settings.config_apply_failed": "No se pudo aplicar la configuración", + "settings.config_load_failed": "No se pudo cargar la configuración", + "settings.current_user": "Usuario actual", + "settings.current_version": "Versión actual", + "settings.audit_action": "Acción", + "settings.audit_empty": "Aún no hay eventos de auditoría", + "settings.audit_log": "Auditoría", + "settings.audit_log_subtitle": "Acciones del panel, acceso, Telegram e historial de conexiones WireGuard. Nunca se guardan secretos.", + "settings.audit_object": "Objeto", + "settings.audit_result": "Resultado", + "settings.audit_retention_note": "Retención: 30 días", + "settings.audit_search": "Búsqueda rápida", + "settings.audit_search_clear": "Borrar búsqueda", + "settings.audit_search_empty": "Ningún evento de auditoría coincide", + "settings.audit_time": "Fecha / hora", + "settings.audit_user": "Usuario", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Regla de acceso creada", + "audit.action.access_rule.deleted": "Regla de acceso eliminada", + "audit.action.access_rule.updated": "Regla de acceso actualizada", + "audit.action.auth.first_user_created": "Primer usuario creado", + "audit.action.auth.login": "Sesión iniciada", + "audit.action.auth.login_failed": "Error de inicio de sesión", + "audit.action.auth.logout": "Sesión cerrada", + "audit.action.backup.full_created": "Copia de seguridad completa creada", + "audit.action.backup.full_restored": "Copia de seguridad completa restaurada", + "audit.action.client.config_downloaded": "Configuración del cliente descargada", + "audit.action.client.config_viewed": "Configuración del cliente consultada", + "audit.action.client.created": "Cliente creado", + "audit.action.client.deleted": "Cliente eliminado", + "audit.action.client.qr_viewed": "Código QR del cliente consultado", + "audit.action.client.updated": "Cliente actualizado", + "audit.action.client_group.created": "Grupo de clientes creado", + "audit.action.client_group.deleted": "Grupo de clientes eliminado", + "audit.action.client_group.updated": "Grupo de clientes actualizado", + "audit.action.interface.created": "Interfaz creada", + "audit.action.interface.deleted": "Interfaz eliminada", + "audit.action.interface.renamed": "Interfaz renombrada", + "audit.action.route.created": "Ruta creada", + "audit.action.route.deleted": "Ruta eliminada", + "audit.action.route.updated": "Ruta actualizada", + "audit.action.server.created": "Servidor creado", + "audit.action.server.raw_config_applied": "Configuración sin procesar aplicada", + "audit.action.server.settings_applied": "Ajustes del servidor aplicados", + "audit.action.settings.updated": "Ajustes del panel actualizados", + "audit.action.telegram.action_denied": "Acción de Telegram denegada", + "audit.action.telegram.action_failed": "Error de acción de Telegram", + "audit.action.telegram.connection_test": "Prueba de conexión de Telegram", + "audit.action.telegram.settings_updated": "Ajustes de Telegram actualizados", + "audit.action.update.checked": "Actualización comprobada", + "audit.action.update.scheduled": "Actualización programada", + "audit.action.update.backup_created": "Copia previa a la actualización", + "audit.action.update.completed": "Actualización completada", + "audit.action.update.failed": "Error de actualización", + "audit.action.update.rollback_completed": "Versión anterior restaurada", + "audit.action.update.rollback_failed": "Error al revertir la actualización", + "audit.action.user.created": "Usuario creado", + "audit.action.user.deleted": "Usuario eliminado", + "audit.action.user.password_changed": "Contraseña de usuario cambiada", + "audit.action.vps.candidate_deleted": "Candidato VPS eliminado", + "audit.action.vps.candidate_saved": "Candidato VPS guardado", + "audit.action.vps.detached": "Relay VPS desconectado", + "audit.action.vps.relay_installed": "Relay VPS instalado", + "audit.action.wireguard.client_connected": "Cliente WireGuard conectado", + "audit.action.wireguard.installed": "WireGuard instalado", + "audit.action.wireguard.restarted": "WireGuard reiniciado", + "audit.action.wireguard.started": "WireGuard iniciado", + "audit.action.wireguard.stopped": "WireGuard detenido", + "audit.result.applied": "aplicado", + "audit.result.available": "disponible", + "audit.result.changed": "cambiado", + "audit.result.created": "creado", + "audit.result.current": "actual", + "audit.result.deleted": "eliminado", + "audit.result.detached": "desconectado", + "audit.result.denied": "denegado", + "audit.result.downloaded": "descargado", + "audit.result.endpoint": "Punto final", + "audit.result.error": "Error", + "audit.result.installed": "instalado", + "audit.result.invalid_credentials": "credenciales no válidas", + "audit.result.ok": "Correcto", + "audit.result.queued": "en cola", + "audit.result.restarted": "reiniciado", + "audit.result.restored": "restaurado", + "audit.result.rotated": "renovado", + "audit.result.saved": "guardado", + "audit.result.shown": "mostrado", + "audit.result.started": "iniciado", + "audit.result.stopped": "detenido", + "audit.result.updated": "actualizado", + "settings.delete_user": "Eliminar", + "settings.delete_user_confirm": "¿Eliminar al usuario {name}?", + "settings.edit_raw_config": "Editar configuración de interfaz", + "settings.expert_mode": "Experto", + "settings.full_backup_component_clients": "Metadatos de clientes gestionados, claves privadas, PSK, caducidad y grupos para regenerar configuraciones y QR.", + "settings.full_backup_component_db": "Base de datos WGTools: usuarios, preferencias, correo/SMTP, Telegram y estado guardado de VPS Relay.", + "settings.full_backup_component_relay": "Datos de recuperación VPS Relay: ID de controlador/tenant, token de administración y clave de transporte doméstico. Tras restaurar, WGTools puede reconstruir el transporte y reconectar el tenant conservado.", + "settings.full_backup_component_system": "Archivo sysctl IPv4 de WGTools, nombres visibles de interfaces y políticas/plantillas de grupos, si existen. Se excluye deliberadamente el historial automático por interfaz.", + "settings.full_backup_component_wg": "Todas las configuraciones WireGuard detectadas en /etc/wireguard/, incluido su estado activo/detenido.", + "settings.full_backup_create_failed": "No se pudo crear la copia completa", + "settings.full_backup_creating": "Creando copia completa…", + "settings.full_backup_download": "Crear", + "settings.full_backup_downloaded": "Copia creada y descargada. Guárdala de forma segura.", + "settings.full_backup_downloaded_short": "Copia completa descargada.", + "settings.full_backup_help": "Crea una copia portátil de WGTools para migración o recuperación: configuraciones WireGuard, usuarios, ajustes, grupos, clientes gestionados y datos para reconectar tenants VPS Relay.", + "settings.full_backup_no_file": "No se seleccionó ninguna copia", + "settings.full_backup_restore": "Restaurar", + "settings.full_backup_restore_confirm": "¿Restaurar esta copia completa de WGTools? Se restaurarán usuarios, ajustes, clientes gestionados y configuraciones WireGuard incluidos. Las interfaces pueden reiniciarse. WGTools crea una copia de seguridad previa y revierte automáticamente si falla.", + "settings.full_backup_restore_failed": "Error de restauración", + "settings.full_backup_restored": "Copia restaurada correctamente. Inicia sesión con una cuenta de esa copia.", + "settings.full_backup_restored_short": "Copia restaurada.", + "settings.full_backup_restoring": "Validando copia, creando respaldo de seguridad y restaurando…", + "settings.full_backup_secret_warning": "Este archivo contiene datos sensibles: claves privadas WireGuard y clientes, PSK, hashes de contraseñas WGTools, token de Telegram y contraseña SMTP guardada. Protégelo como una contraseña y nunca lo adjuntes a incidencias o chats públicos.", + "settings.full_backup_select": "Seleccionar", + "settings.full_backup_title": "Copia completa y restauración", + "settings.full_mode": "Gestión del servidor y clientes habilitada", + "settings.interface_help": "La interfaz WireGuard gestionada se elige al desplegar WGTools.", + "settings.language": "Idioma", + "settings.last_backup": "Última copia", + "settings.latest_version": "Última versión", + "settings.loading_config": "Cargando configuración…", + "settings.mode": "Modo", + "settings.never_logged_in": "Nunca", + "settings.new_password": "Nueva contraseña", + "settings.no_backups": "Aún no hay copias", + "settings.online_help": "Un par está en línea si el último handshake es más reciente que este valor. 30–3600 segundos.", + "settings.online_threshold": "Umbral de conexión", + "settings.open_release": "Abrir versión", + "settings.password_changed": "Contraseña cambiada.", + "settings.passwords_mismatch": "Las contraseñas no coinciden.", + "settings.project_github": "Proyecto / GitHub", + "settings.raw_config_confirm": "¿Guardar y aplicar la configuración WireGuard? Se reiniciará la interfaz seleccionada. Antes se creará una copia y WGTools revertirá automáticamente si el arranque falla.", + "settings.raw_config_help": "Abrir la configuración de origen de la interfaz WireGuard elegida.", + "settings.raw_config_title": "Configuración WireGuard sin procesar", + "settings.raw_config_warning": "Modo experto: esta es la configuración real del servidor WireGuard con clave privada y PSK de pares. Guardar y aplicar reinicia la interfaz. WGTools crea antes una copia y revierte si el arranque falla.", + "settings.readonly_mode": "Gestión de clientes habilitada", + "settings.refresh_help": "Frecuencia de actualización de datos de estado. De 2 a 60 segundos.", + "settings.refresh_interval": "Intervalo de actualización", + "settings.release_notes": "Notas de versión", + "settings.reload_config": "Recargar del disco", + "settings.save_apply": "Guardar y aplicar", + "settings.saved": "Ajustes guardados.", + "settings.saved_reload": "Ajustes guardados. Recargando…", + "settings.saving": "Guardando ajustes…", + "settings.status": "Actualización de estado", + "settings.status_help": "Frecuencia de actualización del panel y estado de los pares.", + "settings.subtitle": "Preferencias de interfaz y ajustes de estado de WGTools.", + "settings.syntax_hint": "Se resaltan secciones, claves, valores y comentarios WireGuard al editar.", + "settings.tab_about": "Acerca de", + "settings.tab_backups": "Copias", + "settings.tab_general": "General", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Usuarios", + "settings.tabs_aria": "Secciones de ajustes", + "settings.telegram": "Bot de Telegram", + "settings.telegram_allowed_ids": "ID de usuario de Telegram permitidos", + "settings.telegram_allowed_ids_help": "Un ID numérico por línea. Un /start no autorizado responde con el ID Telegram del remitente para añadirlo aquí.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Conectado", + "settings.telegram_disabled": "Desactivado", + "settings.telegram_dns": "DNS predeterminado del cliente", + "settings.telegram_dns_help": "Direcciones DNS IPv4 opcionales separadas por comas. Se usan en clientes creados por el bot.", + "settings.telegram_enabled": "Activar bot Telegram", + "settings.telegram_endpoint": "Dirección / dominio predeterminado del servidor", + "settings.telegram_endpoint_help": "Se usa cuando el bot crea un cliente. Introduce solo IP o dominio; el puerto WireGuard viene de la configuración del servidor.", + "settings.telegram_language": "Idioma del bot", + "settings.telegram_language_auto": "Auto (idioma de Telegram)", + "settings.telegram_last_poll": "Último contacto con Telegram", + "settings.telegram_not_configured": "Sin configurar", + "settings.telegram_remove_token": "Eliminar token", + "settings.telegram_remove_token_confirm": "¿Eliminar el token guardado de Telegram y deshabilitar el bot?", + "settings.telegram_save": "Guardar ajustes de Telegram", + "settings.telegram_saved": "Ajustes de Telegram guardados.", + "settings.telegram_setup_note": "Crea un bot con @BotFather, guarda su token, habilítalo y envía /start. Si tu ID no está autorizado, WGTools lo mostrará: añádelo a la lista permitida.", + "settings.telegram_status": "Estado del bot", + "settings.telegram_subtitle": "Gestión WireGuard desde Telegram: estado del servidor, clientes, creación/eliminación e inicio/reinicio/parada.", + "settings.telegram_test": "Probar conexión", + "settings.telegram_test_ok": "Conexión Telegram correcta: @{username}", + "settings.telegram_test_recent_ok": "El bot Telegram funciona. La prueba directa expiró, pero el bot contactó con Telegram recientemente.", + "settings.telegram_token": "Token del bot", + "settings.telegram_token_help": "Crea un bot con @BotFather y pega aquí el token Bot API. No se necesitan API ID ni API Hash.", + "settings.telegram_token_keep": "Deja en blanco para conservar el token guardado.", + "settings.telegram_waiting": "Configurado, esperando servicio del bot", + "settings.theme": "Tema", + "settings.theme_dark": "Oscuro", + "settings.theme_light": "Claro", + "settings.theme_system": "Sistema", + "settings.title": "Configuración", + "settings.update_available": "Actualización disponible", + "settings.update_backup_queued": "Actualización en cola. WGTools creará una copia completa automática antes de instalar…", + "settings.update_backup_running": "Creando copia completa antes de actualizar…", + "settings.update_check_failed": "No se pudieron comprobar las actualizaciones", + "settings.update_checking": "Comprobando el último lanzamiento publicado en GitHub…", + "settings.update_confirm": "¿Actualizar WGTools de v{current} a v{latest}? Se crearán una copia completa y otra para revertir. La interfaz web se reiniciará brevemente.", + "settings.update_current": "Actualizado", + "settings.update_downloading": "Descargando y validando la versión de GitHub…", + "settings.update_failed": "La actualización de WGTools falló.", + "settings.update_installing": "Instalando actualización. La interfaz web puede no estar disponible por un momento…", + "settings.update_no_update": "WGTools ya está actualizado.", + "settings.update_not_checked": "Sin comprobar", + "settings.update_queued": "Actualización en cola. Esperando al servicio actualizador…", + "settings.update_rollback_ok": "Se restauró automáticamente la versión anterior de WGTools.", + "settings.update_rolling_back": "Falló la actualización. Restaurando la versión anterior…", + "settings.update_running": "Creando copias de seguridad…", + "settings.update_safety_hint": "Las actualizaciones son opcionales. WGTools crea una copia completa y una para revertir. Si falla, restaura automáticamente la aplicación anterior. WireGuard no se reinicia salvo que la nueva versión modifique expresamente su configuración.", + "settings.update_sidebar": "Nueva versión disponible", + "settings.update_sidebar_hint": "Ajustes → Acerca de", + "settings.update_starting": "Iniciando actualización…", + "settings.update_status_unknown": "Estado de actualización no disponible. Reintentando…", + "settings.update_subtitle": "Información del proyecto, comprobación automática de versiones y actualizaciones seguras desde GitHub Releases.", + "settings.update_success": "WGTools actualizado a v{version}. Recargando…", + "settings.update_wgtools": "Actualizar WGTools", + "settings.user_actions": "Acciones", + "settings.user_created": "Creado", + "settings.user_created_ok": "Usuario creado.", + "settings.user_deleted": "Usuario eliminado.", + "settings.user_equal_rights": "Todos los usuarios WGTools tienen los mismos permisos.", + "settings.user_last_login": "Último inicio de sesión", + "settings.user_name": "Nombre de usuario", + "settings.users": "Usuarios", + "settings.users_subtitle": "Cuentas locales WGTools. El correo es opcional y solo se usa para recuperar la contraseña cuando está habilitado.", + "vps.add": "Añadir VPS", + "vps.add_help": "WGTools usa SSH para comprobar o instalar Relay. Nunca guarda contraseñas ni claves SSH privadas.", + "vps.add_title": "Añadir VPS", + "vps.agent": "Agente Relay", + "vps.agent_found": "Ya instalado", + "vps.agent_will_install": "Se instalará", + "vps.arch": "Arquitectura", + "vps.auth_method": "Autenticación", + "vps.authentication": "Autenticación SSH", + "vps.check": "Comprobar VPS", + "vps.check_failed": "Error al comprobar el VPS", + "vps.check_link": "Comprobar enlace", + "vps.check_ok": "VPS compatible", + "vps.checking": "Comprobando acceso SSH y compatibilidad VPS…", + "vps.connections": "conexiones", + "vps.credentials_not_saved": "Solo se usan para esta comprobación; WGTools no los guarda.", + "vps.delete_candidate": "Quitar", + "vps.delete_installed": "Eliminar VPS", + "vps.delete_installed_confirm": "¿Quitar «{name}» de WGTools? Se desconectará el transporte Relay local, pero se conservarán el agente y el tenant del VPS. Puedes añadirlo otra vez y WGTools reutilizará el Relay existente. Los clientes no podrán usarlo hasta reconectarlo.", + "vps.delete_installed_failed": "No se pudo eliminar el VPS de WGTools", + "vps.delete_installed_ok": "VPS eliminado de WGTools. El Relay remoto se conserva y puede reconectarse.", + "vps.empty_help": "Añade un VPS Debian o Ubuntu para comprobar SSH, compatibilidad del sistema y puertos UDP necesarios.", + "vps.empty_title": "Ningún VPS configurado", + "vps.endpoint": "Endpoint público", + "vps.endpoint_domain": "Dominio (recomendado)", + "vps.endpoint_domain_hint": "Si reemplazas el VPS principal, cambiar DNS puede mantener intactas las configuraciones del cliente.", + "vps.health_failed": "Error al comprobar el enlace Relay", + "vps.host": "IP / nombre de host", + "vps.host_key": "Clave de host SSH", + "vps.identity": "Conexión VPS", + "vps.install_failed": "Error al instalar Relay", + "vps.install_ok": "Relay instalado y enlace de administración protegido verificado", + "vps.install_relay": "Instalar Relay", + "vps.install_title": "Instalar Relay VPS", + "vps.installed": "Instalado", + "vps.installing": "Instalando agente Relay y estableciendo túnel protegido…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Frase de acceso de la clave", + "vps.link_ok": "Enlace Relay correcto", + "vps.multi_tenant_note": "Ya funciona un agente Relay WGTools en este VPS. No se reemplazará: este WGTools tendrá una conexión aislada con claves y puertos UDP propios.", + "vps.name": "Nombre", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Se instalará", + "vps.os": "Sistema operativo", + "vps.password": "Contraseña", + "vps.phase_note": "El agente Relay admite varios controladores WGTools independientes en un VPS. Cada uno tiene conexión, claves y puertos UDP aislados; los existentes no se modifican.", + "vps.port_pair": "Puertos UDP", + "vps.ports_adjusted": "puertos libres seleccionados", + "vps.private_key": "Clave privada", + "vps.privilege": "Privilegios", + "vps.public_endpoint": "Futuro endpoint público", + "vps.ready_help": "Las credenciales SSH solo se usan para comprobar compatibilidad e instalar Relay inmediatamente; no se guardan.", + "vps.reconnect_note": "Se encontró una conexión Relay creada antes por este WGTools. Se reutilizará el mismo tenant sin crear nuevos ni puertos UDP.", + "vps.reconnect_ok": "Relay existente reconectado correctamente", + "vps.reconnect_relay": "Reconectar Relay", + "vps.relay_port": "Puerto UDP Relay", + "vps.remove_confirm": "¿Quitar este candidato VPS? No se han hecho cambios remotos.", + "vps.save_candidate": "Guardar candidato", + "vps.saved": "Candidato VPS guardado", + "vps.ssh": "SSH", + "vps.ssh_key": "Clave SSH", + "vps.ssh_port": "Puerto SSH", + "vps.ssh_user": "Usuario SSH", + "vps.status_candidate": "Listo para instalar", + "vps.status_installed": "Relay conectado", + "vps.subtitle": "Prepara un VPS público para acceso remoto cuando este servidor WGTools no tiene IP pública.", + "vps.tenant": "Conexión", + "vps.title": "Relay VPS", + "vps.transport_port": "Puerto UDP de transporte", + "vps.transport_port_hint": "Puerto UDP separado para el túnel de transporte privado Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Guardado", + "vps.active_short": "Activo", + "dashboard.traffic_reset": "Restablecer", + "dashboard.traffic_reset_confirm": "¿Restablecer los contadores de tráfico WireGuard de esta interfaz? Los contadores de clientes también volverán a cero.", + "dashboard.traffic_reset_done": "Contadores de tráfico restablecidos", + "dashboard.traffic_reset_failed": "No se pudieron restablecer los contadores", + "audit.action.traffic.reset": "Contadores de tráfico restablecidos", + "audit.result.reset": "restablecido", + "server.mtu": "MTU", + "server.mtu_auto": "Automático", + "server.mtu_hint": "Opcional. Déjalo vacío para MTU automática de wg-quick. Usa 1380 o 1420 solo si es necesario por LTE o PPPoE.", + "clients.peer_isolation": "Aislamiento de clientes VPN", + "clients.peer_isolation_enable": "Aislar de otros clientes VPN", + "clients.peer_isolation_hint": "Bloquea el tráfico entre este cliente y otras direcciones del grupo WireGuard. El acceso al servidor, Internet y redes locales o Site-to-site sigue controlado por otras políticas.", + "clients.credentials_rotate": "Claves del cliente", + "clients.credentials_rotate_button": "Renovar claves", + "clients.credentials_rotate_confirm": "¿Generar claves nuevas para este cliente? Si está conectado, su sesión WireGuard se desconectará inmediatamente. Envía después nueva configuración o QR.", + "clients.credentials_rotate_confirm_psk": "¿Generar un nuevo par de claves y un PSK para este cliente? Su sesión WireGuard activa se cortará inmediatamente. Envía después nueva configuración o QR.", + "clients.credentials_rotate_hint": "Renueva PrivateKey/PublicKey y el PSK si está habilitado. Conserva dirección, rutas, grupo, horario, aislamiento y estadísticas.", + "clients.credentials_rotating": "Generando claves nuevas y cerrando la sesión anterior…", + "clients.credentials_rotated": "Claves del cliente cambiadas. Si estaba conectado, su sesión anterior se cortó. La configuración antigua ya no funciona; envía una nueva o QR.", + "clients.credentials_rotated_short": "Claves cambiadas — se requiere nueva configuración", + "audit.action.client.credentials_rotated": "Claves del cliente renovadas", + "clients.credentials_connection_lost": "Se perdió la conexión a WGTools. Si el panel se abrió a través del cliente cuyas claves se renovaron, es normal: su sesión antigua se cerró. Vuelve a entrar por otra vía y genera nueva configuración o QR.", + "nav.navigation": "Navegación principal", + "nav.project_github": "WGTools en GitHub", + "auth.email": "Correo electrónico", + "auth.email_optional_help": "Opcional por ahora. Permite recuperar la contraseña después de configurar el correo.", + "auth.forgot_password": "¿Olvidaste la contraseña?", + "auth.reset_title": "Restablecer contraseña", + "auth.reset_subtitle": "Recibe un código de un solo uso por correo y establece una nueva contraseña de WGTools.", + "auth.reset_identifier": "Usuario o correo", + "auth.reset_identifier_help": "Por privacidad, WGTools siempre muestra la misma respuesta tanto si la cuenta existe como si no.", + "auth.send_reset_code": "Enviar código", + "auth.reset_code_sent_generic": "Si la cuenta existe y tiene correo, se envió un código. Es válido durante 15 minutos.", + "auth.reset_code": "Código de 6 dígitos", + "auth.set_new_password": "Establecer nueva contraseña", + "auth.request_another_code": "Solicitar otro código", + "auth.back_to_login": "Volver al inicio de sesión", + "auth.reset_not_configured": "La recuperación de contraseña por correo no está configurada. Contacta con el administrador de WGTools.", + "settings.tab_mail": "Correo", + "settings.mail": "Correo / SMTP", + "settings.mail_subtitle": "SMTP se usa para recuperar contraseñas.", + "settings.mail_not_configured": "Sin configurar", + "settings.mail_enabled": "Habilitar correo y recuperación de contraseña", + "settings.mail_smtp_host": "Servidor SMTP", + "settings.mail_smtp_port": "Puerto SMTP", + "settings.mail_security": "Cifrado", + "settings.mail_security_none": "Sin cifrado", + "settings.mail_username": "Usuario SMTP", + "settings.mail_username_help": "Se usa para autenticación SMTP y como correo remitente.", + "settings.mail_password": "Contraseña SMTP", + "settings.mail_password_keep": "Deja vacío para conservar la contraseña guardada.", + "settings.mail_from_email": "Correo del remitente", + "settings.mail_from_name": "Nombre del remitente", + "settings.mail_test_recipient": "Destinatario de prueba", + "settings.mail_test_recipient_help": "La prueba utiliza los ajustes SMTP guardados actualmente.", + "settings.mail_remove_password": "Eliminar contraseña", + "settings.mail_test": "Enviar prueba", + "settings.mail_save": "Guardar ajustes de correo", + "settings.mail_enabled_badge": "Activado", + "settings.mail_disabled_badge": "Desactivado", + "settings.mail_saved": "Ajustes de correo guardados.", + "settings.mail_remove_password_confirm": "¿Eliminar la contraseña SMTP guardada y deshabilitar el correo?", + "settings.mail_password_removed": "Contraseña SMTP eliminada y correo deshabilitado.", + "settings.mail_test_recipient_required": "Introduce la dirección de correo del destinatario de prueba.", + "settings.mail_testing": "Enviando correo de prueba…", + "settings.mail_test_ok": "Correo de prueba enviado correctamente.", + "settings.user_email": "Correo electrónico", + "settings.user_email_help": "Opcional. Solo necesario para recuperar la contraseña por cuenta propia.", + "settings.change_email": "Correo electrónico", + "settings.user_email_saved": "Correo guardado.", + "settings.send_password_reset": "Enviar restablecimiento", + "settings.user_reset_mail_not_configured": "Configura y habilita primero el correo.", + "settings.user_reset_email_missing": "Añade primero una dirección de correo.", + "settings.user_reset_confirm": "¿Enviar código de restablecimiento a {name} en {email}?", + "settings.user_reset_sent": "Código de restablecimiento enviado a {email}.", + "audit.action.auth.password_reset_requested": "Restablecimiento de contraseña solicitado", + "audit.action.auth.password_reset_code_sent": "Código de restablecimiento enviado", + "audit.action.auth.password_reset_completed": "Contraseña restablecida", + "audit.action.auth.password_reset_failed": "Error al restablecer la contraseña", + "audit.action.mail.settings_updated": "Configuración de correo actualizada", + "audit.action.mail.test_sent": "Correo de prueba enviado", + "audit.action.mail.test_failed": "Error en el correo de prueba", + "audit.action.user.email_changed": "Correo del usuario cambiado", + "audit.action.user.password_reset_sent": "Restablecimiento enviado al usuario", + "audit.action.user.password_reset_failed": "Error al restablecer la contraseña del usuario", + "audit.result.accepted": "aceptado", + "audit.result.sent": "enviado", + "audit.result.invalid_code": "código no válido", + "common.copy": "Copiar", + "common.copied": "Copiado", + "clients.use_panel_host": "Usar dirección del panel", + "clients.use_panel_host_done": "Dirección del panel insertada: {host}", + "clients.use_panel_host_failed": "No se pudo obtener la dirección del panel de la URL del navegador.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS de Let’s Encrypt integrado para acceso directo a WGTools sin proxy inverso.", + "settings.https_disabled": "Desactivado", + "settings.https_enabled": "Activado", + "settings.https_enable": "Habilitar HTTPS integrado", + "settings.https_type": "Certificado para", + "settings.https_domain": "Dominio", + "settings.https_public_ip": "IP pública", + "settings.https_target": "Dominio o IP pública", + "settings.https_email": "Correo de Let’s Encrypt", + "settings.https_port": "Puerto HTTPS", + "settings.https_port80_note": "El puerto TCP 80 debe ser accesible desde Internet para emitir y renovar el certificado. Abre también el puerto HTTPS elegido para el panel.", + "settings.https_check_ports": "Comprobar puertos", + "settings.https_certificate": "Certificado", + "settings.https_certificate_ready": "Listo", + "settings.https_certificate_missing": "No emitido", + "settings.https_expires": "Válido hasta", + "settings.https_renewal": "Renovación automática", + "settings.https_renewal_enabled": "Activado", + "settings.https_renewal_disabled": "Desactivado", + "settings.https_certificate_path": "Certificado", + "settings.https_private_key_path": "Clave privada", + "settings.https_issue": "Obtener / renovar certificado", + "settings.https_port_free": "Libre", + "settings.https_port_busy": "Ocupado", + "settings.https_ports_checked": "Comprobación de puertos terminada.", + "settings.https_target_email_required": "Introduce dominio/IP pública y correo de Let’s Encrypt.", + "settings.https_issue_confirm": "¿Solicitar o renovar el certificado Let’s Encrypt para {target}? Se guardarán los ajustes HTTPS. El puerto TCP 80 debe ser accesible desde Internet.", + "settings.https_issuing": "Solicitando certificado a Let’s Encrypt…", + "settings.https_issue_ok": "Certificado listo.", + "settings.https_already_enabled": "HTTPS integrado ya está habilitado.", + "settings.https_already_disabled": "HTTPS integrado ya está deshabilitado.", + "settings.https_enable_confirm": "¿Habilitar HTTPS integrado en TCP {port} con ruta {path}? WGTools se reiniciará y la página volverá a conectarse a la nueva dirección.", + "settings.https_disable_confirm": "¿Deshabilitar HTTPS integrado y volver a HTTP?", + "settings.https_switching": "Habilitando HTTPS y reiniciando WGTools…", + "settings.https_switching_http": "Deshabilitando HTTPS y reiniciando WGTools…", + "audit.action.https.certificate_issued": "Certificado HTTPS emitido", + "audit.action.https.certificate_failed": "Error al solicitar el certificado HTTPS", + "audit.action.https.enabled": "HTTPS habilitado", + "audit.action.https.disabled": "HTTPS deshabilitado", + "audit.result.issued": "emitido", + "audit.result.enabled": "habilitado", + "audit.result.disabled": "deshabilitado", + "settings.https_access_path": "Ruta de acceso al panel", + "settings.https_access_path_help": "Elige tu propia ruta. Con HTTPS integrado, las solicitudes fuera de ella reciben 404.", + "settings.https_enable_fields_required": "Introduce dominio/IP pública, correo Let’s Encrypt y ruta del panel.", + "settings.https_use_panel_host": "Usar dirección del panel", + "settings.https_reconnecting": "WGTools cambiando a la nueva dirección HTTPS…", + "server.tab_nodes": "Nodos", + "common.type": "Tipo", + "common.status": "Estado", + "common.copy_failed": "No se pudo copiar", + "clients.vpn_address": "Dirección VPN", + "nodes.title": "Nodos WGTools", + "nodes.subtitle": "Conecta varios servidores WGTools en una red protegida y publica solo las redes accesibles a otros nodos.", + "nodes.enable_hub": "Habilitar HUB", + "nodes.connect_hub": "Conectar al HUB", + "nodes.settings": "Ajustes del nodo", + "nodes.settings_action": "Configuración", + "nodes.sync_now": "Sincronizar", + "nodes.disable": "Deshabilitar nodos", + "nodes.disable_action": "Desconectar", + "nodes.join_title": "Conectar nuevos nodos", + "nodes.join_help": "Crea un código de un solo uso e introdúcelo en otro panel WGTools junto con el endpoint del HUB, p. ej. vpn.example.com:51950. Dura 15 minutos y solo se usa una vez.", + "nodes.create_code": "Crear código", + "nodes.connected_nodes": "Nodos conectados", + "nodes.connected_nodes_help": "Información de otros paneles, redes publicadas y clientes. Los clientes remotos son de solo lectura.", + "nodes.enable_hub_help": "Este panel será el nodo central. El mismo puerto acepta WireGuard por UDP y el emparejamiento inicial protegido por TCP.", + "nodes.node_name": "Nombre del nodo", + "nodes.transport_network": "Red de transporte de nodos", + "nodes.transport_help": "Red privada separada solo para el transporte entre WGTools. No debe solaparse con las redes VPN/LAN.", + "nodes.panel_url": "URL del panel", + "nodes.panel_url_help": "Opcional. Solo es un enlace informativo del botón «Abrir panel» en otros nodos; no se usa para conectar nodos.", + "nodes.extra_networks": "Redes de nodo adicionales", + "nodes.extra_networks_help": "Una red por línea. Las redes VPN y las redes remotas Site-to-site se publican automáticamente. Añade solo otras LAN/redes enrutadas, p. ej. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools rellena redes VPN, Site-to-site y LAN enrutadas detectadas. Deja solo las redes que este nodo debe publicar. Una por línea.", + "nodes.published_networks_settings_help": "Una red por línea. Lista explícita de redes publicadas por este nodo. Quitar una línea deja de anunciar esa red a otros nodos.", + "nodes.available_networks_help": "Redes detectadas: {networks}. Las redes nuevas no se publican automáticamente; añade arriba las que quieras.", + "nodes.available_networks_none": "No se detectaron redes locales adicionales.", + "nodes.connect_help": "Introduce endpoint del HUB y código de un uso. La URL, el puerto HTTPS, certificado y ruta privada del panel no se usan para emparejar.", + "nodes.join_code": "Código de conexión", + "nodes.connect_reachability_note": "El emparejamiento inicial usa TCP protegido en el puerto indicado. Tras crear wgnode0, las redes, estados, versiones y datos de clientes de solo lectura se sincronizan con HUB por WireGuard interno.", + "nodes.connect": "Conectar", + "nodes.settings_help": "Nombre del nodo, enlace opcional «Abrir panel» y lista de redes publicadas. La URL del panel no se usa para emparejamiento ni sincronización.", + "nodes.details": "Detalles", + "nodes.not_configured": "WGTools Nodes sin configurar", + "nodes.not_configured_help": "Habilita HUB en este panel o conéctalo a un HUB WGTools existente.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Conectado al HUB", + "nodes.mode_none": "Sin configurar", + "nodes.role": "Rol", + "nodes.tunnel": "Túnel del nodo", + "nodes.node_ip": "Dirección del nodo", + "nodes.endpoint": "Endpoint de HUB", + "nodes.published_networks": "Redes publicadas", + "nodes.last_sync": "Última sincronización", + "nodes.no_nodes_hub": "Aún no hay nodos conectados. Crea un código y úsalo en otro panel WGTools.", + "nodes.no_nodes_spoke": "Aún no se recibió información de nodos remotos.", + "nodes.clients_short": "Clientes", + "nodes.open_panel": "Abrir panel", + "nodes.route_conflict": "Conflicto de rutas", + "nodes.no_published_networks": "Sin redes publicadas", + "nodes.load_failed": "No se pudo cargar WGTools Nodes", + "nodes.enable_hub_confirm": "¿Habilitar HUB de WGTools y crear el túnel WireGuard interno?", + "nodes.applying": "Configurando túnel WGTools Nodes…", + "nodes.enable_failed": "No se pudo habilitar HUB", + "nodes.hub_enabled": "HUB de WGTools habilitado", + "nodes.connecting": "Verificando código HUB y creando túnel protegido…", + "nodes.connect_failed": "No se pudo conectar al HUB", + "nodes.connected": "Conectado al HUB WGTools", + "nodes.settings_failed": "No se pudieron guardar los ajustes del nodo", + "nodes.settings_saved": "Ajustes del nodo guardados", + "nodes.code_failed": "No se pudo crear código de conexión", + "nodes.code_expires": "Código de un solo uso. Válido hasta {time}.", + "nodes.code_copied": "Código de conexión copiado", + "nodes.network_vpn": "Clientes VPN", + "nodes.network_site_to_site": "Red Site-to-site", + "nodes.network_custom": "Red adicional", + "nodes.conflict": "Conflicto", + "nodes.remote_clients": "Clientes (solo lectura)", + "nodes.no_clients": "Este nodo no informa de clientes", + "nodes.details_failed": "No se pudieron cargar los detalles del nodo", + "nodes.remove_confirm": "¿Quitar el nodo «{name}» del HUB? Se revocará su acceso al túnel interno.", + "nodes.remove_failed": "No se pudo quitar el nodo", + "nodes.removed": "Nodo eliminado", + "nodes.disable_hub_confirm": "¿Deshabilitar HUB y desconectar todos los nodos WGTools? Se eliminará el túnel interno.", + "nodes.disconnect_confirm": "¿Desconectar este panel WGTools del HUB y eliminar su túnel interno?", + "nodes.disable_failed": "No se pudieron deshabilitar los nodos WGTools", + "nodes.disabled": "Nodos WGTools deshabilitados", + "nodes.sync_failed": "Error de sincronización de nodos", + "nodes.synced": "Información de nodos sincronizada", + "nodes.service_port": "Puerto Nodes", + "nodes.service_port_help": "Se usa el mismo número de puerto: UDP para WireGuard y TCP para emparejamiento inicial protegido.", + "nodes.hub_port_forward_note": "Si HUB está tras NAT, redirige el mismo puerto para UDP y TCP. El puerto web WGTools, HTTPS y la ruta privada no están relacionados con Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Dominio/IP y puerto de Nodes sin http:// ni https://, p. ej. vpn.example.com:51950.", + "settings.collapse_sidebar": "Contraer barra lateral", + "settings.expand_sidebar": "Expandir barra lateral", + "settings.https_issue_fields_required": "Introduce dominio/IP pública, correo Let’s Encrypt y ruta del panel.", + "settings.https_issue_ok_saved": "Certificado listo y ajustes HTTPS guardados.", + "settings.https_enable_need_certificate": "Primero obtén un certificado.", + "settings.https_enable_certificate_mismatch": "Primero obtén un certificado para el dominio o IP actual.", + "settings.https_enable_certificate_expired": "El certificado caducó. Renuévalo antes de habilitar HTTPS.", + "settings.https_enable_certificate_ready": "Certificado listo: ya puedes habilitar HTTPS integrado.", + "settings.https_enable_active_help": "Desmarca y guarda para volver a HTTP.", + "settings.https_certificate_expired": "Caducado", + "settings.https_certificate_wrong_target": "Para otra dirección", + "nodes.network_conflict_error": "Las redes publicadas entran en conflicto con otro nodo o red de transporte Nodes: {conflicts}. Elimina o cambia la red conflictiva.", + "nodes.networks_changed": "Las redes detectadas cambiaron desde el último guardado. Nuevas: {added}. Ya no detectadas: {removed}. Revisa y guarda las redes publicadas.", + "nodes.review_networks": "Revisar redes", + "nodes.vpn_pool_mismatch": "El grupo VPN cambió: Nodes sigue publicando {old}, pero el grupo actual es {current}. Abre los ajustes y actualiza las redes publicadas.", + "server.error_vpn_network_invalid": "La red VPN debe ser una red IPv4 válida, p. ej. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Solo se admiten redes VPN IPv4.", + "server.error_vpn_network_too_small": "La red VPN debe tener al menos dos direcciones utilizables.", + "server.error_vpn_network_no_hosts": "La red VPN elegida no tiene direcciones de servidor utilizables.", + "server.error_server_address_prefix": "La dirección VPN del servidor debe incluir prefijo, p. ej. 10.0.0.1/24.", + "server.error_server_address_network": "La dirección VPN del servidor debe pertenecer al grupo elegido y usar el mismo prefijo.", + "server.error_server_address_reserved": "La dirección VPN del servidor no puede ser la de red ni la de difusión.", + "server.error_listen_port_number": "El puerto WireGuard debe ser un número.", + "server.error_listen_port_range": "El puerto WireGuard debe estar entre 1 y 65535.", + "server.error_mtu_number": "MTU debe ser un número.", + "auth.mfa_title": "Autenticación de dos factores", + "auth.mfa_login_help": "Introduce el código de 6 dígitos de Google Authenticator o un código de recuperación.", + "auth.mfa_code": "Código de autenticación", + "auth.mfa_verify": "Verificar e iniciar sesión", + "auth.mfa_back": "Volver a la contraseña", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Autenticación de dos factores (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Activado", + "settings.mfa_disabled": "Desactivado", + "settings.mfa_google_help": "Protege esta cuenta con Google Authenticator u otra app TOTP. Para comenzar se requiere tu contraseña actual.", + "settings.current_password": "Contraseña actual", + "settings.mfa_start": "Configurar Google Authenticator", + "settings.mfa_secret": "Clave de configuración manual", + "settings.mfa_scan_help": "Escanea el QR con Google Authenticator y escribe el código actual de 6 dígitos para habilitar MFA.", + "settings.mfa_code": "Código de 6 dígitos", + "settings.mfa_enable": "Habilitar MFA", + "settings.mfa_manage_help": "Para cambiar MFA, introduce la contraseña actual y un código de Authenticator o recuperación.", + "settings.mfa_code_or_recovery": "Código de Authenticator o recuperación", + "settings.mfa_regenerate": "Nuevos códigos de recuperación", + "settings.mfa_disable": "Deshabilitar MFA", + "settings.mfa_recovery_title": "Códigos de recuperación", + "settings.mfa_recovery_help": "Guarda estos códigos ahora. Cada uno se usa una vez si Google Authenticator no está disponible. No se mostrarán otra vez.", + "settings.mfa_recovery_remaining": "Códigos de recuperación restantes: {count}", + "settings.mfa_enabled_ok": "MFA habilitada.", + "settings.mfa_disabled_ok": "MFA deshabilitada.", + "settings.mfa_disable_confirm": "¿Deshabilitar la autenticación de dos factores para esta cuenta?", + "settings.mfa_regenerate_confirm": "¿Reemplazar todos los códigos de recuperación existentes?", + "settings.mfa_recovery_regenerated": "Nuevos códigos de recuperación creados.", + "audit.action.auth.mfa_failed": "Error de verificación MFA", + "audit.action.auth.mfa_recovery_used": "Código de recuperación MFA utilizado", + "audit.action.user.mfa_setup_started": "Configuración de MFA iniciada", + "audit.action.user.mfa_enabled": "MFA habilitada", + "audit.action.user.mfa_disabled": "MFA deshabilitada", + "audit.action.user.mfa_disabled_cli": "MFA deshabilitada por CLI", + "audit.action.user.mfa_recovery_regenerated": "Códigos de recuperación MFA regenerados", + "settings.mfa_error_password": "Contraseña actual incorrecta.", + "settings.mfa_error_code": "Código de autenticación no válido.", + "settings.mfa_error_already_enabled": "MFA ya está habilitada.", + "settings.mfa_error_not_enabled": "MFA no está habilitada.", + "settings.mfa_error_not_started": "Vuelve a iniciar la configuración MFA.", + "trace.title": "Traceroute, ping y mapa de ruta", + "trace.subtitle": "Mide la latencia hacia un VPS u otro servidor y detecta retrasos en la ruta.", + "trace.target": "IP o nombre de host del servidor", + "trace.show_map": "Mostrar ruta en el mapa", + "trace.run": "Iniciar traceroute", + "trace.geo_note": "La geolocalización es aproximada. Con el mapa activado, las IP públicas de los saltos se envían a ipwho.is; los mapas se cargan desde OpenStreetMap.", + "trace.latency_note": "Traceroute mide la latencia en milisegundos, no el rendimiento en Mbit/s.", + "trace.map": "Mapa de ruta", + "trace.map_hint": "Mapa interactivo: arrastra para mover, usa la rueda o +/− para ampliar y pulsa un salto para ver detalles.", + "trace.hop": "Salto / IP", + "trace.location": "Ubicación", + "trace.avg_rtt": "RTT medio", + "trace.delta": "Δ RTT", + "trace.loss": "Pérdida", + "trace.summary_target": "Destino", + "trace.summary_ping": "Ping medio", + "trace.summary_loss": "Pérdida de ping", + "trace.summary_hops": "Saltos", + "trace.no_reply": "Sin respuesta", + "trace.private": "Red privada", + "trace.unknown": "Desconocido", + "trace.running": "Ejecutando ping y traceroute… Puede tardar hasta un minuto.", + "trace.done": "Traza de red completada.", + "trace.failed": "Error de traza de red", + "trace.partial_geo": "No se pudieron geolocalizar algunos saltos públicos.", + "trace.not_reached": "Traceroute no alcanzó el destino.", + "trace.reached": "Destino alcanzado", + "trace.ms": "ms", + "server.tab_trace": "Rastreo", + "trace.map_controls": "Controles del mapa", + "trace.zoom_in": "Acercar", + "trace.zoom_out": "Alejar", + "trace.fit_route": "Ajustar a la ruta", + "trace.fit": "Ajustar", + "trace.map_click_hint": "Pulsa un salto para ver IP, ubicación, ASN y RTT.", + "trace.route_path": "Ruta", + "trace.ping_ok_trace_filtered": "El destino responde a ping, pero los últimos saltos del traceroute no responden.", + "trace.latency_legend": "Aumento de latencia entre saltos que responden", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — elevado", + "trace.latency_bad": "Δ RTT > 20 ms — salto brusco" +} diff --git a/app/locales/fr.json b/app/locales/fr.json new file mode 100644 index 0000000..2c3844e --- /dev/null +++ b/app/locales/fr.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Créer un utilisateur", + "auth.login_subtitle": "Saisissez votre nom d’utilisateur et votre mot de passe WGTools.", + "auth.login_title": "Se connecter à WGTools", + "auth.password": "Mot de passe", + "auth.password_repeat": "Répéter le mot de passe", + "auth.setup_help": "Le premier compte dispose d’un accès complet à WGTools. D’autres utilisateurs peuvent être créés plus tard dans les paramètres.", + "auth.setup_subtitle": "Un compte WGTools est requis avant de pouvoir gérer le serveur.", + "auth.setup_title": "Créer le premier utilisateur", + "auth.sign_in": "Se connecter", + "auth.sign_out": "Se déconnecter", + "auth.username": "Nom d’utilisateur", + "clients.actions": "Actions", + "clients.add": "+ Ajouter un client", + "clients.address": "Adresse VPN", + "clients.address_hint": "La première adresse disponible est proposée automatiquement.", + "clients.allowed_ips_required": "Saisissez au moins un réseau AllowedIPs pour la configuration client.", + "clients.basic_connection": "Paramètres de connexion", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs de la configuration client", + "clients.config_private_warning": "Cette configuration contient la clé privée du client. Conservez-la en lieu sûr.", + "clients.config_title": "Configuration client", + "clients.config_unavailable": "Configuration indisponible", + "clients.connection_direct": "Directement vers WGTools", + "clients.connection_path": "Chemin de connexion", + "clients.connection_relay": "Relais VPS", + "clients.connection_via": "Se connecter via", + "clients.connection_via_hint": "Choisissez le point d’entrée public du client. Le relais n’apparaît que s’il est installé pour l’interface WireGuard sélectionnée.", + "clients.copy_config": "Copier", + "clients.copy_done": "Configuration copiée", + "clients.create_subtitle": "Créer un pair WireGuard et générer sa configuration client.", + "clients.create_title": "Créer un client", + "clients.creating": "Création des clés et application du client…", + "clients.day_fri": "Ven", + "clients.day_mon": "Lun", + "clients.day_sat": "Sam", + "clients.day_sun": "Dim", + "clients.day_thu": "Jeu", + "clients.day_tue": "Mar", + "clients.day_wed": "Mer", + "clients.delete_confirm": "Supprimer ce client de WireGuard ? WGTools créera une sauvegarde et supprimera les règles automatiques associées.", + "clients.deleted": "Client supprimé", + "clients.dns": "DNS (facultatif)", + "clients.dns_hint": "Serveurs DNS IPv4 séparés par des virgules.", + "clients.download_config": "Télécharger .conf", + "clients.duplicate": "Dupliquer", + "clients.duplicate_address_error": "Cette adresse VPN est déjà utilisée par un autre pair.", + "clients.duplicate_name_error": "Un pair portant ce nom existe déjà.", + "clients.duplicate_ready": "Copie prête. WGTools a attribué un nouveau nom et une adresse VPN. Vérifiez les paramètres avant d’enregistrer.", + "clients.duplicate_site_hint": "Les réseaux distants ont été effacés pour éviter les routes en double. Indiquez les réseaux du nouveau pair Site-to-site.", + "clients.duplicate_suffix": "copie", + "clients.edit_subtitle": "Modifier le pair côté serveur. Les changements sont appliqués sans redémarrer WireGuard.", + "clients.edit_title": "Modifier le client", + "clients.endpoint": "Endpoint du serveur", + "clients.endpoint_hint": "Pour les clients distants, utilisez l’IP publique ou le domaine qui redirige le port WireGuard vers ce serveur.", + "clients.existing": "Pair existant", + "clients.expiration": "Durée de validité", + "clients.expiration_action": "À expiration", + "clients.expiration_action_hint": "Si cette option est décochée, le client reste dans WGTools mais son accès WireGuard est désactivé. Choisissez une nouvelle durée ou aucune expiration et enregistrez pour rétablir l’accès.", + "clients.expiration_datetime": "Expire le", + "clients.expiration_datetime_hint": "Utilise la date et l’heure locales du navigateur.", + "clients.expiration_delete": "Supprimer le client", + "clients.expiration_future_required": "Choisissez une date et une heure futures.", + "clients.expiration_hint": "À expiration, WGTools exécute l’action choisie au début de la minute suivante. Une sauvegarde WireGuard est créée avant.", + "clients.expire_1d": "1 jour", + "clients.expire_1h": "1 heure", + "clients.expire_3h": "3 heures", + "clients.expire_6h": "6 heures", + "clients.expire_custom": "Date et heure personnalisées", + "clients.expire_never": "Aucune expiration", + "clients.expired": "Expiré", + "clients.expired_disabled_hint": "L’accès a expiré. Le client est conservé mais WireGuard est désactivé. Choisissez une nouvelle durée ou aucune expiration puis enregistrez.", + "clients.expired_disabled_short": "Expiré · désactivé", + "clients.expired_disabled_status": "Expiré", + "clients.expires_days": "Expire dans {n} j", + "clients.expires_hours": "Expire dans {n} h", + "clients.expires_minutes": "Expire dans {n} min", + "clients.generated_config": "Configuration client générée", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 secondes est une bonne valeur par défaut pour les clients derrière un NAT.", + "clients.local_access_exceptions": "Adresses locales autorisées", + "clients.local_access_exceptions_hint": "IP ou CIDR facultatifs restant accessibles même si leur réseau local ou Site-to-site est bloqué. Séparez-les par des virgules.", + "clients.managed": "Géré par WGTools", + "clients.name": "Nom", + "clients.no_peers": "Aucun pair trouvé", + "clients.peers": "Pairs", + "clients.peers_subtitle": "Les modifications sont sauvegardées puis appliquées avec wg syncconf sans redémarrer l’interface WireGuard.", + "clients.protected_networks_reference": "Réseaux locaux bloqués (référence)", + "clients.protected_networks_reference_hint": "Ces réseaux ne sont pas écrits dans AllowedIPs. L’accès est bloqué par la politique serveur WGTools ; des adresses individuelles peuvent être autorisées ci-dessus.", + "clients.psk": "Clé prépartagée (PSK)", + "clients.psk_enable": "Utiliser une clé WireGuard prépartagée supplémentaire", + "clients.psk_hint": "Recommandé. Ajoute un secret symétrique au handshake WireGuard. Les clients standards le prennent en charge ; WGTools inclut le PSK dans la configuration et le QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Génération du QR…", + "clients.quick_search": "Recherche rapide", + "clients.quick_search_clear": "Effacer la recherche", + "clients.quick_search_empty": "Aucun client correspondant", + "clients.relay_endpoint_note": "La configuration client générée se connectera à {endpoint}. Le serveur WireGuard reste sur cet hôte WGTools.", + "clients.relay_required": "Choisissez un relais VPS pour ce client.", + "clients.relay_short": "Relais", + "clients.relay_unknown": "indisponible", + "clients.relay_vps": "Relais VPS", + "clients.relay_vps_hint": "L’endpoint du client est généré automatiquement depuis ce relais.", + "clients.remote_hint": "Réseaux situés derrière ce pair. Un par ligne ou séparés par des virgules.", + "clients.remote_networks": "Réseaux distants", + "clients.remote_required": "Saisissez au moins un réseau distant pour le pair Site-to-site.", + "clients.required": "Le nom et l’adresse VPN sont obligatoires.", + "clients.route_custom": "Personnalisé", + "clients.route_full": "Tunnel complet", + "clients.route_full_except_local": "Tunnel complet sauf réseaux locaux", + "clients.route_hint": "Seuls ces réseaux sont écrits dans AllowedIPs de la configuration client.", + "clients.route_preset": "Trafic via VPN", + "clients.route_vpn": "Réseau VPN uniquement", + "clients.route_vpn_lan": "VPN + réseau local", + "clients.saved": "Client enregistré", + "clients.schedule_blocked_short": "Horaire · bloqué", + "clients.schedule_blocked_status": "Bloqué par la plage horaire", + "clients.schedule_days": "Jours autorisés", + "clients.schedule_days_required": "Choisissez au moins un jour pour la plage horaire.", + "clients.schedule_disabled_hint": "Ce client est actuellement bloqué par son horaire. WGTools rétablira le pair automatiquement au prochain créneau autorisé.", + "clients.schedule_enable": "Limiter l’accès selon un horaire", + "clients.schedule_from": "Accès à partir de", + "clients.schedule_hint": "WGTools peut désactiver puis réactiver le client aux jours et heures choisis sans modifier sa configuration.", + "clients.schedule_short": "Horaire", + "clients.schedule_time_required": "Définissez les heures de début et de fin.", + "clients.schedule_timezone_hint": "L’horaire utilise l’heure locale du serveur WireGuard. Les plages traversant minuit, comme 22:00–06:00, sont prises en charge.", + "clients.schedule_title": "Plage horaire d’accès", + "clients.schedule_to": "Accès jusqu’à", + "clients.security_access": "Sécurité et heures d’accès", + "clients.server_host": "Adresse / domaine du serveur", + "clients.server_host_hint": "IP publique ou domaine utilisé par ce client. Les valeurs précédentes apparaissent comme suggestions.", + "clients.server_host_required": "Une adresse / un domaine serveur est nécessaire pour la configuration client.", + "clients.server_peer": "Pair serveur", + "clients.server_port": "Port WireGuard", + "clients.server_port_hint": "Repris automatiquement de la configuration serveur.", + "clients.site_to_site": "Site à site", + "clients.status": "État", + "clients.subtitle": "Pairs WireGuard, état en direct et gestion des configurations client.", + "clients.tab_basic": "Basique", + "clients.tab_config": "Configuration", + "clients.tab_policy": "Politiques", + "clients.tab_security": "Sécurité", + "clients.title": "Clients", + "clients.type": "Type", + "clients.unmanaged_note": "Ce pair existait avant WGTools. Sa clé privée client est irrécupérable. WGTools peut modifier le pair côté serveur mais ne peut pas générer sa configuration client ou son QR.", + "clients.updating": "Mise à jour du client…", + "common.actions": "Actions", + "common.ago": "il y a", + "common.cancel": "Annuler", + "common.checking": "Vérification…", + "common.close": "Fermer", + "common.config": "Configuration", + "common.delete": "Supprimer", + "common.disabled": "Désactivé", + "common.edit": "Modifier", + "common.enabled": "Activé", + "common.loading": "Chargement…", + "common.never": "Jamais", + "common.no": "Non", + "common.not_configured": "Non configuré", + "common.not_installed": "Non installé", + "common.offline": "hors ligne", + "common.online": "en ligne", + "common.refresh": "Actualiser", + "common.running": "En cours", + "common.save": "Enregistrer", + "common.stopped": "Arrêté", + "common.total": "Total", + "common.unknown": "Inconnu", + "common.updated": "Mis à jour", + "common.yes": "Oui", + "dashboard.active_peers": "Pairs actifs", + "dashboard.active_peers_subtitle": "Données en direct issues de wg show.", + "dashboard.activity": "Vue d’ensemble du système", + "dashboard.activity_subtitle": "Vérifications en lecture seule de WireGuard en fonctionnement.", + "dashboard.cores": "cœurs", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Dernières 24 h", + "dashboard.history_avg": "Moy.", + "dashboard.history_max": "Max.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "maintenant", + "dashboard.memory": "Mémoire", + "dashboard.network": "Réseau", + "dashboard.peers": "Pairs", + "dashboard.quick_search": "Recherche rapide", + "dashboard.quick_search_clear": "Effacer la recherche", + "dashboard.quick_search_empty": "Aucun pair ne correspond à la recherche", + "dashboard.restart": "Redémarrer", + "dashboard.restart_confirm": "Redémarrer WireGuard ? Les clients VPN actifs se reconnecteront automatiquement.", + "dashboard.restart_ok": "WireGuard redémarré.", + "dashboard.routing": "Routage", + "dashboard.site_to_site": "Site à site", + "dashboard.start": "Démarrer", + "dashboard.start_ok": "WireGuard démarré.", + "dashboard.stop": "Arrêter", + "dashboard.stop_confirm": "Arrêter WireGuard ? Les clients VPN actifs seront déconnectés.", + "dashboard.stop_ok": "WireGuard arrêté.", + "dashboard.subtitle": "État du serveur WireGuard, pairs et trafic en direct.", + "dashboard.title": "Tableau de bord", + "dashboard.traffic": "Trafic", + "dashboard.uptime": "Temps de fonctionnement", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Politique d’accès au serveur", + "groups.additional_allowed": "Adresses supplémentaires autorisées", + "groups.additional_blocked": "Adresses supplémentaires bloquées", + "groups.allow": "Autoriser", + "groups.allowed": "Autorisé", + "groups.allowed_addresses": "Adresses / réseaux autorisés", + "groups.apply_current_template": "Appliquer le modèle actuel du groupe", + "groups.apply_defaults": "Appliquer le modèle actuel du groupe", + "groups.apply_defaults_hint": "Copie les routes, DNS et Keepalive du modèle de groupe vers ce client. Enregistrez-le puis générez une nouvelle configuration ou un QR si nécessaire.", + "groups.basic": "Informations de base", + "groups.block": "Bloquer", + "groups.blocked": "Bloqué", + "groups.blocked_addresses": "Adresses / réseaux bloqués", + "groups.client_config_source": "Source de configuration client", + "groups.client_defaults": "Paramètres client par défaut", + "groups.client_group_hint": "Groupe facultatif pour réutiliser les règles d’accès et paramètres client. Chaque groupe est associé à l’interface WireGuard sélectionnée.", + "groups.config_differs": "La configuration du client diffère des paramètres actuels du groupe. La politique serveur est à jour, mais le téléphone ou PC doit recevoir une nouvelle configuration ou un QR.", + "groups.config_differs_short": "Configuration client différente du groupe", + "groups.create": "Créer un groupe", + "groups.create_title": "Créer un groupe", + "groups.created": "Groupe créé", + "groups.creating": "Création du groupe…", + "groups.defaults_applied": "Modèle actuel du groupe appliqué. Enregistrez le client pour conserver les changements.", + "groups.defaults_hint": "Définit le trafic envoyé par le client via WireGuard. La politique serveur ci-dessus détermine séparément les accès autorisés. Modifier le modèle ne change jamais les configurations déjà installées.", + "groups.delete_message": "Supprimer « {name} » ? Les configurations client ne sont jamais supprimées avec le groupe.", + "groups.delete_move": "Déplacer ses clients vers un autre groupe", + "groups.delete_title": "Supprimer le groupe de clients", + "groups.delete_unassign": "Retirer l’affectation du groupe aux clients", + "groups.deleted": "Groupe supprimé", + "groups.deleting": "Mise à jour des clients et suppression du groupe…", + "groups.description": "Description", + "groups.edit_title": "Modifier le groupe", + "groups.editor_subtitle": "Un groupe associe des règles d’accès serveur actives à un modèle de configuration client.", + "groups.effective_allow": "Exceptions autorisées", + "groups.effective_deny": "Exceptions bloquées", + "groups.effective_policy": "Politique serveur effective", + "groups.empty": "Aucun groupe de clients. Créez-en un pour réutiliser les règles d’accès et les paramètres par défaut.", + "groups.group": "Groupe", + "groups.inherit": "Hériter", + "groups.internet_access": "Accès Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Réseaux locaux", + "groups.local_short": "Local", + "groups.manage": "Groupes", + "groups.members_count": "{count} clients", + "groups.name": "Nom", + "groups.name_required": "Le nom du groupe est obligatoire.", + "groups.new_client_defaults": "Modèle de configuration client", + "groups.new_clients_short": "Nouveaux clients", + "groups.no_group": "Aucun groupe", + "groups.none": "Aucun", + "groups.override_client_config": "Remplacer le modèle client du groupe pour ce client", + "groups.override_client_config_hint": "Désactivé : routes, DNS et Keepalive proviennent du groupe. Activé : ce client conserve ses valeurs. Les exceptions de politique serveur restent indépendantes.", + "groups.policy_addresses_hint": "Adresses IPv4 ou CIDR séparés par des virgules. Les exceptions client ont priorité sur celles du groupe.", + "groups.policy_custom": "Politique personnalisée", + "groups.policy_inherit": "Utiliser la politique du groupe", + "groups.policy_mode": "Source de la politique", + "groups.policy_mode_hint": "La politique du groupe s’applique par défaut. Les exceptions client ne modifient jamais le groupe.", + "groups.routes_required": "Les routes du client ne peuvent pas être vides.", + "groups.subtitle": "Réutilisez les règles d’accès serveur et les paramètres par défaut pour les clients de l’interface WireGuard sélectionnée.", + "groups.title": "Groupes de clients", + "groups.traffic_through_vpn": "Trafic via VPN", + "groups.updated": "Groupe mis à jour", + "groups.updating": "Mise à jour de la politique du groupe…", + "help.example_note": "Toutes les adresses, interfaces, noms de pairs et domaines des exemples d’aide sont fictifs. Remplacez-les par vos propres valeurs.", + "help.navigation": "Navigation de l’aide", + "help.open": "Ouvrir l’aide", + "help.subtitle": "Aide accessible pour le tableau de bord, le serveur, les clients et les paramètres, avec des exemples pratiques.", + "help.title": "Aide WGTools", + "interfaces.add": "+ Ajouter une interface", + "interfaces.create": "Créer une interface", + "interfaces.create_confirm": "Créer et démarrer l’interface {name} ?", + "interfaces.create_failed": "Impossible de créer l’interface", + "interfaces.create_hint": "Avant la création, WGTools vérifie que le réseau VPN, le port UDP et la table de routage ne sont pas déjà utilisés par une autre interface WireGuard.", + "interfaces.create_subtitle": "Créez une interface WireGuard indépendante avec son propre pool d’adresses, port UDP et paramètres de routage.", + "interfaces.create_title": "Ajouter une interface WireGuard", + "interfaces.created": "Interface créée avec succès.", + "interfaces.creating": "Génération des clés, écriture de la configuration et démarrage de WireGuard…", + "interfaces.current": "Actuelle", + "interfaces.delete": "Supprimer", + "interfaces.delete_confirm": "Supprimer l’interface {name} ? Sa configuration WireGuard et tous ses pairs seront supprimés. Une sauvegarde sera créée au préalable.", + "interfaces.delete_failed": "Impossible de supprimer l’interface", + "interfaces.delete_last": "La dernière interface WireGuard configurée ne peut pas être supprimée ici.", + "interfaces.delete_tooltip": "Supprimer cette interface WireGuard", + "interfaces.deleted": "Interface supprimée. Sauvegarde : {backup}", + "interfaces.deleting": "Arrêt de WireGuard et suppression de l’interface…", + "interfaces.display_name": "Nom affiché", + "interfaces.display_name_edit_hint": "Nom d’affichage uniquement : le nom de l’interface Linux ne change pas.", + "interfaces.display_name_hint": "Nom convivial facultatif, par exemple Travail ou Prestataires.", + "interfaces.identity": "Identité de l’interface", + "interfaces.none": "Aucune interface WireGuard trouvée", + "interfaces.none_configured": "Aucune interface WireGuard n’est encore configurée.", + "interfaces.peers_short": "pairs", + "interfaces.rename_failed": "Impossible d’enregistrer le nom affiché de l’interface.", + "interfaces.select": "Sélectionner", + "interfaces.subtitle": "Chaque interface possède son réseau VPN, son port, ses pairs et ses règles. Sélectionnez-en une pour la gérer dans WGTools.", + "interfaces.switch_title": "Interfaces WireGuard", + "interfaces.system_name": "Nom système", + "interfaces.system_name_hint": "Nom de l’interface Linux, par exemple wg1. Non modifiable après création.", + "interfaces.title": "Interfaces WireGuard", + "interfaces.unique_port_hint": "Chaque interface WireGuard de ce serveur doit utiliser un port UDP distinct.", + "interfaces.unique_table_hint": "WGTools recommande une table de routage distincte par interface. Laissez vide pour le routage standard.", + "nav.clients": "Clients", + "nav.dashboard": "Tableau de bord", + "nav.server": "Serveur", + "nav.settings": "Paramètres", + "server.access_apply_confirm": "Enregistrer et appliquer cette règle de pare-feu ? WireGuard redémarrera brièvement et une sauvegarde sera créée.", + "server.access_rule_deleted": "Règle d’accès supprimée.", + "server.access_rule_help": "Créez une règle FORWARD sans modifier manuellement les commandes iptables.", + "server.access_rule_order_hint": "WGTools insère les règles au début de la chaîne FORWARD pour appliquer les restrictions avant les règles VPN ACCEPT générales.", + "server.access_rule_saved": "Règle d’accès enregistrée et appliquée.", + "server.action": "Action", + "server.action_hint": "REJECT signale le refus au client ; DROP écarte sans réponse ; ACCEPT autorise explicitement.", + "server.add_access_rule": "Ajouter une règle d’accès", + "server.add_route": "Ajouter une route", + "server.address": "Adresse", + "server.any": "Tous", + "server.any_protocol": "Tout protocole", + "server.apply_confirm": "Enregistrer et appliquer les paramètres serveur ? WireGuard redémarrera brièvement. Une sauvegarde sera créée et la configuration précédente restaurée automatiquement si le démarrage échoue.", + "server.apply_settings": "Enregistrer et appliquer", + "server.applying_rule": "Création de sauvegarde et application…", + "server.applying_settings": "Validation, sauvegarde et application des paramètres…", + "server.basic_settings": "Paramètres de base", + "server.config_tab_help": "Ouvrir l’éditeur de configuration brute de l’interface WireGuard sélectionnée.", + "server.create_confirm": "Créer et démarrer le serveur WireGuard avec ces paramètres ?", + "server.create_server": "Créer le serveur", + "server.create_step_conf": "Créer la configuration de l’interface WireGuard avec les permissions 600.", + "server.create_step_forward": "Configurer le transfert, le NAT et éventuellement le routage par politique.", + "server.create_step_key": "Générer une nouvelle paire de clés serveur.", + "server.create_step_start": "Activer et démarrer l’interface wg-quick choisie.", + "server.create_subtitle": "WireGuard est installé, mais l’interface sélectionnée n’est pas configurée.", + "server.create_success": "Serveur WireGuard créé avec succès.", + "server.create_title": "Créer le serveur WireGuard", + "server.creating": "Génération des clés, écriture de la configuration et démarrage de WireGuard…", + "server.custom_preserved": "Les blocs de pairs, routes Site-to-site et règles PostUp/PostDown non gérées ici sont conservés.", + "server.delete_access_confirm": "Supprimer cette règle d’accès et appliquer ?", + "server.delete_route_confirm": "Supprimer cette route personnalisée et appliquer ?", + "server.destination": "Destination", + "server.destination_hint": "Vide = tous. IP, CIDR ou plage IP acceptés. Séparez plusieurs destinations par des virgules.", + "server.destination_port": "Port de destination", + "server.destination_port_hint": "Facultatif. Port comme 443 ou plage 10000:20000. Sélectionnez d’abord TCP ou UDP.", + "server.details": "Détails", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostic", + "server.diagnostics_done": "Diagnostic terminé", + "server.diagnostics_subtitle": "Contrôles système actuels. Aucune modification de configuration.", + "server.direction": "Hook", + "server.edit_access_rule": "Modifier la règle d’accès", + "server.edit_route": "Modifier la route", + "server.edit_server": "Modifier le serveur", + "server.edit_subtitle": "Modifier les paramètres WireGuard, routage et NAT courants. Les pairs et règles personnalisées sont conservés.", + "server.edit_title": "Paramètres du serveur", + "server.edit_warning": "Appliquer les paramètres d’interface, routage ou pare-feu redémarre brièvement WireGuard. Les pairs actifs se reconnectent automatiquement.", + "server.enable_forwarding": "Activer le transfert IPv4", + "server.enable_nat": "Activer NAT / Masquerade", + "server.firewall": "Pare-feu et NAT", + "server.firewall_subtitle": "Règles détectées dans les hooks WireGuard.", + "server.firewall_subtitle_v08": "Règles de transfert/NAT et d’accès de l’interface. Les règles simples se gèrent ici ; les plus avancées restent dans l’éditeur brut.", + "server.forward_from_vpn": "Autoriser le transfert depuis VPN", + "server.forward_to_vpn": "Autoriser le transfert vers VPN", + "server.forwarding_section": "Transfert et NAT", + "server.gateway": "Passerelle", + "server.gateway_hint": "Obligatoire uniquement avec une table de routage par politique.", + "server.install_success": "WireGuard installé avec succès.", + "server.install_wireguard": "Installer WireGuard", + "server.install_wireguard_help": "Exécute apt update et installe WireGuard et les outils réseau nécessaires.", + "server.install_wireguard_title": "Installer WireGuard", + "server.installing": "Installation de WireGuard… Cela peut prendre une minute.", + "server.interface": "Interface", + "server.interface_hint": "WGTools gère actuellement cette interface.", + "server.interface_name": "Interface", + "server.interface_section": "Interface WireGuard", + "server.ip_forwarding": "Transfert IPv4", + "server.kind": "Type", + "server.listen_port": "Port d’écoute", + "server.local_network": "Réseau local", + "server.local_network_hint": "Route facultative ajoutée à la table de routage.", + "server.managed_automatically": "Géré automatiquement", + "server.nat": "NAT / Masquerade", + "server.network": "Réseau", + "server.network_settings": "Réseau et NAT", + "server.no_firewall": "Aucune règle de pare-feu trouvée", + "server.no_routes": "Aucune route trouvée", + "server.not_configured": "Non configuré", + "server.not_set": "Non défini", + "server.policy_disabled_hint": "Désactivez pour le routage système normal. Activez uniquement si ce VPN requiert une table par adresse source.", + "server.policy_enabled": "Activer le routage par politique", + "server.policy_table": "Table de routage", + "server.policy_table_hint": "Laissez vide pour le routage normal ; utilisez par ex. 200 pour le routage par source.", + "server.port_word": "port", + "server.private_hidden": "Configuré (masqué)", + "server.private_key": "Clé privée", + "server.protocol": "Protocole", + "server.route_apply_confirm": "Enregistrer et appliquer cette route ? WireGuard redémarrera brièvement et une sauvegarde sera créée.", + "server.route_custom": "Personnalisée", + "server.route_deleted": "Route supprimée.", + "server.route_device_hint": "Interface de sortie facultative, par ex. wg0 ou enp6s18.", + "server.route_editor_help": "Ajoutez une route installée au démarrage de WireGuard puis retirée à l’arrêt.", + "server.route_gateway_hint": "Passerelle de prochain saut facultative. Une passerelle ou interface est requise.", + "server.route_managed_peer": "Pair Site-to-site", + "server.route_managed_server": "Paramètre serveur", + "server.route_network_hint": "Réseau IPv4 comme 10.20.0.0/24 ou 'default'.", + "server.route_saved": "Route enregistrée et appliquée.", + "server.route_table_hint": "Utilisez 'main' pour le routage normal ou une table numérique comme 200.", + "server.route_type": "Type", + "server.routes": "Routes détectées", + "server.routes_subtitle": "Routes extraites de PostUp/PostDown et de l’état actuel du routage par politique.", + "server.routes_subtitle_v08": "Routes serveur, Site-to-site et personnalisées de l’interface choisie. Vous pouvez ajouter, modifier et retirer des routes personnalisées ici.", + "server.routing": "Routage", + "server.routing_section": "Routage", + "server.rule": "Règle", + "server.rule_access": "Règle d’accès", + "server.rule_advanced": "Avancé", + "server.rule_apply_warning": "L’application d’une route ou règle de pare-feu redémarre brièvement WireGuard. WGTools sauvegarde puis restaure automatiquement en cas d’échec de démarrage.", + "server.rule_client_exception": "Exception client", + "server.rule_client_policy": "Politique client", + "server.rule_managed_server": "Paramètre serveur", + "server.rule_type": "Type", + "server.run_diagnostics": "Lancer le diagnostic", + "server.save_apply": "Enregistrer et appliquer", + "server.save_config": "SaveConfig", + "server.server_address": "Adresse VPN du serveur", + "server.server_address_hint": "Habituellement la première adresse utilisable du réseau VPN.", + "server.settings_applied": "Paramètres serveur enregistrés et appliqués avec succès.", + "server.settings_apply_failed": "Impossible d’appliquer les paramètres serveur", + "server.setup_required": "Configuration requise", + "server.source": "Source", + "server.source_hint": "Vide = tous. Accepte IP, CIDR ou plage telle que 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installation, première configuration et paramètres actuels du serveur WireGuard.", + "server.tab_config": "Configuration", + "server.tab_interface": "Interface", + "server.tab_routing": "Routage", + "server.tab_vps": "VPS", + "server.table": "Table", + "server.tabs_aria": "Sections des paramètres serveur", + "server.title": "Serveur", + "server.uplink": "Interface montante", + "server.use_raw_editor": "Utiliser l’éditeur brut", + "server.via": "Via / Interface", + "server.via_word": "via", + "server.vpn_network": "Réseau VPN", + "server.vpn_network_hint": "Les adresses client seront ensuite attribuées depuis ce réseau.", + "server.vpn_pool": "Pool d’adresses VPN", + "server.wg_not_installed": "WireGuard n’est pas installé", + "server.wg_not_installed_subtitle": "WGTools peut installer automatiquement les paquets Debian nécessaires.", + "server.what_happens": "Ce que fera WGTools", + "settings.about": "À propos", + "settings.add_user": "Ajouter un utilisateur", + "settings.advanced": "Avancé", + "settings.advanced_subtitle": "Accès direct aux outils avancés de configuration WireGuard.", + "settings.appearance": "Apparence", + "settings.applying_config": "Vérification de configuration, sauvegarde et application…", + "settings.backup_count": "Sauvegardes stockées", + "settings.backup_retention": "Nombre de sauvegardes à garder", + "settings.backup_retention_help": "Les anciennes sauvegardes automatiques sont supprimées après la création de la suivante. De 1 à 200 fichiers.", + "settings.backups": "Sauvegardes de configuration", + "settings.backups_always_on": "Activé", + "settings.backups_subtitle": "WGTools crée automatiquement une sauvegarde avant toute modification de configuration. Cette protection ne peut pas être désactivée.", + "settings.change_password": "Changer le mot de passe", + "settings.check_updates": "Rechercher des mises à jour", + "settings.config_applied": "Configuration enregistrée et appliquée avec succès.", + "settings.config_applied_restarted": "Configuration appliquée et WireGuard redémarré.", + "settings.config_applied_stopped": "Configuration enregistrée. WireGuard était arrêté et reste arrêté.", + "settings.config_apply_failed": "Impossible d’appliquer la configuration", + "settings.config_load_failed": "Impossible de charger la configuration", + "settings.current_user": "Utilisateur actuel", + "settings.current_version": "Version actuelle", + "settings.audit_action": "Action", + "settings.audit_empty": "Aucun événement d’audit", + "settings.audit_log": "Journal d’audit", + "settings.audit_log_subtitle": "Actions du panneau, connexions, Telegram et historique des clients WireGuard. Aucun secret n’est enregistré ici.", + "settings.audit_object": "Objet", + "settings.audit_result": "Résultat", + "settings.audit_retention_note": "Conservation : 30 jours", + "settings.audit_search": "Recherche rapide", + "settings.audit_search_clear": "Effacer la recherche", + "settings.audit_search_empty": "Aucun événement d’audit correspondant", + "settings.audit_time": "Date / heure", + "settings.audit_user": "Utilisateur", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Règle d’accès créée", + "audit.action.access_rule.deleted": "Règle d’accès supprimée", + "audit.action.access_rule.updated": "Règle d’accès modifiée", + "audit.action.auth.first_user_created": "Premier utilisateur créé", + "audit.action.auth.login": "Connexion réussie", + "audit.action.auth.login_failed": "Échec de connexion", + "audit.action.auth.logout": "Déconnexion effectuée", + "audit.action.backup.full_created": "Sauvegarde complète créée", + "audit.action.backup.full_restored": "Sauvegarde complète restaurée", + "audit.action.client.config_downloaded": "Configuration client téléchargée", + "audit.action.client.config_viewed": "Configuration client consultée", + "audit.action.client.created": "Client créé", + "audit.action.client.deleted": "Client supprimé", + "audit.action.client.qr_viewed": "Code QR du client consulté", + "audit.action.client.updated": "Client mis à jour", + "audit.action.client_group.created": "Groupe de clients créé", + "audit.action.client_group.deleted": "Groupe de clients supprimé", + "audit.action.client_group.updated": "Groupe de clients mis à jour", + "audit.action.interface.created": "Interface créée", + "audit.action.interface.deleted": "Interface supprimée", + "audit.action.interface.renamed": "Interface renommée", + "audit.action.route.created": "Route créée", + "audit.action.route.deleted": "Route supprimée", + "audit.action.route.updated": "Route mise à jour", + "audit.action.server.created": "Serveur créé", + "audit.action.server.raw_config_applied": "Configuration brute appliquée", + "audit.action.server.settings_applied": "Paramètres serveur appliqués", + "audit.action.settings.updated": "Paramètres du panneau modifiés", + "audit.action.telegram.action_denied": "Action Telegram refusée", + "audit.action.telegram.action_failed": "Échec de l’action Telegram", + "audit.action.telegram.connection_test": "Test de connexion Telegram", + "audit.action.telegram.settings_updated": "Paramètres Telegram modifiés", + "audit.action.update.checked": "Mise à jour vérifiée", + "audit.action.update.scheduled": "Mise à jour planifiée", + "audit.action.update.backup_created": "Sauvegarde avant mise à jour", + "audit.action.update.completed": "Mise à jour terminée", + "audit.action.update.failed": "Échec de la mise à jour", + "audit.action.update.rollback_completed": "Version précédente restaurée", + "audit.action.update.rollback_failed": "Échec du retour arrière", + "audit.action.user.created": "Utilisateur créé", + "audit.action.user.deleted": "Utilisateur supprimé", + "audit.action.user.password_changed": "Mot de passe utilisateur modifié", + "audit.action.vps.candidate_deleted": "Candidat VPS supprimé", + "audit.action.vps.candidate_saved": "Candidat VPS enregistré", + "audit.action.vps.detached": "Relais VPS détaché", + "audit.action.vps.relay_installed": "Relais VPS installé", + "audit.action.wireguard.client_connected": "Client WireGuard connecté", + "audit.action.wireguard.installed": "WireGuard installé", + "audit.action.wireguard.restarted": "WireGuard redémarré", + "audit.action.wireguard.started": "WireGuard démarré", + "audit.action.wireguard.stopped": "WireGuard arrêté", + "audit.result.applied": "appliqué", + "audit.result.available": "disponible", + "audit.result.changed": "modifié", + "audit.result.created": "créé", + "audit.result.current": "à jour", + "audit.result.deleted": "supprimé", + "audit.result.detached": "détaché", + "audit.result.denied": "refusé", + "audit.result.downloaded": "téléchargé", + "audit.result.endpoint": "Point de terminaison", + "audit.result.error": "Erreur", + "audit.result.installed": "installé", + "audit.result.invalid_credentials": "identifiants invalides", + "audit.result.ok": "OK", + "audit.result.queued": "en attente", + "audit.result.restarted": "redémarré", + "audit.result.restored": "restauré", + "audit.result.rotated": "renouvelé", + "audit.result.saved": "enregistré", + "audit.result.shown": "affiché", + "audit.result.started": "démarré", + "audit.result.stopped": "arrêté", + "audit.result.updated": "mis à jour", + "settings.delete_user": "Supprimer", + "settings.delete_user_confirm": "Supprimer l’utilisateur {name} ?", + "settings.edit_raw_config": "Modifier la configuration de l’interface", + "settings.expert_mode": "Expert", + "settings.full_backup_component_clients": "Métadonnées des clients gérés, clés privées, PSK, expirations et groupes nécessaires pour recréer leurs configurations et QR.", + "settings.full_backup_component_db": "Base WGTools : utilisateurs, préférences, messagerie/SMTP, Telegram et état enregistré des relais VPS.", + "settings.full_backup_component_relay": "Données de récupération VPS Relay : identifiants contrôleur/tenant, jeton d’administration et clé de transport domicile. WGTools pourra reconstruire le transport local et reconnecter le tenant conservé.", + "settings.full_backup_component_system": "Fichier sysctl de transfert IPv4 WGTools, noms d’affichage des interfaces, règles et modèles de groupes si présents. L’historique automatique des configurations est exclu intentionnellement.", + "settings.full_backup_component_wg": "Toutes les configurations des interfaces WireGuard détectées dans /etc/wireguard/, avec leur état actif/arrêté.", + "settings.full_backup_create_failed": "Impossible de créer la sauvegarde complète", + "settings.full_backup_creating": "Création de la sauvegarde complète…", + "settings.full_backup_download": "Créer", + "settings.full_backup_downloaded": "Sauvegarde créée et téléchargée. Conservez-la en sécurité.", + "settings.full_backup_downloaded_short": "Sauvegarde complète téléchargée.", + "settings.full_backup_help": "Crée une sauvegarde portable WGTools pour migration ou reprise après incident : configurations WireGuard, utilisateurs, paramètres, groupes, clients gérés et données nécessaires pour reconnecter les tenants VPS Relay conservés.", + "settings.full_backup_no_file": "Aucune sauvegarde sélectionnée", + "settings.full_backup_restore": "Restaurer", + "settings.full_backup_restore_confirm": "Restaurer cette sauvegarde complète ? Les utilisateurs, paramètres, clients gérés et configurations WireGuard contenus dans l’archive seront restaurés. Des interfaces peuvent redémarrer. WGTools crée d’abord une sauvegarde de sécurité et annule automatiquement en cas d’échec.", + "settings.full_backup_restore_failed": "Échec de la restauration", + "settings.full_backup_restored": "Sauvegarde restaurée. Connectez-vous avec un compte de la sauvegarde.", + "settings.full_backup_restored_short": "Sauvegarde restaurée.", + "settings.full_backup_restoring": "Validation de la sauvegarde, création d’une copie de sécurité et restauration…", + "settings.full_backup_secret_warning": "Ce fichier contient des secrets : clés privées WireGuard et clients, PSK, empreintes des mots de passe WGTools, jeton du bot Telegram et mot de passe SMTP enregistré. Protégez-le comme un mot de passe ; ne le publiez jamais dans des issues ou chats.", + "settings.full_backup_select": "Sélectionner", + "settings.full_backup_title": "Sauvegarde complète et restauration", + "settings.full_mode": "Gestion serveur et clients activée", + "settings.interface_help": "L’interface WireGuard gérée est choisie lors du déploiement WGTools.", + "settings.language": "Langue", + "settings.last_backup": "Dernière sauvegarde", + "settings.latest_version": "Dernière version", + "settings.loading_config": "Chargement de la configuration…", + "settings.mode": "Mode", + "settings.never_logged_in": "Jamais", + "settings.new_password": "Nouveau mot de passe", + "settings.no_backups": "Aucune sauvegarde", + "settings.online_help": "Un pair est en ligne si sa dernière poignée de main est plus récente que cette valeur. 30 à 3600 secondes.", + "settings.online_threshold": "Seuil de connexion", + "settings.open_release": "Ouvrir la version", + "settings.password_changed": "Mot de passe modifié.", + "settings.passwords_mismatch": "Les mots de passe ne correspondent pas.", + "settings.project_github": "Projet / GitHub", + "settings.raw_config_confirm": "Enregistrer et appliquer la configuration WireGuard ? L’interface sélectionnée redémarrera. Une sauvegarde est créée au préalable ; WGTools restaurera automatiquement l’ancienne configuration en cas d’échec.", + "settings.raw_config_help": "Ouvrir la configuration source de l’interface WireGuard sélectionnée.", + "settings.raw_config_title": "Configuration WireGuard brute", + "settings.raw_config_warning": "Mode expert : configuration réelle du serveur WireGuard contenant la clé privée du serveur et les PSK des pairs. Enregistrer et appliquer redémarre l’interface. WGTools crée une sauvegarde et restaure automatiquement en cas d’échec.", + "settings.readonly_mode": "Gestion des clients activée", + "settings.refresh_help": "Fréquence de mise à jour des données d’état. De 2 à 60 secondes.", + "settings.refresh_interval": "Intervalle d'actualisation", + "settings.release_notes": "Notes de version", + "settings.reload_config": "Recharger depuis le disque", + "settings.save_apply": "Enregistrer et appliquer", + "settings.saved": "Paramètres enregistrés.", + "settings.saved_reload": "Paramètres enregistrés. Rechargement…", + "settings.saving": "Enregistrement des paramètres…", + "settings.status": "Actualisation de l’état", + "settings.status_help": "Fréquence d’actualisation du tableau de bord et des pairs.", + "settings.subtitle": "Préférences de l’interface et paramètres d’état WGTools.", + "settings.syntax_hint": "Sections, clés, valeurs et commentaires WireGuard sont colorés pendant l’édition.", + "settings.tab_about": "À propos", + "settings.tab_backups": "Sauvegardes", + "settings.tab_general": "Général", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Utilisateurs", + "settings.tabs_aria": "Sections des paramètres", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "ID utilisateur Telegram autorisés", + "settings.telegram_allowed_ids_help": "Un ID numérique par ligne. Un message /start non autorisé renverra l’ID Telegram de l’expéditeur, pour l’ajouter ici.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connecté", + "settings.telegram_disabled": "Désactivé", + "settings.telegram_dns": "DNS client par défaut", + "settings.telegram_dns_help": "Adresses DNS IPv4 facultatives séparées par des virgules. Utilisées pour les clients créés par le bot.", + "settings.telegram_enabled": "Activer le bot Telegram", + "settings.telegram_endpoint": "Adresse / domaine serveur par défaut", + "settings.telegram_endpoint_help": "Utilisée par le bot pour créer une configuration client. Saisissez seulement IP ou domaine ; le port WireGuard vient de la configuration serveur.", + "settings.telegram_language": "Langue du bot", + "settings.telegram_language_auto": "Auto (langue Telegram)", + "settings.telegram_last_poll": "Dernier contact Telegram", + "settings.telegram_not_configured": "Non configuré", + "settings.telegram_remove_token": "Supprimer le jeton", + "settings.telegram_remove_token_confirm": "Supprimer le jeton Telegram enregistré et désactiver le bot ?", + "settings.telegram_save": "Enregistrer les paramètres Telegram", + "settings.telegram_saved": "Paramètres Telegram enregistrés.", + "settings.telegram_setup_note": "Créez un bot avec @BotFather, enregistrez son jeton, activez-le et envoyez /start. Si votre ID n’est pas autorisé, WGTools l’affichera : ajoutez-le à la liste.", + "settings.telegram_status": "Statut du bot", + "settings.telegram_subtitle": "Gestion WireGuard à distance via Telegram : état serveur, clients, création/suppression et démarrage/redémarrage/arrêt.", + "settings.telegram_test": "Tester la connexion", + "settings.telegram_test_ok": "Connexion Telegram opérationnelle : @{username}", + "settings.telegram_test_recent_ok": "Le bot Telegram fonctionne. Le test direct a expiré, mais le bot a contacté Telegram récemment.", + "settings.telegram_token": "Jeton du bot", + "settings.telegram_token_help": "Créez un bot avec @BotFather et collez son jeton API ici. Aucun API ID ni API Hash n’est nécessaire pour l’API Bot.", + "settings.telegram_token_keep": "Laissez vide pour conserver le jeton actuel.", + "settings.telegram_waiting": "Configuré, en attente du service bot", + "settings.theme": "Thème", + "settings.theme_dark": "Sombre", + "settings.theme_light": "Clair", + "settings.theme_system": "Système", + "settings.title": "Paramètres", + "settings.update_available": "Mise à jour disponible", + "settings.update_backup_queued": "Mise à jour en attente. WGTools créera une sauvegarde complète avant installation…", + "settings.update_backup_running": "Création de la sauvegarde complète avant mise à jour…", + "settings.update_check_failed": "Impossible de vérifier les mises à jour", + "settings.update_checking": "Vérification de la dernière version publiée sur GitHub…", + "settings.update_confirm": "Mettre WGTools à jour de v{current} vers v{latest} ? Une sauvegarde complète et une copie pour retour arrière seront créées. L’interface web redémarrera brièvement.", + "settings.update_current": "À jour", + "settings.update_downloading": "Téléchargement et validation de la version GitHub…", + "settings.update_failed": "Échec de la mise à jour WGTools.", + "settings.update_installing": "Installation de la mise à jour. L’interface web peut être brièvement indisponible…", + "settings.update_no_update": "WGTools est déjà à jour.", + "settings.update_not_checked": "Non vérifié", + "settings.update_queued": "Mise à jour en attente du service de mise à jour…", + "settings.update_rollback_ok": "L’application WGTools précédente a été restaurée automatiquement.", + "settings.update_rolling_back": "Échec de la mise à jour. Restauration de la version précédente…", + "settings.update_running": "Création des sauvegardes de sécurité…", + "settings.update_safety_hint": "Les mises à jour nécessitent votre accord. WGTools crée une sauvegarde complète et une copie de retour arrière avant installation. En cas d’échec, l’ancienne application est restaurée automatiquement. WireGuard n’est pas redémarré, sauf si la nouvelle version modifie explicitement sa configuration.", + "settings.update_sidebar": "Nouvelle version disponible", + "settings.update_sidebar_hint": "Paramètres → À propos", + "settings.update_starting": "Démarrage de la mise à jour…", + "settings.update_status_unknown": "État de la mise à jour indisponible. Nouvelle tentative…", + "settings.update_subtitle": "Informations du projet, vérification automatique des versions et mises à jour sécurisées depuis GitHub Releases.", + "settings.update_success": "WGTools mis à jour vers v{version}. Rechargement…", + "settings.update_wgtools": "Mettre à jour WGTools", + "settings.user_actions": "Actions", + "settings.user_created": "Créé", + "settings.user_created_ok": "Utilisateur créé.", + "settings.user_deleted": "Utilisateur supprimé.", + "settings.user_equal_rights": "Tous les utilisateurs WGTools disposent des mêmes autorisations.", + "settings.user_last_login": "Dernière connexion", + "settings.user_name": "Nom d’utilisateur", + "settings.users": "Utilisateurs", + "settings.users_subtitle": "Comptes locaux WGTools. L’e-mail est facultatif et sert uniquement à récupérer le mot de passe lorsque la messagerie est activée.", + "vps.add": "Ajouter un VPS", + "vps.add_help": "WGTools utilise SSH pour vérifier ou installer le relais. Les mots de passe et clés SSH privées ne sont jamais stockés.", + "vps.add_title": "Ajouter un VPS", + "vps.agent": "Agent relais", + "vps.agent_found": "Déjà installé", + "vps.agent_will_install": "Sera installé", + "vps.arch": "Architecture", + "vps.auth_method": "Authentification", + "vps.authentication": "Authentification SSH", + "vps.check": "Vérifier le VPS", + "vps.check_failed": "Échec de la vérification VPS", + "vps.check_link": "Vérifier la liaison", + "vps.check_ok": "VPS compatible", + "vps.checking": "Vérification SSH et compatibilité VPS…", + "vps.connections": "connexions", + "vps.credentials_not_saved": "Utilisés uniquement pour ce contrôle, sans stockage par WGTools.", + "vps.delete_candidate": "Retirer", + "vps.delete_installed": "Retirer le VPS", + "vps.delete_installed_confirm": "Retirer « {name} » de WGTools ? Le transport local sera déconnecté, mais l’agent Relay et son espace sur le VPS seront conservés. Vous pourrez ajouter ce VPS à nouveau pour réutiliser le même relais. Les clients ne pourront pas s’y connecter avant reconnexion.", + "vps.delete_installed_failed": "Impossible de retirer le VPS de WGTools", + "vps.delete_installed_ok": "VPS retiré de WGTools. Le relais distant est conservé et peut être reconnecté.", + "vps.empty_help": "Ajoutez un VPS Debian ou Ubuntu pour vérifier SSH, la compatibilité du système et les ports UDP nécessaires.", + "vps.empty_title": "Aucun VPS configuré", + "vps.endpoint": "Endpoint public", + "vps.endpoint_domain": "Domaine (recommandé)", + "vps.endpoint_domain_hint": "Si vous remplacez le VPS principal, changer le DNS peut éviter de modifier les configurations client.", + "vps.health_failed": "Échec de la vérification du relais", + "vps.host": "IP / nom d’hôte", + "vps.host_key": "Clé de l’hôte SSH", + "vps.identity": "Connexion VPS", + "vps.install_failed": "Échec de l’installation du relais", + "vps.install_ok": "Relais installé et liaison d’administration sécurisée vérifiée", + "vps.install_relay": "Installer le relais", + "vps.install_title": "Installer le relais VPS", + "vps.installed": "Installé", + "vps.installing": "Installation de l’agent Relay et établissement du tunnel sécurisé…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Phrase secrète de la clé", + "vps.link_ok": "Liaison Relay OK", + "vps.multi_tenant_note": "Un agent Relay WGTools fonctionne déjà sur ce VPS. Il ne sera pas remplacé : ce WGTools recevra une connexion isolée avec ses propres clés et ports UDP.", + "vps.name": "Nom", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Sera installé", + "vps.os": "Système d’exploitation", + "vps.password": "Mot de passe", + "vps.phase_note": "L’agent Relay accepte plusieurs contrôleurs WGTools indépendants sur un VPS. Chaque contrôleur dispose d’une connexion, de clés et ports UDP isolés ; les connexions existantes restent intactes.", + "vps.port_pair": "Ports UDP", + "vps.ports_adjusted": "ports libres sélectionnés", + "vps.private_key": "Clé privée", + "vps.privilege": "Privilèges", + "vps.public_endpoint": "Futur endpoint public", + "vps.ready_help": "Les identifiants SSH servent uniquement à vérifier la compatibilité et installer immédiatement le relais ; ils ne sont pas enregistrés.", + "vps.reconnect_note": "Une connexion Relay de ce WGTools existe déjà sur le VPS. WGTools reconnectera le même espace sans créer de nouveau tenant ni de ports UDP.", + "vps.reconnect_ok": "Relais existant reconnecté avec succès", + "vps.reconnect_relay": "Reconnecter le relais", + "vps.relay_port": "Port UDP du relais", + "vps.remove_confirm": "Retirer ce candidat VPS ? Aucune modification distante n’a été effectuée.", + "vps.save_candidate": "Enregistrer le candidat", + "vps.saved": "Candidat VPS enregistré", + "vps.ssh": "SSH", + "vps.ssh_key": "Clé SSH", + "vps.ssh_port": "Port SSH", + "vps.ssh_user": "Utilisateur SSH", + "vps.status_candidate": "Prêt à installer", + "vps.status_installed": "Relais connecté", + "vps.subtitle": "Préparez un VPS public pour l’accès distant lorsque ce serveur WGTools ne possède pas d’IP publique.", + "vps.tenant": "Connexion", + "vps.title": "Relais VPS", + "vps.transport_port": "Port UDP de transport", + "vps.transport_port_hint": "Port UDP distinct pour le tunnel de transport privé domicile ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Enregistré", + "vps.active_short": "Actif", + "dashboard.traffic_reset": "Réinitialiser", + "dashboard.traffic_reset_confirm": "Réinitialiser les compteurs de trafic WireGuard de cette interface ? Les compteurs des clients repartiront aussi de zéro.", + "dashboard.traffic_reset_done": "Compteurs de trafic réinitialisés", + "dashboard.traffic_reset_failed": "Impossible de réinitialiser les compteurs", + "audit.action.traffic.reset": "Compteurs de trafic réinitialisés", + "audit.result.reset": "réinitialisé", + "server.mtu": "MTU", + "server.mtu_auto": "Auto", + "server.mtu_hint": "Facultatif. Laissez vide pour le MTU automatique de wg-quick. Définissez 1380 ou 1420 uniquement si nécessaire pour LTE ou PPPoE.", + "clients.peer_isolation": "Isolation des clients VPN", + "clients.peer_isolation_enable": "Isoler des autres clients VPN", + "clients.peer_isolation_hint": "Bloque le trafic entre ce client et les autres adresses du pool WireGuard. Les autres politiques régissent toujours l’accès au serveur, à Internet et aux réseaux locaux ou Site-to-site.", + "clients.credentials_rotate": "Clés du client", + "clients.credentials_rotate_button": "Renouveler les clés", + "clients.credentials_rotate_confirm": "Générer de nouvelles clés pour ce client ? Si connecté, sa session WireGuard sera immédiatement interrompue. Envoyez ensuite une nouvelle configuration ou un QR.", + "clients.credentials_rotate_confirm_psk": "Générer une nouvelle paire de clés et un PSK pour ce client ? Sa session WireGuard active sera interrompue immédiatement. Envoyez ensuite une nouvelle configuration ou un QR.", + "clients.credentials_rotate_hint": "Renouvelle PrivateKey/PublicKey et, si activé, le PSK. L’adresse, les routes, le groupe, l’horaire, l’isolation et les statistiques sont conservés.", + "clients.credentials_rotating": "Génération de nouvelles clés et fermeture de l’ancienne session…", + "clients.credentials_rotated": "Clés du client modifiées. Si connecté, son ancienne session a été interrompue. L’ancienne configuration ne fonctionne plus ; envoyez une nouvelle configuration ou un QR.", + "clients.credentials_rotated_short": "Clés modifiées — nouvelle configuration requise", + "audit.action.client.credentials_rotated": "Clés du client renouvelées", + "clients.credentials_connection_lost": "Connexion à WGTools interrompue. Si ce panneau utilisait le client dont les clés viennent de changer, c’est normal : son ancienne session WireGuard est coupée. Reconnectez-vous par un autre chemin et générez une nouvelle configuration ou un QR.", + "nav.navigation": "Navigation principale", + "nav.project_github": "WGTools sur GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Facultatif pour l’instant. Utilisable pour récupérer le mot de passe une fois la messagerie configurée.", + "auth.forgot_password": "Mot de passe oublié ?", + "auth.reset_title": "Réinitialiser le mot de passe", + "auth.reset_subtitle": "Recevez un code unique par e-mail et définissez un nouveau mot de passe WGTools.", + "auth.reset_identifier": "Nom d’utilisateur ou e-mail", + "auth.reset_identifier_help": "Pour préserver la confidentialité, WGTools affiche toujours la même réponse, que le compte existe ou non.", + "auth.send_reset_code": "Envoyer le code", + "auth.reset_code_sent_generic": "Si le compte existe et possède une adresse e-mail, un code a été envoyé. Il reste valable 15 minutes.", + "auth.reset_code": "Code à 6 chiffres", + "auth.set_new_password": "Définir un nouveau mot de passe", + "auth.request_another_code": "Demander un autre code", + "auth.back_to_login": "Retour à la connexion", + "auth.reset_not_configured": "La récupération du mot de passe par e-mail n’est pas configurée. Contactez l’administrateur WGTools.", + "settings.tab_mail": "Messagerie", + "settings.mail": "Messagerie / SMTP", + "settings.mail_subtitle": "SMTP sert à récupérer les mots de passe.", + "settings.mail_not_configured": "Non configuré", + "settings.mail_enabled": "Activer la messagerie et la récupération de mot de passe", + "settings.mail_smtp_host": "Serveur SMTP", + "settings.mail_smtp_port": "Port SMTP", + "settings.mail_security": "Chiffrement", + "settings.mail_security_none": "Sans chiffrement", + "settings.mail_username": "Nom d’utilisateur SMTP", + "settings.mail_username_help": "Utilisé pour l’authentification SMTP et comme adresse d’expéditeur.", + "settings.mail_password": "Mot de passe SMTP", + "settings.mail_password_keep": "Laissez vide pour conserver le mot de passe enregistré.", + "settings.mail_from_email": "E-mail expéditeur", + "settings.mail_from_name": "Nom de l’expéditeur", + "settings.mail_test_recipient": "Destinataire du test", + "settings.mail_test_recipient_help": "Le test utilise les paramètres SMTP actuellement enregistrés.", + "settings.mail_remove_password": "Supprimer le mot de passe", + "settings.mail_test": "Envoyer un test", + "settings.mail_save": "Enregistrer les paramètres mail", + "settings.mail_enabled_badge": "Activé", + "settings.mail_disabled_badge": "Désactivé", + "settings.mail_saved": "Paramètres mail enregistrés.", + "settings.mail_remove_password_confirm": "Supprimer le mot de passe SMTP enregistré et désactiver la messagerie ?", + "settings.mail_password_removed": "Mot de passe SMTP supprimé et messagerie désactivée.", + "settings.mail_test_recipient_required": "Saisissez l’adresse e-mail du destinataire du test.", + "settings.mail_testing": "Envoi de l’e-mail de test…", + "settings.mail_test_ok": "E-mail de test envoyé.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Facultatif. Nécessaire uniquement pour récupérer soi-même le mot de passe.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail enregistré.", + "settings.send_password_reset": "Envoyer une réinitialisation", + "settings.user_reset_mail_not_configured": "Configurez et activez d’abord la messagerie.", + "settings.user_reset_email_missing": "Ajoutez d’abord une adresse e-mail.", + "settings.user_reset_confirm": "Envoyer un code de réinitialisation à {name} à l’adresse {email} ?", + "settings.user_reset_sent": "Code de réinitialisation envoyé à {email}.", + "audit.action.auth.password_reset_requested": "Réinitialisation du mot de passe demandée", + "audit.action.auth.password_reset_code_sent": "Code de réinitialisation envoyé", + "audit.action.auth.password_reset_completed": "Mot de passe réinitialisé", + "audit.action.auth.password_reset_failed": "Échec de la réinitialisation du mot de passe", + "audit.action.mail.settings_updated": "Paramètres de messagerie modifiés", + "audit.action.mail.test_sent": "E-mail de test envoyé", + "audit.action.mail.test_failed": "Échec de l’e-mail de test", + "audit.action.user.email_changed": "E-mail utilisateur modifié", + "audit.action.user.password_reset_sent": "Réinitialisation envoyée à l’utilisateur", + "audit.action.user.password_reset_failed": "Échec du reset du mot de passe utilisateur", + "audit.result.accepted": "accepté", + "audit.result.sent": "envoyé", + "audit.result.invalid_code": "code invalide", + "common.copy": "Copier", + "common.copied": "Copié", + "clients.use_panel_host": "Utiliser l’adresse du panneau", + "clients.use_panel_host_done": "Adresse du panneau insérée : {host}", + "clients.use_panel_host_failed": "Impossible de déterminer l’adresse du panneau depuis l’URL du navigateur.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS Let’s Encrypt intégré pour accéder directement à WGTools sans proxy inverse.", + "settings.https_disabled": "Désactivé", + "settings.https_enabled": "Activé", + "settings.https_enable": "Activer HTTPS intégré", + "settings.https_type": "Certificat pour", + "settings.https_domain": "Domaine", + "settings.https_public_ip": "IP publique", + "settings.https_target": "Domaine ou IP publique", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "Port HTTPS", + "settings.https_port80_note": "Le port TCP 80 doit être accessible depuis Internet pour émettre et renouveler le certificat. Ouvrez aussi le port HTTPS choisi pour le panneau.", + "settings.https_check_ports": "Vérifier les ports", + "settings.https_certificate": "Certificat", + "settings.https_certificate_ready": "Prêt", + "settings.https_certificate_missing": "Non émis", + "settings.https_expires": "Valable jusqu’au", + "settings.https_renewal": "Renouvellement automatique", + "settings.https_renewal_enabled": "Activé", + "settings.https_renewal_disabled": "Désactivé", + "settings.https_certificate_path": "Certificat", + "settings.https_private_key_path": "Clé privée", + "settings.https_issue": "Obtenir / renouveler le certificat", + "settings.https_port_free": "Libre", + "settings.https_port_busy": "Occupé", + "settings.https_ports_checked": "Vérification des ports terminée.", + "settings.https_target_email_required": "Saisissez le domaine ou l’IP publique et l’e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Demander ou renouveler le certificat Let’s Encrypt pour {target} ? Les paramètres HTTPS seront enregistrés. Le port TCP 80 doit être accessible depuis Internet.", + "settings.https_issuing": "Demande de certificat auprès de Let’s Encrypt…", + "settings.https_issue_ok": "Certificat prêt.", + "settings.https_already_enabled": "HTTPS intégré est déjà activé.", + "settings.https_already_disabled": "HTTPS intégré est déjà désactivé.", + "settings.https_enable_confirm": "Activer HTTPS intégré sur TCP {port} avec le chemin {path} ? WGTools redémarrera et la page se reconnectera à la nouvelle adresse.", + "settings.https_disable_confirm": "Désactiver HTTPS intégré et revenir à HTTP ?", + "settings.https_switching": "Activation HTTPS et redémarrage de WGTools…", + "settings.https_switching_http": "Désactivation HTTPS et redémarrage de WGTools…", + "audit.action.https.certificate_issued": "Certificat HTTPS émis", + "audit.action.https.certificate_failed": "Échec de la demande de certificat HTTPS", + "audit.action.https.enabled": "HTTPS activé", + "audit.action.https.disabled": "HTTPS désactivé", + "audit.result.issued": "émis", + "audit.result.enabled": "activé", + "audit.result.disabled": "désactivé", + "settings.https_access_path": "Chemin d’accès au panneau", + "settings.https_access_path_help": "Choisissez votre propre chemin. Avec HTTPS intégré, les requêtes hors de ce chemin obtiennent une erreur 404.", + "settings.https_enable_fields_required": "Saisissez domaine/IP publique, e-mail Let’s Encrypt et chemin du panneau.", + "settings.https_use_panel_host": "Utiliser l’adresse du panneau", + "settings.https_reconnecting": "WGTools passe à la nouvelle adresse HTTPS…", + "server.tab_nodes": "Nœuds", + "common.type": "Type", + "common.status": "État", + "common.copy_failed": "Copie impossible", + "clients.vpn_address": "Adresse VPN", + "nodes.title": "Nœuds WGTools", + "nodes.subtitle": "Reliez plusieurs serveurs WGTools dans un réseau protégé et publiez uniquement les réseaux accessibles aux autres nœuds.", + "nodes.enable_hub": "Activer le HUB", + "nodes.connect_hub": "Se connecter au HUB", + "nodes.settings": "Paramètres des nœuds", + "nodes.settings_action": "Paramètres", + "nodes.sync_now": "Synchroniser", + "nodes.disable": "Désactiver les nœuds", + "nodes.disable_action": "Déconnecter", + "nodes.join_title": "Connecter de nouveaux nœuds", + "nodes.join_help": "Créez un code à usage unique et saisissez-le sur un autre panneau WGTools avec l’endpoint du HUB, par ex. vpn.example.com:51950. Le code est valable 15 minutes et une seule fois.", + "nodes.create_code": "Créer un code", + "nodes.connected_nodes": "Nœuds connectés", + "nodes.connected_nodes_help": "Informations sur les autres panneaux, réseaux publiés et clients. Les clients distants sont en lecture seule.", + "nodes.enable_hub_help": "Ce panneau devient le nœud central. Le même port accueille WireGuard en UDP et l’appairage initial sécurisé en TCP.", + "nodes.node_name": "Nom du nœud", + "nodes.transport_network": "Réseau de transport des nœuds", + "nodes.transport_help": "Réseau privé distinct réservé au transport entre WGTools. Il ne doit pas chevaucher vos réseaux VPN/LAN.", + "nodes.panel_url": "URL du panneau", + "nodes.panel_url_help": "Facultatif. Simple lien informatif du bouton « Ouvrir le panneau » sur les autres nœuds ; non utilisé pour la connexion Nodes.", + "nodes.extra_networks": "Réseaux de nœud supplémentaires", + "nodes.extra_networks_help": "Un réseau par ligne. Les réseaux VPN et les réseaux distants Site-to-site sont publiés automatiquement. Ajoutez seulement les autres LAN/réseaux routés, par ex. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools préremplit les réseaux VPN, Site-to-site et LAN routés détectés. Gardez uniquement les réseaux à publier. Un réseau par ligne.", + "nodes.published_networks_settings_help": "Un réseau par ligne. Liste explicite des réseaux publiés par ce nœud. Retirer une ligne cesse d’annoncer ce réseau aux autres nœuds.", + "nodes.available_networks_help": "Réseaux actuellement détectés : {networks}. Les nouveaux réseaux ne sont pas publiés automatiquement ; ajoutez ceux souhaités ci-dessus.", + "nodes.available_networks_none": "Aucun réseau local supplémentaire détecté.", + "nodes.connect_help": "Saisissez l’endpoint du HUB et le code à usage unique. L’URL, le port HTTPS, le certificat et le chemin privé du panneau ne servent pas à l’appairage.", + "nodes.join_code": "Code de connexion", + "nodes.connect_reachability_note": "L’appairage initial utilise TCP sécurisé sur le port indiqué. Une fois wgnode0 créé, réseaux, état, versions et données client en lecture seule se synchronisent avec le HUB via l’adresse WireGuard interne.", + "nodes.connect": "Connecter", + "nodes.settings_help": "Nom du nœud, lien « Ouvrir le panneau » facultatif et liste des réseaux publiés. L’URL du panneau n’est utilisée ni pour l’appairage ni pour la synchronisation.", + "nodes.details": "Détails", + "nodes.not_configured": "WGTools Nodes non configuré", + "nodes.not_configured_help": "Activez le HUB sur ce panneau ou connectez-le à un HUB WGTools existant.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connecté au HUB", + "nodes.mode_none": "Non configuré", + "nodes.role": "Rôle", + "nodes.tunnel": "Tunnel du nœud", + "nodes.node_ip": "Adresse du nœud", + "nodes.endpoint": "Endpoint du HUB", + "nodes.published_networks": "Réseaux publiés", + "nodes.last_sync": "Dernière synchronisation", + "nodes.no_nodes_hub": "Aucun nœud connecté. Créez un code et utilisez-le sur un autre panneau WGTools.", + "nodes.no_nodes_spoke": "Aucune information reçue sur les nœuds distants.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Ouvrir le panneau", + "nodes.route_conflict": "Conflit de routage", + "nodes.no_published_networks": "Aucun réseau publié", + "nodes.load_failed": "Impossible de charger WGTools Nodes", + "nodes.enable_hub_confirm": "Activer le HUB WGTools et créer le tunnel WireGuard interne ?", + "nodes.applying": "Configuration du tunnel WGTools Nodes…", + "nodes.enable_failed": "Impossible d’activer le HUB", + "nodes.hub_enabled": "HUB WGTools activé", + "nodes.connecting": "Vérification du code HUB et création du tunnel sécurisé…", + "nodes.connect_failed": "Impossible de se connecter au HUB", + "nodes.connected": "Connecté au HUB WGTools", + "nodes.settings_failed": "Impossible d’enregistrer les paramètres du nœud", + "nodes.settings_saved": "Paramètres du nœud enregistrés", + "nodes.code_failed": "Impossible de créer le code de connexion", + "nodes.code_expires": "Code à usage unique. Valable jusqu’à {time}.", + "nodes.code_copied": "Code de connexion copié", + "nodes.network_vpn": "Clients VPN", + "nodes.network_site_to_site": "Réseau Site-to-site", + "nodes.network_custom": "Réseau supplémentaire", + "nodes.conflict": "Conflit", + "nodes.remote_clients": "Clients (lecture seule)", + "nodes.no_clients": "Aucun client signalé par ce nœud", + "nodes.details_failed": "Impossible de charger les détails du nœud", + "nodes.remove_confirm": "Retirer le nœud « {name} » du HUB ? Son accès au tunnel interne sera révoqué.", + "nodes.remove_failed": "Impossible de retirer le nœud", + "nodes.removed": "Nœud retiré", + "nodes.disable_hub_confirm": "Désactiver le HUB et déconnecter tous les nœuds WGTools ? Le tunnel interne sera supprimé.", + "nodes.disconnect_confirm": "Déconnecter ce panneau WGTools du HUB et supprimer le tunnel interne ?", + "nodes.disable_failed": "Impossible de désactiver WGTools Nodes", + "nodes.disabled": "WGTools Nodes désactivé", + "nodes.sync_failed": "Échec de synchronisation des nœuds", + "nodes.synced": "Informations des nœuds synchronisées", + "nodes.service_port": "Port Nodes", + "nodes.service_port_help": "Le même numéro de port sert simultanément à WireGuard en UDP et à l’appairage initial protégé en TCP.", + "nodes.hub_port_forward_note": "Si le HUB est derrière un NAT, redirigez le même port en UDP et TCP vers lui. Le port web WGTools, HTTPS et le chemin privé sont indépendants de Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Domaine/IP et port Nodes sans http:// ni https://, par ex. vpn.example.com:51950.", + "settings.collapse_sidebar": "Réduire la barre latérale", + "settings.expand_sidebar": "Développer la barre latérale", + "settings.https_issue_fields_required": "Saisissez domaine/IP publique, e-mail Let’s Encrypt et chemin du panneau.", + "settings.https_issue_ok_saved": "Certificat prêt et paramètres HTTPS enregistrés.", + "settings.https_enable_need_certificate": "Obtenez d’abord un certificat.", + "settings.https_enable_certificate_mismatch": "Obtenez d’abord un certificat pour le domaine ou l’IP actuel.", + "settings.https_enable_certificate_expired": "Certificat expiré. Renouvelez-le avant d’activer HTTPS.", + "settings.https_enable_certificate_ready": "Certificat prêt : HTTPS intégré peut être activé.", + "settings.https_enable_active_help": "Décochez puis enregistrez pour revenir à HTTP.", + "settings.https_certificate_expired": "Expiré", + "settings.https_certificate_wrong_target": "Pour une autre adresse", + "nodes.network_conflict_error": "Les réseaux publiés chevauchent un autre nœud ou le réseau de transport Nodes : {conflicts}. Supprimez ou modifiez le réseau concerné.", + "nodes.networks_changed": "Les réseaux détectés ont changé depuis l’enregistrement. Nouveaux : {added}. Plus détectés : {removed}. Vérifiez puis enregistrez la liste publiée.", + "nodes.review_networks": "Vérifier les réseaux", + "nodes.vpn_pool_mismatch": "Pool VPN modifié : Nodes publie encore {old}, alors que le pool actuel est {current}. Ouvrez les paramètres et mettez à jour les réseaux publiés.", + "server.error_vpn_network_invalid": "Le réseau VPN doit être une adresse réseau IPv4 valide, par ex. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Seuls les réseaux VPN IPv4 sont pris en charge.", + "server.error_vpn_network_too_small": "Le réseau VPN doit contenir au moins deux adresses utilisables.", + "server.error_vpn_network_no_hosts": "Le réseau VPN choisi n’a aucune adresse serveur utilisable.", + "server.error_server_address_prefix": "L’adresse VPN du serveur doit inclure un préfixe, par ex. 10.0.0.1/24.", + "server.error_server_address_network": "L’adresse VPN du serveur doit appartenir au pool choisi et utiliser le même préfixe.", + "server.error_server_address_reserved": "L’adresse VPN du serveur ne peut être celle du réseau ni celle de diffusion.", + "server.error_listen_port_number": "Le port WireGuard doit être un nombre.", + "server.error_listen_port_range": "Le port WireGuard doit être compris entre 1 et 65535.", + "server.error_mtu_number": "Le MTU doit être un nombre.", + "auth.mfa_title": "Authentification à deux facteurs", + "auth.mfa_login_help": "Saisissez le code à 6 chiffres de Google Authenticator ou un code de récupération.", + "auth.mfa_code": "Code d’authentification", + "auth.mfa_verify": "Vérifier et se connecter", + "auth.mfa_back": "Retour au mot de passe", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Authentification à deux facteurs (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Activé", + "settings.mfa_disabled": "Désactivé", + "settings.mfa_google_help": "Protégez ce compte avec Google Authenticator ou une application TOTP. Votre mot de passe actuel est requis pour commencer.", + "settings.current_password": "Mot de passe actuel", + "settings.mfa_start": "Configurer Google Authenticator", + "settings.mfa_secret": "Clé de configuration manuelle", + "settings.mfa_scan_help": "Scannez le QR avec Google Authenticator puis saisissez le code actuel à 6 chiffres pour activer MFA.", + "settings.mfa_code": "Code à 6 chiffres", + "settings.mfa_enable": "Activer MFA", + "settings.mfa_manage_help": "Pour modifier MFA, saisissez le mot de passe actuel et un code Authenticator ou de récupération.", + "settings.mfa_code_or_recovery": "Code Authenticator ou de récupération", + "settings.mfa_regenerate": "Nouveaux codes de récupération", + "settings.mfa_disable": "Désactiver MFA", + "settings.mfa_recovery_title": "Codes de récupération", + "settings.mfa_recovery_help": "Enregistrez ces codes maintenant. Chacun sert une seule fois si Google Authenticator est indisponible. Ils ne seront plus affichés.", + "settings.mfa_recovery_remaining": "Codes de récupération restants : {count}", + "settings.mfa_enabled_ok": "MFA activée.", + "settings.mfa_disabled_ok": "MFA désactivée.", + "settings.mfa_disable_confirm": "Désactiver l’authentification à deux facteurs pour ce compte ?", + "settings.mfa_regenerate_confirm": "Remplacer tous les codes de récupération existants ?", + "settings.mfa_recovery_regenerated": "Nouveaux codes de récupération générés.", + "audit.action.auth.mfa_failed": "Échec de la vérification MFA", + "audit.action.auth.mfa_recovery_used": "Code de récupération MFA utilisé", + "audit.action.user.mfa_setup_started": "Configuration MFA démarrée", + "audit.action.user.mfa_enabled": "MFA activée", + "audit.action.user.mfa_disabled": "MFA désactivée", + "audit.action.user.mfa_disabled_cli": "MFA désactivée via CLI", + "audit.action.user.mfa_recovery_regenerated": "Codes de récupération MFA régénérés", + "settings.mfa_error_password": "Mot de passe actuel incorrect.", + "settings.mfa_error_code": "Code d’authentification invalide.", + "settings.mfa_error_already_enabled": "MFA est déjà activée.", + "settings.mfa_error_not_enabled": "MFA n’est pas activée.", + "settings.mfa_error_not_started": "Recommencez la configuration MFA.", + "trace.title": "Traceroute, ping et carte de l’itinéraire", + "trace.subtitle": "Mesurez la latence vers un VPS ou un autre serveur et repérez les retards sur le trajet.", + "trace.target": "IP ou nom d’hôte du serveur", + "trace.show_map": "Afficher le trajet sur la carte", + "trace.run": "Lancer le traceroute", + "trace.geo_note": "La géolocalisation est approximative. Si la carte est activée, les IP publiques des sauts sont envoyées à ipwho.is ; les tuiles proviennent d’OpenStreetMap.", + "trace.latency_note": "Traceroute mesure la latence en millisecondes, pas le débit en Mbit/s.", + "trace.map": "Carte de l’itinéraire", + "trace.map_hint": "Carte interactive : faites glisser, zoomez avec la molette ou +/− et cliquez sur un saut pour plus de détails.", + "trace.hop": "Saut / IP", + "trace.location": "Emplacement", + "trace.avg_rtt": "RTT moyen", + "trace.delta": "Δ RTT", + "trace.loss": "Perte", + "trace.summary_target": "Cible", + "trace.summary_ping": "Ping moyen", + "trace.summary_loss": "Perte de ping", + "trace.summary_hops": "Sauts", + "trace.no_reply": "Aucune réponse", + "trace.private": "Réseau privé", + "trace.unknown": "Inconnu", + "trace.running": "Ping et traceroute en cours… Cela peut prendre une minute.", + "trace.done": "Analyse du réseau terminée.", + "trace.failed": "Échec de l’analyse du réseau", + "trace.partial_geo": "Certains sauts publics n’ont pas pu être géolocalisés.", + "trace.not_reached": "La cible n’a pas été atteinte par traceroute.", + "trace.reached": "Cible atteinte", + "trace.ms": "ms", + "server.tab_trace": "Traçage", + "trace.map_controls": "Commandes de carte", + "trace.zoom_in": "Zoom avant", + "trace.zoom_out": "Zoom arrière", + "trace.fit_route": "Afficher tout le trajet", + "trace.fit": "Ajuster", + "trace.map_click_hint": "Cliquez sur un saut pour consulter l’IP, l’emplacement, l’ASN et le RTT.", + "trace.route_path": "Trajet", + "trace.ping_ok_trace_filtered": "La cible répond au ping, mais les derniers sauts traceroute ne répondent pas.", + "trace.latency_legend": "Augmentation de la latence entre sauts répondants", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — accru", + "trace.latency_bad": "Δ RTT > 20 ms — forte hausse" +} diff --git a/app/locales/it.json b/app/locales/it.json new file mode 100644 index 0000000..885d3f8 --- /dev/null +++ b/app/locales/it.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Crea utente", + "auth.login_subtitle": "Inserisci nome utente e password WGTools.", + "auth.login_title": "Accedi a WGTools", + "auth.password": "Password", + "auth.password_repeat": "Ripeti la password", + "auth.setup_help": "Il primo account ha accesso completo a WGTools. Puoi creare altri utenti in seguito nelle impostazioni.", + "auth.setup_subtitle": "Per gestire il server è necessario prima creare un account WGTools.", + "auth.setup_title": "Crea il primo utente", + "auth.sign_in": "Accedi", + "auth.sign_out": "Esci", + "auth.username": "Nome utente", + "clients.actions": "Azioni", + "clients.add": "+ Aggiungi client", + "clients.address": "Indirizzo VPN", + "clients.address_hint": "Il primo indirizzo libero viene suggerito automaticamente.", + "clients.allowed_ips_required": "Inserisci almeno una rete AllowedIPs per la configurazione client.", + "clients.basic_connection": "Impostazioni connessione", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs nella configurazione client", + "clients.config_private_warning": "Questa configurazione contiene la chiave privata del client. Conservala al sicuro.", + "clients.config_title": "Configurazione client", + "clients.config_unavailable": "Configurazione non disponibile", + "clients.connection_direct": "Direttamente a WGTools", + "clients.connection_path": "Percorso di connessione", + "clients.connection_relay": "Relay VPS", + "clients.connection_via": "Connetti tramite", + "clients.connection_via_hint": "Scegli l’accesso pubblico usato dal client. Il Relay appare solo se installato per l’interfaccia WireGuard scelta.", + "clients.copy_config": "Copia", + "clients.copy_done": "Configurazione copiata", + "clients.create_subtitle": "Crea un peer WireGuard e genera la configurazione client.", + "clients.create_title": "Crea client", + "clients.creating": "Creazione chiavi e applicazione client…", + "clients.day_fri": "Ven", + "clients.day_mon": "Lun", + "clients.day_sat": "Sab", + "clients.day_sun": "Dom", + "clients.day_thu": "Gio", + "clients.day_tue": "Mar", + "clients.day_wed": "Mer", + "clients.delete_confirm": "Eliminare questo client da WireGuard? WGTools creerà un backup e rimuoverà le regole automatiche associate.", + "clients.deleted": "Client eliminato", + "clients.dns": "DNS (facoltativo)", + "clients.dns_hint": "Server DNS IPv4 separati da virgole.", + "clients.download_config": "Scarica .conf", + "clients.duplicate": "Duplica", + "clients.duplicate_address_error": "Questo indirizzo VPN è già usato da un altro peer.", + "clients.duplicate_name_error": "Esiste già un peer con questo nome.", + "clients.duplicate_ready": "Copia pronta. WGTools ha assegnato un nuovo nome e indirizzo VPN. Controlla le impostazioni prima di salvare.", + "clients.duplicate_site_hint": "Le reti remote sono state rimosse per evitare route duplicate. Inserisci le reti del nuovo peer Site-to-site.", + "clients.duplicate_suffix": "copia", + "clients.edit_subtitle": "Aggiorna il peer sul server. Le modifiche vengono applicate senza riavviare WireGuard.", + "clients.edit_title": "Modifica client", + "clients.endpoint": "Endpoint server", + "clients.endpoint_hint": "Per i client remoti usa l’IP pubblico o dominio che inoltra la porta WireGuard a questo server.", + "clients.existing": "Peer esistente", + "clients.expiration": "Durata accesso", + "clients.expiration_action": "Alla scadenza", + "clients.expiration_action_hint": "Se deselezionato, il client resta in WGTools ma l’accesso WireGuard viene disabilitato. Scegli una nuova scadenza o Nessuna scadenza e salva per riattivarlo.", + "clients.expiration_datetime": "Scade il", + "clients.expiration_datetime_hint": "Usa data e ora locali di questo browser.", + "clients.expiration_delete": "Elimina client", + "clients.expiration_future_required": "Scegli una data e ora future.", + "clients.expiration_hint": "Alla scadenza WGTools esegue l’azione selezionata al minuto successivo. Prima crea un backup WireGuard.", + "clients.expire_1d": "1 giorno", + "clients.expire_1h": "1 ora", + "clients.expire_3h": "3 ore", + "clients.expire_6h": "6 ore", + "clients.expire_custom": "Data e ora personalizzate", + "clients.expire_never": "Nessuna scadenza", + "clients.expired": "Scaduto", + "clients.expired_disabled_hint": "L’accesso è scaduto. Il client è conservato, ma WireGuard è disabilitato. Scegli una nuova durata o Nessuna scadenza e salva.", + "clients.expired_disabled_short": "Scaduto · disabilitato", + "clients.expired_disabled_status": "Scaduto", + "clients.expires_days": "Scade tra {n} g", + "clients.expires_hours": "Scade tra {n} h", + "clients.expires_minutes": "Scade tra {n} min", + "clients.generated_config": "Configurazione client generata", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 secondi è un buon valore predefinito per client dietro NAT.", + "clients.local_access_exceptions": "Indirizzi locali consentiti", + "clients.local_access_exceptions_hint": "IP o CIDR facoltativi raggiungibili anche quando la rete locale o Site-to-site è bloccata. Separa con virgole.", + "clients.managed": "Gestito da WGTools", + "clients.name": "Nome", + "clients.no_peers": "Nessun peer trovato", + "clients.peers": "Peer", + "clients.peers_subtitle": "Le modifiche vengono salvate e applicate con wg syncconf senza riavviare l’interfaccia WireGuard.", + "clients.protected_networks_reference": "Reti locali bloccate (riferimento)", + "clients.protected_networks_reference_hint": "Queste reti non sono scritte in AllowedIPs. L’accesso è bloccato dai criteri server WGTools; puoi consentire singoli indirizzi sopra.", + "clients.psk": "Chiave precondivisa (PSK)", + "clients.psk_enable": "Usa una chiave WireGuard precondivisa aggiuntiva", + "clients.psk_hint": "Consigliato. Aggiunge un segreto simmetrico all’handshake WireGuard. I client standard lo supportano; WGTools inserisce il PSK nella configurazione e nel QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generazione QR…", + "clients.quick_search": "Ricerca rapida", + "clients.quick_search_clear": "Cancella ricerca", + "clients.quick_search_empty": "Nessun client corrispondente", + "clients.relay_endpoint_note": "La configurazione generata si connetterà a {endpoint}. Il server WireGuard resta su questo host WGTools.", + "clients.relay_required": "Scegli un Relay VPS per questo client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "non disponibile", + "clients.relay_vps": "Relay VPS", + "clients.relay_vps_hint": "L’endpoint del client viene generato automaticamente da questo Relay.", + "clients.remote_hint": "Reti dietro questo peer. Una per riga o separate da virgole.", + "clients.remote_networks": "Reti remote", + "clients.remote_required": "Inserisci almeno una rete remota per il peer Site-to-site.", + "clients.required": "Nome e indirizzo VPN sono obbligatori.", + "clients.route_custom": "Personalizzato", + "clients.route_full": "Tunnel completo", + "clients.route_full_except_local": "Tunnel completo eccetto reti locali", + "clients.route_hint": "Solo queste reti vengono inserite in AllowedIPs della configurazione client.", + "clients.route_preset": "Traffico tramite VPN", + "clients.route_vpn": "Solo rete VPN", + "clients.route_vpn_lan": "VPN + LAN locale", + "clients.saved": "Client salvato", + "clients.schedule_blocked_short": "Pianificazione · bloccato", + "clients.schedule_blocked_status": "Bloccato dalla pianificazione", + "clients.schedule_days": "Giorni consentiti", + "clients.schedule_days_required": "Scegli almeno un giorno per la pianificazione.", + "clients.schedule_disabled_hint": "Questo client è bloccato dalla pianificazione. WGTools ripristinerà automaticamente il peer al prossimo intervallo consentito.", + "clients.schedule_enable": "Limita accesso con pianificazione", + "clients.schedule_from": "Accesso dalle", + "clients.schedule_hint": "WGTools può disabilitare e riattivare il client nei giorni e orari scelti senza cambiarne la configurazione.", + "clients.schedule_short": "Pianificazione", + "clients.schedule_time_required": "Imposta ora di inizio e fine della pianificazione.", + "clients.schedule_timezone_hint": "La pianificazione usa l’ora locale del server WireGuard. Sono supportati intervalli notturni come 22:00–06:00.", + "clients.schedule_title": "Pianificazione accesso", + "clients.schedule_to": "Accesso fino alle", + "clients.security_access": "Sicurezza e orari di accesso", + "clients.server_host": "Indirizzo / dominio server", + "clients.server_host_hint": "IP pubblico o dominio usato dal client. I valori inseriti in precedenza sono suggeriti.", + "clients.server_host_required": "L’indirizzo / dominio server è obbligatorio per generare la configurazione.", + "clients.server_peer": "Peer server", + "clients.server_port": "Porta WireGuard", + "clients.server_port_hint": "Preso automaticamente dalla configurazione server.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Stato", + "clients.subtitle": "Peer WireGuard, stato in tempo reale e gestione configurazioni client.", + "clients.tab_basic": "Base", + "clients.tab_config": "Configurazione", + "clients.tab_policy": "Criteri", + "clients.tab_security": "Sicurezza", + "clients.title": "Client", + "clients.type": "Tipo", + "clients.unmanaged_note": "Questo peer esisteva prima di WGTools. La sua chiave privata non può essere recuperata. WGTools può modificare il peer server ma non può generarne configurazione client o QR.", + "clients.updating": "Aggiornamento client…", + "common.actions": "Azioni", + "common.ago": "fa", + "common.cancel": "Annulla", + "common.checking": "Verifica…", + "common.close": "Chiudi", + "common.config": "Configurazione", + "common.delete": "Elimina", + "common.disabled": "Disabilitato", + "common.edit": "Modifica", + "common.enabled": "Abilitato", + "common.loading": "Caricamento…", + "common.never": "Mai", + "common.no": "No", + "common.not_configured": "Non configurato", + "common.not_installed": "Non installato", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Aggiorna", + "common.running": "In esecuzione", + "common.save": "Salva", + "common.stopped": "Arrestato", + "common.total": "Totale", + "common.unknown": "Sconosciuto", + "common.updated": "Aggiornato", + "common.yes": "Sì", + "dashboard.active_peers": "Peer attivi", + "dashboard.active_peers_subtitle": "Dati in tempo reale da wg show.", + "dashboard.activity": "Panoramica del sistema", + "dashboard.activity_subtitle": "Controlli in sola lettura sul sistema WireGuard attivo.", + "dashboard.cores": "core", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Ultime 24 ore", + "dashboard.history_avg": "Media", + "dashboard.history_max": "Max", + "dashboard.history_min": "Min", + "dashboard.history_now": "ora", + "dashboard.memory": "Memoria", + "dashboard.network": "Rete", + "dashboard.peers": "Peer", + "dashboard.quick_search": "Ricerca rapida", + "dashboard.quick_search_clear": "Cancella ricerca", + "dashboard.quick_search_empty": "Nessun peer corrisponde alla ricerca", + "dashboard.restart": "Riavvia", + "dashboard.restart_confirm": "Riavviare WireGuard? I client VPN attivi si riconnetteranno automaticamente.", + "dashboard.restart_ok": "WireGuard riavviato.", + "dashboard.routing": "Instradamento", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Avvia", + "dashboard.start_ok": "WireGuard avviato.", + "dashboard.stop": "Arresta", + "dashboard.stop_confirm": "Arrestare WireGuard? I client VPN attivi verranno disconnessi.", + "dashboard.stop_ok": "WireGuard arrestato.", + "dashboard.subtitle": "Stato del server WireGuard, peer e traffico in tempo reale.", + "dashboard.title": "Panoramica", + "dashboard.traffic": "Traffico", + "dashboard.uptime": "Tempo di attività", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Criteri di accesso al server", + "groups.additional_allowed": "Indirizzi consentiti aggiuntivi", + "groups.additional_blocked": "Indirizzi bloccati aggiuntivi", + "groups.allow": "Consenti", + "groups.allowed": "Consentito", + "groups.allowed_addresses": "Indirizzi / reti consentiti", + "groups.apply_current_template": "Applica modello corrente del gruppo", + "groups.apply_defaults": "Applica modello corrente del gruppo", + "groups.apply_defaults_hint": "Copia route, DNS e Keepalive del gruppo in questo client. Salva il client, poi genera una nuova configurazione o QR se necessario.", + "groups.basic": "Informazioni di base", + "groups.block": "Blocca", + "groups.blocked": "Bloccato", + "groups.blocked_addresses": "Indirizzi / reti bloccati", + "groups.client_config_source": "Origine configurazione client", + "groups.client_defaults": "Valori predefiniti client", + "groups.client_group_hint": "Gruppo facoltativo per riutilizzare criteri di accesso e valori predefiniti. I gruppi appartengono all’interfaccia WireGuard selezionata.", + "groups.config_differs": "La configurazione del client differisce dai valori del gruppo. I criteri server sono aggiornati, ma telefono o PC cambieranno solo dopo un nuovo file o QR.", + "groups.config_differs_short": "Configurazione client diversa dal gruppo", + "groups.create": "Crea gruppo", + "groups.create_title": "Crea gruppo", + "groups.created": "Gruppo creato", + "groups.creating": "Creazione gruppo…", + "groups.defaults_applied": "Modello del gruppo applicato. Salva il client per mantenere le modifiche.", + "groups.defaults_hint": "Definisce il traffico inviato dal client tramite WireGuard. I criteri server definiscono separatamente cosa può raggiungere. Le modifiche al modello non cambiano i file già installati.", + "groups.delete_message": "Eliminare “{name}”? Le configurazioni dei client non vengono mai eliminate insieme al gruppo.", + "groups.delete_move": "Sposta i client in un altro gruppo", + "groups.delete_title": "Elimina gruppo client", + "groups.delete_unassign": "Rimuovi assegnazione del gruppo dai client", + "groups.deleted": "Gruppo eliminato", + "groups.deleting": "Aggiornamento client ed eliminazione gruppo…", + "groups.description": "Descrizione", + "groups.edit_title": "Modifica gruppo", + "groups.editor_subtitle": "Un gruppo combina criteri di accesso server attivi e un modello per le configurazioni client.", + "groups.effective_allow": "Eccezioni consentite", + "groups.effective_deny": "Eccezioni bloccate", + "groups.effective_policy": "Criteri server effettivi", + "groups.empty": "Non ci sono gruppi client. Creane uno per riutilizzare criteri di accesso e valori predefiniti.", + "groups.group": "Gruppo", + "groups.inherit": "Eredita", + "groups.internet_access": "Accesso a Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Reti locali", + "groups.local_short": "Locale", + "groups.manage": "Gruppi", + "groups.members_count": "{count} client", + "groups.name": "Nome", + "groups.name_required": "Il nome del gruppo è obbligatorio.", + "groups.new_client_defaults": "Modello configurazione client", + "groups.new_clients_short": "Nuovi client", + "groups.no_group": "Nessun gruppo", + "groups.none": "Nessuno", + "groups.override_client_config": "Sovrascrivi il modello client del gruppo per questo client", + "groups.override_client_config_hint": "Disattivato: route, DNS e Keepalive dal gruppo. Attivato: il client usa valori propri. Le eccezioni dei criteri server restano indipendenti.", + "groups.policy_addresses_hint": "Indirizzi IPv4 o CIDR separati da virgole. Le eccezioni client hanno precedenza sulle eccezioni del gruppo.", + "groups.policy_custom": "Criteri personalizzati", + "groups.policy_inherit": "Usa criteri del gruppo", + "groups.policy_mode": "Origine criteri", + "groups.policy_mode_hint": "I criteri di gruppo si ereditano per impostazione predefinita. Le eccezioni client non modificano il gruppo.", + "groups.routes_required": "Le route client non possono essere vuote.", + "groups.subtitle": "Riutilizza criteri di accesso server e valori predefiniti per i client dell’interfaccia WireGuard selezionata.", + "groups.title": "Gruppi client", + "groups.traffic_through_vpn": "Traffico tramite VPN", + "groups.updated": "Gruppo aggiornato", + "groups.updating": "Aggiornamento criteri gruppo…", + "help.example_note": "Gli indirizzi, le interfacce, i nomi dei peer e i domini degli esempi sono fittizi. Sostituiscili con i dati della tua rete.", + "help.navigation": "Navigazione della guida", + "help.open": "Apri la guida", + "help.subtitle": "Guida semplice per Dashboard, Server, Client e Impostazioni con brevi esempi pratici.", + "help.title": "Guida WGTools", + "interfaces.add": "+ Aggiungi interfaccia", + "interfaces.create": "Crea interfaccia", + "interfaces.create_confirm": "Creare e avviare l’interfaccia {name}?", + "interfaces.create_failed": "Impossibile creare l’interfaccia", + "interfaces.create_hint": "Prima di creare la configurazione, WGTools verifica che rete VPN, porta UDP e tabella di routing non siano in conflitto con altre interfacce WireGuard.", + "interfaces.create_subtitle": "Crea un’interfaccia WireGuard indipendente con pool di indirizzi, porta UDP e impostazioni di routing propri.", + "interfaces.create_title": "Aggiungi interfaccia WireGuard", + "interfaces.created": "Interfaccia creata correttamente.", + "interfaces.creating": "Generazione chiavi, scrittura configurazione e avvio di WireGuard…", + "interfaces.current": "Attuale", + "interfaces.delete": "Elimina", + "interfaces.delete_confirm": "Eliminare l’interfaccia {name}? La configurazione WireGuard e tutti i peer saranno rimossi. Prima viene creato un backup.", + "interfaces.delete_failed": "Impossibile eliminare l’interfaccia", + "interfaces.delete_last": "Non puoi eliminare qui l’ultima interfaccia WireGuard configurata.", + "interfaces.delete_tooltip": "Elimina questa interfaccia WireGuard", + "interfaces.deleted": "Interfaccia eliminata. Backup: {backup}", + "interfaces.deleting": "Arresto WireGuard ed eliminazione interfaccia…", + "interfaces.display_name": "Nome visualizzato", + "interfaces.display_name_edit_hint": "Solo nome visualizzato: il nome dell’interfaccia Linux non cambia.", + "interfaces.display_name_hint": "Nome facoltativo, ad es. Lavoro o Collaboratori.", + "interfaces.identity": "Identità interfaccia", + "interfaces.none": "Nessuna interfaccia WireGuard trovata", + "interfaces.none_configured": "Nessuna interfaccia WireGuard configurata.", + "interfaces.peers_short": "peer", + "interfaces.rename_failed": "Impossibile salvare il nome visualizzato dell’interfaccia.", + "interfaces.select": "Seleziona", + "interfaces.subtitle": "Ogni interfaccia ha rete VPN, porta, peer e criteri propri. Selezionane una per gestirla in WGTools.", + "interfaces.switch_title": "Interfacce WireGuard", + "interfaces.system_name": "Nome di sistema", + "interfaces.system_name_hint": "Nome interfaccia Linux, ad es. wg1. Non modificabile dopo la creazione.", + "interfaces.title": "Interfacce WireGuard", + "interfaces.unique_port_hint": "Ogni interfaccia WireGuard sul server deve usare una porta UDP distinta.", + "interfaces.unique_table_hint": "WGTools consiglia una tabella di routing separata per ogni interfaccia. Lascia vuoto per il routing normale.", + "nav.clients": "Client", + "nav.dashboard": "Panoramica", + "nav.server": "Server", + "nav.settings": "Impostazioni", + "server.access_apply_confirm": "Salvare e applicare la regola firewall? WireGuard verrà riavviato brevemente dopo un backup.", + "server.access_rule_deleted": "Regola di accesso eliminata.", + "server.access_rule_help": "Crea una regola di accesso FORWARD senza modificare i comandi iptables manualmente.", + "server.access_rule_order_hint": "WGTools inserisce le regole all’inizio di FORWARD affinché quelle restrittive precedano le regole VPN ACCEPT generali.", + "server.access_rule_saved": "Regola di accesso salvata e applicata.", + "server.action": "Azione", + "server.action_hint": "REJECT comunica al client il rifiuto; DROP scarta senza risposta; ACCEPT consente esplicitamente.", + "server.add_access_rule": "Aggiungi regola di accesso", + "server.add_route": "Aggiungi route", + "server.address": "Indirizzo", + "server.any": "Qualsiasi", + "server.any_protocol": "Qualsiasi", + "server.apply_confirm": "Salvare e applicare le impostazioni server? WireGuard verrà riavviato brevemente. WGTools crea un backup e ripristina automaticamente la configurazione se l’avvio fallisce.", + "server.apply_settings": "Salva e applica", + "server.applying_rule": "Creazione backup e applicazione…", + "server.applying_settings": "Convalida impostazioni, creazione backup e applicazione…", + "server.basic_settings": "Impostazioni di base", + "server.config_tab_help": "Apri editor della configurazione grezza dell’interfaccia WireGuard scelta.", + "server.create_confirm": "Creare e avviare il server WireGuard con queste impostazioni?", + "server.create_server": "Crea server", + "server.create_step_conf": "Crea configurazione dell’interfaccia WireGuard con permessi 600.", + "server.create_step_forward": "Configura forwarding, NAT e routing per policy opzionale.", + "server.create_step_key": "Genera nuova coppia di chiavi server.", + "server.create_step_start": "Abilita e avvia l’interfaccia wg-quick scelta.", + "server.create_subtitle": "WireGuard è installato, ma l’interfaccia selezionata non è configurata.", + "server.create_success": "Server WireGuard creato correttamente.", + "server.create_title": "Crea server WireGuard", + "server.creating": "Generazione chiavi, scrittura configurazione e avvio WireGuard…", + "server.custom_preserved": "Restano invariati blocchi peer, route Site-to-site e regole PostUp/PostDown personalizzate non gestite qui.", + "server.delete_access_confirm": "Eliminare questa regola di accesso e applicare?", + "server.delete_route_confirm": "Eliminare questa route personalizzata e applicare?", + "server.destination": "Destinazione", + "server.destination_hint": "Vuoto = qualsiasi. Accetta IP, CIDR o intervallo IP. Separa più destinazioni con virgole.", + "server.destination_port": "Porta destinazione", + "server.destination_port_hint": "Facoltativo. Porta come 443 o intervallo 10000:20000. Prima scegli TCP o UDP.", + "server.details": "Dettagli", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostica", + "server.diagnostics_done": "Diagnostica completata", + "server.diagnostics_subtitle": "Controlli correnti del sistema. Nessuna modifica alla configurazione.", + "server.direction": "Hook", + "server.edit_access_rule": "Modifica regola di accesso", + "server.edit_route": "Modifica route", + "server.edit_server": "Modifica server", + "server.edit_subtitle": "Modifica impostazioni comuni WireGuard, routing e NAT. Peer e regole personalizzate esistenti vengono mantenuti.", + "server.edit_title": "Impostazioni server", + "server.edit_warning": "Applicare impostazioni di interfaccia, routing o firewall riavvia brevemente WireGuard. I peer attivi si ricollegano da soli.", + "server.enable_forwarding": "Abilita forwarding IPv4", + "server.enable_nat": "Abilita NAT / Masquerade", + "server.firewall": "Firewall e NAT", + "server.firewall_subtitle": "Regole rilevate dagli hook WireGuard.", + "server.firewall_subtitle_v08": "Regole di forwarding/NAT e accesso dall’interfaccia. Le regole semplici si gestiscono qui; quelle avanzate nell’editor grezzo.", + "server.forward_from_vpn": "Consenti forwarding da VPN", + "server.forward_to_vpn": "Consenti forwarding verso VPN", + "server.forwarding_section": "Forwarding e NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Richiesto solo con una tabella di policy routing.", + "server.install_success": "WireGuard installato correttamente.", + "server.install_wireguard": "Installa WireGuard", + "server.install_wireguard_help": "Esegue apt update e installa WireGuard e gli strumenti di rete necessari.", + "server.install_wireguard_title": "Installa WireGuard", + "server.installing": "Installazione WireGuard… Potrebbe volerci un minuto.", + "server.interface": "Interfaccia", + "server.interface_hint": "WGTools gestisce attualmente questa interfaccia.", + "server.interface_name": "Interfaccia", + "server.interface_section": "Interfaccia WireGuard", + "server.ip_forwarding": "Forwarding IPv4", + "server.kind": "Tipo", + "server.listen_port": "Porta di ascolto", + "server.local_network": "Rete locale", + "server.local_network_hint": "Route facoltativa aggiunta alla tabella di routing.", + "server.managed_automatically": "Gestito automaticamente", + "server.nat": "NAT / Masquerade", + "server.network": "Rete", + "server.network_settings": "Rete e NAT", + "server.no_firewall": "Nessuna regola firewall trovata", + "server.no_routes": "Nessuna route trovata", + "server.not_configured": "Non configurato", + "server.not_set": "Non impostato", + "server.policy_disabled_hint": "Disattiva per il routing di sistema normale. Attiva solo se la VPN richiede una propria tabella basata sull’origine.", + "server.policy_enabled": "Abilita policy routing", + "server.policy_table": "Tabella policy", + "server.policy_table_hint": "Lascia vuoto per il routing normale; usa ad es. 200 per il routing basato sull’origine.", + "server.port_word": "porta", + "server.private_hidden": "Configurato (nascosto)", + "server.private_key": "Chiave privata", + "server.protocol": "Protocollo", + "server.route_apply_confirm": "Salvare e applicare la route? WireGuard verrà riavviato brevemente dopo un backup.", + "server.route_custom": "Personalizzata", + "server.route_deleted": "Route eliminata.", + "server.route_device_hint": "Interfaccia di uscita facoltativa, ad es. wg0 o enp6s18.", + "server.route_editor_help": "Aggiungi route installata all’avvio di WireGuard e rimossa all’arresto.", + "server.route_gateway_hint": "Gateway next-hop facoltativo. Serve un gateway o un’interfaccia.", + "server.route_managed_peer": "Peer Site-to-site", + "server.route_managed_server": "Impostazione server", + "server.route_network_hint": "Rete IPv4 come 10.20.0.0/24 o 'default'.", + "server.route_saved": "Route salvata e applicata.", + "server.route_table_hint": "Usa 'main' per il routing normale o una tabella numerica come 200.", + "server.route_type": "Tipo", + "server.routes": "Rotte rilevate", + "server.routes_subtitle": "Route estratte da PostUp/PostDown e dallo stato del policy routing.", + "server.routes_subtitle_v08": "Route server, Site-to-site e personalizzate dell’interfaccia selezionata. Qui puoi aggiungere, modificare e rimuovere route.", + "server.routing": "Instradamento", + "server.routing_section": "Instradamento", + "server.rule": "Regola", + "server.rule_access": "Regola di accesso", + "server.rule_advanced": "Avanzate", + "server.rule_apply_warning": "Applicare route o regole firewall riavvia brevemente WireGuard. WGTools crea un backup e ripristina la configurazione se l’avvio fallisce.", + "server.rule_client_exception": "Eccezione client", + "server.rule_client_policy": "Criterio client", + "server.rule_managed_server": "Impostazione server", + "server.rule_type": "Tipo", + "server.run_diagnostics": "Esegui diagnostica", + "server.save_apply": "Salva e applica", + "server.save_config": "SaveConfig", + "server.server_address": "Indirizzo VPN server", + "server.server_address_hint": "Di solito il primo indirizzo utilizzabile nella rete VPN.", + "server.settings_applied": "Impostazioni server salvate e applicate correttamente.", + "server.settings_apply_failed": "Impossibile applicare le impostazioni server", + "server.setup_required": "Configurazione necessaria", + "server.source": "Origine", + "server.source_hint": "Vuoto = qualsiasi. Accetta IP, CIDR o intervallo come 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installazione, configurazione iniziale e stato del server WireGuard.", + "server.tab_config": "Configurazione", + "server.tab_interface": "Interfaccia", + "server.tab_routing": "Instradamento", + "server.tab_vps": "VPS", + "server.table": "Tabella", + "server.tabs_aria": "Sezioni delle impostazioni server", + "server.title": "Server", + "server.uplink": "Interfaccia uplink", + "server.use_raw_editor": "Usa editor configurazione grezza", + "server.via": "Via / Dispositivo", + "server.via_word": "via", + "server.vpn_network": "Rete VPN", + "server.vpn_network_hint": "Gli indirizzi client verranno assegnati da questa rete.", + "server.vpn_pool": "Pool indirizzi VPN", + "server.wg_not_installed": "WireGuard non è installato", + "server.wg_not_installed_subtitle": "WGTools può installare automaticamente i pacchetti Debian necessari.", + "server.what_happens": "Operazioni di WGTools", + "settings.about": "Informazioni", + "settings.add_user": "Aggiungi utente", + "settings.advanced": "Avanzate", + "settings.advanced_subtitle": "Accesso diretto agli strumenti avanzati di configurazione WireGuard.", + "settings.appearance": "Aspetto", + "settings.applying_config": "Validazione configurazione, creazione backup e applicazione…", + "settings.backup_count": "Backup salvati", + "settings.backup_retention": "Backup da conservare", + "settings.backup_retention_help": "I vecchi backup automatici vengono eliminati dopo la creazione del nuovo. Da 1 a 200 file.", + "settings.backups": "Backup della configurazione", + "settings.backups_always_on": "Abilitato", + "settings.backups_subtitle": "WGTools crea automaticamente un backup prima di modificare la configurazione. I backup automatici non possono essere disabilitati.", + "settings.change_password": "Cambia password", + "settings.check_updates": "Controlla aggiornamenti", + "settings.config_applied": "Configurazione salvata e applicata correttamente.", + "settings.config_applied_restarted": "Configurazione applicata e WireGuard riavviato.", + "settings.config_applied_stopped": "Configurazione salvata. WireGuard era fermo e rimane fermo.", + "settings.config_apply_failed": "Impossibile applicare la configurazione", + "settings.config_load_failed": "Impossibile caricare la configurazione", + "settings.current_user": "Utente corrente", + "settings.current_version": "Versione attuale", + "settings.audit_action": "Azione", + "settings.audit_empty": "Nessun evento audit", + "settings.audit_log": "Registro audit", + "settings.audit_log_subtitle": "Azioni nel pannello, autenticazione, Telegram e cronologia delle connessioni WireGuard. I segreti non vengono registrati.", + "settings.audit_object": "Oggetto", + "settings.audit_result": "Risultato", + "settings.audit_retention_note": "Conservazione: 30 giorni", + "settings.audit_search": "Ricerca rapida", + "settings.audit_search_clear": "Cancella ricerca", + "settings.audit_search_empty": "Nessun evento audit corrispondente", + "settings.audit_time": "Data / ora", + "settings.audit_user": "Utente", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Regola di accesso creata", + "audit.action.access_rule.deleted": "Regola di accesso eliminata", + "audit.action.access_rule.updated": "Regola di accesso aggiornata", + "audit.action.auth.first_user_created": "Primo utente creato", + "audit.action.auth.login": "Accesso effettuato", + "audit.action.auth.login_failed": "Accesso non riuscito", + "audit.action.auth.logout": "Disconnessione effettuata", + "audit.action.backup.full_created": "Backup completo creato", + "audit.action.backup.full_restored": "Backup completo ripristinato", + "audit.action.client.config_downloaded": "Configurazione client scaricata", + "audit.action.client.config_viewed": "Configurazione client visualizzata", + "audit.action.client.created": "Client creato", + "audit.action.client.deleted": "Client eliminato", + "audit.action.client.qr_viewed": "Codice QR client visualizzato", + "audit.action.client.updated": "Client aggiornato", + "audit.action.client_group.created": "Gruppo client creato", + "audit.action.client_group.deleted": "Gruppo client eliminato", + "audit.action.client_group.updated": "Gruppo client aggiornato", + "audit.action.interface.created": "Interfaccia creata", + "audit.action.interface.deleted": "Interfaccia eliminata", + "audit.action.interface.renamed": "Interfaccia rinominata", + "audit.action.route.created": "Rotta creata", + "audit.action.route.deleted": "Rotta eliminata", + "audit.action.route.updated": "Rotta aggiornata", + "audit.action.server.created": "Server creato", + "audit.action.server.raw_config_applied": "Configurazione grezza applicata", + "audit.action.server.settings_applied": "Impostazioni server applicate", + "audit.action.settings.updated": "Impostazioni pannello aggiornate", + "audit.action.telegram.action_denied": "Azione Telegram negata", + "audit.action.telegram.action_failed": "Azione Telegram non riuscita", + "audit.action.telegram.connection_test": "Test connessione Telegram", + "audit.action.telegram.settings_updated": "Impostazioni Telegram aggiornate", + "audit.action.update.checked": "Aggiornamento verificato", + "audit.action.update.scheduled": "Aggiornamento pianificato", + "audit.action.update.backup_created": "Backup pre-aggiornamento", + "audit.action.update.completed": "Aggiornamento completato", + "audit.action.update.failed": "Aggiornamento non riuscito", + "audit.action.update.rollback_completed": "Versione precedente ripristinata", + "audit.action.update.rollback_failed": "Rollback aggiornamento non riuscito", + "audit.action.user.created": "Utente creato", + "audit.action.user.deleted": "Utente eliminato", + "audit.action.user.password_changed": "Password utente modificata", + "audit.action.vps.candidate_deleted": "Candidato VPS eliminato", + "audit.action.vps.candidate_saved": "Candidato VPS salvato", + "audit.action.vps.detached": "Relay VPS scollegato", + "audit.action.vps.relay_installed": "Relay VPS installato", + "audit.action.wireguard.client_connected": "Client WireGuard connesso", + "audit.action.wireguard.installed": "WireGuard installato", + "audit.action.wireguard.restarted": "WireGuard riavviato", + "audit.action.wireguard.started": "WireGuard avviato", + "audit.action.wireguard.stopped": "WireGuard arrestato", + "audit.result.applied": "applicato", + "audit.result.available": "disponibile", + "audit.result.changed": "modificato", + "audit.result.created": "creato", + "audit.result.current": "attuale", + "audit.result.deleted": "eliminato", + "audit.result.detached": "scollegato", + "audit.result.denied": "negato", + "audit.result.downloaded": "scaricato", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Errore", + "audit.result.installed": "installato", + "audit.result.invalid_credentials": "credenziali non valide", + "audit.result.ok": "OK", + "audit.result.queued": "in coda", + "audit.result.restarted": "riavviato", + "audit.result.restored": "ripristinato", + "audit.result.rotated": "rigenerato", + "audit.result.saved": "salvato", + "audit.result.shown": "mostrato", + "audit.result.started": "avviato", + "audit.result.stopped": "arrestato", + "audit.result.updated": "aggiornato", + "settings.delete_user": "Elimina", + "settings.delete_user_confirm": "Eliminare l’utente {name}?", + "settings.edit_raw_config": "Modifica configurazione interfaccia", + "settings.expert_mode": "Esperto", + "settings.full_backup_component_clients": "Metadati dei client gestiti, chiavi private, PSK, scadenze e gruppi necessari per rigenerare configurazioni e QR.", + "settings.full_backup_component_db": "Database WGTools: utenti, preferenze, email/SMTP, Telegram e stato salvato di VPS Relay.", + "settings.full_backup_component_relay": "Dati di recupero VPS Relay: ID controller/tenant, token di gestione e chiave di trasporto Home. Dopo il ripristino WGTools può ricreare il trasporto locale e riconnettere il tenant.", + "settings.full_backup_component_system": "File sysctl IPv4 forwarding WGTools, metadati dei nomi interfaccia e criteri/modelli gruppo, se presenti. La cronologia automatica è esclusa intenzionalmente.", + "settings.full_backup_component_wg": "Tutte le configurazioni WireGuard rilevate in /etc/wireguard/, incluso lo stato attivo/fermo.", + "settings.full_backup_create_failed": "Impossibile creare backup completo", + "settings.full_backup_creating": "Creazione backup completo…", + "settings.full_backup_download": "Crea", + "settings.full_backup_downloaded": "Backup creato e scaricato. Conservalo al sicuro.", + "settings.full_backup_downloaded_short": "Backup completo scaricato.", + "settings.full_backup_help": "Crea un backup WGTools portatile per migrazione o emergenze: configurazioni WireGuard, utenti, impostazioni, gruppi, client gestiti e dati per riconnettere i tenant VPS Relay conservati.", + "settings.full_backup_no_file": "Nessun backup selezionato", + "settings.full_backup_restore": "Ripristina", + "settings.full_backup_restore_confirm": "Ripristinare il backup completo WGTools? Verranno ripristinati utenti, impostazioni, client gestiti e configurazioni WireGuard incluse. Le interfacce potrebbero riavviarsi. WGTools crea prima un backup di sicurezza e annulla automaticamente in caso di errore.", + "settings.full_backup_restore_failed": "Ripristino non riuscito", + "settings.full_backup_restored": "Backup ripristinato. Accedi con un account presente nel backup.", + "settings.full_backup_restored_short": "Backup ripristinato.", + "settings.full_backup_restoring": "Verifica backup, creazione copia di sicurezza e ripristino…", + "settings.full_backup_secret_warning": "Il file contiene dati sensibili: chiavi private WireGuard e dei client, PSK, hash delle password WGTools, token bot Telegram e password SMTP salvata. Custodiscilo come una password e non allegarlo mai a issue o chat pubbliche.", + "settings.full_backup_select": "Seleziona", + "settings.full_backup_title": "Backup completo e ripristino", + "settings.full_mode": "Gestione server e client attiva", + "settings.interface_help": "L’interfaccia WireGuard gestita viene scelta durante l’installazione di WGTools.", + "settings.language": "Lingua", + "settings.last_backup": "Ultimo backup", + "settings.latest_version": "Ultima versione", + "settings.loading_config": "Caricamento configurazione…", + "settings.mode": "Modalità", + "settings.never_logged_in": "Mai", + "settings.new_password": "Nuova password", + "settings.no_backups": "Nessun backup", + "settings.online_help": "Un peer è online se il suo ultimo handshake è più recente della soglia. 30–3600 secondi.", + "settings.online_threshold": "Soglia online", + "settings.open_release": "Apri release", + "settings.password_changed": "Password modificata.", + "settings.passwords_mismatch": "Le password non coincidono.", + "settings.project_github": "Progetto / GitHub", + "settings.raw_config_confirm": "Salvare e applicare questa configurazione WireGuard? L’interfaccia selezionata verrà riavviata. Prima viene creato un backup; WGTools ripristina quella precedente se l’avvio fallisce.", + "settings.raw_config_help": "Apri la configurazione sorgente dell’interfaccia WireGuard scelta.", + "settings.raw_config_title": "Configurazione WireGuard grezza", + "settings.raw_config_warning": "Modalità esperto: questa è la vera configurazione server WireGuard e contiene la chiave privata e i PSK dei peer. Salvare e applicare riavvia l’interfaccia. WGTools crea prima un backup e ripristina se l’avvio fallisce.", + "settings.readonly_mode": "Gestione client attiva", + "settings.refresh_help": "Frequenza di aggiornamento dello stato. Da 2 a 60 secondi.", + "settings.refresh_interval": "Intervallo di aggiornamento", + "settings.release_notes": "Note di rilascio", + "settings.reload_config": "Ricarica da disco", + "settings.save_apply": "Salva e applica", + "settings.saved": "Impostazioni salvate.", + "settings.saved_reload": "Impostazioni salvate. Ricaricamento…", + "settings.saving": "Salvataggio impostazioni…", + "settings.status": "Aggiornamento stato", + "settings.status_help": "Intervalli di aggiornamento Dashboard e stato dei peer.", + "settings.subtitle": "Preferenze interfaccia e impostazioni stato WGTools.", + "settings.syntax_hint": "Sezioni, chiavi, valori e commenti WireGuard sono evidenziati durante la modifica.", + "settings.tab_about": "Informazioni", + "settings.tab_backups": "Backup", + "settings.tab_general": "Generale", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Utenti", + "settings.tabs_aria": "Sezioni impostazioni", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "ID utenti Telegram consentiti", + "settings.telegram_allowed_ids_help": "Un ID numerico per riga. Un /start non autorizzato risponderà con l’ID Telegram del mittente, che potrai aggiungere qui.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connesso", + "settings.telegram_disabled": "Disabilitato", + "settings.telegram_dns": "DNS client predefinito", + "settings.telegram_dns_help": "Indirizzi DNS IPv4 facoltativi, separati da virgole. Usati per client creati dal bot.", + "settings.telegram_enabled": "Abilita bot Telegram", + "settings.telegram_endpoint": "Indirizzo / dominio server predefinito", + "settings.telegram_endpoint_help": "Usato dal bot per nuove configurazioni client. Inserisci solo IP o dominio; la porta WireGuard è letta dalla configurazione server.", + "settings.telegram_language": "Lingua del bot", + "settings.telegram_language_auto": "Auto (lingua Telegram)", + "settings.telegram_last_poll": "Ultimo contatto Telegram", + "settings.telegram_not_configured": "Non configurato", + "settings.telegram_remove_token": "Rimuovi token", + "settings.telegram_remove_token_confirm": "Rimuovere il token del bot Telegram salvato e disabilitare il bot?", + "settings.telegram_save": "Salva impostazioni Telegram", + "settings.telegram_saved": "Impostazioni Telegram salvate.", + "settings.telegram_setup_note": "Crea un bot con @BotFather, salva il token, attivalo e invia /start. Se il tuo ID non è autorizzato, WGTools lo mostrerà: aggiungilo alla lista degli ID consentiti.", + "settings.telegram_status": "Stato del bot", + "settings.telegram_subtitle": "Gestione WireGuard da Telegram: stato server, client, creazione/eliminazione e avvio/riavvio/arresto.", + "settings.telegram_test": "Testa connessione", + "settings.telegram_test_ok": "Connessione Telegram funzionante: @{username}", + "settings.telegram_test_recent_ok": "Il bot Telegram funziona. Il controllo diretto è scaduto, ma il bot ha contattato Telegram di recente.", + "settings.telegram_token": "Token del bot", + "settings.telegram_token_help": "Crea un bot con @BotFather e incolla qui il token Bot API. API ID e API Hash non sono richiesti.", + "settings.telegram_token_keep": "Lascia vuoto per conservare il token salvato.", + "settings.telegram_waiting": "Configurato, in attesa del servizio bot", + "settings.theme": "Tema", + "settings.theme_dark": "Scuro", + "settings.theme_light": "Chiaro", + "settings.theme_system": "Sistema", + "settings.title": "Impostazioni", + "settings.update_available": "Aggiornamento disponibile", + "settings.update_backup_queued": "Aggiornamento in coda. WGTools creerà un backup completo automatico prima dell’installazione…", + "settings.update_backup_running": "Creazione del backup completo prima dell’aggiornamento…", + "settings.update_check_failed": "Impossibile verificare aggiornamenti", + "settings.update_checking": "Verifica dell’ultima release pubblicata su GitHub…", + "settings.update_confirm": "Aggiornare WGTools da v{current} a v{latest}? Prima verranno creati un backup completo e una copia per il rollback. L’interfaccia web si riavvierà brevemente.", + "settings.update_current": "Aggiornato", + "settings.update_downloading": "Download e verifica della release GitHub…", + "settings.update_failed": "Aggiornamento WGTools non riuscito.", + "settings.update_installing": "Installazione aggiornamento. L’interfaccia web potrebbe non essere disponibile per poco…", + "settings.update_no_update": "WGTools è già aggiornato.", + "settings.update_not_checked": "Non verificato", + "settings.update_queued": "Aggiornamento in coda. In attesa del servizio updater…", + "settings.update_rollback_ok": "La precedente applicazione WGTools è stata ripristinata automaticamente.", + "settings.update_rolling_back": "Aggiornamento non riuscito. Ripristino versione WGTools precedente…", + "settings.update_running": "Creazione backup di sicurezza…", + "settings.update_safety_hint": "Gli aggiornamenti sono facoltativi. WGTools crea backup completo e copia per rollback prima di installare. In caso di errore ripristina l’applicazione precedente. WireGuard non viene riavviato, salvo modifiche esplicite della sua configurazione nella release.", + "settings.update_sidebar": "Nuova versione disponibile", + "settings.update_sidebar_hint": "Impostazioni → Info", + "settings.update_starting": "Avvio aggiornamento…", + "settings.update_status_unknown": "Stato aggiornamento non disponibile. Nuovo tentativo…", + "settings.update_subtitle": "Informazioni progetto, verifica automatica delle release e aggiornamenti sicuri da GitHub Releases.", + "settings.update_success": "WGTools aggiornato a v{version}. Ricaricamento…", + "settings.update_wgtools": "Aggiorna WGTools", + "settings.user_actions": "Azioni", + "settings.user_created": "Creato", + "settings.user_created_ok": "Utente creato.", + "settings.user_deleted": "Utente eliminato.", + "settings.user_equal_rights": "Tutti gli utenti WGTools hanno gli stessi permessi.", + "settings.user_last_login": "Ultimo accesso", + "settings.user_name": "Nome utente", + "settings.users": "Utenti", + "settings.users_subtitle": "Account locali WGTools. L’email è facoltativa ed è usata solo per recuperare la password se la posta è attiva.", + "vps.add": "Aggiungi VPS", + "vps.add_help": "WGTools usa SSH per verificare o installare Relay. Password e chiavi SSH private non vengono mai salvate.", + "vps.add_title": "Aggiungi VPS", + "vps.agent": "Agente Relay", + "vps.agent_found": "Già installato", + "vps.agent_will_install": "Verrà installato", + "vps.arch": "Architettura", + "vps.auth_method": "Autenticazione", + "vps.authentication": "Autenticazione SSH", + "vps.check": "Verifica VPS", + "vps.check_failed": "Verifica VPS non riuscita", + "vps.check_link": "Verifica collegamento", + "vps.check_ok": "VPS compatibile", + "vps.checking": "Verifica accesso SSH e compatibilità VPS…", + "vps.connections": "connessioni", + "vps.credentials_not_saved": "Usati solo per questa verifica, non salvati da WGTools.", + "vps.delete_candidate": "Rimuovi", + "vps.delete_installed": "Rimuovi VPS", + "vps.delete_installed_confirm": "Rimuovere “{name}” da WGTools? Il trasporto Relay locale verrà scollegato, ma Relay Agent e tenant sul VPS saranno conservati. Potrai aggiungere di nuovo il VPS per riconnetterti al Relay esistente. I client non potranno usarlo finché non sarà riconnesso.", + "vps.delete_installed_failed": "Impossibile rimuovere VPS da WGTools", + "vps.delete_installed_ok": "VPS rimosso da WGTools. Il Relay remoto è conservato e può essere riconnesso.", + "vps.empty_help": "Aggiungi un VPS Debian o Ubuntu per verificare SSH, compatibilità del sistema e porte UDP necessarie.", + "vps.empty_title": "Nessun VPS configurato", + "vps.endpoint": "Endpoint pubblico", + "vps.endpoint_domain": "Dominio (consigliato)", + "vps.endpoint_domain_hint": "Se cambi in futuro il VPS principale, modificare il DNS può mantenere invariate le configurazioni client.", + "vps.health_failed": "Verifica collegamento Relay non riuscita", + "vps.host": "IP / nome host", + "vps.host_key": "Chiave host SSH", + "vps.identity": "Connessione VPS", + "vps.install_failed": "Installazione Relay non riuscita", + "vps.install_ok": "Relay installato e collegamento di gestione protetto verificato", + "vps.install_relay": "Installa Relay", + "vps.install_title": "Installa Relay VPS", + "vps.installed": "Installato", + "vps.installing": "Installazione Relay Agent e creazione tunnel protetto…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Passphrase chiave", + "vps.link_ok": "Collegamento Relay OK", + "vps.multi_tenant_note": "Un Relay Agent WGTools è già in esecuzione su questo VPS. Non sarà sostituito: questo WGTools avrà connessione isolata con chiavi e porte UDP proprie.", + "vps.name": "Nome", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Verrà installato", + "vps.os": "Sistema operativo", + "vps.password": "Password", + "vps.phase_note": "Relay Agent supporta più controller WGTools indipendenti su un VPS. Ogni controller riceve connessione, chiavi e porte UDP isolate; quelle esistenti restano intatte.", + "vps.port_pair": "Porte UDP", + "vps.ports_adjusted": "selezionate porte libere", + "vps.private_key": "Chiave privata", + "vps.privilege": "Privilegi", + "vps.public_endpoint": "Futuro endpoint pubblico", + "vps.ready_help": "Le credenziali SSH servono solo per la verifica e l’installazione immediata di Relay; non vengono salvate.", + "vps.reconnect_note": "Sul VPS esiste già una connessione Relay creata da questo WGTools. Verrà riconnesso lo stesso tenant, senza crearne uno nuovo né nuove porte UDP.", + "vps.reconnect_ok": "Relay esistente riconnesso correttamente", + "vps.reconnect_relay": "Riconnetti Relay", + "vps.relay_port": "Porta UDP Relay", + "vps.remove_confirm": "Rimuovere questo candidato VPS? Nessuna modifica remota è stata effettuata.", + "vps.save_candidate": "Salva candidato", + "vps.saved": "Candidato VPS salvato", + "vps.ssh": "SSH", + "vps.ssh_key": "Chiave SSH", + "vps.ssh_port": "Porta SSH", + "vps.ssh_user": "Utente SSH", + "vps.status_candidate": "Pronto per installazione", + "vps.status_installed": "Relay connesso", + "vps.subtitle": "Prepara un VPS pubblico per l’accesso remoto quando questo server WGTools non ha IP pubblico.", + "vps.tenant": "Connessione", + "vps.title": "Relay VPS", + "vps.transport_port": "Porta UDP di trasporto", + "vps.transport_port_hint": "Porta UDP separata per il tunnel di trasporto privato Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Salvato", + "vps.active_short": "Attivo", + "dashboard.traffic_reset": "Ripristina", + "dashboard.traffic_reset_confirm": "Azzerare i contatori di traffico WireGuard per questa interfaccia? Anche quelli dei client ripartiranno da zero.", + "dashboard.traffic_reset_done": "Contatori traffico azzerati", + "dashboard.traffic_reset_failed": "Impossibile azzerare i contatori traffico", + "audit.action.traffic.reset": "Contatori traffico azzerati", + "audit.result.reset": "azzerato", + "server.mtu": "MTU", + "server.mtu_auto": "Automatico", + "server.mtu_hint": "Facoltativo. Lascia vuoto per MTU automatico di wg-quick. Imposta 1380 o 1420 solo se richiesto da LTE o PPPoE.", + "clients.peer_isolation": "Isolamento client VPN", + "clients.peer_isolation_enable": "Isola dagli altri client VPN", + "clients.peer_isolation_hint": "Blocca il traffico tra questo client e gli altri indirizzi del pool WireGuard. L’accesso al server, a Internet e alle reti locali o Site-to-site resta regolato dagli altri criteri.", + "clients.credentials_rotate": "Chiavi del client", + "clients.credentials_rotate_button": "Rigenera chiavi", + "clients.credentials_rotate_confirm": "Generare nuove chiavi per questo client? Se connesso, la sessione WireGuard verrà interrotta immediatamente. Invia poi una nuova configurazione o QR.", + "clients.credentials_rotate_confirm_psk": "Generare una nuova coppia di chiavi e un nuovo PSK? La sessione WireGuard attiva del client verrà interrotta immediatamente. Invia poi una nuova configurazione o QR.", + "clients.credentials_rotate_hint": "Rigenera PrivateKey/PublicKey e anche il PSK se attivo. Indirizzo, route, gruppo, pianificazione, isolamento e statistiche restano invariati.", + "clients.credentials_rotating": "Generazione nuove chiavi e disconnessione della vecchia sessione…", + "clients.credentials_rotated": "Chiavi del client cambiate. La vecchia sessione è stata interrotta se attiva. La precedente configurazione non funziona più; invia nuova configurazione o QR.", + "clients.credentials_rotated_short": "Chiavi cambiate — serve nuova configurazione", + "audit.action.client.credentials_rotated": "Chiavi del client rigenerate", + "clients.credentials_connection_lost": "Connessione a WGTools interrotta. Se il pannello era aperto tramite il client le cui chiavi sono state rigenerate, è normale: la vecchia sessione WireGuard è stata chiusa. Ricollegati con un altro percorso e genera nuova configurazione o QR.", + "nav.navigation": "Navigazione principale", + "nav.project_github": "WGTools su GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Facoltativo per ora. Può servire a recuperare la password dopo aver configurato la posta.", + "auth.forgot_password": "Password dimenticata?", + "auth.reset_title": "Reimposta la password", + "auth.reset_subtitle": "Ricevi un codice monouso via email e imposta una nuova password WGTools.", + "auth.reset_identifier": "Nome utente o e-mail", + "auth.reset_identifier_help": "Per la privacy, WGTools mostra sempre la stessa risposta, sia che l’account esista o no.", + "auth.send_reset_code": "Invia codice", + "auth.reset_code_sent_generic": "Se l’account esiste e ha un indirizzo email, è stato inviato un codice. È valido per 15 minuti.", + "auth.reset_code": "Codice a 6 cifre", + "auth.set_new_password": "Imposta nuova password", + "auth.request_another_code": "Richiedi un altro codice", + "auth.back_to_login": "Torna all'accesso", + "auth.reset_not_configured": "Il recupero password via email non è configurato. Contatta l’amministratore WGTools.", + "settings.tab_mail": "Posta", + "settings.mail": "Email / SMTP", + "settings.mail_subtitle": "SMTP viene usato per il recupero password.", + "settings.mail_not_configured": "Non configurato", + "settings.mail_enabled": "Abilita posta e recupero password", + "settings.mail_smtp_host": "Server SMTP", + "settings.mail_smtp_port": "Porta SMTP", + "settings.mail_security": "Crittografia", + "settings.mail_security_none": "Nessuna crittografia", + "settings.mail_username": "Nome utente SMTP", + "settings.mail_username_help": "Usato per l’autenticazione SMTP e come indirizzo email mittente.", + "settings.mail_password": "Password SMTP", + "settings.mail_password_keep": "Lascia vuoto per mantenere la password salvata.", + "settings.mail_from_email": "Email mittente", + "settings.mail_from_name": "Nome mittente", + "settings.mail_test_recipient": "Destinatario test", + "settings.mail_test_recipient_help": "Il test usa le impostazioni SMTP attualmente salvate.", + "settings.mail_remove_password": "Rimuovi password", + "settings.mail_test": "Invia test", + "settings.mail_save": "Salva impostazioni email", + "settings.mail_enabled_badge": "Abilitato", + "settings.mail_disabled_badge": "Disabilitato", + "settings.mail_saved": "Impostazioni email salvate.", + "settings.mail_remove_password_confirm": "Rimuovere la password SMTP salvata e disabilitare la posta?", + "settings.mail_password_removed": "Password SMTP rimossa e posta disabilitata.", + "settings.mail_test_recipient_required": "Inserisci l’indirizzo email del destinatario del test.", + "settings.mail_testing": "Invio email di prova…", + "settings.mail_test_ok": "Email di prova inviata correttamente.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Facoltativa. Necessaria solo per recuperare autonomamente la password.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "Email salvata.", + "settings.send_password_reset": "Invia reset", + "settings.user_reset_mail_not_configured": "Prima configura e abilita la posta.", + "settings.user_reset_email_missing": "Aggiungi prima un indirizzo email.", + "settings.user_reset_confirm": "Inviare un codice di reset password a {name} all’indirizzo {email}?", + "settings.user_reset_sent": "Codice di reset inviato a {email}.", + "audit.action.auth.password_reset_requested": "Richiesto reset password", + "audit.action.auth.password_reset_code_sent": "Codice di reset password inviato", + "audit.action.auth.password_reset_completed": "Password reimpostata", + "audit.action.auth.password_reset_failed": "Reset password non riuscito", + "audit.action.mail.settings_updated": "Impostazioni email aggiornate", + "audit.action.mail.test_sent": "Email di prova inviata", + "audit.action.mail.test_failed": "Invio email di prova non riuscito", + "audit.action.user.email_changed": "Email utente modificata", + "audit.action.user.password_reset_sent": "Reset password utente inviato", + "audit.action.user.password_reset_failed": "Reset password utente non riuscito", + "audit.result.accepted": "accettato", + "audit.result.sent": "inviato", + "audit.result.invalid_code": "codice non valido", + "common.copy": "Copia", + "common.copied": "Copiato", + "clients.use_panel_host": "Usa indirizzo pannello", + "clients.use_panel_host_done": "Indirizzo pannello inserito: {host}", + "clients.use_panel_host_failed": "Impossibile ricavare l’indirizzo del pannello dall’URL del browser.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS Let’s Encrypt integrato per accesso diretto a WGTools senza reverse proxy.", + "settings.https_disabled": "Disabilitato", + "settings.https_enabled": "Abilitato", + "settings.https_enable": "Abilita HTTPS integrato", + "settings.https_type": "Certificato per", + "settings.https_domain": "Dominio", + "settings.https_public_ip": "IP pubblico", + "settings.https_target": "Dominio o IP pubblico", + "settings.https_email": "Email Let’s Encrypt", + "settings.https_port": "Porta HTTPS", + "settings.https_port80_note": "La porta TCP 80 deve essere raggiungibile da Internet per emissione e rinnovo del certificato. Apri anche la porta HTTPS scelta per il pannello.", + "settings.https_check_ports": "Verifica porte", + "settings.https_certificate": "Certificato", + "settings.https_certificate_ready": "Pronto", + "settings.https_certificate_missing": "Non emesso", + "settings.https_expires": "Valido fino al", + "settings.https_renewal": "Rinnovo automatico", + "settings.https_renewal_enabled": "Abilitato", + "settings.https_renewal_disabled": "Disabilitato", + "settings.https_certificate_path": "Certificato", + "settings.https_private_key_path": "Chiave privata", + "settings.https_issue": "Ottieni / rinnova certificato", + "settings.https_port_free": "Libera", + "settings.https_port_busy": "Occupata", + "settings.https_ports_checked": "Verifica porte completata.", + "settings.https_target_email_required": "Inserisci dominio/IP pubblico ed email Let’s Encrypt.", + "settings.https_issue_confirm": "Richiedere o rinnovare il certificato Let’s Encrypt per {target}? Le impostazioni HTTPS verranno salvate. La porta TCP 80 deve essere accessibile da Internet.", + "settings.https_issuing": "Richiesta certificato a Let’s Encrypt…", + "settings.https_issue_ok": "Certificato pronto.", + "settings.https_already_enabled": "HTTPS integrato già attivo.", + "settings.https_already_disabled": "HTTPS integrato già disattivato.", + "settings.https_enable_confirm": "Attivare HTTPS integrato su TCP {port} con percorso {path}? WGTools si riavvierà e la pagina si riconnetterà al nuovo indirizzo.", + "settings.https_disable_confirm": "Disattivare HTTPS integrato e tornare a HTTP?", + "settings.https_switching": "Attivazione HTTPS e riavvio WGTools…", + "settings.https_switching_http": "Disattivazione HTTPS e riavvio WGTools…", + "audit.action.https.certificate_issued": "Certificato HTTPS emesso", + "audit.action.https.certificate_failed": "Richiesta certificato HTTPS non riuscita", + "audit.action.https.enabled": "HTTPS attivato", + "audit.action.https.disabled": "HTTPS disattivato", + "audit.result.issued": "emesso", + "audit.result.enabled": "attivato", + "audit.result.disabled": "disattivato", + "settings.https_access_path": "Percorso di accesso al pannello", + "settings.https_access_path_help": "Scegli un percorso personalizzato. Con HTTPS integrato, le richieste fuori percorso ricevono 404.", + "settings.https_enable_fields_required": "Inserisci dominio/IP pubblico, email Let’s Encrypt e percorso pannello.", + "settings.https_use_panel_host": "Usa indirizzo pannello", + "settings.https_reconnecting": "WGTools passa al nuovo indirizzo HTTPS…", + "server.tab_nodes": "Nodi", + "common.type": "Tipo", + "common.status": "Stato", + "common.copy_failed": "Impossibile copiare", + "clients.vpn_address": "Indirizzo VPN", + "nodes.title": "Nodi WGTools", + "nodes.subtitle": "Collega più server WGTools in una rete protetta e pubblica solo le reti accessibili agli altri nodi.", + "nodes.enable_hub": "Attiva HUB", + "nodes.connect_hub": "Connetti a HUB", + "nodes.settings": "Impostazioni nodo", + "nodes.settings_action": "Impostazioni", + "nodes.sync_now": "Sincronizza", + "nodes.disable": "Disattiva nodi", + "nodes.disable_action": "Disconnetti", + "nodes.join_title": "Connetti nuovi nodi", + "nodes.join_help": "Genera un codice monouso e inseriscilo su un altro pannello WGTools insieme all’endpoint HUB, ad es. vpn.example.com:51950. Il codice vale 15 minuti e un solo utilizzo.", + "nodes.create_code": "Crea codice", + "nodes.connected_nodes": "Nodi connessi", + "nodes.connected_nodes_help": "Informazioni su altri pannelli, reti pubblicate e client. I client remoti sono in sola lettura.", + "nodes.enable_hub_help": "Questo pannello diventa il nodo centrale. La stessa porta accetta WireGuard su UDP e l’associazione iniziale protetta su TCP.", + "nodes.node_name": "Nome nodo", + "nodes.transport_network": "Rete di trasporto nodi", + "nodes.transport_help": "Rete privata separata usata solo per il trasporto tra WGTools. Non deve sovrapporsi alle reti VPN/LAN.", + "nodes.panel_url": "URL pannello", + "nodes.panel_url_help": "Facoltativo. Solo collegamento informativo per “Apri pannello” sugli altri nodi; non usato per la connessione Nodes.", + "nodes.extra_networks": "Reti nodo aggiuntive", + "nodes.extra_networks_help": "Una rete per riga. Reti VPN delle interfacce e reti remote Site-to-site sono pubblicate automaticamente. Aggiungi solo altre LAN/reti instradate, ad es. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools inserisce reti VPN, Site-to-site e LAN instradate rilevate. Mantieni solo le reti da pubblicare. Una per riga.", + "nodes.published_networks_settings_help": "Una rete per riga. Questo è l’elenco esplicito delle reti pubblicate dal nodo. Rimuovere una riga interrompe l’annuncio agli altri nodi.", + "nodes.available_networks_help": "Reti rilevate: {networks}. Le nuove reti non vengono pubblicate automaticamente; aggiungi quelle desiderate sopra.", + "nodes.available_networks_none": "Nessuna rete locale aggiuntiva rilevata.", + "nodes.connect_help": "Inserisci endpoint HUB e codice monouso. URL web, porta HTTPS, certificato e percorso privato non sono usati per associare i nodi.", + "nodes.join_code": "Codice connessione", + "nodes.connect_reachability_note": "L’associazione iniziale usa TCP protetto sulla porta indicata. Dopo la creazione di wgnode0, reti, stato, versioni e dati client in sola lettura si sincronizzano con HUB tramite indirizzo WireGuard interno.", + "nodes.connect": "Connetti", + "nodes.settings_help": "Nome nodo, collegamento facoltativo “Apri pannello” ed elenco reti pubblicate. L’URL non è usata per associazione o sincronizzazione.", + "nodes.details": "Dettagli", + "nodes.not_configured": "WGTools Nodes non configurato", + "nodes.not_configured_help": "Attiva HUB su questo pannello o collegalo a un HUB WGTools esistente.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connesso a HUB", + "nodes.mode_none": "Non configurato", + "nodes.role": "Ruolo", + "nodes.tunnel": "Tunnel nodo", + "nodes.node_ip": "Indirizzo nodo", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Reti pubblicate", + "nodes.last_sync": "Ultima sincronizzazione", + "nodes.no_nodes_hub": "Nessun nodo connesso. Crea un codice e usalo su un altro pannello WGTools.", + "nodes.no_nodes_spoke": "Nessuna informazione ricevuta sui nodi remoti.", + "nodes.clients_short": "Client", + "nodes.open_panel": "Apri pannello", + "nodes.route_conflict": "Conflitto di route", + "nodes.no_published_networks": "Nessuna rete pubblicata", + "nodes.load_failed": "Impossibile caricare WGTools Nodes", + "nodes.enable_hub_confirm": "Attivare WGTools HUB e creare il tunnel WireGuard interno dei nodi?", + "nodes.applying": "Configurazione tunnel WGTools Nodes…", + "nodes.enable_failed": "Impossibile attivare HUB", + "nodes.hub_enabled": "WGTools HUB attivato", + "nodes.connecting": "Verifica codice HUB e creazione tunnel protetto…", + "nodes.connect_failed": "Impossibile connettersi a HUB", + "nodes.connected": "Connesso a WGTools HUB", + "nodes.settings_failed": "Impossibile salvare impostazioni nodo", + "nodes.settings_saved": "Impostazioni nodo salvate", + "nodes.code_failed": "Impossibile creare codice di connessione", + "nodes.code_expires": "Codice monouso. Valido fino alle {time}.", + "nodes.code_copied": "Codice connessione copiato", + "nodes.network_vpn": "Client VPN", + "nodes.network_site_to_site": "Rete Site-to-site", + "nodes.network_custom": "Rete aggiuntiva", + "nodes.conflict": "Conflitto", + "nodes.remote_clients": "Client (sola lettura)", + "nodes.no_clients": "Nessun client segnalato da questo nodo", + "nodes.details_failed": "Impossibile caricare dettagli nodo", + "nodes.remove_confirm": "Rimuovere il nodo “{name}” da HUB? L’accesso al tunnel interno sarà revocato.", + "nodes.remove_failed": "Impossibile rimuovere il nodo", + "nodes.removed": "Nodo rimosso", + "nodes.disable_hub_confirm": "Disattivare HUB e disconnettere tutti i nodi WGTools? Il tunnel interno sarà rimosso.", + "nodes.disconnect_confirm": "Disconnettere questo pannello WGTools da HUB e rimuovere il tunnel interno?", + "nodes.disable_failed": "Impossibile disattivare WGTools Nodes", + "nodes.disabled": "WGTools Nodes disattivato", + "nodes.sync_failed": "Sincronizzazione nodi non riuscita", + "nodes.synced": "Informazioni nodi sincronizzate", + "nodes.service_port": "Porta Nodes", + "nodes.service_port_help": "La stessa porta serve contemporaneamente WireGuard su UDP e l’associazione iniziale protetta su TCP.", + "nodes.hub_port_forward_note": "Se HUB è dietro NAT, inoltra la stessa porta UDP e TCP. Porta web WGTools, HTTPS e percorso privato del pannello non riguardano Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Dominio/IP e porta Nodes senza http:// o https://, ad es. vpn.example.com:51950.", + "settings.collapse_sidebar": "Comprimi barra laterale", + "settings.expand_sidebar": "Espandi barra laterale", + "settings.https_issue_fields_required": "Inserisci dominio/IP pubblico, email Let’s Encrypt e percorso pannello.", + "settings.https_issue_ok_saved": "Certificato pronto e impostazioni HTTPS salvate.", + "settings.https_enable_need_certificate": "Prima ottieni un certificato.", + "settings.https_enable_certificate_mismatch": "Prima ottieni un certificato per dominio o IP corrente.", + "settings.https_enable_certificate_expired": "Certificato scaduto. Rinnovalo prima di attivare HTTPS.", + "settings.https_enable_certificate_ready": "Certificato pronto: puoi attivare HTTPS integrato.", + "settings.https_enable_active_help": "Deseleziona e salva per tornare a HTTP.", + "settings.https_certificate_expired": "Scaduto", + "settings.https_certificate_wrong_target": "Per un altro indirizzo", + "nodes.network_conflict_error": "Le reti pubblicate sono in conflitto con un altro nodo o la rete di trasporto Nodes: {conflicts}. Rimuovi o modifica le reti.", + "nodes.networks_changed": "Le reti rilevate sono cambiate dall’ultimo salvataggio. Nuove: {added}. Non più rilevate: {removed}. Controlla e salva l’elenco pubblicato.", + "nodes.review_networks": "Controlla reti", + "nodes.vpn_pool_mismatch": "Pool VPN modificato: Nodes pubblica ancora {old}, mentre il pool attuale è {current}. Apri impostazioni nodo e aggiorna le reti pubblicate.", + "server.error_vpn_network_invalid": "La rete VPN deve essere una rete IPv4 valida, ad es. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Sono supportate solo reti VPN IPv4.", + "server.error_vpn_network_too_small": "La rete VPN deve contenere almeno due indirizzi utilizzabili.", + "server.error_vpn_network_no_hosts": "La rete VPN scelta non contiene indirizzi server utilizzabili.", + "server.error_server_address_prefix": "L’indirizzo VPN server deve includere un prefisso, ad es. 10.0.0.1/24.", + "server.error_server_address_network": "L’indirizzo VPN server deve appartenere al pool selezionato e usare lo stesso prefisso.", + "server.error_server_address_reserved": "L’indirizzo VPN server non può essere indirizzo di rete o broadcast.", + "server.error_listen_port_number": "La porta WireGuard deve essere un numero.", + "server.error_listen_port_range": "La porta WireGuard deve essere tra 1 e 65535.", + "server.error_mtu_number": "MTU deve essere un numero.", + "auth.mfa_title": "Autenticazione a due fattori", + "auth.mfa_login_help": "Inserisci il codice a 6 cifre di Google Authenticator o uno dei codici di recupero.", + "auth.mfa_code": "Codice di autenticazione", + "auth.mfa_verify": "Verifica e accedi", + "auth.mfa_back": "Torna alla password", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Autenticazione a due fattori (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Abilitato", + "settings.mfa_disabled": "Disabilitato", + "settings.mfa_google_help": "Proteggi l’account con Google Authenticator o un’altra app TOTP. Per iniziare serve la password corrente.", + "settings.current_password": "Password corrente", + "settings.mfa_start": "Configura Google Authenticator", + "settings.mfa_secret": "Chiave di configurazione manuale", + "settings.mfa_scan_help": "Scansiona il QR con Google Authenticator e inserisci il codice corrente a 6 cifre per abilitare MFA.", + "settings.mfa_code": "Codice a 6 cifre", + "settings.mfa_enable": "Attiva MFA", + "settings.mfa_manage_help": "Per modificare MFA, inserisci password corrente e codice Authenticator o di recupero.", + "settings.mfa_code_or_recovery": "Codice Authenticator o di recupero", + "settings.mfa_regenerate": "Nuovi codici di recupero", + "settings.mfa_disable": "Disattiva MFA", + "settings.mfa_recovery_title": "Codici di recupero", + "settings.mfa_recovery_help": "Salva questi codici ora. Ognuno può essere usato una volta se Google Authenticator non è disponibile. Non verranno mostrati di nuovo.", + "settings.mfa_recovery_remaining": "Codici di recupero rimanenti: {count}", + "settings.mfa_enabled_ok": "MFA attivata.", + "settings.mfa_disabled_ok": "MFA disattivata.", + "settings.mfa_disable_confirm": "Disattivare l’autenticazione a due fattori per questo account?", + "settings.mfa_regenerate_confirm": "Sostituire tutti i codici di recupero esistenti?", + "settings.mfa_recovery_regenerated": "Nuovi codici di recupero creati.", + "audit.action.auth.mfa_failed": "Verifica MFA non riuscita", + "audit.action.auth.mfa_recovery_used": "Codice di recupero MFA utilizzato", + "audit.action.user.mfa_setup_started": "Configurazione MFA avviata", + "audit.action.user.mfa_enabled": "MFA attivata", + "audit.action.user.mfa_disabled": "MFA disattivata", + "audit.action.user.mfa_disabled_cli": "MFA disattivata da CLI", + "audit.action.user.mfa_recovery_regenerated": "Codici di recupero MFA rigenerati", + "settings.mfa_error_password": "Password corrente non valida.", + "settings.mfa_error_code": "Codice di autenticazione non valido.", + "settings.mfa_error_already_enabled": "MFA è già attiva.", + "settings.mfa_error_not_enabled": "MFA non è attiva.", + "settings.mfa_error_not_started": "Riavvia la configurazione MFA.", + "trace.title": "Traceroute, ping e mappa del percorso", + "trace.subtitle": "Misura la latenza verso un VPS o altro server e individua i ritardi lungo il percorso.", + "trace.target": "IP o nome host del server", + "trace.show_map": "Mostra percorso sulla mappa", + "trace.run": "Avvia traceroute", + "trace.geo_note": "La geolocalizzazione è approssimativa. Con la mappa attiva, gli IP pubblici degli hop vengono inviati a ipwho.is; le mappe sono caricate da OpenStreetMap.", + "trace.latency_note": "Traceroute misura la latenza in millisecondi, non la velocità in Mbit/s.", + "trace.map": "Mappa del percorso", + "trace.map_hint": "Mappa interattiva: trascina per spostare, usa la rotella o +/− per lo zoom e clicca un hop per i dettagli.", + "trace.hop": "Hop / IP", + "trace.location": "Posizione", + "trace.avg_rtt": "RTT medio", + "trace.delta": "Δ RTT", + "trace.loss": "Perdita", + "trace.summary_target": "Destinazione", + "trace.summary_ping": "Ping medio", + "trace.summary_loss": "Perdita ping", + "trace.summary_hops": "Hop", + "trace.no_reply": "Nessuna risposta", + "trace.private": "Rete privata", + "trace.unknown": "Sconosciuto", + "trace.running": "Ping e traceroute in corso… L’operazione può durare un minuto.", + "trace.done": "Tracciamento di rete completato.", + "trace.failed": "Tracciamento di rete non riuscito", + "trace.partial_geo": "Impossibile geolocalizzare alcuni hop pubblici.", + "trace.not_reached": "Destinazione non raggiunta dal traceroute.", + "trace.reached": "Destinazione raggiunta", + "trace.ms": "ms", + "server.tab_trace": "Tracciamento", + "trace.map_controls": "Controlli mappa", + "trace.zoom_in": "Ingrandisci", + "trace.zoom_out": "Riduci", + "trace.fit_route": "Adatta al percorso", + "trace.fit": "Adatta", + "trace.map_click_hint": "Clicca un hop per visualizzare IP, posizione, ASN e RTT.", + "trace.route_path": "Percorso", + "trace.ping_ok_trace_filtered": "La destinazione risponde al ping, ma gli ultimi hop del traceroute non rispondono.", + "trace.latency_legend": "Aumento della latenza tra hop che rispondono", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normale", + "trace.latency_warn": "Δ RTT 5–20 ms — elevato", + "trace.latency_bad": "Δ RTT > 20 ms — forte aumento" +} diff --git a/app/locales/pl.json b/app/locales/pl.json new file mode 100644 index 0000000..ff5fd67 --- /dev/null +++ b/app/locales/pl.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Utwórz użytkownika", + "auth.login_subtitle": "Podaj nazwę użytkownika i hasło WGTools.", + "auth.login_title": "Zaloguj się do WGTools", + "auth.password": "Hasło", + "auth.password_repeat": "Powtórz hasło", + "auth.setup_help": "Pierwsze konto ma pełny dostęp do WGTools. Kolejnych użytkowników można dodać później w ustawieniach.", + "auth.setup_subtitle": "Przed zarządzaniem serwerem trzeba utworzyć konto WGTools.", + "auth.setup_title": "Utwórz pierwszego użytkownika", + "auth.sign_in": "Zaloguj", + "auth.sign_out": "Wyloguj", + "auth.username": "Nazwa użytkownika", + "clients.actions": "Akcje", + "clients.add": "+ Dodaj klienta", + "clients.address": "Adres VPN", + "clients.address_hint": "Pierwszy wolny adres jest proponowany automatycznie.", + "clients.allowed_ips_required": "Podaj przynajmniej jedną sieć AllowedIPs dla konfiguracji klienta.", + "clients.basic_connection": "Ustawienia połączenia", + "clients.basic_details": "Klient", + "clients.client": "Klient", + "clients.client_allowed_ips": "AllowedIPs w konfiguracji klienta", + "clients.config_private_warning": "Ta konfiguracja zawiera klucz prywatny klienta. Przechowuj ją bezpiecznie.", + "clients.config_title": "Konfiguracja klienta", + "clients.config_unavailable": "Konfiguracja niedostępna", + "clients.connection_direct": "Bezpośrednio do WGTools", + "clients.connection_path": "Ścieżka połączenia", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Połącz przez", + "clients.connection_via_hint": "Wybierz publiczny punkt wejścia dla klienta. Relay jest widoczny tylko po instalacji dla wybranego interfejsu WireGuard.", + "clients.copy_config": "Kopiuj", + "clients.copy_done": "Skopiowano konfigurację", + "clients.create_subtitle": "Utwórz peer WireGuard i wygeneruj jego konfigurację.", + "clients.create_title": "Utwórz klienta", + "clients.creating": "Generowanie kluczy i stosowanie konfiguracji klienta…", + "clients.day_fri": "Pt", + "clients.day_mon": "Pon", + "clients.day_sat": "Sob", + "clients.day_sun": "Niedz", + "clients.day_thu": "Czw", + "clients.day_tue": "Wt", + "clients.day_wed": "Śr", + "clients.delete_confirm": "Usunąć tego klienta z WireGuard? WGTools utworzy kopię i usunie powiązane reguły automatyczne.", + "clients.deleted": "Klient usunięty", + "clients.dns": "DNS (opcjonalnie)", + "clients.dns_hint": "Serwery DNS IPv4 rozdzielone przecinkami.", + "clients.download_config": "Pobierz .conf", + "clients.duplicate": "Duplikuj", + "clients.duplicate_address_error": "Ten adres VPN jest już używany przez innego peera.", + "clients.duplicate_name_error": "Peer o tej nazwie już istnieje.", + "clients.duplicate_ready": "Kopia gotowa. WGTools przydzielił nową nazwę i adres VPN. Sprawdź ustawienia przed zapisaniem.", + "clients.duplicate_site_hint": "Sieci zdalne wyczyszczono, aby uniknąć zduplikowanych tras. Podaj sieci dla nowego peera Site-to-site.", + "clients.duplicate_suffix": "kopia", + "clients.edit_subtitle": "Zaktualizuj peer na serwerze. Zmiany są stosowane bez restartu WireGuard.", + "clients.edit_title": "Edytuj klienta", + "clients.endpoint": "Endpoint serwera", + "clients.endpoint_hint": "Dla klientów zdalnych użyj publicznego IP lub domeny przekierowującej port WireGuard na ten serwer.", + "clients.existing": "Istniejący peer", + "clients.expiration": "Czas ważności dostępu", + "clients.expiration_action": "Po wygaśnięciu", + "clients.expiration_action_hint": "Jeśli opcja nie jest zaznaczona, klient zostanie w WGTools, ale utraci dostęp WireGuard. Ustaw nowy termin lub Bez terminu i zapisz, aby przywrócić dostęp.", + "clients.expiration_datetime": "Wygasa dnia", + "clients.expiration_datetime_hint": "Używa lokalnej daty i godziny przeglądarki.", + "clients.expiration_delete": "Usuń klienta", + "clients.expiration_future_required": "Wybierz przyszłą datę i godzinę.", + "clients.expiration_hint": "Po wygaśnięciu WGTools wykonuje wybraną akcję na początku następnej minuty. Najpierw tworzy kopię WireGuard.", + "clients.expire_1d": "1 dzień", + "clients.expire_1h": "1 godzina", + "clients.expire_3h": "3 godziny", + "clients.expire_6h": "6 godzin", + "clients.expire_custom": "Własna data i godzina", + "clients.expire_never": "Bez terminu wygaśnięcia", + "clients.expired": "Wygasło", + "clients.expired_disabled_hint": "Okres dostępu wygasł. Klient pozostał, ale dostęp WireGuard jest wyłączony. Ustaw nowy termin lub Bez terminu i zapisz.", + "clients.expired_disabled_short": "Wygasło · wyłączono", + "clients.expired_disabled_status": "Wygasło", + "clients.expires_days": "Wygasa za {n} dni", + "clients.expires_hours": "Wygasa za {n} godz.", + "clients.expires_minutes": "Wygasa za {n} min", + "clients.generated_config": "Wygenerowana konfiguracja klienta", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 sekund to dobry domyślny czas dla klientów za NAT.", + "clients.local_access_exceptions": "Dozwolone adresy lokalne", + "clients.local_access_exceptions_hint": "Opcjonalne adresy IP lub CIDR dostępne nawet wtedy, gdy ich sieć lokalna lub Site-to-site jest zablokowana. Oddziel przecinkami.", + "clients.managed": "Zarządzany przez WGTools", + "clients.name": "Nazwa", + "clients.no_peers": "Nie znaleziono peerów", + "clients.peers": "Peery", + "clients.peers_subtitle": "Zmiany są archiwizowane i stosowane przez wg syncconf bez restartu interfejsu WireGuard.", + "clients.protected_networks_reference": "Zablokowane sieci lokalne (informacja)", + "clients.protected_networks_reference_hint": "Te sieci nie są wpisywane do AllowedIPs. Dostęp blokują zasady serwera WGTools; poszczególne adresy można dopuścić powyżej.", + "clients.psk": "Klucz współdzielony (PSK)", + "clients.psk_enable": "Używaj dodatkowego klucza współdzielonego WireGuard", + "clients.psk_hint": "Zalecane. Dodaje dodatkowy sekret symetryczny do handshake WireGuard. Standardowe klienty go obsługują; WGTools dołącza PSK do konfiguracji i QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generowanie kodu QR…", + "clients.quick_search": "Szybkie wyszukiwanie", + "clients.quick_search_clear": "Wyczyść wyszukiwanie", + "clients.quick_search_empty": "Brak pasujących klientów", + "clients.relay_endpoint_note": "Wygenerowana konfiguracja klienta połączy się z {endpoint}. Serwer WireGuard pozostaje na tym hoście WGTools.", + "clients.relay_required": "Wybierz VPS Relay dla tego klienta.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "niedostępny", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "Endpoint klienta jest generowany automatycznie na podstawie Relay.", + "clients.remote_hint": "Sieci za tym peerem. Jedna w wierszu lub rozdzielone przecinkami.", + "clients.remote_networks": "Sieci zdalne", + "clients.remote_required": "Podaj co najmniej jedną sieć zdalną dla peera Site-to-site.", + "clients.required": "Nazwa i adres VPN są wymagane.", + "clients.route_custom": "Własne", + "clients.route_full": "Pełny tunel", + "clients.route_full_except_local": "Pełny tunel bez sieci lokalnych", + "clients.route_hint": "Tylko te sieci zostaną wpisane do AllowedIPs konfiguracji klienta.", + "clients.route_preset": "Ruch przez VPN", + "clients.route_vpn": "Tylko sieć VPN", + "clients.route_vpn_lan": "VPN + lokalny LAN", + "clients.saved": "Klient zapisany", + "clients.schedule_blocked_short": "Harmonogram · blokada", + "clients.schedule_blocked_status": "Zablokowano przez harmonogram", + "clients.schedule_days": "Dozwolone dni", + "clients.schedule_days_required": "Wybierz co najmniej jeden dzień harmonogramu.", + "clients.schedule_disabled_hint": "Ten klient jest obecnie blokowany harmonogramem. WGTools automatycznie przywróci peera w następnym dozwolonym okresie.", + "clients.schedule_enable": "Ogranicz dostęp harmonogramem", + "clients.schedule_from": "Dostęp od", + "clients.schedule_hint": "WGTools może automatycznie wyłączać i przywracać klienta w wybrane dni i godziny bez zmiany konfiguracji.", + "clients.schedule_short": "Harmonogram", + "clients.schedule_time_required": "Ustaw godzinę początku i końca harmonogramu.", + "clients.schedule_timezone_hint": "Harmonogram używa lokalnego czasu serwera WireGuard. Obsługuje przedziały przez północ, np. 22:00–06:00.", + "clients.schedule_title": "Harmonogram dostępu", + "clients.schedule_to": "Dostęp do", + "clients.security_access": "Bezpieczeństwo i czas dostępu", + "clients.server_host": "Adres / domena serwera", + "clients.server_host_hint": "Publiczny IP lub domena używane przez klienta. Wcześniejsze wartości są proponowane.", + "clients.server_host_required": "Adres / domena serwera są wymagane do wygenerowania konfiguracji.", + "clients.server_peer": "Peer serwera", + "clients.server_port": "Port WireGuard", + "clients.server_port_hint": "Pobierany automatycznie z konfiguracji serwera.", + "clients.site_to_site": "Sieć do sieci", + "clients.status": "Status", + "clients.subtitle": "Peery WireGuard, stan na żywo i zarządzanie konfiguracjami klientów.", + "clients.tab_basic": "Podstawowe", + "clients.tab_config": "Konfiguracja", + "clients.tab_policy": "Zasady", + "clients.tab_security": "Bezpieczeństwo", + "clients.title": "Klienci", + "clients.type": "Typ", + "clients.unmanaged_note": "Peer istniał przed WGTools. Nie da się odzyskać jego klucza prywatnego. WGTools może edytować peera na serwerze, ale nie wygeneruje jego konfiguracji ani QR.", + "clients.updating": "Aktualizacja klienta…", + "common.actions": "Akcje", + "common.ago": "temu", + "common.cancel": "Anuluj", + "common.checking": "Sprawdzanie…", + "common.close": "Zamknij", + "common.config": "Konfiguracja", + "common.delete": "Usuń", + "common.disabled": "Wyłączone", + "common.edit": "Edytuj", + "common.enabled": "Włączone", + "common.loading": "Ładowanie…", + "common.never": "Nigdy", + "common.no": "Nie", + "common.not_configured": "Nie skonfigurowano", + "common.not_installed": "Nie zainstalowano", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Odśwież", + "common.running": "Działa", + "common.save": "Zapisz", + "common.stopped": "Zatrzymano", + "common.total": "Łącznie", + "common.unknown": "Nieznany", + "common.updated": "Zaktualizowano", + "common.yes": "Tak", + "dashboard.active_peers": "Aktywne peery", + "dashboard.active_peers_subtitle": "Dane na żywo z wg show.", + "dashboard.activity": "Przegląd systemu", + "dashboard.activity_subtitle": "Kontrole działającego WireGuard bez wprowadzania zmian.", + "dashboard.cores": "rdzenie", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Ostatnie 24 godz.", + "dashboard.history_avg": "Śr.", + "dashboard.history_max": "Maks.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "teraz", + "dashboard.memory": "Pamięć", + "dashboard.network": "Sieć", + "dashboard.peers": "Peery", + "dashboard.quick_search": "Szybkie wyszukiwanie", + "dashboard.quick_search_clear": "Wyczyść wyszukiwanie", + "dashboard.quick_search_empty": "Brak peerów pasujących do wyszukiwania", + "dashboard.restart": "Uruchom ponownie", + "dashboard.restart_confirm": "Uruchomić WireGuard ponownie? Aktywni klienci VPN połączą się automatycznie.", + "dashboard.restart_ok": "WireGuard uruchomiono ponownie.", + "dashboard.routing": "Trasowanie", + "dashboard.site_to_site": "Sieć do sieci", + "dashboard.start": "Uruchom", + "dashboard.start_ok": "Uruchomiono WireGuard.", + "dashboard.stop": "Zatrzymaj", + "dashboard.stop_confirm": "Zatrzymać WireGuard? Aktywni klienci VPN zostaną rozłączeni.", + "dashboard.stop_ok": "Zatrzymano WireGuard.", + "dashboard.subtitle": "Stan serwera WireGuard, peery i ruch na żywo.", + "dashboard.title": "Pulpit", + "dashboard.traffic": "Ruch", + "dashboard.uptime": "Czas działania", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Zasady dostępu do serwera", + "groups.additional_allowed": "Dodatkowe dozwolone adresy", + "groups.additional_blocked": "Dodatkowe blokowane adresy", + "groups.allow": "Zezwól", + "groups.allowed": "Dozwolone", + "groups.allowed_addresses": "Dozwolone adresy / sieci", + "groups.apply_current_template": "Zastosuj bieżący szablon grupy", + "groups.apply_defaults": "Zastosuj bieżący szablon grupy", + "groups.apply_defaults_hint": "Kopiuje trasy, DNS i Keepalive z szablonu grupy do klienta. Zapisz klienta, a następnie wygeneruj nową konfigurację lub QR, jeśli urządzenie wymaga aktualizacji.", + "groups.basic": "Informacje podstawowe", + "groups.block": "Blokuj", + "groups.blocked": "Zablokowane", + "groups.blocked_addresses": "Zablokowane adresy / sieci", + "groups.client_config_source": "Źródło konfiguracji klienta", + "groups.client_defaults": "Domyślne ustawienia klienta", + "groups.client_group_hint": "Opcjonalna grupa do ponownego użycia zasad dostępu i ustawień klienta. Grupy dotyczą wybranego interfejsu WireGuard.", + "groups.config_differs": "Konfiguracja klienta różni się od bieżącego szablonu grupy. Zasady serwera są aktualne, ale urządzenie wymaga nowej konfiguracji lub kodu QR.", + "groups.config_differs_short": "Konfiguracja klienta różni się od grupy", + "groups.create": "Utwórz grupę", + "groups.create_title": "Utwórz grupę", + "groups.created": "Utworzono grupę", + "groups.creating": "Tworzenie grupy…", + "groups.defaults_applied": "Zastosowano szablon grupy. Zapisz klienta, aby zachować zmiany.", + "groups.defaults_hint": "Określa ruch wysyłany przez urządzenie przez WireGuard. Zasady serwera niezależnie decydują o dostępie. Zmiana szablonu nie zmienia automatycznie konfiguracji już zainstalowanych.", + "groups.delete_message": "Usunąć „{name}”? Konfiguracje klientów nie są usuwane wraz z grupą.", + "groups.delete_move": "Przenieś klientów do innej grupy", + "groups.delete_title": "Usuń grupę klientów", + "groups.delete_unassign": "Usuń przypisanie klientów do grupy", + "groups.deleted": "Usunięto grupę", + "groups.deleting": "Aktualizacja klientów i usuwanie grupy…", + "groups.description": "Opis", + "groups.edit_title": "Edytuj grupę", + "groups.editor_subtitle": "Grupa łączy aktywne zasady dostępu do serwera z szablonem konfiguracji klientów.", + "groups.effective_allow": "Dozwolone wyjątki", + "groups.effective_deny": "Zablokowane wyjątki", + "groups.effective_policy": "Obowiązujące zasady serwera", + "groups.empty": "Brak grup klientów. Utwórz grupę, aby ponownie wykorzystywać zasady dostępu i ustawienia.", + "groups.group": "Grupa", + "groups.inherit": "Dziedzicz", + "groups.internet_access": "Dostęp do Internetu", + "groups.internet_short": "Internet", + "groups.local_access": "Sieci lokalne", + "groups.local_short": "Lokalnie", + "groups.manage": "Grupy", + "groups.members_count": "Klienci: {count}", + "groups.name": "Nazwa", + "groups.name_required": "Nazwa grupy jest wymagana.", + "groups.new_client_defaults": "Szablon konfiguracji klienta", + "groups.new_clients_short": "Nowi klienci", + "groups.no_group": "Brak grupy", + "groups.none": "Brak", + "groups.override_client_config": "Nadpisz szablon grupy dla tego klienta", + "groups.override_client_config_hint": "Wyłączone: trasy, DNS i Keepalive pochodzą z grupy. Włączone: klient zachowuje własne wartości. Wyjątki zasad serwera działają niezależnie.", + "groups.policy_addresses_hint": "Adresy IPv4 lub CIDR rozdzielone przecinkami. Wyjątki klienta mają pierwszeństwo przed wyjątkami grupy.", + "groups.policy_custom": "Własne zasady", + "groups.policy_inherit": "Użyj zasad grupy", + "groups.policy_mode": "Źródło zasad", + "groups.policy_mode_hint": "Domyślnie dziedziczone są zasady grupy. Wyjątki klienta nigdy nie modyfikują grupy.", + "groups.routes_required": "Trasy klienta nie mogą być puste.", + "groups.subtitle": "Korzystaj ponownie z zasad dostępu i ustawień klientów na wybranym interfejsie WireGuard.", + "groups.title": "Grupy klientów", + "groups.traffic_through_vpn": "Ruch przez VPN", + "groups.updated": "Zaktualizowano grupę", + "groups.updating": "Aktualizacja zasad grupy…", + "help.example_note": "Wszystkie adresy, interfejsy, nazwy peerów i domeny w przykładach pomocy są fikcyjne. Zastąp je danymi swojej sieci.", + "help.navigation": "Nawigacja pomocy", + "help.open": "Otwórz pomoc", + "help.subtitle": "Przystępna pomoc dotycząca panelu, serwera, klientów i ustawień z krótkimi przykładami.", + "help.title": "Pomoc WGTools", + "interfaces.add": "+ Dodaj interfejs", + "interfaces.create": "Utwórz interfejs", + "interfaces.create_confirm": "Utworzyć i uruchomić interfejs {name}?", + "interfaces.create_failed": "Nie udało się utworzyć interfejsu", + "interfaces.create_hint": "Przed utworzeniem konfiguracji WGTools sprawdza, czy sieć VPN, port UDP i tablica routingu nie kolidują z innymi interfejsami WireGuard.", + "interfaces.create_subtitle": "Utwórz niezależny interfejs WireGuard z własną pulą adresów, portem UDP i ustawieniami routingu.", + "interfaces.create_title": "Dodaj interfejs WireGuard", + "interfaces.created": "Pomyślnie utworzono interfejs.", + "interfaces.creating": "Generowanie kluczy, zapisywanie konfiguracji i uruchamianie WireGuard…", + "interfaces.current": "Bieżący", + "interfaces.delete": "Usuń", + "interfaces.delete_confirm": "Usunąć interfejs {name}? Zostanie usunięta jego konfiguracja WireGuard oraz wszystkie peery. Najpierw powstanie kopia zapasowa.", + "interfaces.delete_failed": "Nie udało się usunąć interfejsu", + "interfaces.delete_last": "Nie można tutaj usunąć ostatniego skonfigurowanego interfejsu WireGuard.", + "interfaces.delete_tooltip": "Usuń ten interfejs WireGuard", + "interfaces.deleted": "Usunięto interfejs. Kopia: {backup}", + "interfaces.deleting": "Zatrzymywanie WireGuard i usuwanie interfejsu…", + "interfaces.display_name": "Nazwa wyświetlana", + "interfaces.display_name_edit_hint": "Tylko nazwa wyświetlana; nazwa interfejsu Linux nie zmieni się.", + "interfaces.display_name_hint": "Opcjonalna przyjazna nazwa, np. Praca lub Wykonawcy.", + "interfaces.identity": "Tożsamość interfejsu", + "interfaces.none": "Nie znaleziono interfejsów WireGuard", + "interfaces.none_configured": "Nie skonfigurowano jeszcze żadnego interfejsu WireGuard.", + "interfaces.peers_short": "peery", + "interfaces.rename_failed": "Nie udało się zapisać nazwy wyświetlanej interfejsu.", + "interfaces.select": "Wybierz", + "interfaces.subtitle": "Każdy interfejs ma własną sieć VPN, port, peery i reguły. Wybierz interfejs, aby zarządzać nim w WGTools.", + "interfaces.switch_title": "Interfejsy WireGuard", + "interfaces.system_name": "Nazwa systemowa", + "interfaces.system_name_hint": "Nazwa interfejsu Linux, np. wg1. Nie można jej zmienić po utworzeniu.", + "interfaces.title": "Interfejsy WireGuard", + "interfaces.unique_port_hint": "Każdy interfejs WireGuard na tym serwerze musi używać osobnego portu UDP.", + "interfaces.unique_table_hint": "WGTools zaleca osobną tablicę routingu dla każdego interfejsu. Pozostaw puste przy zwykłym routingu.", + "nav.clients": "Klienci", + "nav.dashboard": "Pulpit", + "nav.server": "Serwer", + "nav.settings": "Ustawienia", + "server.access_apply_confirm": "Zapisać i zastosować tę regułę zapory? WireGuard zostanie na krótko uruchomiony ponownie po wykonaniu kopii.", + "server.access_rule_deleted": "Usunięto regułę dostępu.", + "server.access_rule_help": "Utwórz regułę dostępu FORWARD bez ręcznej edycji poleceń iptables.", + "server.access_rule_order_hint": "WGTools wstawia reguły na początek łańcucha FORWARD, aby ograniczenia działały przed ogólnymi regułami VPN ACCEPT.", + "server.access_rule_saved": "Zapisano i zastosowano regułę dostępu.", + "server.action": "Akcja", + "server.action_hint": "REJECT informuje klienta o odmowie; DROP odrzuca bez odpowiedzi; ACCEPT jawnie zezwala.", + "server.add_access_rule": "Dodaj regułę dostępu", + "server.add_route": "Dodaj trasę", + "server.address": "Adres", + "server.any": "Dowolny", + "server.any_protocol": "Dowolny", + "server.apply_confirm": "Zapisać i zastosować ustawienia serwera? WireGuard zostanie na krótko uruchomiony ponownie. WGTools najpierw utworzy kopię i automatycznie przywróci konfigurację w razie błędu.", + "server.apply_settings": "Zapisz i zastosuj", + "server.applying_rule": "Tworzenie kopii i stosowanie zmian…", + "server.applying_settings": "Weryfikacja ustawień, tworzenie kopii i stosowanie zmian…", + "server.basic_settings": "Ustawienia podstawowe", + "server.config_tab_help": "Otwórz edytor źródłowej konfiguracji wybranego interfejsu WireGuard.", + "server.create_confirm": "Utworzyć i uruchomić serwer WireGuard z tymi ustawieniami?", + "server.create_server": "Utwórz serwer", + "server.create_step_conf": "Utwórz konfigurację wybranego interfejsu WireGuard z uprawnieniami 600.", + "server.create_step_forward": "Skonfiguruj forwarding, NAT i opcjonalny routing oparty na regułach.", + "server.create_step_key": "Wygeneruj nową parę kluczy serwera.", + "server.create_step_start": "Włącz i uruchom wybrany interfejs wg-quick.", + "server.create_subtitle": "WireGuard jest zainstalowany, ale wybrany interfejs nie jest skonfigurowany.", + "server.create_success": "Pomyślnie utworzono serwer WireGuard.", + "server.create_title": "Utwórz serwer WireGuard", + "server.creating": "Generowanie kluczy, zapisywanie konfiguracji i uruchamianie WireGuard…", + "server.custom_preserved": "Bloki peerów, trasy Site-to-site i niestandardowe reguły PostUp/PostDown poza tymi polami zostaną zachowane.", + "server.delete_access_confirm": "Usunąć tę regułę dostępu i zastosować zmianę?", + "server.delete_route_confirm": "Usunąć tę własną trasę i zastosować zmianę?", + "server.destination": "Cel", + "server.destination_hint": "Puste = dowolny. IP, CIDR lub zakres adresów. Oddziel wiele celów przecinkami.", + "server.destination_port": "Port docelowy", + "server.destination_port_hint": "Opcjonalnie. Port np. 443 lub zakres 10000:20000. Najpierw wybierz TCP lub UDP.", + "server.details": "Szczegóły", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostyka", + "server.diagnostics_done": "Diagnostyka zakończona", + "server.diagnostics_subtitle": "Bieżące kontrole systemu. Konfiguracja nie jest zmieniana.", + "server.direction": "Hook", + "server.edit_access_rule": "Edytuj regułę dostępu", + "server.edit_route": "Edytuj trasę", + "server.edit_server": "Edytuj serwer", + "server.edit_subtitle": "Edytuj podstawowe ustawienia WireGuard, routingu i NAT. Istniejące peery i własne reguły zostają zachowane.", + "server.edit_title": "Ustawienia serwera", + "server.edit_warning": "Zastosowanie ustawień interfejsu, routingu lub zapory na krótko restartuje WireGuard. Aktywne peery połączą się ponownie.", + "server.enable_forwarding": "Włącz przekazywanie IPv4", + "server.enable_nat": "Włącz NAT / Masquerade", + "server.firewall": "Zapora i NAT", + "server.firewall_subtitle": "Reguły wykryte w hookach WireGuard.", + "server.firewall_subtitle_v08": "Reguły forwarding/NAT i dostępu z konfiguracji interfejsu. Proste reguły edytujesz tutaj, zaawansowane w edytorze źródłowym.", + "server.forward_from_vpn": "Zezwól na przekazywanie z VPN", + "server.forward_to_vpn": "Zezwól na przekazywanie do VPN", + "server.forwarding_section": "Przekazywanie i NAT", + "server.gateway": "Brama", + "server.gateway_hint": "Wymagana tylko przy korzystaniu z tablicy routingu regułowego.", + "server.install_success": "Pomyślnie zainstalowano WireGuard.", + "server.install_wireguard": "Zainstaluj WireGuard", + "server.install_wireguard_help": "Uruchamia apt update i instaluje WireGuard oraz wymagane narzędzia sieciowe.", + "server.install_wireguard_title": "Zainstaluj WireGuard", + "server.installing": "Instalowanie WireGuard… Może potrwać minutę.", + "server.interface": "Interfejs", + "server.interface_hint": "WGTools zarządza obecnie tym interfejsem.", + "server.interface_name": "Interfejs", + "server.interface_section": "Interfejs WireGuard", + "server.ip_forwarding": "Przekazywanie IPv4", + "server.kind": "Rodzaj", + "server.listen_port": "Port nasłuchiwania", + "server.local_network": "Sieć lokalna", + "server.local_network_hint": "Opcjonalna trasa dodawana do tablicy reguł routingu.", + "server.managed_automatically": "Zarządzane automatycznie", + "server.nat": "NAT / Masquerade", + "server.network": "Sieć", + "server.network_settings": "Sieć i NAT", + "server.no_firewall": "Nie znaleziono reguł zapory", + "server.no_routes": "Nie znaleziono tras", + "server.not_configured": "Nie skonfigurowano", + "server.not_set": "Nie ustawiono", + "server.policy_disabled_hint": "Wyłącz dla zwykłego routingu systemowego. Włącz tylko jeśli ten VPN wymaga osobnej tablicy routingu według źródła.", + "server.policy_enabled": "Włącz routing regułowy", + "server.policy_table": "Tablica reguł", + "server.policy_table_hint": "Dla zwykłego routingu pozostaw puste; np. 200 dla routingu według źródła.", + "server.port_word": "port", + "server.private_hidden": "Skonfigurowano (ukryto)", + "server.private_key": "Klucz prywatny", + "server.protocol": "Protokół", + "server.route_apply_confirm": "Zapisać i zastosować tę trasę? WireGuard zostanie na krótko uruchomiony ponownie po utworzeniu kopii.", + "server.route_custom": "Własna", + "server.route_deleted": "Usunięto trasę.", + "server.route_device_hint": "Opcjonalny interfejs wyjściowy, np. wg0 lub enp6s18.", + "server.route_editor_help": "Dodaj trasę instalowaną przy uruchomieniu WireGuard i usuwaną po zatrzymaniu.", + "server.route_gateway_hint": "Opcjonalna brama następnego skoku. Wymagana jest brama lub interfejs.", + "server.route_managed_peer": "Peer Site-to-site", + "server.route_managed_server": "Ustawienie serwera", + "server.route_network_hint": "Sieć IPv4, np. 10.20.0.0/24, lub 'default'.", + "server.route_saved": "Zapisano i zastosowano trasę.", + "server.route_table_hint": "Użyj 'main' dla zwykłego routingu albo numerycznej tablicy np. 200.", + "server.route_type": "Typ", + "server.routes": "Wykryte trasy", + "server.routes_subtitle": "Trasy z PostUp/PostDown i aktualnego stanu routingu regułowego.", + "server.routes_subtitle_v08": "Trasy serwera, Site-to-site i własne z wybranego interfejsu. Własne trasy można tu dodawać, edytować i usuwać.", + "server.routing": "Trasowanie", + "server.routing_section": "Trasowanie", + "server.rule": "Reguła", + "server.rule_access": "Reguła dostępu", + "server.rule_advanced": "Zaawansowane", + "server.rule_apply_warning": "Zastosowanie trasy lub reguły zapory na krótko restartuje WireGuard. WGTools tworzy kopię i przywraca konfigurację automatycznie w razie błędu.", + "server.rule_client_exception": "Wyjątek klienta", + "server.rule_client_policy": "Zasada klienta", + "server.rule_managed_server": "Ustawienie serwera", + "server.rule_type": "Typ", + "server.run_diagnostics": "Uruchom diagnostykę", + "server.save_apply": "Zapisz i zastosuj", + "server.save_config": "SaveConfig", + "server.server_address": "Adres VPN serwera", + "server.server_address_hint": "Zwykle pierwszy użyteczny adres w sieci VPN.", + "server.settings_applied": "Pomyślnie zapisano i zastosowano ustawienia serwera.", + "server.settings_apply_failed": "Nie udało się zastosować ustawień serwera", + "server.setup_required": "Wymagana konfiguracja", + "server.source": "Źródło", + "server.source_hint": "Puste = dowolny. IP, CIDR lub zakres np. 10.0.0.100-10.0.0.120.", + "server.subtitle": "Instalacja, pierwsza konfiguracja i bieżące ustawienia serwera WireGuard.", + "server.tab_config": "Konfiguracja", + "server.tab_interface": "Interfejs", + "server.tab_routing": "Trasowanie", + "server.tab_vps": "VPS", + "server.table": "Tabela", + "server.tabs_aria": "Sekcje ustawień serwera", + "server.title": "Serwer", + "server.uplink": "Interfejs uplink", + "server.use_raw_editor": "Użyj edytora źródłowego", + "server.via": "Przez / urządzenie", + "server.via_word": "via", + "server.vpn_network": "Sieć VPN", + "server.vpn_network_hint": "Adresy klientów będą później przydzielane z tej sieci.", + "server.vpn_pool": "Pula adresów VPN", + "server.wg_not_installed": "WireGuard nie jest zainstalowany", + "server.wg_not_installed_subtitle": "WGTools może automatycznie zainstalować wymagane pakiety Debiana.", + "server.what_happens": "Co zrobi WGTools", + "settings.about": "O programie", + "settings.add_user": "Dodaj użytkownika", + "settings.advanced": "Zaawansowane", + "settings.advanced_subtitle": "Bezpośredni dostęp do zaawansowanych narzędzi konfiguracji WireGuard.", + "settings.appearance": "Wygląd", + "settings.applying_config": "Weryfikacja konfiguracji, tworzenie kopii i stosowanie zmian…", + "settings.backup_count": "Zapisane kopie", + "settings.backup_retention": "Liczba kopii", + "settings.backup_retention_help": "Stare automatyczne kopie są usuwane po utworzeniu nowej. Od 1 do 200 plików.", + "settings.backups": "Kopie konfiguracji", + "settings.backups_always_on": "Włączone", + "settings.backups_subtitle": "WGTools tworzy automatyczne kopie przed operacjami zmieniającymi konfigurację. Nie można ich wyłączyć.", + "settings.change_password": "Zmień hasło", + "settings.check_updates": "Sprawdź aktualizacje", + "settings.config_applied": "Pomyślnie zapisano i zastosowano konfigurację.", + "settings.config_applied_restarted": "Zastosowano konfigurację i uruchomiono ponownie WireGuard.", + "settings.config_applied_stopped": "Zapisano konfigurację. WireGuard był zatrzymany i pozostał zatrzymany.", + "settings.config_apply_failed": "Nie udało się zastosować konfiguracji", + "settings.config_load_failed": "Nie udało się wczytać konfiguracji", + "settings.current_user": "Bieżący użytkownik", + "settings.current_version": "Bieżąca wersja", + "settings.audit_action": "Akcja", + "settings.audit_empty": "Brak zdarzeń audytu", + "settings.audit_log": "Dziennik audytu", + "settings.audit_log_subtitle": "Działania w panelu, logowanie, Telegram i historia połączeń klientów WireGuard. Sekrety nie są zapisywane.", + "settings.audit_object": "Obiekt", + "settings.audit_result": "Wynik", + "settings.audit_retention_note": "Przechowywanie: 30 dni", + "settings.audit_search": "Szybkie wyszukiwanie", + "settings.audit_search_clear": "Wyczyść wyszukiwanie", + "settings.audit_search_empty": "Brak zdarzeń audytu pasujących do wyszukiwania", + "settings.audit_time": "Data / godzina", + "settings.audit_user": "Użytkownik", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Utworzono regułę dostępu", + "audit.action.access_rule.deleted": "Usunięto regułę dostępu", + "audit.action.access_rule.updated": "Zaktualizowano regułę dostępu", + "audit.action.auth.first_user_created": "Utworzono pierwszego użytkownika", + "audit.action.auth.login": "Zalogowano", + "audit.action.auth.login_failed": "Logowanie nie powiodło się", + "audit.action.auth.logout": "Wylogowano", + "audit.action.backup.full_created": "Utworzono pełną kopię zapasową", + "audit.action.backup.full_restored": "Przywrócono pełną kopię zapasową", + "audit.action.client.config_downloaded": "Pobrano konfigurację klienta", + "audit.action.client.config_viewed": "Wyświetlono konfigurację klienta", + "audit.action.client.created": "Utworzono klienta", + "audit.action.client.deleted": "Klient usunięty", + "audit.action.client.qr_viewed": "Wyświetlono kod QR klienta", + "audit.action.client.updated": "Zaktualizowano klienta", + "audit.action.client_group.created": "Utworzono grupę klientów", + "audit.action.client_group.deleted": "Usunięto grupę klientów", + "audit.action.client_group.updated": "Zaktualizowano grupę klientów", + "audit.action.interface.created": "Utworzono interfejs", + "audit.action.interface.deleted": "Usunięto interfejs", + "audit.action.interface.renamed": "Zmieniono nazwę interfejsu", + "audit.action.route.created": "Utworzono trasę", + "audit.action.route.deleted": "Usunięto trasę", + "audit.action.route.updated": "Zaktualizowano trasę", + "audit.action.server.created": "Utworzono serwer", + "audit.action.server.raw_config_applied": "Zastosowano konfigurację źródłową", + "audit.action.server.settings_applied": "Zastosowano ustawienia serwera", + "audit.action.settings.updated": "Zaktualizowano ustawienia panelu", + "audit.action.telegram.action_denied": "Odrzucono akcję Telegram", + "audit.action.telegram.action_failed": "Akcja Telegram nie powiodła się", + "audit.action.telegram.connection_test": "Test połączenia Telegram", + "audit.action.telegram.settings_updated": "Zaktualizowano ustawienia Telegram", + "audit.action.update.checked": "Sprawdzono aktualizację", + "audit.action.update.scheduled": "Zaplanowano aktualizację", + "audit.action.update.backup_created": "Kopia przed aktualizacją", + "audit.action.update.completed": "Zakończono aktualizację", + "audit.action.update.failed": "Aktualizacja nie powiodła się", + "audit.action.update.rollback_completed": "Przywrócono poprzednią wersję", + "audit.action.update.rollback_failed": "Nie udało się cofnąć aktualizacji", + "audit.action.user.created": "Utworzono użytkownika", + "audit.action.user.deleted": "Usunięto użytkownika", + "audit.action.user.password_changed": "Zmieniono hasło użytkownika", + "audit.action.vps.candidate_deleted": "Usunięto kandydata VPS", + "audit.action.vps.candidate_saved": "Zapisano kandydata VPS", + "audit.action.vps.detached": "Odłączono VPS Relay", + "audit.action.vps.relay_installed": "Zainstalowano VPS Relay", + "audit.action.wireguard.client_connected": "Połączono klienta WireGuard", + "audit.action.wireguard.installed": "Zainstalowano WireGuard", + "audit.action.wireguard.restarted": "Uruchomiono WireGuard ponownie", + "audit.action.wireguard.started": "Uruchomiono WireGuard", + "audit.action.wireguard.stopped": "Zatrzymano WireGuard", + "audit.result.applied": "zastosowano", + "audit.result.available": "dostępna", + "audit.result.changed": "zmieniono", + "audit.result.created": "utworzono", + "audit.result.current": "aktualna", + "audit.result.deleted": "usunięto", + "audit.result.detached": "odłączono", + "audit.result.denied": "odrzucono", + "audit.result.downloaded": "pobrano", + "audit.result.endpoint": "Punkt końcowy", + "audit.result.error": "Błąd", + "audit.result.installed": "zainstalowano", + "audit.result.invalid_credentials": "nieprawidłowe dane logowania", + "audit.result.ok": "OK", + "audit.result.queued": "w kolejce", + "audit.result.restarted": "uruchomiono ponownie", + "audit.result.restored": "przywrócono", + "audit.result.rotated": "odnowiono", + "audit.result.saved": "zapisano", + "audit.result.shown": "wyświetlono", + "audit.result.started": "uruchomiono", + "audit.result.stopped": "zatrzymano", + "audit.result.updated": "zaktualizowano", + "settings.delete_user": "Usuń", + "settings.delete_user_confirm": "Usunąć użytkownika {name}?", + "settings.edit_raw_config": "Edytuj konfigurację interfejsu", + "settings.expert_mode": "Ekspert", + "settings.full_backup_component_clients": "Metadane klientów WGTools, klucze prywatne, PSK, terminy ważności i grupy wymagane do odtworzenia konfiguracji oraz QR.", + "settings.full_backup_component_db": "Baza WGTools: użytkownicy, preferencje, poczta/SMTP, Telegram i zapisany stan VPS Relay.", + "settings.full_backup_component_relay": "Dane odzyskiwania VPS Relay: identyfikatory kontrolera i tenanta, token zarządzania oraz klucz transportowy Home. Po przywróceniu WGTools może odbudować lokalny transport i połączyć zachowany tenant.", + "settings.full_backup_component_system": "Plik sysctl przekazywania IPv4 WGTools, nazwy wyświetlane interfejsów oraz zasady i szablony grup, jeśli istnieją. Automatyczna historia konfiguracji interfejsów jest celowo pomijana.", + "settings.full_backup_component_wg": "Wszystkie wykryte konfiguracje interfejsów WireGuard z /etc/wireguard/ wraz ze stanem działania.", + "settings.full_backup_create_failed": "Nie udało się utworzyć pełnej kopii", + "settings.full_backup_creating": "Tworzenie pełnej kopii zapasowej…", + "settings.full_backup_download": "Utwórz", + "settings.full_backup_downloaded": "Kopia utworzona i pobrana. Przechowuj ją bezpiecznie.", + "settings.full_backup_downloaded_short": "Pobrano pełną kopię.", + "settings.full_backup_help": "Tworzy przenośną kopię WGTools do migracji lub odzyskiwania: konfiguracje WireGuard, użytkownicy, ustawienia, grupy, dane klientów i informacje potrzebne do ponownego połączenia tenantów VPS Relay.", + "settings.full_backup_no_file": "Nie wybrano kopii", + "settings.full_backup_restore": "Przywróć", + "settings.full_backup_restore_confirm": "Przywrócić pełną kopię WGTools? Użytkownicy, ustawienia, zarządzani klienci i konfiguracje WireGuard z kopii zostaną przywrócone. Interfejsy mogą zostać zrestartowane. WGTools najpierw utworzy kopię bezpieczeństwa i automatycznie cofnie zmiany w razie błędu.", + "settings.full_backup_restore_failed": "Przywracanie nie powiodło się", + "settings.full_backup_restored": "Pomyślnie przywrócono kopię. Zaloguj się kontem z przywróconej kopii.", + "settings.full_backup_restored_short": "Przywrócono kopię.", + "settings.full_backup_restoring": "Weryfikacja kopii, tworzenie zabezpieczenia i przywracanie…", + "settings.full_backup_secret_warning": "Plik zawiera dane poufne: klucze prywatne WireGuard i klientów, PSK, skróty haseł WGTools, token bota Telegram i zapisane hasło SMTP. Chroń go jak hasło i nigdy nie dołączaj do publicznych zgłoszeń ani czatów.", + "settings.full_backup_select": "Wybierz", + "settings.full_backup_title": "Pełna kopia i przywracanie", + "settings.full_mode": "Włączono zarządzanie serwerem i klientami", + "settings.interface_help": "Zarządzany interfejs WireGuard wybiera się podczas wdrożenia WGTools.", + "settings.language": "Język", + "settings.last_backup": "Ostatnia kopia", + "settings.latest_version": "Najnowsza wersja", + "settings.loading_config": "Wczytywanie konfiguracji…", + "settings.mode": "Tryb", + "settings.never_logged_in": "Nigdy", + "settings.new_password": "Nowe hasło", + "settings.no_backups": "Brak kopii zapasowych", + "settings.online_help": "Peer jest online, jeśli jego ostatni handshake jest młodszy niż ta wartość. 30–3600 sekund.", + "settings.online_threshold": "Próg online", + "settings.open_release": "Otwórz wydanie", + "settings.password_changed": "Zmieniono hasło.", + "settings.passwords_mismatch": "Hasła nie są zgodne.", + "settings.project_github": "Projekt / GitHub", + "settings.raw_config_confirm": "Zapisać i zastosować konfigurację WireGuard? Wybrany interfejs zostanie zrestartowany. Najpierw powstanie kopia; WGTools automatycznie przywróci poprzedni stan w razie błędu.", + "settings.raw_config_help": "Otwórz źródłową konfigurację wybranego interfejsu WireGuard.", + "settings.raw_config_title": "Źródłowa konfiguracja WireGuard", + "settings.raw_config_warning": "Tryb eksperta: to rzeczywista konfiguracja serwera WireGuard zawierająca klucz prywatny i PSK peerów. Zapisanie i zastosowanie restartuje interfejs. WGTools najpierw tworzy kopię i przywraca stan w razie błędu.", + "settings.readonly_mode": "Włączono zarządzanie klientami", + "settings.refresh_help": "Częstotliwość odświeżania stanu przez WGTools. Od 2 do 60 sekund.", + "settings.refresh_interval": "Interwał odświeżania", + "settings.release_notes": "Informacje o wydaniu", + "settings.reload_config": "Wczytaj ponownie z dysku", + "settings.save_apply": "Zapisz i zastosuj", + "settings.saved": "Zapisano ustawienia.", + "settings.saved_reload": "Zapisano ustawienia. Ponowne wczytywanie…", + "settings.saving": "Zapisywanie ustawień…", + "settings.status": "Odświeżanie statusu", + "settings.status_help": "Ustawienia odświeżania panelu i stanu peerów.", + "settings.subtitle": "Preferencje interfejsu i ustawienia stanu WGTools.", + "settings.syntax_hint": "Sekcje, klucze, wartości i komentarze WireGuard są podświetlane podczas edycji.", + "settings.tab_about": "O programie", + "settings.tab_backups": "Kopie zapasowe", + "settings.tab_general": "Ogólne", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Użytkownicy", + "settings.tabs_aria": "Sekcje ustawień", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "Dozwolone identyfikatory użytkowników Telegram", + "settings.telegram_allowed_ids_help": "Jeden liczbowy identyfikator na wiersz. Nieautoryzowane /start odpowie identyfikatorem Telegram nadawcy, aby dodać go tutaj.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Połączono", + "settings.telegram_disabled": "Wyłączone", + "settings.telegram_dns": "Domyślny DNS klienta", + "settings.telegram_dns_help": "Opcjonalne adresy DNS IPv4 rozdzielone przecinkami. Dla klientów utworzonych przez bota.", + "settings.telegram_enabled": "Włącz bota Telegram", + "settings.telegram_endpoint": "Domyślny adres / domena serwera", + "settings.telegram_endpoint_help": "Używany przy tworzeniu klienta przez bota. Podaj tylko IP lub domenę; port WireGuard jest pobierany z konfiguracji serwera.", + "settings.telegram_language": "Język bota", + "settings.telegram_language_auto": "Automatycznie (język Telegram)", + "settings.telegram_last_poll": "Ostatni kontakt z Telegram", + "settings.telegram_not_configured": "Nie skonfigurowano", + "settings.telegram_remove_token": "Usuń token", + "settings.telegram_remove_token_confirm": "Usunąć zapisany token bota Telegram i wyłączyć bota?", + "settings.telegram_save": "Zapisz ustawienia Telegram", + "settings.telegram_saved": "Zapisano ustawienia Telegram.", + "settings.telegram_setup_note": "Utwórz bota w @BotFather, zapisz token, włącz bota i wyślij /start. Jeśli identyfikator nie jest autoryzowany, WGTools go pokaże — dodaj go do listy dozwolonych ID.", + "settings.telegram_status": "Status bota", + "settings.telegram_subtitle": "Zdalne zarządzanie WireGuard przez Telegram: stan serwera, klienci, tworzenie/usuwanie i start/restart/stop.", + "settings.telegram_test": "Testuj połączenie", + "settings.telegram_test_ok": "Połączenie Telegram działa: @{username}", + "settings.telegram_test_recent_ok": "Bot Telegram działa. Test bezpośredni przekroczył limit czasu, ale bot kontaktował się z Telegram niedawno.", + "settings.telegram_token": "Token bota", + "settings.telegram_token_help": "Utwórz bota w @BotFather i wklej tutaj token Bot API. API ID i API Hash nie są potrzebne.", + "settings.telegram_token_keep": "Pozostaw puste, aby zachować zapisany token.", + "settings.telegram_waiting": "Skonfigurowano, oczekiwanie na usługę bota", + "settings.theme": "Motyw", + "settings.theme_dark": "Ciemny", + "settings.theme_light": "Jasny", + "settings.theme_system": "System", + "settings.title": "Ustawienia", + "settings.update_available": "Dostępna aktualizacja", + "settings.update_backup_queued": "Aktualizacja w kolejce. WGTools przed instalacją wykona automatycznie pełną kopię…", + "settings.update_backup_running": "Tworzenie pełnej kopii przed aktualizacją…", + "settings.update_check_failed": "Nie udało się sprawdzić aktualizacji", + "settings.update_checking": "Sprawdzanie najnowszego wydania GitHub…", + "settings.update_confirm": "Zaktualizować WGTools z v{current} do v{latest}? Najpierw powstaną pełna kopia i kopia do wycofania zmian. Panel na chwilę uruchomi się ponownie.", + "settings.update_current": "Aktualna wersja", + "settings.update_downloading": "Pobieranie i weryfikowanie wydania GitHub…", + "settings.update_failed": "Aktualizacja WGTools nie powiodła się.", + "settings.update_installing": "Instalowanie aktualizacji. Panel może być przez chwilę niedostępny…", + "settings.update_no_update": "WGTools ma już najnowszą wersję.", + "settings.update_not_checked": "Nie sprawdzono", + "settings.update_queued": "Aktualizacja w kolejce. Oczekiwanie na usługę aktualizacji…", + "settings.update_rollback_ok": "Automatycznie przywrócono poprzednią wersję WGTools.", + "settings.update_rolling_back": "Aktualizacja nie powiodła się. Przywracanie poprzedniej wersji WGTools…", + "settings.update_running": "Tworzenie kopii bezpieczeństwa…", + "settings.update_safety_hint": "Aktualizacje są uruchamiane na życzenie. WGTools najpierw tworzy pełną kopię i kopię do wycofania. W razie błędu przywraca poprzednią aplikację. Sam WireGuard nie jest restartowany, chyba że nowe wydanie wyraźnie zmienia jego konfigurację.", + "settings.update_sidebar": "Dostępna nowa wersja", + "settings.update_sidebar_hint": "Ustawienia → Informacje", + "settings.update_starting": "Uruchamianie aktualizacji…", + "settings.update_status_unknown": "Stan aktualizacji niedostępny. Ponawianie…", + "settings.update_subtitle": "Wgraj zaufany pakiet wydania WGTools-Extended w formacie .bin.", + "settings.update_success": "Pomyślnie zaktualizowano WGTools do v{version}. Ponowne wczytywanie…", + "settings.update_wgtools": "Zaktualizuj WGTools", + "settings.user_actions": "Akcje", + "settings.user_created": "Utworzono", + "settings.user_created_ok": "Utworzono użytkownika.", + "settings.user_deleted": "Usunięto użytkownika.", + "settings.user_equal_rights": "Uprawnienia sieciowe są przypisywane przez administratora.", + "settings.user_last_login": "Ostatnie logowanie", + "settings.user_name": "Nazwa użytkownika", + "settings.users": "Użytkownicy", + "settings.users_subtitle": "Lokalne konta WGTools. E-mail jest opcjonalny i służy jedynie do odzyskiwania hasła po włączeniu poczty.", + "vps.add": "Dodaj VPS", + "vps.add_help": "WGTools używa SSH do sprawdzania lub instalacji Relay. Hasła i prywatne klucze SSH nigdy nie są zapisywane.", + "vps.add_title": "Dodaj VPS", + "vps.agent": "Agent Relay", + "vps.agent_found": "Już zainstalowany", + "vps.agent_will_install": "Zostanie zainstalowany", + "vps.arch": "Architektura", + "vps.auth_method": "Uwierzytelnianie", + "vps.authentication": "Uwierzytelnianie SSH", + "vps.check": "Sprawdź VPS", + "vps.check_failed": "Sprawdzanie VPS nie powiodło się", + "vps.check_link": "Sprawdź połączenie", + "vps.check_ok": "VPS zgodny", + "vps.checking": "Sprawdzanie dostępu SSH i zgodności VPS…", + "vps.connections": "połączenia", + "vps.credentials_not_saved": "Używane tylko do tej kontroli, nie są zapisywane przez WGTools.", + "vps.delete_candidate": "Usuń", + "vps.delete_installed": "Usuń VPS", + "vps.delete_installed_confirm": "Usunąć „{name}” z WGTools? Lokalny transport Relay zostanie rozłączony, ale agent i tenant na VPS pozostaną. Po ponownym dodaniu VPS WGTools połączy się z istniejącym Relay, zamiast tworzyć nowy. Klienci nie połączą się przez Relay do czasu ponownego podłączenia.", + "vps.delete_installed_failed": "Nie udało się usunąć VPS z WGTools", + "vps.delete_installed_ok": "Usunięto VPS z WGTools. Zdalny Relay zachowano i można go ponownie połączyć.", + "vps.empty_help": "Dodaj VPS Debian lub Ubuntu, aby sprawdzić SSH, zgodność systemu i wymagane porty UDP.", + "vps.empty_title": "Brak skonfigurowanego VPS", + "vps.endpoint": "Publiczny endpoint", + "vps.endpoint_domain": "Domena (zalecana)", + "vps.endpoint_domain_hint": "Przy późniejszej zmianie głównego VPS zmiana DNS pozwoli zachować dotychczasowe konfiguracje klientów.", + "vps.health_failed": "Sprawdzanie połączenia Relay nie powiodło się", + "vps.host": "IP / nazwa hosta", + "vps.host_key": "Klucz hosta SSH", + "vps.identity": "Połączenie VPS", + "vps.install_failed": "Instalacja Relay nie powiodła się", + "vps.install_ok": "Zainstalowano Relay i zweryfikowano chronione połączenie zarządzania", + "vps.install_relay": "Zainstaluj Relay", + "vps.install_title": "Zainstaluj VPS Relay", + "vps.installed": "Zainstalowano", + "vps.installing": "Instalowanie agenta Relay i zestawianie chronionego tunelu…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Hasło klucza", + "vps.link_ok": "Połączenie Relay OK", + "vps.multi_tenant_note": "Na tym VPS działa już agent WGTools Relay. Nie zostanie zastąpiony: ten WGTools otrzyma odizolowane połączenie z własnymi kluczami i portami UDP.", + "vps.name": "Nazwa", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Zostanie zainstalowany", + "vps.os": "System operacyjny", + "vps.password": "Hasło", + "vps.phase_note": "Agent Relay obsługuje wiele niezależnych kontrolerów WGTools na jednym VPS. Każdy ma osobne połączenie, klucze i porty UDP; istniejące połączenia pozostają bez zmian.", + "vps.port_pair": "Porty UDP", + "vps.ports_adjusted": "wybrano wolne porty", + "vps.private_key": "Klucz prywatny", + "vps.privilege": "Uprawnienia", + "vps.public_endpoint": "Przyszły publiczny endpoint", + "vps.ready_help": "Dane SSH służą wyłącznie do sprawdzenia zgodności i natychmiastowej instalacji Relay; nie są zapisywane.", + "vps.reconnect_note": "Na VPS znaleziono istniejące połączenie Relay utworzone przez ten WGTools. Zostanie ponownie połączony ten sam tenant bez tworzenia nowego lub portów UDP.", + "vps.reconnect_ok": "Pomyślnie połączono z istniejącym Relay", + "vps.reconnect_relay": "Połącz Relay ponownie", + "vps.relay_port": "Port UDP Relay", + "vps.remove_confirm": "Usunąć tego kandydata VPS? Nie wprowadzono zmian na serwerze zdalnym.", + "vps.save_candidate": "Zapisz kandydata", + "vps.saved": "Zapisano kandydata VPS", + "vps.ssh": "SSH", + "vps.ssh_key": "Klucz SSH", + "vps.ssh_port": "Port SSH", + "vps.ssh_user": "Użytkownik SSH", + "vps.status_candidate": "Gotowy do instalacji", + "vps.status_installed": "Relay połączony", + "vps.subtitle": "Przygotuj publiczny VPS do zdalnego dostępu, gdy ten serwer WGTools nie ma publicznego IP.", + "vps.tenant": "Połączenie", + "vps.title": "VPS Relay", + "vps.transport_port": "Port UDP transportu", + "vps.transport_port_hint": "Osobny port UDP dla prywatnego tunelu transportowego Dom ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Zapisano", + "vps.active_short": "Aktywny", + "dashboard.traffic_reset": "Resetuj", + "dashboard.traffic_reset_confirm": "Zresetować liczniki ruchu WireGuard tego interfejsu? Liczniki klientów również zaczną od zera.", + "dashboard.traffic_reset_done": "Zresetowano liczniki ruchu", + "dashboard.traffic_reset_failed": "Nie udało się zresetować liczników ruchu", + "audit.action.traffic.reset": "Zresetowano liczniki ruchu", + "audit.result.reset": "zresetowano", + "server.mtu": "MTU", + "server.mtu_auto": "Automatycznie", + "server.mtu_hint": "Opcjonalnie. Pozostaw puste dla automatycznego MTU wg-quick. Ustaw np. 1380 lub 1420 tylko gdy wymaga tego LTE lub PPPoE.", + "clients.peer_isolation": "Izolacja klientów VPN", + "clients.peer_isolation_enable": "Izoluj od innych klientów VPN", + "clients.peer_isolation_hint": "Blokuje ruch między tym klientem a innymi adresami puli WireGuard. Dostęp do serwera, Internetu i sieci lokalnych lub Site-to-site nadal zależy od pozostałych zasad.", + "clients.credentials_rotate": "Klucze klienta", + "clients.credentials_rotate_button": "Odnów klucze", + "clients.credentials_rotate_confirm": "Wygenerować nowe klucze klienta? Jeśli jest połączony, jego sesja WireGuard zostanie natychmiast przerwana. Następnie wyślij nową konfigurację lub QR.", + "clients.credentials_rotate_confirm_psk": "Wygenerować nową parę kluczy i PSK? Aktywna sesja WireGuard klienta zostanie natychmiast przerwana. Następnie wyślij nową konfigurację lub QR.", + "clients.credentials_rotate_hint": "Odnawia PrivateKey/PublicKey, a przy włączonym PSK również PSK. Adres, trasy, grupa, harmonogram, izolacja i statystyki pozostają bez zmian.", + "clients.credentials_rotating": "Generowanie nowych kluczy i rozłączanie starej sesji…", + "clients.credentials_rotated": "Zmieniono klucze klienta. Aktywną sesję rozłączono. Stara konfiguracja już nie działa; przed ponownym połączeniem prześlij nową lub kod QR.", + "clients.credentials_rotated_short": "Klucze zmienione — wymagana nowa konfiguracja", + "audit.action.client.credentials_rotated": "Odnowiono klucze klienta", + "clients.credentials_connection_lost": "Przerwano połączenie z WGTools. Jeśli panel otwarto przez klienta, którego klucze odnowiono, to normalne: stara sesja WireGuard została od razu rozłączona. Połącz się inną drogą i wygeneruj nową konfigurację lub QR.", + "nav.navigation": "Nawigacja główna", + "nav.project_github": "WGTools na GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Na razie opcjonalny. Po skonfigurowaniu poczty może służyć do odzyskiwania hasła.", + "auth.forgot_password": "Nie pamiętasz hasła?", + "auth.reset_title": "Zresetuj hasło", + "auth.reset_subtitle": "Odbierz jednorazowy kod e-mailem i ustaw nowe hasło WGTools.", + "auth.reset_identifier": "Nazwa użytkownika lub e-mail", + "auth.reset_identifier_help": "Dla ochrony prywatności WGTools zawsze pokazuje tę samą odpowiedź niezależnie od istnienia konta.", + "auth.send_reset_code": "Wyślij kod", + "auth.reset_code_sent_generic": "Jeśli konto istnieje i ma adres e-mail, wysłano kod resetowania ważny przez 15 minut.", + "auth.reset_code": "Kod 6-cyfrowy", + "auth.set_new_password": "Ustaw nowe hasło", + "auth.request_another_code": "Poproś o nowy kod", + "auth.back_to_login": "Wróć do logowania", + "auth.reset_not_configured": "Odzyskiwanie hasła e-mailem nie jest skonfigurowane. Skontaktuj się z administratorem WGTools.", + "settings.tab_mail": "Poczta", + "settings.mail": "Poczta / SMTP", + "settings.mail_subtitle": "SMTP służy do odzyskiwania hasła.", + "settings.mail_not_configured": "Nie skonfigurowano", + "settings.mail_enabled": "Włącz pocztę i odzyskiwanie hasła", + "settings.mail_smtp_host": "Serwer SMTP", + "settings.mail_smtp_port": "Port SMTP", + "settings.mail_security": "Szyfrowanie", + "settings.mail_security_none": "Bez szyfrowania", + "settings.mail_username": "Użytkownik SMTP", + "settings.mail_username_help": "Używane do logowania SMTP i jako adres e-mail nadawcy.", + "settings.mail_password": "Hasło SMTP", + "settings.mail_password_keep": "Pozostaw puste, aby zachować zapisane hasło.", + "settings.mail_from_email": "E-mail nadawcy", + "settings.mail_from_name": "Nazwa nadawcy", + "settings.mail_test_recipient": "Odbiorca testowy", + "settings.mail_test_recipient_help": "Test używa aktualnie zapisanych ustawień SMTP.", + "settings.mail_remove_password": "Usuń hasło", + "settings.mail_test": "Wyślij test", + "settings.mail_save": "Zapisz ustawienia poczty", + "settings.mail_enabled_badge": "Włączone", + "settings.mail_disabled_badge": "Wyłączone", + "settings.mail_saved": "Zapisano ustawienia poczty.", + "settings.mail_remove_password_confirm": "Usunąć zapisane hasło SMTP i wyłączyć pocztę?", + "settings.mail_password_removed": "Usunięto hasło SMTP i wyłączono pocztę.", + "settings.mail_test_recipient_required": "Podaj adres e-mail odbiorcy testowego.", + "settings.mail_testing": "Wysyłanie testowego e-maila…", + "settings.mail_test_ok": "Pomyślnie wysłano testowy e-mail.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Opcjonalny. Wymagany tylko do samodzielnego odzyskiwania hasła.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "Zapisano e-mail.", + "settings.send_password_reset": "Wyślij reset", + "settings.user_reset_mail_not_configured": "Najpierw skonfiguruj i włącz pocztę.", + "settings.user_reset_email_missing": "Najpierw dodaj adres e-mail.", + "settings.user_reset_confirm": "Wysłać kod resetowania hasła do {name} na {email}?", + "settings.user_reset_sent": "Wysłano kod resetowania hasła na {email}.", + "audit.action.auth.password_reset_requested": "Zażądano resetowania hasła", + "audit.action.auth.password_reset_code_sent": "Wysłano kod resetowania hasła", + "audit.action.auth.password_reset_completed": "Zresetowano hasło", + "audit.action.auth.password_reset_failed": "Resetowanie hasła nie powiodło się", + "audit.action.mail.settings_updated": "Zaktualizowano ustawienia poczty", + "audit.action.mail.test_sent": "Wysłano testowy e-mail", + "audit.action.mail.test_failed": "Nie udało się wysłać testowego e-maila", + "audit.action.user.email_changed": "Zmieniono e-mail użytkownika", + "audit.action.user.password_reset_sent": "Wysłano resetowanie hasła użytkownika", + "audit.action.user.password_reset_failed": "Resetowanie hasła użytkownika nie powiodło się", + "audit.result.accepted": "zaakceptowano", + "audit.result.sent": "wysłano", + "audit.result.invalid_code": "nieprawidłowy kod", + "common.copy": "Kopiuj", + "common.copied": "Skopiowano", + "clients.use_panel_host": "Użyj adresu panelu", + "clients.use_panel_host_done": "Wstawiono adres panelu: {host}", + "clients.use_panel_host_failed": "Nie udało się ustalić adresu panelu z URL przeglądarki.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Wbudowany HTTPS Let’s Encrypt do bezpośredniego dostępu do WGTools bez reverse proxy.", + "settings.https_disabled": "Wyłączone", + "settings.https_enabled": "Włączone", + "settings.https_enable": "Włącz wbudowany HTTPS", + "settings.https_type": "Certyfikat dla", + "settings.https_domain": "Domena", + "settings.https_public_ip": "Publiczny IP", + "settings.https_target": "Domena lub publiczny IP", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "Port HTTPS", + "settings.https_port80_note": "Port TCP 80 musi być dostępny z Internetu do wydania i odnawiania certyfikatu. Otwórz też wybrany port HTTPS panelu.", + "settings.https_check_ports": "Sprawdź porty", + "settings.https_certificate": "Certyfikat", + "settings.https_certificate_ready": "Gotowy", + "settings.https_certificate_missing": "Nie wydano", + "settings.https_expires": "Ważny do", + "settings.https_renewal": "Automatyczne odnawianie", + "settings.https_renewal_enabled": "Włączone", + "settings.https_renewal_disabled": "Wyłączone", + "settings.https_certificate_path": "Certyfikat", + "settings.https_private_key_path": "Klucz prywatny", + "settings.https_issue": "Uzyskaj / odnów certyfikat", + "settings.https_port_free": "Wolny", + "settings.https_port_busy": "Zajęty", + "settings.https_ports_checked": "Zakończono sprawdzanie portów.", + "settings.https_target_email_required": "Podaj domenę/publiczny IP i e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Uzyskać lub odnowić certyfikat Let’s Encrypt dla {target}? Ustawienia HTTPS zostaną zapisane. Port TCP 80 musi być dostępny z Internetu.", + "settings.https_issuing": "Pobieranie certyfikatu z Let’s Encrypt…", + "settings.https_issue_ok": "Certyfikat gotowy.", + "settings.https_already_enabled": "Wbudowany HTTPS jest już włączony.", + "settings.https_already_disabled": "Wbudowany HTTPS jest już wyłączony.", + "settings.https_enable_confirm": "Włączyć wbudowany HTTPS na TCP {port} ze ścieżką {path}? WGTools uruchomi się ponownie, a strona połączy z nowym adresem.", + "settings.https_disable_confirm": "Wyłączyć wbudowany HTTPS i wrócić do HTTP?", + "settings.https_switching": "Włączanie HTTPS i ponowne uruchamianie WGTools…", + "settings.https_switching_http": "Wyłączanie HTTPS i ponowne uruchamianie WGTools…", + "audit.action.https.certificate_issued": "Wydano certyfikat HTTPS", + "audit.action.https.certificate_failed": "Nie udało się uzyskać certyfikatu HTTPS", + "audit.action.https.enabled": "Włączono HTTPS", + "audit.action.https.disabled": "Wyłączono HTTPS", + "audit.result.issued": "wydano", + "audit.result.enabled": "włączono", + "audit.result.disabled": "wyłączono", + "settings.https_access_path": "Ścieżka dostępu do panelu", + "settings.https_access_path_help": "Wybierz własną ścieżkę. Przy wbudowanym HTTPS żądania poza nią zwracają 404.", + "settings.https_enable_fields_required": "Podaj domenę/publiczny IP, e-mail Let’s Encrypt i ścieżkę panelu.", + "settings.https_use_panel_host": "Użyj adresu panelu", + "settings.https_reconnecting": "WGTools przełącza się na nowy adres HTTPS…", + "server.tab_nodes": "Węzły", + "common.type": "Typ", + "common.status": "Status", + "common.copy_failed": "Nie udało się skopiować", + "clients.vpn_address": "Adres VPN", + "nodes.title": "Węzły WGTools", + "nodes.subtitle": "Połącz serwery WGTools w jedną chronioną sieć i publikuj tylko sieci dostępne dla innych węzłów.", + "nodes.enable_hub": "Włącz HUB", + "nodes.connect_hub": "Połącz z HUB", + "nodes.settings": "Ustawienia węzła", + "nodes.settings_action": "Ustawienia", + "nodes.sync_now": "Synchronizuj", + "nodes.disable": "Wyłącz węzły", + "nodes.disable_action": "Rozłącz", + "nodes.join_title": "Połącz nowe węzły", + "nodes.join_help": "Utwórz jednorazowy kod i wpisz go w drugim panelu WGTools wraz z endpointem usługi HUB, np. vpn.example.com:51950. Kod jest ważny 15 minut i można go użyć tylko raz.", + "nodes.create_code": "Utwórz kod", + "nodes.connected_nodes": "Połączone węzły", + "nodes.connected_nodes_help": "Informacje o innych panelach, publikowanych sieciach i klientach. Klienci zdalni są tylko do odczytu.", + "nodes.enable_hub_help": "Ten panel stanie się węzłem centralnym. Na tym samym porcie HUB odbiera WireGuard przez UDP i chronione pierwsze parowanie przez TCP.", + "nodes.node_name": "Nazwa węzła", + "nodes.transport_network": "Sieć transportowa węzłów", + "nodes.transport_help": "Osobna sieć prywatna tylko do komunikacji WGTools ↔ WGTools. Nie może pokrywać się z sieciami VPN/LAN.", + "nodes.panel_url": "URL panelu", + "nodes.panel_url_help": "Opcjonalnie. To tylko link dla przycisku „Otwórz panel” na innych węzłach; nie służy do łączenia Nodes.", + "nodes.extra_networks": "Dodatkowe sieci węzła", + "nodes.extra_networks_help": "Jedna sieć w wierszu. Sieci VPN interfejsów i zdalne sieci Site-to-site są publikowane automatycznie. Dodaj tylko inne routowane sieci LAN, np. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools uzupełnia wykryte sieci VPN, Site-to-site i routowane LAN. Pozostaw tylko sieci przeznaczone do publikacji. Jedna na wiersz.", + "nodes.published_networks_settings_help": "Jedna sieć na wiersz. To jawna lista sieci publikowanych przez węzeł. Usunięcie wiersza zatrzymuje ogłaszanie sieci innym węzłom.", + "nodes.available_networks_help": "Wykryte sieci: {networks}. Nowe sieci nie są publikowane automatycznie; dodaj potrzebne powyżej.", + "nodes.available_networks_none": "Nie wykryto dodatkowych sieci lokalnych.", + "nodes.connect_help": "Podaj endpoint usługi HUB i kod jednorazowy. URL panelu, port HTTPS, certyfikat i prywatna ścieżka nie są używane do parowania Nodes.", + "nodes.join_code": "Kod połączenia", + "nodes.connect_reachability_note": "Pierwsze parowanie korzysta z chronionego TCP na podanym porcie. Po utworzeniu wgnode0 sieci, stan, wersje i dane klientów tylko do odczytu synchronizują się z HUB przez wewnętrzny adres WireGuard.", + "nodes.connect": "Połącz", + "nodes.settings_help": "Nazwa węzła, opcjonalny link „Otwórz panel” i lista publikowanych sieci. URL panelu nie służy do parowania ani synchronizacji.", + "nodes.details": "Szczegóły", + "nodes.not_configured": "WGTools Nodes nieskonfigurowane", + "nodes.not_configured_help": "Włącz HUB w tym panelu lub połącz go z istniejącym WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Połączono z HUB", + "nodes.mode_none": "Nie skonfigurowano", + "nodes.role": "Rola", + "nodes.tunnel": "Tunel węzła", + "nodes.node_ip": "Adres węzła", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Publikowane sieci", + "nodes.last_sync": "Ostatnia synchronizacja", + "nodes.no_nodes_hub": "Nie połączono jeszcze węzłów. Utwórz kod i użyj go w innym panelu WGTools.", + "nodes.no_nodes_spoke": "Nie otrzymano jeszcze informacji o zdalnych węzłach.", + "nodes.clients_short": "Klienci", + "nodes.open_panel": "Otwórz panel", + "nodes.route_conflict": "Konflikt tras", + "nodes.no_published_networks": "Brak publikowanych sieci", + "nodes.load_failed": "Nie udało się wczytać WGTools Nodes", + "nodes.enable_hub_confirm": "Włączyć WGTools HUB i utworzyć wewnętrzny tunel WireGuard Nodes?", + "nodes.applying": "Konfigurowanie tunelu WGTools Nodes…", + "nodes.enable_failed": "Nie udało się włączyć HUB", + "nodes.hub_enabled": "Włączono WGTools HUB", + "nodes.connecting": "Weryfikacja kodu HUB i tworzenie chronionego tunelu…", + "nodes.connect_failed": "Nie udało się połączyć z HUB", + "nodes.connected": "Połączono z WGTools HUB", + "nodes.settings_failed": "Nie udało się zapisać ustawień węzła", + "nodes.settings_saved": "Zapisano ustawienia węzła", + "nodes.code_failed": "Nie udało się utworzyć kodu połączenia", + "nodes.code_expires": "Kod jednorazowy. Ważny do {time}.", + "nodes.code_copied": "Skopiowano kod połączenia", + "nodes.network_vpn": "Klienci VPN", + "nodes.network_site_to_site": "Sieć Site-to-site", + "nodes.network_custom": "Dodatkowa sieć", + "nodes.conflict": "Konflikt", + "nodes.remote_clients": "Klienci (tylko odczyt)", + "nodes.no_clients": "Ten węzeł nie zgłasza klientów", + "nodes.details_failed": "Nie udało się pobrać szczegółów węzła", + "nodes.remove_confirm": "Usunąć węzeł „{name}” z HUB? Dostęp do wewnętrznego tunelu zostanie cofnięty.", + "nodes.remove_failed": "Nie udało się usunąć węzła", + "nodes.removed": "Usunięto węzeł", + "nodes.disable_hub_confirm": "Wyłączyć HUB i rozłączyć wszystkie węzły WGTools? Wewnętrzny tunel zostanie usunięty.", + "nodes.disconnect_confirm": "Odłączyć ten panel WGTools od HUB i usunąć wewnętrzny tunel węzła?", + "nodes.disable_failed": "Nie udało się wyłączyć WGTools Nodes", + "nodes.disabled": "Wyłączono WGTools Nodes", + "nodes.sync_failed": "Synchronizacja węzłów nie powiodła się", + "nodes.synced": "Zsynchronizowano informacje węzłów", + "nodes.service_port": "Port Nodes", + "nodes.service_port_help": "Ten sam numer portu służy równocześnie: UDP dla WireGuard i TCP do chronionego parowania.", + "nodes.hub_port_forward_note": "Jeśli HUB jest za NAT, przekieruj ten sam port UDP i TCP. Port web WGTools, HTTPS i prywatna ścieżka panelu nie są powiązane z Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Domena/IP i port Nodes bez http:// lub https://, np. vpn.example.com:51950.", + "settings.collapse_sidebar": "Zwiń pasek boczny", + "settings.expand_sidebar": "Rozwiń panel boczny", + "settings.https_issue_fields_required": "Podaj domenę/publiczny IP, e-mail Let’s Encrypt i ścieżkę panelu.", + "settings.https_issue_ok_saved": "Certyfikat gotowy i ustawienia HTTPS zapisane.", + "settings.https_enable_need_certificate": "Najpierw uzyskaj certyfikat.", + "settings.https_enable_certificate_mismatch": "Najpierw uzyskaj certyfikat dla bieżącej domeny lub IP.", + "settings.https_enable_certificate_expired": "Certyfikat wygasł. Odnów go przed włączeniem HTTPS.", + "settings.https_enable_certificate_ready": "Certyfikat gotowy — można włączyć wbudowany HTTPS.", + "settings.https_enable_active_help": "Odznacz i zapisz, aby wrócić do HTTP.", + "settings.https_certificate_expired": "Wygasł", + "settings.https_certificate_wrong_target": "Dla innego adresu", + "nodes.network_conflict_error": "Publikowane sieci kolidują z innym węzłem lub siecią transportową Nodes: {conflicts}. Usuń lub zmień kolidującą sieć.", + "nodes.networks_changed": "Wykryte sieci zmieniły się od ostatniego zapisu. Nowe: {added}. Niewykrywane: {removed}. Sprawdź listę publikowanych sieci i zapisz ustawienia.", + "nodes.review_networks": "Sprawdź sieci", + "nodes.vpn_pool_mismatch": "Pula VPN zmieniła się: Nodes nadal publikuje {old}, a aktualna pula to {current}. Otwórz ustawienia węzła i zaktualizuj publikowane sieci.", + "server.error_vpn_network_invalid": "Sieć VPN musi być prawidłową siecią IPv4, np. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Obsługiwane są tylko sieci VPN IPv4.", + "server.error_vpn_network_too_small": "Sieć VPN musi zawierać co najmniej dwa użyteczne adresy.", + "server.error_vpn_network_no_hosts": "Wybrana sieć VPN nie ma użytecznych adresów serwera.", + "server.error_server_address_prefix": "Adres VPN serwera musi zawierać prefiks, np. 10.0.0.1/24.", + "server.error_server_address_network": "Adres VPN serwera musi należeć do wybranej puli i mieć ten sam prefiks.", + "server.error_server_address_reserved": "Adres VPN serwera nie może być adresem sieci ani adresem rozgłoszeniowym.", + "server.error_listen_port_number": "Port WireGuard musi być liczbą.", + "server.error_listen_port_range": "Port WireGuard musi mieścić się w zakresie 1–65535.", + "server.error_mtu_number": "MTU musi być liczbą.", + "auth.mfa_title": "Uwierzytelnianie dwuskładnikowe", + "auth.mfa_login_help": "Wprowadź 6-cyfrowy kod z Google Authenticator lub jeden z kodów odzyskiwania.", + "auth.mfa_code": "Kod uwierzytelniania", + "auth.mfa_verify": "Zweryfikuj i zaloguj", + "auth.mfa_back": "Wróć do hasła", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Uwierzytelnianie dwuskładnikowe (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Włączone", + "settings.mfa_disabled": "Wyłączone", + "settings.mfa_google_help": "Chroń konto przez Google Authenticator lub inną aplikację TOTP. Aby zacząć, podaj bieżące hasło.", + "settings.current_password": "Bieżące hasło", + "settings.mfa_start": "Skonfiguruj Google Authenticator", + "settings.mfa_secret": "Ręczny klucz konfiguracji", + "settings.mfa_scan_help": "Zeskanuj QR w Google Authenticator i wpisz aktualny 6-cyfrowy kod, aby włączyć MFA.", + "settings.mfa_code": "Kod 6-cyfrowy", + "settings.mfa_enable": "Włącz MFA", + "settings.mfa_manage_help": "Aby zmienić MFA, podaj bieżące hasło oraz kod Authenticator lub kod odzyskiwania.", + "settings.mfa_code_or_recovery": "Kod Authenticator lub odzyskiwania", + "settings.mfa_regenerate": "Nowe kody odzyskiwania", + "settings.mfa_disable": "Wyłącz MFA", + "settings.mfa_recovery_title": "Kody odzyskiwania", + "settings.mfa_recovery_help": "Zapisz te kody teraz. Każdego można użyć raz, gdy Google Authenticator jest niedostępny. Nie zostaną ponownie pokazane.", + "settings.mfa_recovery_remaining": "Pozostałe kody odzyskiwania: {count}", + "settings.mfa_enabled_ok": "Włączono MFA.", + "settings.mfa_disabled_ok": "Wyłączono MFA.", + "settings.mfa_disable_confirm": "Wyłączyć uwierzytelnianie dwuskładnikowe dla tego konta?", + "settings.mfa_regenerate_confirm": "Zastąpić wszystkie istniejące kody odzyskiwania?", + "settings.mfa_recovery_regenerated": "Utworzono nowe kody odzyskiwania.", + "audit.action.auth.mfa_failed": "Weryfikacja MFA nie powiodła się", + "audit.action.auth.mfa_recovery_used": "Użyto kodu odzyskiwania MFA", + "audit.action.user.mfa_setup_started": "Rozpoczęto konfigurację MFA", + "audit.action.user.mfa_enabled": "Włączono MFA", + "audit.action.user.mfa_disabled": "Wyłączono MFA", + "audit.action.user.mfa_disabled_cli": "Wyłączono MFA przez CLI", + "audit.action.user.mfa_recovery_regenerated": "Wygenerowano ponownie kody odzyskiwania MFA", + "settings.mfa_error_password": "Nieprawidłowe bieżące hasło.", + "settings.mfa_error_code": "Nieprawidłowy kod uwierzytelniania.", + "settings.mfa_error_already_enabled": "MFA jest już włączone.", + "settings.mfa_error_not_enabled": "MFA nie jest włączone.", + "settings.mfa_error_not_started": "Rozpocznij konfigurację MFA ponownie.", + "trace.title": "Traceroute, ping i mapa trasy", + "trace.subtitle": "Zmierz opóźnienie do VPS lub innego serwera i sprawdź, gdzie rośnie na trasie.", + "trace.target": "IP lub nazwa hosta serwera", + "trace.show_map": "Pokaż trasę na mapie", + "trace.run": "Uruchom traceroute", + "trace.geo_note": "Geolokalizacja jest przybliżona. Po włączeniu mapy publiczne IP przeskoków są wysyłane do ipwho.is, a kafelki mapy pobierane z OpenStreetMap.", + "trace.latency_note": "Traceroute mierzy opóźnienia w milisekundach, a nie przepustowość w Mbit/s.", + "trace.map": "Mapa trasy", + "trace.map_hint": "Mapa interaktywna: przeciągnij, aby przesunąć; użyj kółka myszy lub +/− do powiększenia; kliknij przeskok po szczegóły.", + "trace.hop": "Przeskok / IP", + "trace.location": "Lokalizacja", + "trace.avg_rtt": "Śr. RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Straty", + "trace.summary_target": "Cel", + "trace.summary_ping": "Średni ping", + "trace.summary_loss": "Straty ping", + "trace.summary_hops": "Przeskoki", + "trace.no_reply": "Brak odpowiedzi", + "trace.private": "Sieć prywatna", + "trace.unknown": "Nieznany", + "trace.running": "Trwa ping i traceroute… Może to potrwać do minuty.", + "trace.done": "Zakończono śledzenie trasy.", + "trace.failed": "Śledzenie trasy nie powiodło się", + "trace.partial_geo": "Nie udało się ustalić lokalizacji części publicznych przeskoków.", + "trace.not_reached": "Traceroute nie dotarł do celu.", + "trace.reached": "Osiągnięto cel", + "trace.ms": "ms", + "server.tab_trace": "Śledzenie trasy", + "trace.map_controls": "Sterowanie mapą", + "trace.zoom_in": "Powiększ", + "trace.zoom_out": "Pomniejsz", + "trace.fit_route": "Dopasuj trasę", + "trace.fit": "Dopasuj", + "trace.map_click_hint": "Kliknij przeskok, aby zobaczyć IP, lokalizację, ASN i RTT.", + "trace.route_path": "Trasa", + "trace.ping_ok_trace_filtered": "Cel odpowiada na ping, ale ostatnie przeskoki traceroute nie odpowiadają.", + "trace.latency_legend": "Wzrost opóźnienia między odpowiadającymi przeskokami", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normalnie", + "trace.latency_warn": "Δ RTT 5–20 ms — podwyższone", + "trace.latency_bad": "Δ RTT > 20 ms — duży skok" +} diff --git a/app/locales/ru.json b/app/locales/ru.json new file mode 100644 index 0000000..015c465 --- /dev/null +++ b/app/locales/ru.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Создать пользователя", + "auth.login_subtitle": "Введите логин и пароль WGTools.", + "auth.login_title": "Вход в WGTools", + "auth.password": "Пароль", + "auth.password_repeat": "Повторите пароль", + "auth.setup_help": "Первый пользователь получает полный доступ к WGTools. Дополнительных пользователей можно будет создать в Настройках.", + "auth.setup_subtitle": "Перед управлением сервером WGTools нужно создать учетную запись.", + "auth.setup_title": "Создание первого пользователя", + "auth.sign_in": "Войти", + "auth.sign_out": "Выйти", + "auth.username": "Логин", + "clients.actions": "Действия", + "clients.add": "+ Добавить клиента", + "clients.address": "VPN адрес", + "clients.address_hint": "Первый свободный адрес предлагается автоматически.", + "clients.allowed_ips_required": "Укажите хотя бы одну сеть AllowedIPs для конфигурации клиента.", + "clients.basic_connection": "Основные настройки подключения", + "clients.basic_details": "Клиент", + "clients.client": "Клиент", + "clients.client_allowed_ips": "AllowedIPs в клиентском конфиге", + "clients.config_private_warning": "В конфигурации находится приватный ключ клиента. Храни её безопасно.", + "clients.config_title": "Конфигурация клиента", + "clients.config_unavailable": "Конфигурация недоступна", + "clients.connection_direct": "Напрямую к WGTools", + "clients.connection_path": "Точка подключения", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Подключение через", + "clients.connection_via_hint": "Выберите публичную точку входа для этого клиента. Relay показывается только если он установлен для выбранного интерфейса WireGuard.", + "clients.copy_config": "Копировать", + "clients.copy_done": "Конфигурация скопирована", + "clients.create_subtitle": "Создание пира WireGuard и готовой клиентской конфигурации.", + "clients.create_title": "Создать клиента", + "clients.creating": "Генерирую ключи и добавляю клиента…", + "clients.day_fri": "Пт", + "clients.day_mon": "Пн", + "clients.day_sat": "Сб", + "clients.day_sun": "Вс", + "clients.day_thu": "Чт", + "clients.day_tue": "Вт", + "clients.day_wed": "Ср", + "clients.delete_confirm": "Удалить этого клиента из WireGuard? WGTools создаст резервную копию и удалит связанные с этим клиентом автоматически созданные правила политики.", + "clients.deleted": "Клиент удалён", + "clients.dns": "DNS (необязательно)", + "clients.dns_hint": "IPv4-адреса DNS через запятую.", + "clients.download_config": "Скачать .conf", + "clients.duplicate": "Дублировать", + "clients.duplicate_address_error": "Этот VPN-адрес уже используется другим пиром.", + "clients.duplicate_name_error": "Пир с таким именем уже существует.", + "clients.duplicate_ready": "Копия подготовлена. WGTools назначил новое имя и VPN-адрес; проверьте параметры перед сохранением.", + "clients.duplicate_site_hint": "Удалённые сети очищены, чтобы не создать дублирующиеся маршруты. Укажите сети для нового Site-to-site пира.", + "clients.duplicate_suffix": "копия", + "clients.edit_subtitle": "Изменение серверной части пира. Настройки применяются без перезапуска WireGuard.", + "clients.edit_title": "Изменить клиента", + "clients.endpoint": "Адрес сервера для клиента", + "clients.endpoint_hint": "Для удалённых клиентов укажи внешний IP/домен, с которого порт WireGuard проброшен на этот сервер.", + "clients.existing": "Существующий пир", + "clients.expiration": "Срок доступа", + "clients.expiration_action": "После окончания срока", + "clients.expiration_action_hint": "Если выключено, клиент останется в WGTools, но доступ WireGuard будет отключён. Чтобы вернуть доступ, укажите новый срок или «Без ограничения» и сохраните клиента.", + "clients.expiration_datetime": "Доступ до", + "clients.expiration_datetime_hint": "Используется локальная дата и время этого браузера.", + "clients.expiration_delete": "Удалить клиента", + "clients.expiration_future_required": "Укажи дату и время в будущем.", + "clients.expiration_hint": "Когда срок закончится, WGTools выполнит выбранное действие на ближайшей минутной границе. Перед изменением создаётся резервная копия WireGuard-конфига.", + "clients.expire_1d": "1 день", + "clients.expire_1h": "1 час", + "clients.expire_3h": "3 часа", + "clients.expire_6h": "6 часов", + "clients.expire_custom": "Своя дата и время", + "clients.expire_never": "Без ограничения", + "clients.expired": "Срок истёк", + "clients.expired_disabled_hint": "Срок доступа истёк, клиент сохранён, но WireGuard-доступ отключён. Укажите новый срок или «Без ограничения» и сохраните, чтобы вернуть доступ.", + "clients.expired_disabled_short": "Срок истёк · отключён", + "clients.expired_disabled_status": "Срок истёк", + "clients.expires_days": "Осталось {n} дн", + "clients.expires_hours": "Осталось {n} ч", + "clients.expires_minutes": "Осталось {n} мин", + "clients.generated_config": "Клиентская конфигурация", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 секунд — хороший вариант для клиентов за NAT.", + "clients.local_access_exceptions": "Разрешённые локальные адреса", + "clients.local_access_exceptions_hint": "Необязательные IP или CIDR, которые останутся доступны, даже если их локальная или Site-to-site сеть заблокирована. Несколько значений — через запятую.", + "clients.managed": "Управляется WGTools", + "clients.name": "Имя", + "clients.no_peers": "Клиенты не найдены", + "clients.peers": "Клиенты", + "clients.peers_subtitle": "Перед изменениями создаётся резервная копия, затем конфигурация применяется через wg syncconf без перезапуска интерфейса WireGuard.", + "clients.protected_networks_reference": "Заблокированные локальные сети (справочно)", + "clients.protected_networks_reference_hint": "Эти сети не записываются в AllowedIPs. Доступ к ним блокируется серверной политикой WGTools; отдельные адреса можно разрешить полем выше.", + "clients.psk": "Preshared key (PSK)", + "clients.psk_enable": "Использовать дополнительный PSK WireGuard", + "clients.psk_hint": "Рекомендуется. Добавляет к рукопожатию WireGuard дополнительный симметричный секрет. Стандартные клиенты WireGuard его поддерживают; WGTools добавляет PSK в конфиг и QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Создаю QR…", + "clients.quick_search": "Быстрый поиск", + "clients.quick_search_clear": "Очистить поиск", + "clients.quick_search_empty": "По запросу клиентов нет", + "clients.relay_endpoint_note": "Готовый конфиг клиента будет подключаться к {endpoint}. Сам сервер WireGuard по-прежнему находится на этом WGTools.", + "clients.relay_required": "Выберите VPS Relay для этого клиента.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "недоступен", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "Endpoint клиента формируется автоматически из настроек выбранного Relay.", + "clients.remote_hint": "Сети, расположенные за этим пиром. По одной сети в строке или через запятую.", + "clients.remote_networks": "Удалённые сети", + "clients.remote_required": "Для Site-to-site пира укажите хотя бы одну удалённую сеть.", + "clients.required": "Нужно указать имя и VPN-адрес.", + "clients.route_custom": "Свои маршруты", + "clients.route_full": "Весь трафик через VPN", + "clients.route_full_except_local": "Весь трафик кроме локальных сетей", + "clients.route_hint": "Только эти сети записываются в AllowedIPs готового клиентского конфига.", + "clients.route_preset": "Трафик через VPN", + "clients.route_vpn": "Только VPN-сеть", + "clients.route_vpn_lan": "VPN + локальная сеть", + "clients.saved": "Клиент сохранён", + "clients.schedule_blocked_short": "Расписание · заблокирован", + "clients.schedule_blocked_status": "Заблокирован расписанием", + "clients.schedule_days": "Дни доступа", + "clients.schedule_days_required": "Выбери хотя бы один день для расписания доступа.", + "clients.schedule_disabled_hint": "Сейчас клиент заблокирован расписанием. В следующем разрешённом интервале WGTools автоматически вернёт доступ тому же peer — конфиг клиента менять не нужно.", + "clients.schedule_enable": "Ограничивать доступ по расписанию", + "clients.schedule_from": "Доступ с", + "clients.schedule_hint": "WGTools будет автоматически отключать и возвращать доступ этому клиенту в выбранные дни и часы без замены клиентского конфига.", + "clients.schedule_short": "Расписание", + "clients.schedule_time_required": "Укажи время начала и окончания доступа.", + "clients.schedule_timezone_hint": "Расписание работает по локальному времени WireGuard-сервера. Поддерживаются интервалы через полночь, например 22:00–06:00.", + "clients.schedule_title": "Расписание доступа", + "clients.schedule_to": "Доступ до", + "clients.security_access": "Безопасность и срок доступа", + "clients.server_host": "Адрес / домен сервера", + "clients.server_host_hint": "Внешний IP или домен для подключения этого клиента. Ранее введённые значения доступны в подсказках.", + "clients.server_host_required": "Для готовой конфигурации клиента обязательно укажите адрес или домен сервера.", + "clients.server_peer": "Пир на сервере", + "clients.server_port": "Порт WireGuard", + "clients.server_port_hint": "Берётся автоматически из конфигурации сервера.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Статус", + "clients.subtitle": "Пиры WireGuard, текущий статус и управление конфигурациями клиентов.", + "clients.tab_basic": "Основное", + "clients.tab_config": "Конфигурация", + "clients.tab_policy": "Политики", + "clients.tab_security": "Безопасность", + "clients.title": "Клиенты", + "clients.type": "Тип", + "clients.unmanaged_note": "Этот пир существовал до WGTools. Его приватный ключ восстановить невозможно, поэтому WGTools может менять серверную часть, но не сможет сгенерировать клиентский конфиг или QR-код.", + "clients.updating": "Обновляю клиента…", + "common.actions": "Действия", + "common.ago": "назад", + "common.cancel": "Отмена", + "common.checking": "Проверка…", + "common.close": "Закрыть", + "common.config": "Конфиг", + "common.delete": "Удалить", + "common.disabled": "Выключено", + "common.edit": "Изменить", + "common.enabled": "Включено", + "common.loading": "Загрузка…", + "common.never": "Никогда", + "common.no": "Нет", + "common.not_configured": "Не настроен", + "common.not_installed": "Не установлен", + "common.offline": "офлайн", + "common.online": "онлайн", + "common.refresh": "Обновить", + "common.running": "Работает", + "common.save": "Сохранить", + "common.stopped": "Остановлен", + "common.total": "Всего", + "common.unknown": "Неизвестно", + "common.updated": "Обновлено", + "common.yes": "Да", + "dashboard.active_peers": "Активные клиенты", + "dashboard.active_peers_subtitle": "Живые данные из wg show.", + "dashboard.activity": "Состояние системы", + "dashboard.activity_subtitle": "Проверки работающего WireGuard без изменения конфигурации.", + "dashboard.cores": "ядер", + "dashboard.cpu": "ЦП", + "dashboard.history_24h": "Последние 24 ч", + "dashboard.history_avg": "Сред", + "dashboard.history_max": "Макс", + "dashboard.history_min": "Мин", + "dashboard.history_now": "сейчас", + "dashboard.memory": "Память", + "dashboard.network": "Сеть", + "dashboard.peers": "Клиенты", + "dashboard.quick_search": "Быстрый поиск", + "dashboard.quick_search_clear": "Очистить поиск", + "dashboard.quick_search_empty": "По запросу ничего не найдено", + "dashboard.restart": "Перезапуск", + "dashboard.restart_confirm": "Перезапустить WireGuard? Активные VPN-клиенты автоматически переподключатся.", + "dashboard.restart_ok": "WireGuard перезапущен.", + "dashboard.routing": "Маршрутизация", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Пуск", + "dashboard.start_ok": "WireGuard запущен.", + "dashboard.stop": "Стоп", + "dashboard.stop_confirm": "Остановить WireGuard? Активные VPN-клиенты будут отключены.", + "dashboard.stop_ok": "WireGuard остановлен.", + "dashboard.subtitle": "Состояние WireGuard, клиенты и текущий трафик.", + "dashboard.title": "Главная", + "dashboard.traffic": "Трафик", + "dashboard.uptime": "Аптайм", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Политика доступа на сервере", + "groups.additional_allowed": "Дополнительно разрешить", + "groups.additional_blocked": "Дополнительно запретить", + "groups.allow": "Разрешить", + "groups.allowed": "Разрешён", + "groups.allowed_addresses": "Разрешённые адреса / сети", + "groups.apply_current_template": "Применить текущий шаблон группы", + "groups.apply_defaults": "Применить текущий шаблон группы", + "groups.apply_defaults_hint": "Копирует текущие маршруты, DNS и Keepalive группы в этого клиента. После сохранения выдай новый конфиг или QR, если нужно обновить уже установленное устройство.", + "groups.basic": "Основное", + "groups.block": "Запретить", + "groups.blocked": "Запрещён", + "groups.blocked_addresses": "Запрещённые адреса / сети", + "groups.client_config_source": "Источник конфигурации клиента", + "groups.client_defaults": "Настройки клиента", + "groups.client_group_hint": "Необязательная группа с общей политикой доступа и настройками новых клиентов. Группы относятся только к выбранному интерфейсу WireGuard.", + "groups.config_differs": "Конфигурация этого клиента отличается от текущих настроек группы. Серверная политика уже актуальна, но конфиг на телефоне/ПК изменится только после выдачи нового файла или QR.", + "groups.config_differs_short": "Конфиг клиента отличается от настроек группы", + "groups.create": "Создать группу", + "groups.create_title": "Создать группу", + "groups.created": "Группа создана", + "groups.creating": "Создаю группу…", + "groups.defaults_applied": "Текущий шаблон группы применён. Сохрани клиента, чтобы закрепить изменения.", + "groups.defaults_hint": "Определяет, какой трафик устройство отправляет через WireGuard. Политика сервера выше независимо определяет, куда этот трафик будет допущен. Изменение шаблона позже не меняет молча конфиги, уже установленные на устройствах.", + "groups.delete_message": "Удалить группу «{name}»? Клиентские конфигурации при удалении группы никогда не удаляются.", + "groups.delete_move": "Переместить её клиентов в другую группу", + "groups.delete_title": "Удалить группу клиентов", + "groups.delete_unassign": "Убрать принадлежность к группе у её клиентов", + "groups.deleted": "Группа удалена", + "groups.deleting": "Обновляю клиентов и удаляю группу…", + "groups.description": "Описание", + "groups.edit_title": "Изменить группу", + "groups.editor_subtitle": "Группа объединяет действующую серверную политику доступа и шаблон, который используется при создании клиентских конфигураций.", + "groups.effective_allow": "Разрешённые исключения", + "groups.effective_deny": "Запрещённые исключения", + "groups.effective_policy": "Итоговая политика сервера", + "groups.empty": "Групп клиентов пока нет. Создайте группу, чтобы переиспользовать правила доступа и настройки клиентов.", + "groups.group": "Группа", + "groups.inherit": "Наследовать", + "groups.internet_access": "Доступ в интернет", + "groups.internet_short": "Интернет", + "groups.local_access": "Локальные сети", + "groups.local_short": "Локальные сети", + "groups.manage": "Группы", + "groups.members_count": "Клиентов: {count}", + "groups.name": "Название", + "groups.name_required": "Укажите название группы.", + "groups.new_client_defaults": "Шаблон конфигурации клиента", + "groups.new_clients_short": "Новые клиенты", + "groups.no_group": "Без группы", + "groups.none": "Нет", + "groups.override_client_config": "Переопределить шаблон группы для этого клиента", + "groups.override_client_config_hint": "Выключено: маршруты, DNS и Keepalive берутся из шаблона группы. Включено: у клиента собственные значения. Индивидуальная серверная политика выше работает независимо.", + "groups.policy_addresses_hint": "IPv4-адреса или CIDR через запятую. Индивидуальные исключения клиента имеют приоритет над исключениями группы.", + "groups.policy_custom": "Своя политика", + "groups.policy_inherit": "Использовать политику группы", + "groups.policy_mode": "Источник политики", + "groups.policy_mode_hint": "По умолчанию политика наследуется от группы. Исключения клиента никогда не меняют саму группу.", + "groups.routes_required": "Маршруты клиента не могут быть пустыми.", + "groups.subtitle": "Общие политики доступа и настройки для обычных клиентов выбранного интерфейса WireGuard.", + "groups.title": "Группы клиентов", + "groups.traffic_through_vpn": "Трафик через VPN", + "groups.updated": "Группа обновлена", + "groups.updating": "Обновляю политику группы…", + "help.example_note": "Все IP-адреса, имена интерфейсов, peer и домены в примерах справки вымышлены и используются только для документации. Заменяйте их значениями своей сети.", + "help.navigation": "Навигация по справке", + "help.open": "Открыть справку", + "help.subtitle": "Понятная справка по Главной, Серверу, Клиентам и Настройкам с короткими примерами.", + "help.title": "Справка WGTools", + "interfaces.add": "+ Добавить интерфейс", + "interfaces.create": "Создать интерфейс", + "interfaces.create_confirm": "Создать и запустить интерфейс {name}?", + "interfaces.create_failed": "Не удалось создать интерфейс", + "interfaces.create_hint": "Перед созданием WGTools проверит, что VPN-сеть, UDP-порт и policy table не конфликтуют с другими интерфейсами WireGuard.", + "interfaces.create_subtitle": "Создать отдельный интерфейс WireGuard со своим пулом адресов, UDP-портом и настройками маршрутизации.", + "interfaces.create_title": "Добавить интерфейс WireGuard", + "interfaces.created": "Интерфейс успешно создан.", + "interfaces.creating": "Генерирую ключи, создаю новую конфигурацию и запускаю WireGuard…", + "interfaces.current": "Текущий", + "interfaces.delete": "Удалить", + "interfaces.delete_confirm": "Удалить интерфейс {name}? Будут удалены его конфигурация WireGuard и все пиры этого интерфейса. Перед удалением WGTools создаст резервную копию конфигурации.", + "interfaces.delete_failed": "Не удалось удалить интерфейс", + "interfaces.delete_last": "Последний настроенный интерфейс WireGuard нельзя удалить здесь.", + "interfaces.delete_tooltip": "Удалить этот интерфейс WireGuard", + "interfaces.deleted": "Интерфейс удалён. Резервная копия: {backup}", + "interfaces.deleting": "Останавливаю WireGuard и удаляю интерфейс…", + "interfaces.display_name": "Отображаемое имя", + "interfaces.display_name_edit_hint": "Меняется только понятное имя в WGTools; системное имя Linux остаётся прежним.", + "interfaces.display_name_hint": "Необязательное понятное имя, например Работа или Подрядчики.", + "interfaces.identity": "Идентификация интерфейса", + "interfaces.none": "Интерфейсы WireGuard не найдены", + "interfaces.none_configured": "Настроенных интерфейсов WireGuard пока нет.", + "interfaces.peers_short": "пиров", + "interfaces.rename_failed": "Не удалось сохранить понятное имя интерфейса.", + "interfaces.select": "Выбрать", + "interfaces.subtitle": "У каждого интерфейса своя VPN-сеть, порт, клиенты и правила. Выбранный интерфейс используется на всех страницах WGTools.", + "interfaces.switch_title": "Интерфейсы WireGuard", + "interfaces.system_name": "Системное имя", + "interfaces.system_name_hint": "Имя интерфейса Linux, например wg1. После создания его лучше не менять.", + "interfaces.title": "Интерфейсы WireGuard", + "interfaces.unique_port_hint": "Каждый интерфейс WireGuard на этом сервере должен использовать свой UDP-порт.", + "interfaces.unique_table_hint": "WGTools рекомендует отдельную policy table для каждого интерфейса. Оставь пустым для обычной системной маршрутизации.", + "nav.clients": "Клиенты", + "nav.dashboard": "Главная", + "nav.server": "Сервер", + "nav.settings": "Настройки", + "server.access_apply_confirm": "Сохранить правило firewall и применить его сейчас? WireGuard кратковременно перезапустится, перед этим будет создан backup.", + "server.access_rule_deleted": "Правило доступа удалено.", + "server.access_rule_help": "Создание обычного правила FORWARD без ручного редактирования команд iptables.", + "server.access_rule_order_hint": "WGTools вставляет правила доступа в начало цепочки FORWARD, чтобы ограничения срабатывали раньше общих разрешающих правил VPN.", + "server.access_rule_saved": "Правило доступа сохранено и применено.", + "server.action": "Действие", + "server.action_hint": "REJECT сообщает клиенту об отказе; DROP молча отбрасывает трафик; ACCEPT явно разрешает его.", + "server.add_access_rule": "Добавить правило доступа", + "server.add_route": "Добавить маршрут", + "server.address": "Адрес", + "server.any": "Любой", + "server.any_protocol": "Любой", + "server.apply_confirm": "Сохранить эти настройки сервера и применить их сейчас? WireGuard будет кратковременно перезапущен. Перед изменением создаётся резервная копия, а при ошибке WGTools автоматически вернёт предыдущую конфигурацию.", + "server.apply_settings": "Сохранить и применить", + "server.applying_rule": "Создаю backup и применяю…", + "server.applying_settings": "Проверяю настройки, создаю резервную копию и применяю…", + "server.basic_settings": "Основные настройки", + "server.config_tab_help": "Открывает редактор исходного конфига выбранного интерфейса WireGuard.", + "server.create_confirm": "Создать и запустить сервер WireGuard с этими настройками?", + "server.create_server": "Создать сервер", + "server.create_step_conf": "Создаст конфигурацию выбранного интерфейса WireGuard с правами 600.", + "server.create_step_forward": "Настроит forwarding, NAT и при необходимости policy routing.", + "server.create_step_key": "Сгенерирует новую пару ключей сервера.", + "server.create_step_start": "Включит и запустит выбранный интерфейс wg-quick.", + "server.create_subtitle": "WireGuard установлен, но выбранный интерфейс пока не настроен.", + "server.create_success": "Сервер WireGuard успешно создан.", + "server.create_title": "Создать сервер WireGuard", + "server.creating": "Генерирую ключи, записываю конфигурацию и запускаю WireGuard…", + "server.custom_preserved": "Блоки пиров, маршруты site-to-site и пользовательские PostUp/PostDown, которыми эти поля не управляют, сохраняются.", + "server.delete_access_confirm": "Удалить это правило доступа и применить изменение?", + "server.delete_route_confirm": "Удалить этот пользовательский маршрут и применить изменение?", + "server.destination": "Назначение", + "server.destination_hint": "Пусто = любое назначение. Можно указать IP, CIDR или диапазон IP. Несколько назначений разделяйте запятыми.", + "server.destination_port": "Порт назначения", + "server.destination_port_hint": "Необязательно. Например 443 или диапазон 10000:20000. Для порта сначала выбери TCP или UDP.", + "server.details": "Детали", + "server.dev_word": "dev", + "server.diagnostics": "Диагностика", + "server.diagnostics_done": "Диагностика завершена", + "server.diagnostics_subtitle": "Текущие проверки системы. Конфигурация не изменяется.", + "server.direction": "Хук", + "server.edit_access_rule": "Изменить правило доступа", + "server.edit_route": "Изменить маршрут", + "server.edit_server": "Изменить настройки", + "server.edit_subtitle": "Основные настройки WireGuard, маршрутизации и NAT. Существующие пиры и пользовательские правила сохраняются.", + "server.edit_title": "Настройки сервера", + "server.edit_warning": "При изменении настроек интерфейса, маршрутизации или firewall интерфейс WireGuard кратковременно перезапускается. Активные пиры подключатся снова автоматически.", + "server.enable_forwarding": "Включить IPv4 forwarding", + "server.enable_nat": "Включить NAT / Masquerade", + "server.firewall": "Firewall и NAT", + "server.firewall_subtitle": "Правила, обнаруженные в хуках WireGuard.", + "server.firewall_subtitle_v08": "Базовые правила forwarding/NAT и правила доступа из конфигурации выбранного интерфейса. Простые правила редактируются здесь, сложные остаются доступны через raw-редактор.", + "server.forward_from_vpn": "Разрешить forwarding из VPN", + "server.forward_to_vpn": "Разрешить forwarding в VPN", + "server.forwarding_section": "Forwarding и NAT", + "server.gateway": "Шлюз", + "server.gateway_hint": "Нужен только при использовании отдельной таблицы policy routing.", + "server.install_success": "WireGuard успешно установлен.", + "server.install_wireguard": "Установить WireGuard", + "server.install_wireguard_help": "Выполняет apt update и устанавливает WireGuard вместе с сетевыми инструментами, необходимыми WGTools.", + "server.install_wireguard_title": "Установить WireGuard", + "server.installing": "Устанавливаю WireGuard… Это может занять некоторое время.", + "server.interface": "Интерфейс", + "server.interface_hint": "Сейчас WGTools управляет этим интерфейсом.", + "server.interface_name": "Интерфейс", + "server.interface_section": "Интерфейс WireGuard", + "server.ip_forwarding": "IPv4 forwarding", + "server.kind": "Тип", + "server.listen_port": "Порт", + "server.local_network": "Локальная сеть", + "server.local_network_hint": "Необязательный маршрут, который будет добавлен в policy table.", + "server.managed_automatically": "Управляется автоматически", + "server.nat": "NAT / Masquerade", + "server.network": "Сеть", + "server.network_settings": "Сеть и NAT", + "server.no_firewall": "Правила firewall не обнаружены", + "server.no_routes": "Маршруты не обнаружены", + "server.not_configured": "Не настроен", + "server.not_set": "Не задан", + "server.policy_disabled_hint": "Для обычной системной маршрутизации выключи эту опцию. Включай её, если VPN нужна отдельная source policy routing table.", + "server.policy_enabled": "Включить policy routing", + "server.policy_table": "Таблица маршрутизации", + "server.policy_table_hint": "Оставь пустым для обычной системной маршрутизации; например 200 — для source policy routing.", + "server.port_word": "порт", + "server.private_hidden": "Настроен (скрыт)", + "server.private_key": "Приватный ключ", + "server.protocol": "Протокол", + "server.route_apply_confirm": "Сохранить маршрут и применить его сейчас? WireGuard кратковременно перезапустится, перед этим будет создан backup.", + "server.route_custom": "Пользовательский", + "server.route_deleted": "Маршрут удалён.", + "server.route_device_hint": "Необязательный выходной интерфейс, например wg0 или enp6s18.", + "server.route_editor_help": "Маршрут будет добавляться при запуске WireGuard и удаляться при его остановке.", + "server.route_gateway_hint": "Необязательный шлюз. Нужно указать хотя бы шлюз или интерфейс.", + "server.route_managed_peer": "Site-to-site пир", + "server.route_managed_server": "Настройка сервера", + "server.route_network_hint": "IPv4-сеть, например 10.20.0.0/24, либо 'default'.", + "server.route_saved": "Маршрут сохранён и применён.", + "server.route_table_hint": "'main' — обычная маршрутизация, либо номер таблицы, например 200.", + "server.route_type": "Тип", + "server.routes": "Обнаруженные маршруты", + "server.routes_subtitle": "Маршруты из PostUp/PostDown и текущего policy routing.", + "server.routes_subtitle_v08": "Системные, site-to-site и пользовательские маршруты выбранного интерфейса. Пользовательские маршруты можно добавлять, изменять и удалять здесь.", + "server.routing": "Маршрутизация", + "server.routing_section": "Маршрутизация", + "server.rule": "Правило", + "server.rule_access": "Правило доступа", + "server.rule_advanced": "Расширенное", + "server.rule_apply_warning": "При применении маршрута или правила firewall интерфейс WireGuard кратковременно перезапускается. WGTools создаёт backup и автоматически откатывается при ошибке запуска.", + "server.rule_client_exception": "Исключение клиента", + "server.rule_client_policy": "Политика клиента", + "server.rule_managed_server": "Настройка сервера", + "server.rule_type": "Тип", + "server.run_diagnostics": "Запустить диагностику", + "server.save_apply": "Сохранить и применить", + "server.save_config": "SaveConfig", + "server.server_address": "VPN-адрес сервера", + "server.server_address_hint": "Обычно используется первый доступный адрес VPN-сети.", + "server.settings_applied": "Настройки сервера сохранены и успешно применены.", + "server.settings_apply_failed": "Не удалось применить настройки сервера", + "server.setup_required": "Требуется настройка", + "server.source": "Источник", + "server.source_hint": "Пусто = любой. Можно указать IP, CIDR или диапазон, например 10.0.0.100-10.0.0.120.", + "server.subtitle": "Установка WireGuard, первичная настройка и текущая конфигурация сервера.", + "server.tab_config": "Конфиг", + "server.tab_interface": "Интерфейс", + "server.tab_routing": "Маршрутизация", + "server.tab_vps": "VPS", + "server.table": "Таблица", + "server.tabs_aria": "Разделы настроек сервера", + "server.title": "Сервер", + "server.uplink": "Внешний интерфейс", + "server.use_raw_editor": "Через raw-редактор", + "server.via": "Через / Интерфейс", + "server.via_word": "via", + "server.vpn_network": "VPN сеть", + "server.vpn_network_hint": "Адреса клиентов будут выдаваться из этой сети.", + "server.vpn_pool": "Пул VPN-адресов", + "server.wg_not_installed": "WireGuard не установлен", + "server.wg_not_installed_subtitle": "WGTools может автоматически установить необходимые пакеты Debian.", + "server.what_happens": "Что сделает WGTools", + "settings.about": "О программе", + "settings.add_user": "Добавить пользователя", + "settings.advanced": "Расширенные настройки", + "settings.advanced_subtitle": "Прямой доступ к профессиональным инструментам конфигурации WireGuard.", + "settings.appearance": "Оформление", + "settings.applying_config": "Проверяю конфигурацию, создаю резервную копию и применяю…", + "settings.backup_count": "Сохранено копий", + "settings.backup_retention": "Хранить копий", + "settings.backup_retention_help": "Старые автоматические копии удаляются после создания новой. От 1 до 200 файлов.", + "settings.backups": "Резервные копии конфигурации", + "settings.backups_always_on": "Включено", + "settings.backups_subtitle": "WGTools автоматически создаёт резервную копию перед операциями, меняющими конфигурацию. Автоматические копии отключить нельзя.", + "settings.change_password": "Изменить пароль", + "settings.check_updates": "Проверить обновления", + "settings.config_applied": "Конфигурация сохранена и успешно применена.", + "settings.config_applied_restarted": "Конфигурация применена, WireGuard перезагружен.", + "settings.config_applied_stopped": "Конфигурация сохранена. WireGuard уже был остановлен и оставлен остановленным.", + "settings.config_apply_failed": "Не удалось применить конфигурацию", + "settings.config_load_failed": "Не удалось загрузить конфигурацию", + "settings.current_user": "Текущий пользователь", + "settings.current_version": "Текущая версия", + "settings.audit_action": "Действие", + "settings.audit_empty": "Событий аудита пока нет", + "settings.audit_log": "Аудит", + "settings.audit_log_subtitle": "Действия в панели, вход/восстановление доступа и Telegram, а также история подключений WireGuard-клиентов. Секреты сюда не записываются.", + "settings.audit_object": "Объект", + "settings.audit_result": "Результат", + "settings.audit_retention_note": "Срок хранения: 30 дней", + "settings.audit_search": "Быстрый поиск", + "settings.audit_search_clear": "Очистить поиск", + "settings.audit_search_empty": "По запросу событий нет", + "settings.audit_time": "Дата / время", + "settings.audit_user": "Пользователь", + "audit.user.telegram_short": "ТГ", + "audit.action.access_rule.created": "Правило доступа создано", + "audit.action.access_rule.deleted": "Правило доступа удалено", + "audit.action.access_rule.updated": "Правило доступа изменено", + "audit.action.auth.first_user_created": "Первый пользователь создан", + "audit.action.auth.login": "Вход в панель", + "audit.action.auth.login_failed": "Неудачный вход", + "audit.action.auth.logout": "Выход из панели", + "audit.action.backup.full_created": "Полная копия создана", + "audit.action.backup.full_restored": "Полная копия восстановлена", + "audit.action.client.config_downloaded": "Конфиг клиента скачан", + "audit.action.client.config_viewed": "Конфиг клиента открыт", + "audit.action.client.created": "Клиент создан", + "audit.action.client.deleted": "Клиент удалён", + "audit.action.client.qr_viewed": "QR клиента открыт", + "audit.action.client.updated": "Клиент изменён", + "audit.action.client_group.created": "Группа клиентов создана", + "audit.action.client_group.deleted": "Группа клиентов удалена", + "audit.action.client_group.updated": "Группа клиентов изменена", + "audit.action.interface.created": "Интерфейс создан", + "audit.action.interface.deleted": "Интерфейс удалён", + "audit.action.interface.renamed": "Интерфейс переименован", + "audit.action.route.created": "Маршрут создан", + "audit.action.route.deleted": "Маршрут удалён", + "audit.action.route.updated": "Маршрут изменён", + "audit.action.server.created": "Сервер создан", + "audit.action.server.raw_config_applied": "Raw config применён", + "audit.action.server.settings_applied": "Настройки сервера применены", + "audit.action.settings.updated": "Настройки панели изменены", + "audit.action.telegram.action_denied": "Действие Telegram запрещено", + "audit.action.telegram.action_failed": "Ошибка действия Telegram", + "audit.action.telegram.connection_test": "Проверка подключения Telegram", + "audit.action.telegram.settings_updated": "Настройки Telegram изменены", + "audit.action.update.checked": "Проверка обновлений", + "audit.action.update.scheduled": "Обновление запланировано", + "audit.action.update.backup_created": "Резервная копия перед обновлением", + "audit.action.update.completed": "Обновление завершено", + "audit.action.update.failed": "Ошибка обновления", + "audit.action.update.rollback_completed": "Предыдущая версия восстановлена", + "audit.action.update.rollback_failed": "Ошибка отката обновления", + "audit.action.user.created": "Пользователь создан", + "audit.action.user.deleted": "Пользователь удалён", + "audit.action.user.password_changed": "Пароль пользователя изменён", + "audit.action.vps.candidate_deleted": "VPS удалён из списка", + "audit.action.vps.candidate_saved": "VPS сохранён", + "audit.action.vps.detached": "VPS Relay отключён", + "audit.action.vps.relay_installed": "VPS Relay установлен", + "audit.action.wireguard.client_connected": "Клиент WireGuard подключён", + "audit.action.wireguard.installed": "WireGuard установлен", + "audit.action.wireguard.restarted": "WireGuard перезапущен", + "audit.action.wireguard.started": "WireGuard запущен", + "audit.action.wireguard.stopped": "WireGuard остановлен", + "audit.result.applied": "применено", + "audit.result.available": "доступно", + "audit.result.changed": "изменено", + "audit.result.created": "создано", + "audit.result.current": "актуально", + "audit.result.deleted": "удалено", + "audit.result.detached": "отключено", + "audit.result.denied": "запрещено", + "audit.result.downloaded": "скачано", + "audit.result.endpoint": "IP", + "audit.result.error": "Ошибка", + "audit.result.installed": "установлено", + "audit.result.invalid_credentials": "неверные данные", + "audit.result.ok": "успешно", + "audit.result.queued": "в очереди", + "audit.result.restarted": "перезапущено", + "audit.result.restored": "восстановлено", + "audit.result.rotated": "обновлено", + "audit.result.saved": "сохранено", + "audit.result.shown": "показано", + "audit.result.started": "запущено", + "audit.result.stopped": "остановлено", + "audit.result.updated": "изменено", + "settings.delete_user": "Удалить", + "settings.delete_user_confirm": "Удалить пользователя {name}?", + "settings.edit_raw_config": "Редактировать конфиг интерфейса", + "settings.expert_mode": "Для профи", + "settings.full_backup_component_clients": "Данные и приватные ключи клиентов, PSK, сроки доступа и принадлежность к группам, необходимые для повторной выдачи конфигов и QR.", + "settings.full_backup_component_db": "База WGTools: пользователи, настройки программы, почта/SMTP, Telegram и сохранённое состояние VPS Relay.", + "settings.full_backup_component_relay": "Данные для восстановления VPS Relay: controller/tenant ID, management token и домашний transport-ключ. После restore WGTools может заново поднять локальный transport и подключиться к сохранённому tenant на VPS.", + "settings.full_backup_component_system": "Файл sysctl WGTools для IPv4 forwarding, метаданные понятных имён интерфейсов и определения групп клиентов с их политиками и шаблонами, если они существуют. История автоматических копий конфигураций интерфейсов намеренно не включается.", + "settings.full_backup_component_wg": "Все обнаруженные конфигурации интерфейсов WireGuard из /etc/wireguard/ вместе с их состоянием запущен/остановлен.", + "settings.full_backup_create_failed": "Не удалось создать полную резервную копию", + "settings.full_backup_creating": "Создаю полную резервную копию…", + "settings.full_backup_download": "Создать", + "settings.full_backup_downloaded": "Резервная копия создана и скачана. Храните её в безопасном месте.", + "settings.full_backup_downloaded_short": "Полная копия скачана.", + "settings.full_backup_help": "Создаёт переносимую резервную копию WGTools для переезда или аварийного восстановления. В архив входят конфигурации WireGuard, пользователи, настройки, группы, данные управляемых клиентов и состояние, необходимое для повторного подключения к сохранённым VPS Relay.", + "settings.full_backup_no_file": "Файл резервной копии не выбран", + "settings.full_backup_restore": "Восстановить", + "settings.full_backup_restore_confirm": "Восстановить эту полную копию WGTools? Будут восстановлены пользователи, настройки, данные управляемых клиентов и все конфигурации WireGuard, включённые в архив. Интерфейсы WireGuard могут быть перезапущены. Перед восстановлением WGTools создаст страховочную копию и автоматически откатит изменения, если применение восстановленного состояния завершится ошибкой.", + "settings.full_backup_restore_failed": "Ошибка восстановления", + "settings.full_backup_restored": "Резервная копия успешно восстановлена. Войдите под пользователем из восстановленной копии.", + "settings.full_backup_restored_short": "Резервная копия восстановлена.", + "settings.full_backup_restoring": "Проверяю архив, создаю страховочную копию и выполняю восстановление…", + "settings.full_backup_secret_warning": "Файл содержит секретные данные: приватные ключи WireGuard, приватные ключи клиентов, preshared keys (PSK), хэши паролей WGTools, токен Telegram-бота и сохранённый пароль SMTP. Храните его как пароль и никогда не прикладывайте к публичным issue, чатам или форумам.", + "settings.full_backup_select": "Выбрать", + "settings.full_backup_title": "Полная резервная копия и восстановление", + "settings.full_mode": "Управление сервером и клиентами включено", + "settings.interface_help": "Интерфейс WireGuard выбирается при установке WGTools.", + "settings.language": "Язык", + "settings.last_backup": "Последняя копия", + "settings.latest_version": "Последний релиз", + "settings.loading_config": "Загрузка конфигурации…", + "settings.mode": "Режим", + "settings.never_logged_in": "Никогда", + "settings.new_password": "Новый пароль", + "settings.no_backups": "Резервных копий пока нет", + "settings.online_help": "Клиент считается онлайн, пока последний handshake не старше этого значения. От 30 до 3600 секунд.", + "settings.online_threshold": "Порог Online", + "settings.open_release": "Открыть релиз", + "settings.password_changed": "Пароль изменен.", + "settings.passwords_mismatch": "Пароли не совпадают.", + "settings.project_github": "Проект / GitHub", + "settings.raw_config_confirm": "Сохранить эту конфигурацию WireGuard и применить её сейчас? Выбранный интерфейс будет перезапущен. Сначала создаётся резервная копия; если новая конфигурация не запустится, WGTools автоматически выполнит откат.", + "settings.raw_config_help": "Открыть исходную конфигурацию выбранного интерфейса WireGuard.", + "settings.raw_config_title": "Конфигурация WireGuard вручную", + "settings.raw_config_warning": "Режим для опытных пользователей: это реальный конфигурационный файл WireGuard, в нём находятся приватный ключ сервера и PSK пиров, если они используются. При сохранении и применении интерфейс WireGuard будет перезапущен. Перед изменением WGTools создаёт резервную копию и автоматически откатывается, если новая конфигурация не запускается.", + "settings.readonly_mode": "Управление клиентами включено", + "settings.refresh_help": "Как часто WGTools запрашивает свежие данные состояния. От 2 до 60 секунд.", + "settings.refresh_interval": "Интервал обновления", + "settings.release_notes": "Описание релиза", + "settings.reload_config": "Перечитать с диска", + "settings.save_apply": "Сохранить и применить", + "settings.saved": "Настройки сохранены.", + "settings.saved_reload": "Настройки сохранены. Перезагрузка…", + "settings.saving": "Сохраняю настройки…", + "settings.status": "Обновление статуса", + "settings.status_help": "Настройки обновления живых данных Главной и статусов клиентов.", + "settings.subtitle": "Настройки интерфейса WGTools и отображения статуса.", + "settings.syntax_hint": "Секции, параметры, значения и комментарии WireGuard подсвечиваются во время редактирования.", + "settings.tab_about": "О программе", + "settings.tab_backups": "Резервные копии", + "settings.tab_general": "Основные", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Пользователи", + "settings.tabs_aria": "Разделы настроек", + "settings.telegram": "Telegram Bot", + "settings.telegram_allowed_ids": "Разрешённые Telegram user ID", + "settings.telegram_allowed_ids_help": "По одному числовому user ID в строке. Если неразрешённый пользователь отправит /start, WGTools ответит его Telegram user ID — его можно добавить сюда.", + "settings.telegram_bot_name": "Бот", + "settings.telegram_connected": "Подключён", + "settings.telegram_disabled": "Отключён", + "settings.telegram_dns": "DNS клиентов по умолчанию", + "settings.telegram_dns_help": "Необязательные IPv4-адреса DNS через запятую. Используются для клиентов, созданных ботом.", + "settings.telegram_enabled": "Включить Telegram-бота", + "settings.telegram_endpoint": "Адрес / домен сервера по умолчанию", + "settings.telegram_endpoint_help": "Используется ботом при создании нового клиентского конфига. Укажите только IP или домен; порт WireGuard берётся из конфигурации сервера.", + "settings.telegram_language": "Язык бота", + "settings.telegram_language_auto": "Авто (язык Telegram)", + "settings.telegram_last_poll": "Последняя связь с Telegram", + "settings.telegram_not_configured": "Не настроен", + "settings.telegram_remove_token": "Удалить токен", + "settings.telegram_remove_token_confirm": "Удалить сохранённый токен Telegram-бота и отключить бота?", + "settings.telegram_save": "Сохранить настройки Telegram", + "settings.telegram_saved": "Настройки Telegram сохранены.", + "settings.telegram_setup_note": "Создайте бота в @BotFather, сохраните токен, включите бота и отправьте ему /start. Если ваш user ID ещё не разрешён, WGTools покажет его — добавьте этот ID в список разрешённых Telegram user ID.", + "settings.telegram_status": "Состояние бота", + "settings.telegram_subtitle": "Удалённое управление WireGuard из Telegram: состояние сервера, клиенты, создание/удаление клиентов и запуск/перезапуск/остановка WireGuard.", + "settings.telegram_test": "Проверить подключение", + "settings.telegram_test_ok": "Telegram подключён: @{username}", + "settings.telegram_test_recent_ok": "Telegram-бот работает. Прямая проверка получила timeout, но бот недавно успешно связывался с Telegram.", + "settings.telegram_token": "Токен бота", + "settings.telegram_token_help": "Создайте бота через @BotFather и вставьте сюда его Bot API token. API ID и API Hash для Telegram Bot API не нужны.", + "settings.telegram_token_keep": "Оставьте поле пустым, чтобы сохранить уже записанный токен.", + "settings.telegram_waiting": "Настроен, ожидается запуск бота", + "settings.theme": "Тема", + "settings.theme_dark": "Тёмная", + "settings.theme_light": "Светлая", + "settings.theme_system": "Системная", + "settings.title": "Настройки", + "settings.update_available": "Доступно обновление", + "settings.update_backup_queued": "Обновление поставлено в очередь. Перед установкой WGTools создаст автоматическую полную резервную копию…", + "settings.update_backup_running": "Создаю автоматическую полную резервную копию перед обновлением…", + "settings.update_check_failed": "Не удалось проверить обновления", + "settings.update_checking": "Проверяю последний опубликованный релиз на GitHub…", + "settings.update_confirm": "Обновить WGTools с v{current} до v{latest}? Сначала будет создана полная резервная копия и копия приложения для отката. Веб-интерфейс ненадолго перезапустится.", + "settings.update_current": "Актуальная версия", + "settings.update_downloading": "Скачиваю и проверяю релиз с GitHub…", + "settings.update_failed": "Не удалось обновить WGTools.", + "settings.update_installing": "Устанавливаю обновление. Веб-интерфейс может ненадолго стать недоступен…", + "settings.update_no_update": "Установлена последняя версия WGTools.", + "settings.update_not_checked": "Не проверялось", + "settings.update_queued": "Обновление поставлено в очередь. Жду запуска службы обновления…", + "settings.update_rollback_ok": "Предыдущая версия WGTools восстановлена автоматически.", + "settings.update_rolling_back": "Обновление завершилось ошибкой. Восстанавливаю предыдущую версию WGTools…", + "settings.update_running": "Создаю резервные копии перед обновлением…", + "settings.update_safety_hint": "Обновление запускается только вручную. Перед установкой WGTools создаёт полную резервную копию состояния и отдельную копию приложения для отката. При ошибке предыдущая версия приложения восстанавливается автоматически. Сам WireGuard обновлятор не перезапускает, если новый релиз явно не меняет его конфигурацию.", + "settings.update_sidebar": "Доступна новая версия", + "settings.update_sidebar_hint": "Открыть Настройки → О программе", + "settings.update_starting": "Запускаю обновление…", + "settings.update_status_unknown": "Статус обновления временно недоступен. Повторяю проверку…", + "settings.update_subtitle": "Информация о проекте, автоматическая проверка новых релизов и безопасное обновление из GitHub Releases.", + "settings.update_success": "WGTools успешно обновлён до v{version}. Перезагружаю страницу…", + "settings.update_wgtools": "Обновить WGTools", + "settings.user_actions": "Действия", + "settings.user_created": "Создан", + "settings.user_created_ok": "Пользователь создан.", + "settings.user_deleted": "Пользователь удален.", + "settings.user_equal_rights": "Все пользователи WGTools имеют одинаковые права.", + "settings.user_last_login": "Последний вход", + "settings.user_name": "Логин", + "settings.users": "Пользователи", + "settings.users_subtitle": "Локальные учётные записи WGTools. E-mail необязателен и используется только для восстановления пароля при включённой почте.", + "vps.add": "Добавить VPS", + "vps.add_help": "WGTools подключится по SSH для проверки или установки Relay. Пароль и приватный SSH-ключ не сохраняются.", + "vps.add_title": "Добавить VPS", + "vps.agent": "Relay Agent", + "vps.agent_found": "Уже установлен", + "vps.agent_will_install": "Будет установлен", + "vps.arch": "Архитектура", + "vps.auth_method": "Способ входа", + "vps.authentication": "Авторизация SSH", + "vps.check": "Проверить VPS", + "vps.check_failed": "Проверка VPS не пройдена", + "vps.check_link": "Проверить связь", + "vps.check_ok": "VPS совместим", + "vps.checking": "Проверяем SSH и совместимость VPS…", + "vps.connections": "подключений", + "vps.credentials_not_saved": "Используется только для этой проверки и не сохраняется WGTools.", + "vps.delete_candidate": "Убрать", + "vps.delete_installed": "Удалить VPS", + "vps.delete_installed_confirm": "Удалить «{name}» из WGTools? Локальный транспорт Relay будет отключён, но Relay Agent и tenant на самом VPS останутся без изменений. Этот VPS можно будет добавить снова и WGTools подключится к существующему Relay, не создавая новый. Клиенты, использующие Relay, не смогут подключаться через него, пока VPS не будет подключён повторно.", + "vps.delete_installed_failed": "Не удалось удалить VPS из WGTools", + "vps.delete_installed_ok": "VPS удалён из WGTools. Relay на удалённом VPS сохранён и может быть подключён повторно.", + "vps.empty_help": "Добавьте VPS на Debian или Ubuntu: WGTools проверит SSH-доступ, совместимость системы и свободные UDP-порты.", + "vps.empty_title": "VPS пока не настроен", + "vps.endpoint": "Публичная точка", + "vps.endpoint_domain": "Домен (рекомендуется)", + "vps.endpoint_domain_hint": "При замене основного VPS достаточно будет изменить DNS, не перевыпуская конфиги клиентов.", + "vps.health_failed": "Проверка Relay не пройдена", + "vps.host": "IP / имя хоста", + "vps.host_key": "Ключ хоста SSH", + "vps.identity": "Подключение к VPS", + "vps.install_failed": "Не удалось установить Relay", + "vps.install_ok": "Relay установлен, защищённый канал управления проверен", + "vps.install_relay": "Установить Relay", + "vps.install_title": "Установить VPS Relay", + "vps.installed": "Установлен", + "vps.installing": "Устанавливаем Relay Agent и поднимаем защищённый транспортный туннель…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Пароль ключа", + "vps.link_ok": "Связь с Relay работает", + "vps.multi_tenant_note": "На VPS уже работает WGTools Relay Agent. Он не будет переустановлен: для этого WGTools создаст отдельное изолированное подключение со своими ключами и UDP-портами.", + "vps.name": "Название", + "vps.no_domain": "Подключение по IP", + "vps.not_installed": "Будет установлен", + "vps.os": "Операционная система", + "vps.password": "Пароль", + "vps.phase_note": "Relay Agent поддерживает несколько независимых WGTools на одном VPS. Каждый контроллер получает отдельное изолированное подключение, ключи и UDP-порты; существующие подключения не изменяются.", + "vps.port_pair": "UDP-порты", + "vps.ports_adjusted": "выбраны свободные порты", + "vps.private_key": "Приватный ключ", + "vps.privilege": "Права", + "vps.public_endpoint": "Будущая публичная точка", + "vps.ready_help": "SSH-данные используются для проверки совместимости и сразу для установки Relay; WGTools их не сохраняет.", + "vps.reconnect_note": "На VPS найдено существующее подключение Relay, созданное этим WGTools. Будет восстановлено именно оно — новый tenant и новые UDP-порты создаваться не будут.", + "vps.reconnect_ok": "Существующий Relay успешно подключён повторно", + "vps.reconnect_relay": "Подключить Relay", + "vps.relay_port": "UDP-порт Relay", + "vps.remove_confirm": "Убрать этого кандидата VPS? На удалённом сервере ничего не менялось.", + "vps.save_candidate": "Сохранить кандидата", + "vps.saved": "Кандидат VPS сохранён", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH-ключ", + "vps.ssh_port": "SSH-порт", + "vps.ssh_user": "SSH-пользователь", + "vps.status_candidate": "Готов к установке", + "vps.status_installed": "Relay подключён", + "vps.subtitle": "Подготовка публичного VPS для удалённого доступа, когда у этого сервера WGTools нет белого IP.", + "vps.tenant": "Подключение", + "vps.title": "VPS Relay", + "vps.transport_port": "UDP-порт транспорта", + "vps.transport_port_hint": "Отдельный UDP-порт защищённого туннеля Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Сохранено", + "vps.active_short": "Активно", + "dashboard.traffic_reset": "Сбросить", + "dashboard.traffic_reset_confirm": "Сбросить накопленные счётчики трафика WireGuard для этого интерфейса? Счётчики клиентов также начнутся с нуля.", + "dashboard.traffic_reset_done": "Счётчики трафика сброшены", + "dashboard.traffic_reset_failed": "Не удалось сбросить счётчики трафика", + "audit.action.traffic.reset": "Счётчики трафика сброшены", + "audit.result.reset": "сброшено", + "server.mtu": "MTU", + "server.mtu_auto": "Авто", + "server.mtu_hint": "Необязательно. Пустое поле — автоматический MTU wg-quick. Укажите вручную, например 1380 или 1420, если этого требует сеть, LTE или PPPoE.", + "clients.peer_isolation": "Изоляция VPN-клиента", + "clients.peer_isolation_enable": "Изолировать от других VPN-клиентов", + "clients.peer_isolation_hint": "Блокирует обмен трафиком между этим клиентом и другими адресами из пула WireGuard. Доступ к самому серверу, Интернету, локальным и Site-to-site сетям определяется остальными правилами.", + "clients.credentials_rotate": "Ключи клиента", + "clients.credentials_rotate_button": "Сменить ключи", + "clients.credentials_rotate_confirm": "Сгенерировать новые ключи этого клиента? Если клиент сейчас подключён, его текущая WireGuard-сессия будет принудительно разорвана. После смены нужно выдать новый конфиг или QR.", + "clients.credentials_rotate_confirm_psk": "Сгенерировать новую ключевую пару и новый PSK этого клиента? Если клиент сейчас подключён, его текущая WireGuard-сессия будет принудительно разорвана. После смены нужно выдать новый конфиг или QR.", + "clients.credentials_rotate_hint": "Одной операцией меняет PrivateKey/PublicKey и, если PSK включён, также PSK. Адрес, маршруты, группа, расписание, изоляция и накопленная статистика сохраняются.", + "clients.credentials_rotating": "Генерируем новые ключи и отключаем старую сессию клиента…", + "clients.credentials_rotated": "Ключи клиента сменены. Если клиент был подключён, его старая сессия принудительно отключена. Старый конфиг больше не работает; перед подключением выдайте новый конфиг или QR.", + "clients.credentials_rotated_short": "Ключи клиента сменены — нужен новый конфиг", + "audit.action.client.credentials_rotated": "Ключи клиента обновлены", + "clients.credentials_connection_lost": "Соединение с WGTools прервалось. Если панель была открыта через клиента, которому только что сменили ключи, это ожидаемо: его старая WireGuard-сессия отключается сразу. Подключитесь к WGTools другим способом и выдайте новый конфиг или QR.", + "nav.navigation": "Основная навигация", + "nav.project_github": "WGTools на GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Пока необязательно. После настройки почты адрес можно использовать для восстановления пароля.", + "auth.forgot_password": "Забыли пароль?", + "auth.reset_title": "Сброс пароля", + "auth.reset_subtitle": "Получите одноразовый код по почте и задайте новый пароль WGTools.", + "auth.reset_identifier": "Логин или E-mail", + "auth.reset_identifier_help": "Для защиты данных WGTools всегда показывает одинаковый ответ независимо от существования учётной записи.", + "auth.send_reset_code": "Отправить код", + "auth.reset_code_sent_generic": "Если такая учётная запись существует и для неё указан E-mail, код сброса отправлен. Код действует 15 минут.", + "auth.reset_code": "6-значный код", + "auth.set_new_password": "Установить новый пароль", + "auth.request_another_code": "Запросить другой код", + "auth.back_to_login": "Вернуться ко входу", + "auth.reset_not_configured": "Восстановление пароля по почте не настроено. Обратитесь к администратору WGTools.", + "settings.tab_mail": "Почта", + "settings.mail": "Почта / SMTP", + "settings.mail_subtitle": "SMTP используется для восстановления пароля.", + "settings.mail_not_configured": "Не настроено", + "settings.mail_enabled": "Включить почту и восстановление пароля", + "settings.mail_smtp_host": "SMTP-сервер", + "settings.mail_smtp_port": "SMTP-порт", + "settings.mail_security": "Шифрование", + "settings.mail_security_none": "Без шифрования", + "settings.mail_username": "Логин SMTP", + "settings.mail_username_help": "Используется для авторизации SMTP и как E-mail отправителя.", + "settings.mail_password": "Пароль SMTP", + "settings.mail_password_keep": "Оставьте пустым, чтобы сохранить текущий пароль.", + "settings.mail_from_email": "E-mail отправителя", + "settings.mail_from_name": "Имя отправителя", + "settings.mail_test_recipient": "Получатель теста", + "settings.mail_test_recipient_help": "Тест использует уже сохранённые настройки SMTP.", + "settings.mail_remove_password": "Удалить пароль", + "settings.mail_test": "Отправить тест", + "settings.mail_save": "Сохранить настройки почты", + "settings.mail_enabled_badge": "Включено", + "settings.mail_disabled_badge": "Отключено", + "settings.mail_saved": "Настройки почты сохранены.", + "settings.mail_remove_password_confirm": "Удалить сохранённый пароль SMTP и отключить почту?", + "settings.mail_password_removed": "Пароль SMTP удалён, почта отключена.", + "settings.mail_test_recipient_required": "Укажите E-mail получателя тестового письма.", + "settings.mail_testing": "Отправляем тестовое письмо…", + "settings.mail_test_ok": "Тестовое письмо успешно отправлено.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Необязательно. Нужен только для самостоятельного восстановления пароля.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail сохранён.", + "settings.send_password_reset": "Отправить сброс", + "settings.user_reset_mail_not_configured": "Сначала настройте и включите почту.", + "settings.user_reset_email_missing": "Сначала укажите E-mail пользователя.", + "settings.user_reset_confirm": "Отправить код сброса пароля пользователю {name} на {email}?", + "settings.user_reset_sent": "Код сброса пароля отправлен на {email}.", + "audit.action.auth.password_reset_requested": "Запрошен сброс пароля", + "audit.action.auth.password_reset_code_sent": "Код сброса отправлен", + "audit.action.auth.password_reset_completed": "Пароль восстановлен", + "audit.action.auth.password_reset_failed": "Ошибка сброса пароля", + "audit.action.mail.settings_updated": "Настройки почты изменены", + "audit.action.mail.test_sent": "Тестовое письмо отправлено", + "audit.action.mail.test_failed": "Ошибка тестового письма", + "audit.action.user.email_changed": "E-mail пользователя изменён", + "audit.action.user.password_reset_sent": "Сброс пароля пользователю отправлен", + "audit.action.user.password_reset_failed": "Не удалось отправить сброс пароля", + "audit.result.accepted": "принято", + "audit.result.sent": "отправлено", + "audit.result.invalid_code": "неверный код", + "common.copy": "Копировать", + "common.copied": "Скопировано", + "clients.use_panel_host": "Подставить адрес панели", + "clients.use_panel_host_done": "Адрес панели подставлен: {host}", + "clients.use_panel_host_failed": "Не удалось определить адрес панели из строки браузера.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Встроенный HTTPS Let’s Encrypt для прямого доступа к WGTools без reverse proxy.", + "settings.https_disabled": "Отключено", + "settings.https_enabled": "Включено", + "settings.https_enable": "Включить встроенный HTTPS", + "settings.https_type": "Сертификат для", + "settings.https_domain": "Домен", + "settings.https_public_ip": "Публичный IP", + "settings.https_target": "Домен или публичный IP", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "HTTPS-порт", + "settings.https_port80_note": "TCP-порт 80 должен быть открыт из Интернета для выпуска и автоматического продления сертификата. Для самой панели откройте выбранный HTTPS-порт.", + "settings.https_check_ports": "Проверить порты", + "settings.https_certificate": "Сертификат", + "settings.https_certificate_ready": "Готов", + "settings.https_certificate_missing": "Не выпущен", + "settings.https_expires": "Действует до", + "settings.https_renewal": "Автопродление", + "settings.https_renewal_enabled": "Включено", + "settings.https_renewal_disabled": "Отключено", + "settings.https_certificate_path": "Сертификат", + "settings.https_private_key_path": "Приватный ключ", + "settings.https_issue": "Получить / обновить сертификат", + "settings.https_port_free": "Свободен", + "settings.https_port_busy": "Занят", + "settings.https_ports_checked": "Проверка портов завершена.", + "settings.https_target_email_required": "Укажите домен/публичный IP и e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Получить или обновить сертификат Let’s Encrypt для {target}? Введённые настройки HTTPS будут сохранены. TCP-порт 80 должен быть доступен из Интернета.", + "settings.https_issuing": "Получаем сертификат Let’s Encrypt…", + "settings.https_issue_ok": "Сертификат готов.", + "settings.https_already_enabled": "Встроенный HTTPS уже включён.", + "settings.https_already_disabled": "Встроенный HTTPS уже отключён.", + "settings.https_enable_confirm": "Включить встроенный HTTPS на TCP {port} с путём {path}? WGTools перезапустится, а эта страница переподключится по новому адресу.", + "settings.https_disable_confirm": "Отключить встроенный HTTPS и вернуть WGTools на HTTP?", + "settings.https_switching": "Включаем HTTPS и перезапускаем WGTools…", + "settings.https_switching_http": "Отключаем HTTPS и перезапускаем WGTools…", + "audit.action.https.certificate_issued": "HTTPS-сертификат выпущен", + "audit.action.https.certificate_failed": "Ошибка выпуска HTTPS-сертификата", + "audit.action.https.enabled": "HTTPS включён", + "audit.action.https.disabled": "HTTPS отключён", + "audit.result.issued": "выпущен", + "audit.result.enabled": "включено", + "audit.result.disabled": "отключено", + "settings.https_access_path": "Путь доступа к панели", + "settings.https_access_path_help": "Задайте свой путь. При включённом встроенном HTTPS запросы вне него получают 404.", + "settings.https_enable_fields_required": "Укажите домен/публичный IP, e-mail Let’s Encrypt и путь доступа к панели.", + "settings.https_use_panel_host": "Подставить адрес панели", + "settings.https_reconnecting": "WGTools переключается на новый HTTPS-адрес…", + "server.tab_nodes": "Узлы", + "common.type": "Тип", + "common.status": "Статус", + "common.copy_failed": "Не удалось скопировать", + "clients.vpn_address": "VPN адрес", + "nodes.title": "Узлы WGTools", + "nodes.subtitle": "Объединяйте несколько серверов WGTools в одну защищённую сеть и публикуйте только те сети, которые должны быть доступны другим узлам.", + "nodes.enable_hub": "Включить HUB", + "nodes.connect_hub": "Подключиться к HUB", + "nodes.settings": "Настройки узла", + "nodes.settings_action": "Настройки", + "nodes.sync_now": "Синхронизировать", + "nodes.disable": "Отключить узлы", + "nodes.disable_action": "Отключить", + "nodes.join_title": "Подключение новых узлов", + "nodes.join_help": "Создайте одноразовый код и введите его на другой панели WGTools вместе со служебным endpoint HUB, например vpn.example.com:51950. Код действует 15 минут и используется один раз.", + "nodes.create_code": "Создать код", + "nodes.connected_nodes": "Связанные узлы", + "nodes.connected_nodes_help": "Информация о других панелях, их опубликованных сетях и клиентах. Клиенты удалённых панелей доступны только для просмотра.", + "nodes.enable_hub_help": "Эта панель станет центральным узлом. На одном номере порта HUB принимает UDP WireGuard и защищённый TCP для первоначального pairing.", + "nodes.node_name": "Имя узла", + "nodes.transport_network": "Служебная сеть узлов", + "nodes.transport_help": "Отдельная приватная сеть только для связи WGTools ↔ WGTools. Не должна пересекаться с вашими VPN/LAN сетями.", + "nodes.panel_url": "Адрес панели", + "nodes.panel_url_help": "Необязательно. Это только информационная ссылка для кнопки «Открыть панель» на других узлах и она никак не участвует в работе Nodes.", + "nodes.extra_networks": "Дополнительные сети узла", + "nodes.extra_networks_help": "По одной сети в строке. VPN-сети интерфейсов и удалённые сети Site-to-site клиентов публикуются автоматически. Здесь добавляются только остальные маршрутизируемые LAN/сети, например 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools подставляет найденные VPN-сети, сети Site-to-Site и локальные маршрутизируемые LAN. Оставьте только те сети, которые этот узел должен публиковать в Nodes. По одной сети в строке.", + "nodes.published_networks_settings_help": "По одной сети в строке. Здесь хранится явный список сетей, которые узел публикует в Nodes. Удалённая строка перестаёт распространяться на другие узлы.", + "nodes.available_networks_help": "Сейчас обнаружены: {networks}. Новые сети не публикуются автоматически — добавьте нужные в список выше.", + "nodes.available_networks_none": "Дополнительных локальных сетей сейчас не обнаружено.", + "nodes.connect_help": "Введите служебный endpoint HUB и одноразовый код. Адрес веб-панели, её HTTPS-порт, сертификат и приватный путь для подключения Nodes не используются.", + "nodes.join_code": "Код подключения", + "nodes.connect_reachability_note": "Первоначальный pairing идёт по защищённому TCP на указанном порту. После создания wgnode0 списки сетей, статусы, версии и read-only данные клиентов синхронизируются с HUB по его служебному адресу внутри WireGuard-туннеля.", + "nodes.connect": "Подключить", + "nodes.settings_help": "Имя узла, необязательная ссылка «Открыть панель» и явный список публикуемых сетей. Адрес панели не используется для pairing или синхронизации Nodes.", + "nodes.details": "Подробнее", + "nodes.not_configured": "WGTools Nodes не настроены", + "nodes.not_configured_help": "Включите HUB на этой панели или подключите её к уже существующему WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Подключён к HUB", + "nodes.mode_none": "Не настроено", + "nodes.role": "Роль", + "nodes.tunnel": "Туннель узлов", + "nodes.node_ip": "Адрес узла", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Опубликованные сети", + "nodes.last_sync": "Последняя синхронизация", + "nodes.no_nodes_hub": "Пока нет подключённых узлов. Создайте код подключения и используйте его на другой панели WGTools.", + "nodes.no_nodes_spoke": "Информация об удалённых узлах ещё не получена.", + "nodes.clients_short": "Клиенты", + "nodes.open_panel": "Открыть панель", + "nodes.route_conflict": "Конфликт маршрутов", + "nodes.no_published_networks": "Нет опубликованных сетей", + "nodes.load_failed": "Не удалось загрузить WGTools Nodes", + "nodes.enable_hub_confirm": "Включить WGTools HUB и создать служебный WireGuard-туннель узлов?", + "nodes.applying": "Настраиваем служебный туннель WGTools Nodes…", + "nodes.enable_failed": "Не удалось включить HUB", + "nodes.hub_enabled": "WGTools HUB включён", + "nodes.connecting": "Проверяем код HUB и создаём защищённый туннель узлов…", + "nodes.connect_failed": "Не удалось подключиться к HUB", + "nodes.connected": "Подключено к WGTools HUB", + "nodes.settings_failed": "Не удалось сохранить настройки узла", + "nodes.settings_saved": "Настройки узла сохранены", + "nodes.code_failed": "Не удалось создать код подключения", + "nodes.code_expires": "Одноразовый код. Действует до {time}.", + "nodes.code_copied": "Код подключения скопирован", + "nodes.network_vpn": "VPN-клиенты", + "nodes.network_site_to_site": "Сеть Site-to-site", + "nodes.network_custom": "Дополнительная сеть", + "nodes.conflict": "Конфликт", + "nodes.remote_clients": "Клиенты (только чтение)", + "nodes.no_clients": "Узел не передал список клиентов", + "nodes.details_failed": "Не удалось загрузить информацию об узле", + "nodes.remove_confirm": "Удалить узел «{name}» из HUB? Его доступ через служебный туннель будет отозван.", + "nodes.remove_failed": "Не удалось удалить узел", + "nodes.removed": "Узел удалён", + "nodes.disable_hub_confirm": "Отключить HUB и отсоединить все WGTools Nodes? Служебный туннель будет удалён.", + "nodes.disconnect_confirm": "Отключить эту панель WGTools от HUB и удалить служебный туннель?", + "nodes.disable_failed": "Не удалось отключить WGTools Nodes", + "nodes.disabled": "WGTools Nodes отключены", + "nodes.sync_failed": "Не удалось синхронизировать узел", + "nodes.synced": "Информация об узлах синхронизирована", + "nodes.service_port": "Порт Nodes", + "nodes.service_port_help": "Один номер порта используется одновременно: UDP — WireGuard, TCP — защищённое первоначальное подключение.", + "nodes.hub_port_forward_note": "Если HUB находится за NAT, пробросьте на него один и тот же порт и по UDP, и по TCP. Веб-порт WGTools, HTTPS и приватный путь панели к Nodes не относятся.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Домен или IP и порт Nodes без http:// и https://, например vpn.example.com:51950.", + "settings.collapse_sidebar": "Свернуть панель", + "settings.expand_sidebar": "Развернуть панель", + "settings.https_issue_fields_required": "Укажите домен/публичный IP, e-mail Let’s Encrypt и путь доступа к панели.", + "settings.https_issue_ok_saved": "Сертификат готов, настройки HTTPS сохранены.", + "settings.https_enable_need_certificate": "Сначала получите сертификат.", + "settings.https_enable_certificate_mismatch": "Для текущего домена или публичного IP нужно получить сертификат.", + "settings.https_enable_certificate_expired": "Сертификат истёк. Обновите его перед включением HTTPS.", + "settings.https_enable_certificate_ready": "Сертификат готов — встроенный HTTPS можно включить.", + "settings.https_enable_active_help": "Снимите флажок и сохраните, чтобы вернуться на HTTP.", + "settings.https_certificate_expired": "Истёк", + "settings.https_certificate_wrong_target": "Для другого адреса", + "nodes.network_conflict_error": "Опубликованные сети конфликтуют с другим узлом или служебной сетью Nodes: {conflicts}. Удалите или измените конфликтующую сеть.", + "nodes.networks_changed": "Обнаруженные сети изменились после последнего сохранения. Новые: {added}. Больше не обнаруживаются: {removed}. Проверьте список опубликованных сетей и сохраните настройки после проверки.", + "nodes.review_networks": "Проверьте сети", + "nodes.vpn_pool_mismatch": "VPN-пул изменён: в Nodes всё ещё опубликовано {old}, а текущий VPN-пул WireGuard — {current}. Откройте настройки узла и обновите список опубликованных сетей.", + "server.error_vpn_network_invalid": "VPN-сеть должна быть корректной IPv4-сетью, например 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Поддерживаются только IPv4 VPN-сети.", + "server.error_vpn_network_too_small": "VPN-сеть должна содержать как минимум два доступных адреса.", + "server.error_vpn_network_no_hosts": "В выбранной VPN-сети нет доступных адресов для сервера.", + "server.error_server_address_prefix": "VPN-адрес сервера должен содержать префикс, например 10.0.0.1/24.", + "server.error_server_address_network": "VPN-адрес сервера должен принадлежать выбранному пулу VPN-адресов и использовать тот же префикс.", + "server.error_server_address_reserved": "VPN-адрес сервера не может быть адресом сети или широковещательным адресом.", + "server.error_listen_port_number": "Порт WireGuard должен быть числом.", + "server.error_listen_port_range": "Порт WireGuard должен быть в диапазоне от 1 до 65535.", + "server.error_mtu_number": "MTU должен быть числом.", + "auth.mfa_title": "Двухфакторная аутентификация", + "auth.mfa_login_help": "Введите 6-значный код из Google Authenticator или один из резервных кодов.", + "auth.mfa_code": "Код аутентификации", + "auth.mfa_verify": "Проверить и войти", + "auth.mfa_back": "Вернуться к паролю", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Двухфакторная аутентификация (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Включена", + "settings.mfa_disabled": "Отключена", + "settings.mfa_google_help": "Защитите эту учётную запись с помощью Google Authenticator или другого TOTP-приложения. Для начала настройки нужен текущий пароль.", + "settings.current_password": "Текущий пароль", + "settings.mfa_start": "Настроить Google Authenticator", + "settings.mfa_secret": "Ключ для ручной настройки", + "settings.mfa_scan_help": "Отсканируйте QR-код в Google Authenticator, затем введите текущий 6-значный код для включения MFA.", + "settings.mfa_code": "6-значный код", + "settings.mfa_enable": "Включить MFA", + "settings.mfa_manage_help": "Для изменения MFA введите текущий пароль и код Google Authenticator или резервный код.", + "settings.mfa_code_or_recovery": "Код Authenticator или резервный код", + "settings.mfa_regenerate": "Новые резервные коды", + "settings.mfa_disable": "Отключить MFA", + "settings.mfa_recovery_title": "Резервные коды", + "settings.mfa_recovery_help": "Сохраните эти коды сейчас. Каждый код можно использовать один раз, если Google Authenticator недоступен. Повторно они не показываются.", + "settings.mfa_recovery_remaining": "Осталось резервных кодов: {count}", + "settings.mfa_enabled_ok": "MFA включена.", + "settings.mfa_disabled_ok": "MFA отключена.", + "settings.mfa_disable_confirm": "Отключить двухфакторную аутентификацию для этой учётной записи?", + "settings.mfa_regenerate_confirm": "Заменить все существующие резервные коды?", + "settings.mfa_recovery_regenerated": "Созданы новые резервные коды.", + "audit.action.auth.mfa_failed": "Ошибка проверки MFA", + "audit.action.auth.mfa_recovery_used": "Использован резервный код MFA", + "audit.action.user.mfa_setup_started": "Начата настройка MFA", + "audit.action.user.mfa_enabled": "MFA включена", + "audit.action.user.mfa_disabled": "MFA отключена", + "audit.action.user.mfa_disabled_cli": "MFA отключена через CLI", + "audit.action.user.mfa_recovery_regenerated": "Резервные коды MFA обновлены", + "settings.mfa_error_password": "Неверный текущий пароль.", + "settings.mfa_error_code": "Неверный код аутентификации.", + "settings.mfa_error_already_enabled": "MFA уже включена.", + "settings.mfa_error_not_enabled": "MFA не включена.", + "settings.mfa_error_not_started": "Начните настройку MFA заново.", + "trace.title": "Traceroute, ping и карта маршрута", + "trace.subtitle": "Проверка задержки до VPS или другого сервера и поиск участка маршрута, где растёт ping.", + "trace.target": "IP или имя сервера", + "trace.show_map": "Показать маршрут на карте", + "trace.run": "Запустить", + "trace.geo_note": "Геолокация приблизительная. Если карта включена, публичные IP узлов отправляются в ipwho.is для определения координат; тайлы карты загружаются с OpenStreetMap.", + "trace.latency_note": "Traceroute измеряет задержку в миллисекундах, а не пропускную способность в Мбит/с.", + "trace.map": "Карта маршрута", + "trace.map_hint": "Интерактивная карта: перетаскивайте мышью, масштабируйте колесом или кнопками +/− и нажимайте на узлы для деталей.", + "trace.hop": "Узел / IP", + "trace.location": "Расположение", + "trace.avg_rtt": "Средний RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Потери", + "trace.summary_target": "Цель", + "trace.summary_ping": "Средний ping", + "trace.summary_loss": "Потери ping", + "trace.summary_hops": "Узлов", + "trace.no_reply": "Нет ответа", + "trace.private": "Локальная сеть", + "trace.unknown": "Неизвестно", + "trace.running": "Выполняются ping и traceroute… Это может занять до минуты.", + "trace.done": "Проверка маршрута завершена.", + "trace.failed": "Не удалось выполнить traceroute", + "trace.partial_geo": "Для части публичных узлов не удалось определить геолокацию.", + "trace.not_reached": "Traceroute не дошёл до конечного адреса.", + "trace.reached": "Цель достигнута", + "trace.ms": "мс", + "server.tab_trace": "Маршрут", + "trace.map_controls": "Управление картой", + "trace.zoom_in": "Приблизить", + "trace.zoom_out": "Отдалить", + "trace.fit_route": "Показать весь маршрут", + "trace.fit": "Весь маршрут", + "trace.map_click_hint": "Нажмите на узел, чтобы увидеть IP, расположение, ASN и RTT.", + "trace.route_path": "Маршрут", + "trace.ping_ok_trace_filtered": "Цель отвечает на ping; конечные узлы traceroute не отвечают.", + "trace.latency_legend": "Рост задержки между отвечающими узлами", + "trace.latency_ok": "Δ RTT ≤ 5 мс — нормально", + "trace.latency_warn": "Δ RTT 5–20 мс — рост", + "trace.latency_bad": "Δ RTT > 20 мс — резкий скачок" +} diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..e66a81a --- /dev/null +++ b/app/main.py @@ -0,0 +1,2075 @@ +from __future__ import annotations + +import base64 +import io +import json +import os +import re +import secrets +import threading +import time +from pathlib import Path + +import qrcode +import qrcode.image.svg +from fastapi import FastAPI, Request +from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response, FileResponse +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates +from starlette.middleware.sessions import SessionMiddleware +from starlette.background import BackgroundTask +from pydantic import BaseModel, Field + +from app.core.auth import ( + authenticate, begin_mfa_setup, confirm_mfa_setup, create_user, delete_user, disable_mfa, + get_user, init_database, list_users, load_session_secret, record_login_success, + regenerate_mfa_recovery_codes, set_password, update_user_email, user_count, + verify_password, verify_user_mfa, + get_user_access, set_user_access, +) +from app.core.audit import init_audit_database, list_audit, merge_wireguard_last_seen, record_wireguard_connections, write_audit +from app.core.helper import HelperError, run_helper +from app.core.settings import APP_NAME, ONLINE_THRESHOLD_SECONDS, REFRESH_SECONDS, SESSION_MAX_AGE_SECONDS, VERSION, WG_INTERFACE +from app.core.preferences import get_preferences, init_preferences, update_preferences, get_branding, update_branding +from app.core.telegram_config import get_telegram_settings, init_telegram_settings, test_telegram_connection, update_telegram_settings +from app.core.mail_config import ( + get_mail_settings, init_mail_settings, mask_email, password_recovery_available, + send_test_email, update_mail_settings, +) +from app.core.password_reset import ( + confirm_password_reset, init_password_reset_database, issue_password_reset, + public_reset_request_allowed, request_password_reset, +) +from app.core.help_content import get_help_sections +from app.core.vps import ( + delete_vps_candidate, detach_vps, init_vps_database, install_relay, list_vps, + preflight_vps, reconcile_local_relays, relay_health, save_vps_candidate, +) +from app.core.nodes import ( + DEFAULT_LISTEN_PORT as NODE_DEFAULT_LISTEN_PORT, + DEFAULT_TRANSPORT_NETWORK as NODE_DEFAULT_TRANSPORT_NETWORK, + connect_to_hub, create_join_code, disable_nodes, enable_hub, get_nodes_status, + init_nodes_database, node_control_server_loop, node_details, reconcile_node, + remove_peer, sync_spoke_once, update_local_settings, +) + +BASE_DIR = Path(__file__).resolve().parent +LOCALE_DIR = BASE_DIR / "locales" +SUPPORTED_LANGUAGES = {"en", "ru", "de", "fr", "it", "es", "pl"} +DEFAULT_LANGUAGE = "pl" +PROCESS_INSTANCE = secrets.token_urlsafe(12) +MFA_CHALLENGE_MAX_AGE_SECONDS = 5 * 60 +MFA_CHALLENGE_MAX_ATTEMPTS = 8 + + +def _load_locales() -> dict[str, dict[str, str]]: + result: dict[str, dict[str, str]] = {} + for language in SUPPORTED_LANGUAGES: + path = LOCALE_DIR / f"{language}.json" + try: + data = json.loads(path.read_text(encoding="utf-8")) + result[language] = {str(k): str(v) for k, v in data.items()} + except Exception: + result[language] = {} + return result + + +LOCALES = _load_locales() +# Sparse translation overrides are resolved against English at startup. +# This preserves meaning for untranslated strings and newly added keys. +for _lang, _messages in LOCALES.items(): + if _lang != "en": + LOCALES[_lang] = {**LOCALES.get("en", {}), **_messages} +templates = Jinja2Templates(directory=str(BASE_DIR / "templates")) +app = FastAPI(title=APP_NAME, version=VERSION, docs_url=None, redoc_url=None) +app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static") +init_database() +init_audit_database() +init_preferences() +init_telegram_settings() +init_mail_settings() +init_password_reset_database() +init_vps_database() +init_nodes_database() +# Installed Relay state is durable in SQLite. If this is a restored/reinstalled +# WGTools host, rebuild only the missing local transport and reuse the VPS tenant. +reconcile_local_relays() +reconcile_node() + +_metrics_sampler_started = False +_wg_connection_audit_started = False +_node_sync_started = False +_node_control_thread: threading.Thread | None = None + + +def _metrics_sampler_loop() -> None: + # Keep a rolling host history even when nobody has the Dashboard open. + while True: + try: + run_helper("metrics_sample") + except Exception: + pass + time.sleep(60) + + +@app.on_event("startup") +def _start_metrics_sampler() -> None: + global _metrics_sampler_started + if _metrics_sampler_started: + return + _metrics_sampler_started = True + threading.Thread(target=_metrics_sampler_loop, name="wgtools-metrics", daemon=True).start() + + +def _wg_connection_audit_loop() -> None: + while True: + try: + online_threshold = int(get_preferences().get("online_threshold_seconds") or ONLINE_THRESHOLD_SECONDS) + interfaces = run_helper("interfaces_list") + for item in interfaces.get("interfaces") or []: + iface = str(item.get("name") or "").strip() + if not iface or not item.get("configured") or is_internal_interface(iface): + continue + try: + snapshot = run_helper("snapshot", {"view": "peers"}, interface=iface) + record_wireguard_connections(iface, list(snapshot.get("peers") or []), online_threshold) + except Exception: + continue + except Exception: + pass + time.sleep(60) + + +@app.on_event("startup") +def _start_wg_connection_audit() -> None: + global _wg_connection_audit_started + if _wg_connection_audit_started: + return + _wg_connection_audit_started = True + threading.Thread(target=_wg_connection_audit_loop, name="wgtools-wg-audit", daemon=True).start() + + +def _node_sync_loop() -> None: + while True: + try: + sync_spoke_once() + except Exception: + pass + time.sleep(15) + + +@app.on_event("startup") +def _start_node_sync() -> None: + global _node_sync_started + if _node_sync_started: + return + _node_sync_started = True + threading.Thread(target=_node_sync_loop, name="wgtools-node-sync", daemon=True).start() + + +@app.on_event("startup") +def _start_node_control() -> None: + global _node_control_thread + if _node_control_thread is not None and _node_control_thread.is_alive(): + return + _node_control_thread = threading.Thread( + target=node_control_server_loop, + name="wgtools-node-control", + daemon=True, + ) + _node_control_thread.start() + + +class CreateServerRequest(BaseModel): + display_name: str = Field(default="", max_length=64) + vpn_network: str = Field(min_length=3, max_length=64) + server_address: str = Field(default="", max_length=64) + listen_port: int = Field(default=51820, ge=1, le=65535) + mtu: int = Field(default=0, ge=0, le=65535) + uplink_interface: str = Field(min_length=1, max_length=15) + gateway: str = Field(default="", max_length=64) + local_network: str = Field(default="", max_length=64) + policy_table: str = Field(default="", max_length=12) + nat_enabled: bool = True + ip_forwarding: bool = True + + +class CreateInterfaceRequest(CreateServerRequest): + interface: str = Field(min_length=1, max_length=15, pattern=r"^[A-Za-z0-9_.-]+$") + + +class InterfaceNameRequest(BaseModel): + interface: str = Field(min_length=1, max_length=15, pattern=r"^[A-Za-z0-9_.-]+$") + display_name: str = Field(default="", max_length=64) + + +class InterfaceDeleteRequest(BaseModel): + interface: str = Field(min_length=1, max_length=15, pattern=r"^[A-Za-z0-9_.-]+$") + + +class ServerSettingsRequest(BaseModel): + vpn_network: str = Field(min_length=3, max_length=64) + server_address: str = Field(min_length=3, max_length=64) + listen_port: int = Field(default=51820, ge=1, le=65535) + mtu: int = Field(default=0, ge=0, le=65535) + uplink_interface: str = Field(min_length=1, max_length=15) + gateway: str = Field(default="", max_length=64) + local_network: str = Field(default="", max_length=64) + policy_table: str = Field(default="", max_length=12) + nat_enabled: bool = True + ip_forwarding: bool = True + forward_from_vpn: bool = True + forward_to_vpn: bool = True + + +class HttpsRequest(BaseModel): + target_type: str = Field(default="domain", max_length=16) + target: str = Field(min_length=1, max_length=255) + email: str = Field(min_length=3, max_length=254) + https_port: int = Field(default=443, ge=1, le=65535) + access_path: str = Field(default="", max_length=100) + + +class HttpsPortsRequest(BaseModel): + https_port: int = Field(default=443, ge=1, le=65535) + + +class ClientRequest(BaseModel): + name: str = Field(min_length=1, max_length=64) + type: str = Field(default="client", max_length=32) + vpn_address: str = Field(default="", max_length=64) + remote_networks: list[str] = Field(default_factory=list) + persistent_keepalive: int = Field(default=25, ge=0, le=65535) + endpoint: str = Field(default="", max_length=255) + client_allowed_ips: list[str] = Field(default_factory=list) + route_preset: str = Field(default="", max_length=32) + protect_local_networks: bool = False + local_access_exceptions: list[str] = Field(default_factory=list) + dns: list[str] = Field(default_factory=list) + group_id: str = Field(default="", max_length=64) + policy_mode: str = Field(default="", max_length=16) + internet_access: str = Field(default="", max_length=16) + local_access: str = Field(default="", max_length=16) + policy_allow: list[str] = Field(default_factory=list) + policy_deny: list[str] = Field(default_factory=list) + config_mode: str = Field(default="", max_length=16) + use_preshared_key: bool = True + peer_isolation: bool = False + expires_at: int = Field(default=0, ge=0, le=4102444800) + expiration_action: str = Field(default="delete", max_length=16) + access_schedule_enabled: bool = False + access_schedule_days: list[int] = Field(default_factory=list) + access_schedule_start: str = Field(default="08:00", max_length=5) + access_schedule_end: str = Field(default="19:00", max_length=5) + connection_mode: str = Field(default="direct", max_length=16) + relay_vps_id: str = Field(default="", max_length=64) + + +class UpdateClientRequest(ClientRequest): + public_key: str = Field(min_length=20, max_length=128) + + +class ClientKeyRequest(BaseModel): + public_key: str = Field(min_length=20, max_length=128) + + +class ClientGroupRequest(BaseModel): + name: str = Field(min_length=1, max_length=64) + description: str = Field(default="", max_length=240) + internet_access: str = Field(default="allow", max_length=16) + local_access: str = Field(default="allow", max_length=16) + policy_allow: list[str] = Field(default_factory=list) + policy_deny: list[str] = Field(default_factory=list) + route_preset: str = Field(default="full", max_length=32) + client_allowed_ips: list[str] = Field(default_factory=list) + dns: list[str] = Field(default_factory=list) + persistent_keepalive: int = Field(default=25, ge=0, le=65535) + + +class UpdateClientGroupRequest(ClientGroupRequest): + group_id: str = Field(min_length=3, max_length=64) + + +class DeleteClientGroupRequest(BaseModel): + group_id: str = Field(min_length=3, max_length=64) + move_to_group_id: str = Field(default="", max_length=64) + + +class VpsPreflightRequest(BaseModel): + name: str = Field(min_length=1, max_length=64) + host: str = Field(min_length=1, max_length=255) + ssh_port: int = Field(default=22, ge=1, le=65535) + ssh_user: str = Field(min_length=1, max_length=64) + auth_method: str = Field(default="password", max_length=16) + password: str = Field(default="", max_length=512) + private_key: str = Field(default="", max_length=32768) + key_passphrase: str = Field(default="", max_length=512) + endpoint_domain: str = Field(default="", max_length=255) + relay_port: int = Field(default=51820, ge=1, le=65535) + transport_port: int = Field(default=51900, ge=1, le=65535) + + +class VpsCandidateSaveRequest(VpsPreflightRequest): + preflight: dict = Field(default_factory=dict) + + +class VpsInstallRequest(BaseModel): + auth_method: str = Field(default="password", max_length=16) + password: str = Field(default="", max_length=512) + private_key: str = Field(default="", max_length=32768) + key_passphrase: str = Field(default="", max_length=512) + + +class RouteRequest(BaseModel): + network: str = Field(min_length=1, max_length=64) + gateway: str = Field(default="", max_length=64) + device: str = Field(default="", max_length=15) + table: str = Field(default="main", max_length=16) + + +class UpdateRouteRequest(RouteRequest): + original_command: str = Field(min_length=3, max_length=1024) + + +class RouteKeyRequest(BaseModel): + original_command: str = Field(min_length=3, max_length=1024) + + +class AccessRuleRequest(BaseModel): + source: str = Field(default="", max_length=64) + destination: str = Field(default="", max_length=512) + action: str = Field(default="REJECT", max_length=16) + protocol: str = Field(default="any", max_length=16) + destination_port: str = Field(default="", max_length=16) + + +class UpdateAccessRuleRequest(AccessRuleRequest): + original_command: str = Field(min_length=3, max_length=2048) + + +class AccessRuleKeyRequest(BaseModel): + original_command: str = Field(min_length=3, max_length=2048) + + +class RawConfigRequest(BaseModel): + content: str = Field(min_length=1, max_length=1024 * 1024) + + +class AuthRequest(BaseModel): + username: str = Field(min_length=1, max_length=64) + password: str = Field(min_length=1, max_length=256) + email: str = Field(default="", max_length=254) + + +class UserEmailRequest(BaseModel): + email: str = Field(default="", max_length=254) + + +class MfaCodeRequest(BaseModel): + code: str = Field(min_length=6, max_length=32) + + +class MfaPasswordRequest(BaseModel): + password: str = Field(min_length=1, max_length=256) + + +class MfaManageRequest(BaseModel): + password: str = Field(min_length=1, max_length=256) + code: str = Field(min_length=6, max_length=32) + + +class MailSettingsRequest(BaseModel): + enabled: bool = False + smtp_host: str = Field(default="", max_length=253) + smtp_port: int = Field(default=587, ge=1, le=65535) + security: str = Field(default="starttls", max_length=16) + username: str = Field(default="", max_length=254) + password: str = Field(default="", max_length=512) + clear_password: bool = False + from_email: str = Field(default="", max_length=254) + from_name: str = Field(default="WGTools", max_length=120) + + +class MailTestRequest(BaseModel): + recipient: str = Field(min_length=3, max_length=254) + + +class PasswordResetRequest(BaseModel): + identifier: str = Field(min_length=1, max_length=254) + + +class PasswordResetConfirmRequest(BaseModel): + identifier: str = Field(min_length=1, max_length=254) + code: str = Field(min_length=6, max_length=6) + password: str = Field(min_length=8, max_length=256) + + +class NodeHubEnableRequest(BaseModel): + node_name: str = Field(default="", max_length=64) + listen_port: int = Field(default=NODE_DEFAULT_LISTEN_PORT, ge=1, le=65535) + transport_network: str = Field(default=NODE_DEFAULT_TRANSPORT_NETWORK, max_length=64) + published_networks: list[str] | None = None + extra_networks: list[str] = Field(default_factory=list) + + +class NodeConnectRequest(BaseModel): + node_name: str = Field(default="", max_length=64) + hub_endpoint: str = Field(min_length=1, max_length=320) + join_code: str = Field(min_length=8, max_length=256) + published_networks: list[str] | None = None + extra_networks: list[str] = Field(default_factory=list) + + +class NodeSettingsRequest(BaseModel): + node_name: str = Field(default="", max_length=64) + panel_url: str = Field(default="", max_length=512) + published_networks: list[str] | None = None + extra_networks: list[str] = Field(default_factory=list) + + +class AppSettingsRequest(BaseModel): + refresh_seconds: int = Field(default=5, ge=2, le=60) + online_threshold_seconds: int = Field(default=180, ge=30, le=3600) + backup_retention: int = Field(default=20, ge=1, le=200) + + +class BrandingRequest(BaseModel): + name: str = Field(default="", max_length=80) + color: str = Field(default="#8f1f27", max_length=7) + logo: str = Field(default="", max_length=400000) + + +class UserAccessRequest(BaseModel): + role: str + interfaces: list[str] = Field(default_factory=list, max_length=100) + permissions: dict[str, list[str]] | None = None + + +class ExtendedSnatRequest(BaseModel): + address: str = Field(default="", max_length=15) + uplink: str = Field(default="", max_length=15) + + +class ExtendedListenRequest(BaseModel): + address: str = Field(default="", max_length=15) + interface: str = Field(default="", max_length=15) + + +class ExtendedIPGroupRequest(BaseModel): + name: str = Field(min_length=1, max_length=64) + addresses: list[str] = Field(default_factory=list, max_length=256) + interfaces: list[str] = Field(default_factory=list, max_length=100) + delete: bool = False + + +class ExtendedForwardRequest(BaseModel): + public_ip: str = Field(max_length=15) + public_port: int = Field(ge=1, le=65535) + target_ip: str = Field(max_length=15) + target_port: int = Field(ge=1, le=65535) + protocol: str = Field(max_length=4) + + +class ExtendedForwardDeleteRequest(BaseModel): + id: str = Field(pattern=r"^[0-9a-f]{16}$") + + +class NetworkTraceRequest(BaseModel): + target: str = Field(min_length=1, max_length=320) + geolocate: bool = True + language: str = Field(default="en", max_length=8) + + +class PasswordRequest(BaseModel): + password: str = Field(min_length=1, max_length=256) + + +class UpdateApplyRequest(BaseModel): + tag: str = Field(min_length=2, max_length=64) + + +class TelegramSettingsRequest(BaseModel): + enabled: bool = False + bot_token: str = Field(default="", max_length=256) + clear_token: bool = False + allowed_user_ids: list[int] = Field(default_factory=list) + default_endpoint: str = Field(default="", max_length=253) + default_dns: list[str] = Field(default_factory=list) + language: str = Field(default="auto", max_length=8) + + +def request_language(request: Request) -> str: + value = (request.cookies.get("wgtools_language") or DEFAULT_LANGUAGE).strip().lower() + return value if value in SUPPORTED_LANGUAGES else DEFAULT_LANGUAGE + + +IFACE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,15}$") +INTERNAL_INTERFACE_PREFIXES = ("wgrly", "wgnode") + + +def is_internal_interface(name: str) -> bool: + value = str(name or "").strip().lower() + return any(value.startswith(prefix) for prefix in INTERNAL_INTERFACE_PREFIXES) + + +def request_interface(request: Request) -> str: + current = getattr(request.state, "current_user", None) + access = get_user_access(int(current["id"])) if current else {"role": "admin", "interfaces": []} + default_iface = (access["interfaces"][0] if access["role"] == "user" and access["interfaces"] else WG_INTERFACE) + value = (request.cookies.get("wgtools_interface") or default_iface).strip() + if not IFACE_RE.fullmatch(value) or is_internal_interface(value): + fallback = str(WG_INTERFACE or "wg0").strip() + return fallback if IFACE_RE.fullmatch(fallback) and not is_internal_interface(fallback) else "wg0" + return value + + +def request_base_path(request: Request) -> str: + value = str(request.scope.get("root_path") or "").rstrip("/") + return value if value.startswith("/") else "" + + +def request_route_path(request: Request) -> str: + path = request.url.path + base = request_base_path(request) + if base and path.startswith(base): + path = path[len(base):] or "/" + return path + + +def app_url(request: Request, path: str) -> str: + base = request_base_path(request) + suffix = path if path.startswith("/") else f"/{path}" + return f"{base}{suffix}" or "/" + + +def render(request: Request, template: str, page: str, title_key: str) -> HTMLResponse: + language = request_language(request) + branding = get_branding() + messages = {key: re.sub(r"WGTools(?:-Extended)?", lambda _: branding['name'] or 'panel', value) for key, value in (LOCALES.get(language) or LOCALES.get(DEFAULT_LANGUAGE, {})).items()} + preferences = get_preferences() + + def tr(key: str, fallback: str | None = None) -> str: + return messages.get(key) or fallback or key + + messages_json = json.dumps(messages, ensure_ascii=False).replace(" HTMLResponse: + language = request_language(request) + branding = get_branding() + messages = {key: re.sub(r"WGTools(?:-Extended)?", lambda _: branding['name'] or 'panel', value) for key, value in (LOCALES.get(language) or LOCALES.get(DEFAULT_LANGUAGE, {})).items()} + + def tr(key: str, fallback: str | None = None) -> str: + return messages.get(key) or fallback or key + + return templates.TemplateResponse( + request=request, + name=template, + context={ + "app_name": APP_NAME, + "branding": branding, + "version": VERSION, + "asset_rev": PROCESS_INSTANCE, + "page": page, + "base_path": request_base_path(request), + "language": language, + "tr": tr, + "error": error, + "password_recovery_available": password_recovery_available(), + }, + headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"}, + ) + + +def request_ip(request: Request | None) -> str: + if request is None or request.client is None: + return "" + return str(request.client.host or "")[:120] + + +def audit_username(request: Request | None = None, fallback: str = "system") -> str: + if request is not None: + current = getattr(request.state, "current_user", None) + if current and current.get("username"): + return str(current["username"]) + return fallback + + +def audit_action(request: Request | None, action: str, *, object: str = "", result: str = "ok", details: dict | None = None) -> None: + try: + write_audit(audit_username(request), action, object=object, result=result, details=details) + except Exception: + pass + + +PUBLIC_PREFIXES = ("/static/",) +PUBLIC_PATHS = { + "/healthz", "/robots.txt", "/login", "/setup", "/forgot-password", + "/api/auth/login", "/api/auth/setup", "/api/auth/mfa", + "/api/auth/password-reset/request", "/api/auth/password-reset/confirm", +} + + +@app.middleware("http") +async def require_authentication(request: Request, call_next): + path = request_route_path(request) + if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES): + return await call_next(request) + + users_exist = user_count() > 0 + user_id = request.session.get("user_id") + current = get_user(int(user_id)) if user_id else None + if user_id and not current: + request.session.clear() + if current: + current_version = int(current.get("session_version") or 1) + session_version = request.session.get("session_version") + if session_version is None: + # Sessions created before this feature may be upgraded only while the + # account still has its initial session version. After any password + # change/reset, an old cookie without a version must be rejected. + if current_version == 1: + request.session["session_version"] = current_version + else: + request.session.clear() + current = None + elif int(session_version) != current_version: + request.session.clear() + current = None + + if not users_exist: + if path.startswith("/api/"): + return JSONResponse(status_code=428, content={"ok": False, "error": "Initial user setup is required"}) + return RedirectResponse(url=app_url(request, "/setup"), status_code=303) + + if not current: + if path.startswith("/api/"): + return JSONResponse(status_code=401, content={"ok": False, "error": "Authentication required"}) + next_path = path if path.startswith("/") else "/" + return RedirectResponse(url=f"{app_url(request, '/login')}?next={next_path}", status_code=303) + + request.state.current_user = current + access = get_user_access(int(current["id"])) + request.state.access = access + if access["role"] != "admin": + allowed = {"/clients", "/api/interfaces", "/api/snapshot", "/api/app-settings", "/api/auth/logout", "/api/clients/create", "/api/clients/update", "/api/clients/credentials/rotate", "/api/clients/config", "/api/clients/config/download", "/api/clients/qr", "/api/extended/forwardings", "/api/extended/forwardings/delete"} + if path == "/": + return RedirectResponse(url=app_url(request, "/clients"), status_code=303) + if path not in allowed or (path == "/api/app-settings" and request.method != "GET"): + return JSONResponse(status_code=403, content={"ok": False, "error": "Brak uprawnień"}) + if path.startswith("/api/clients/") or path.startswith("/api/extended/forwardings") or path == "/api/snapshot": + iface = request_interface(request) + if iface not in access["interfaces"]: + return JSONResponse(status_code=403, content={"ok": False, "error": "Brak dostępu do tej sieci"}) + required = None + if path == '/api/clients/create': + required = 'add' + elif path in {'/api/clients/update', '/api/clients/credentials/rotate'}: + required = 'edit' + elif path.startswith('/api/extended/forwardings') and request.method != 'GET': + required = 'forward' + if required and required not in access['permissions'].get(iface, []): + return JSONResponse(status_code=403, content={"ok": False, "error": "Brak uprawnienia do tej operacji w wybranej sieci"}) + return await call_next(request) + + +# SessionMiddleware is registered after the authentication middleware so it wraps it +# and request.session is available inside the guard. +app.add_middleware( + SessionMiddleware, + secret_key=load_session_secret(), + session_cookie="wgtools_session", + max_age=SESSION_MAX_AGE_SECONDS, + same_site="lax", + https_only=False, +) + + +@app.get("/robots.txt", include_in_schema=False) +def robots_txt(): + return Response( + content="User-agent: *\nDisallow: /\n", + media_type="text/plain", + headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"}, + ) + + +@app.get("/setup", response_class=HTMLResponse) +def setup_page(request: Request): + if user_count() > 0: + return RedirectResponse(url=app_url(request, "/login"), status_code=303) + return render_auth(request, "setup.html", "setup") + + +@app.get("/login", response_class=HTMLResponse) +def login_page(request: Request): + if user_count() == 0: + return RedirectResponse(url=app_url(request, "/setup"), status_code=303) + user_id = request.session.get("user_id") + if user_id and get_user(int(user_id)): + return RedirectResponse(url=app_url(request, "/"), status_code=303) + return render_auth(request, "login.html", "login") + + +@app.get("/forgot-password", response_class=HTMLResponse) +def forgot_password_page(request: Request): + if user_count() == 0: + return RedirectResponse(url=app_url(request, "/setup"), status_code=303) + return render_auth(request, "forgot_password.html", "forgot-password") + + +@app.post("/api/auth/setup") +def api_auth_setup(request: Request, payload: AuthRequest): + if user_count() > 0: + return JSONResponse(status_code=409, content={"ok": False, "error": "Initial setup has already been completed"}) + try: + user = create_user(payload.username, payload.password, payload.email) + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + request.session.clear() + request.session["user_id"] = int(user["id"]) + request.session["session_version"] = int(user.get("session_version") or 1) + try: + write_audit(str(user["username"]), "auth.first_user_created", object=user["username"], result="created") + except Exception: + pass + return {"ok": True, "user": user} + + +@app.post("/api/auth/login") +def api_auth_login(request: Request, payload: AuthRequest): + user = authenticate(payload.username, payload.password, record_login=False) + if not user: + try: + ip = request_ip(request) + obj = f"login · IP {ip}" if ip else "login" + write_audit(str(payload.username or "unknown"), "auth.login_failed", object=obj, result="invalid credentials") + except Exception: + pass + return JSONResponse(status_code=401, content={"ok": False, "error": "Invalid username or password"}) + + if bool(user.get("mfa_enabled")): + request.session.clear() + request.session["mfa_user_id"] = int(user["id"]) + request.session["mfa_session_version"] = int(user.get("session_version") or 1) + request.session["mfa_started_at"] = int(time.time()) + request.session["mfa_attempts"] = 0 + return {"ok": True, "mfa_required": True} + + user = record_login_success(int(user["id"])) + request.session.clear() + request.session["user_id"] = int(user["id"]) + request.session["session_version"] = int(user.get("session_version") or 1) + try: + write_audit(str(user["username"]), "auth.login", object=user["username"], result="ok") + except Exception: + pass + return {"ok": True, "user": user, "mfa_required": False} + + +@app.post("/api/auth/mfa") +def api_auth_mfa(request: Request, payload: MfaCodeRequest): + user_id = int(request.session.get("mfa_user_id") or 0) + started_at = int(request.session.get("mfa_started_at") or 0) + expected_version = int(request.session.get("mfa_session_version") or 0) + now = int(time.time()) + attempts = int(request.session.get("mfa_attempts") or 0) + user = get_user(user_id) if user_id else None + if (not user or not bool(user.get("mfa_enabled")) or not started_at + or now - started_at > MFA_CHALLENGE_MAX_AGE_SECONDS + or attempts >= MFA_CHALLENGE_MAX_ATTEMPTS + or expected_version != int(user.get("session_version") or 1)): + request.session.clear() + return JSONResponse(status_code=401, content={"ok": False, "error": "MFA challenge expired. Sign in again."}) + + result = verify_user_mfa(user_id, payload.code, consume_recovery=True) + if not result.get("ok"): + attempts += 1 + request.session["mfa_attempts"] = attempts + try: + ip = request_ip(request) + obj = f"MFA · IP {ip}" if ip else "MFA" + write_audit(str(user["username"]), "auth.mfa_failed", object=obj, result="invalid code") + except Exception: + pass + if attempts >= MFA_CHALLENGE_MAX_ATTEMPTS: + request.session.clear() + return JSONResponse(status_code=401, content={"ok": False, "error": "Too many invalid MFA attempts. Sign in again."}) + return JSONResponse(status_code=401, content={"ok": False, "error": "Invalid authentication code"}) + + user = record_login_success(user_id) + request.session.clear() + request.session["user_id"] = user_id + request.session["session_version"] = int(user.get("session_version") or 1) + try: + write_audit(str(user["username"]), "auth.login", object=user["username"], result="ok", details={"mfa": result.get("method")}) + if result.get("method") == "recovery": + write_audit(str(user["username"]), "auth.mfa_recovery_used", object=user["username"], result="used", details={"remaining": result.get("recovery_remaining")}) + except Exception: + pass + return {"ok": True, "user": user, "mfa_method": result.get("method")} + + +def _deliver_public_password_reset(identifier: str, ip: str, language: str) -> None: + try: + result = request_password_reset(identifier, request_ip=ip, rate_checked=True, language=language) + if result.get("delivered"): + actor = str(result.get("username") or "anonymous") + write_audit( + actor, + "auth.password_reset_code_sent", + object=actor, + result="sent", + details={"email": result.get("masked_email"), "ip": ip}, + ) + except Exception as exc: + try: + write_audit("anonymous", "auth.password_reset_failed", object=f"password recovery · IP {ip}" if ip else "password recovery", result=f"error: {exc}") + except Exception: + pass + + +@app.post("/api/auth/password-reset/request") +def api_auth_password_reset_request(request: Request, payload: PasswordResetRequest): + generic = { + "ok": True, + "message": "If the account exists and has an email address, a password reset code has been sent.", + } + ip = request_ip(request) + try: + allowed = public_reset_request_allowed(payload.identifier, ip) + if allowed: + # Log accepted recovery requests, but do not let a rate-limited public + # endpoint become an unlimited Audit-log flooding path. + write_audit("anonymous", "auth.password_reset_requested", object=f"password recovery · IP {ip}" if ip else "password recovery", result="accepted") + threading.Thread( + target=_deliver_public_password_reset, + args=(str(payload.identifier), ip, request_language(request)), + name="wgtools-password-reset", + daemon=True, + ).start() + except Exception: + # Public recovery deliberately returns the same response on internal errors. + pass + return generic + + +@app.post("/api/auth/password-reset/confirm") +def api_auth_password_reset_confirm(request: Request, payload: PasswordResetConfirmRequest): + ip = request_ip(request) + try: + result = confirm_password_reset(payload.identifier, payload.code, payload.password) + write_audit( + str(result.get("username") or "anonymous"), + "auth.password_reset_completed", + object=str(result.get("username") or "password recovery"), + result="changed", + details={"email": result.get("masked_email"), "ip": ip}, + ) + request.session.clear() + return {"ok": True} + except ValueError: + try: + write_audit("anonymous", "auth.password_reset_failed", object=f"password recovery · IP {ip}" if ip else "password recovery", result="invalid code") + except Exception: + pass + return JSONResponse(status_code=400, content={"ok": False, "error": "Invalid or expired reset code"}) + + +@app.post("/api/auth/logout") +def api_auth_logout(request: Request): + audit_action(request, "auth.logout", object=audit_username(request), result="ok") + request.session.clear() + return {"ok": True} + + +@app.get("/api/app-settings") +def api_app_settings(): + return {"ok": True, "settings": get_preferences()} + + +@app.post("/api/app-settings") +def api_app_settings_update(payload: AppSettingsRequest, request: Request): + try: + settings = update_preferences(**payload.model_dump()) + audit_action(request, "settings.updated", object="application settings", result="saved", details=payload.model_dump()) + return {"ok": True, "settings": settings} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/branding") +def api_branding(payload: BrandingRequest, request: Request): + try: + branding = update_branding(payload.name, payload.color, payload.logo) + audit_action(request, "branding.updated", object="branding", result="saved") + return {"ok": True, "branding": branding} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/update/check") +def api_update_check(request: Request): + try: + data = run_helper("update_check") + audit_action(request, "update.checked", object="GitHub release", result="available" if data.get("update_available") else "current", details={"latest_version": data.get("latest_version")}) + return data + except HelperError as exc: + return JSONResponse(status_code=502, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/update/notice") +def api_update_notice(): + try: + return run_helper("update_notice") + except HelperError as exc: + # Notification checks are informational and must never break navigation. + return {"ok": True, "update_available": False, "latest_version": "", "check_error": str(exc)} + + +@app.get("/api/update/status") +def api_update_status(): + try: + return run_helper("update_status") + except HelperError as exc: + return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/update/apply") +def api_update_apply(payload: UpdateApplyRequest, request: Request): + try: + result = run_helper("update_schedule", {"tag": payload.tag}) + audit_action(request, "update.scheduled", object=payload.tag, result="queued" if result.get("scheduled") else "current") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/update/upload") +async def api_update_upload(request: Request): + import_root = Path("/var/lib/wgtools/imports") + import_root.mkdir(parents=True, exist_ok=True) + import_root.chmod(0o700) + path = import_root / f"upload-{secrets.token_hex(12)}.bin" + scheduled = False + try: + total = 0 + with path.open('wb') as handle: + path.chmod(0o600) + async for chunk in request.stream(): + total += len(chunk) + if total > 64 * 1024 * 1024: + raise ValueError("Pakiet przekracza limit 64 MB") + handle.write(chunk) + if not total: + raise ValueError("Pakiet jest pusty") + result = run_helper('update_file_schedule', {'path': str(path)}, interface=request_interface(request)) + scheduled = bool(result.get('scheduled')) + audit_action(request, 'update.upload_scheduled', object=str(result.get('target_version') or ''), result='queued') + return result + except (ValueError, HelperError) as exc: + return JSONResponse(status_code=400, content={'ok': False, 'error': str(exc)}) + finally: + if not scheduled: + _unlink_quiet(path) + + +def _unlink_quiet(path: Path) -> None: + try: + path.unlink() + except FileNotFoundError: + pass + except OSError: + pass + + +@app.get("/api/migration/backup") +def api_migration_backup(request: Request): + try: + result = run_helper("migration_backup_create") + path = Path(str(result.get("path") or "")) + export_root = Path("/var/lib/wgtools/exports").resolve() + try: + path.resolve().relative_to(export_root) + except Exception as exc: + raise HelperError("Backup helper returned an unsafe path") from exc + if not path.exists(): + raise HelperError("Backup file was not created") + filename = str(result.get("filename") or path.name) + audit_action(request, "backup.full_created", object=filename, result="downloaded") + return FileResponse( + path=str(path), + filename=filename, + media_type="application/octet-stream", + background=BackgroundTask(_unlink_quiet, path), + ) + except HelperError as exc: + return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/migration/restore") +async def api_migration_restore(request: Request): + import_root = Path("/var/lib/wgtools/imports") + import_root.mkdir(parents=True, exist_ok=True) + import_root.chmod(0o700) + path = import_root / f"upload-{secrets.token_hex(12)}.wgtbackup" + limit = 64 * 1024 * 1024 + total = 0 + try: + with path.open("wb") as handle: + path.chmod(0o600) + async for chunk in request.stream(): + total += len(chunk) + if total > limit: + raise ValueError("Backup file exceeds the 64 MB safety limit") + handle.write(chunk) + if total == 0: + raise ValueError("Backup file is empty") + result = run_helper("migration_restore", {"path": str(path)}) + # The restored database contains the original Relay tenant identity and + # transport keys. Rebuild the home side only; never provision a new VPS tenant. + result["relay_reconcile"] = reconcile_local_relays() + audit_action(request, "backup.full_restored", object=path.name, result="restored") + request.session.clear() + return result + except ValueError as exc: + return JSONResponse(status_code=413 if "64 MB" in str(exc) else 400, content={"ok": False, "error": str(exc)}) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + finally: + _unlink_quiet(path) + +@app.get("/api/https/status") +def api_https_status(request: Request): + try: + return run_helper("https_status", interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/https/ports") +def api_https_ports(payload: HttpsPortsRequest, request: Request): + try: + return run_helper("https_ports", {"https_port": payload.https_port}, interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/https/issue") +def api_https_issue(payload: HttpsRequest, request: Request): + try: + result = run_helper("https_issue", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "https.certificate_issued", object=payload.target, result="issued", details={"type": payload.target_type, "email": mask_email(payload.email)}) + return result + except HelperError as exc: + audit_action(request, "https.certificate_failed", object=payload.target, result=f"error: {exc}", details={"type": payload.target_type}) + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/https/enable") +def api_https_enable(payload: HttpsRequest, request: Request): + try: + result = run_helper("https_enable", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "https.enabled", object=payload.target, result="enabled") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/https/disable") +def api_https_disable(request: Request): + try: + result = run_helper("https_disable", interface=request_interface(request)) + audit_action(request, "https.disabled", object="built-in HTTPS", result="disabled") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/mail/settings") +def api_mail_settings(): + return {"ok": True, "settings": get_mail_settings()} + + +@app.post("/api/mail/settings") +def api_mail_settings_update(payload: MailSettingsRequest, request: Request): + try: + settings = update_mail_settings(**payload.model_dump()) + audit_action(request, "mail.settings_updated", object="SMTP", result="saved", details=payload.model_dump()) + return {"ok": True, "settings": settings} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/mail/test") +def api_mail_test(payload: MailTestRequest, request: Request): + try: + result = send_test_email(payload.recipient, language=request_language(request)) + audit_action(request, "mail.test_sent", object=mask_email(payload.recipient), result="sent") + return result + except (ValueError, RuntimeError) as exc: + audit_action(request, "mail.test_failed", object=mask_email(payload.recipient), result=f"error: {exc}") + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/telegram/settings") +def api_telegram_settings(): + return {"ok": True, "settings": get_telegram_settings()} + + +@app.post("/api/telegram/settings") +def api_telegram_settings_update(payload: TelegramSettingsRequest, request: Request): + try: + settings = update_telegram_settings( + enabled=payload.enabled, + bot_token=payload.bot_token, + clear_token=payload.clear_token, + allowed_user_ids=payload.allowed_user_ids, + default_endpoint=payload.default_endpoint, + default_dns=payload.default_dns, + language=payload.language, + ) + audit_action(request, "telegram.settings_updated", object="Telegram Bot", result="saved", details=payload.model_dump()) + return {"ok": True, "settings": settings} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/telegram/test") +def api_telegram_test(request: Request): + try: + result = test_telegram_connection() + audit_action(request, "telegram.connection_test", object=f"@{result.get('username') or 'bot'}", result="ok") + return result + except Exception as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/users") +def api_users(request: Request): + current_id = int(request.session.get("user_id")) + users = list_users() + for user in users: + user["access"] = get_user_access(user["id"]) + return {"ok": True, "users": users, "current_user_id": current_id, "mail_configured": password_recovery_available()} + + +@app.post("/api/users/{user_id}/access") +def api_user_access(user_id: int, payload: UserAccessRequest, request: Request): + if user_id == int(request.session.get("user_id") or 0) and payload.role != "admin": + return JSONResponse(status_code=400, content={"ok": False, "error": "Nie można odebrać własnych uprawnień administratora"}) + try: + access = set_user_access(user_id, payload.role, payload.interfaces, payload.permissions) + audit_action(request, "user.access_updated", object=str(user_id), result="saved", details=access) + return {"ok": True, "access": access} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/users") +def api_users_create(payload: AuthRequest, request: Request): + try: + user = create_user(payload.username, payload.password, payload.email) + audit_action(request, "user.created", object=user["username"], result="created", details={"email": mask_email(str(user.get("email") or ""))}) + return {"ok": True, "user": user} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/users/{user_id}/password") +def api_users_password(user_id: int, payload: PasswordRequest, request: Request): + try: + set_password(user_id, payload.password) + user = get_user(user_id) + audit_action(request, "user.password_changed", object=str((user or {}).get("username") or user_id), result="changed") + reauthenticate = user_id == int(request.session.get("user_id") or 0) + if reauthenticate: + request.session.clear() + return {"ok": True, "reauthenticate": reauthenticate} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/users/{user_id}/email") +def api_users_email(user_id: int, payload: UserEmailRequest, request: Request): + try: + user = update_user_email(user_id, payload.email) + audit_action( + request, + "user.email_changed", + object=str(user.get("username") or user_id), + result="changed", + details={"email": mask_email(str(user.get("email") or ""))}, + ) + return {"ok": True, "user": user} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/users/{user_id}/password-reset") +def api_users_password_reset(user_id: int, request: Request): + user = get_user(user_id) + if not user: + return JSONResponse(status_code=404, content={"ok": False, "error": "User not found"}) + try: + result = issue_password_reset(user_id, request_ip=request_ip(request), language=request_language(request)) + audit_action( + request, + "user.password_reset_sent", + object=str(user.get("username") or user_id), + result="sent", + details={"email": result.get("masked_email")}, + ) + return {"ok": True, "masked_email": result.get("masked_email", "")} + except (ValueError, RuntimeError) as exc: + audit_action(request, "user.password_reset_failed", object=str(user.get("username") or user_id), result=f"error: {exc}") + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.delete("/api/users/{user_id}") +def api_users_delete(request: Request, user_id: int): + current_id = int(request.session.get("user_id")) + if user_id == current_id: + return JSONResponse(status_code=400, content={"ok": False, "error": "You cannot delete the user that is currently signed in"}) + try: + user = get_user(user_id) + delete_user(user_id) + audit_action(request, "user.deleted", object=str((user or {}).get("username") or user_id), result="deleted") + return {"ok": True} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/users/mfa/status") +def api_users_mfa_status(request: Request): + user_id = int(request.session.get("user_id") or 0) + user = get_user(user_id) + if not user: + return JSONResponse(status_code=404, content={"ok": False, "error": "User not found"}) + return { + "ok": True, + "enabled": bool(user.get("mfa_enabled")), + "recovery_remaining": int(user.get("mfa_recovery_remaining") or 0), + } + + +@app.post("/api/users/mfa/setup") +def api_users_mfa_setup(payload: MfaPasswordRequest, request: Request): + user_id = int(request.session.get("user_id") or 0) + if not verify_password(user_id, payload.password): + return JSONResponse(status_code=401, content={"ok": False, "error": "Invalid current password"}) + try: + setup = begin_mfa_setup(user_id) + image = qrcode.make(setup["uri"], box_size=7, border=2) + output = io.BytesIO() + image.save(output, format="PNG") + qr_data = "data:image/png;base64," + base64.b64encode(output.getvalue()).decode("ascii") + audit_action(request, "user.mfa_setup_started", object=str(setup.get("username") or user_id), result="started") + return {"ok": True, "secret": setup["secret"], "qr": qr_data} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/users/mfa/confirm") +def api_users_mfa_confirm(payload: MfaCodeRequest, request: Request): + user_id = int(request.session.get("user_id") or 0) + try: + result = confirm_mfa_setup(user_id, payload.code) + request.session["session_version"] = int(result["session_version"]) + user = get_user(user_id) + audit_action(request, "user.mfa_enabled", object=str((user or {}).get("username") or user_id), result="enabled") + return {"ok": True, "recovery_codes": result["recovery_codes"]} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/users/mfa/disable") +def api_users_mfa_disable(payload: MfaManageRequest, request: Request): + user_id = int(request.session.get("user_id") or 0) + user = get_user(user_id) + if not user or not bool(user.get("mfa_enabled")): + return JSONResponse(status_code=400, content={"ok": False, "error": "MFA is not enabled"}) + if not verify_password(user_id, payload.password): + return JSONResponse(status_code=401, content={"ok": False, "error": "Invalid current password"}) + verified = verify_user_mfa(user_id, payload.code, consume_recovery=False) + if not verified.get("ok"): + return JSONResponse(status_code=401, content={"ok": False, "error": "Invalid authentication code"}) + result = disable_mfa(user_id) + request.session["session_version"] = int(result["session_version"]) + audit_action(request, "user.mfa_disabled", object=str(user.get("username") or user_id), result="disabled") + return {"ok": True} + + +@app.post("/api/users/mfa/recovery-codes") +def api_users_mfa_recovery_codes(payload: MfaManageRequest, request: Request): + user_id = int(request.session.get("user_id") or 0) + user = get_user(user_id) + if not user or not bool(user.get("mfa_enabled")): + return JSONResponse(status_code=400, content={"ok": False, "error": "MFA is not enabled"}) + if not verify_password(user_id, payload.password): + return JSONResponse(status_code=401, content={"ok": False, "error": "Invalid current password"}) + verified = verify_user_mfa(user_id, payload.code, consume_recovery=False) + if not verified.get("ok"): + return JSONResponse(status_code=401, content={"ok": False, "error": "Invalid authentication code"}) + result = regenerate_mfa_recovery_codes(user_id) + audit_action(request, "user.mfa_recovery_regenerated", object=str(user.get("username") or user_id), result="created") + return {"ok": True, "recovery_codes": result["recovery_codes"]} + + +@app.get("/api/audit") +def api_audit_log(limit: int = 500): + return {"ok": True, "items": list_audit(limit)} + + +@app.get("/", response_class=HTMLResponse) +def dashboard(request: Request): + return render(request, "dashboard.html", "dashboard", "nav.dashboard") + + +@app.get("/server", response_class=HTMLResponse) +def server(request: Request): + return render(request, "server.html", "server", "nav.server") + + +@app.get("/clients", response_class=HTMLResponse) +def clients(request: Request): + return render(request, "clients.html", "clients", "nav.clients") + + +@app.get("/settings", response_class=HTMLResponse) +def settings(request: Request): + return render(request, "settings.html", "settings", "nav.settings") + + +def _node_error_response(exc: Exception, *, status_code: int = 400) -> JSONResponse: + content: dict[str, object] = {"ok": False, "error": str(exc)} + error_code = str(getattr(exc, "code", "") or getattr(exc, "error_code", "")) + if error_code: + content["error_code"] = error_code + conflicts = getattr(exc, "conflicts", None) + if isinstance(conflicts, list): + content["conflicts"] = conflicts[:64] + return JSONResponse(status_code=status_code, content=content) + + +@app.get("/api/nodes") +def api_nodes_list(): + try: + return get_nodes_status() + except Exception as exc: + return JSONResponse(status_code=503, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/nodes/{node_id}/details") +def api_node_details(node_id: str): + try: + return node_details(node_id) + except ValueError as exc: + return JSONResponse(status_code=404, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/nodes/hub/enable") +def api_nodes_hub_enable(payload: NodeHubEnableRequest, request: Request): + try: + result = enable_hub(payload.model_dump()) + # Startup hooks of mounted FastAPI apps are not guaranteed to run. + # Ensure the control worker exists immediately when HUB mode is enabled, + # and restart it if a previous worker ever died unexpectedly. + _start_node_control() + audit_action(request, "nodes.hub_enabled", object=str(result.get("local", {}).get("name") or "HUB"), result="enabled", details={"listen_port": payload.listen_port, "transport_network": payload.transport_network}) + return result + except (ValueError, RuntimeError) as exc: + audit_action(request, "nodes.hub_enabled", object=payload.node_name or "HUB", result="failed", details={"error": str(exc)}) + return _node_error_response(exc) + + +@app.post("/api/nodes/hub/code") +def api_nodes_hub_code(request: Request): + try: + result = create_join_code() + audit_action(request, "nodes.join_code_created", object="HUB", result="created", details={"expires_at": result.get("expires_at")}) + return result + except (ValueError, RuntimeError) as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/nodes/connect") +def api_nodes_connect(payload: NodeConnectRequest, request: Request): + try: + result = connect_to_hub(payload.model_dump()) + audit_action(request, "nodes.connected", object=str(result.get("hub", {}).get("hub_name") or payload.hub_endpoint), result="connected", details={"hub_endpoint": payload.hub_endpoint}) + return result + except (ValueError, RuntimeError) as exc: + audit_action(request, "nodes.connected", object=payload.hub_endpoint, result="failed", details={"error": str(exc)}) + return _node_error_response(exc) + + +@app.post("/api/nodes/settings") +def api_nodes_settings(payload: NodeSettingsRequest, request: Request): + try: + result = update_local_settings(payload.model_dump()) + audit_action(request, "nodes.settings_saved", object=str(result.get("local", {}).get("name") or "node"), result="saved") + return result + except (ValueError, RuntimeError) as exc: + return _node_error_response(exc) + + +@app.post("/api/nodes/sync-now") +def api_nodes_sync_now(request: Request): + try: + result = sync_spoke_once() + audit_action(request, "nodes.synced", object="HUB", result="ok") + return result + except (ValueError, RuntimeError) as exc: + return _node_error_response(exc) + + +@app.delete("/api/nodes/{node_id}") +def api_nodes_peer_remove(node_id: str, request: Request): + try: + result = remove_peer(node_id) + audit_action(request, "nodes.peer_removed", object=node_id, result="removed") + return result + except (ValueError, RuntimeError) as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/nodes/disable") +def api_nodes_disable(request: Request): + try: + result = disable_nodes() + audit_action(request, "nodes.disabled", object="nodes", result="disabled") + return result + except (ValueError, RuntimeError) as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/vps") +def api_vps_list(): + return {"ok": True, "items": list_vps()} + + +@app.post("/api/vps/preflight") +def api_vps_preflight(payload: VpsPreflightRequest): + try: + return preflight_vps(payload.model_dump()) + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/vps/candidates") +def api_vps_candidate_save(payload: VpsCandidateSaveRequest, request: Request): + try: + data = payload.model_dump() + preflight = dict(data.pop("preflight") or {}) + if not preflight.get("ok"): + return JSONResponse(status_code=400, content={"ok": False, "error": "Run a successful VPS check before saving"}) + item = save_vps_candidate(data, preflight) + audit_action(request, "vps.candidate_saved", object=str(item.get("name") or payload.name), result="saved", details=data) + return {"ok": True, "item": item} + except (ValueError, TypeError) as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.delete("/api/vps/candidates/{vps_id}") +def api_vps_candidate_delete(vps_id: str, request: Request): + try: + delete_vps_candidate(vps_id) + audit_action(request, "vps.candidate_deleted", object=vps_id, result="deleted") + return {"ok": True} + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.delete("/api/vps/{vps_id}") +def api_vps_detach(vps_id: str, request: Request): + try: + result = detach_vps(vps_id) + audit_action(request, "vps.detached", object=vps_id, result="detached") + return result + except ValueError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/vps/{vps_id}/install") +def api_vps_install(request: Request, vps_id: str, payload: VpsInstallRequest): + try: + iface = request_interface(request) + snap = run_helper("snapshot", interface=iface) + listen_port = int(snap.get("listen_port") or 0) + if not listen_port: + return JSONResponse(status_code=400, content={"ok": False, "error": "Start and configure the selected WireGuard interface before installing Relay"}) + result = install_relay( + vps_id, payload.model_dump(), + published_interface=iface, home_wg_port=listen_port, + ) + audit_action(request, "vps.relay_installed", object=vps_id, result="installed") + return result + except (ValueError, HelperError, TypeError) as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/vps/{vps_id}/health") +def api_vps_health(vps_id: str): + try: + return relay_health(vps_id) + except ValueError as exc: + return JSONResponse(status_code=503, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/interfaces") +def api_interfaces(request: Request): + try: + data = run_helper("interfaces_list", interface=request_interface(request)) + access = request.state.access + if access["role"] != "admin": + data["interfaces"] = [item for item in data.get("interfaces", []) if item.get("name") in access["interfaces"]] + data.pop("suggested", None) + return data + except HelperError as exc: + return JSONResponse(status_code=503, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/interfaces/create") +def api_interface_create(payload: CreateInterfaceRequest, request: Request): + try: + data = payload.model_dump() + iface = data.pop("interface") + result = run_helper("create_server", data, interface=iface) + reconcile_node() + audit_action(request, "interface.created", object=iface, result="created", details=data) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/interfaces/name") +def api_interface_name(payload: InterfaceNameRequest, request: Request): + try: + result = run_helper("interface_meta_set", {"display_name": payload.display_name}, interface=payload.interface) + audit_action(request, "interface.renamed", object=payload.interface, result="saved", details={"display_name": payload.display_name}) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/interfaces/delete") +def api_interface_delete(payload: InterfaceDeleteRequest, request: Request): + try: + result = run_helper("interface_delete", {}, interface=payload.interface) + reconcile_node() + audit_action(request, "interface.deleted", object=payload.interface, result="deleted", details={"backup": result.get("backup")}) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/snapshot") +def api_snapshot(request: Request, view: str = "full"): + try: + iface = request_interface(request) + selected_view = str(view or "full").strip().lower() + if request.state.access["role"] != "admin": + selected_view = "clients" + if selected_view not in {"full", "clients", "dashboard", "server"}: + selected_view = "full" + data = run_helper("snapshot", {"view": selected_view}, interface=iface) + if request.state.access["role"] != "admin": + config = data.get("config") or {} + interface = config.get("interface") or {} + interface.pop("post_up", None) + interface.pop("post_down", None) + config.pop("firewall", None) + config.pop("routes", None) + data["peers"] = merge_wireguard_last_seen(iface, list(data.get("peers") or [])) + data["vps_relays"] = [ + { + "id": item.get("id"), + "name": item.get("name"), + "host": item.get("host"), + "endpoint_domain": item.get("endpoint_domain"), + "relay_port": item.get("relay_port"), + "status": item.get("status"), + "published_interface": item.get("published_interface"), + "last_health": item.get("last_health"), + "last_error": item.get("last_error"), + } + for item in list_vps() + if str(item.get("status") or "") == "installed" + and str(item.get("published_interface") or "") == iface + ] + preferences = get_preferences() + data["ui"] = { + "version": VERSION, + "refresh_seconds": preferences["refresh_seconds"], + "online_threshold_seconds": preferences["online_threshold_seconds"], + "backup_retention": preferences["backup_retention"], + } + return data + except HelperError as exc: + return JSONResponse(status_code=503, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/metrics/history") +def api_metrics_history(): + try: + return run_helper("metrics_history") + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/diagnostics") +def api_diagnostics(request: Request): + try: + return run_helper("diagnostics", interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=503, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/network/trace") +def api_network_trace(payload: NetworkTraceRequest, request: Request): + try: + data = payload.model_dump() + data["language"] = request_language(request) + return run_helper("network_trace", data, interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/traffic/reset") +def api_traffic_reset(request: Request): + try: + iface = request_interface(request) + result = run_helper("traffic_reset", interface=iface) + audit_action(request, "traffic.reset", object=iface, result="reset") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/start") +def api_server_start(request: Request): + try: + iface = request_interface(request) + result = run_helper("wireguard_start", interface=iface) + audit_action(request, "wireguard.started", object=iface, result="started") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/stop") +def api_server_stop(request: Request): + try: + iface = request_interface(request) + result = run_helper("wireguard_stop", interface=iface) + audit_action(request, "wireguard.stopped", object=iface, result="stopped") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/restart") +def api_server_restart(request: Request): + try: + iface = request_interface(request) + result = run_helper("wireguard_restart", interface=iface) + audit_action(request, "wireguard.restarted", object=iface, result="restarted") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/install") +def api_install_wireguard(request: Request): + try: + result = run_helper("install_wireguard") + audit_action(request, "wireguard.installed", object="WireGuard", result="installed") + return result + except HelperError as exc: + return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/create") +def api_create_server(payload: CreateServerRequest, request: Request): + try: + iface = request_interface(request) + result = run_helper("create_server", payload.model_dump(), interface=iface) + reconcile_node() + audit_action(request, "server.created", object=iface, result="created", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/extended/ip-groups") +def api_extended_groups_get(request: Request): + try: + return run_helper("extended_ip_groups_get", interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/extended/ip-groups") +def api_extended_groups_set(payload: ExtendedIPGroupRequest, request: Request): + try: + result = run_helper("extended_ip_groups_set", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "network.ip_group_updated", object=payload.name, result="saved", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/extended/forwardings") +def api_extended_forward_get(request: Request): + try: + return run_helper("extended_forward_get", interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/extended/forwardings") +def api_extended_forward_add(payload: ExtendedForwardRequest, request: Request): + try: + result = run_helper("extended_forward_add", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "network.forward_added", object=request_interface(request), result="saved", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/extended/forwardings/delete") +def api_extended_forward_delete(payload: ExtendedForwardDeleteRequest, request: Request): + try: + result = run_helper("extended_forward_delete", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "network.forward_deleted", object=request_interface(request), result="deleted", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/server/extended-listen") +def api_extended_listen_get(request: Request): + try: + return run_helper("extended_listen_get", interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/extended-listen") +def api_extended_listen_apply(payload: ExtendedListenRequest, request: Request): + try: + result = run_helper("extended_listen_apply", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "server.listen_updated", object=request_interface(request), result="saved", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/server/extended-snat") +def api_extended_snat_get(request: Request): + try: + return run_helper("extended_snat_get", interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/extended-snat") +def api_extended_snat_apply(payload: ExtendedSnatRequest, request: Request): + try: + result = run_helper("extended_snat_apply", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "server.snat_updated", object=request_interface(request), result="saved", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/settings/apply") +def api_server_settings_apply(payload: ServerSettingsRequest, request: Request): + try: + iface = request_interface(request) + result = run_helper("server_settings_apply", payload.model_dump(), interface=iface) + reconcile_node() + audit_action(request, "server.settings_applied", object=iface, result="applied", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/routes/create") +def api_route_create(payload: RouteRequest, request: Request): + try: + result = run_helper("route_create", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "route.created", object=payload.network, result="created", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/routes/update") +def api_route_update(payload: UpdateRouteRequest, request: Request): + try: + result = run_helper("route_update", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "route.updated", object=payload.network, result="updated", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/routes/delete") +def api_route_delete(payload: RouteKeyRequest, request: Request): + try: + result = run_helper("route_delete", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "route.deleted", object="route", result="deleted") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/access-rules/create") +def api_access_rule_create(payload: AccessRuleRequest, request: Request): + try: + result = run_helper("access_rule_create", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "access_rule.created", object=payload.destination or payload.source, result="created", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/access-rules/update") +def api_access_rule_update(payload: UpdateAccessRuleRequest, request: Request): + try: + result = run_helper("access_rule_update", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "access_rule.updated", object=payload.destination or payload.source, result="updated", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/access-rules/delete") +def api_access_rule_delete(payload: AccessRuleKeyRequest, request: Request): + try: + result = run_helper("access_rule_delete", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "access_rule.deleted", object="access rule", result="deleted") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/api/server/config/raw") +def api_raw_config_get(request: Request): + try: + return run_helper("raw_config_get", interface=request_interface(request)) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/server/config/apply") +def api_raw_config_apply(payload: RawConfigRequest, request: Request): + try: + iface = request_interface(request) + result = run_helper("raw_config_apply", payload.model_dump(), interface=iface) + reconcile_node() + audit_action(request, "server.raw_config_applied", object=iface, result="applied") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/clients/create") +def api_create_client(payload: ClientRequest, request: Request): + try: + if request.state.access["role"] != "admin" and (payload.type != "client" or payload.remote_networks or payload.connection_mode != "direct" or payload.relay_vps_id): + return JSONResponse(status_code=403, content={"ok": False, "error": "Zaawansowana konfiguracja wymaga uprawnień administratora"}) + result = run_helper("create_client", payload.model_dump(), interface=request_interface(request)) + reconcile_node() + audit_action(request, "client.created", object=payload.name, result="created", details={"type": payload.type, "connection_mode": payload.connection_mode, "peer_isolation": payload.peer_isolation}) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/clients/update") +def api_update_client(payload: UpdateClientRequest, request: Request): + try: + if request.state.access["role"] != "admin": + if payload.type != "client" or payload.remote_networks or payload.connection_mode != "direct" or payload.relay_vps_id: + return JSONResponse(status_code=403, content={"ok": False, "error": "Zaawansowana konfiguracja wymaga uprawnień administratora"}) + snapshot = run_helper("snapshot", {"view": "clients"}, interface=request_interface(request)) + peer = next((p for p in snapshot.get("peers", []) if p.get("public_key") == payload.public_key), None) + if not peer or peer.get("remote_networks") or peer.get("connection_mode") == "relay": + return JSONResponse(status_code=403, content={"ok": False, "error": "Tego połączenia nie można edytować bez uprawnień administratora"}) + result = run_helper("update_client", payload.model_dump(), interface=request_interface(request)) + reconcile_node() + audit_action(request, "client.updated", object=payload.name, result="updated", details={"type": payload.type, "connection_mode": payload.connection_mode, "peer_isolation": payload.peer_isolation}) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/clients/delete") +def api_delete_client(payload: ClientKeyRequest, request: Request): + try: + iface = request_interface(request) + result = run_helper("delete_client", payload.model_dump(), interface=iface) + reconcile_node() + audit_action(request, "client.deleted", object=f"{iface} · {result.get('name') or payload.public_key[:16]}", result="deleted") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/clients/credentials/rotate") +def api_rotate_client_credentials(payload: ClientKeyRequest, request: Request): + try: + result = run_helper("rotate_client_credentials", payload.model_dump(), interface=request_interface(request)) + audit_action( + request, + "client.credentials_rotated", + object=str(result.get("name") or "client"), + result="rotated", + details={"psk_rotated": bool(result.get("psk_rotated"))}, + ) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/client-groups/create") +def api_create_client_group(payload: ClientGroupRequest, request: Request): + try: + result = run_helper("group_create", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "client_group.created", object=payload.name, result="created", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/client-groups/update") +def api_update_client_group(payload: UpdateClientGroupRequest, request: Request): + try: + result = run_helper("group_update", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "client_group.updated", object=payload.name, result="updated", details=payload.model_dump()) + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/client-groups/delete") +def api_delete_client_group(payload: DeleteClientGroupRequest, request: Request): + try: + result = run_helper("group_delete", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "client_group.deleted", object=payload.group_id, result="deleted") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/clients/config") +def api_client_config(payload: ClientKeyRequest, request: Request): + try: + result = run_helper("client_config", payload.model_dump(), interface=request_interface(request)) + audit_action(request, "client.config_viewed", object=str(result.get("filename") or "client config"), result="shown") + return result + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/clients/config/download") +def api_client_config_download(payload: ClientKeyRequest, request: Request): + try: + data = run_helper("client_config", payload.model_dump(), interface=request_interface(request)) + filename = data.get("filename") or "wireguard-client.conf" + audit_action(request, "client.config_downloaded", object=filename, result="downloaded") + return Response( + content=data["config"], + media_type="text/plain; charset=utf-8", + headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + ) + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.post("/api/clients/qr") +def api_client_qr(payload: ClientKeyRequest, request: Request): + try: + data = run_helper("client_config", payload.model_dump(), interface=request_interface(request)) + # The web UI displays config text and QR in one modal. Opening that modal is + # already audited by /api/clients/config, so do not create a duplicate QR row. + image = qrcode.make(data["config"], image_factory=qrcode.image.svg.SvgPathImage, border=2) + stream = io.BytesIO() + image.save(stream) + return Response(content=stream.getvalue(), media_type="image/svg+xml") + except HelperError as exc: + return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) + + +@app.get("/healthz") +def healthz(): + # Public, non-sensitive readiness endpoint used during live HTTPS port/path + # hand-offs. CORS is intentionally limited to this endpoint so the old + # browser origin can verify that the *new* WGTools process is ready before + # navigating to a different HTTPS port. + return JSONResponse( + content={"ok": True, "version": VERSION, "instance": PROCESS_INSTANCE}, + headers={ + "Cache-Control": "no-store, max-age=0", + "Access-Control-Allow-Origin": "*", + }, + ) + + +# When built-in HTTPS has a configured access path, expose the whole application +# only below that prefix. Direct requests to /, /login, /api, /static, etc. then +# receive the outer application's normal 404 response. Disabling built-in HTTPS +# intentionally returns WGTools to its regular unprefixed HTTP mode for reverse proxies. +def _configured_access_path() -> str: + if os.environ.get("WGTOOLS_HTTPS_ENABLED", "0").strip() != "1": + return "" + raw = os.environ.get("WGTOOLS_ACCESS_PATH", "").strip().strip("/") + if not re.fullmatch(r"[A-Za-z0-9_-]{8,96}", raw): + return "" + return f"/{raw}" + + +ACCESS_PATH = _configured_access_path() +if ACCESS_PATH: + application = FastAPI(title=APP_NAME, version=VERSION, docs_url=None, redoc_url=None) + application.mount(ACCESS_PATH, app) + + # Starlette/FastAPI does not run a mounted sub-application's lifespan/startup + # handlers as the parent application's own lifespan. WGTools keeps the web + # app mounted below the private HTTPS path, so explicitly start the same + # background services from the outer application as well. The per-service + # guards make this safe even if framework lifespan behaviour changes later. + @application.on_event("startup") + def _start_private_path_background_services() -> None: + _start_metrics_sampler() + _start_wg_connection_audit() + _start_node_sync() + _start_node_control() +else: + application = app diff --git a/app/static/css/app.css b/app/static/css/app.css new file mode 100644 index 0000000..048af8d --- /dev/null +++ b/app/static/css/app.css @@ -0,0 +1,429 @@ +:root{ + --bg:#171a1f;--panel:#23282f;--panel-2:#1d2228;--border:#39414a;--text:#f4f6f8;--muted:#aab4bf; + --accent:#8f1f27;--accent-2:#6f171e;--accent-soft:#3a2024;--ok:#69c17d;--bad:#d46a72;--warn:#d9b35f;--sidebar:#1c2127; + --shadow:0 8px 30px rgba(0,0,0,.18) +} +html[data-theme="light"]{ + --bg:#eef1f4;--panel:#ffffff;--panel-2:#f7f8fa;--border:#d5dbe2;--text:#20252b;--muted:#66717d; + --accent:#8f1f27;--accent-2:#721820;--accent-soft:#f4e5e7;--sidebar:#262b31;--shadow:0 8px 24px rgba(25,35,45,.08) +} +*{box-sizing:border-box}html,body{margin:0;min-height:100%;font-family:Inter,Segoe UI,Roboto,Arial,sans-serif;background:var(--bg);color:var(--text)}body{padding-top:66px;padding-left:205px} +.topbar{height:66px;position:fixed;top:0;left:0;right:0;z-index:20;background:linear-gradient(90deg,var(--accent-2),var(--accent));display:flex;align-items:center;justify-content:space-between;padding:0 22px;color:#fff;box-shadow:0 2px 12px rgba(0,0,0,.25)} +.brand{display:flex;align-items:center;gap:12px}.brand-mark{width:38px;height:38px;border-radius:50%;border:1px solid rgba(255,255,255,.45);display:flex;align-items:center;justify-content:center;font-weight:800;font-size:12px;background:rgba(255,255,255,.08)}.brand-logo{display:block;object-fit:cover;padding:0;background:transparent}.brand-title{font-weight:800;font-size:15px}.brand-subtitle{font-size:11px;opacity:.84;margin-top:2px}.top-status{font-size:13px;font-weight:700;display:flex;gap:8px;align-items:center} +.sidebar{position:fixed;top:66px;bottom:0;left:0;width:205px;background:var(--sidebar);border-right:1px solid #2a3037;display:flex;flex-direction:column;z-index:15}.sidebar nav{padding:10px 0}.nav-item{display:flex;align-items:center;gap:12px;height:46px;color:#e7ebef;text-decoration:none;padding:0 20px;border-left:3px solid transparent;font-size:14px}.nav-item:hover{background:#292f36}.nav-item.active{background:#313942;border-left-color:#b83a44}.nav-icon{width:18px;text-align:center;color:#d8dde2}.sidebar-footer{margin-top:auto;padding:12px 14px 16px;color:#e6eaee;font-size:11px;border-top:1px solid #2d333a}.sidebar-version{padding:6px 4px 0}.sidebar-version span{color:#aeb7c1}.sidebar-update-notice{display:flex;align-items:center;gap:9px;margin:0 0 8px;padding:9px 10px;border:1px solid rgba(217,179,95,.46);border-radius:6px;background:rgba(217,179,95,.12);color:#f2d589;text-decoration:none;box-shadow:0 0 0 1px rgba(217,179,95,.04) inset}.sidebar-update-notice[hidden]{display:none!important}.sidebar-update-notice:hover{background:rgba(217,179,95,.19);border-color:rgba(217,179,95,.7)}.sidebar-update-mark{display:grid;place-items:center;width:23px;height:23px;flex:0 0 23px;border-radius:50%;background:rgba(217,179,95,.17);color:#ffe1a0;font-size:15px;font-weight:900}.sidebar-update-copy{display:flex;min-width:0;flex-direction:column;gap:2px}.sidebar-update-copy strong{font-size:10px;line-height:1.2;color:#ffe1a0}.sidebar-update-copy small{font-size:10px;line-height:1.2;color:#d9b35f;font-weight:800} +.content{padding:25px;max-width:1650px;margin:0 auto}.page-head{margin-bottom:18px}.page-head h1{margin:0 0 6px;font-size:25px}.page-head p{margin:0;color:var(--muted);font-size:14px} +.card{background:var(--panel);border:1px solid var(--border);border-radius:6px;box-shadow:var(--shadow);margin-bottom:16px;overflow:hidden}.card-head{display:flex;align-items:center;justify-content:space-between;gap:15px;padding:16px;border-bottom:1px solid var(--border)}.card-head h2{font-size:16px;margin:0}.card-head p{font-size:12px;color:var(--muted);margin:5px 0 0}.metric-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin-bottom:16px}.metric-card{padding:16px;min-height:155px;margin:0}.metric-title{font-size:13px;color:var(--muted);font-weight:700;margin-bottom:13px}.metric-value{font-size:24px;font-weight:800;display:flex;align-items:center;gap:9px}.metric-value small{font-size:14px;color:var(--muted);font-weight:600}.metric-lines{display:flex;flex-direction:column;gap:5px;color:var(--muted);font-size:12px;margin-top:14px}.traffic-pair{display:flex;gap:26px}.traffic-pair div{display:grid;grid-template-columns:auto auto;grid-template-areas:'arrow value' '. label';gap:0 7px}.traffic-pair b{grid-area:value;font-size:19px}.traffic-pair small{grid-area:label;color:var(--muted);font-size:10px}.traffic-arrow{grid-area:arrow;font-size:18px;color:#c8ced5} +.status-dot{width:9px;height:9px;border-radius:50%;display:inline-block;background:#8b939c;box-shadow:0 0 0 3px rgba(255,255,255,.04)}.status-dot.online{background:var(--ok)}.status-dot.offline{background:var(--bad)}.status-dot.unknown{background:#9aa1a8}.status-dot.large{width:11px;height:11px}.badge{padding:4px 8px;border-radius:999px;font-size:11px;font-weight:700}.badge.readonly{background:var(--accent-soft);color:#e2a7ad;border:1px solid rgba(190,90,100,.22)}html[data-theme="light"] .badge.readonly{color:#83202a} +.table-wrap{overflow:auto}table{width:100%;border-collapse:collapse;font-size:13px}th,td{padding:11px 15px;border-bottom:1px solid var(--border);text-align:left;white-space:nowrap}th{font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:var(--muted);background:var(--panel-2)}tbody tr:hover{background:rgba(255,255,255,.018)}tbody tr:last-child td{border-bottom:0}.empty{text-align:center!important;color:var(--muted);padding:28px!important}.peer-name{font-weight:700}.subtle{font-size:11px;color:var(--muted);margin-top:3px}.status-cell{display:flex;align-items:center;gap:7px}.muted{color:var(--muted);font-size:12px}.btn{border:1px solid var(--border);background:var(--panel-2);color:var(--text);border-radius:5px;padding:8px 12px;cursor:pointer;font-weight:650}.btn:hover{border-color:#59636f}.btn:disabled{opacity:.55;cursor:not-allowed} +.two-col{display:grid;grid-template-columns:1fr 1fr;gap:16px}.kv-list{margin:0;padding:7px 16px 13px}.kv-list>div{display:flex;justify-content:space-between;gap:20px;padding:10px 0;border-bottom:1px solid var(--border)}.kv-list>div:last-child{border-bottom:0}.kv-list dt{color:var(--muted);font-size:12px}.kv-list dd{margin:0;font-size:13px;font-weight:700;text-align:right;word-break:break-all}.health-list{display:flex;flex-direction:column;gap:10px}.health-list>div{display:flex;align-items:center;gap:8px;font-size:12px}.health-list.compact{margin-top:8px}.health-ok{color:var(--ok)}.health-bad{color:var(--bad)}.health-warn{color:var(--warn)} +.diagnostic-grid{padding:14px 16px;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.diag-chip{background:var(--panel-2);border:1px solid var(--border);padding:10px 12px;border-radius:5px;display:flex;gap:8px;align-items:center;font-size:12px}.diagnostics-list{padding:10px 16px 16px}.diag-row{display:grid;grid-template-columns:24px minmax(190px,1fr) 2fr;gap:10px;align-items:center;padding:10px 0;border-bottom:1px solid var(--border);font-size:13px}.diag-row:last-child{border-bottom:0}.diag-detail{color:var(--muted);font-size:12px;word-break:break-all} +.form-grid{display:grid;grid-template-columns:1fr;gap:14px;padding:16px}.form-grid label{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px}.form-grid select{background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:9px;border-radius:5px}.hint{padding:0 16px 16px;color:var(--muted);font-size:12px}.toast{position:fixed;right:20px;bottom:20px;z-index:40;background:#20252b;color:#fff;padding:10px 14px;border-radius:5px;box-shadow:var(--shadow);opacity:0;transform:translateY(10px);pointer-events:none;transition:.2s}.toast.show{opacity:1;transform:translateY(0)} +code,.mono{font-family:Consolas,Monaco,monospace}.wrap{white-space:normal!important;word-break:break-word}.tag{display:inline-block;padding:2px 6px;border:1px solid var(--border);border-radius:4px;margin:1px 3px 1px 0;background:var(--panel-2);font-size:11px} +@media(max-width:1050px){.metric-grid{grid-template-columns:repeat(2,1fr)}.diagnostic-grid{grid-template-columns:repeat(2,1fr)}} +@media(max-width:760px){body{padding-left:0}.sidebar{transform:translateX(-100%)}.brand-subtitle{display:none}.content{padding:14px}.metric-grid,.two-col{grid-template-columns:1fr}.diagnostic-grid{grid-template-columns:1fr}.top-status{font-size:11px}.diag-row{grid-template-columns:24px 1fr}.diag-detail{grid-column:2}} + +/* v0.2 provisioning */ +.badge.warn{background:rgba(217,179,95,.12);color:var(--warn);border:1px solid rgba(217,179,95,.28)} +.btn.primary{background:var(--accent);border-color:var(--accent);color:#fff}.btn.primary:hover{background:var(--accent-2);border-color:var(--accent-2)} +.provision-body{display:grid;grid-template-columns:auto 1fr auto;gap:16px;align-items:center;padding:18px}.provision-icon{width:48px;height:48px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:var(--accent-soft);border:1px solid rgba(184,58,68,.35);font-weight:900;color:#e8b0b5}.provision-copy b{font-size:15px}.provision-copy p{margin:5px 0 0;color:var(--muted);font-size:12px;max-width:760px} +.setup-form{padding:0}.setup-section{padding:17px 18px;border-bottom:1px solid var(--border)}.setup-section-title{font-weight:800;font-size:13px;margin-bottom:14px}.setup-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px 18px}.setup-grid label{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px}.setup-grid input{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px;outline:none}.setup-grid input:focus{border-color:#7d8995;box-shadow:0 0 0 2px rgba(125,137,149,.12)}.setup-grid input:disabled{opacity:.62;cursor:not-allowed}.setup-grid small{font-size:10px;line-height:1.35;color:var(--muted)} +.toggle-row{display:flex;gap:24px;flex-wrap:wrap;margin-top:16px}.check-label{display:flex!important;flex-direction:row!important;align-items:center;gap:8px!important;color:var(--text)!important;font-size:12px!important}.check-label input{width:auto!important;accent-color:var(--accent)} +.setup-preview{display:flex;justify-content:space-between;gap:22px;align-items:flex-end;padding:18px}.setup-preview b{font-size:13px}.setup-preview ul{margin:9px 0 0;padding-left:18px;color:var(--muted);font-size:12px;line-height:1.7}.operation-status{margin:0 18px 18px;padding:11px 13px;border-radius:5px;font-size:12px;border:1px solid var(--border);background:var(--panel-2);white-space:pre-wrap;word-break:break-word}.operation-status.working{color:var(--warn);border-color:rgba(217,179,95,.35)}.operation-status.success{color:var(--ok);border-color:rgba(105,193,125,.35)}.operation-status.error{color:var(--bad);border-color:rgba(212,106,114,.4)} +[hidden]{display:none!important} +@media(max-width:760px){.setup-grid{grid-template-columns:1fr}.provision-body{grid-template-columns:auto 1fr}.provision-body .btn{grid-column:1/-1}.setup-preview{align-items:stretch;flex-direction:column}.setup-preview .btn{width:100%}} + +/* v0.3 client management */ +.page-head-actions{display:flex;align-items:flex-end;justify-content:space-between;gap:16px}.page-head-actions .btn{flex:0 0 auto} +.action-row{display:flex;gap:6px;align-items:center}.btn.small{padding:5px 8px;font-size:11px}.btn.danger{color:#f1a3aa;border-color:rgba(212,106,114,.45);background:rgba(212,106,114,.08)}.btn.danger:hover{background:rgba(212,106,114,.15)} +.badge.managed{background:rgba(105,193,125,.1);color:var(--ok);border:1px solid rgba(105,193,125,.25)} +.modal-backdrop{position:fixed;inset:0;z-index:80;background:rgba(5,8,11,.72);display:flex;align-items:center;justify-content:center;padding:24px;overflow:auto}.modal-card{width:min(680px,100%);max-height:calc(100vh - 48px);overflow:auto;background:var(--panel);border:1px solid var(--border);border-radius:7px;box-shadow:0 25px 80px rgba(0,0,0,.42)}.modal-wide{width:min(980px,100%)}.modal-head{display:flex;align-items:flex-start;justify-content:space-between;gap:15px;padding:17px 18px;border-bottom:1px solid var(--border);position:sticky;top:0;background:var(--panel);z-index:2}.modal-head h2{margin:0;font-size:17px}.modal-head p{margin:5px 0 0;color:var(--muted);font-size:11px}.icon-btn{border:0;background:transparent;color:var(--muted);font-size:25px;line-height:1;cursor:pointer;padding:0 4px}.icon-btn:hover{color:var(--text)}.modal-body{padding:18px}.modal-actions{display:flex;justify-content:flex-end;gap:8px;padding:14px 18px;border-top:1px solid var(--border);position:sticky;bottom:0;background:var(--panel)} +.setup-grid select,.field-block input,.field-block textarea,.setup-grid textarea,.setup-grid select{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px;outline:none}.field-block{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px;margin-top:15px}.field-block small{font-size:10px;line-height:1.35}.section-space{margin-top:22px;padding-top:18px;border-top:1px solid var(--border)}.section-space-small{margin-top:14px}.inline-note{margin-top:16px;padding:11px 12px;border-radius:5px;font-size:11px;line-height:1.5}.warn-note{color:var(--warn);border:1px solid rgba(217,179,95,.3);background:rgba(217,179,95,.08)} +.config-modal{width:min(1040px,100%)}.config-layout{display:grid;grid-template-columns:minmax(0,1.65fr) minmax(280px,.75fr);gap:18px;padding:18px}.config-text{width:100%;height:390px;resize:vertical;background:#11161b;color:#e8edf2;border:1px solid var(--border);border-radius:5px;padding:13px;line-height:1.5;font-size:12px}.config-buttons{display:flex;justify-content:flex-end;gap:8px;margin-top:10px}.qr-panel{min-height:320px;background:#fff;border-radius:6px;display:flex;align-items:center;justify-content:center;padding:16px}.qr-panel img{display:block;width:min(100%,340px);height:auto}.qr-panel .muted{color:#555;text-align:center} +@media(max-width:900px){.config-layout{grid-template-columns:1fr}.qr-panel{min-height:240px}.page-head-actions{align-items:stretch;flex-direction:column}.page-head-actions .btn{align-self:flex-start}} + +/* v0.4 client editor refinements */ +.modal-card{overflow-y:auto;overflow-x:hidden} +.setup-grid>*{min-width:0} +.field-block{min-width:0} +.controlled-textarea{box-sizing:border-box;max-width:100%;min-width:0;resize:vertical} +#client-server-port[readonly]{opacity:.78;cursor:default} + +/* v0.5 server-side i18n + expert raw config editor */ +.advanced-action-row{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:18px}.advanced-action-row b{font-size:14px}.advanced-action-row .hint{padding:0;margin:6px 0 0;max-width:920px}.danger-note{color:#ef9ba3;border:1px solid rgba(212,106,114,.4);background:rgba(212,106,114,.09)} +.raw-config-modal{width:min(1220px,100%)}.raw-config-toolbar{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:14px 0 9px}.wg-config-editor{position:relative;height:min(58vh,620px);min-height:360px;border:1px solid var(--border);border-radius:6px;overflow:hidden;background:#11161b}.wg-config-editor pre,.wg-config-editor textarea{position:absolute;inset:0;width:100%;height:100%;margin:0;padding:15px 16px;border:0;outline:0;font-family:Consolas,Monaco,monospace;font-size:13px;line-height:1.55;tab-size:4;white-space:pre;overflow:auto}.wg-config-editor pre{z-index:1;pointer-events:none;color:#d9e0e6;background:#11161b}.wg-config-editor textarea{z-index:2;resize:none;background:transparent;color:transparent;-webkit-text-fill-color:transparent;caret-color:#f4f6f8}.wg-config-editor textarea::selection{background:rgba(100,150,220,.34)}.wg-syn-comment{color:#77838e;font-style:italic}.wg-syn-section{color:#f0bd70;font-weight:800}.wg-syn-key{color:#8dc6ff}.wg-syn-eq{color:#97a2ad}.wg-syn-value{color:#dce6cf}.raw-config-modal .operation-status{margin:14px 0 0}.raw-config-modal .modal-body{padding-top:14px} +html[data-theme="light"] .wg-config-editor,html[data-theme="light"] .wg-config-editor pre{background:#1b2026}.advanced-card .badge{flex:0 0 auto} +@media(max-width:760px){.advanced-action-row{align-items:stretch;flex-direction:column}.advanced-action-row .btn{align-self:flex-start}.raw-config-toolbar{align-items:flex-start;flex-direction:column}.wg-config-editor{min-height:320px}} + +/* v0.6 authentication and users */ +.topbar-right{display:flex;align-items:center;gap:18px}.user-chip{display:flex;align-items:center;gap:8px;padding-left:16px;border-left:1px solid rgba(255,255,255,.25)}.user-chip-name{font-size:12px;font-weight:700;color:#fff}.topbar-logout{border:1px solid rgba(255,255,255,.35);background:rgba(255,255,255,.08);color:#fff;border-radius:5px;padding:5px 8px;font-size:11px;font-weight:700;cursor:pointer}.topbar-logout:hover{background:rgba(255,255,255,.16)} +.users-card .card-head p{max-width:900px}.user-modal{width:min(620px,100%)}.user-form-grid{grid-template-columns:1fr}.user-form-grid label{min-width:0} +.audit-modal{width:min(1120px,100%)}.audit-modal .modal-head p{max-width:760px}.audit-modal-body{padding:0}.audit-toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:11px 14px;border-bottom:1px solid var(--border);background:var(--panel)}.audit-search-wrap .quick-search-input{width:280px}.audit-retention-note{color:var(--muted);font-size:10px;font-weight:700}.audit-table-wrap{max-height:min(62vh,620px);overflow-y:auto;overflow-x:hidden}.audit-table-wrap table{table-layout:fixed;min-width:0}.audit-table-wrap th:nth-child(1),.audit-table-wrap td:nth-child(1){width:18%}.audit-table-wrap th:nth-child(2),.audit-table-wrap td:nth-child(2){width:24%}.audit-table-wrap th:nth-child(3),.audit-table-wrap td:nth-child(3){width:25%}.audit-table-wrap th:nth-child(4),.audit-table-wrap td:nth-child(4){width:18%}.audit-table-wrap th:nth-child(5),.audit-table-wrap td:nth-child(5){width:15%}.audit-table-wrap thead th{position:sticky;top:0;z-index:1;background:var(--panel-2)}.audit-table-wrap td{min-width:0;overflow:hidden;text-overflow:ellipsis}.audit-table-wrap td:nth-child(3),.audit-table-wrap td:nth-child(4),.audit-table-wrap td:nth-child(5){max-width:280px;overflow:hidden;text-overflow:ellipsis}.audit-table-wrap td:nth-child(4){white-space:normal;min-width:0}.audit-row{--audit-tone:#8aa4c7;--audit-soft:rgba(92,126,166,.10)}.audit-row.audit-tone-connection{--audit-tone:#65b7d7;--audit-soft:rgba(65,151,187,.11)}.audit-row.audit-tone-success{--audit-tone:var(--ok);--audit-soft:rgba(105,193,125,.10)}.audit-row.audit-tone-warning{--audit-tone:var(--warn);--audit-soft:rgba(217,179,95,.10)}.audit-row.audit-tone-danger{--audit-tone:var(--bad);--audit-soft:rgba(212,106,114,.10)}.audit-row td:first-child{box-shadow:inset 3px 0 0 var(--audit-tone)}.audit-row:hover{background:var(--audit-soft)}.audit-action-badge,.audit-result-badge,.audit-user-badge{display:inline-flex;align-items:center;max-width:100%;border-radius:4px;padding:3px 7px;font-size:11px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.audit-action-badge{color:var(--audit-tone);border:1px solid color-mix(in srgb,var(--audit-tone) 42%,transparent);background:var(--audit-soft)}.audit-result-badge{color:var(--audit-tone);background:var(--audit-soft)}.audit-user-badge{color:var(--text);background:rgba(138,164,199,.10);border:1px solid rgba(138,164,199,.22)}.audit-user-system{color:var(--muted);background:rgba(170,180,191,.07);border-color:rgba(170,180,191,.18)}@media(max-width:760px){.audit-toolbar{align-items:stretch;flex-direction:column}.audit-search-wrap,.audit-search-wrap .quick-search-input{width:100%;max-width:none}.audit-retention-note{padding:0 2px}.audit-table-wrap{max-height:60vh;overflow-x:auto}.audit-table-wrap table{min-width:760px}} +.auth-body{padding:0;min-height:100vh;background:var(--bg)}.auth-topbar{height:66px;background:linear-gradient(90deg,var(--accent-2),var(--accent));display:flex;align-items:center;padding:0 22px;color:#fff;box-shadow:0 2px 12px rgba(0,0,0,.25)}.auth-shell{min-height:calc(100vh - 66px);display:flex;align-items:center;justify-content:center;padding:32px 18px}.auth-card{width:min(470px,100%);background:var(--panel);border:1px solid var(--border);border-radius:8px;box-shadow:var(--shadow);overflow:hidden}.auth-card-head{display:flex;align-items:center;gap:14px;padding:22px;border-bottom:1px solid var(--border)}.auth-card-head h1{font-size:20px;margin:0}.auth-card-head p{font-size:12px;line-height:1.45;color:var(--muted);margin:6px 0 0}.auth-mark{width:46px;height:46px;color:var(--text);border-color:var(--border);background:var(--panel-2);flex:0 0 auto}.auth-form{display:flex;flex-direction:column;gap:15px;padding:22px}.auth-form label{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px}.auth-form input{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:10px 11px;outline:none}.auth-form input:focus{border-color:#7d8995;box-shadow:0 0 0 2px rgba(125,137,149,.12)}.auth-hint{margin:0;color:var(--muted);font-size:11px;line-height:1.5}.auth-form .operation-status{margin:0}.auth-submit{width:100%;padding:10px 12px} +@media(max-width:760px){.topbar-right{gap:8px}.user-chip-name{display:none}.user-chip{padding-left:8px}.topbar-logout{padding:4px 7px}.auth-topbar{padding:0 14px}} + +/* v0.7 visual server settings editor */ +.server-edit-modal{width:min(980px,100%)} +.server-edit-modal .modal-body{padding:18px} +.toggle-stack{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:13px 24px;margin-top:12px} +.disabled-fields{opacity:.52} +.disabled-fields input{cursor:not-allowed} +#server-edit-status{margin:14px 0 0} +@media(max-width:760px){.toggle-stack{grid-template-columns:1fr}} + +/* v0.9 dashboard system metrics, WireGuard controls and editable application settings */ +.dashboard-head{align-items:center} +.wg-control-row{display:flex;gap:7px;align-items:center;flex-wrap:wrap} +.btn.success-control{color:var(--ok);border-color:rgba(105,193,125,.4);background:rgba(105,193,125,.08)} +.btn.success-control:hover:not(:disabled){background:rgba(105,193,125,.15)} +.resource-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin-bottom:16px} +.resource-card{margin:0;padding:16px;min-height:145px} +.resource-head{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:12px;font-weight:800;text-transform:uppercase;letter-spacing:.03em} +.resource-icon{font-size:15px;color:#c7cdd4} +.resource-value{font-size:34px;font-weight:800;margin-top:12px;line-height:1}.resource-value small{font-size:15px;color:var(--muted);margin-left:4px} +.resource-sub{font-size:11px;color:var(--muted);margin-top:9px;min-height:15px} +.resource-bar{height:4px;background:var(--panel-2);border-radius:3px;overflow:hidden;margin-top:14px;border:1px solid var(--border)} +.resource-bar span{display:block;height:100%;width:0;background:currentColor;color:#6f91d8;transition:width .35s ease} +.network-speed-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px;margin-top:17px}.network-speed-row div{display:flex;flex-direction:column;gap:5px}.network-speed-row small{font-size:10px;color:var(--muted)}.network-speed-row b{font-size:19px;white-space:nowrap} +.settings-form-pad{padding:16px 18px}.settings-form-pad .setup-grid{gap:12px 16px}.settings-save-row{display:flex;justify-content:flex-end;margin-top:14px}.settings-form-pad .operation-status{margin:14px 0 0} +.settings-tabs{display:flex;gap:4px;margin:0 0 14px;padding:0 10px;border-bottom:1px solid var(--border);background:var(--panel);border-radius:12px 12px 0 0;overflow-x:auto}.settings-tab{appearance:none;border:0;background:transparent;color:var(--muted);padding:13px 16px;border-bottom:2px solid transparent;font-weight:700;font-size:12px;cursor:pointer;white-space:nowrap}.settings-tab:hover{color:var(--text)}.settings-tab.active{color:var(--text);border-bottom-color:var(--accent)}.settings-tab-panel[hidden]{display:none!important}.settings-tab-panel>.card:first-child,.settings-tab-panel>.two-col>.card{margin-top:0}.settings-backup-grid{display:grid;grid-template-columns:minmax(320px,.82fr) minmax(520px,1.18fr);gap:16px;align-items:stretch}.settings-backup-grid>.card{margin-bottom:0;height:100%}.settings-backup-grid>.backup-card{display:flex;flex-direction:column}.settings-backup-grid>.backup-card .card-head .badge{flex:0 0 auto;white-space:nowrap}.settings-backup-grid>.backup-card .backup-save-row{margin-top:auto}.backup-settings-grid-single{grid-template-columns:1fr}.settings-backup-grid .full-backup-card .migration-backup-block{grid-template-columns:1fr;border-top:0;padding:18px;gap:16px}.settings-backup-grid .full-backup-card .migration-secret-warning{margin-top:0}.settings-backup-grid .full-backup-card .migration-actions{align-self:auto} +@media(max-width:1180px){.settings-backup-grid{grid-template-columns:1fr}.settings-backup-grid>.card{margin-bottom:16px;height:auto}} +@media(max-width:620px){.settings-tabs{padding:0 4px}.settings-tab{padding:12px 10px}} +.backup-settings-grid{display:grid;grid-template-columns:minmax(280px,.8fr) minmax(0,1.2fr);gap:28px;padding:18px}.backup-settings-grid>label{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px}.backup-settings-grid input{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px;outline:none}.backup-settings-grid small{font-size:10px;line-height:1.4}.compact-kv{margin:0}.backup-save-row{display:flex;justify-content:flex-end;padding:0 18px 18px}.backup-settings-grid.backup-settings-grid-single{grid-template-columns:1fr;gap:18px}.backup-settings-grid-single .compact-kv{padding:0}.backup-settings-grid-single .compact-kv dd{word-break:normal;white-space:nowrap} +@media(max-width:980px){.resource-grid{grid-template-columns:1fr}.dashboard-head{align-items:flex-start}.wg-control-row{align-self:flex-start}.backup-settings-grid{grid-template-columns:1fr}} + +/* v0.10 Telegram Bot integration */ +.telegram-settings-body{padding:18px} +.telegram-enable-row{display:flex;align-items:center;justify-content:space-between;gap:18px;padding-bottom:16px;border-bottom:1px solid var(--border)} +.telegram-runtime{display:flex;align-items:center;gap:12px;font-size:12px}.telegram-runtime b{font-size:13px}.telegram-runtime .muted{font-size:11px} +.telegram-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px 18px;margin-top:18px}.telegram-grid>label{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px;min-width:0}.telegram-grid input,.telegram-grid select,.telegram-grid textarea{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px;outline:none}.telegram-grid textarea{resize:vertical;min-height:112px}.telegram-grid small{font-size:10px;line-height:1.45}.telegram-ids-field{grid-column:1/-1}.telegram-actions{display:flex;align-items:center;gap:8px;margin-top:16px}.telegram-actions-spacer{flex:1}.telegram-card .operation-status{margin:16px 0 0}.telegram-card .badge.managed{background:rgba(105,193,125,.1);color:var(--ok);border:1px solid rgba(105,193,125,.25)} +@media(max-width:800px){.telegram-grid{grid-template-columns:1fr}.telegram-enable-row{align-items:flex-start;flex-direction:column}.telegram-actions{flex-wrap:wrap}.telegram-actions-spacer{display:none;width:100%}} + +/* v0.11.2: in-app help */ +.topbar-help{width:30px;height:30px;border:1px solid rgba(255,255,255,.38);border-radius:50%;background:rgba(255,255,255,.08);color:#fff;font-size:17px;font-weight:800;line-height:1;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;flex:0 0 auto}.topbar-help:hover{background:rgba(255,255,255,.18);border-color:rgba(255,255,255,.62)} +.help-modal{width:min(1240px,100%);height:min(86vh,860px);max-height:calc(100vh - 48px);display:flex;flex-direction:column;overflow:hidden}.help-modal-head{flex:0 0 auto}.help-layout{display:grid;grid-template-columns:220px minmax(0,1fr);min-height:0;flex:1;overflow:hidden}.help-nav{padding:14px;border-right:1px solid var(--border);background:var(--panel-2);overflow:auto}.help-nav-item{width:100%;border:1px solid transparent;background:transparent;color:var(--muted);text-align:left;border-radius:5px;padding:10px 11px;margin:0 0 6px;font:inherit;font-size:12px;font-weight:750;cursor:pointer}.help-nav-item:hover{background:var(--panel);color:var(--text)}.help-nav-item.active{background:rgba(142,31,37,.13);border-color:rgba(142,31,37,.38);color:var(--text)}.help-content{padding:18px 20px 28px;overflow:auto;min-width:0}.help-example-note{border:1px solid var(--border);background:var(--panel-2);border-radius:6px;padding:10px 12px;color:var(--muted);font-size:11px;line-height:1.55;margin:0 0 16px}.help-section-head{padding-bottom:13px;border-bottom:1px solid var(--border);margin-bottom:6px}.help-section-head h3{font-size:22px;margin:0 0 7px}.help-section-head p{margin:0;color:var(--muted);font-size:12px;line-height:1.6;max-width:920px}.help-topic{padding:17px 0;border-bottom:1px solid var(--border)}.help-topic:last-child{border-bottom:0}.help-topic h4{font-size:14px;margin:0 0 9px}.help-topic p{margin:7px 0;color:var(--text);font-size:12px;line-height:1.65}.help-topic ul{margin:8px 0 4px;padding-left:20px}.help-topic li{margin:6px 0;color:var(--text);font-size:12px;line-height:1.55}.help-example{margin:12px 0 3px;border:1px solid var(--border);border-radius:6px;overflow:hidden;background:#11161b}.help-example-title{padding:8px 11px;border-bottom:1px solid #2e3740;color:#bac4ce;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.04em}.help-example pre{margin:0;padding:11px 13px;white-space:pre-wrap;overflow-wrap:anywhere;color:#dbe4ec;font:12px/1.55 Consolas,Monaco,monospace}.help-warning{margin:12px 0 2px;padding:10px 12px;border:1px solid rgba(184,142,57,.42);border-radius:6px;background:rgba(184,142,57,.08);color:var(--text);font-size:11px;line-height:1.55}.help-actions{flex:0 0 auto}.about-link{color:var(--text);text-decoration:none}.about-link:hover{text-decoration:underline} +@media(max-width:760px){.top-status{display:none}.help-modal{height:calc(100vh - 24px);max-height:calc(100vh - 24px)}.help-layout{grid-template-columns:1fr;grid-template-rows:auto minmax(0,1fr)}.help-nav{display:flex;gap:6px;border-right:0;border-bottom:1px solid var(--border);overflow-x:auto;padding:9px}.help-nav-item{width:auto;min-width:max-content;margin:0;padding:8px 10px}.help-content{padding:14px}.help-section-head h3{font-size:19px}} + +/* v0.12 full migration backup and restore */ +.migration-backup-block{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(300px,.65fr);gap:26px;border-top:1px solid var(--border);padding:20px 18px}.migration-backup-copy h3{margin:0 0 8px;font-size:14px}.migration-backup-copy>p{margin:0;color:var(--muted);font-size:11px;line-height:1.6}.migration-secret-warning{margin:13px 0 11px}.migration-components{margin:0;padding-left:19px;color:var(--text);font-size:11px;line-height:1.7}.migration-components li{margin:3px 0}.migration-actions{display:grid;grid-template-columns:auto auto minmax(160px,1fr) auto;align-items:center;gap:9px;align-self:end}.migration-selected-file{min-width:0;min-height:36px;display:flex;align-items:center;padding:0 11px;color:var(--muted);font-size:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:1px solid var(--border);border-radius:5px;background:var(--panel-2)}.migration-status{margin:0 18px 18px}@media(max-width:980px){.migration-backup-block{grid-template-columns:1fr}.migration-actions{grid-template-columns:auto auto minmax(0,1fr) auto}}@media(max-width:680px){.migration-actions{grid-template-columns:1fr 1fr}.migration-selected-file{grid-column:1/-1;grid-row:2;white-space:normal}.migration-actions #migration-backup-restore-button{grid-column:2}.migration-actions #migration-backup-download-button,.migration-actions #migration-backup-select-button,.migration-actions #migration-backup-restore-button{width:100%}} +.about-card{scroll-margin-top:84px}.about-kv{padding-bottom:6px}.update-panel{padding:0 18px 18px}.update-actions{display:flex;align-items:center;gap:8px;padding-top:14px;border-top:1px solid var(--border)}.update-actions-spacer{flex:1}.update-notes{margin:2px 0 14px;border:1px solid var(--border);border-radius:6px;background:var(--panel-2);overflow:hidden}.update-notes-head{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:10px 12px;border-bottom:1px solid var(--border);font-size:12px}.update-notes-head a{color:var(--muted);font-size:11px}.update-notes pre{margin:0;padding:12px;max-height:280px;overflow:auto;white-space:pre-wrap;word-break:break-word;font:11px/1.55 Consolas,Monaco,monospace;color:var(--text)}.update-panel .operation-status{margin:14px 0 0}.update-safety-hint{margin:12px 0 0;line-height:1.55}.about-card #update-status-badge.managed{background:rgba(105,193,125,.1);color:var(--ok);border-color:rgba(105,193,125,.25)}.about-card #update-status-badge.warn{background:rgba(217,179,95,.1);color:var(--warn);border-color:rgba(217,179,95,.3)} +@media(max-width:720px){.update-actions{align-items:stretch;flex-direction:column}.update-actions-spacer{display:none}.update-actions .btn{width:100%;text-align:center}} + + +/* v0.15 usability: delayed tooltips, duplicate action and 24-hour metric charts */ +.wg-tooltip{position:fixed;z-index:120;max-width:280px;padding:7px 9px;border:1px solid var(--border);border-radius:5px;background:#11161b;color:#eef2f5;font-size:11px;line-height:1.35;box-shadow:0 7px 20px rgba(0,0,0,.34);pointer-events:none;opacity:0;transform:translateY(3px);transition:opacity .12s ease,transform .12s ease}.wg-tooltip.show{opacity:1;transform:translateY(0)}html[data-theme="light"] .wg-tooltip{background:#252b31;color:#fff;border-color:#414a54} +.icon-action-btn{width:31px;height:31px;padding:0;display:inline-flex;align-items:center;justify-content:center;font-size:18px;font-weight:800;line-height:1} +.resource-card{min-height:235px}.resource-history{margin-top:13px}.history-chart{display:block;width:100%;height:66px;overflow:visible}.history-grid{fill:none;stroke:var(--border);stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.65}.history-line{fill:none;stroke-width:1.8;vector-effect:non-scaling-stroke;stroke-linecap:round;stroke-linejoin:round}.history-line.primary{stroke:#cf5963}.history-line.memory{stroke:#d9b35f}.history-line.network-rx{stroke:#6f91d8}.history-line.network-tx{stroke:var(--ok)}.history-caption{display:flex;justify-content:space-between;gap:10px;margin-top:3px;color:var(--muted);font-size:9px}.history-chart.is-empty{opacity:.35} +@media(max-width:760px){.resource-card{min-height:220px}} +/* v0.16.1: clearer client route policy presentation */ +.route-reference{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px;margin-top:14px}.route-reference-list{min-height:38px;padding:9px 11px;border:1px solid var(--border);border-radius:5px;background:rgba(255,255,255,.018);color:#7f8a95;font-size:11px;line-height:1.55;white-space:pre-line}.route-reference small{font-size:10px;line-height:1.4;color:var(--muted)}html[data-theme="light"] .route-reference-list{background:#f3f5f7;color:#7a8490} + +/* v0.40.3: restrained online ring; red offline stays static. + Polling updates preserve status DOM nodes, so animation never resets. */ +.status-cell.online{color:var(--ok);font-weight:700} +.status-dot.peer-status-dot{ + position:relative;display:inline-block;flex:0 0 9px; + width:9px;height:9px;vertical-align:middle;transform-origin:center; +} +.status-dot.peer-status-dot.offline{ + animation:none!important;transform:none;box-shadow:none; +} +.status-dot.peer-status-dot.online{ + background:#79d590; + box-shadow:0 0 0 1px rgba(105,193,125,.15); + animation:wgtools-peer-online-breathe 2.4s ease-in-out infinite; +} +.status-dot.peer-status-dot.online::before{ + content:"";display:block;position:absolute;inset:-2px; + border-radius:50%;border:1px solid rgba(115,225,145,.70); + pointer-events:none; + animation:wgtools-peer-online-halo 2.4s ease-in-out infinite; +} +@keyframes wgtools-peer-online-breathe{ + 0%,100%{transform:scale(1)} + 50%{transform:scale(1.06)} +} +@keyframes wgtools-peer-online-halo{ + 0%,100%{transform:scale(.84);opacity:.30} + 50%{transform:scale(1.10);opacity:.88} +} +@media (prefers-reduced-motion:reduce){ + .status-dot.peer-status-dot.online{animation:none} + .status-dot.peer-status-dot.online::before{animation:none;display:none} +} + +/* v0.16.3: useful 24-hour min / average / max summaries */ +.history-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:0 0 7px}.history-stats>span{display:flex;align-items:baseline;justify-content:center;gap:5px;min-width:0;padding:4px 6px;border:1px solid var(--border);border-radius:4px;background:rgba(255,255,255,.018)}.history-stats small{color:var(--muted);font-size:8px;font-weight:750;text-transform:uppercase;letter-spacing:.04em}.history-stats b{min-width:0;color:var(--text);font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.network-history-stats{display:flex;flex-direction:column;gap:4px}.network-stat-row{display:grid;grid-template-columns:24px repeat(3,minmax(0,1fr));gap:5px;align-items:center}.network-stat-row>strong{font-size:9px;text-align:center}.network-stat-row.rx>strong{color:#6f91d8}.network-stat-row.tx>strong{color:var(--ok)}.network-stat-row>span{display:flex;align-items:baseline;justify-content:center;gap:3px;min-width:0;padding:3px 4px;border:1px solid var(--border);border-radius:4px;background:rgba(255,255,255,.018)}.network-stat-row small{color:var(--muted);font-size:7px;font-weight:750;text-transform:uppercase}.network-stat-row b{min-width:0;font-size:9px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.resource-card{min-height:270px}@media(max-width:760px){.resource-card{min-height:250px}.history-stats{gap:5px}.history-stats>span{padding:4px}.network-stat-row{grid-template-columns:22px repeat(3,minmax(0,1fr))}} + +/* v0.17.0: multi-interface navigation and manager */ +.interface-switcher-wrap{position:relative}.interface-switcher-button{appearance:none;border:1px solid transparent;background:transparent;color:#fff;padding:7px 8px;border-radius:5px;cursor:pointer;max-width:420px}.interface-switcher-button:hover,.interface-switcher-button[aria-expanded="true"]{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.2)}.interface-switcher-caret{font-size:10px;opacity:.8;margin-left:1px}.interface-switcher-menu{position:absolute;right:0;top:calc(100% + 9px);z-index:80;width:min(420px,calc(100vw - 24px));padding:6px;border:1px solid var(--border);border-radius:7px;background:var(--panel);box-shadow:0 14px 38px rgba(0,0,0,.34);color:var(--text)}.interface-switcher-menu[hidden]{display:none}.interface-switcher-menu-head{padding:7px 9px 8px;color:var(--muted);font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.05em}.interface-switcher-item{width:100%;display:grid;grid-template-columns:12px minmax(0,1fr) auto;gap:9px;align-items:center;border:1px solid transparent;background:transparent;color:var(--text);text-align:left;border-radius:5px;padding:9px 10px;cursor:pointer}.interface-switcher-item:hover{background:var(--panel-2);border-color:var(--border)}.interface-switcher-item.active{background:rgba(143,31,39,.1);border-color:rgba(184,58,68,.38)}.interface-switcher-main{min-width:0}.interface-switcher-title{display:flex;align-items:baseline;gap:7px;font-size:12px;font-weight:800}.interface-switcher-title .iface-alias{font-weight:600;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.interface-switcher-meta{margin-top:3px;color:var(--muted);font-size:9px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.interface-switcher-state{font-size:10px;font-weight:750;color:var(--muted)}.interface-switcher-empty{padding:10px;color:var(--muted);font-size:11px}.page-head-button-row{display:flex;align-items:center;gap:8px}.interface-manager-card .card-head{padding-bottom:13px}.interface-manager-list{display:flex;flex-direction:column}.interface-manager-row{display:grid;grid-template-columns:13px minmax(180px,1.1fr) minmax(160px,.8fr) minmax(100px,.55fr) minmax(90px,.45fr) auto;gap:14px;align-items:center;padding:12px 16px;border-bottom:1px solid var(--border);cursor:pointer}.interface-manager-row:last-child{border-bottom:0}.interface-manager-row:hover{background:rgba(255,255,255,.018)}.interface-manager-row.active{background:rgba(143,31,39,.07);box-shadow:inset 3px 0 0 #b83a44}.interface-manager-name{min-width:0}.interface-manager-title{display:flex;align-items:baseline;gap:8px;font-size:13px;font-weight:800}.interface-manager-alias{color:var(--muted);font-size:11px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.interface-manager-meta{margin-top:3px;color:var(--muted);font-size:10px}.interface-manager-value{min-width:0;color:var(--text);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.interface-manager-value .label{display:block;color:var(--muted);font-size:8px;font-weight:750;text-transform:uppercase;letter-spacing:.04em;margin-bottom:3px}.interface-manager-state{font-size:10px;font-weight:750}.interface-manager-state.running{color:var(--ok)}.interface-manager-state.stopped{color:var(--bad)}.interface-manager-state.unconfigured{color:var(--warn)}.interface-manager-action{justify-self:end;display:flex;align-items:center;gap:6px}.interface-create-modal{width:min(880px,100%)} +@media(max-width:980px){.interface-manager-row{grid-template-columns:13px minmax(160px,1fr) minmax(130px,.8fr) minmax(80px,.5fr) auto}.interface-manager-row .hide-medium{display:none}} +@media(max-width:760px){.interface-switcher-wrap{display:none}.page-head-button-row{width:100%;justify-content:flex-end}.interface-manager-row{grid-template-columns:13px minmax(0,1fr) auto;gap:10px}.interface-manager-row .interface-manager-value{display:none}.interface-manager-action{display:none}} +@media(max-width:760px){.interface-switcher-wrap{display:block}.interface-switcher-button.top-status{display:flex;max-width:190px;font-size:10px;padding:6px}.interface-switcher-button #header-status{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.interface-switcher-caret{display:none}} + +/* v0.17.1: interface deletion and required client fields */ +.interface-manager-action .btn:disabled{opacity:.42;cursor:not-allowed} + + +/* v0.18.0: client groups, inherited policies and reusable client defaults */ +.page-action-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.group-badge{display:inline-flex;align-items:center;max-width:180px;padding:3px 7px;border:1px solid rgba(111,145,216,.34);border-radius:999px;background:rgba(111,145,216,.1);color:#a9c0ef;font-size:10px;font-weight:800;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.group-config-warning{display:inline-flex;align-items:center;justify-content:center;margin-left:5px;color:var(--warn);font-size:12px;cursor:help}.field-button-wrap{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px}.field-button-wrap .btn{align-self:flex-start}.field-button-wrap small{font-size:10px;line-height:1.35}.policy-preview{padding:12px 13px;border:1px solid var(--border);border-radius:6px;background:rgba(255,255,255,.018)}.policy-preview-title{margin-bottom:8px;font-size:11px;font-weight:800;color:var(--text)}.policy-preview>div:last-child{display:grid;gap:6px}.policy-preview #client-policy-preview{display:grid;gap:6px}.policy-preview #client-policy-preview>div{display:grid;grid-template-columns:minmax(150px,.65fr) minmax(0,1.35fr);gap:12px;align-items:start;font-size:11px}.policy-preview #client-policy-preview span{color:var(--muted)}.policy-preview #client-policy-preview b,.policy-preview #client-policy-preview code{font-size:11px;word-break:break-word}.policy-ok{color:var(--ok)}.policy-block{color:var(--bad)}.group-list{display:flex;flex-direction:column;gap:8px}.group-row{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:13px 14px;border:1px solid var(--border);border-radius:6px;background:var(--panel-2)}.group-row-main{min-width:0}.group-row-title{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.group-description{margin:6px 0;color:var(--text);font-size:11px}.group-row .subtle{margin-top:4px}.group-empty{padding:26px 12px}.choice-row{display:flex;align-items:center;gap:8px;margin-bottom:10px;color:var(--text);font-size:12px}.choice-row input{accent-color:var(--accent)}#group-delete-target{width:100%;margin-top:4px;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px}.group-row .action-row{flex:0 0 auto}html[data-theme="light"] .group-badge{color:#486ba8;background:rgba(74,108,169,.08);border-color:rgba(74,108,169,.28)} +@media(max-width:760px){.page-action-row{width:100%}.group-row{align-items:flex-start;flex-direction:column}.group-row .action-row{width:100%}.policy-preview #client-policy-preview>div{grid-template-columns:1fr}.group-badge{max-width:140px}} +.setup-grid select:disabled,.setup-grid textarea:disabled,.field-block input:disabled,.field-block textarea:disabled{opacity:.62;cursor:not-allowed} +.compact-choice{margin:0}.group-config-mode{margin-top:12px}.group-config-mode>small{display:block;color:var(--muted);font-size:10px;line-height:1.4}.group-config-mode .inline-note{margin-top:10px} + +/* v0.19 client editor tabs */ +.client-editor-card{display:flex;flex-direction:column;overflow:hidden;height:min(820px,calc(100vh - 48px))} +.client-editor-card>.modal-head{position:static;flex:0 0 auto} +.client-editor-form-shell{display:flex;flex:1 1 auto;min-height:0;flex-direction:column} +.client-editor-tabs{display:flex;flex:0 0 auto;gap:4px;padding:0 18px;border-bottom:1px solid var(--border);background:var(--panel);overflow-x:auto} +.client-editor-tab{position:relative;flex:0 0 auto;border:0;background:transparent;color:var(--muted);padding:13px 15px 12px;cursor:pointer;font-weight:750;font-size:12px;white-space:nowrap} +.client-editor-tab:hover{color:var(--text);background:rgba(255,255,255,.018)} +.client-editor-tab.active{color:var(--text)} +.client-editor-tab.active::after{content:"";position:absolute;left:10px;right:10px;bottom:-1px;height:2px;border-radius:2px 2px 0 0;background:var(--accent)} +.client-editor-tab:disabled{opacity:.38;cursor:not-allowed;background:transparent} +.client-editor-body{flex:1 1 auto;min-height:0;overflow:auto} +.client-tab-panel[hidden]{display:none!important} +.client-editor-status-wrap{flex:0 0 auto;padding:0 18px;background:var(--panel)} +.client-editor-status-wrap .operation-status{margin:10px 0 12px} +.client-editor-card .modal-actions{position:static;flex:0 0 auto} +@media(max-width:700px){.client-editor-card{height:calc(100vh - 20px)}.client-editor-tabs{padding:0 8px}.client-editor-tab{padding:12px 10px;font-size:11px}.client-editor-body{padding:14px}} + +/* v0.19.2: recurring access schedule */ +.client-table-tools{display:flex;align-items:center;gap:8px;flex-wrap:wrap} +.schedule-enable-row{margin:0}.schedule-help{display:block;margin-top:6px;color:var(--muted);font-size:10px;line-height:1.45}.schedule-editor{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(220px,.75fr);gap:18px;padding:13px;border:1px solid var(--border);border-radius:6px;background:rgba(255,255,255,.018)}.schedule-editor>small{grid-column:1/-1;color:var(--muted);font-size:10px;line-height:1.45}.field-caption{display:block;margin-bottom:8px;color:var(--muted);font-size:11px}.schedule-days{display:flex;flex-wrap:wrap;gap:7px}.schedule-days label{position:relative}.schedule-days input{position:absolute;opacity:0;pointer-events:none}.schedule-days span{display:inline-flex;align-items:center;justify-content:center;min-width:38px;height:32px;padding:0 9px;border:1px solid var(--border);border-radius:5px;background:var(--panel-2);color:var(--muted);font-size:11px;font-weight:750;cursor:pointer}.schedule-days input:checked+span{border-color:rgba(184,58,68,.56);background:rgba(143,31,39,.16);color:var(--text)}.schedule-time-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.schedule-time-grid label{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:11px}.schedule-time-grid input{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:9px 10px;outline:none} +@media(max-width:760px){.client-table-tools{width:100%;justify-content:flex-end}.schedule-editor{grid-template-columns:1fr}.schedule-editor>small{grid-column:auto}.schedule-time-grid{grid-template-columns:1fr 1fr}} + + +/* v0.19.2 test refinement: compact security choices and stable client table */ +.setup-grid label.choice-row, +.setup-grid label.compact-choice, +.choice-row.schedule-enable-row{ + flex-direction:row; + align-items:center; + justify-content:flex-start; + gap:9px; + width:100%; + margin:0 0 10px; + text-align:left; +} +.setup-grid label.choice-row input[type="checkbox"], +.setup-grid label.compact-choice input[type="checkbox"], +.choice-row.schedule-enable-row input[type="checkbox"]{ + width:auto; + min-width:0; + flex:0 0 auto; + margin:0; +} +.setup-grid label.choice-row span, +.setup-grid label.compact-choice span, +.choice-row.schedule-enable-row span{ + flex:0 1 auto; + min-width:0; +} +.client-table-wrap{max-width:100%} +.client-table .action-row{gap:4px;flex-wrap:wrap} +.client-table .btn.small{padding:6px 7px} +.client-table th,.client-table td{padding-left:10px;padding-right:10px} +.client-table td:nth-child(1), +.client-table td:nth-child(4), +.client-table td:nth-child(6){white-space:normal} +.client-table td:nth-child(9){white-space:nowrap} +@media(min-width:1400px){ + .client-table-wrap{overflow-x:hidden;overflow-y:visible} + .client-table{table-layout:fixed;font-size:12px} + .client-table .client-col-name{width:20%} + .client-table .client-col-group{width:8%} + .client-table .client-col-address{width:9%} + .client-table .client-col-remote{width:10%} + .client-table .client-col-keepalive{width:6%} + .client-table .client-col-status{width:13%} + .client-table .client-col-handshake{width:9%} + .client-table .client-col-traffic{width:9%} + .client-table .client-col-actions{width:16%} + .client-table th,.client-table td{overflow:hidden;text-overflow:ellipsis} + .client-table td:nth-child(9){overflow:visible;text-overflow:clip} +} +@media(max-width:1399px){ + .client-table-wrap{overflow-x:auto} +} +/* v0.19.4: compact client actions and Dashboard quick-search controls */ +.dashboard-peer-tools{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex-wrap:wrap} +.quick-search-wrap{position:relative;display:inline-flex;align-items:center} +.quick-search-input{width:220px;max-width:42vw;background:var(--panel-2);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:8px 30px 8px 10px;font-size:11px;outline:none} +.quick-search-clear{position:absolute;right:6px;top:50%;transform:translateY(-50%);width:20px;height:20px;border:0;background:transparent;color:var(--muted);font-size:18px;line-height:18px;padding:0;cursor:pointer;border-radius:4px} +.quick-search-clear:hover{color:var(--text);background:rgba(255,255,255,.06)} +.quick-search-clear[hidden]{display:none} +.quick-search-input:focus{border-color:#59636f;box-shadow:0 0 0 2px rgba(89,99,111,.10)} +.quick-search-input::placeholder{color:var(--muted)} +.client-delete-compact{min-width:30px;font-size:15px;line-height:1;padding-left:7px!important;padding-right:7px!important} +@media(min-width:1400px){.client-table .action-row{flex-wrap:nowrap;gap:4px}.client-table td:nth-child(9){overflow:visible}} +@media(max-width:760px){.dashboard-peer-tools{width:100%;justify-content:flex-end}.quick-search-wrap{width:min(100%,240px)}.quick-search-input{width:100%;max-width:none}} + +/* v0.19.5: simple Clients quick search */ +.client-table-tools .quick-search-input{width:220px} +@media(max-width:760px){.client-table-tools{width:100%;justify-content:flex-end}.client-table-tools .quick-search-wrap{width:min(100%,240px)}.client-table-tools .quick-search-input{width:100%;max-width:none}} + +/* v0.19.6 — compact Server workspace tabs and VPS preflight */ +.server-editor-tabs{display:flex;gap:4px;margin:0 0 14px;padding:0 10px;border-bottom:1px solid var(--border);background:var(--panel);border-radius:12px 12px 0 0;overflow-x:auto} +.server-editor-tab{appearance:none;border:0;background:transparent;color:var(--muted);padding:13px 16px;border-bottom:2px solid transparent;font-weight:700;font-size:12px;cursor:pointer;white-space:nowrap} +.server-editor-tab:hover{color:var(--text)} +.server-editor-tab.active{color:var(--text);border-bottom-color:var(--accent)} +.server-tab-panel[hidden]{display:none!important} +.server-tab-panel>.card:first-child{margin-top:0} +.vps-empty{display:flex;align-items:center;gap:16px;padding:22px;border:1px dashed var(--border);border-radius:12px;background:var(--panel-2)} +.vps-empty-icon{display:grid;place-items:center;width:56px;height:56px;border-radius:14px;background:var(--panel);border:1px solid var(--border);font-weight:800;color:var(--muted)} +.vps-empty p{margin:5px 0 0;color:var(--muted)} +.vps-list{display:grid;gap:10px} +.vps-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:12px;padding:14px 16px;border:1px solid var(--border);border-radius:12px;background:var(--panel-2)} +.vps-row-main{min-width:0}.vps-row-title{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.vps-row-meta{display:flex;gap:10px;flex-wrap:wrap;margin-top:5px;color:var(--muted);font-size:12px}.vps-row-side{display:flex;align-items:center;gap:10px;max-width:420px}.vps-row-side .subtle{text-align:right} +.vps-operation-status{margin:8px 18px} +.vps-operation-status:not([hidden]) + .vps-preflight-result{margin-top:8px} +.vps-preflight-result{margin-top:12px;padding:14px;border:1px solid var(--border);border-radius:12px;background:var(--panel-2)} +.vps-preflight-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}.vps-preflight-result .kv-list.compact{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 18px}.vps-preflight-result .kv-list.compact>div{padding:6px 0} +.vps-modal textarea{min-height:130px;resize:vertical} +@media(max-width:850px){.vps-row{grid-template-columns:auto minmax(0,1fr)}.vps-row-side{grid-column:2;justify-content:space-between;max-width:none}.vps-row-side .subtle{text-align:left}.vps-preflight-result .kv-list.compact{grid-template-columns:1fr}} +@media(max-width:620px){.server-editor-tabs{padding:0 4px}.server-editor-tab{padding:12px 10px}.vps-row{grid-template-columns:1fr}.vps-row>.status-dot{display:none}.vps-row-side{grid-column:1;align-items:flex-start;flex-direction:column}.vps-empty{align-items:flex-start}.vps-empty-icon{display:none}} +.setup-grid .span-2{grid-column:1/-1} +.metric-title-row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:13px}.metric-title-row .metric-title{margin-bottom:0}.traffic-reset-button{padding:4px 8px!important;color:var(--muted);background:var(--panel-2);border-color:var(--border)}.traffic-reset-button:hover:not(:disabled){color:var(--text);background:rgba(255,255,255,.045)} + +/* v0.20.19 compact/collapsible navigation */ +:root{--sidebar-expanded-width:205px;--sidebar-compact-width:56px} +body{transition:padding-left .18s ease} +.sidebar{width:var(--sidebar-expanded-width);transition:width .18s ease;overflow:hidden} +.sidebar nav{flex:0 0 auto} +.nav-item{position:relative;min-width:0;transition:padding .18s ease,gap .18s ease,background-color .15s ease} +.nav-icon{display:grid;place-items:center;width:22px;height:22px;flex:0 0 22px;color:#d8dde2} +.nav-icon svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round} +.nav-label{min-width:0;overflow:hidden;white-space:nowrap;transition:opacity .12s ease} +.sidebar-bottom{margin-top:auto;flex:0 0 auto} +.sidebar-footer{margin-top:0;padding:10px 12px 13px} +.sidebar-project-link{display:flex;align-items:center;gap:8px;min-width:0;padding:5px 3px;color:#eef2f5;text-decoration:none;border-radius:5px;white-space:nowrap} +.sidebar-project-link:hover{background:rgba(255,255,255,.045)} +.sidebar-project-logo{width:25px;height:25px;flex:0 0 25px;border-radius:50%;object-fit:cover} +.sidebar-project-copy{min-width:0;font-size:11px;font-weight:750;overflow:hidden;text-overflow:ellipsis} +.sr-only{position:absolute!important;width:1px!important;height:1px!important;padding:0!important;margin:-1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important;white-space:nowrap!important;border:0!important} +html.sidebar-pref-collapsed body,body.sidebar-collapsed{padding-left:var(--sidebar-compact-width)} +html.sidebar-pref-collapsed .sidebar,body.sidebar-collapsed .sidebar{width:var(--sidebar-compact-width)} +html.sidebar-pref-collapsed .nav-item,body.sidebar-collapsed .nav-item{justify-content:center;gap:0;padding-left:0;padding-right:0} +html.sidebar-pref-collapsed .nav-label,body.sidebar-collapsed .nav-label{display:none;opacity:0} +html.sidebar-pref-collapsed .sidebar-footer,body.sidebar-collapsed .sidebar-footer{padding-left:11px;padding-right:11px} +html.sidebar-pref-collapsed .sidebar-project-link,body.sidebar-collapsed .sidebar-project-link{justify-content:center;padding:5px 0} +html.sidebar-pref-collapsed .sidebar-project-copy,body.sidebar-collapsed .sidebar-project-copy{display:none} +html.sidebar-pref-collapsed .sidebar-update-notice,body.sidebar-collapsed .sidebar-update-notice{justify-content:center;padding:8px;margin-bottom:8px} +html.sidebar-pref-collapsed .sidebar-update-copy,body.sidebar-collapsed .sidebar-update-copy{display:none} +@media(max-width:760px){ + body,body.sidebar-collapsed{padding-left:var(--sidebar-compact-width)} + .sidebar,body.sidebar-collapsed .sidebar{width:var(--sidebar-compact-width);transform:none} + .nav-item,body.sidebar-collapsed .nav-item{justify-content:center;gap:0;padding-left:0;padding-right:0} + .nav-label{display:none} + .sidebar-footer{padding-left:11px;padding-right:11px} + .sidebar-project-link{justify-content:center;padding:5px 0} + .sidebar-project-copy,.sidebar-update-copy{display:none} + .sidebar-update-notice{justify-content:center;padding:8px;margin-bottom:8px} +} + +/* v0.20.22: mail recovery and user email management */ +.mail-settings-body{padding:18px}.mail-enable-row{display:flex;align-items:center;justify-content:space-between;gap:18px}.mail-enable-row .hint{padding:0;margin:0;text-align:right}.mail-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px 18px;margin-top:18px}.mail-grid>label{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px;min-width:0}.mail-grid input,.mail-grid select{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px;outline:none}.mail-grid input:focus,.mail-grid select:focus{border-color:#7d8995;box-shadow:0 0 0 2px rgba(125,137,149,.12)}.mail-grid small{font-size:10px;line-height:1.45}.mail-actions{display:flex;align-items:center;gap:8px;margin-top:16px}.mail-actions-spacer{flex:1}.mail-card .operation-status{margin:16px 0 0}.mail-card .badge.managed{background:rgba(105,193,125,.1);color:var(--ok);border:1px solid rgba(105,193,125,.25)}.auth-secondary-row{display:flex;justify-content:center;margin-top:-3px;font-size:12px}.auth-secondary-row a{color:#9fbce8;text-decoration:none}.auth-secondary-row a:hover{text-decoration:underline}.auth-reset-note{margin:0}.auth-form label small{font-size:10px;line-height:1.4}.users-card .action-row{flex-wrap:wrap}.users-card td:nth-child(2){word-break:break-word} +@media(max-width:760px){.mail-grid{grid-template-columns:1fr}.mail-enable-row{align-items:flex-start;flex-direction:column}.mail-enable-row .hint{text-align:left}.mail-actions{flex-wrap:wrap}.mail-actions-spacer{display:none}.mail-actions .btn{flex:1 1 auto}} + +/* v0.20.25: direct HTTPS and compact endpoint helpers */ +.input-action-wrap{display:flex;align-items:stretch;gap:6px;min-width:0} +.input-action-wrap>input{min-width:0;flex:1 1 auto} +.input-action-button{display:grid;place-items:center;flex:0 0 38px;width:38px;min-width:38px;border:1px solid var(--border);border-radius:5px;background:var(--panel-2);color:var(--text);cursor:pointer;font-size:16px;line-height:1;padding:0} +.input-action-button:hover:not(:disabled){background:rgba(255,255,255,.055);border-color:#59636f} +.path-copy-button{font-size:15px} +.https-card .settings-form-pad{padding:18px} +.https-enable-block{margin-bottom:18px}.https-enable-row{margin-bottom:0}.https-enable-help{display:block;margin:6px 0 0 25px;color:var(--muted);font-size:10px;line-height:1.45}.https-enable-row input:disabled+span{opacity:.58} +.https-port-note{margin:18px 0 0} +.https-port-status{display:grid;grid-template-columns:minmax(150px,.65fr) minmax(150px,.65fr) auto;gap:10px;align-items:center;margin-top:14px} +.https-port-status>div{display:flex;justify-content:space-between;gap:14px;padding:10px 12px;border:1px solid var(--border);border-radius:7px;background:var(--panel-2)} +.https-port-status>div span{color:var(--muted);font-size:12px}.https-port-status>div b{font-size:12px} +.https-certificate-block{margin-top:18px;padding-top:18px;border-top:1px solid var(--border)} +.https-paths{display:grid;grid-template-columns:1fr;gap:12px;margin-top:16px}.https-paths label{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px}.https-paths input{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px;outline:none} +.https-actions{display:flex;align-items:center;gap:8px;margin-top:16px}.https-actions-spacer{flex:1} +.https-card .operation-status{margin-top:16px} +@media(max-width:760px){.https-port-status{grid-template-columns:1fr}.https-port-status .btn{width:100%}.https-actions{flex-wrap:wrap}.https-actions-spacer{display:none}.https-actions .btn{flex:1 1 auto}} +.text-ok{color:var(--ok)!important}.text-warn{color:var(--warn)!important} + + +/* v0.20.30 — WGTools Nodes */ +.nodes-status{display:grid;gap:10px}.nodes-empty{padding:18px;border:1px dashed var(--border);border-radius:12px;background:var(--panel-2)}.nodes-empty p{margin:5px 0 0;color:var(--muted)} +.nodes-summary{margin:0}.nodes-summary.compact{grid-template-columns:repeat(2,minmax(0,1fr));gap:0 24px}.nodes-summary.compact>div{padding:9px 0}.nodes-summary dd.wrap{overflow-wrap:anywhere} +.nodes-code-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center}.nodes-code-row input{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px;outline:none}.nodes-code-row input:focus{border-color:#7d8995;box-shadow:0 0 0 2px rgba(125,137,149,.12)} +.nodes-list{display:grid;gap:10px}.node-row .status-dot{align-self:center}.node-details-modal .table-wrap{max-height:280px;overflow:auto}.node-clients-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:22px;margin-bottom:14px}.node-clients-head .setup-section-title{margin:0}.node-clients-search .quick-search-input{width:220px}.inline-note.danger{border-color:rgba(221,75,75,.35);background:rgba(221,75,75,.08);color:var(--text)} +@media(max-width:850px){.nodes-summary.compact{grid-template-columns:1fr}.nodes-code-row{grid-template-columns:1fr}.nodes-code-row .btn{justify-self:start}} + +/* v0.20.34 — Nodes publication picker and modal status spacing */ +#node-hub-status,#node-connect-status,#node-settings-status{margin:16px 0 0} +.nodes-available-networks{display:block;margin-top:2px;overflow-wrap:anywhere} + +/* v0.20.36 — compact Nodes actions */ +#nodes-primary-actions .btn{white-space:nowrap} + +/* v0.20.37 — quick search in remote Node clients */ +@media(max-width:760px){.node-clients-head{align-items:stretch;flex-direction:column}.node-clients-search,.node-clients-search .quick-search-input{width:100%;max-width:none}} + +.nodes-network-drift{border-color:rgba(217,179,95,.55)!important}.nodes-review-badge{margin-left:7px;vertical-align:middle}.nodes-network-warning{font-weight:600}.network-drift-field{border-color:var(--warn)!important;box-shadow:0 0 0 1px rgba(217,179,95,.18)} + +/* v0.30.1 — stable compact update notice + account MFA */ +.sidebar-update-notice{min-height:43px;box-sizing:border-box} +.sidebar-update-mark{width:23px;height:23px;min-width:23px;min-height:23px;flex:0 0 23px;box-sizing:border-box;font-size:15px;line-height:1} +html.sidebar-pref-collapsed .sidebar-update-notice,body.sidebar-collapsed .sidebar-update-notice{min-height:43px;padding:9px 4px} +.badge.success{background:rgba(105,193,125,.1);color:var(--ok);border:1px solid rgba(105,193,125,.25)} +.auth-mfa-intro{margin:-2px 0 2px;color:var(--muted);font-size:12px;line-height:1.5}.auth-mfa-intro b{display:block;margin-bottom:3px;color:var(--text);font-size:13px}.auth-mfa-intro p{margin:0} +.mfa-modal{width:min(620px,calc(100vw - 30px))}.mfa-modal .modal-body{display:grid;gap:16px}.mfa-inline-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:12px}.mfa-manage-actions{display:flex;justify-content:space-between;gap:10px;margin-top:14px}.mfa-status-row{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px}.mfa-setup-details{margin-top:18px;padding-top:18px;border-top:1px solid var(--border)}.mfa-qr-wrap{display:flex;justify-content:center;margin-bottom:14px}.mfa-qr-wrap img{display:block;width:210px;height:210px;padding:8px;border-radius:8px;background:#fff}.mfa-secret-wrap{display:grid;gap:6px;margin-bottom:10px}.mfa-secret-wrap span{color:var(--muted);font-size:11px}.mfa-secret-wrap code{display:block;padding:9px 10px;border:1px solid var(--border);border-radius:5px;background:var(--panel-2);font-size:12px;letter-spacing:.04em;overflow-wrap:anywhere;user-select:all}.mfa-recovery-panel{padding:14px;border:1px solid rgba(217,179,95,.35);border-radius:7px;background:rgba(217,179,95,.07)}.mfa-recovery-panel h3{margin:0 0 5px;font-size:13px}.mfa-recovery-panel .hint{margin:0 0 10px;padding:0}.mfa-recovery-panel pre{margin:0;padding:12px;border:1px solid var(--border);border-radius:6px;background:var(--panel-2);font:600 13px/1.7 ui-monospace,SFMono-Regular,Consolas,monospace;letter-spacing:.06em;user-select:all}.mfa-modal .operation-status{margin:0}.users-card td:nth-child(3){white-space:nowrap} +@media(max-width:760px){html.sidebar-pref-collapsed .sidebar-update-notice,body.sidebar-collapsed .sidebar-update-notice,.sidebar-update-notice{min-height:43px;padding:9px 4px}.mfa-manage-actions{align-items:stretch;flex-direction:column}.mfa-inline-actions .btn,.mfa-manage-actions .btn{width:100%}.mfa-status-row{align-items:flex-start;flex-direction:column}} + +/* v0.30.4 — interactive network traceroute route map */ +.trace-toolbar{display:grid;grid-template-columns:minmax(260px,1fr) auto auto;gap:12px;align-items:end;padding:16px 16px 8px}.trace-target-field{display:flex;flex-direction:column;gap:7px;color:var(--muted);font-size:12px}.trace-target-field input{width:100%;background:var(--panel-2);color:var(--text);border:1px solid var(--border);padding:10px 11px;border-radius:5px;outline:none}.trace-target-field input:focus{border-color:#7d8995;box-shadow:0 0 0 2px rgba(125,137,149,.12)}.trace-geo-toggle{height:38px;padding:0 4px;white-space:nowrap}.trace-privacy-note{padding:0 16px 13px;color:var(--muted);font-size:10px;line-height:1.55}.trace-operation-status{margin:0 16px 14px}.trace-summary-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;padding:3px 16px 16px}.trace-summary-item{border:1px solid var(--border);border-radius:6px;background:var(--panel-2);padding:11px 12px;min-width:0}.trace-summary-item span{display:block;color:var(--muted);font-size:9px;font-weight:800;text-transform:uppercase;letter-spacing:.04em;margin-bottom:5px}.trace-summary-item b{display:block;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.trace-summary-item small{display:block;color:var(--muted);font-size:10px;margin-top:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.trace-map-panel{margin:0 16px 16px;border:1px solid var(--border);border-radius:7px;overflow:hidden;background:var(--panel-2)}.trace-map-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px;padding:10px 12px;border-bottom:1px solid var(--border)}.trace-map-head b{font-size:12px}.trace-map-head span{color:var(--muted);font-size:10px}.trace-map{position:relative;width:100%;height:520px;min-height:320px;overflow:hidden;background:#16202a;cursor:grab;touch-action:none;user-select:none}.trace-map.dragging{cursor:grabbing}.trace-map-stage,.trace-map-tiles,.trace-map>svg{position:absolute;inset:0;width:100%;height:100%}.trace-map-tiles{overflow:hidden;background:#1a252e}.trace-map-tiles img{position:absolute;width:256px;height:256px;max-width:none;pointer-events:none;filter:brightness(.48) saturate(.55) contrast(1.18)}html[data-theme="light"] .trace-map{background:#dfe7ec}html[data-theme="light"] .trace-map-tiles{background:#e8eef2}html[data-theme="light"] .trace-map-tiles img{filter:saturate(.75) contrast(.92)}.trace-map-stage>svg{overflow:hidden;pointer-events:auto}.trace-route-line{stroke:#e24147;stroke-width:3.5;stroke-linecap:round;opacity:.92;fill:none;vector-effect:non-scaling-stroke;filter:drop-shadow(0 1px 2px rgba(0,0,0,.55))}.trace-route-line.estimated{stroke-dasharray:7 6;opacity:.65}.trace-route-marker{cursor:pointer}.trace-route-dot{fill:#202a33;stroke:#f2be4f;stroke-width:3;vector-effect:non-scaling-stroke;filter:drop-shadow(0 1px 2px rgba(0,0,0,.8))}.trace-route-marker:hover .trace-route-dot{stroke-width:5}.trace-route-dot.target{stroke:#67d68a;stroke-width:4}.trace-route-label{fill:#fff;font:700 12px Inter,Segoe UI,Arial,sans-serif;text-anchor:middle;dominant-baseline:middle;pointer-events:none}.trace-map-controls{position:absolute;z-index:5;top:12px;left:12px;display:flex;flex-direction:column;gap:5px}.trace-map-control{min-width:36px;height:36px;border:1px solid rgba(255,255,255,.22);border-radius:5px;background:rgba(24,32,40,.92);color:#fff;font-weight:800;font-size:19px;cursor:pointer;box-shadow:0 2px 7px rgba(0,0,0,.28)}.trace-map-control:hover{background:#303d48}.trace-map-control.trace-map-fit{width:auto;padding:0 10px;font-size:11px}.trace-map-attribution{position:absolute;z-index:5;right:4px;bottom:3px;background:rgba(245,245,245,.86);color:#333;border-radius:3px;padding:2px 5px;font-size:9px;line-height:1.2}.trace-map-attribution a{color:#245b89}.trace-map-popup{position:absolute;z-index:8;width:min(330px,calc(100% - 16px));display:flex;flex-direction:column;gap:5px;padding:10px 12px;border:1px solid var(--border);border-radius:6px;background:rgba(27,35,43,.97);color:var(--text);box-shadow:0 8px 24px rgba(0,0,0,.35);font-size:11px;line-height:1.4;pointer-events:none}.trace-map-popup[hidden]{display:none}.trace-map-popup b{font-size:12px}.trace-map-popup span{color:var(--muted)}.trace-map-popup strong{color:var(--text)}.trace-table-wrap{border-top:1px solid var(--border)}.trace-table th:nth-child(1),.trace-table td:nth-child(1){width:48px;text-align:center}.trace-table td{vertical-align:middle}.trace-hop-main{display:flex;align-items:center;gap:8px}.trace-hop-main .mono{font-weight:700}.trace-hop-target{color:var(--ok)}.trace-location{max-width:360px;overflow:hidden;text-overflow:ellipsis}.trace-rtt-warn{color:var(--warn);font-weight:700}.trace-rtt-bad{color:var(--bad);font-weight:700}.trace-loss-bad{color:var(--bad);font-weight:700} +@media(max-width:900px){.trace-toolbar{grid-template-columns:1fr auto}.trace-target-field{grid-column:1/-1}.trace-summary-grid{grid-template-columns:repeat(2,minmax(0,1fr))}} +@media(max-width:620px){.trace-toolbar{grid-template-columns:1fr}.trace-target-field{grid-column:auto}.trace-geo-toggle{height:auto;padding:3px 0}.trace-summary-grid{grid-template-columns:1fr 1fr}.trace-map-head{align-items:flex-start;flex-direction:column}.trace-map{height:360px;min-height:260px}.trace-table{min-width:680px}} +.trace-route-line.estimated{stroke-dasharray:7 6;opacity:.56} + +/* v0.30.5 — keep traceroute overlay above slippy-map tiles */ +.trace-map-stage{position:absolute;inset:0;width:100%;height:100%;overflow:hidden} +.trace-map-tiles{z-index:1} +.trace-map-stage>svg{position:absolute;inset:0;z-index:3;width:100%;height:100%;overflow:hidden;pointer-events:auto} +.trace-route-line-halo{stroke:rgba(8,12,16,.92);stroke-width:8;stroke-linecap:round;opacity:.88;fill:none;vector-effect:non-scaling-stroke} +.trace-route-line-halo.estimated{stroke-dasharray:9 6;opacity:.7} +.trace-route-line{stroke:#ff4d57;stroke-width:4.5;opacity:1} +.trace-route-marker{position:relative} +.trace-route-dot{fill:#202a33;stroke:#ffd166;stroke-width:3.5} +.trace-route-dot.target{fill:#173326;stroke:#67e28e;stroke-width:4.5} +.trace-map-route-summary{padding:8px 12px;border-bottom:1px solid var(--border);background:rgba(0,0,0,.08);color:var(--muted);font-size:10px;line-height:1.5;white-space:normal} +.trace-map-route-summary b{color:var(--text)} +.trace-map-route-summary span{display:inline-block;padding:0 3px;color:var(--warn)} + + +/* v0.30.6 — traceroute latency-growth colors and neutral no-reply state */ +.trace-latency-legend{display:flex;align-items:center;gap:16px;flex-wrap:wrap;padding:7px 12px;border-bottom:1px solid var(--border);background:rgba(0,0,0,.045);color:var(--muted);font-size:10px} +.trace-latency-legend span{display:inline-flex;align-items:center;gap:6px}.trace-legend-dot{display:inline-block;width:10px;height:10px;border-radius:50%;box-shadow:0 0 0 1px rgba(0,0,0,.45)}.trace-legend-ok{background:#59c77a}.trace-legend-warn{background:#e0aa3e}.trace-legend-bad{background:#e45b62} +.trace-route-line.latency-ok{stroke:#59c77a}.trace-route-line.latency-warn{stroke:#e0aa3e}.trace-route-line.latency-bad{stroke:#e45b62}.trace-route-line.latency-unknown{stroke:#8b97a3} +.trace-route-marker.latency-ok .trace-route-dot:not(.target){stroke:#59c77a}.trace-route-marker.latency-warn .trace-route-dot:not(.target){stroke:#e0aa3e}.trace-route-marker.latency-bad .trace-route-dot:not(.target){stroke:#e45b62;stroke-width:4}.trace-route-marker.latency-unknown .trace-route-dot:not(.target){stroke:#8b97a3} +.trace-delta-ok{color:var(--ok);font-weight:700}.trace-delta-warn{color:var(--warn);font-weight:800}.trace-delta-bad{color:var(--bad);font-weight:800}.trace-loss-none{color:var(--muted)}.trace-loss-warn{color:var(--warn);font-weight:700} +.trace-table tr.trace-hop-latency-warn td{background:rgba(224,170,62,.055)}.trace-table tr.trace-hop-latency-bad td{background:rgba(228,91,98,.075)}.trace-table tr.trace-hop-latency-warn td:first-child{box-shadow:inset 3px 0 0 #e0aa3e}.trace-table tr.trace-hop-latency-bad td:first-child{box-shadow:inset 3px 0 0 #e45b62} + +/* v0.40.1: visible update and instant topbar theme toggle */ +.topbar-theme-toggle{display:flex;align-items:center;justify-content:center;width:31px;height:31px;flex:0 0 31px;padding:0;line-height:0;border:1px solid rgba(255,255,255,.38);border-radius:7px;background:rgba(255,255,255,.08);color:#fff;cursor:pointer} +.topbar-theme-icon{width:20px;height:20px;display:grid;place-items:center;line-height:0} +.topbar-theme-icon svg{display:block;width:20px;height:20px;overflow:visible} +.topbar-theme-icon .theme-icon-moon{display:none} +html[data-theme="light"] .topbar-theme-icon .theme-icon-sun{display:none} +html[data-theme="light"] .topbar-theme-icon .theme-icon-moon{display:block} +.topbar-theme-toggle:hover{background:rgba(255,255,255,.2)} +.topbar-theme-toggle:focus-visible,.topbar-update-link:focus-visible{outline:2px solid #fff;outline-offset:2px} +.topbar-update-link{display:flex;align-items:center;gap:4px;text-decoration:none;color:#ffe6a3;border:1px solid rgba(255,225,160,.55);border-radius:6px;padding:5px 7px;font-weight:800;font-size:11px;background:rgba(20,20,20,.14);white-space:nowrap} +.topbar-update-link:hover{background:rgba(255,225,160,.12)} +.topbar-update-link[hidden]{display:none!important} +@media(max-width:760px){.topbar-update-link{padding:5px}.topbar-update-link span{display:none}.topbar-theme-toggle{width:29px;height:29px;flex-basis:29px}} + +/* v0.40.5: header audit shortcut and compact sidebar control */ +.topbar-audit-toggle{display:inline-grid;place-items:center;width:31px;height:31px;flex:0 0 31px;padding:0;border:1px solid rgba(255,255,255,.38);border-radius:7px;background:rgba(255,255,255,.08);color:#fff;cursor:pointer} +.topbar-audit-toggle svg{width:19px;height:19px;display:block} +.topbar-audit-toggle:hover{background:rgba(255,255,255,.2)} +.topbar-audit-toggle:focus-visible,.sidebar-collapse-button:focus-visible{outline:2px solid var(--ok);outline-offset:2px} +.sidebar-collapse-button{display:flex;align-items:center;justify-content:center;gap:9px;width:100%;border:1px solid rgba(255,255,255,.14);border-radius:7px;min-height:36px;background:rgba(255,255,255,.05);color:#e7ebef;cursor:pointer;font-size:11px;font-weight:700} +.sidebar-collapse-button:hover{background:rgba(255,255,255,.13)} +.sidebar-collapse-button svg{width:19px;height:19px;flex:0 0 19px} +.sidebar-collapse-button.is-collapsed svg{transform:scaleX(-1)} +html.sidebar-pref-collapsed .sidebar-collapse-caption,body.sidebar-collapsed .sidebar-collapse-caption{display:none} +@media(max-width:760px){.sidebar-collapse-caption{display:none}.topbar-audit-toggle{width:29px;height:29px;flex-basis:29px}} diff --git a/app/static/de.json b/app/static/de.json new file mode 100644 index 0000000..492122e --- /dev/null +++ b/app/static/de.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Benutzer erstellen", + "auth.login_subtitle": "Gib deinen WGTools-Benutzernamen und dein Passwort ein.", + "auth.login_title": "Bei WGTools anmelden", + "auth.password": "Passwort", + "auth.password_repeat": "Passwort wiederholen", + "auth.setup_help": "Das erste Konto erhält vollen Zugriff auf WGTools. Weitere Benutzer können später in den Einstellungen erstellt werden.", + "auth.setup_subtitle": "Vor der Serververwaltung muss ein WGTools-Konto eingerichtet werden.", + "auth.setup_title": "Ersten Benutzer erstellen", + "auth.sign_in": "Anmelden", + "auth.sign_out": "Abmelden", + "auth.username": "Benutzername", + "clients.actions": "Aktionen", + "clients.add": "+ Client hinzufügen", + "clients.address": "VPN-Adresse", + "clients.address_hint": "Die erste freie Adresse wird automatisch vorgeschlagen.", + "clients.allowed_ips_required": "Gib mindestens ein AllowedIPs-Netz für die Client-Konfiguration ein.", + "clients.basic_connection": "Verbindungseinstellungen", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs in Client-Konfiguration", + "clients.config_private_warning": "Diese Konfiguration enthält den privaten Client-Schlüssel. Bewahre sie sicher auf.", + "clients.config_title": "Client-Konfiguration", + "clients.config_unavailable": "Konfiguration nicht verfügbar", + "clients.connection_direct": "Direkt zu WGTools", + "clients.connection_path": "Verbindungsweg", + "clients.connection_relay": "VPS-Relay", + "clients.connection_via": "Verbinden über", + "clients.connection_via_hint": "Wähle den öffentlichen Zugang für diesen Client. Relay ist nur sichtbar, wenn es für die ausgewählte WireGuard-Schnittstelle installiert ist.", + "clients.copy_config": "Kopieren", + "clients.copy_done": "Konfiguration kopiert", + "clients.create_subtitle": "WireGuard-Peer erstellen und Client-Konfiguration erzeugen.", + "clients.create_title": "Client erstellen", + "clients.creating": "Schlüssel werden erstellt und Client angewendet…", + "clients.day_fri": "Fr", + "clients.day_mon": "Mo", + "clients.day_sat": "Sa", + "clients.day_sun": "So", + "clients.day_thu": "Do", + "clients.day_tue": "Di", + "clients.day_wed": "Mi", + "clients.delete_confirm": "Diesen Client aus WireGuard löschen? WGTools erstellt ein Backup und entfernt die automatisch generierten Richtlinienregeln dieses Clients.", + "clients.deleted": "Client gelöscht", + "clients.dns": "DNS (optional)", + "clients.dns_hint": "IPv4-DNS-Server durch Komma trennen.", + "clients.download_config": ".conf herunterladen", + "clients.duplicate": "Duplizieren", + "clients.duplicate_address_error": "Diese VPN-Adresse wird bereits von einem anderen Peer verwendet.", + "clients.duplicate_name_error": "Ein Peer mit diesem Namen existiert bereits.", + "clients.duplicate_ready": "Kopie bereit. WGTools hat einen neuen Namen und eine VPN-Adresse vergeben. Prüfe die Einstellungen vor dem Speichern.", + "clients.duplicate_site_hint": "Remote-Netze wurden entfernt, um doppelte Routen zu vermeiden. Gib die Netze für den neuen Site-to-site-Peer ein.", + "clients.duplicate_suffix": "Kopie", + "clients.edit_subtitle": "Serverseitigen Peer aktualisieren. Änderungen werden ohne WireGuard-Neustart angewendet.", + "clients.edit_title": "Client bearbeiten", + "clients.endpoint": "Server-Endpoint", + "clients.endpoint_hint": "Für Remote-Clients die öffentliche IP oder Domain verwenden, die den WireGuard-Port an diesen Server weiterleitet.", + "clients.existing": "Vorhandener Peer", + "clients.expiration": "Gültigkeitsdauer", + "clients.expiration_action": "Bei Ablauf", + "clients.expiration_action_hint": "Ohne Haken bleibt der Client in WGTools, aber WireGuard-Zugriff wird gesperrt. Neue Laufzeit oder „Kein Ablaufdatum“ wählen und speichern, um ihn freizugeben.", + "clients.expiration_datetime": "Läuft ab am", + "clients.expiration_datetime_hint": "Verwendet lokales Datum und Uhrzeit dieses Browsers.", + "clients.expiration_delete": "Client löschen", + "clients.expiration_future_required": "Wähle Datum und Uhrzeit in der Zukunft.", + "clients.expiration_hint": "Bei Ablauf führt WGTools die gewählte Aktion zur nächsten vollen Minute aus. Zuvor wird ein WireGuard-Backup erstellt.", + "clients.expire_1d": "1 Tag", + "clients.expire_1h": "1 Stunde", + "clients.expire_3h": "3 Stunden", + "clients.expire_6h": "6 Stunden", + "clients.expire_custom": "Eigenes Datum und Uhrzeit", + "clients.expire_never": "Kein Ablaufdatum", + "clients.expired": "Abgelaufen", + "clients.expired_disabled_hint": "Die Gültigkeit ist abgelaufen. Der Client bleibt erhalten, aber WireGuard-Zugriff ist gesperrt. Wähle eine neue Laufzeit oder „Kein Ablaufdatum“ und speichere.", + "clients.expired_disabled_short": "Abgelaufen · deaktiviert", + "clients.expired_disabled_status": "Abgelaufen", + "clients.expires_days": "Läuft in {n} Tagen ab", + "clients.expires_hours": "Läuft in {n} Std. ab", + "clients.expires_minutes": "Läuft in {n} Min. ab", + "clients.generated_config": "Erstellte Client-Konfiguration", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 Sekunden sind ein guter Standardwert für Clients hinter NAT.", + "clients.local_access_exceptions": "Erlaubte lokale Adressen", + "clients.local_access_exceptions_hint": "Optionale IPs oder CIDRs, die trotz Sperre ihres lokalen oder Site-to-site-Netzes erreichbar bleiben. Kommagetrennt eingeben.", + "clients.managed": "Von WGTools verwaltet", + "clients.name": "Name", + "clients.no_peers": "Keine Peers gefunden", + "clients.peers": "Peers", + "clients.peers_subtitle": "Änderungen werden gesichert und mit wg syncconf ohne Neustart der WireGuard-Schnittstelle angewendet.", + "clients.protected_networks_reference": "Gesperrte lokale Netze (Referenz)", + "clients.protected_networks_reference_hint": "Diese Netze erscheinen nicht in AllowedIPs. Der Zugriff wird durch WGTools-Serverregeln gesperrt; einzelne Adressen können oben erlaubt werden.", + "clients.psk": "Zusätzlicher Schlüssel (PSK)", + "clients.psk_enable": "Zusätzlichen WireGuard-PSK verwenden", + "clients.psk_hint": "Empfohlen. Fügt dem WireGuard-Handshake ein zusätzliches symmetrisches Geheimnis hinzu. Standard-Clients unterstützen es; WGTools fügt den PSK in Konfiguration und QR ein.", + "clients.psk_short": "PSK", + "clients.qr_loading": "QR-Code wird erstellt…", + "clients.quick_search": "Schnellsuche", + "clients.quick_search_clear": "Suche löschen", + "clients.quick_search_empty": "Keine passenden Clients gefunden", + "clients.relay_endpoint_note": "Die erstellte Client-Konfiguration verbindet sich mit {endpoint}. Der WireGuard-Server bleibt auf diesem WGTools-Host.", + "clients.relay_required": "Wähle einen VPS-Relay für diesen Client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "nicht verfügbar", + "clients.relay_vps": "VPS-Relay", + "clients.relay_vps_hint": "Der Client-Endpoint wird automatisch aus diesem Relay erstellt.", + "clients.remote_hint": "Netze hinter diesem Peer. Ein Netz pro Zeile oder durch Komma getrennt.", + "clients.remote_networks": "Entfernte Netzwerke", + "clients.remote_required": "Gib mindestens ein Remote-Netz für den Site-to-site-Peer an.", + "clients.required": "Name und VPN-Adresse sind erforderlich.", + "clients.route_custom": "Benutzerdefiniert", + "clients.route_full": "Vollständiger Tunnel", + "clients.route_full_except_local": "Vollständiger Tunnel außer lokalen Netzen", + "clients.route_hint": "Nur diese Netze werden in AllowedIPs der Client-Konfiguration geschrieben.", + "clients.route_preset": "Verkehr über VPN", + "clients.route_vpn": "Nur VPN-Netzwerk", + "clients.route_vpn_lan": "VPN + lokales LAN", + "clients.saved": "Client gespeichert", + "clients.schedule_blocked_short": "Zeitplan · gesperrt", + "clients.schedule_blocked_status": "Durch Zeitplan gesperrt", + "clients.schedule_days": "Erlaubte Tage", + "clients.schedule_days_required": "Wähle mindestens einen Tag für den Zeitplan.", + "clients.schedule_disabled_hint": "Dieser Client wird derzeit durch seinen Zeitplan gesperrt. WGTools stellt den Peer beim nächsten erlaubten Zeitfenster automatisch wieder her.", + "clients.schedule_enable": "Zugriff nach Zeitplan begrenzen", + "clients.schedule_from": "Zugriff ab", + "clients.schedule_hint": "WGTools kann diesen Client an ausgewählten Tagen und Zeiten automatisch sperren und wieder freigeben, ohne seine Konfiguration zu ändern.", + "clients.schedule_short": "Zeitplan", + "clients.schedule_time_required": "Lege Start- und Endzeit des Zeitplans fest.", + "clients.schedule_timezone_hint": "Der Zeitplan verwendet die lokale Uhrzeit des WireGuard-Servers. Zeitfenster über Mitternacht, z. B. 22:00–06:00, werden unterstützt.", + "clients.schedule_title": "Zugriffszeitplan", + "clients.schedule_to": "Zugriff bis", + "clients.security_access": "Sicherheit und Zugriffszeiten", + "clients.server_host": "Serveradresse / Domain", + "clients.server_host_hint": "Öffentliche IP oder Domain dieses Clients. Früher verwendete Werte werden vorgeschlagen.", + "clients.server_host_required": "Serveradresse / Domain ist für die Client-Konfiguration erforderlich.", + "clients.server_peer": "Server-Peer", + "clients.server_port": "WireGuard-Port", + "clients.server_port_hint": "Wird automatisch aus der Serverkonfiguration übernommen.", + "clients.site_to_site": "Standort-zu-Standort", + "clients.status": "Status", + "clients.subtitle": "WireGuard-Peers, Live-Status und Verwaltung der Client-Konfigurationen.", + "clients.tab_basic": "Grundlagen", + "clients.tab_config": "Konfiguration", + "clients.tab_policy": "Richtlinien", + "clients.tab_security": "Sicherheit", + "clients.title": "Clients", + "clients.type": "Typ", + "clients.unmanaged_note": "Dieser Peer existierte vor WGTools. Sein privater Client-Schlüssel kann nicht wiederhergestellt werden. WGTools kann den serverseitigen Peer bearbeiten, aber keine Client-Konfiguration oder QR erzeugen.", + "clients.updating": "Client wird aktualisiert…", + "common.actions": "Aktionen", + "common.ago": "vor", + "common.cancel": "Abbrechen", + "common.checking": "Prüfung läuft…", + "common.close": "Schließen", + "common.config": "Konfiguration", + "common.delete": "Löschen", + "common.disabled": "Deaktiviert", + "common.edit": "Bearbeiten", + "common.enabled": "Aktiviert", + "common.loading": "Wird geladen…", + "common.never": "Nie", + "common.no": "Nein", + "common.not_configured": "Nicht konfiguriert", + "common.not_installed": "Nicht installiert", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Aktualisieren", + "common.running": "Läuft", + "common.save": "Speichern", + "common.stopped": "Angehalten", + "common.total": "Gesamt", + "common.unknown": "Unbekannt", + "common.updated": "Aktualisiert", + "common.yes": "Ja", + "dashboard.active_peers": "Aktive Peers", + "dashboard.active_peers_subtitle": "Live-Daten aus wg show.", + "dashboard.activity": "Systemübersicht", + "dashboard.activity_subtitle": "Schreibgeschützte Prüfungen des laufenden WireGuard-Systems.", + "dashboard.cores": "Kerne", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Letzte 24 Std.", + "dashboard.history_avg": "Ø", + "dashboard.history_max": "Max.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "jetzt", + "dashboard.memory": "Arbeitsspeicher", + "dashboard.network": "Netzwerk", + "dashboard.peers": "Peers", + "dashboard.quick_search": "Schnellsuche", + "dashboard.quick_search_clear": "Suche löschen", + "dashboard.quick_search_empty": "Keine passenden Peers gefunden", + "dashboard.restart": "Neustart", + "dashboard.restart_confirm": "WireGuard neu starten? Aktive VPN-Clients werden automatisch wieder verbunden.", + "dashboard.restart_ok": "WireGuard neu gestartet.", + "dashboard.routing": "Routing", + "dashboard.site_to_site": "Standort-zu-Standort", + "dashboard.start": "Starten", + "dashboard.start_ok": "WireGuard gestartet.", + "dashboard.stop": "Stoppen", + "dashboard.stop_confirm": "WireGuard stoppen? Aktive VPN-Clients werden getrennt.", + "dashboard.stop_ok": "WireGuard gestoppt.", + "dashboard.subtitle": "WireGuard-Serverstatus, Peers und Live-Traffic.", + "dashboard.title": "Übersicht", + "dashboard.traffic": "Datenverkehr", + "dashboard.uptime": "Betriebszeit", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Server-Zugriffsregeln", + "groups.additional_allowed": "Zusätzlich erlaubte Adressen", + "groups.additional_blocked": "Zusätzlich gesperrte Adressen", + "groups.allow": "Erlauben", + "groups.allowed": "Erlaubt", + "groups.allowed_addresses": "Erlaubte Adressen / Netze", + "groups.apply_current_template": "Aktuelle Gruppenvorlage anwenden", + "groups.apply_defaults": "Aktuelle Gruppenvorlage anwenden", + "groups.apply_defaults_hint": "Übernimmt Routen, DNS und Keepalive der Gruppenvorlage für diesen Client. Client speichern und bei Bedarf neue Konfiguration oder QR ausgeben.", + "groups.basic": "Grunddaten", + "groups.block": "Sperren", + "groups.blocked": "Gesperrt", + "groups.blocked_addresses": "Gesperrte Adressen / Netze", + "groups.client_config_source": "Quelle der Client-Konfiguration", + "groups.client_defaults": "Client-Standardwerte", + "groups.client_group_hint": "Optionale Gruppe für wiederverwendbare Zugriffsregeln und Client-Standardwerte. Gruppen gelten nur für die ausgewählte WireGuard-Schnittstelle.", + "groups.config_differs": "Die Client-Konfiguration weicht von den aktuellen Gruppenvorgaben ab. Die Serverregeln sind aktuell; die Konfiguration auf Handy oder PC ändert sich erst nach Ausgabe einer neuen Konfiguration oder eines QR-Codes.", + "groups.config_differs_short": "Client-Konfiguration weicht von Gruppe ab", + "groups.create": "Gruppe erstellen", + "groups.create_title": "Gruppe erstellen", + "groups.created": "Gruppe erstellt", + "groups.creating": "Gruppe wird erstellt…", + "groups.defaults_applied": "Aktuelle Gruppenvorlage übernommen. Client zum Speichern sichern.", + "groups.defaults_hint": "Legt fest, welchen Traffic das Client-Gerät über WireGuard sendet. Die obigen Serverregeln bestimmen separat den erlaubten Zugriff. Änderungen an der Vorlage ändern nie heimlich bereits installierte Konfigurationen.", + "groups.delete_message": "„{name}“ löschen? Client-Konfigurationen werden beim Löschen einer Gruppe nie entfernt.", + "groups.delete_move": "Clients in andere Gruppe verschieben", + "groups.delete_title": "Client-Gruppe löschen", + "groups.delete_unassign": "Gruppenzuordnung der Clients entfernen", + "groups.deleted": "Gruppe gelöscht", + "groups.deleting": "Clients werden aktualisiert und Gruppe gelöscht…", + "groups.description": "Beschreibung", + "groups.edit_title": "Gruppe bearbeiten", + "groups.editor_subtitle": "Eine Gruppe kombiniert aktive Server-Zugriffsregeln mit einer Vorlage für neue Client-Konfigurationen.", + "groups.effective_allow": "Erlaubte Ausnahmen", + "groups.effective_deny": "Gesperrte Ausnahmen", + "groups.effective_policy": "Wirksame Serverregeln", + "groups.empty": "Noch keine Client-Gruppen. Erstelle eine Gruppe, um Zugriffsregeln und Client-Standardwerte wiederzuverwenden.", + "groups.group": "Gruppe", + "groups.inherit": "Übernehmen", + "groups.internet_access": "Internetzugriff", + "groups.internet_short": "Internet", + "groups.local_access": "Lokale Netzwerke", + "groups.local_short": "Lokal", + "groups.manage": "Gruppen", + "groups.members_count": "{count} Clients", + "groups.name": "Name", + "groups.name_required": "Gruppenname erforderlich.", + "groups.new_client_defaults": "Client-Konfigurationsvorlage", + "groups.new_clients_short": "Neue Clients", + "groups.no_group": "Keine Gruppe", + "groups.none": "Keine", + "groups.override_client_config": "Gruppenvorlage für diesen Client überschreiben", + "groups.override_client_config_hint": "Aus: Routen, DNS und Keepalive kommen aus der Gruppenvorlage. Ein: Dieser Client nutzt eigene Werte. Änderungen an den Serverregeln oben bleiben unabhängig.", + "groups.policy_addresses_hint": "IPv4-Adressen oder CIDRs, durch Komma getrennt. Client-Ausnahmen haben Vorrang vor Gruppenausnahmen.", + "groups.policy_custom": "Eigene Regeln", + "groups.policy_inherit": "Gruppenregeln verwenden", + "groups.policy_mode": "Regelquelle", + "groups.policy_mode_hint": "Standardmäßig gelten die Gruppenregeln. Client-Ausnahmen ändern nie die Gruppe selbst.", + "groups.routes_required": "Client-Routen dürfen nicht leer sein.", + "groups.subtitle": "Server-Zugriffsregeln und Standardwerte für normale Clients auf der gewählten WireGuard-Schnittstelle wiederverwenden.", + "groups.title": "Client-Gruppen", + "groups.traffic_through_vpn": "Verkehr über VPN", + "groups.updated": "Gruppe aktualisiert", + "groups.updating": "Gruppenregeln werden aktualisiert…", + "help.example_note": "Alle Adressen, Schnittstellen, Peer-Namen und Domains in der Hilfe sind fiktiv. Ersetze sie durch Werte aus deinem Netzwerk.", + "help.navigation": "Hilfe-Navigation", + "help.open": "Hilfe öffnen", + "help.subtitle": "Verständliche Hilfe für Dashboard, Server, Clients und Einstellungen mit kurzen Beispielen.", + "help.title": "WGTools-Hilfe", + "interfaces.add": "+ Schnittstelle hinzufügen", + "interfaces.create": "Schnittstelle erstellen", + "interfaces.create_confirm": "Schnittstelle {name} erstellen und starten?", + "interfaces.create_failed": "Schnittstelle konnte nicht erstellt werden", + "interfaces.create_hint": "WGTools prüft vor der Erstellung, dass VPN-Netz, UDP-Port und Policy-Routing-Tabelle nicht mit anderen WireGuard-Schnittstellen kollidieren.", + "interfaces.create_subtitle": "Eine unabhängige WireGuard-Schnittstelle mit eigenem Adresspool, UDP-Port und Routing-Einstellungen erstellen.", + "interfaces.create_title": "WireGuard-Schnittstelle hinzufügen", + "interfaces.created": "Schnittstelle erfolgreich erstellt.", + "interfaces.creating": "Schlüssel werden erzeugt, Konfiguration gespeichert und WireGuard gestartet…", + "interfaces.current": "Aktuell", + "interfaces.delete": "Löschen", + "interfaces.delete_confirm": "Schnittstelle {name} löschen? Ihre WireGuard-Konfiguration und alle Peers werden entfernt. Zuvor wird ein Backup erstellt.", + "interfaces.delete_failed": "Schnittstelle konnte nicht gelöscht werden", + "interfaces.delete_last": "Die letzte konfigurierte WireGuard-Schnittstelle kann hier nicht gelöscht werden.", + "interfaces.delete_tooltip": "Diese WireGuard-Schnittstelle löschen", + "interfaces.deleted": "Schnittstelle gelöscht. Backup: {backup}", + "interfaces.deleting": "WireGuard wird gestoppt und Schnittstelle gelöscht…", + "interfaces.display_name": "Anzeigename", + "interfaces.display_name_edit_hint": "Nur Anzeigename; der Linux-Schnittstellenname bleibt unverändert.", + "interfaces.display_name_hint": "Optionaler Anzeigename, z. B. Arbeit oder Auftragnehmer.", + "interfaces.identity": "Schnittstellenkennung", + "interfaces.none": "Keine WireGuard-Schnittstellen gefunden", + "interfaces.none_configured": "Noch keine WireGuard-Schnittstellen konfiguriert.", + "interfaces.peers_short": "Peers", + "interfaces.rename_failed": "Anzeigename der Schnittstelle konnte nicht gespeichert werden.", + "interfaces.select": "Auswählen", + "interfaces.subtitle": "Jede Schnittstelle hat ein eigenes VPN-Netz, einen Port, Peers und Regeln. Wähle eine, um sie in WGTools zu verwalten.", + "interfaces.switch_title": "WireGuard-Schnittstellen", + "interfaces.system_name": "Systemname", + "interfaces.system_name_hint": "Linux-Schnittstellenname, z. B. wg1. Nach der Erstellung unveränderbar.", + "interfaces.title": "WireGuard-Schnittstellen", + "interfaces.unique_port_hint": "Jede WireGuard-Schnittstelle auf diesem Server muss einen eigenen UDP-Port verwenden.", + "interfaces.unique_table_hint": "WGTools empfiehlt eine eigene Routing-Tabelle pro Schnittstelle. Für normales Routing leer lassen.", + "nav.clients": "Clients", + "nav.dashboard": "Übersicht", + "nav.server": "Server", + "nav.settings": "Einstellungen", + "server.access_apply_confirm": "Diese Firewall-Regel speichern und anwenden? WireGuard wird kurz neu gestartet und ein Backup erstellt.", + "server.access_rule_deleted": "Zugriffsregel gelöscht.", + "server.access_rule_help": "Allgemeine FORWARD-Zugriffsregel erstellen, ohne iptables-Befehle manuell zu bearbeiten.", + "server.access_rule_order_hint": "WGTools fügt Zugriffsregeln am Anfang der FORWARD-Kette ein, damit Einschränkungen vor allgemeinen VPN-ACCEPT-Regeln greifen.", + "server.access_rule_saved": "Zugriffsregel gespeichert und angewendet.", + "server.action": "Aktion", + "server.action_hint": "REJECT meldet dem Client die Ablehnung; DROP verwirft still; ACCEPT erlaubt ausdrücklich.", + "server.add_access_rule": "Zugriffsregel hinzufügen", + "server.add_route": "Route hinzufügen", + "server.address": "Adresse", + "server.any": "Beliebig", + "server.any_protocol": "Beliebig", + "server.apply_confirm": "Servereinstellungen speichern und anwenden? WireGuard wird kurz neu gestartet. Zuvor erstellt WGTools ein Backup und stellt bei Startfehlern automatisch die vorherige Konfiguration wieder her.", + "server.apply_settings": "Speichern und anwenden", + "server.applying_rule": "Backup wird erstellt und Änderungen angewendet…", + "server.applying_settings": "Einstellungen werden geprüft, Backup erstellt und angewendet…", + "server.basic_settings": "Grundeinstellungen", + "server.config_tab_help": "Rohkonfigurationseditor der ausgewählten WireGuard-Schnittstelle öffnen.", + "server.create_confirm": "WireGuard-Server mit diesen Einstellungen erstellen und starten?", + "server.create_server": "Server erstellen", + "server.create_step_conf": "Konfiguration der ausgewählten WireGuard-Schnittstelle mit Modus 600 erstellen.", + "server.create_step_forward": "Forwarding, NAT und optionales Policy-Routing einrichten.", + "server.create_step_key": "Neues Server-Schlüsselpaar erzeugen.", + "server.create_step_start": "Ausgewählte wg-quick-Schnittstelle aktivieren und starten.", + "server.create_subtitle": "WireGuard ist installiert, aber die ausgewählte Schnittstelle ist noch nicht konfiguriert.", + "server.create_success": "WireGuard-Server erfolgreich erstellt.", + "server.create_title": "WireGuard-Server erstellen", + "server.creating": "Schlüssel werden erzeugt, Konfiguration gespeichert und WireGuard gestartet…", + "server.custom_preserved": "Peer-Blöcke, Site-to-site-Routen und eigene PostUp/PostDown-Regeln außerhalb dieser Felder bleiben erhalten.", + "server.delete_access_confirm": "Diese Zugriffsregel löschen und Änderung anwenden?", + "server.delete_route_confirm": "Diese eigene Route löschen und Änderung anwenden?", + "server.destination": "Ziel", + "server.destination_hint": "Leer = beliebig. IP, CIDR oder IP-Bereich. Mehrere Ziele durch Komma trennen.", + "server.destination_port": "Zielport", + "server.destination_port_hint": "Optional. Port wie 443 oder Bereich wie 10000:20000. Erst TCP oder UDP auswählen.", + "server.details": "Details", + "server.dev_word": "dev", + "server.diagnostics": "Diagnose", + "server.diagnostics_done": "Diagnose abgeschlossen", + "server.diagnostics_subtitle": "Aktuelle Systemprüfungen. Keine Konfigurationsänderung.", + "server.direction": "Hook", + "server.edit_access_rule": "Zugriffsregel bearbeiten", + "server.edit_route": "Route bearbeiten", + "server.edit_server": "Server bearbeiten", + "server.edit_subtitle": "Allgemeine WireGuard-, Routing- und NAT-Einstellungen bearbeiten. Vorhandene Peers und eigene Regeln bleiben erhalten.", + "server.edit_title": "Servereinstellungen", + "server.edit_warning": "Beim Anwenden von Schnittstellen-, Routing- oder Firewall-Einstellungen wird WireGuard kurz neu gestartet. Aktive Peers verbinden sich automatisch neu.", + "server.enable_forwarding": "IPv4-Forwarding aktivieren", + "server.enable_nat": "NAT / Masquerade aktivieren", + "server.firewall": "Firewall & NAT", + "server.firewall_subtitle": "Erkannte Regeln aus WireGuard-Hooks.", + "server.firewall_subtitle_v08": "Allgemeine Forwarding-/NAT- und Zugriffsregeln der Schnittstelle. Einfache Regeln können hier bearbeitet werden, komplexe im Rohkonfigurationseditor.", + "server.forward_from_vpn": "Weiterleitung aus VPN erlauben", + "server.forward_to_vpn": "Weiterleitung ins VPN erlauben", + "server.forwarding_section": "Forwarding und NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Nur bei Verwendung einer Policy-Routing-Tabelle erforderlich.", + "server.install_success": "WireGuard erfolgreich installiert.", + "server.install_wireguard": "WireGuard installieren", + "server.install_wireguard_help": "Führt apt update aus und installiert WireGuard sowie benötigte Netzwerktools.", + "server.install_wireguard_title": "WireGuard installieren", + "server.installing": "WireGuard wird installiert… Kann eine Minute dauern.", + "server.interface": "Schnittstelle", + "server.interface_hint": "WGTools verwaltet derzeit diese Schnittstelle.", + "server.interface_name": "Schnittstelle", + "server.interface_section": "WireGuard-Schnittstelle", + "server.ip_forwarding": "IPv4-Forwarding", + "server.kind": "Art", + "server.listen_port": "Listen-Port", + "server.local_network": "Lokales Netz", + "server.local_network_hint": "Optionale Route zur Policy-Tabelle hinzufügen.", + "server.managed_automatically": "Automatisch verwaltet", + "server.nat": "NAT / Masquerade", + "server.network": "Netzwerk", + "server.network_settings": "Netzwerk und NAT", + "server.no_firewall": "Keine Firewall-Regeln gefunden", + "server.no_routes": "Keine Routen gefunden", + "server.not_configured": "Nicht konfiguriert", + "server.not_set": "Nicht gesetzt", + "server.policy_disabled_hint": "Für normales System-Routing deaktivieren. Nur aktivieren, wenn dieses VPN eine eigene quellbasierte Routing-Tabelle benötigt.", + "server.policy_enabled": "Policy-Routing aktivieren", + "server.policy_table": "Policy-Tabelle", + "server.policy_table_hint": "Für normales Routing leer lassen; für quellbasiertes Policy-Routing z. B. 200 verwenden.", + "server.port_word": "Port", + "server.private_hidden": "Konfiguriert (ausgeblendet)", + "server.private_key": "Privater Schlüssel", + "server.protocol": "Protokoll", + "server.route_apply_confirm": "Diese Route speichern und anwenden? WireGuard wird kurz neu gestartet und ein Backup erstellt.", + "server.route_custom": "Benutzerdefiniert", + "server.route_deleted": "Route gelöscht.", + "server.route_device_hint": "Optionale Ausgabeschnittstelle, z. B. wg0 oder enp6s18.", + "server.route_editor_help": "Route hinzufügen, die beim WireGuard-Start erstellt und beim Stoppen entfernt wird.", + "server.route_gateway_hint": "Optionales Next-Hop-Gateway. Gateway oder Schnittstelle ist erforderlich.", + "server.route_managed_peer": "Site-to-site-Peer", + "server.route_managed_server": "Servereinstellung", + "server.route_network_hint": "IPv4-Netz, z. B. 10.20.0.0/24, oder 'default'.", + "server.route_saved": "Route gespeichert und angewendet.", + "server.route_table_hint": "Für normales Routing 'main' oder eine numerische Tabelle wie 200 verwenden.", + "server.route_type": "Typ", + "server.routes": "Erkannte Routen", + "server.routes_subtitle": "Aus PostUp/PostDown und aktuellem Policy-Routing gelesene Routen.", + "server.routes_subtitle_v08": "Server-, Site-to-site- und eigene Routen der ausgewählten Schnittstelle. Eigene Routen können hier erstellt, bearbeitet und entfernt werden.", + "server.routing": "Routing", + "server.routing_section": "Routing", + "server.rule": "Regel", + "server.rule_access": "Zugriffsregel", + "server.rule_advanced": "Erweitert", + "server.rule_apply_warning": "Beim Anwenden einer Route oder Firewall-Regel wird WireGuard kurz neu gestartet. WGTools erstellt ein Backup und stellt die vorherige Konfiguration bei Startfehlern automatisch wieder her.", + "server.rule_client_exception": "Ausnahme für Client", + "server.rule_client_policy": "Client-Regel", + "server.rule_managed_server": "Servereinstellung", + "server.rule_type": "Typ", + "server.run_diagnostics": "Diagnose starten", + "server.save_apply": "Speichern und anwenden", + "server.save_config": "SaveConfig", + "server.server_address": "Server-VPN-Adresse", + "server.server_address_hint": "Gewöhnlich die erste nutzbare Adresse im VPN-Netz.", + "server.settings_applied": "Servereinstellungen erfolgreich gespeichert und angewendet.", + "server.settings_apply_failed": "Servereinstellungen konnten nicht angewendet werden", + "server.setup_required": "Einrichtung erforderlich", + "server.source": "Quelle", + "server.source_hint": "Leer = beliebig. IP, CIDR oder Bereich wie 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installation, Ersteinrichtung und aktuelle Konfiguration des WireGuard-Servers.", + "server.tab_config": "Konfiguration", + "server.tab_interface": "Schnittstelle", + "server.tab_routing": "Routing", + "server.tab_vps": "VPS", + "server.table": "Tabelle", + "server.tabs_aria": "Abschnitte der Servereinstellungen", + "server.title": "Server", + "server.uplink": "Uplink-Schnittstelle", + "server.use_raw_editor": "Rohkonfigurationseditor verwenden", + "server.via": "Über / Gerät", + "server.via_word": "via", + "server.vpn_network": "VPN-Netzwerk", + "server.vpn_network_hint": "Client-Adressen werden später aus diesem Netz vergeben.", + "server.vpn_pool": "VPN-Adresspool", + "server.wg_not_installed": "WireGuard ist nicht installiert", + "server.wg_not_installed_subtitle": "WGTools kann die benötigten Debian-Pakete automatisch installieren.", + "server.what_happens": "Was WGTools ausführt", + "settings.about": "Über", + "settings.add_user": "Benutzer hinzufügen", + "settings.advanced": "Erweitert", + "settings.advanced_subtitle": "Direkter Zugriff auf erweiterte WireGuard-Konfiguration.", + "settings.appearance": "Darstellung", + "settings.applying_config": "Konfiguration wird geprüft, Backup erstellt und angewendet…", + "settings.backup_count": "Gespeicherte Backups", + "settings.backup_retention": "Anzahl aufzubewahrender Backups", + "settings.backup_retention_help": "Alte automatische Backups werden nach Erstellung eines neuen Backups entfernt. 1–200 Dateien.", + "settings.backups": "Konfigurations-Backups", + "settings.backups_always_on": "Aktiviert", + "settings.backups_subtitle": "WGTools erstellt vor Änderungen an der Konfiguration automatisch ein Backup. Automatische Backups können nicht deaktiviert werden.", + "settings.change_password": "Passwort ändern", + "settings.check_updates": "Auf Updates prüfen", + "settings.config_applied": "Konfiguration erfolgreich gespeichert und angewendet.", + "settings.config_applied_restarted": "Konfiguration angewendet, WireGuard neu gestartet.", + "settings.config_applied_stopped": "Konfiguration gespeichert. WireGuard war gestoppt und bleibt gestoppt.", + "settings.config_apply_failed": "Konfiguration konnte nicht angewendet werden", + "settings.config_load_failed": "Konfiguration konnte nicht geladen werden", + "settings.current_user": "Aktueller Benutzer", + "settings.current_version": "Aktuelle Version", + "settings.audit_action": "Aktion", + "settings.audit_empty": "Noch keine Audit-Ereignisse", + "settings.audit_log": "Audit-Protokoll", + "settings.audit_log_subtitle": "Aktionen im Panel, Anmeldungen, Telegram und WireGuard-Verbindungsverlauf. Geheimnisse werden hier nie protokolliert.", + "settings.audit_object": "Objekt", + "settings.audit_result": "Ergebnis", + "settings.audit_retention_note": "Aufbewahrung: 30 Tage", + "settings.audit_search": "Schnellsuche", + "settings.audit_search_clear": "Suche löschen", + "settings.audit_search_empty": "Keine passenden Audit-Ereignisse", + "settings.audit_time": "Datum / Uhrzeit", + "settings.audit_user": "Benutzer", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Zugriffsregel erstellt", + "audit.action.access_rule.deleted": "Zugriffsregel gelöscht", + "audit.action.access_rule.updated": "Zugriffsregel geändert", + "audit.action.auth.first_user_created": "Erster Benutzer erstellt", + "audit.action.auth.login": "Angemeldet", + "audit.action.auth.login_failed": "Anmeldung fehlgeschlagen", + "audit.action.auth.logout": "Abgemeldet", + "audit.action.backup.full_created": "Vollständiges Backup erstellt", + "audit.action.backup.full_restored": "Vollständiges Backup wiederhergestellt", + "audit.action.client.config_downloaded": "Client-Konfiguration heruntergeladen", + "audit.action.client.config_viewed": "Client-Konfiguration angezeigt", + "audit.action.client.created": "Client erstellt", + "audit.action.client.deleted": "Client gelöscht", + "audit.action.client.qr_viewed": "Client-QR-Code angezeigt", + "audit.action.client.updated": "Client aktualisiert", + "audit.action.client_group.created": "Client-Gruppe erstellt", + "audit.action.client_group.deleted": "Client-Gruppe gelöscht", + "audit.action.client_group.updated": "Client-Gruppe aktualisiert", + "audit.action.interface.created": "Schnittstelle erstellt", + "audit.action.interface.deleted": "Schnittstelle gelöscht", + "audit.action.interface.renamed": "Schnittstelle umbenannt", + "audit.action.route.created": "Route erstellt", + "audit.action.route.deleted": "Route gelöscht", + "audit.action.route.updated": "Route aktualisiert", + "audit.action.server.created": "Server erstellt", + "audit.action.server.raw_config_applied": "Rohkonfiguration angewendet", + "audit.action.server.settings_applied": "Servereinstellungen angewendet", + "audit.action.settings.updated": "Panel-Einstellungen geändert", + "audit.action.telegram.action_denied": "Telegram-Aktion verweigert", + "audit.action.telegram.action_failed": "Telegram-Aktion fehlgeschlagen", + "audit.action.telegram.connection_test": "Telegram-Verbindungstest", + "audit.action.telegram.settings_updated": "Telegram-Einstellungen geändert", + "audit.action.update.checked": "Auf Update geprüft", + "audit.action.update.scheduled": "Update geplant", + "audit.action.update.backup_created": "Backup vor Update", + "audit.action.update.completed": "Update abgeschlossen", + "audit.action.update.failed": "Update fehlgeschlagen", + "audit.action.update.rollback_completed": "Vorherige Version wiederhergestellt", + "audit.action.update.rollback_failed": "Update-Rollback fehlgeschlagen", + "audit.action.user.created": "Benutzer erstellt", + "audit.action.user.deleted": "Benutzer gelöscht", + "audit.action.user.password_changed": "Benutzerpasswort geändert", + "audit.action.vps.candidate_deleted": "VPS-Kandidat gelöscht", + "audit.action.vps.candidate_saved": "VPS-Kandidat gespeichert", + "audit.action.vps.detached": "VPS-Relay getrennt", + "audit.action.vps.relay_installed": "VPS-Relay installiert", + "audit.action.wireguard.client_connected": "WireGuard-Client verbunden", + "audit.action.wireguard.installed": "WireGuard installiert", + "audit.action.wireguard.restarted": "WireGuard neu gestartet", + "audit.action.wireguard.started": "WireGuard gestartet", + "audit.action.wireguard.stopped": "WireGuard gestoppt", + "audit.result.applied": "angewendet", + "audit.result.available": "verfügbar", + "audit.result.changed": "geändert", + "audit.result.created": "erstellt", + "audit.result.current": "aktuell", + "audit.result.deleted": "gelöscht", + "audit.result.detached": "getrennt", + "audit.result.denied": "verweigert", + "audit.result.downloaded": "heruntergeladen", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Fehler", + "audit.result.installed": "installiert", + "audit.result.invalid_credentials": "ungültige Zugangsdaten", + "audit.result.ok": "OK", + "audit.result.queued": "in Warteschlange", + "audit.result.restarted": "neu gestartet", + "audit.result.restored": "wiederhergestellt", + "audit.result.rotated": "erneuert", + "audit.result.saved": "gespeichert", + "audit.result.shown": "angezeigt", + "audit.result.started": "gestartet", + "audit.result.stopped": "gestoppt", + "audit.result.updated": "aktualisiert", + "settings.delete_user": "Löschen", + "settings.delete_user_confirm": "Benutzer {name} löschen?", + "settings.edit_raw_config": "Schnittstellenkonfiguration bearbeiten", + "settings.expert_mode": "Experte", + "settings.full_backup_component_clients": "Von WGTools verwaltete Client-Metadaten, private Schlüssel, PSKs, Ablaufzeiten und Gruppenzuordnungen zur Wiederherstellung von Konfigurationen/QR-Codes.", + "settings.full_backup_component_db": "WGTools-Datenbank: Benutzer, App-Einstellungen, E-Mail/SMTP, Telegram und gespeicherter VPS-Relay-Status.", + "settings.full_backup_component_relay": "VPS-Relay-Wiederherstellungsdaten: Controller-/Tenant-IDs, Verwaltungstoken und Home-Transportschlüssel. Danach kann WGTools den lokalen Transport wieder aufbauen und sich mit dem bestehenden VPS-Tenant verbinden.", + "settings.full_backup_component_system": "WGTools-sysctl-Datei für IPv4-Forwarding, Anzeigenamen der Schnittstellen sowie Gruppenregeln und Standardvorlagen (falls vorhanden). Der automatische Konfigurationsverlauf je Schnittstelle ist absichtlich ausgeschlossen.", + "settings.full_backup_component_wg": "Alle erkannten WireGuard-Schnittstellenkonfigurationen aus /etc/wireguard/ samt Status (gestartet/gestoppt).", + "settings.full_backup_create_failed": "Vollständiges Backup konnte nicht erstellt werden", + "settings.full_backup_creating": "Vollständiges Backup wird erstellt…", + "settings.full_backup_download": "Erstellen", + "settings.full_backup_downloaded": "Backup erstellt und heruntergeladen. Sicher aufbewahren.", + "settings.full_backup_downloaded_short": "Vollständiges Backup heruntergeladen.", + "settings.full_backup_help": "Erstellt ein übertragbares WGTools-Backup für Umzug oder Notfall. Enthält WireGuard-Konfigurationen, Benutzer, Einstellungen, Gruppen, verwaltete Clients und Daten zum Wiederverbinden bestehender VPS-Relay-Tenants.", + "settings.full_backup_no_file": "Kein Backup ausgewählt", + "settings.full_backup_restore": "Wiederherstellen", + "settings.full_backup_restore_confirm": "Vollständiges WGTools-Backup wiederherstellen? Aktuelle Benutzer, Einstellungen, verwaltete Clients und alle im Backup enthaltenen WireGuard-Konfigurationen werden ersetzt. Schnittstellen können neu starten. WGTools erstellt vorher ein Sicherheitsbackup und stellt bei Fehlern den vorherigen Zustand wieder her.", + "settings.full_backup_restore_failed": "Wiederherstellung fehlgeschlagen", + "settings.full_backup_restored": "Backup erfolgreich wiederhergestellt. Melde dich mit einem Konto aus dem Backup an.", + "settings.full_backup_restored_short": "Backup wiederhergestellt.", + "settings.full_backup_restoring": "Backup wird geprüft, Sicherheitskopie erstellt und wiederhergestellt…", + "settings.full_backup_secret_warning": "Diese Datei enthält geheime Daten: private WireGuard- und Client-Schlüssel, PSKs, WGTools-Passworthashes, Telegram-Bot-Token und gespeichertes SMTP-Passwort. Wie ein Passwort schützen und niemals an öffentliche Issues oder Chats anhängen.", + "settings.full_backup_select": "Auswählen", + "settings.full_backup_title": "Vollständiges Backup und Wiederherstellung", + "settings.full_mode": "Server- und Client-Verwaltung aktiviert", + "settings.interface_help": "Die verwaltete WireGuard-Schnittstelle wird bei der WGTools-Installation ausgewählt.", + "settings.language": "Sprache", + "settings.last_backup": "Letztes Backup", + "settings.latest_version": "Neueste Version", + "settings.loading_config": "Konfiguration wird geladen…", + "settings.mode": "Modus", + "settings.never_logged_in": "Nie", + "settings.new_password": "Neues Passwort", + "settings.no_backups": "Noch keine Backups", + "settings.online_help": "Ein Peer gilt als online, wenn sein letzter Handshake jünger als dieser Wert ist. 30–3600 Sekunden.", + "settings.online_threshold": "Online-Schwelle", + "settings.open_release": "Release öffnen", + "settings.password_changed": "Passwort geändert.", + "settings.passwords_mismatch": "Passwörter stimmen nicht überein.", + "settings.project_github": "Projekt / GitHub", + "settings.raw_config_confirm": "WireGuard-Konfiguration speichern und anwenden? Die ausgewählte Schnittstelle wird neu gestartet. Zuvor wird ein Backup erstellt. Bei Startfehlern stellt WGTools den vorherigen Zustand automatisch wieder her.", + "settings.raw_config_help": "Quellkonfiguration der ausgewählten WireGuard-Schnittstelle öffnen.", + "settings.raw_config_title": "WireGuard-Rohkonfiguration", + "settings.raw_config_warning": "Expertenmodus: Dies ist die echte WireGuard-Serverkonfiguration einschließlich privatem Server-Schlüssel und Peer-PSKs. Speichern und Anwenden startet die Schnittstelle neu. WGTools erstellt vorher ein Backup und stellt bei Startfehlern automatisch wieder her.", + "settings.readonly_mode": "Client-Verwaltung aktiviert", + "settings.refresh_help": "Intervall der Live-Statusabfrage durch WGTools. 2–60 Sekunden.", + "settings.refresh_interval": "Aktualisierungsintervall", + "settings.release_notes": "Versionshinweise", + "settings.reload_config": "Von Datenträger neu laden", + "settings.save_apply": "Speichern und anwenden", + "settings.saved": "Einstellungen gespeichert.", + "settings.saved_reload": "Einstellungen gespeichert. Seite wird neu geladen…", + "settings.saving": "Einstellungen werden gespeichert…", + "settings.status": "Statusaktualisierung", + "settings.status_help": "Aktualisierungsintervall für Dashboard und Peer-Status.", + "settings.subtitle": "WGTools-Oberfläche und Status-Einstellungen.", + "settings.syntax_hint": "WireGuard-Abschnitte, Schlüssel, Werte und Kommentare werden beim Bearbeiten hervorgehoben.", + "settings.tab_about": "Über", + "settings.tab_backups": "Backups", + "settings.tab_general": "Allgemein", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Benutzer", + "settings.tabs_aria": "Einstellungsbereiche", + "settings.telegram": "Telegram-Bot", + "settings.telegram_allowed_ids": "Zugelassene Telegram-Benutzer-IDs", + "settings.telegram_allowed_ids_help": "Eine numerische Benutzer-ID pro Zeile. Ein nicht autorisierter /start-Aufruf zeigt die Telegram-ID des Absenders, die du hier hinzufügen kannst.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Verbunden", + "settings.telegram_disabled": "Deaktiviert", + "settings.telegram_dns": "Standard-Client-DNS", + "settings.telegram_dns_help": "Optionale IPv4-DNS-Adressen, durch Komma getrennt. Für vom Bot erstellte Clients.", + "settings.telegram_enabled": "Telegram-Bot aktivieren", + "settings.telegram_endpoint": "Standard-Serveradresse / Domain", + "settings.telegram_endpoint_help": "Für neue Client-Konfigurationen des Bots. Nur IP oder Domain eingeben; WireGuard-Port wird aus der Serverkonfiguration gelesen.", + "settings.telegram_language": "Bot-Sprache", + "settings.telegram_language_auto": "Automatisch (Telegram-Sprache)", + "settings.telegram_last_poll": "Letzter Telegram-Kontakt", + "settings.telegram_not_configured": "Nicht konfiguriert", + "settings.telegram_remove_token": "Token entfernen", + "settings.telegram_remove_token_confirm": "Gespeicherten Telegram-Bot-Token entfernen und Bot deaktivieren?", + "settings.telegram_save": "Telegram-Einstellungen speichern", + "settings.telegram_saved": "Telegram-Einstellungen gespeichert.", + "settings.telegram_setup_note": "Bot mit @BotFather erstellen, Token speichern, Bot aktivieren und /start senden. Falls deine Benutzer-ID nicht autorisiert ist, zeigt WGTools sie an — füge sie zur Liste zugelassener Telegram-IDs hinzu.", + "settings.telegram_status": "Bot-Status", + "settings.telegram_subtitle": "WireGuard-Verwaltung über Telegram: Serverstatus, Clients, Erstellen/Löschen und Start/Neustart/Stopp.", + "settings.telegram_test": "Verbindung testen", + "settings.telegram_test_ok": "Telegram-Verbindung funktioniert: @{username}", + "settings.telegram_test_recent_ok": "Telegram-Bot funktioniert. Direkte Prüfung hat Zeitlimit überschritten, aber Bot hat Telegram kürzlich erreicht.", + "settings.telegram_token": "Bot-Token", + "settings.telegram_token_help": "Bot mit @BotFather erstellen und Bot-API-Token hier einfügen. API ID und API Hash sind für die Telegram Bot API nicht nötig.", + "settings.telegram_token_keep": "Leer lassen, um gespeicherten Token zu behalten.", + "settings.telegram_waiting": "Konfiguriert, wartet auf Bot-Dienst", + "settings.theme": "Darstellung", + "settings.theme_dark": "Dunkel", + "settings.theme_light": "Hell", + "settings.theme_system": "System", + "settings.title": "Einstellungen", + "settings.update_available": "Update verfügbar", + "settings.update_backup_queued": "Update vorgemerkt. WGTools erstellt vor Installation automatisch ein vollständiges Backup…", + "settings.update_backup_running": "Vollständiges Backup vor Update wird erstellt…", + "settings.update_check_failed": "Prüfung auf Updates fehlgeschlagen", + "settings.update_checking": "Neueste veröffentlichte GitHub Release wird geprüft…", + "settings.update_confirm": "WGTools von v{current} auf v{latest} aktualisieren? Zuvor werden ein vollständiges Backup und eine Rollback-Kopie erstellt. Die Weboberfläche wird kurz neu gestartet.", + "settings.update_current": "Aktuell", + "settings.update_downloading": "GitHub-Release wird heruntergeladen und geprüft…", + "settings.update_failed": "WGTools-Update fehlgeschlagen.", + "settings.update_installing": "Update wird installiert. Die Weboberfläche kann kurz nicht erreichbar sein…", + "settings.update_no_update": "WGTools ist bereits auf dem neuesten Stand.", + "settings.update_not_checked": "Nicht geprüft", + "settings.update_queued": "Update vorgemerkt. Warte auf den Update-Dienst…", + "settings.update_rollback_ok": "Vorherige WGTools-Version wurde automatisch wiederhergestellt.", + "settings.update_rolling_back": "Update fehlgeschlagen. Vorherige WGTools-Version wird wiederhergestellt…", + "settings.update_running": "Sicherheits-Backups werden erstellt…", + "settings.update_safety_hint": "Updates erfolgen nur auf Wunsch. WGTools erstellt vor der Installation ein vollständiges Backup und eine Rollback-Kopie. Bei Fehlern wird die vorherige Anwendung automatisch wiederhergestellt. WireGuard selbst wird nur neu gestartet, wenn das neue Release ausdrücklich seine Konfiguration ändert.", + "settings.update_sidebar": "Neue Version verfügbar", + "settings.update_sidebar_hint": "Einstellungen → Über", + "settings.update_starting": "Update wird gestartet…", + "settings.update_status_unknown": "Update-Status nicht verfügbar. Neuer Versuch…", + "settings.update_subtitle": "Projektinformationen, automatische Release-Prüfung und sichere Updates über GitHub Releases.", + "settings.update_success": "WGTools erfolgreich auf v{version} aktualisiert. Seite wird neu geladen…", + "settings.update_wgtools": "WGTools aktualisieren", + "settings.user_actions": "Aktionen", + "settings.user_created": "Erstellt", + "settings.user_created_ok": "Benutzer erstellt.", + "settings.user_deleted": "Benutzer gelöscht.", + "settings.user_equal_rights": "Alle WGTools-Benutzer haben dieselben Berechtigungen.", + "settings.user_last_login": "Letzte Anmeldung", + "settings.user_name": "Benutzername", + "settings.users": "Benutzer", + "settings.users_subtitle": "Lokale WGTools-Konten. E-Mail ist optional und wird bei aktivierter E-Mail-Funktion nur für Passwortwiederherstellung genutzt.", + "vps.add": "VPS hinzufügen", + "vps.add_help": "WGTools prüft oder installiert Relay per SSH. Passwörter und private SSH-Schlüssel werden nie gespeichert.", + "vps.add_title": "VPS hinzufügen", + "vps.agent": "Relay-Agent", + "vps.agent_found": "Bereits installiert", + "vps.agent_will_install": "Wird installiert", + "vps.arch": "Architektur", + "vps.auth_method": "Authentifizierung", + "vps.authentication": "SSH-Authentifizierung", + "vps.check": "VPS prüfen", + "vps.check_failed": "VPS-Prüfung fehlgeschlagen", + "vps.check_link": "Verbindung prüfen", + "vps.check_ok": "VPS ist kompatibel", + "vps.checking": "SSH-Zugang und VPS-Kompatibilität werden geprüft…", + "vps.connections": "Verbindungen", + "vps.credentials_not_saved": "Nur für diese Prüfung verwendet und nicht von WGTools gespeichert.", + "vps.delete_candidate": "Entfernen", + "vps.delete_installed": "VPS entfernen", + "vps.delete_installed_confirm": "„{name}“ aus WGTools entfernen? Der lokale Relay-Transport wird getrennt, aber Relay-Agent und Tenant bleiben auf dem VPS erhalten. Wenn du den VPS erneut hinzufügst, verbindet sich WGTools mit dem bestehenden Relay, statt einen neuen zu erstellen. Clients dieses Relay können bis zur Wiederverbindung nicht darauf zugreifen.", + "vps.delete_installed_failed": "VPS konnte nicht aus WGTools entfernt werden", + "vps.delete_installed_ok": "VPS aus WGTools entfernt. Remote-Relay bleibt erhalten und kann wiederverbunden werden.", + "vps.empty_help": "Füge einen Debian- oder Ubuntu-VPS hinzu, um SSH-Zugang, Systemkompatibilität und erforderliche UDP-Ports zu prüfen.", + "vps.empty_title": "Kein VPS eingerichtet", + "vps.endpoint": "Öffentlicher Endpoint", + "vps.endpoint_domain": "Domain (empfohlen)", + "vps.endpoint_domain_hint": "Wenn du später den Haupt-VPS austauschst, können Client-Konfigurationen durch eine DNS-Änderung unverändert bleiben.", + "vps.health_failed": "Relay-Verbindungsprüfung fehlgeschlagen", + "vps.host": "IP / Hostname", + "vps.host_key": "SSH-Hostschlüssel", + "vps.identity": "VPS-Verbindung", + "vps.install_failed": "Relay-Installation fehlgeschlagen", + "vps.install_ok": "Relay installiert und geschützte Verwaltungsverbindung geprüft", + "vps.install_relay": "Relay installieren", + "vps.install_title": "VPS-Relay installieren", + "vps.installed": "Installiert", + "vps.installing": "Relay-Agent wird installiert und geschützter Transporttunnel aufgebaut…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Schlüssel-Passphrase", + "vps.link_ok": "Relay-Verbindung OK", + "vps.multi_tenant_note": "Auf diesem VPS läuft bereits ein WGTools-Relay-Agent. Er wird nicht ersetzt: Dieses WGTools erhält eine eigene isolierte Verbindung mit eigenen Schlüsseln und UDP-Ports.", + "vps.name": "Name", + "vps.no_domain": "IP-Endpoint", + "vps.not_installed": "Wird installiert", + "vps.os": "Betriebssystem", + "vps.password": "Passwort", + "vps.phase_note": "Relay-Agent unterstützt mehrere unabhängige WGTools-Controller auf einem VPS. Jeder Controller erhält isolierte Verbindung, Schlüssel und UDP-Ports; bestehende Verbindungen bleiben unberührt.", + "vps.port_pair": "UDP-Ports", + "vps.ports_adjusted": "freie Ports ausgewählt", + "vps.private_key": "Privater Schlüssel", + "vps.privilege": "Berechtigungen", + "vps.public_endpoint": "Künftiger öffentlicher Endpoint", + "vps.ready_help": "SSH-Zugangsdaten werden nur für Kompatibilitätsprüfung und direkte Relay-Installation verwendet; sie werden nicht gespeichert.", + "vps.reconnect_note": "Auf diesem VPS wurde eine bestehende Relay-Verbindung dieses WGTools gefunden. WGTools verbindet sich mit demselben Tenant; neue Tenants oder UDP-Ports werden nicht erstellt.", + "vps.reconnect_ok": "Bestehenden Relay erfolgreich wiederverbunden", + "vps.reconnect_relay": "Relay wiederverbinden", + "vps.relay_port": "Relay-UDP-Port", + "vps.remove_confirm": "Diesen VPS-Kandidaten entfernen? Es wurden keine Remote-Änderungen vorgenommen.", + "vps.save_candidate": "Kandidaten speichern", + "vps.saved": "VPS-Kandidat gespeichert", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH-Schlüssel", + "vps.ssh_port": "SSH-Port", + "vps.ssh_user": "SSH-Benutzer", + "vps.status_candidate": "Bereit zur Installation", + "vps.status_installed": "Relay verbunden", + "vps.subtitle": "Öffentlichen VPS für Remote-Zugriff vorbereiten, wenn dieser WGTools-Server keine öffentliche IP hat.", + "vps.tenant": "Verbindung", + "vps.title": "VPS-Relay", + "vps.transport_port": "Transport-UDP-Port", + "vps.transport_port_hint": "Separater UDP-Port für privaten Home-↔-VPS-Transporttunnel.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Gespeichert", + "vps.active_short": "Aktiv", + "dashboard.traffic_reset": "Zurücksetzen", + "dashboard.traffic_reset_confirm": "Aufgelaufene WireGuard-Traffic-Zähler dieser Schnittstelle zurücksetzen? Auch die Client-Zähler beginnen bei null.", + "dashboard.traffic_reset_done": "Traffic-Zähler zurückgesetzt", + "dashboard.traffic_reset_failed": "Traffic-Zähler konnten nicht zurückgesetzt werden", + "audit.action.traffic.reset": "Traffic-Zähler zurückgesetzt", + "audit.result.reset": "zurückgesetzt", + "server.mtu": "MTU", + "server.mtu_auto": "Automatisch", + "server.mtu_hint": "Optional. Für automatische MTU durch wg-quick leer lassen. Nur bei Bedarf, z. B. LTE oder PPPoE, 1380 oder 1420 einstellen.", + "clients.peer_isolation": "VPN-Client-Isolation", + "clients.peer_isolation_enable": "Von anderen VPN-Clients isolieren", + "clients.peer_isolation_hint": "Blockiert den Verkehr zwischen diesem Client und anderen Adressen im WireGuard-Pool. Der Zugriff auf Server, Internet, lokale und Site-to-site-Netze wird weiterhin durch andere Regeln gesteuert.", + "clients.credentials_rotate": "Client-Schlüssel", + "clients.credentials_rotate_button": "Schlüssel erneuern", + "clients.credentials_rotate_confirm": "Neue Schlüssel für diesen Client erzeugen? Bei aktiver Verbindung wird seine WireGuard-Sitzung sofort getrennt. Anschließend neue Konfiguration oder QR übermitteln.", + "clients.credentials_rotate_confirm_psk": "Neues Schlüsselpaar und neuen PSK für diesen Client erzeugen? Bei aktiver Verbindung wird seine WireGuard-Sitzung sofort getrennt. Anschließend neue Konfiguration oder QR senden.", + "clients.credentials_rotate_hint": "Erneuert PrivateKey/PublicKey und bei aktiviertem PSK auch diesen. Adresse, Routen, Gruppe, Zeitplan, Isolation und gespeicherte Statistiken bleiben erhalten.", + "clients.credentials_rotating": "Neue Schlüssel werden erstellt, alte Sitzung getrennt…", + "clients.credentials_rotated": "Client-Schlüssel geändert. Die alte Sitzung wurde gegebenenfalls getrennt. Die alte Konfiguration funktioniert nicht mehr; sende vor dem nächsten Verbindungsaufbau neue Konfiguration oder QR.", + "clients.credentials_rotated_short": "Client-Schlüssel geändert — neue Konfiguration nötig", + "audit.action.client.credentials_rotated": "Client-Schlüssel erneuert", + "clients.credentials_connection_lost": "Verbindung zu WGTools unterbrochen. Falls dieses Panel über den Client mit gerade erneuerten Schlüsseln geöffnet war, ist das normal: seine alte WireGuard-Sitzung wurde sofort getrennt. Verbinde dich über einen anderen Weg und erstelle neue Konfiguration oder QR.", + "nav.navigation": "Hauptnavigation", + "nav.project_github": "WGTools auf GitHub", + "auth.email": "E-Mail", + "auth.email_optional_help": "Jetzt optional. Kann nach Einrichtung der E-Mail-Funktion zur Passwortwiederherstellung dienen.", + "auth.forgot_password": "Passwort vergessen?", + "auth.reset_title": "Passwort zurücksetzen", + "auth.reset_subtitle": "Einmalcode per E-Mail erhalten und neues WGTools-Passwort festlegen.", + "auth.reset_identifier": "Benutzername oder E-Mail", + "auth.reset_identifier_help": "Zum Schutz der Privatsphäre zeigt WGTools immer dieselbe Antwort, ob das Konto existiert oder nicht.", + "auth.send_reset_code": "Code senden", + "auth.reset_code_sent_generic": "Wenn das Konto existiert und eine E-Mail-Adresse hat, wurde ein Reset-Code gesendet. Er ist 15 Minuten gültig.", + "auth.reset_code": "6-stelliger Code", + "auth.set_new_password": "Neues Passwort festlegen", + "auth.request_another_code": "Neuen Code anfordern", + "auth.back_to_login": "Zur Anmeldung", + "auth.reset_not_configured": "E-Mail-Passwortwiederherstellung ist nicht eingerichtet. Wende dich an den WGTools-Administrator.", + "settings.tab_mail": "E-Mail", + "settings.mail": "E-Mail / SMTP", + "settings.mail_subtitle": "SMTP dient zur Passwortwiederherstellung.", + "settings.mail_not_configured": "Nicht konfiguriert", + "settings.mail_enabled": "E-Mail und Passwortwiederherstellung aktivieren", + "settings.mail_smtp_host": "SMTP-Server", + "settings.mail_smtp_port": "SMTP-Port", + "settings.mail_security": "Verschlüsselung", + "settings.mail_security_none": "Keine Verschlüsselung", + "settings.mail_username": "SMTP-Benutzername", + "settings.mail_username_help": "Für SMTP-Anmeldung und als Absender-E-Mail-Adresse verwendet.", + "settings.mail_password": "SMTP-Passwort", + "settings.mail_password_keep": "Leer lassen, um gespeichertes Passwort beizubehalten.", + "settings.mail_from_email": "Absender-E-Mail", + "settings.mail_from_name": "Absendername", + "settings.mail_test_recipient": "Testempfänger", + "settings.mail_test_recipient_help": "Der Test verwendet die aktuell gespeicherten SMTP-Einstellungen.", + "settings.mail_remove_password": "Passwort entfernen", + "settings.mail_test": "Test senden", + "settings.mail_save": "E-Mail-Einstellungen speichern", + "settings.mail_enabled_badge": "Aktiviert", + "settings.mail_disabled_badge": "Deaktiviert", + "settings.mail_saved": "E-Mail-Einstellungen gespeichert.", + "settings.mail_remove_password_confirm": "Gespeichertes SMTP-Passwort entfernen und E-Mail deaktivieren?", + "settings.mail_password_removed": "SMTP-Passwort entfernt und E-Mail deaktiviert.", + "settings.mail_test_recipient_required": "E-Mail-Adresse des Testempfängers eingeben.", + "settings.mail_testing": "Test-E-Mail wird gesendet…", + "settings.mail_test_ok": "Test-E-Mail erfolgreich gesendet.", + "settings.user_email": "E-Mail", + "settings.user_email_help": "Optional. Nur für eigenständige Passwortwiederherstellung nötig.", + "settings.change_email": "E-Mail", + "settings.user_email_saved": "E-Mail gespeichert.", + "settings.send_password_reset": "Reset senden", + "settings.user_reset_mail_not_configured": "Zuerst E-Mail einrichten und aktivieren.", + "settings.user_reset_email_missing": "Zuerst E-Mail-Adresse hinzufügen.", + "settings.user_reset_confirm": "Passwort-Reset-Code an {name} unter {email} senden?", + "settings.user_reset_sent": "Passwort-Reset-Code an {email} gesendet.", + "audit.action.auth.password_reset_requested": "Passwortzurücksetzung angefordert", + "audit.action.auth.password_reset_code_sent": "Passwort-Reset-Code gesendet", + "audit.action.auth.password_reset_completed": "Passwort zurückgesetzt", + "audit.action.auth.password_reset_failed": "Passwortzurücksetzung fehlgeschlagen", + "audit.action.mail.settings_updated": "E-Mail-Einstellungen geändert", + "audit.action.mail.test_sent": "Test-E-Mail gesendet", + "audit.action.mail.test_failed": "Test-E-Mail fehlgeschlagen", + "audit.action.user.email_changed": "Benutzer-E-Mail geändert", + "audit.action.user.password_reset_sent": "Passwort-Reset an Benutzer gesendet", + "audit.action.user.password_reset_failed": "Benutzer-Passwort-Reset fehlgeschlagen", + "audit.result.accepted": "angenommen", + "audit.result.sent": "gesendet", + "audit.result.invalid_code": "ungültiger Code", + "common.copy": "Kopieren", + "common.copied": "Kopiert", + "clients.use_panel_host": "Paneladresse verwenden", + "clients.use_panel_host_done": "Paneladresse eingefügt: {host}", + "clients.use_panel_host_failed": "Paneladresse konnte nicht aus der Browser-URL ermittelt werden.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Integriertes Let’s-Encrypt-HTTPS für direkten WGTools-Zugriff ohne Reverse-Proxy.", + "settings.https_disabled": "Deaktiviert", + "settings.https_enabled": "Aktiviert", + "settings.https_enable": "Integriertes HTTPS aktivieren", + "settings.https_type": "Zertifikat für", + "settings.https_domain": "Domain", + "settings.https_public_ip": "Öffentliche IP", + "settings.https_target": "Domain oder öffentliche IP", + "settings.https_email": "Let’s-Encrypt-E-Mail", + "settings.https_port": "HTTPS-Port", + "settings.https_port80_note": "TCP-Port 80 muss für die Ausstellung und Verlängerung des Zertifikats aus dem Internet erreichbar sein. Den gewählten HTTPS-Port für das Panel ebenfalls öffnen.", + "settings.https_check_ports": "Ports prüfen", + "settings.https_certificate": "Zertifikat", + "settings.https_certificate_ready": "Bereit", + "settings.https_certificate_missing": "Nicht ausgestellt", + "settings.https_expires": "Gültig bis", + "settings.https_renewal": "Automatische Verlängerung", + "settings.https_renewal_enabled": "Aktiviert", + "settings.https_renewal_disabled": "Deaktiviert", + "settings.https_certificate_path": "Zertifikat", + "settings.https_private_key_path": "Privater Schlüssel", + "settings.https_issue": "Zertifikat anfordern / erneuern", + "settings.https_port_free": "Frei", + "settings.https_port_busy": "Belegt", + "settings.https_ports_checked": "Portprüfung abgeschlossen.", + "settings.https_target_email_required": "Domain/öffentliche IP und Let’s-Encrypt-E-Mail eingeben.", + "settings.https_issue_confirm": "Let’s-Encrypt-Zertifikat für {target} anfordern oder erneuern? Die HTTPS-Einstellungen werden gespeichert. TCP-Port 80 muss aus dem Internet erreichbar sein.", + "settings.https_issuing": "Let’s-Encrypt-Zertifikat wird angefordert…", + "settings.https_issue_ok": "Zertifikat bereit.", + "settings.https_already_enabled": "Integriertes HTTPS ist bereits aktiviert.", + "settings.https_already_disabled": "Integriertes HTTPS ist bereits deaktiviert.", + "settings.https_enable_confirm": "Integriertes HTTPS auf TCP {port} mit Pfad {path} aktivieren? WGTools wird neu gestartet und die Seite unter der neuen Adresse wiederverbunden.", + "settings.https_disable_confirm": "Integriertes HTTPS deaktivieren und WGTools wieder über HTTP öffnen?", + "settings.https_switching": "HTTPS wird aktiviert und WGTools neu gestartet…", + "settings.https_switching_http": "HTTPS wird deaktiviert und WGTools neu gestartet…", + "audit.action.https.certificate_issued": "HTTPS-Zertifikat ausgestellt", + "audit.action.https.certificate_failed": "HTTPS-Zertifikatsanfrage fehlgeschlagen", + "audit.action.https.enabled": "HTTPS aktiviert", + "audit.action.https.disabled": "HTTPS deaktiviert", + "audit.result.issued": "ausgestellt", + "audit.result.enabled": "aktiviert", + "audit.result.disabled": "deaktiviert", + "settings.https_access_path": "Panel-Zugriffspfad", + "settings.https_access_path_help": "Eigenen Pfad wählen. Bei integriertem HTTPS erhalten Anfragen außerhalb dieses Pfads einen 404-Fehler.", + "settings.https_enable_fields_required": "Domain/öffentliche IP, Let’s-Encrypt-E-Mail und Panel-Pfad eingeben.", + "settings.https_use_panel_host": "Paneladresse verwenden", + "settings.https_reconnecting": "WGTools wechselt zur neuen HTTPS-Adresse…", + "server.tab_nodes": "Knoten", + "common.type": "Typ", + "common.status": "Status", + "common.copy_failed": "Kopieren fehlgeschlagen", + "clients.vpn_address": "VPN-Adresse", + "nodes.title": "WGTools Nodes", + "nodes.subtitle": "Mehrere WGTools-Server sicher verbinden und nur die Netze veröffentlichen, die andere Nodes erreichen dürfen.", + "nodes.enable_hub": "HUB aktivieren", + "nodes.connect_hub": "Mit HUB verbinden", + "nodes.settings": "Node-Einstellungen", + "nodes.settings_action": "Einstellungen", + "nodes.sync_now": "Synchronisieren", + "nodes.disable": "Nodes deaktivieren", + "nodes.disable_action": "Trennen", + "nodes.join_title": "Neue Nodes verbinden", + "nodes.join_help": "Einmalcode erzeugen und zusammen mit dem HUB-Service-Endpoint (z. B. vpn.example.com:51950) in einer anderen WGTools-Oberfläche eingeben. Der Code ist 15 Minuten gültig und einmal verwendbar.", + "nodes.create_code": "Code erstellen", + "nodes.connected_nodes": "Verbundene Nodes", + "nodes.connected_nodes_help": "Informationen zu anderen Panels, veröffentlichten Netzen und Clients. Remote-Clients sind schreibgeschützt.", + "nodes.enable_hub_help": "Dieses Panel wird zum zentralen Node. Über denselben Port akzeptiert HUB WireGuard per UDP und die geschützte Erstkopplung per TCP.", + "nodes.node_name": "Node-Name", + "nodes.transport_network": "Node-Transportnetz", + "nodes.transport_help": "Eigenes privates Netz nur für die WGTools-zu-WGTools-Verbindung. Darf sich nicht mit VPN-/LAN-Netzen überschneiden.", + "nodes.panel_url": "Panel-URL", + "nodes.panel_url_help": "Optional. Nur ein Informationslink für „Panel öffnen“ auf anderen Nodes; wird nie für die Node-Verbindung genutzt.", + "nodes.extra_networks": "Zusätzliche Node-Netze", + "nodes.extra_networks_help": "Ein Netz pro Zeile. VPN-Netze der Schnittstellen und Remote-Netze von Site-to-site-Clients werden automatisch veröffentlicht. Hier nur weitere geroutete LAN-/Netze ergänzen, z. B. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools trägt erkannte VPN-, Site-to-site- und lokale geroutete LAN-Netze ein. Behalte nur die Netze, die dieser Node veröffentlichen soll. Ein Netz pro Zeile.", + "nodes.published_networks_settings_help": "Ein Netz pro Zeile. Dies ist die explizite Liste der von diesem Node veröffentlichten Netze. Entfernen einer Zeile beendet die Ankündigung an andere Nodes.", + "nodes.available_networks_help": "Aktuell erkannt: {networks}. Neue Netze werden nicht automatisch veröffentlicht; füge gewünschte oben hinzu.", + "nodes.available_networks_none": "Zurzeit keine weiteren lokalen Netze erkannt.", + "nodes.connect_help": "HUB-Service-Endpoint und Einmalcode eingeben. Panel-URL, HTTPS-Port, Zertifikat und privater Pfad werden für die Nodes-Kopplung nicht verwendet.", + "nodes.join_code": "Code zum Verbinden", + "nodes.connect_reachability_note": "Die Erstkopplung erfolgt über geschütztes TCP auf dem angegebenen Port. Nach Erstellung von wgnode0 werden Netze, Status, Versionen und schreibgeschützte Client-Daten über die interne WireGuard-Adresse mit HUB synchronisiert.", + "nodes.connect": "Verbinden", + "nodes.settings_help": "Node-Name, optionaler Link „Panel öffnen“ und Liste veröffentlichter Netze. Panel-URL wird weder zur Kopplung noch zur Synchronisierung verwendet.", + "nodes.details": "Details", + "nodes.not_configured": "WGTools Nodes nicht eingerichtet", + "nodes.not_configured_help": "Aktiviere HUB auf diesem Panel oder verbinde es mit einem bestehenden WGTools-HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Mit HUB verbunden", + "nodes.mode_none": "Nicht konfiguriert", + "nodes.role": "Rolle", + "nodes.tunnel": "Node-Tunnel", + "nodes.node_ip": "Node-Adresse", + "nodes.endpoint": "HUB-Endpoint", + "nodes.published_networks": "Veröffentlichte Netze", + "nodes.last_sync": "Letzte Synchronisierung", + "nodes.no_nodes_hub": "Noch keine Nodes verbunden. Erstelle einen Verbindungscode und verwende ihn auf einem anderen WGTools-Panel.", + "nodes.no_nodes_spoke": "Noch keine Informationen zu anderen Nodes empfangen.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Panel öffnen", + "nodes.route_conflict": "Routenkonflikt", + "nodes.no_published_networks": "Keine veröffentlichten Netze", + "nodes.load_failed": "WGTools Nodes konnte nicht geladen werden", + "nodes.enable_hub_confirm": "WGTools HUB aktivieren und internen WireGuard-Node-Tunnel erstellen?", + "nodes.applying": "WGTools-Node-Tunnel wird eingerichtet…", + "nodes.enable_failed": "HUB konnte nicht aktiviert werden", + "nodes.hub_enabled": "WGTools HUB aktiviert", + "nodes.connecting": "HUB-Code wird geprüft und geschützter Node-Tunnel erstellt…", + "nodes.connect_failed": "Verbindung mit HUB fehlgeschlagen", + "nodes.connected": "Mit WGTools HUB verbunden", + "nodes.settings_failed": "Node-Einstellungen konnten nicht gespeichert werden", + "nodes.settings_saved": "Node-Einstellungen gespeichert", + "nodes.code_failed": "Verbindungscode konnte nicht erstellt werden", + "nodes.code_expires": "Einmalcode. Gültig bis {time}.", + "nodes.code_copied": "Verbindungscode kopiert", + "nodes.network_vpn": "VPN-Clients", + "nodes.network_site_to_site": "Site-to-site-Netz", + "nodes.network_custom": "Zusätzliches Netz", + "nodes.conflict": "Konflikt", + "nodes.remote_clients": "Clients (schreibgeschützt)", + "nodes.no_clients": "Dieser Node meldet keine Clients", + "nodes.details_failed": "Node-Details konnten nicht geladen werden", + "nodes.remove_confirm": "Node „{name}“ aus HUB entfernen? Sein Zugang zum internen Tunnel wird widerrufen.", + "nodes.remove_failed": "Node konnte nicht entfernt werden", + "nodes.removed": "Node entfernt", + "nodes.disable_hub_confirm": "HUB deaktivieren und alle WGTools Nodes trennen? Der interne Node-Tunnel wird entfernt.", + "nodes.disconnect_confirm": "Dieses WGTools-Panel vom HUB trennen und internen Node-Tunnel entfernen?", + "nodes.disable_failed": "WGTools Nodes konnte nicht deaktiviert werden", + "nodes.disabled": "WGTools Nodes deaktiviert", + "nodes.sync_failed": "Node-Synchronisierung fehlgeschlagen", + "nodes.synced": "Node-Informationen synchronisiert", + "nodes.service_port": "Nodes-Port", + "nodes.service_port_help": "Dieselbe Portnummer wird gleichzeitig genutzt: UDP für WireGuard und TCP für die geschützte Erstkopplung.", + "nodes.hub_port_forward_note": "Liegt HUB hinter NAT, leite denselben Port für UDP und TCP an ihn weiter. WGTools-Webport, HTTPS und privater Panel-Pfad gehören nicht zu Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Nodes-Domain/IP und Port ohne http:// oder https://, z. B. vpn.example.com:51950.", + "settings.collapse_sidebar": "Seitenleiste einklappen", + "settings.expand_sidebar": "Seitenleiste ausklappen", + "settings.https_issue_fields_required": "Domain/öffentliche IP, Let’s-Encrypt-E-Mail und Panel-Pfad eingeben.", + "settings.https_issue_ok_saved": "Zertifikat bereit und HTTPS-Einstellungen gespeichert.", + "settings.https_enable_need_certificate": "Zuerst ein Zertifikat anfordern.", + "settings.https_enable_certificate_mismatch": "Zuerst Zertifikat für die aktuelle Domain oder IP anfordern.", + "settings.https_enable_certificate_expired": "Zertifikat abgelaufen. Vor HTTPS-Aktivierung erneuern.", + "settings.https_enable_certificate_ready": "Zertifikat bereit — integriertes HTTPS kann aktiviert werden.", + "settings.https_enable_active_help": "Haken entfernen und speichern, um zu HTTP zurückzukehren.", + "settings.https_certificate_expired": "Abgelaufen", + "settings.https_certificate_wrong_target": "Für andere Adresse", + "nodes.network_conflict_error": "Veröffentlichte Netze überschneiden sich mit anderem Node oder dem Nodes-Transportnetz: {conflicts}. Entferne oder ändere das betroffene Netz.", + "nodes.networks_changed": "Erkannte Netze haben sich seit dem Speichern geändert. Neu: {added}. Nicht mehr erkannt: {removed}. Prüfe die veröffentlichte Liste und speichere nach Kontrolle.", + "nodes.review_networks": "Netze prüfen", + "nodes.vpn_pool_mismatch": "VPN-Pool geändert: Nodes veröffentlicht weiterhin {old}, aktuell ist {current}. Öffne die Node-Einstellungen und aktualisiere die veröffentlichten Netze.", + "server.error_vpn_network_invalid": "VPN-Netz muss ein gültiges IPv4-Netz sein, z. B. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Nur IPv4-VPN-Netze werden unterstützt.", + "server.error_vpn_network_too_small": "Das VPN-Netz muss mindestens zwei nutzbare Adressen enthalten.", + "server.error_vpn_network_no_hosts": "Das gewählte VPN-Netz hat keine nutzbaren Serveradressen.", + "server.error_server_address_prefix": "Server-VPN-Adresse muss ein Präfix enthalten, z. B. 10.0.0.1/24.", + "server.error_server_address_network": "Die Server-VPN-Adresse muss zum gewählten Adresspool gehören und das gleiche Präfix verwenden.", + "server.error_server_address_reserved": "Die Server-VPN-Adresse darf nicht die Netz- oder Broadcast-Adresse sein.", + "server.error_listen_port_number": "Der WireGuard-Port muss eine Zahl sein.", + "server.error_listen_port_range": "Der WireGuard-Port muss zwischen 1 und 65535 liegen.", + "server.error_mtu_number": "MTU muss eine Zahl sein.", + "auth.mfa_title": "Zwei-Faktor-Authentifizierung", + "auth.mfa_login_help": "Gib den sechsstelligen Code aus Google Authenticator oder einen Wiederherstellungscode ein.", + "auth.mfa_code": "Authentifizierungscode", + "auth.mfa_verify": "Prüfen und anmelden", + "auth.mfa_back": "Zurück zum Passwort", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Zwei-Faktor-Authentifizierung (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Aktiviert", + "settings.mfa_disabled": "Deaktiviert", + "settings.mfa_google_help": "Schütze dieses Konto mit Google Authenticator oder einer anderen TOTP-App. Für die Einrichtung ist dein aktuelles Passwort nötig.", + "settings.current_password": "Aktuelles Passwort", + "settings.mfa_start": "Google Authenticator einrichten", + "settings.mfa_secret": "Manueller Einrichtungsschlüssel", + "settings.mfa_scan_help": "QR-Code mit Google Authenticator scannen und aktuellen sechsstelligen Code eingeben, um MFA zu aktivieren.", + "settings.mfa_code": "6-stelliger Code", + "settings.mfa_enable": "MFA aktivieren", + "settings.mfa_manage_help": "Zum Ändern von MFA aktuelles Passwort und Google-Authenticator-Code oder Wiederherstellungscode eingeben.", + "settings.mfa_code_or_recovery": "Authenticator- oder Wiederherstellungscode", + "settings.mfa_regenerate": "Neue Wiederherstellungscodes", + "settings.mfa_disable": "MFA deaktivieren", + "settings.mfa_recovery_title": "Wiederherstellungscodes", + "settings.mfa_recovery_help": "Speichere diese Codes jetzt. Jeder kann einmalig genutzt werden, wenn Google Authenticator nicht verfügbar ist. Sie werden nicht erneut angezeigt.", + "settings.mfa_recovery_remaining": "Verbleibende Wiederherstellungscodes: {count}", + "settings.mfa_enabled_ok": "MFA aktiviert.", + "settings.mfa_disabled_ok": "MFA deaktiviert.", + "settings.mfa_disable_confirm": "Zwei-Faktor-Authentifizierung für dieses Konto deaktivieren?", + "settings.mfa_regenerate_confirm": "Alle bestehenden Wiederherstellungscodes ersetzen?", + "settings.mfa_recovery_regenerated": "Neue Wiederherstellungscodes erstellt.", + "audit.action.auth.mfa_failed": "MFA-Prüfung fehlgeschlagen", + "audit.action.auth.mfa_recovery_used": "MFA-Wiederherstellungscode verwendet", + "audit.action.user.mfa_setup_started": "MFA-Einrichtung begonnen", + "audit.action.user.mfa_enabled": "MFA aktiviert", + "audit.action.user.mfa_disabled": "MFA deaktiviert", + "audit.action.user.mfa_disabled_cli": "MFA über CLI deaktiviert", + "audit.action.user.mfa_recovery_regenerated": "MFA-Wiederherstellungscodes erneuert", + "settings.mfa_error_password": "Aktuelles Passwort ungültig.", + "settings.mfa_error_code": "Authentifizierungscode ungültig.", + "settings.mfa_error_already_enabled": "MFA ist bereits aktiviert.", + "settings.mfa_error_not_enabled": "MFA ist nicht aktiviert.", + "settings.mfa_error_not_started": "MFA-Einrichtung erneut beginnen.", + "trace.title": "Traceroute, Ping und Routenkarte", + "trace.subtitle": "Latenz zu einem VPS oder Server messen und Verzögerungen entlang der Route erkennen.", + "trace.target": "Server-IP oder Hostname", + "trace.show_map": "Route auf Karte zeigen", + "trace.run": "Traceroute starten", + "trace.geo_note": "Geolokalisierung ist ungenau. Bei aktivierter Karte werden öffentliche Hop-IPs zur Standortabfrage an ipwho.is gesendet; Kartenkacheln stammen von OpenStreetMap.", + "trace.latency_note": "Traceroute misst die Latenz in Millisekunden, nicht den Durchsatz in Mbit/s.", + "trace.map": "Routenkarte", + "trace.map_hint": "Interaktive Karte: ziehen zum Verschieben, Mausrad oder +/− zum Zoomen, Hop anklicken für Details.", + "trace.hop": "Hop / IP", + "trace.location": "Standort", + "trace.avg_rtt": "Ø RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Verlust", + "trace.summary_target": "Ziel", + "trace.summary_ping": "Durchschnittlicher Ping", + "trace.summary_loss": "Ping-Verlust", + "trace.summary_hops": "Hops", + "trace.no_reply": "Keine Antwort", + "trace.private": "Privates Netzwerk", + "trace.unknown": "Unbekannt", + "trace.running": "Ping und Traceroute laufen… Das kann bis zu einer Minute dauern.", + "trace.done": "Netzwerktrace abgeschlossen.", + "trace.failed": "Netzwerktrace fehlgeschlagen", + "trace.partial_geo": "Einige öffentliche Hops konnten nicht geolokalisiert werden.", + "trace.not_reached": "Ziel per Traceroute nicht erreicht.", + "trace.reached": "Ziel erreicht", + "trace.ms": "ms", + "server.tab_trace": "Routenverfolgung", + "trace.map_controls": "Kartensteuerung", + "trace.zoom_in": "Vergrößern", + "trace.zoom_out": "Verkleinern", + "trace.fit_route": "Gesamte Route anzeigen", + "trace.fit": "Anpassen", + "trace.map_click_hint": "Für IP, Standort, ASN und RTT auf einen Hop klicken.", + "trace.route_path": "Route", + "trace.ping_ok_trace_filtered": "Ziel antwortet auf Ping, die letzten Traceroute-Hops nicht.", + "trace.latency_legend": "Latenzanstieg zwischen antwortenden Hops", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — erhöht", + "trace.latency_bad": "Δ RTT > 20 ms — starker Sprung" +} diff --git a/app/static/en.json b/app/static/en.json new file mode 100644 index 0000000..0c385e2 --- /dev/null +++ b/app/static/en.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Create user", + "auth.login_subtitle": "Enter your WGTools username and password.", + "auth.login_title": "Sign in to WGTools", + "auth.password": "Password", + "auth.password_repeat": "Repeat password", + "auth.setup_help": "The first account has full WGTools access. Additional users can be created later in Settings.", + "auth.setup_subtitle": "WGTools requires an account before server management is available.", + "auth.setup_title": "Create the first user", + "auth.sign_in": "Sign in", + "auth.sign_out": "Sign out", + "auth.username": "Username", + "clients.actions": "Actions", + "clients.add": "+ Add client", + "clients.address": "VPN address", + "clients.address_hint": "The first free address is suggested automatically.", + "clients.allowed_ips_required": "Enter at least one AllowedIPs network for the client configuration.", + "clients.basic_connection": "Connection settings", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs in client config", + "clients.config_private_warning": "This configuration contains the client's private key. Store it securely.", + "clients.config_title": "Client configuration", + "clients.config_unavailable": "Configuration unavailable", + "clients.connection_direct": "Directly to WGTools", + "clients.connection_path": "Connection path", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Connect through", + "clients.connection_via_hint": "Choose the public entry point used by this client. Relay is shown only when one is installed for the selected WireGuard interface.", + "clients.copy_config": "Copy", + "clients.copy_done": "Configuration copied", + "clients.create_subtitle": "Create a WireGuard peer and generate its client configuration.", + "clients.create_title": "Create client", + "clients.creating": "Creating keys and applying client…", + "clients.day_fri": "Fri", + "clients.day_mon": "Mon", + "clients.day_sat": "Sat", + "clients.day_sun": "Sun", + "clients.day_thu": "Thu", + "clients.day_tue": "Tue", + "clients.day_wed": "Wed", + "clients.delete_confirm": "Delete this client from WireGuard? WGTools will create a backup and remove the automatically generated policy rules tied to this client.", + "clients.deleted": "Client deleted", + "clients.dns": "DNS (optional)", + "clients.dns_hint": "Comma-separated IPv4 DNS servers.", + "clients.download_config": "Download .conf", + "clients.duplicate": "Duplicate", + "clients.duplicate_address_error": "This VPN address is already used by another peer.", + "clients.duplicate_name_error": "A peer with this name already exists.", + "clients.duplicate_ready": "A copy is ready. WGTools assigned a new name and VPN address; review the settings before saving.", + "clients.duplicate_site_hint": "Remote networks were cleared to prevent duplicate routes. Enter the networks for the new Site-to-site peer.", + "clients.duplicate_suffix": "copy", + "clients.edit_subtitle": "Update the server-side peer. Changes are applied without restarting WireGuard.", + "clients.edit_title": "Edit client", + "clients.endpoint": "Server endpoint", + "clients.endpoint_hint": "For remote clients use the public IP/domain that forwards the WireGuard port to this server.", + "clients.existing": "Existing peer", + "clients.expiration": "Access lifetime", + "clients.expiration_action": "At expiration", + "clients.expiration_action_hint": "If unchecked, the client remains in WGTools but WireGuard access is disabled. Set a new lifetime or No expiration and save to restore access.", + "clients.expiration_datetime": "Expires at", + "clients.expiration_datetime_hint": "Uses the local date and time of this browser.", + "clients.expiration_delete": "Delete client", + "clients.expiration_future_required": "Choose a future expiration date and time.", + "clients.expiration_hint": "At expiration WGTools performs the selected action on the next minute boundary. A WireGuard config backup is created first.", + "clients.expire_1d": "1 day", + "clients.expire_1h": "1 hour", + "clients.expire_3h": "3 hours", + "clients.expire_6h": "6 hours", + "clients.expire_custom": "Custom date and time", + "clients.expire_never": "No expiration", + "clients.expired": "Expired", + "clients.expired_disabled_hint": "This access lifetime has expired. The client is kept, but WireGuard access is disabled. Choose a future lifetime or No expiration and save to restore access.", + "clients.expired_disabled_short": "Expired · disabled", + "clients.expired_disabled_status": "Expired", + "clients.expires_days": "Expires in {n}d", + "clients.expires_hours": "Expires in {n}h", + "clients.expires_minutes": "Expires in {n}m", + "clients.generated_config": "Generated client configuration", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 seconds is a good default for clients behind NAT.", + "clients.local_access_exceptions": "Allowed local addresses", + "clients.local_access_exceptions_hint": "Optional IPs or CIDRs that stay reachable even while their local or Site-to-site network is blocked. Separate values with commas.", + "clients.managed": "WGTools managed", + "clients.name": "Name", + "clients.no_peers": "No peers found", + "clients.peers": "Peers", + "clients.peers_subtitle": "Changes are backed up and applied with wg syncconf without restarting the WireGuard interface.", + "clients.protected_networks_reference": "Blocked local networks (reference)", + "clients.protected_networks_reference_hint": "These networks are not written to AllowedIPs. Access is blocked by the WGTools server policy; individual addresses can be allowed in the field above.", + "clients.psk": "Preshared key (PSK)", + "clients.psk_enable": "Use an additional WireGuard preshared key", + "clients.psk_hint": "Recommended. Adds an extra symmetric secret to the WireGuard handshake. Standard WireGuard clients support it; WGTools includes the PSK in the generated config and QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generating QR…", + "clients.quick_search": "Quick search", + "clients.quick_search_clear": "Clear search", + "clients.quick_search_empty": "No clients match the search", + "clients.relay_endpoint_note": "The generated client config will connect to {endpoint}. The WireGuard server itself remains on this WGTools host.", + "clients.relay_required": "Choose a VPS Relay for this client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "unavailable", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "The client Endpoint is generated automatically from this Relay.", + "clients.remote_hint": "Networks located behind this peer. One network per line or separated by commas.", + "clients.remote_networks": "Remote networks", + "clients.remote_required": "Enter at least one remote network for a Site-to-site peer.", + "clients.required": "Name and VPN address are required.", + "clients.route_custom": "Custom", + "clients.route_full": "Full tunnel", + "clients.route_full_except_local": "Full tunnel except local networks", + "clients.route_hint": "Only these networks are written to AllowedIPs in the generated client config.", + "clients.route_preset": "Traffic through VPN", + "clients.route_vpn": "VPN network only", + "clients.route_vpn_lan": "VPN + local LAN", + "clients.saved": "Client saved", + "clients.schedule_blocked_short": "Schedule · blocked", + "clients.schedule_blocked_status": "Blocked by schedule", + "clients.schedule_days": "Allowed days", + "clients.schedule_days_required": "Choose at least one day for the access schedule.", + "clients.schedule_disabled_hint": "This client is currently blocked by its access schedule. WGTools will restore the same peer automatically when the next allowed window begins.", + "clients.schedule_enable": "Limit access by schedule", + "clients.schedule_from": "Access from", + "clients.schedule_hint": "WGTools can automatically disable and restore this client on selected days and times without changing the client config.", + "clients.schedule_short": "Schedule", + "clients.schedule_time_required": "Set both start and end times for the access schedule.", + "clients.schedule_timezone_hint": "The schedule uses the WireGuard server local time. Overnight windows such as 22:00–06:00 are supported.", + "clients.schedule_title": "Access schedule", + "clients.schedule_to": "Access until", + "clients.security_access": "Security and access time", + "clients.server_host": "Server address / domain", + "clients.server_host_hint": "Public IP or domain used by this client. Previously entered values are available as suggestions.", + "clients.server_host_required": "Server address / domain is required for a generated client configuration.", + "clients.server_peer": "Server peer", + "clients.server_port": "WireGuard port", + "clients.server_port_hint": "Taken automatically from the server configuration.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Status", + "clients.subtitle": "WireGuard peers, live status and client configuration management.", + "clients.tab_basic": "Basic", + "clients.tab_config": "Configuration", + "clients.tab_policy": "Policies", + "clients.tab_security": "Security", + "clients.title": "Clients", + "clients.type": "Type", + "clients.unmanaged_note": "This peer existed before WGTools. Its client private key cannot be recovered, so WGTools can edit the server-side peer but cannot generate its client configuration or QR code.", + "clients.updating": "Updating client…", + "common.actions": "Actions", + "common.ago": "ago", + "common.cancel": "Cancel", + "common.checking": "Checking…", + "common.close": "Close", + "common.config": "Config", + "common.delete": "Delete", + "common.disabled": "Disabled", + "common.edit": "Edit", + "common.enabled": "Enabled", + "common.loading": "Loading…", + "common.never": "Never", + "common.no": "No", + "common.not_configured": "Not configured", + "common.not_installed": "Not installed", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Refresh", + "common.running": "Running", + "common.save": "Save", + "common.stopped": "Stopped", + "common.total": "Total", + "common.unknown": "Unknown", + "common.updated": "Updated", + "common.yes": "Yes", + "dashboard.active_peers": "Active peers", + "dashboard.active_peers_subtitle": "Live information from wg show.", + "dashboard.activity": "System overview", + "dashboard.activity_subtitle": "Read-only checks for the running WireGuard stack.", + "dashboard.cores": "cores", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Last 24 h", + "dashboard.history_avg": "Avg", + "dashboard.history_max": "Max", + "dashboard.history_min": "Min", + "dashboard.history_now": "now", + "dashboard.memory": "Memory", + "dashboard.network": "Network", + "dashboard.peers": "Peers", + "dashboard.quick_search": "Quick search", + "dashboard.quick_search_clear": "Clear search", + "dashboard.quick_search_empty": "No peers match the search", + "dashboard.restart": "Restart", + "dashboard.restart_confirm": "Restart WireGuard? Active VPN clients will reconnect automatically.", + "dashboard.restart_ok": "WireGuard restarted.", + "dashboard.routing": "Routing", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Start", + "dashboard.start_ok": "WireGuard started.", + "dashboard.stop": "Stop", + "dashboard.stop_confirm": "Stop WireGuard? Active VPN clients will be disconnected.", + "dashboard.stop_ok": "WireGuard stopped.", + "dashboard.subtitle": "WireGuard server status, peers and live traffic.", + "dashboard.title": "Dashboard", + "dashboard.traffic": "Traffic", + "dashboard.uptime": "Uptime", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Server access policy", + "groups.additional_allowed": "Additional allowed addresses", + "groups.additional_blocked": "Additional blocked addresses", + "groups.allow": "Allow", + "groups.allowed": "Allowed", + "groups.allowed_addresses": "Allowed addresses / networks", + "groups.apply_current_template": "Apply current group template", + "groups.apply_defaults": "Apply current group template", + "groups.apply_defaults_hint": "Copies the current group route, DNS and Keepalive template into this client. Save the client, then issue a new config or QR if the installed device must be updated.", + "groups.basic": "Basic information", + "groups.block": "Block", + "groups.blocked": "Blocked", + "groups.blocked_addresses": "Blocked addresses / networks", + "groups.client_config_source": "Client configuration source", + "groups.client_defaults": "Client defaults", + "groups.client_group_hint": "Optional group for reusable access policy and client defaults. Groups are scoped to the selected WireGuard interface.", + "groups.config_differs": "This client configuration differs from the current group defaults. Server policy is current, but the installed phone/PC configuration changes only when you issue a new config or QR.", + "groups.config_differs_short": "Client config differs from group defaults", + "groups.create": "Create group", + "groups.create_title": "Create group", + "groups.created": "Group created", + "groups.creating": "Creating group…", + "groups.defaults_applied": "Current group template applied. Save the client to keep it.", + "groups.defaults_hint": "Defines what the client device sends through WireGuard. The server policy above independently decides what that traffic may access. Changing the template later never silently changes configs already installed on devices.", + "groups.delete_message": "Delete “{name}”? Client configurations are never deleted with a group.", + "groups.delete_move": "Move its clients to another group", + "groups.delete_title": "Delete client group", + "groups.delete_unassign": "Remove the group assignment from its clients", + "groups.deleted": "Group deleted", + "groups.deleting": "Updating clients and deleting group…", + "groups.description": "Description", + "groups.edit_title": "Edit group", + "groups.editor_subtitle": "A group combines a live server access policy with a template used when creating client configurations.", + "groups.effective_allow": "Allowed exceptions", + "groups.effective_deny": "Blocked exceptions", + "groups.effective_policy": "Effective server policy", + "groups.empty": "No client groups yet. Create one to reuse access policies and client defaults.", + "groups.group": "Group", + "groups.inherit": "Inherit", + "groups.internet_access": "Internet access", + "groups.internet_short": "Internet", + "groups.local_access": "Local networks", + "groups.local_short": "Local", + "groups.manage": "Groups", + "groups.members_count": "{count} clients", + "groups.name": "Name", + "groups.name_required": "Group name is required.", + "groups.new_client_defaults": "Client configuration template", + "groups.new_clients_short": "New clients", + "groups.no_group": "No group", + "groups.none": "None", + "groups.override_client_config": "Override the group client template for this client", + "groups.override_client_config_hint": "Off: Routes, DNS and Keepalive come from the group template. On: this client keeps its own values. Server access-policy overrides above remain independent.", + "groups.policy_addresses_hint": "IPv4 addresses or CIDRs, comma separated. Client exceptions take priority over group exceptions.", + "groups.policy_custom": "Custom policy", + "groups.policy_inherit": "Use group policy", + "groups.policy_mode": "Policy source", + "groups.policy_mode_hint": "Group policy is inherited by default. Client overrides never modify the group itself.", + "groups.routes_required": "Client routes cannot be empty.", + "groups.subtitle": "Reuse server access policies and defaults for normal clients on the selected WireGuard interface.", + "groups.title": "Client groups", + "groups.traffic_through_vpn": "Traffic through VPN", + "groups.updated": "Group updated", + "groups.updating": "Updating group policy…", + "help.example_note": "All addresses, interface names, peer names and domains in Help examples are fictional documentation values. Replace them with values from your own network.", + "help.navigation": "Help navigation", + "help.open": "Open help", + "help.subtitle": "Plain-language help for Dashboard, Server, Clients and Settings with short practical examples.", + "help.title": "WGTools Help", + "interfaces.add": "+ Add interface", + "interfaces.create": "Create interface", + "interfaces.create_confirm": "Create and start interface {name}?", + "interfaces.create_failed": "Interface could not be created", + "interfaces.create_hint": "WGTools checks that the VPN network, UDP port and policy routing table do not conflict with other WireGuard interfaces before creating the configuration.", + "interfaces.create_subtitle": "Create an independent WireGuard interface with its own address pool, UDP port and routing settings.", + "interfaces.create_title": "Add WireGuard interface", + "interfaces.created": "Interface created successfully.", + "interfaces.creating": "Generating keys, writing the new configuration and starting WireGuard…", + "interfaces.current": "Current", + "interfaces.delete": "Delete", + "interfaces.delete_confirm": "Delete interface {name}? This removes its WireGuard configuration and all peers on this interface. A configuration backup is created first.", + "interfaces.delete_failed": "Interface could not be deleted", + "interfaces.delete_last": "The last configured WireGuard interface cannot be deleted here.", + "interfaces.delete_tooltip": "Delete this WireGuard interface", + "interfaces.deleted": "Interface deleted. Backup: {backup}", + "interfaces.deleting": "Stopping WireGuard and deleting the interface…", + "interfaces.display_name": "Display name", + "interfaces.display_name_edit_hint": "Friendly name only; the Linux interface name does not change.", + "interfaces.display_name_hint": "Optional friendly name, for example Work or Contractors.", + "interfaces.identity": "Interface identity", + "interfaces.none": "No WireGuard interfaces found", + "interfaces.none_configured": "No configured WireGuard interfaces yet.", + "interfaces.peers_short": "peers", + "interfaces.rename_failed": "Interface display name could not be saved.", + "interfaces.select": "Select", + "interfaces.subtitle": "Each interface has its own VPN network, listen port, peers and policies. Select one to manage it throughout WGTools.", + "interfaces.switch_title": "WireGuard interfaces", + "interfaces.system_name": "System name", + "interfaces.system_name_hint": "Linux interface name, for example wg1. It cannot be changed after creation.", + "interfaces.title": "WireGuard interfaces", + "interfaces.unique_port_hint": "Each WireGuard interface on this server must use its own UDP listen port.", + "interfaces.unique_table_hint": "WGTools recommends a separate policy table for each interface. Leave empty for normal system routing.", + "nav.clients": "Clients", + "nav.dashboard": "Dashboard", + "nav.server": "Server", + "nav.settings": "Settings", + "server.access_apply_confirm": "Save this firewall rule and apply it now? WireGuard will be restarted briefly and a backup will be created.", + "server.access_rule_deleted": "Access rule deleted.", + "server.access_rule_help": "Create a common FORWARD access rule without editing iptables commands manually.", + "server.access_rule_order_hint": "WGTools inserts access rules at the beginning of the FORWARD chain so restrictive rules take effect before the general VPN ACCEPT rules.", + "server.access_rule_saved": "Access rule saved and applied.", + "server.action": "Action", + "server.action_hint": "REJECT tells the client the traffic was refused; DROP silently discards it; ACCEPT explicitly allows it.", + "server.add_access_rule": "Add access rule", + "server.add_route": "Add route", + "server.address": "Address", + "server.any": "Any", + "server.any_protocol": "Any", + "server.apply_confirm": "Save these server settings and apply them now? WireGuard will be restarted briefly. A backup is created first and WGTools will roll back automatically if the new configuration does not start.", + "server.apply_settings": "Save and apply", + "server.applying_rule": "Creating backup and applying…", + "server.applying_settings": "Validating settings, creating backup and applying…", + "server.basic_settings": "Basic settings", + "server.config_tab_help": "Open the raw configuration editor for the currently selected WireGuard interface.", + "server.create_confirm": "Create and start the WireGuard server with these settings?", + "server.create_server": "Create server", + "server.create_step_conf": "Create the configuration for the selected WireGuard interface with mode 600.", + "server.create_step_forward": "Configure forwarding, NAT and optional policy routing.", + "server.create_step_key": "Generate a new server key pair.", + "server.create_step_start": "Enable and start the selected wg-quick interface.", + "server.create_subtitle": "WireGuard is installed, but the selected interface is not configured yet.", + "server.create_success": "WireGuard server created successfully.", + "server.create_title": "Create WireGuard server", + "server.creating": "Generating keys, writing configuration and starting WireGuard…", + "server.custom_preserved": "Peer blocks, site-to-site routes and custom PostUp/PostDown rules that are not managed by these fields are preserved.", + "server.delete_access_confirm": "Delete this access rule and apply the change?", + "server.delete_route_confirm": "Delete this custom route and apply the change?", + "server.destination": "Destination", + "server.destination_hint": "Empty = any. Accepts an IP, CIDR or IP range. Separate multiple destinations with commas.", + "server.destination_port": "Destination port", + "server.destination_port_hint": "Optional. Enter a port such as 443 or a range such as 10000:20000. Select TCP or UDP first.", + "server.details": "Details", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostics", + "server.diagnostics_done": "Diagnostics completed", + "server.diagnostics_subtitle": "Current system checks. No configuration is changed.", + "server.direction": "Hook", + "server.edit_access_rule": "Edit access rule", + "server.edit_route": "Edit route", + "server.edit_server": "Edit server", + "server.edit_subtitle": "Edit the common WireGuard, routing and NAT settings. Existing peers and custom rules are preserved.", + "server.edit_title": "Server settings", + "server.edit_warning": "Applying interface, routing or firewall settings briefly restarts the WireGuard interface. Active peers will reconnect automatically.", + "server.enable_forwarding": "Enable IPv4 forwarding", + "server.enable_nat": "Enable NAT / Masquerade", + "server.firewall": "Firewall & NAT", + "server.firewall_subtitle": "Detected rules from WireGuard hooks.", + "server.firewall_subtitle_v08": "Common forwarding/NAT rules and access rules from the selected interface configuration. Simple access rules can be managed here; advanced rules stay available in the raw editor.", + "server.forward_from_vpn": "Allow forwarding from VPN", + "server.forward_to_vpn": "Allow forwarding to VPN", + "server.forwarding_section": "Forwarding and NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Required only when a policy routing table is used.", + "server.install_success": "WireGuard installed successfully.", + "server.install_wireguard": "Install WireGuard", + "server.install_wireguard_help": "Runs apt update and installs WireGuard plus the networking tools needed by WGTools.", + "server.install_wireguard_title": "Install WireGuard", + "server.installing": "Installing WireGuard… This may take a minute.", + "server.interface": "Interface", + "server.interface_hint": "WGTools currently manages this interface.", + "server.interface_name": "Interface", + "server.interface_section": "WireGuard interface", + "server.ip_forwarding": "IPv4 forwarding", + "server.kind": "Kind", + "server.listen_port": "Listen port", + "server.local_network": "Local network", + "server.local_network_hint": "Optional route added to the policy table.", + "server.managed_automatically": "Managed automatically", + "server.nat": "NAT / Masquerade", + "server.network": "Network", + "server.network_settings": "Network and NAT", + "server.no_firewall": "No firewall rules detected", + "server.no_routes": "No routes detected", + "server.not_configured": "Not configured", + "server.not_set": "Not set", + "server.policy_disabled_hint": "Disable this for normal system routing. Enable it only when this VPN needs its own source policy routing table.", + "server.policy_enabled": "Enable policy routing", + "server.policy_table": "Policy table", + "server.policy_table_hint": "Leave empty for normal system routing; use e.g. 200 for source policy routing.", + "server.port_word": "port", + "server.private_hidden": "Configured (hidden)", + "server.private_key": "Private key", + "server.protocol": "Protocol", + "server.route_apply_confirm": "Save this route and apply it now? WireGuard will be restarted briefly and a backup will be created.", + "server.route_custom": "Custom", + "server.route_deleted": "Route deleted.", + "server.route_device_hint": "Optional output interface, for example wg0 or enp6s18.", + "server.route_editor_help": "Add a route that should be installed when WireGuard starts and removed when it stops.", + "server.route_gateway_hint": "Optional next-hop gateway. A gateway or interface is required.", + "server.route_managed_peer": "Site-to-site peer", + "server.route_managed_server": "Server setting", + "server.route_network_hint": "IPv4 network such as 10.20.0.0/24, or 'default'.", + "server.route_saved": "Route saved and applied.", + "server.route_table_hint": "Use 'main' for normal routing or a numeric table such as 200.", + "server.route_type": "Type", + "server.routes": "Detected routes", + "server.routes_subtitle": "Routes parsed from PostUp/PostDown and current policy routing state.", + "server.routes_subtitle_v08": "Server-managed, site-to-site and custom routes from the selected interface configuration. Custom routes can be added, edited and removed here.", + "server.routing": "Routing", + "server.routing_section": "Routing", + "server.rule": "Rule", + "server.rule_access": "Access rule", + "server.rule_advanced": "Advanced", + "server.rule_apply_warning": "Applying a route or firewall rule briefly restarts the WireGuard interface. WGTools creates a backup and rolls back automatically if startup fails.", + "server.rule_client_exception": "Client exception", + "server.rule_client_policy": "Client policy", + "server.rule_managed_server": "Server setting", + "server.rule_type": "Type", + "server.run_diagnostics": "Run diagnostics", + "server.save_apply": "Save and apply", + "server.save_config": "SaveConfig", + "server.server_address": "Server VPN address", + "server.server_address_hint": "Usually the first usable address in the VPN network.", + "server.settings_applied": "Server settings saved and applied successfully.", + "server.settings_apply_failed": "Server settings could not be applied", + "server.setup_required": "Setup required", + "server.source": "Source", + "server.source_hint": "Empty = any. Accepts an IP, CIDR or range such as 10.0.0.100-10.0.0.120.", + "server.subtitle": "WireGuard installation, initial setup and current server configuration.", + "server.tab_config": "Config", + "server.tab_interface": "Interface", + "server.tab_routing": "Routing", + "server.tab_vps": "VPS", + "server.table": "Table", + "server.tabs_aria": "Server settings sections", + "server.title": "Server", + "server.uplink": "Uplink interface", + "server.use_raw_editor": "Use raw editor", + "server.via": "Via / Device", + "server.via_word": "via", + "server.vpn_network": "VPN network", + "server.vpn_network_hint": "Client addresses will later be allocated from this network.", + "server.vpn_pool": "VPN address pool", + "server.wg_not_installed": "WireGuard is not installed", + "server.wg_not_installed_subtitle": "WGTools can install the required Debian packages automatically.", + "server.what_happens": "What WGTools will do", + "settings.about": "About", + "settings.add_user": "Add user", + "settings.advanced": "Advanced", + "settings.advanced_subtitle": "Direct access to expert WireGuard configuration tools.", + "settings.appearance": "Appearance", + "settings.applying_config": "Validating configuration, creating backup and applying…", + "settings.backup_count": "Stored backups", + "settings.backup_retention": "Backups to keep", + "settings.backup_retention_help": "Old automatic backups are removed after a new backup is created. 1–200 files.", + "settings.backups": "Configuration backups", + "settings.backups_always_on": "Enabled", + "settings.backups_subtitle": "WGTools automatically creates a backup before configuration-changing operations. Automatic backups cannot be disabled.", + "settings.change_password": "Change password", + "settings.check_updates": "Check for updates", + "settings.config_applied": "Configuration saved and applied successfully.", + "settings.config_applied_restarted": "Configuration applied and WireGuard restarted.", + "settings.config_applied_stopped": "Configuration saved. WireGuard was already stopped and remains stopped.", + "settings.config_apply_failed": "Configuration could not be applied", + "settings.config_load_failed": "Could not load configuration", + "settings.current_user": "Current user", + "settings.current_version": "Current version", + "settings.audit_action": "Action", + "settings.audit_empty": "No audit events yet", + "settings.audit_log": "Audit", + "settings.audit_log_subtitle": "Panel, authentication and Telegram actions plus WireGuard client connection history. Secrets are never written here.", + "settings.audit_object": "Object", + "settings.audit_result": "Result", + "settings.audit_retention_note": "Retention: 30 days", + "settings.audit_search": "Quick search", + "settings.audit_search_clear": "Clear search", + "settings.audit_search_empty": "No audit events match the search", + "settings.audit_time": "Date / time", + "settings.audit_user": "User", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Access rule created", + "audit.action.access_rule.deleted": "Access rule deleted", + "audit.action.access_rule.updated": "Access rule updated", + "audit.action.auth.first_user_created": "First user created", + "audit.action.auth.login": "Signed in", + "audit.action.auth.login_failed": "Sign-in failed", + "audit.action.auth.logout": "Signed out", + "audit.action.backup.full_created": "Full backup created", + "audit.action.backup.full_restored": "Full backup restored", + "audit.action.client.config_downloaded": "Client config downloaded", + "audit.action.client.config_viewed": "Client config viewed", + "audit.action.client.created": "Client created", + "audit.action.client.deleted": "Client deleted", + "audit.action.client.qr_viewed": "Client QR viewed", + "audit.action.client.updated": "Client updated", + "audit.action.client_group.created": "Client group created", + "audit.action.client_group.deleted": "Client group deleted", + "audit.action.client_group.updated": "Client group updated", + "audit.action.interface.created": "Interface created", + "audit.action.interface.deleted": "Interface deleted", + "audit.action.interface.renamed": "Interface renamed", + "audit.action.route.created": "Route created", + "audit.action.route.deleted": "Route deleted", + "audit.action.route.updated": "Route updated", + "audit.action.server.created": "Server created", + "audit.action.server.raw_config_applied": "Raw config applied", + "audit.action.server.settings_applied": "Server settings applied", + "audit.action.settings.updated": "Panel settings updated", + "audit.action.telegram.action_denied": "Telegram action denied", + "audit.action.telegram.action_failed": "Telegram action failed", + "audit.action.telegram.connection_test": "Telegram connection test", + "audit.action.telegram.settings_updated": "Telegram settings updated", + "audit.action.update.checked": "Update checked", + "audit.action.update.scheduled": "Update scheduled", + "audit.action.update.backup_created": "Pre-update backup", + "audit.action.update.completed": "Update completed", + "audit.action.update.failed": "Update failed", + "audit.action.update.rollback_completed": "Previous version restored", + "audit.action.update.rollback_failed": "Update rollback failed", + "audit.action.user.created": "User created", + "audit.action.user.deleted": "User deleted", + "audit.action.user.password_changed": "User password changed", + "audit.action.vps.candidate_deleted": "VPS candidate deleted", + "audit.action.vps.candidate_saved": "VPS candidate saved", + "audit.action.vps.detached": "VPS Relay detached", + "audit.action.vps.relay_installed": "VPS Relay installed", + "audit.action.wireguard.client_connected": "WireGuard client connected", + "audit.action.wireguard.installed": "WireGuard installed", + "audit.action.wireguard.restarted": "WireGuard restarted", + "audit.action.wireguard.started": "WireGuard started", + "audit.action.wireguard.stopped": "WireGuard stopped", + "audit.result.applied": "applied", + "audit.result.available": "available", + "audit.result.changed": "changed", + "audit.result.created": "created", + "audit.result.current": "current", + "audit.result.deleted": "deleted", + "audit.result.detached": "detached", + "audit.result.denied": "denied", + "audit.result.downloaded": "downloaded", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Error", + "audit.result.installed": "installed", + "audit.result.invalid_credentials": "invalid credentials", + "audit.result.ok": "ok", + "audit.result.queued": "queued", + "audit.result.restarted": "restarted", + "audit.result.restored": "restored", + "audit.result.rotated": "rotated", + "audit.result.saved": "saved", + "audit.result.shown": "shown", + "audit.result.started": "started", + "audit.result.stopped": "stopped", + "audit.result.updated": "updated", + "settings.delete_user": "Delete", + "settings.delete_user_confirm": "Delete user {name}?", + "settings.edit_raw_config": "Edit interface config", + "settings.expert_mode": "Expert", + "settings.full_backup_component_clients": "WGTools-managed client metadata, private keys, PSKs, expiration settings, and client-group assignments required to regenerate client configs/QR codes.", + "settings.full_backup_component_db": "WGTools database: users, application preferences, mail/SMTP, Telegram settings and saved VPS Relay state.", + "settings.full_backup_component_relay": "VPS Relay recovery data: controller/tenant IDs, management token and home transport key. After restore WGTools can rebuild the local transport and reconnect to the preserved VPS tenant.", + "settings.full_backup_component_system": "WGTools IPv4-forwarding sysctl file, interface display-name metadata, and client-group policy/default definitions, when present. Automatic per-interface configuration history is intentionally excluded.", + "settings.full_backup_component_wg": "All detected WireGuard interface configurations from /etc/wireguard/, including their running/stopped state.", + "settings.full_backup_create_failed": "Could not create the full backup", + "settings.full_backup_creating": "Creating a complete backup…", + "settings.full_backup_download": "Create", + "settings.full_backup_downloaded": "Backup created and downloaded. Store it securely.", + "settings.full_backup_downloaded_short": "Full backup downloaded.", + "settings.full_backup_help": "Creates a portable WGTools backup for migration or disaster recovery. It includes WireGuard configs, users, settings, groups, managed-client data and the state required to reconnect to preserved VPS Relay tenants.", + "settings.full_backup_no_file": "No backup selected", + "settings.full_backup_restore": "Restore", + "settings.full_backup_restore_confirm": "Restore this full WGTools backup? Current users, settings, managed client data and all WireGuard configurations included in the backup will be restored. WireGuard interfaces may restart. WGTools creates a safety backup first and rolls back automatically if applying the restored state fails.", + "settings.full_backup_restore_failed": "Restore failed", + "settings.full_backup_restored": "Backup restored successfully. Sign in with an account from the restored backup.", + "settings.full_backup_restored_short": "Backup restored.", + "settings.full_backup_restoring": "Validating backup, creating a safety copy and restoring…", + "settings.full_backup_secret_warning": "This file contains sensitive data: WireGuard private keys, client private keys, preshared keys (PSKs), WGTools password hashes, the Telegram Bot token and the saved SMTP password. Store it like a password and never attach it to public issues or chats.", + "settings.full_backup_select": "Select", + "settings.full_backup_title": "Full backup and restore", + "settings.full_mode": "Server and client management enabled", + "settings.interface_help": "The managed WireGuard interface is selected when WGTools is deployed.", + "settings.language": "Language", + "settings.last_backup": "Last backup", + "settings.latest_version": "Latest release", + "settings.loading_config": "Loading configuration…", + "settings.mode": "Mode", + "settings.never_logged_in": "Never", + "settings.new_password": "New password", + "settings.no_backups": "No backups yet", + "settings.online_help": "A peer is considered online while its latest handshake is newer than this value. 30–3600 seconds.", + "settings.online_threshold": "Online threshold", + "settings.open_release": "Open release", + "settings.password_changed": "Password changed.", + "settings.passwords_mismatch": "Passwords do not match.", + "settings.project_github": "Project / GitHub", + "settings.raw_config_confirm": "Save this WireGuard configuration and apply it now? The selected interface will be restarted. A backup is created first and WGTools will roll back automatically if the new configuration does not start.", + "settings.raw_config_help": "Open the source configuration of the selected WireGuard interface.", + "settings.raw_config_title": "Raw WireGuard configuration", + "settings.raw_config_warning": "Expert mode: this is the real WireGuard server configuration and includes the server private key and any peer PSKs. Saving and applying restarts the WireGuard interface. WGTools creates a backup first and automatically rolls back if the new configuration cannot start.", + "settings.readonly_mode": "Client management enabled", + "settings.refresh_help": "How often WGTools requests fresh status data. 2–60 seconds.", + "settings.refresh_interval": "Refresh interval", + "settings.release_notes": "Release notes", + "settings.reload_config": "Reload from disk", + "settings.save_apply": "Save & Apply", + "settings.saved": "Settings saved.", + "settings.saved_reload": "Settings saved. Reloading…", + "settings.saving": "Saving settings…", + "settings.status": "Status refresh", + "settings.status_help": "Live dashboard and peer status refresh settings.", + "settings.subtitle": "WGTools interface preferences and status settings.", + "settings.syntax_hint": "WireGuard sections, keys, values and comments are highlighted while you edit.", + "settings.tab_about": "About", + "settings.tab_backups": "Backups", + "settings.tab_general": "General", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Users", + "settings.tabs_aria": "Settings sections", + "settings.telegram": "Telegram Bot", + "settings.telegram_allowed_ids": "Allowed Telegram user IDs", + "settings.telegram_allowed_ids_help": "One numeric user ID per line. An unauthorized /start message will reply with the sender’s Telegram user ID so you can add it here.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connected", + "settings.telegram_disabled": "Disabled", + "settings.telegram_dns": "Default client DNS", + "settings.telegram_dns_help": "Optional IPv4 DNS addresses separated by commas. Used for clients created by the bot.", + "settings.telegram_enabled": "Enable Telegram bot", + "settings.telegram_endpoint": "Default server address / domain", + "settings.telegram_endpoint_help": "Used when the bot creates a new client configuration. Enter only an IP address or domain; the WireGuard port is read from the server configuration.", + "settings.telegram_language": "Bot language", + "settings.telegram_language_auto": "Auto (Telegram language)", + "settings.telegram_last_poll": "Last Telegram contact", + "settings.telegram_not_configured": "Not configured", + "settings.telegram_remove_token": "Remove token", + "settings.telegram_remove_token_confirm": "Remove the saved Telegram bot token and disable the bot?", + "settings.telegram_save": "Save Telegram settings", + "settings.telegram_saved": "Telegram settings saved.", + "settings.telegram_setup_note": "Create a bot with @BotFather, save its token, enable the bot and send /start. If your user ID is not authorized yet, WGTools will show it — add that ID to the Allowed Telegram user IDs list.", + "settings.telegram_status": "Bot status", + "settings.telegram_subtitle": "Remote WireGuard management from Telegram: server status, clients, client creation/deletion and WireGuard start/restart/stop.", + "settings.telegram_test": "Test connection", + "settings.telegram_test_ok": "Telegram connection is working: @{username}", + "settings.telegram_test_recent_ok": "Telegram bot is working. The direct check timed out, but the bot contacted Telegram recently.", + "settings.telegram_token": "Bot token", + "settings.telegram_token_help": "Create a bot with @BotFather and paste its Bot API token here. API ID and API Hash are not required for the Telegram Bot API.", + "settings.telegram_token_keep": "Leave empty to keep the saved token.", + "settings.telegram_waiting": "Configured, waiting for bot service", + "settings.theme": "Theme", + "settings.theme_dark": "Dark", + "settings.theme_light": "Light", + "settings.theme_system": "System", + "settings.title": "Settings", + "settings.update_available": "Update available", + "settings.update_backup_queued": "Update queued. WGTools will create an automatic full backup before installing it…", + "settings.update_backup_running": "Creating the automatic full backup before update…", + "settings.update_check_failed": "Could not check for updates", + "settings.update_checking": "Checking the latest published GitHub Release…", + "settings.update_confirm": "Update WGTools from v{current} to v{latest}? A full backup and application rollback copy will be created first. The web interface will restart briefly.", + "settings.update_current": "Up to date", + "settings.update_downloading": "Downloading and validating the GitHub release…", + "settings.update_failed": "WGTools update failed.", + "settings.update_installing": "Installing the update. The web interface may be unavailable briefly…", + "settings.update_no_update": "WGTools is already up to date.", + "settings.update_not_checked": "Not checked", + "settings.update_queued": "Update queued. Waiting for the updater service…", + "settings.update_rollback_ok": "The previous WGTools application was restored automatically.", + "settings.update_rolling_back": "Update failed. Restoring the previous WGTools application…", + "settings.update_running": "Creating safety backups…", + "settings.update_safety_hint": "Updates are opt-in. Before installation WGTools creates a full state backup and an application rollback copy. If installation fails, the previous application is restored automatically. WireGuard itself is not restarted by the updater unless the new release explicitly changes its configuration.", + "settings.update_sidebar": "New version available", + "settings.update_sidebar_hint": "Open Settings → About", + "settings.update_starting": "Starting the update…", + "settings.update_status_unknown": "Update status is unavailable. Retrying…", + "settings.update_subtitle": "Project information, automatic release checks and safe updates from GitHub Releases.", + "settings.update_success": "WGTools was updated successfully to v{version}. Reloading…", + "settings.update_wgtools": "Update WGTools", + "settings.user_actions": "Actions", + "settings.user_created": "Created", + "settings.user_created_ok": "User created.", + "settings.user_deleted": "User deleted.", + "settings.user_equal_rights": "All WGTools users have the same permissions.", + "settings.user_last_login": "Last login", + "settings.user_name": "Username", + "settings.users": "Users", + "settings.users_subtitle": "Local WGTools accounts. E-mail is optional and is used only for password recovery when mail is enabled.", + "vps.add": "Add VPS", + "vps.add_help": "WGTools uses SSH to check or install Relay. Passwords and private SSH keys are never stored.", + "vps.add_title": "Add VPS", + "vps.agent": "Relay Agent", + "vps.agent_found": "Already installed", + "vps.agent_will_install": "Will be installed", + "vps.arch": "Architecture", + "vps.auth_method": "Authentication", + "vps.authentication": "SSH authentication", + "vps.check": "Check VPS", + "vps.check_failed": "VPS check failed", + "vps.check_link": "Check link", + "vps.check_ok": "VPS is compatible", + "vps.checking": "Checking SSH access and VPS compatibility…", + "vps.connections": "connections", + "vps.credentials_not_saved": "Used only for this check and not stored by WGTools.", + "vps.delete_candidate": "Remove", + "vps.delete_installed": "Remove VPS", + "vps.delete_installed_confirm": "Remove “{name}” from WGTools? The local Relay transport will be disconnected, but the Relay Agent and tenant on the VPS will be preserved. You can add this VPS again and WGTools will reconnect to the existing Relay instead of creating a new one. Clients using this Relay cannot connect through it until the VPS is reconnected.", + "vps.delete_installed_failed": "Could not remove VPS from WGTools", + "vps.delete_installed_ok": "VPS removed from WGTools. The remote Relay was preserved and can be reconnected.", + "vps.empty_help": "Add a Debian or Ubuntu VPS to check SSH access, operating system compatibility and required UDP ports.", + "vps.empty_title": "No VPS configured", + "vps.endpoint": "Public endpoint", + "vps.endpoint_domain": "Domain (recommended)", + "vps.endpoint_domain_hint": "If you later replace the primary VPS, changing DNS can keep existing client configurations unchanged.", + "vps.health_failed": "Relay link check failed", + "vps.host": "IP / hostname", + "vps.host_key": "SSH host key", + "vps.identity": "VPS connection", + "vps.install_failed": "Relay installation failed", + "vps.install_ok": "Relay installed and protected management link verified", + "vps.install_relay": "Install Relay", + "vps.install_title": "Install VPS Relay", + "vps.installed": "Installed", + "vps.installing": "Installing Relay Agent and establishing the protected transport tunnel…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Key passphrase", + "vps.link_ok": "Relay link OK", + "vps.multi_tenant_note": "A WGTools Relay Agent is already running on this VPS. It will not be replaced: this WGTools will get a separate isolated connection with its own keys and UDP ports.", + "vps.name": "Name", + "vps.no_domain": "IP endpoint", + "vps.not_installed": "Will be installed", + "vps.os": "Operating system", + "vps.password": "Password", + "vps.phase_note": "Relay Agent supports multiple independent WGTools controllers on one VPS. Each controller gets an isolated connection, keys and UDP ports; existing connections are left untouched.", + "vps.port_pair": "UDP ports", + "vps.ports_adjusted": "free ports selected", + "vps.private_key": "Private key", + "vps.privilege": "Privileges", + "vps.public_endpoint": "Future public endpoint", + "vps.ready_help": "SSH credentials are used for the compatibility check and immediate Relay installation; they are never saved.", + "vps.reconnect_note": "An existing Relay connection created by this WGTools was found on the VPS. WGTools will reconnect to that same tenant; no new tenant or UDP ports will be created.", + "vps.reconnect_ok": "Existing Relay reconnected successfully", + "vps.reconnect_relay": "Reconnect Relay", + "vps.relay_port": "Relay UDP port", + "vps.remove_confirm": "Remove this VPS candidate? No remote changes have been made.", + "vps.save_candidate": "Save candidate", + "vps.saved": "VPS candidate saved", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH key", + "vps.ssh_port": "SSH port", + "vps.ssh_user": "SSH user", + "vps.status_candidate": "Ready for installation", + "vps.status_installed": "Relay connected", + "vps.subtitle": "Prepare a public VPS for remote access when this WGTools server has no public IP.", + "vps.tenant": "Connection", + "vps.title": "VPS Relay", + "vps.transport_port": "Transport UDP port", + "vps.transport_port_hint": "Separate UDP port for the private Home ↔ VPS transport tunnel.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Saved", + "vps.active_short": "Active", + "dashboard.traffic_reset": "Reset", + "dashboard.traffic_reset_confirm": "Reset accumulated WireGuard traffic counters for this interface? Client counters will also restart from zero.", + "dashboard.traffic_reset_done": "Traffic counters reset", + "dashboard.traffic_reset_failed": "Could not reset traffic counters", + "audit.action.traffic.reset": "Traffic counters reset", + "audit.result.reset": "reset", + "server.mtu": "MTU", + "server.mtu_auto": "Auto", + "server.mtu_hint": "Optional. Leave empty for wg-quick automatic MTU. Set a value such as 1380 or 1420 only when required by the network, LTE or PPPoE path.", + "clients.peer_isolation": "VPN client isolation", + "clients.peer_isolation_enable": "Isolate from other VPN clients", + "clients.peer_isolation_hint": "Blocks traffic between this client and other addresses in the WireGuard pool. Access to the server itself, Internet, local networks and Site-to-site networks is still controlled by the other policies.", + "clients.credentials_rotate": "Client keys", + "clients.credentials_rotate_button": "Rotate keys", + "clients.credentials_rotate_confirm": "Generate new keys for this client? If it is currently connected, its active WireGuard session will be forcibly disconnected. Send a new config or QR afterward.", + "clients.credentials_rotate_confirm_psk": "Generate a new key pair and a new PSK for this client? If it is currently connected, its active WireGuard session will be forcibly disconnected. Send a new config or QR afterward.", + "clients.credentials_rotate_hint": "One action rotates PrivateKey/PublicKey and, when PSK is enabled, the PSK as well. Address, routes, group, schedule, isolation and accumulated statistics are preserved.", + "clients.credentials_rotating": "Generating new keys and disconnecting the old client session…", + "clients.credentials_rotated": "Client keys changed. If the client was connected, its old session was forcibly disconnected. The old config no longer works; send a new config or QR before reconnecting.", + "clients.credentials_rotated_short": "Client keys changed — new config required", + "audit.action.client.credentials_rotated": "Client keys rotated", + "clients.credentials_connection_lost": "The connection to WGTools was interrupted. If this panel was opened through the client whose keys were just rotated, this is expected: its old WireGuard session is disconnected immediately. Reconnect to WGTools by another path and issue the new config or QR.", + "nav.navigation": "Main navigation", + "nav.project_github": "WGTools on GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Optional now. It can be used for password recovery after mail is configured.", + "auth.forgot_password": "Forgot password?", + "auth.reset_title": "Reset password", + "auth.reset_subtitle": "Receive a one-time code by email and set a new WGTools password.", + "auth.reset_identifier": "Username or e-mail", + "auth.reset_identifier_help": "For privacy, WGTools always shows the same response whether the account exists or not.", + "auth.send_reset_code": "Send reset code", + "auth.reset_code_sent_generic": "If the account exists and has an e-mail address, a reset code has been sent. The code is valid for 15 minutes.", + "auth.reset_code": "6-digit code", + "auth.set_new_password": "Set new password", + "auth.request_another_code": "Request another code", + "auth.back_to_login": "Back to sign in", + "auth.reset_not_configured": "Password recovery by e-mail is not configured. Contact the WGTools administrator.", + "settings.tab_mail": "Mail", + "settings.mail": "Mail / SMTP", + "settings.mail_subtitle": "SMTP is used for password recovery.", + "settings.mail_not_configured": "Not configured", + "settings.mail_enabled": "Enable mail and password recovery", + "settings.mail_smtp_host": "SMTP server", + "settings.mail_smtp_port": "SMTP port", + "settings.mail_security": "Encryption", + "settings.mail_security_none": "No encryption", + "settings.mail_username": "SMTP username", + "settings.mail_username_help": "Used for SMTP authentication and as the sender e-mail address.", + "settings.mail_password": "SMTP password", + "settings.mail_password_keep": "Leave empty to keep the saved password.", + "settings.mail_from_email": "Sender e-mail", + "settings.mail_from_name": "Sender name", + "settings.mail_test_recipient": "Test recipient", + "settings.mail_test_recipient_help": "The test uses the currently saved SMTP settings.", + "settings.mail_remove_password": "Remove password", + "settings.mail_test": "Send test", + "settings.mail_save": "Save mail settings", + "settings.mail_enabled_badge": "Enabled", + "settings.mail_disabled_badge": "Disabled", + "settings.mail_saved": "Mail settings saved.", + "settings.mail_remove_password_confirm": "Remove the saved SMTP password and disable mail?", + "settings.mail_password_removed": "SMTP password removed and mail disabled.", + "settings.mail_test_recipient_required": "Enter a test recipient e-mail address.", + "settings.mail_testing": "Sending a test e-mail…", + "settings.mail_test_ok": "Test e-mail sent successfully.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Optional. Required only for self-service password recovery.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail saved.", + "settings.send_password_reset": "Send reset", + "settings.user_reset_mail_not_configured": "Configure and enable mail first.", + "settings.user_reset_email_missing": "Add an e-mail address first.", + "settings.user_reset_confirm": "Send a password reset code to {name} at {email}?", + "settings.user_reset_sent": "Password reset code sent to {email}.", + "audit.action.auth.password_reset_requested": "Password reset requested", + "audit.action.auth.password_reset_code_sent": "Password reset code sent", + "audit.action.auth.password_reset_completed": "Password reset completed", + "audit.action.auth.password_reset_failed": "Password reset failed", + "audit.action.mail.settings_updated": "Mail settings updated", + "audit.action.mail.test_sent": "Test e-mail sent", + "audit.action.mail.test_failed": "Test e-mail failed", + "audit.action.user.email_changed": "User e-mail changed", + "audit.action.user.password_reset_sent": "User password reset sent", + "audit.action.user.password_reset_failed": "User password reset failed", + "audit.result.accepted": "accepted", + "audit.result.sent": "sent", + "audit.result.invalid_code": "invalid code", + "common.copy": "Copy", + "common.copied": "Copied", + "clients.use_panel_host": "Use panel address", + "clients.use_panel_host_done": "Panel address inserted: {host}", + "clients.use_panel_host_failed": "Could not determine the panel address from the browser URL.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Built-in Let’s Encrypt HTTPS for direct WGTools access without a reverse proxy.", + "settings.https_disabled": "Disabled", + "settings.https_enabled": "Enabled", + "settings.https_enable": "Enable built-in HTTPS", + "settings.https_type": "Certificate for", + "settings.https_domain": "Domain", + "settings.https_public_ip": "Public IP", + "settings.https_target": "Domain or public IP", + "settings.https_email": "Let’s Encrypt e-mail", + "settings.https_port": "HTTPS port", + "settings.https_port80_note": "TCP port 80 must be reachable from the Internet for certificate issuance and automatic renewal. Open the selected HTTPS port for the WGTools panel itself.", + "settings.https_check_ports": "Check ports", + "settings.https_certificate": "Certificate", + "settings.https_certificate_ready": "Ready", + "settings.https_certificate_missing": "Not issued", + "settings.https_expires": "Valid until", + "settings.https_renewal": "Automatic renewal", + "settings.https_renewal_enabled": "Enabled", + "settings.https_renewal_disabled": "Disabled", + "settings.https_certificate_path": "Certificate", + "settings.https_private_key_path": "Private key", + "settings.https_issue": "Obtain / renew certificate", + "settings.https_port_free": "Free", + "settings.https_port_busy": "Busy", + "settings.https_ports_checked": "Port check completed.", + "settings.https_target_email_required": "Enter the domain/public IP and Let’s Encrypt e-mail.", + "settings.https_issue_confirm": "Request or renew the Let’s Encrypt certificate for {target}? The entered HTTPS settings will be saved. TCP port 80 must be reachable from the Internet.", + "settings.https_issuing": "Requesting certificate from Let’s Encrypt…", + "settings.https_issue_ok": "Certificate is ready.", + "settings.https_already_enabled": "Built-in HTTPS is already enabled.", + "settings.https_already_disabled": "Built-in HTTPS is already disabled.", + "settings.https_enable_confirm": "Enable built-in HTTPS on TCP {port} with path {path}? WGTools will restart and this page will reconnect at the new address.", + "settings.https_disable_confirm": "Disable built-in HTTPS and return WGTools to HTTP?", + "settings.https_switching": "Enabling HTTPS and restarting WGTools…", + "settings.https_switching_http": "Disabling HTTPS and restarting WGTools…", + "audit.action.https.certificate_issued": "HTTPS certificate issued", + "audit.action.https.certificate_failed": "HTTPS certificate request failed", + "audit.action.https.enabled": "HTTPS enabled", + "audit.action.https.disabled": "HTTPS disabled", + "audit.result.issued": "issued", + "audit.result.enabled": "enabled", + "audit.result.disabled": "disabled", + "settings.https_access_path": "Panel access path", + "settings.https_access_path_help": "Choose your own path. With built-in HTTPS enabled, requests outside it receive 404.", + "settings.https_enable_fields_required": "Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.", + "settings.https_use_panel_host": "Use panel address", + "settings.https_reconnecting": "WGTools is switching to the new HTTPS address…", + "server.tab_nodes": "Nodes", + "common.type": "Type", + "common.status": "Status", + "common.copy_failed": "Could not copy", + "clients.vpn_address": "VPN address", + "nodes.title": "WGTools Nodes", + "nodes.subtitle": "Link multiple WGTools servers into one protected network and publish only the networks that other nodes should be able to reach.", + "nodes.enable_hub": "Enable HUB", + "nodes.connect_hub": "Connect to HUB", + "nodes.settings": "Node settings", + "nodes.settings_action": "Settings", + "nodes.sync_now": "Synchronize", + "nodes.disable": "Disable Nodes", + "nodes.disable_action": "Disconnect", + "nodes.join_title": "Connect new nodes", + "nodes.join_help": "Create a one-time code and enter it on another WGTools panel together with the HUB service endpoint, for example vpn.example.com:51950. The code is valid for 15 minutes and can be used once.", + "nodes.create_code": "Create code", + "nodes.connected_nodes": "Connected nodes", + "nodes.connected_nodes_help": "Information about other panels, their published networks and clients. Remote clients are read-only.", + "nodes.enable_hub_help": "This panel becomes the central node. On the same port number the HUB accepts WireGuard over UDP and protected initial pairing over TCP.", + "nodes.node_name": "Node name", + "nodes.transport_network": "Node transport network", + "nodes.transport_help": "A separate private network used only for WGTools ↔ WGTools transport. It must not overlap your VPN/LAN networks.", + "nodes.panel_url": "Panel URL", + "nodes.panel_url_help": "Optional. This is only an informational link for the “Open panel” button on other nodes and is never used by the Nodes connection itself.", + "nodes.extra_networks": "Additional node networks", + "nodes.extra_networks_help": "One network per line. Interface VPN networks and Site-to-site client remote networks are published automatically. Add only other routed LAN/networks here, for example 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools pre-fills detected VPN networks, Site-to-Site networks and locally routed LANs. Keep only the networks this node should publish into Nodes. One network per line.", + "nodes.published_networks_settings_help": "One network per line. This is the explicit list of networks this node publishes into Nodes. Removing a line stops advertising that network to other nodes.", + "nodes.available_networks_help": "Currently detected: {networks}. Newly detected networks are not published automatically; add the ones you want to the list above.", + "nodes.available_networks_none": "No additional local networks are currently detected.", + "nodes.connect_help": "Enter the HUB service endpoint and one-time code. The web panel URL, HTTPS port, certificate and private path are not used for Nodes pairing.", + "nodes.join_code": "Connection code", + "nodes.connect_reachability_note": "Initial pairing uses protected TCP on the specified port. After wgnode0 is created, networks, status, versions and read-only client data synchronize with the HUB over its internal WireGuard address.", + "nodes.connect": "Connect", + "nodes.settings_help": "Node name, optional “Open panel” link and the explicit published-network list. The panel URL is not used for Nodes pairing or synchronization.", + "nodes.details": "Details", + "nodes.not_configured": "WGTools Nodes is not configured", + "nodes.not_configured_help": "Enable HUB on this panel or connect it to an existing WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connected to HUB", + "nodes.mode_none": "Not configured", + "nodes.role": "Role", + "nodes.tunnel": "Node tunnel", + "nodes.node_ip": "Node address", + "nodes.endpoint": "HUB endpoint", + "nodes.published_networks": "Published networks", + "nodes.last_sync": "Last sync", + "nodes.no_nodes_hub": "No nodes are connected yet. Create a connection code and use it on another WGTools panel.", + "nodes.no_nodes_spoke": "No remote node information has been received yet.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Open panel", + "nodes.route_conflict": "Route conflict", + "nodes.no_published_networks": "No published networks", + "nodes.load_failed": "Could not load WGTools Nodes", + "nodes.enable_hub_confirm": "Enable WGTools HUB and create the internal Node WireGuard tunnel?", + "nodes.applying": "Configuring the WGTools Nodes tunnel…", + "nodes.enable_failed": "Could not enable HUB", + "nodes.hub_enabled": "WGTools HUB enabled", + "nodes.connecting": "Verifying the HUB code and creating the protected Node tunnel…", + "nodes.connect_failed": "Could not connect to HUB", + "nodes.connected": "Connected to WGTools HUB", + "nodes.settings_failed": "Could not save Node settings", + "nodes.settings_saved": "Node settings saved", + "nodes.code_failed": "Could not create connection code", + "nodes.code_expires": "One-time code. Valid until {time}.", + "nodes.code_copied": "Connection code copied", + "nodes.network_vpn": "VPN clients", + "nodes.network_site_to_site": "Site-to-site network", + "nodes.network_custom": "Additional network", + "nodes.conflict": "Conflict", + "nodes.remote_clients": "Clients (read-only)", + "nodes.no_clients": "No clients reported by this node", + "nodes.details_failed": "Could not load Node details", + "nodes.remove_confirm": "Remove node “{name}” from this HUB? Its internal tunnel access will be revoked.", + "nodes.remove_failed": "Could not remove Node", + "nodes.removed": "Node removed", + "nodes.disable_hub_confirm": "Disable HUB and disconnect all WGTools Nodes? The internal Node tunnel will be removed.", + "nodes.disconnect_confirm": "Disconnect this WGTools panel from its HUB and remove the internal Node tunnel?", + "nodes.disable_failed": "Could not disable WGTools Nodes", + "nodes.disabled": "WGTools Nodes disabled", + "nodes.sync_failed": "Node synchronization failed", + "nodes.synced": "Node information synchronized", + "nodes.service_port": "Nodes port", + "nodes.service_port_help": "The same port number is used simultaneously: UDP for WireGuard and TCP for protected initial pairing.", + "nodes.hub_port_forward_note": "If the HUB is behind NAT, forward the same port to it for both UDP and TCP. The WGTools web port, HTTPS and private panel path are unrelated to Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Nodes domain/IP and port without http:// or https://, for example vpn.example.com:51950.", + "settings.collapse_sidebar": "Collapse sidebar", + "settings.expand_sidebar": "Expand sidebar", + "settings.https_issue_fields_required": "Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.", + "settings.https_issue_ok_saved": "Certificate is ready and HTTPS settings are saved.", + "settings.https_enable_need_certificate": "First obtain a certificate.", + "settings.https_enable_certificate_mismatch": "Obtain a certificate for the current domain or public IP first.", + "settings.https_enable_certificate_expired": "The certificate has expired. Renew it before enabling HTTPS.", + "settings.https_enable_certificate_ready": "Certificate is ready — built-in HTTPS can now be enabled.", + "settings.https_enable_active_help": "Clear the checkbox and save to return to HTTP.", + "settings.https_certificate_expired": "Expired", + "settings.https_certificate_wrong_target": "For another address", + "nodes.network_conflict_error": "Published networks conflict with another Node or the Nodes transport network: {conflicts}. Remove or change the conflicting network.", + "nodes.networks_changed": "Detected networks changed after the published list was last saved. New: {added}. No longer detected: {removed}. Review the published network list and save the settings after checking it.", + "nodes.review_networks": "Review networks", + "nodes.vpn_pool_mismatch": "VPN pool changed: Nodes still publishes {old}, while the current WireGuard VPN pool is {current}. Open Node settings and update the published networks.", + "server.error_vpn_network_invalid": "VPN network must be a valid IPv4 network, for example 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Only IPv4 VPN networks are supported.", + "server.error_vpn_network_too_small": "The VPN network must contain at least two usable addresses.", + "server.error_vpn_network_no_hosts": "The selected VPN network has no usable server addresses.", + "server.error_server_address_prefix": "The server VPN address must include a prefix, for example 10.0.0.1/24.", + "server.error_server_address_network": "The server VPN address must belong to the selected VPN address pool and use the same prefix.", + "server.error_server_address_reserved": "The server VPN address cannot be the network or broadcast address.", + "server.error_listen_port_number": "The WireGuard port must be a number.", + "server.error_listen_port_range": "The WireGuard port must be between 1 and 65535.", + "server.error_mtu_number": "MTU must be a number.", + "auth.mfa_title": "Two-factor authentication", + "auth.mfa_login_help": "Enter the 6-digit code from Google Authenticator or one of your recovery codes.", + "auth.mfa_code": "Authentication code", + "auth.mfa_verify": "Verify and sign in", + "auth.mfa_back": "Back to password", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Two-factor authentication (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Enabled", + "settings.mfa_disabled": "Disabled", + "settings.mfa_google_help": "Protect this account with Google Authenticator or another TOTP-compatible authenticator. Your current password is required to start setup.", + "settings.current_password": "Current password", + "settings.mfa_start": "Set up Google Authenticator", + "settings.mfa_secret": "Manual setup key", + "settings.mfa_scan_help": "Scan the QR code in Google Authenticator, then enter the current 6-digit code to finish enabling MFA.", + "settings.mfa_code": "6-digit code", + "settings.mfa_enable": "Enable MFA", + "settings.mfa_manage_help": "To change MFA, enter your current password and a Google Authenticator code or recovery code.", + "settings.mfa_code_or_recovery": "Authenticator or recovery code", + "settings.mfa_regenerate": "New recovery codes", + "settings.mfa_disable": "Disable MFA", + "settings.mfa_recovery_title": "Recovery codes", + "settings.mfa_recovery_help": "Save these codes now. Each code can be used once if Google Authenticator is unavailable. They are not shown again.", + "settings.mfa_recovery_remaining": "Recovery codes remaining: {count}", + "settings.mfa_enabled_ok": "MFA enabled.", + "settings.mfa_disabled_ok": "MFA disabled.", + "settings.mfa_disable_confirm": "Disable two-factor authentication for this account?", + "settings.mfa_regenerate_confirm": "Replace all existing recovery codes?", + "settings.mfa_recovery_regenerated": "New recovery codes created.", + "audit.action.auth.mfa_failed": "MFA verification failed", + "audit.action.auth.mfa_recovery_used": "MFA recovery code used", + "audit.action.user.mfa_setup_started": "MFA setup started", + "audit.action.user.mfa_enabled": "MFA enabled", + "audit.action.user.mfa_disabled": "MFA disabled", + "audit.action.user.mfa_disabled_cli": "MFA disabled from CLI", + "audit.action.user.mfa_recovery_regenerated": "MFA recovery codes regenerated", + "settings.mfa_error_password": "Invalid current password.", + "settings.mfa_error_code": "Invalid authentication code.", + "settings.mfa_error_already_enabled": "MFA is already enabled.", + "settings.mfa_error_not_enabled": "MFA is not enabled.", + "settings.mfa_error_not_started": "Start MFA setup again.", + "trace.title": "Traceroute, ping and route map", + "trace.subtitle": "Measure latency to a VPS or other server and see where delay appears along the route.", + "trace.target": "Server IP or hostname", + "trace.show_map": "Show route on map", + "trace.run": "Run trace", + "trace.geo_note": "Geolocation is approximate. When the map is enabled, public hop IP addresses are sent to ipwho.is for location lookup; map tiles are loaded from OpenStreetMap.", + "trace.latency_note": "Traceroute measures latency in milliseconds, not throughput in Mbit/s.", + "trace.map": "Route map", + "trace.map_hint": "Interactive map: drag to pan, use the mouse wheel or +/− to zoom, and click a hop for details.", + "trace.hop": "Hop / IP", + "trace.location": "Location", + "trace.avg_rtt": "Avg RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Loss", + "trace.summary_target": "Target", + "trace.summary_ping": "Average ping", + "trace.summary_loss": "Ping loss", + "trace.summary_hops": "Hops", + "trace.no_reply": "No reply", + "trace.private": "Private network", + "trace.unknown": "Unknown", + "trace.running": "Running ping and traceroute… This can take up to a minute.", + "trace.done": "Network trace completed.", + "trace.failed": "Network trace failed", + "trace.partial_geo": "Some public hops could not be geolocated.", + "trace.not_reached": "Target was not reached by traceroute.", + "trace.reached": "Target reached", + "trace.ms": "ms", + "server.tab_trace": "Trace", + "trace.map_controls": "Map controls", + "trace.zoom_in": "Zoom in", + "trace.zoom_out": "Zoom out", + "trace.fit_route": "Fit route", + "trace.fit": "Fit", + "trace.map_click_hint": "Click a hop for IP, location, ASN and RTT details.", + "trace.route_path": "Route", + "trace.ping_ok_trace_filtered": "Target responds to ping; final traceroute hops do not reply.", + "trace.latency_legend": "Latency growth between responding hops", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — increased", + "trace.latency_bad": "Δ RTT > 20 ms — sharp jump" +} diff --git a/app/static/es.json b/app/static/es.json new file mode 100644 index 0000000..8c90bb0 --- /dev/null +++ b/app/static/es.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Crear usuario", + "auth.login_subtitle": "Introduce tu usuario y contraseña de WGTools.", + "auth.login_title": "Iniciar sesión en WGTools", + "auth.password": "Contraseña", + "auth.password_repeat": "Repetir contraseña", + "auth.setup_help": "La primera cuenta tiene acceso completo a WGTools. Puedes crear más usuarios después en Ajustes.", + "auth.setup_subtitle": "Para gestionar el servidor, primero debes crear una cuenta de WGTools.", + "auth.setup_title": "Crear el primer usuario", + "auth.sign_in": "Iniciar sesión", + "auth.sign_out": "Cerrar sesión", + "auth.username": "Nombre de usuario", + "clients.actions": "Acciones", + "clients.add": "+ Añadir cliente", + "clients.address": "Dirección VPN", + "clients.address_hint": "Se sugiere automáticamente la primera dirección libre.", + "clients.allowed_ips_required": "Introduce al menos una red AllowedIPs para la configuración del cliente.", + "clients.basic_connection": "Ajustes de conexión", + "clients.basic_details": "Cliente", + "clients.client": "Cliente", + "clients.client_allowed_ips": "AllowedIPs en la configuración del cliente", + "clients.config_private_warning": "Esta configuración contiene la clave privada del cliente. Guárdala de forma segura.", + "clients.config_title": "Configuración del cliente", + "clients.config_unavailable": "Configuración no disponible", + "clients.connection_direct": "Directamente a WGTools", + "clients.connection_path": "Ruta de conexión", + "clients.connection_relay": "Relay VPS", + "clients.connection_via": "Conectar a través de", + "clients.connection_via_hint": "Elige la entrada pública usada por el cliente. Relay solo aparece si está instalado en la interfaz WireGuard seleccionada.", + "clients.copy_config": "Copiar", + "clients.copy_done": "Configuración copiada", + "clients.create_subtitle": "Crea un par WireGuard y genera su configuración de cliente.", + "clients.create_title": "Crear cliente", + "clients.creating": "Generando claves y aplicando cliente…", + "clients.day_fri": "Vie", + "clients.day_mon": "Lun", + "clients.day_sat": "Sáb", + "clients.day_sun": "Dom", + "clients.day_thu": "Jue", + "clients.day_tue": "Mar", + "clients.day_wed": "Mié", + "clients.delete_confirm": "¿Eliminar este cliente de WireGuard? WGTools creará una copia y eliminará las reglas automáticas asociadas.", + "clients.deleted": "Cliente eliminado", + "clients.dns": "DNS (opcional)", + "clients.dns_hint": "Servidores DNS IPv4 separados por comas.", + "clients.download_config": "Descargar .conf", + "clients.duplicate": "Duplicar", + "clients.duplicate_address_error": "Otro par ya usa esta dirección VPN.", + "clients.duplicate_name_error": "Ya existe un par con ese nombre.", + "clients.duplicate_ready": "Copia lista. WGTools asignó un nombre y una dirección VPN nuevos. Revisa los ajustes antes de guardar.", + "clients.duplicate_site_hint": "Se han borrado las redes remotas para evitar rutas duplicadas. Introduce las redes del nuevo par Site-to-site.", + "clients.duplicate_suffix": "copia", + "clients.edit_subtitle": "Actualiza el par del servidor. Los cambios se aplican sin reiniciar WireGuard.", + "clients.edit_title": "Editar cliente", + "clients.endpoint": "Endpoint del servidor", + "clients.endpoint_hint": "Para clientes remotos, usa la IP pública o el dominio que redirige el puerto WireGuard a este servidor.", + "clients.existing": "Par existente", + "clients.expiration": "Duración del acceso", + "clients.expiration_action": "Al caducar", + "clients.expiration_action_hint": "Si se desmarca, el cliente sigue en WGTools pero pierde acceso a WireGuard. Elige una nueva duración o Sin caducidad y guarda para restaurarlo.", + "clients.expiration_datetime": "Caduca el", + "clients.expiration_datetime_hint": "Usa la fecha y hora locales del navegador.", + "clients.expiration_delete": "Eliminar cliente", + "clients.expiration_future_required": "Elige una fecha y hora futuras.", + "clients.expiration_hint": "Al caducar, WGTools ejecuta la acción elegida en el siguiente minuto. Antes crea una copia de WireGuard.", + "clients.expire_1d": "1 día", + "clients.expire_1h": "1 hora", + "clients.expire_3h": "3 horas", + "clients.expire_6h": "6 horas", + "clients.expire_custom": "Fecha y hora personalizadas", + "clients.expire_never": "Sin caducidad", + "clients.expired": "Caducado", + "clients.expired_disabled_hint": "El acceso ha caducado. El cliente se conserva, pero WireGuard está deshabilitado. Elige otra duración o Sin caducidad y guarda.", + "clients.expired_disabled_short": "Caducado · desactivado", + "clients.expired_disabled_status": "Caducado", + "clients.expires_days": "Caduca en {n} d", + "clients.expires_hours": "Caduca en {n} h", + "clients.expires_minutes": "Caduca en {n} min", + "clients.generated_config": "Configuración del cliente generada", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 segundos es un buen valor por defecto para clientes tras NAT.", + "clients.local_access_exceptions": "Direcciones locales permitidas", + "clients.local_access_exceptions_hint": "IP o CIDR opcionales accesibles aunque su red local o Site-to-site esté bloqueada. Sepáralos por comas.", + "clients.managed": "Gestionado por WGTools", + "clients.name": "Nombre", + "clients.no_peers": "No se encontraron pares", + "clients.peers": "Pares", + "clients.peers_subtitle": "Los cambios se respaldan y aplican con wg syncconf sin reiniciar la interfaz WireGuard.", + "clients.protected_networks_reference": "Redes locales bloqueadas (referencia)", + "clients.protected_networks_reference_hint": "Estas redes no se escriben en AllowedIPs. La política del servidor WGTools bloquea su acceso; arriba pueden permitirse direcciones individuales.", + "clients.psk": "Clave precompartida (PSK)", + "clients.psk_enable": "Usar una clave WireGuard precompartida adicional", + "clients.psk_hint": "Recomendado. Añade un secreto simétrico al handshake WireGuard. Los clientes estándar lo admiten; WGTools incluye el PSK en la configuración y el QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generando QR…", + "clients.quick_search": "Búsqueda rápida", + "clients.quick_search_clear": "Borrar búsqueda", + "clients.quick_search_empty": "Ningún cliente coincide", + "clients.relay_endpoint_note": "La configuración generada se conectará a {endpoint}. El servidor WireGuard sigue en este host WGTools.", + "clients.relay_required": "Elige un Relay VPS para este cliente.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "no disponible", + "clients.relay_vps": "Relay VPS", + "clients.relay_vps_hint": "El endpoint del cliente se genera automáticamente desde este Relay.", + "clients.remote_hint": "Redes detrás de este par. Una por línea o separadas por comas.", + "clients.remote_networks": "Redes remotas", + "clients.remote_required": "Introduce al menos una red remota para el par Site-to-site.", + "clients.required": "Se requieren nombre y dirección VPN.", + "clients.route_custom": "Personalizada", + "clients.route_full": "Túnel completo", + "clients.route_full_except_local": "Túnel completo excepto redes locales", + "clients.route_hint": "Solo estas redes se escriben en AllowedIPs de la configuración del cliente.", + "clients.route_preset": "Tráfico por VPN", + "clients.route_vpn": "Solo red VPN", + "clients.route_vpn_lan": "VPN + LAN local", + "clients.saved": "Cliente guardado", + "clients.schedule_blocked_short": "Horario · bloqueado", + "clients.schedule_blocked_status": "Bloqueado por horario", + "clients.schedule_days": "Días permitidos", + "clients.schedule_days_required": "Elige al menos un día para el horario.", + "clients.schedule_disabled_hint": "Este cliente está bloqueado por su horario. WGTools restaurará el par automáticamente en el próximo periodo permitido.", + "clients.schedule_enable": "Limitar acceso por horario", + "clients.schedule_from": "Acceso desde", + "clients.schedule_hint": "WGTools puede deshabilitar y restaurar el cliente en días y horas seleccionados sin cambiar su configuración.", + "clients.schedule_short": "Horario", + "clients.schedule_time_required": "Define las horas de inicio y fin del horario.", + "clients.schedule_timezone_hint": "El horario usa la hora local del servidor WireGuard. Admite periodos nocturnos como 22:00–06:00.", + "clients.schedule_title": "Horario de acceso", + "clients.schedule_to": "Acceso hasta", + "clients.security_access": "Seguridad y horario de acceso", + "clients.server_host": "Dirección / dominio del servidor", + "clients.server_host_hint": "IP pública o dominio usado por el cliente. Se sugieren valores anteriores.", + "clients.server_host_required": "Se requiere dirección / dominio del servidor para generar la configuración.", + "clients.server_peer": "Par servidor", + "clients.server_port": "Puerto WireGuard", + "clients.server_port_hint": "Se obtiene automáticamente de la configuración del servidor.", + "clients.site_to_site": "Sitio a sitio", + "clients.status": "Estado", + "clients.subtitle": "Pares WireGuard, estado en directo y gestión de configuraciones de clientes.", + "clients.tab_basic": "Básico", + "clients.tab_config": "Configuración", + "clients.tab_policy": "Políticas", + "clients.tab_security": "Seguridad", + "clients.title": "Clientes", + "clients.type": "Tipo", + "clients.unmanaged_note": "Este par existía antes de WGTools. Su clave privada no se puede recuperar. WGTools puede editarlo en el servidor pero no generar su configuración de cliente ni QR.", + "clients.updating": "Actualizando cliente…", + "common.actions": "Acciones", + "common.ago": "hace", + "common.cancel": "Cancelar", + "common.checking": "Comprobando…", + "common.close": "Cerrar", + "common.config": "Configuración", + "common.delete": "Eliminar", + "common.disabled": "Desactivado", + "common.edit": "Editar", + "common.enabled": "Activado", + "common.loading": "Cargando…", + "common.never": "Nunca", + "common.no": "No", + "common.not_configured": "Sin configurar", + "common.not_installed": "No instalado", + "common.offline": "desconectado", + "common.online": "conectado", + "common.refresh": "Actualizar", + "common.running": "En ejecución", + "common.save": "Guardar", + "common.stopped": "Detenido", + "common.total": "Total", + "common.unknown": "Desconocido", + "common.updated": "Actualizado", + "common.yes": "Sí", + "dashboard.active_peers": "Pares activos", + "dashboard.active_peers_subtitle": "Datos en directo de wg show.", + "dashboard.activity": "Resumen del sistema", + "dashboard.activity_subtitle": "Comprobaciones de solo lectura de WireGuard en ejecución.", + "dashboard.cores": "núcleos", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Últimas 24 h", + "dashboard.history_avg": "Prom.", + "dashboard.history_max": "Máx.", + "dashboard.history_min": "Mín.", + "dashboard.history_now": "ahora", + "dashboard.memory": "Memoria", + "dashboard.network": "Red", + "dashboard.peers": "Pares", + "dashboard.quick_search": "Búsqueda rápida", + "dashboard.quick_search_clear": "Borrar búsqueda", + "dashboard.quick_search_empty": "Ningún par coincide con la búsqueda", + "dashboard.restart": "Reiniciar", + "dashboard.restart_confirm": "¿Reiniciar WireGuard? Los clientes VPN activos se reconectarán automáticamente.", + "dashboard.restart_ok": "WireGuard reiniciado.", + "dashboard.routing": "Enrutamiento", + "dashboard.site_to_site": "Sitio a sitio", + "dashboard.start": "Iniciar", + "dashboard.start_ok": "WireGuard iniciado.", + "dashboard.stop": "Detener", + "dashboard.stop_confirm": "¿Detener WireGuard? Se desconectarán los clientes VPN activos.", + "dashboard.stop_ok": "WireGuard detenido.", + "dashboard.subtitle": "Estado del servidor WireGuard, pares y tráfico en directo.", + "dashboard.title": "Panel principal", + "dashboard.traffic": "Tráfico", + "dashboard.uptime": "Tiempo de actividad", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Política de acceso al servidor", + "groups.additional_allowed": "Direcciones adicionales permitidas", + "groups.additional_blocked": "Direcciones adicionales bloqueadas", + "groups.allow": "Permitir", + "groups.allowed": "Permitido", + "groups.allowed_addresses": "Direcciones / redes permitidas", + "groups.apply_current_template": "Aplicar plantilla actual del grupo", + "groups.apply_defaults": "Aplicar plantilla actual del grupo", + "groups.apply_defaults_hint": "Copia rutas, DNS y Keepalive de la plantilla al cliente. Guarda el cliente y genera nueva configuración o QR si debes actualizar el dispositivo.", + "groups.basic": "Información básica", + "groups.block": "Bloquear", + "groups.blocked": "Bloqueado", + "groups.blocked_addresses": "Direcciones / redes bloqueadas", + "groups.client_config_source": "Origen de configuración del cliente", + "groups.client_defaults": "Valores predeterminados del cliente", + "groups.client_group_hint": "Grupo opcional para reutilizar políticas de acceso y valores del cliente. Los grupos corresponden a la interfaz WireGuard seleccionada.", + "groups.config_differs": "La configuración del cliente difiere de la plantilla del grupo. La política del servidor está actualizada, pero el dispositivo requiere una nueva configuración o QR.", + "groups.config_differs_short": "Configuración distinta de la del grupo", + "groups.create": "Crear grupo", + "groups.create_title": "Crear grupo", + "groups.created": "Grupo creado", + "groups.creating": "Creando grupo…", + "groups.defaults_applied": "Plantilla del grupo aplicada. Guarda el cliente para conservarla.", + "groups.defaults_hint": "Define qué tráfico envía el cliente mediante WireGuard. La política del servidor determina los accesos permitidos. Los cambios de plantilla nunca modifican configuraciones ya instaladas.", + "groups.delete_message": "¿Eliminar «{name}»? Las configuraciones de clientes nunca se borran con el grupo.", + "groups.delete_move": "Mover sus clientes a otro grupo", + "groups.delete_title": "Eliminar grupo de clientes", + "groups.delete_unassign": "Quitar la asignación de grupo a sus clientes", + "groups.deleted": "Grupo eliminado", + "groups.deleting": "Actualizando clientes y eliminando grupo…", + "groups.description": "Descripción", + "groups.edit_title": "Editar grupo", + "groups.editor_subtitle": "Un grupo combina una política de acceso activa con una plantilla de configuración de clientes.", + "groups.effective_allow": "Excepciones permitidas", + "groups.effective_deny": "Excepciones bloqueadas", + "groups.effective_policy": "Política efectiva del servidor", + "groups.empty": "Aún no hay grupos de clientes. Crea uno para reutilizar políticas y configuraciones predeterminadas.", + "groups.group": "Grupo", + "groups.inherit": "Heredar", + "groups.internet_access": "Acceso a Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Redes locales", + "groups.local_short": "Local", + "groups.manage": "Grupos", + "groups.members_count": "{count} clientes", + "groups.name": "Nombre", + "groups.name_required": "Se requiere el nombre del grupo.", + "groups.new_client_defaults": "Plantilla de configuración del cliente", + "groups.new_clients_short": "Clientes nuevos", + "groups.no_group": "Sin grupo", + "groups.none": "Ninguno", + "groups.override_client_config": "Anular la plantilla de grupo para este cliente", + "groups.override_client_config_hint": "Desactivado: rutas, DNS y Keepalive vienen del grupo. Activado: el cliente conserva sus valores. Las excepciones de política del servidor siguen independientes.", + "groups.policy_addresses_hint": "Direcciones IPv4 o CIDR separados por comas. Las excepciones del cliente prevalecen sobre las del grupo.", + "groups.policy_custom": "Política personalizada", + "groups.policy_inherit": "Usar política del grupo", + "groups.policy_mode": "Origen de la política", + "groups.policy_mode_hint": "La política del grupo se hereda por defecto. Las excepciones del cliente no modifican el grupo.", + "groups.routes_required": "Las rutas del cliente no pueden estar vacías.", + "groups.subtitle": "Reutiliza políticas de acceso y valores predeterminados para los clientes de la interfaz WireGuard elegida.", + "groups.title": "Grupos de clientes", + "groups.traffic_through_vpn": "Tráfico por VPN", + "groups.updated": "Grupo actualizado", + "groups.updating": "Actualizando política del grupo…", + "help.example_note": "Todas las direcciones, interfaces, nombres de pares y dominios de los ejemplos son ficticios. Sustitúyelos por los datos de tu red.", + "help.navigation": "Navegación de ayuda", + "help.open": "Abrir ayuda", + "help.subtitle": "Ayuda clara para Panel, Servidor, Clientes y Ajustes con ejemplos prácticos.", + "help.title": "Ayuda de WGTools", + "interfaces.add": "+ Añadir interfaz", + "interfaces.create": "Crear interfaz", + "interfaces.create_confirm": "¿Crear e iniciar la interfaz {name}?", + "interfaces.create_failed": "No se pudo crear la interfaz", + "interfaces.create_hint": "Antes de crear la configuración, WGTools comprueba que la red VPN, el puerto UDP y la tabla de enrutamiento no entren en conflicto con otras interfaces WireGuard.", + "interfaces.create_subtitle": "Crea una interfaz WireGuard independiente con su propio grupo de direcciones, puerto UDP y opciones de enrutamiento.", + "interfaces.create_title": "Añadir interfaz WireGuard", + "interfaces.created": "Interfaz creada correctamente.", + "interfaces.creating": "Generando claves, guardando configuración e iniciando WireGuard…", + "interfaces.current": "Actual", + "interfaces.delete": "Eliminar", + "interfaces.delete_confirm": "¿Eliminar la interfaz {name}? Se borrarán su configuración WireGuard y todos sus pares. Antes se creará una copia.", + "interfaces.delete_failed": "No se pudo eliminar la interfaz", + "interfaces.delete_last": "No se puede eliminar aquí la última interfaz WireGuard configurada.", + "interfaces.delete_tooltip": "Eliminar esta interfaz WireGuard", + "interfaces.deleted": "Interfaz eliminada. Copia: {backup}", + "interfaces.deleting": "Deteniendo WireGuard y eliminando interfaz…", + "interfaces.display_name": "Nombre visible", + "interfaces.display_name_edit_hint": "Solo nombre visible: el nombre de la interfaz Linux no cambia.", + "interfaces.display_name_hint": "Nombre opcional, p. ej. Trabajo o Contratistas.", + "interfaces.identity": "Identidad de la interfaz", + "interfaces.none": "No se encontraron interfaces WireGuard", + "interfaces.none_configured": "Aún no hay interfaces WireGuard configuradas.", + "interfaces.peers_short": "pares", + "interfaces.rename_failed": "No se pudo guardar el nombre de la interfaz.", + "interfaces.select": "Seleccionar", + "interfaces.subtitle": "Cada interfaz tiene su red VPN, puerto, pares y políticas. Selecciona una para gestionarla en WGTools.", + "interfaces.switch_title": "Interfaces WireGuard", + "interfaces.system_name": "Nombre del sistema", + "interfaces.system_name_hint": "Nombre de la interfaz Linux, p. ej. wg1. No se puede cambiar después.", + "interfaces.title": "Interfaces WireGuard", + "interfaces.unique_port_hint": "Cada interfaz WireGuard del servidor debe usar un puerto UDP distinto.", + "interfaces.unique_table_hint": "WGTools recomienda una tabla de rutas distinta por interfaz. Déjala vacía para el enrutamiento normal.", + "nav.clients": "Clientes", + "nav.dashboard": "Panel principal", + "nav.server": "Servidor", + "nav.settings": "Configuración", + "server.access_apply_confirm": "¿Guardar y aplicar esta regla de firewall? WireGuard se reiniciará brevemente y se creará una copia.", + "server.access_rule_deleted": "Regla de acceso eliminada.", + "server.access_rule_help": "Crea una regla FORWARD sin editar comandos iptables manualmente.", + "server.access_rule_order_hint": "WGTools inserta reglas al inicio de FORWARD para aplicar restricciones antes de las reglas VPN ACCEPT generales.", + "server.access_rule_saved": "Regla de acceso guardada y aplicada.", + "server.action": "Acción", + "server.action_hint": "REJECT notifica el rechazo al cliente; DROP descarta sin respuesta; ACCEPT permite explícitamente.", + "server.add_access_rule": "Añadir regla de acceso", + "server.add_route": "Añadir ruta", + "server.address": "Dirección", + "server.any": "Cualquiera", + "server.any_protocol": "Cualquiera", + "server.apply_confirm": "¿Guardar y aplicar los ajustes del servidor? WireGuard se reiniciará brevemente. Se creará una copia y, si falla el arranque, WGTools restaurará la configuración anterior.", + "server.apply_settings": "Guardar y aplicar", + "server.applying_rule": "Creando copia y aplicando…", + "server.applying_settings": "Validando ajustes, creando copia y aplicando…", + "server.basic_settings": "Ajustes básicos", + "server.config_tab_help": "Abrir el editor de configuración sin procesar de la interfaz WireGuard seleccionada.", + "server.create_confirm": "¿Crear e iniciar el servidor WireGuard con estos ajustes?", + "server.create_server": "Crear servidor", + "server.create_step_conf": "Crear configuración de la interfaz WireGuard con permisos 600.", + "server.create_step_forward": "Configurar reenvío, NAT y enrutamiento por políticas opcional.", + "server.create_step_key": "Generar nuevo par de claves del servidor.", + "server.create_step_start": "Habilitar e iniciar la interfaz wg-quick seleccionada.", + "server.create_subtitle": "WireGuard está instalado, pero la interfaz seleccionada aún no está configurada.", + "server.create_success": "Servidor WireGuard creado correctamente.", + "server.create_title": "Crear servidor WireGuard", + "server.creating": "Generando claves, escribiendo configuración e iniciando WireGuard…", + "server.custom_preserved": "Se conservan bloques de pares, rutas Site-to-site y reglas PostUp/PostDown no gestionadas por estos campos.", + "server.delete_access_confirm": "¿Eliminar esta regla de acceso y aplicar el cambio?", + "server.delete_route_confirm": "¿Eliminar esta ruta personalizada y aplicar el cambio?", + "server.destination": "Destino", + "server.destination_hint": "Vacío = cualquiera. Admite IP, CIDR o rango de IP. Separa destinos con comas.", + "server.destination_port": "Puerto de destino", + "server.destination_port_hint": "Opcional. Puerto como 443 o rango 10000:20000. Selecciona antes TCP o UDP.", + "server.details": "Detalles", + "server.dev_word": "dev", + "server.diagnostics": "Diagnóstico", + "server.diagnostics_done": "Diagnóstico completado", + "server.diagnostics_subtitle": "Comprobaciones actuales del sistema. No se cambia la configuración.", + "server.direction": "Hook", + "server.edit_access_rule": "Editar regla de acceso", + "server.edit_route": "Editar ruta", + "server.edit_server": "Editar servidor", + "server.edit_subtitle": "Editar ajustes generales WireGuard, rutas y NAT. Se conservan los pares y reglas personalizadas.", + "server.edit_title": "Ajustes del servidor", + "server.edit_warning": "Aplicar cambios de interfaz, rutas o firewall reinicia brevemente WireGuard. Los pares activos se reconectarán automáticamente.", + "server.enable_forwarding": "Habilitar reenvío IPv4", + "server.enable_nat": "Habilitar NAT / Masquerade", + "server.firewall": "Cortafuegos y NAT", + "server.firewall_subtitle": "Reglas detectadas de hooks WireGuard.", + "server.firewall_subtitle_v08": "Reglas de reenvío/NAT y acceso de la interfaz. Las simples se gestionan aquí y las avanzadas en el editor sin procesar.", + "server.forward_from_vpn": "Permitir reenvío desde VPN", + "server.forward_to_vpn": "Permitir reenvío hacia VPN", + "server.forwarding_section": "Reenvío y NAT", + "server.gateway": "Puerta de enlace", + "server.gateway_hint": "Solo necesario si se usa una tabla de enrutamiento por políticas.", + "server.install_success": "WireGuard instalado correctamente.", + "server.install_wireguard": "Instalar WireGuard", + "server.install_wireguard_help": "Ejecuta apt update e instala WireGuard y herramientas de red necesarias.", + "server.install_wireguard_title": "Instalar WireGuard", + "server.installing": "Instalando WireGuard… Puede tardar un minuto.", + "server.interface": "Interfaz", + "server.interface_hint": "WGTools gestiona actualmente esta interfaz.", + "server.interface_name": "Interfaz", + "server.interface_section": "Interfaz WireGuard", + "server.ip_forwarding": "Reenvío IPv4", + "server.kind": "Tipo", + "server.listen_port": "Puerto de escucha", + "server.local_network": "Red local", + "server.local_network_hint": "Ruta opcional añadida a la tabla de políticas.", + "server.managed_automatically": "Gestionado automáticamente", + "server.nat": "NAT / Masquerade", + "server.network": "Red", + "server.network_settings": "Red y NAT", + "server.no_firewall": "No se encontraron reglas de firewall", + "server.no_routes": "No se encontraron rutas", + "server.not_configured": "Sin configurar", + "server.not_set": "Sin definir", + "server.policy_disabled_hint": "Desactiva para rutas normales del sistema. Habilita solo si esta VPN necesita su tabla de rutas por origen.", + "server.policy_enabled": "Habilitar enrutamiento por políticas", + "server.policy_table": "Tabla de políticas", + "server.policy_table_hint": "Déjalo vacío para rutas normales; usa p. ej. 200 para rutas por origen.", + "server.port_word": "puerto", + "server.private_hidden": "Configurado (oculto)", + "server.private_key": "Clave privada", + "server.protocol": "Protocolo", + "server.route_apply_confirm": "¿Guardar y aplicar esta ruta? WireGuard se reiniciará brevemente tras crear una copia.", + "server.route_custom": "Personalizada", + "server.route_deleted": "Ruta eliminada.", + "server.route_device_hint": "Interfaz de salida opcional, p. ej. wg0 o enp6s18.", + "server.route_editor_help": "Añade una ruta instalada cuando inicia WireGuard y eliminada cuando se detiene.", + "server.route_gateway_hint": "Puerta de enlace de siguiente salto opcional. Se requiere puerta o interfaz.", + "server.route_managed_peer": "Par Site-to-site", + "server.route_managed_server": "Ajuste del servidor", + "server.route_network_hint": "Red IPv4 como 10.20.0.0/24 o 'default'.", + "server.route_saved": "Ruta guardada y aplicada.", + "server.route_table_hint": "Usa 'main' para rutas normales o una tabla numérica como 200.", + "server.route_type": "Tipo", + "server.routes": "Rutas detectadas", + "server.routes_subtitle": "Rutas extraídas de PostUp/PostDown y del estado actual de rutas por políticas.", + "server.routes_subtitle_v08": "Rutas del servidor, Site-to-site y personalizadas de la interfaz elegida. Aquí puedes añadir, editar o eliminar rutas propias.", + "server.routing": "Enrutamiento", + "server.routing_section": "Enrutamiento", + "server.rule": "Regla", + "server.rule_access": "Regla de acceso", + "server.rule_advanced": "Avanzado", + "server.rule_apply_warning": "Aplicar una ruta o regla de firewall reinicia brevemente WireGuard. WGTools crea una copia y restaura automáticamente si falla el arranque.", + "server.rule_client_exception": "Excepción de cliente", + "server.rule_client_policy": "Política del cliente", + "server.rule_managed_server": "Ajuste del servidor", + "server.rule_type": "Tipo", + "server.run_diagnostics": "Ejecutar diagnóstico", + "server.save_apply": "Guardar y aplicar", + "server.save_config": "SaveConfig", + "server.server_address": "Dirección VPN del servidor", + "server.server_address_hint": "Normalmente la primera dirección utilizable de la red VPN.", + "server.settings_applied": "Ajustes del servidor guardados y aplicados correctamente.", + "server.settings_apply_failed": "No se pudieron aplicar los ajustes del servidor", + "server.setup_required": "Configuración necesaria", + "server.source": "Origen", + "server.source_hint": "Vacío = cualquiera. Admite IP, CIDR o rango como 10.0.0.100-10.0.0.120.", + "server.subtitle": "Instalación, configuración inicial y configuración actual del servidor WireGuard.", + "server.tab_config": "Configuración", + "server.tab_interface": "Interfaz", + "server.tab_routing": "Enrutamiento", + "server.tab_vps": "VPS", + "server.table": "Tabla", + "server.tabs_aria": "Secciones de ajustes del servidor", + "server.title": "Servidor", + "server.uplink": "Interfaz de enlace ascendente", + "server.use_raw_editor": "Usar editor sin procesar", + "server.via": "Vía / Dispositivo", + "server.via_word": "via", + "server.vpn_network": "Red VPN", + "server.vpn_network_hint": "Las direcciones de clientes se asignarán desde esta red.", + "server.vpn_pool": "Grupo de direcciones VPN", + "server.wg_not_installed": "WireGuard no está instalado", + "server.wg_not_installed_subtitle": "WGTools puede instalar automáticamente los paquetes Debian necesarios.", + "server.what_happens": "Qué hará WGTools", + "settings.about": "Acerca de", + "settings.add_user": "Añadir usuario", + "settings.advanced": "Avanzado", + "settings.advanced_subtitle": "Acceso directo a herramientas avanzadas de configuración WireGuard.", + "settings.appearance": "Apariencia", + "settings.applying_config": "Validando configuración, creando copia y aplicando…", + "settings.backup_count": "Copias guardadas", + "settings.backup_retention": "Copias a conservar", + "settings.backup_retention_help": "Las copias automáticas antiguas se eliminan tras crear una nueva. De 1 a 200 archivos.", + "settings.backups": "Copias de configuración", + "settings.backups_always_on": "Activado", + "settings.backups_subtitle": "WGTools crea automáticamente una copia antes de modificar la configuración. Las copias automáticas no se pueden desactivar.", + "settings.change_password": "Cambiar contraseña", + "settings.check_updates": "Buscar actualizaciones", + "settings.config_applied": "Configuración guardada y aplicada correctamente.", + "settings.config_applied_restarted": "Configuración aplicada y WireGuard reiniciado.", + "settings.config_applied_stopped": "Configuración guardada. WireGuard estaba detenido y sigue detenido.", + "settings.config_apply_failed": "No se pudo aplicar la configuración", + "settings.config_load_failed": "No se pudo cargar la configuración", + "settings.current_user": "Usuario actual", + "settings.current_version": "Versión actual", + "settings.audit_action": "Acción", + "settings.audit_empty": "Aún no hay eventos de auditoría", + "settings.audit_log": "Auditoría", + "settings.audit_log_subtitle": "Acciones del panel, acceso, Telegram e historial de conexiones WireGuard. Nunca se guardan secretos.", + "settings.audit_object": "Objeto", + "settings.audit_result": "Resultado", + "settings.audit_retention_note": "Retención: 30 días", + "settings.audit_search": "Búsqueda rápida", + "settings.audit_search_clear": "Borrar búsqueda", + "settings.audit_search_empty": "Ningún evento de auditoría coincide", + "settings.audit_time": "Fecha / hora", + "settings.audit_user": "Usuario", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Regla de acceso creada", + "audit.action.access_rule.deleted": "Regla de acceso eliminada", + "audit.action.access_rule.updated": "Regla de acceso actualizada", + "audit.action.auth.first_user_created": "Primer usuario creado", + "audit.action.auth.login": "Sesión iniciada", + "audit.action.auth.login_failed": "Error de inicio de sesión", + "audit.action.auth.logout": "Sesión cerrada", + "audit.action.backup.full_created": "Copia de seguridad completa creada", + "audit.action.backup.full_restored": "Copia de seguridad completa restaurada", + "audit.action.client.config_downloaded": "Configuración del cliente descargada", + "audit.action.client.config_viewed": "Configuración del cliente consultada", + "audit.action.client.created": "Cliente creado", + "audit.action.client.deleted": "Cliente eliminado", + "audit.action.client.qr_viewed": "Código QR del cliente consultado", + "audit.action.client.updated": "Cliente actualizado", + "audit.action.client_group.created": "Grupo de clientes creado", + "audit.action.client_group.deleted": "Grupo de clientes eliminado", + "audit.action.client_group.updated": "Grupo de clientes actualizado", + "audit.action.interface.created": "Interfaz creada", + "audit.action.interface.deleted": "Interfaz eliminada", + "audit.action.interface.renamed": "Interfaz renombrada", + "audit.action.route.created": "Ruta creada", + "audit.action.route.deleted": "Ruta eliminada", + "audit.action.route.updated": "Ruta actualizada", + "audit.action.server.created": "Servidor creado", + "audit.action.server.raw_config_applied": "Configuración sin procesar aplicada", + "audit.action.server.settings_applied": "Ajustes del servidor aplicados", + "audit.action.settings.updated": "Ajustes del panel actualizados", + "audit.action.telegram.action_denied": "Acción de Telegram denegada", + "audit.action.telegram.action_failed": "Error de acción de Telegram", + "audit.action.telegram.connection_test": "Prueba de conexión de Telegram", + "audit.action.telegram.settings_updated": "Ajustes de Telegram actualizados", + "audit.action.update.checked": "Actualización comprobada", + "audit.action.update.scheduled": "Actualización programada", + "audit.action.update.backup_created": "Copia previa a la actualización", + "audit.action.update.completed": "Actualización completada", + "audit.action.update.failed": "Error de actualización", + "audit.action.update.rollback_completed": "Versión anterior restaurada", + "audit.action.update.rollback_failed": "Error al revertir la actualización", + "audit.action.user.created": "Usuario creado", + "audit.action.user.deleted": "Usuario eliminado", + "audit.action.user.password_changed": "Contraseña de usuario cambiada", + "audit.action.vps.candidate_deleted": "Candidato VPS eliminado", + "audit.action.vps.candidate_saved": "Candidato VPS guardado", + "audit.action.vps.detached": "Relay VPS desconectado", + "audit.action.vps.relay_installed": "Relay VPS instalado", + "audit.action.wireguard.client_connected": "Cliente WireGuard conectado", + "audit.action.wireguard.installed": "WireGuard instalado", + "audit.action.wireguard.restarted": "WireGuard reiniciado", + "audit.action.wireguard.started": "WireGuard iniciado", + "audit.action.wireguard.stopped": "WireGuard detenido", + "audit.result.applied": "aplicado", + "audit.result.available": "disponible", + "audit.result.changed": "cambiado", + "audit.result.created": "creado", + "audit.result.current": "actual", + "audit.result.deleted": "eliminado", + "audit.result.detached": "desconectado", + "audit.result.denied": "denegado", + "audit.result.downloaded": "descargado", + "audit.result.endpoint": "Punto final", + "audit.result.error": "Error", + "audit.result.installed": "instalado", + "audit.result.invalid_credentials": "credenciales no válidas", + "audit.result.ok": "Correcto", + "audit.result.queued": "en cola", + "audit.result.restarted": "reiniciado", + "audit.result.restored": "restaurado", + "audit.result.rotated": "renovado", + "audit.result.saved": "guardado", + "audit.result.shown": "mostrado", + "audit.result.started": "iniciado", + "audit.result.stopped": "detenido", + "audit.result.updated": "actualizado", + "settings.delete_user": "Eliminar", + "settings.delete_user_confirm": "¿Eliminar al usuario {name}?", + "settings.edit_raw_config": "Editar configuración de interfaz", + "settings.expert_mode": "Experto", + "settings.full_backup_component_clients": "Metadatos de clientes gestionados, claves privadas, PSK, caducidad y grupos para regenerar configuraciones y QR.", + "settings.full_backup_component_db": "Base de datos WGTools: usuarios, preferencias, correo/SMTP, Telegram y estado guardado de VPS Relay.", + "settings.full_backup_component_relay": "Datos de recuperación VPS Relay: ID de controlador/tenant, token de administración y clave de transporte doméstico. Tras restaurar, WGTools puede reconstruir el transporte y reconectar el tenant conservado.", + "settings.full_backup_component_system": "Archivo sysctl IPv4 de WGTools, nombres visibles de interfaces y políticas/plantillas de grupos, si existen. Se excluye deliberadamente el historial automático por interfaz.", + "settings.full_backup_component_wg": "Todas las configuraciones WireGuard detectadas en /etc/wireguard/, incluido su estado activo/detenido.", + "settings.full_backup_create_failed": "No se pudo crear la copia completa", + "settings.full_backup_creating": "Creando copia completa…", + "settings.full_backup_download": "Crear", + "settings.full_backup_downloaded": "Copia creada y descargada. Guárdala de forma segura.", + "settings.full_backup_downloaded_short": "Copia completa descargada.", + "settings.full_backup_help": "Crea una copia portátil de WGTools para migración o recuperación: configuraciones WireGuard, usuarios, ajustes, grupos, clientes gestionados y datos para reconectar tenants VPS Relay.", + "settings.full_backup_no_file": "No se seleccionó ninguna copia", + "settings.full_backup_restore": "Restaurar", + "settings.full_backup_restore_confirm": "¿Restaurar esta copia completa de WGTools? Se restaurarán usuarios, ajustes, clientes gestionados y configuraciones WireGuard incluidos. Las interfaces pueden reiniciarse. WGTools crea una copia de seguridad previa y revierte automáticamente si falla.", + "settings.full_backup_restore_failed": "Error de restauración", + "settings.full_backup_restored": "Copia restaurada correctamente. Inicia sesión con una cuenta de esa copia.", + "settings.full_backup_restored_short": "Copia restaurada.", + "settings.full_backup_restoring": "Validando copia, creando respaldo de seguridad y restaurando…", + "settings.full_backup_secret_warning": "Este archivo contiene datos sensibles: claves privadas WireGuard y clientes, PSK, hashes de contraseñas WGTools, token de Telegram y contraseña SMTP guardada. Protégelo como una contraseña y nunca lo adjuntes a incidencias o chats públicos.", + "settings.full_backup_select": "Seleccionar", + "settings.full_backup_title": "Copia completa y restauración", + "settings.full_mode": "Gestión del servidor y clientes habilitada", + "settings.interface_help": "La interfaz WireGuard gestionada se elige al desplegar WGTools.", + "settings.language": "Idioma", + "settings.last_backup": "Última copia", + "settings.latest_version": "Última versión", + "settings.loading_config": "Cargando configuración…", + "settings.mode": "Modo", + "settings.never_logged_in": "Nunca", + "settings.new_password": "Nueva contraseña", + "settings.no_backups": "Aún no hay copias", + "settings.online_help": "Un par está en línea si el último handshake es más reciente que este valor. 30–3600 segundos.", + "settings.online_threshold": "Umbral de conexión", + "settings.open_release": "Abrir versión", + "settings.password_changed": "Contraseña cambiada.", + "settings.passwords_mismatch": "Las contraseñas no coinciden.", + "settings.project_github": "Proyecto / GitHub", + "settings.raw_config_confirm": "¿Guardar y aplicar la configuración WireGuard? Se reiniciará la interfaz seleccionada. Antes se creará una copia y WGTools revertirá automáticamente si el arranque falla.", + "settings.raw_config_help": "Abrir la configuración de origen de la interfaz WireGuard elegida.", + "settings.raw_config_title": "Configuración WireGuard sin procesar", + "settings.raw_config_warning": "Modo experto: esta es la configuración real del servidor WireGuard con clave privada y PSK de pares. Guardar y aplicar reinicia la interfaz. WGTools crea antes una copia y revierte si el arranque falla.", + "settings.readonly_mode": "Gestión de clientes habilitada", + "settings.refresh_help": "Frecuencia de actualización de datos de estado. De 2 a 60 segundos.", + "settings.refresh_interval": "Intervalo de actualización", + "settings.release_notes": "Notas de versión", + "settings.reload_config": "Recargar del disco", + "settings.save_apply": "Guardar y aplicar", + "settings.saved": "Ajustes guardados.", + "settings.saved_reload": "Ajustes guardados. Recargando…", + "settings.saving": "Guardando ajustes…", + "settings.status": "Actualización de estado", + "settings.status_help": "Frecuencia de actualización del panel y estado de los pares.", + "settings.subtitle": "Preferencias de interfaz y ajustes de estado de WGTools.", + "settings.syntax_hint": "Se resaltan secciones, claves, valores y comentarios WireGuard al editar.", + "settings.tab_about": "Acerca de", + "settings.tab_backups": "Copias", + "settings.tab_general": "General", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Usuarios", + "settings.tabs_aria": "Secciones de ajustes", + "settings.telegram": "Bot de Telegram", + "settings.telegram_allowed_ids": "ID de usuario de Telegram permitidos", + "settings.telegram_allowed_ids_help": "Un ID numérico por línea. Un /start no autorizado responde con el ID Telegram del remitente para añadirlo aquí.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Conectado", + "settings.telegram_disabled": "Desactivado", + "settings.telegram_dns": "DNS predeterminado del cliente", + "settings.telegram_dns_help": "Direcciones DNS IPv4 opcionales separadas por comas. Se usan en clientes creados por el bot.", + "settings.telegram_enabled": "Activar bot Telegram", + "settings.telegram_endpoint": "Dirección / dominio predeterminado del servidor", + "settings.telegram_endpoint_help": "Se usa cuando el bot crea un cliente. Introduce solo IP o dominio; el puerto WireGuard viene de la configuración del servidor.", + "settings.telegram_language": "Idioma del bot", + "settings.telegram_language_auto": "Auto (idioma de Telegram)", + "settings.telegram_last_poll": "Último contacto con Telegram", + "settings.telegram_not_configured": "Sin configurar", + "settings.telegram_remove_token": "Eliminar token", + "settings.telegram_remove_token_confirm": "¿Eliminar el token guardado de Telegram y deshabilitar el bot?", + "settings.telegram_save": "Guardar ajustes de Telegram", + "settings.telegram_saved": "Ajustes de Telegram guardados.", + "settings.telegram_setup_note": "Crea un bot con @BotFather, guarda su token, habilítalo y envía /start. Si tu ID no está autorizado, WGTools lo mostrará: añádelo a la lista permitida.", + "settings.telegram_status": "Estado del bot", + "settings.telegram_subtitle": "Gestión WireGuard desde Telegram: estado del servidor, clientes, creación/eliminación e inicio/reinicio/parada.", + "settings.telegram_test": "Probar conexión", + "settings.telegram_test_ok": "Conexión Telegram correcta: @{username}", + "settings.telegram_test_recent_ok": "El bot Telegram funciona. La prueba directa expiró, pero el bot contactó con Telegram recientemente.", + "settings.telegram_token": "Token del bot", + "settings.telegram_token_help": "Crea un bot con @BotFather y pega aquí el token Bot API. No se necesitan API ID ni API Hash.", + "settings.telegram_token_keep": "Deja en blanco para conservar el token guardado.", + "settings.telegram_waiting": "Configurado, esperando servicio del bot", + "settings.theme": "Tema", + "settings.theme_dark": "Oscuro", + "settings.theme_light": "Claro", + "settings.theme_system": "Sistema", + "settings.title": "Configuración", + "settings.update_available": "Actualización disponible", + "settings.update_backup_queued": "Actualización en cola. WGTools creará una copia completa automática antes de instalar…", + "settings.update_backup_running": "Creando copia completa antes de actualizar…", + "settings.update_check_failed": "No se pudieron comprobar las actualizaciones", + "settings.update_checking": "Comprobando el último lanzamiento publicado en GitHub…", + "settings.update_confirm": "¿Actualizar WGTools de v{current} a v{latest}? Se crearán una copia completa y otra para revertir. La interfaz web se reiniciará brevemente.", + "settings.update_current": "Actualizado", + "settings.update_downloading": "Descargando y validando la versión de GitHub…", + "settings.update_failed": "La actualización de WGTools falló.", + "settings.update_installing": "Instalando actualización. La interfaz web puede no estar disponible por un momento…", + "settings.update_no_update": "WGTools ya está actualizado.", + "settings.update_not_checked": "Sin comprobar", + "settings.update_queued": "Actualización en cola. Esperando al servicio actualizador…", + "settings.update_rollback_ok": "Se restauró automáticamente la versión anterior de WGTools.", + "settings.update_rolling_back": "Falló la actualización. Restaurando la versión anterior…", + "settings.update_running": "Creando copias de seguridad…", + "settings.update_safety_hint": "Las actualizaciones son opcionales. WGTools crea una copia completa y una para revertir. Si falla, restaura automáticamente la aplicación anterior. WireGuard no se reinicia salvo que la nueva versión modifique expresamente su configuración.", + "settings.update_sidebar": "Nueva versión disponible", + "settings.update_sidebar_hint": "Ajustes → Acerca de", + "settings.update_starting": "Iniciando actualización…", + "settings.update_status_unknown": "Estado de actualización no disponible. Reintentando…", + "settings.update_subtitle": "Información del proyecto, comprobación automática de versiones y actualizaciones seguras desde GitHub Releases.", + "settings.update_success": "WGTools actualizado a v{version}. Recargando…", + "settings.update_wgtools": "Actualizar WGTools", + "settings.user_actions": "Acciones", + "settings.user_created": "Creado", + "settings.user_created_ok": "Usuario creado.", + "settings.user_deleted": "Usuario eliminado.", + "settings.user_equal_rights": "Todos los usuarios WGTools tienen los mismos permisos.", + "settings.user_last_login": "Último inicio de sesión", + "settings.user_name": "Nombre de usuario", + "settings.users": "Usuarios", + "settings.users_subtitle": "Cuentas locales WGTools. El correo es opcional y solo se usa para recuperar la contraseña cuando está habilitado.", + "vps.add": "Añadir VPS", + "vps.add_help": "WGTools usa SSH para comprobar o instalar Relay. Nunca guarda contraseñas ni claves SSH privadas.", + "vps.add_title": "Añadir VPS", + "vps.agent": "Agente Relay", + "vps.agent_found": "Ya instalado", + "vps.agent_will_install": "Se instalará", + "vps.arch": "Arquitectura", + "vps.auth_method": "Autenticación", + "vps.authentication": "Autenticación SSH", + "vps.check": "Comprobar VPS", + "vps.check_failed": "Error al comprobar el VPS", + "vps.check_link": "Comprobar enlace", + "vps.check_ok": "VPS compatible", + "vps.checking": "Comprobando acceso SSH y compatibilidad VPS…", + "vps.connections": "conexiones", + "vps.credentials_not_saved": "Solo se usan para esta comprobación; WGTools no los guarda.", + "vps.delete_candidate": "Quitar", + "vps.delete_installed": "Eliminar VPS", + "vps.delete_installed_confirm": "¿Quitar «{name}» de WGTools? Se desconectará el transporte Relay local, pero se conservarán el agente y el tenant del VPS. Puedes añadirlo otra vez y WGTools reutilizará el Relay existente. Los clientes no podrán usarlo hasta reconectarlo.", + "vps.delete_installed_failed": "No se pudo eliminar el VPS de WGTools", + "vps.delete_installed_ok": "VPS eliminado de WGTools. El Relay remoto se conserva y puede reconectarse.", + "vps.empty_help": "Añade un VPS Debian o Ubuntu para comprobar SSH, compatibilidad del sistema y puertos UDP necesarios.", + "vps.empty_title": "Ningún VPS configurado", + "vps.endpoint": "Endpoint público", + "vps.endpoint_domain": "Dominio (recomendado)", + "vps.endpoint_domain_hint": "Si reemplazas el VPS principal, cambiar DNS puede mantener intactas las configuraciones del cliente.", + "vps.health_failed": "Error al comprobar el enlace Relay", + "vps.host": "IP / nombre de host", + "vps.host_key": "Clave de host SSH", + "vps.identity": "Conexión VPS", + "vps.install_failed": "Error al instalar Relay", + "vps.install_ok": "Relay instalado y enlace de administración protegido verificado", + "vps.install_relay": "Instalar Relay", + "vps.install_title": "Instalar Relay VPS", + "vps.installed": "Instalado", + "vps.installing": "Instalando agente Relay y estableciendo túnel protegido…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Frase de acceso de la clave", + "vps.link_ok": "Enlace Relay correcto", + "vps.multi_tenant_note": "Ya funciona un agente Relay WGTools en este VPS. No se reemplazará: este WGTools tendrá una conexión aislada con claves y puertos UDP propios.", + "vps.name": "Nombre", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Se instalará", + "vps.os": "Sistema operativo", + "vps.password": "Contraseña", + "vps.phase_note": "El agente Relay admite varios controladores WGTools independientes en un VPS. Cada uno tiene conexión, claves y puertos UDP aislados; los existentes no se modifican.", + "vps.port_pair": "Puertos UDP", + "vps.ports_adjusted": "puertos libres seleccionados", + "vps.private_key": "Clave privada", + "vps.privilege": "Privilegios", + "vps.public_endpoint": "Futuro endpoint público", + "vps.ready_help": "Las credenciales SSH solo se usan para comprobar compatibilidad e instalar Relay inmediatamente; no se guardan.", + "vps.reconnect_note": "Se encontró una conexión Relay creada antes por este WGTools. Se reutilizará el mismo tenant sin crear nuevos ni puertos UDP.", + "vps.reconnect_ok": "Relay existente reconectado correctamente", + "vps.reconnect_relay": "Reconectar Relay", + "vps.relay_port": "Puerto UDP Relay", + "vps.remove_confirm": "¿Quitar este candidato VPS? No se han hecho cambios remotos.", + "vps.save_candidate": "Guardar candidato", + "vps.saved": "Candidato VPS guardado", + "vps.ssh": "SSH", + "vps.ssh_key": "Clave SSH", + "vps.ssh_port": "Puerto SSH", + "vps.ssh_user": "Usuario SSH", + "vps.status_candidate": "Listo para instalar", + "vps.status_installed": "Relay conectado", + "vps.subtitle": "Prepara un VPS público para acceso remoto cuando este servidor WGTools no tiene IP pública.", + "vps.tenant": "Conexión", + "vps.title": "Relay VPS", + "vps.transport_port": "Puerto UDP de transporte", + "vps.transport_port_hint": "Puerto UDP separado para el túnel de transporte privado Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Guardado", + "vps.active_short": "Activo", + "dashboard.traffic_reset": "Restablecer", + "dashboard.traffic_reset_confirm": "¿Restablecer los contadores de tráfico WireGuard de esta interfaz? Los contadores de clientes también volverán a cero.", + "dashboard.traffic_reset_done": "Contadores de tráfico restablecidos", + "dashboard.traffic_reset_failed": "No se pudieron restablecer los contadores", + "audit.action.traffic.reset": "Contadores de tráfico restablecidos", + "audit.result.reset": "restablecido", + "server.mtu": "MTU", + "server.mtu_auto": "Automático", + "server.mtu_hint": "Opcional. Déjalo vacío para MTU automática de wg-quick. Usa 1380 o 1420 solo si es necesario por LTE o PPPoE.", + "clients.peer_isolation": "Aislamiento de clientes VPN", + "clients.peer_isolation_enable": "Aislar de otros clientes VPN", + "clients.peer_isolation_hint": "Bloquea el tráfico entre este cliente y otras direcciones del grupo WireGuard. El acceso al servidor, Internet y redes locales o Site-to-site sigue controlado por otras políticas.", + "clients.credentials_rotate": "Claves del cliente", + "clients.credentials_rotate_button": "Renovar claves", + "clients.credentials_rotate_confirm": "¿Generar claves nuevas para este cliente? Si está conectado, su sesión WireGuard se desconectará inmediatamente. Envía después nueva configuración o QR.", + "clients.credentials_rotate_confirm_psk": "¿Generar un nuevo par de claves y un PSK para este cliente? Su sesión WireGuard activa se cortará inmediatamente. Envía después nueva configuración o QR.", + "clients.credentials_rotate_hint": "Renueva PrivateKey/PublicKey y el PSK si está habilitado. Conserva dirección, rutas, grupo, horario, aislamiento y estadísticas.", + "clients.credentials_rotating": "Generando claves nuevas y cerrando la sesión anterior…", + "clients.credentials_rotated": "Claves del cliente cambiadas. Si estaba conectado, su sesión anterior se cortó. La configuración antigua ya no funciona; envía una nueva o QR.", + "clients.credentials_rotated_short": "Claves cambiadas — se requiere nueva configuración", + "audit.action.client.credentials_rotated": "Claves del cliente renovadas", + "clients.credentials_connection_lost": "Se perdió la conexión a WGTools. Si el panel se abrió a través del cliente cuyas claves se renovaron, es normal: su sesión antigua se cerró. Vuelve a entrar por otra vía y genera nueva configuración o QR.", + "nav.navigation": "Navegación principal", + "nav.project_github": "WGTools en GitHub", + "auth.email": "Correo electrónico", + "auth.email_optional_help": "Opcional por ahora. Permite recuperar la contraseña después de configurar el correo.", + "auth.forgot_password": "¿Olvidaste la contraseña?", + "auth.reset_title": "Restablecer contraseña", + "auth.reset_subtitle": "Recibe un código de un solo uso por correo y establece una nueva contraseña de WGTools.", + "auth.reset_identifier": "Usuario o correo", + "auth.reset_identifier_help": "Por privacidad, WGTools siempre muestra la misma respuesta tanto si la cuenta existe como si no.", + "auth.send_reset_code": "Enviar código", + "auth.reset_code_sent_generic": "Si la cuenta existe y tiene correo, se envió un código. Es válido durante 15 minutos.", + "auth.reset_code": "Código de 6 dígitos", + "auth.set_new_password": "Establecer nueva contraseña", + "auth.request_another_code": "Solicitar otro código", + "auth.back_to_login": "Volver al inicio de sesión", + "auth.reset_not_configured": "La recuperación de contraseña por correo no está configurada. Contacta con el administrador de WGTools.", + "settings.tab_mail": "Correo", + "settings.mail": "Correo / SMTP", + "settings.mail_subtitle": "SMTP se usa para recuperar contraseñas.", + "settings.mail_not_configured": "Sin configurar", + "settings.mail_enabled": "Habilitar correo y recuperación de contraseña", + "settings.mail_smtp_host": "Servidor SMTP", + "settings.mail_smtp_port": "Puerto SMTP", + "settings.mail_security": "Cifrado", + "settings.mail_security_none": "Sin cifrado", + "settings.mail_username": "Usuario SMTP", + "settings.mail_username_help": "Se usa para autenticación SMTP y como correo remitente.", + "settings.mail_password": "Contraseña SMTP", + "settings.mail_password_keep": "Deja vacío para conservar la contraseña guardada.", + "settings.mail_from_email": "Correo del remitente", + "settings.mail_from_name": "Nombre del remitente", + "settings.mail_test_recipient": "Destinatario de prueba", + "settings.mail_test_recipient_help": "La prueba utiliza los ajustes SMTP guardados actualmente.", + "settings.mail_remove_password": "Eliminar contraseña", + "settings.mail_test": "Enviar prueba", + "settings.mail_save": "Guardar ajustes de correo", + "settings.mail_enabled_badge": "Activado", + "settings.mail_disabled_badge": "Desactivado", + "settings.mail_saved": "Ajustes de correo guardados.", + "settings.mail_remove_password_confirm": "¿Eliminar la contraseña SMTP guardada y deshabilitar el correo?", + "settings.mail_password_removed": "Contraseña SMTP eliminada y correo deshabilitado.", + "settings.mail_test_recipient_required": "Introduce la dirección de correo del destinatario de prueba.", + "settings.mail_testing": "Enviando correo de prueba…", + "settings.mail_test_ok": "Correo de prueba enviado correctamente.", + "settings.user_email": "Correo electrónico", + "settings.user_email_help": "Opcional. Solo necesario para recuperar la contraseña por cuenta propia.", + "settings.change_email": "Correo electrónico", + "settings.user_email_saved": "Correo guardado.", + "settings.send_password_reset": "Enviar restablecimiento", + "settings.user_reset_mail_not_configured": "Configura y habilita primero el correo.", + "settings.user_reset_email_missing": "Añade primero una dirección de correo.", + "settings.user_reset_confirm": "¿Enviar código de restablecimiento a {name} en {email}?", + "settings.user_reset_sent": "Código de restablecimiento enviado a {email}.", + "audit.action.auth.password_reset_requested": "Restablecimiento de contraseña solicitado", + "audit.action.auth.password_reset_code_sent": "Código de restablecimiento enviado", + "audit.action.auth.password_reset_completed": "Contraseña restablecida", + "audit.action.auth.password_reset_failed": "Error al restablecer la contraseña", + "audit.action.mail.settings_updated": "Configuración de correo actualizada", + "audit.action.mail.test_sent": "Correo de prueba enviado", + "audit.action.mail.test_failed": "Error en el correo de prueba", + "audit.action.user.email_changed": "Correo del usuario cambiado", + "audit.action.user.password_reset_sent": "Restablecimiento enviado al usuario", + "audit.action.user.password_reset_failed": "Error al restablecer la contraseña del usuario", + "audit.result.accepted": "aceptado", + "audit.result.sent": "enviado", + "audit.result.invalid_code": "código no válido", + "common.copy": "Copiar", + "common.copied": "Copiado", + "clients.use_panel_host": "Usar dirección del panel", + "clients.use_panel_host_done": "Dirección del panel insertada: {host}", + "clients.use_panel_host_failed": "No se pudo obtener la dirección del panel de la URL del navegador.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS de Let’s Encrypt integrado para acceso directo a WGTools sin proxy inverso.", + "settings.https_disabled": "Desactivado", + "settings.https_enabled": "Activado", + "settings.https_enable": "Habilitar HTTPS integrado", + "settings.https_type": "Certificado para", + "settings.https_domain": "Dominio", + "settings.https_public_ip": "IP pública", + "settings.https_target": "Dominio o IP pública", + "settings.https_email": "Correo de Let’s Encrypt", + "settings.https_port": "Puerto HTTPS", + "settings.https_port80_note": "El puerto TCP 80 debe ser accesible desde Internet para emitir y renovar el certificado. Abre también el puerto HTTPS elegido para el panel.", + "settings.https_check_ports": "Comprobar puertos", + "settings.https_certificate": "Certificado", + "settings.https_certificate_ready": "Listo", + "settings.https_certificate_missing": "No emitido", + "settings.https_expires": "Válido hasta", + "settings.https_renewal": "Renovación automática", + "settings.https_renewal_enabled": "Activado", + "settings.https_renewal_disabled": "Desactivado", + "settings.https_certificate_path": "Certificado", + "settings.https_private_key_path": "Clave privada", + "settings.https_issue": "Obtener / renovar certificado", + "settings.https_port_free": "Libre", + "settings.https_port_busy": "Ocupado", + "settings.https_ports_checked": "Comprobación de puertos terminada.", + "settings.https_target_email_required": "Introduce dominio/IP pública y correo de Let’s Encrypt.", + "settings.https_issue_confirm": "¿Solicitar o renovar el certificado Let’s Encrypt para {target}? Se guardarán los ajustes HTTPS. El puerto TCP 80 debe ser accesible desde Internet.", + "settings.https_issuing": "Solicitando certificado a Let’s Encrypt…", + "settings.https_issue_ok": "Certificado listo.", + "settings.https_already_enabled": "HTTPS integrado ya está habilitado.", + "settings.https_already_disabled": "HTTPS integrado ya está deshabilitado.", + "settings.https_enable_confirm": "¿Habilitar HTTPS integrado en TCP {port} con ruta {path}? WGTools se reiniciará y la página volverá a conectarse a la nueva dirección.", + "settings.https_disable_confirm": "¿Deshabilitar HTTPS integrado y volver a HTTP?", + "settings.https_switching": "Habilitando HTTPS y reiniciando WGTools…", + "settings.https_switching_http": "Deshabilitando HTTPS y reiniciando WGTools…", + "audit.action.https.certificate_issued": "Certificado HTTPS emitido", + "audit.action.https.certificate_failed": "Error al solicitar el certificado HTTPS", + "audit.action.https.enabled": "HTTPS habilitado", + "audit.action.https.disabled": "HTTPS deshabilitado", + "audit.result.issued": "emitido", + "audit.result.enabled": "habilitado", + "audit.result.disabled": "deshabilitado", + "settings.https_access_path": "Ruta de acceso al panel", + "settings.https_access_path_help": "Elige tu propia ruta. Con HTTPS integrado, las solicitudes fuera de ella reciben 404.", + "settings.https_enable_fields_required": "Introduce dominio/IP pública, correo Let’s Encrypt y ruta del panel.", + "settings.https_use_panel_host": "Usar dirección del panel", + "settings.https_reconnecting": "WGTools cambiando a la nueva dirección HTTPS…", + "server.tab_nodes": "Nodos", + "common.type": "Tipo", + "common.status": "Estado", + "common.copy_failed": "No se pudo copiar", + "clients.vpn_address": "Dirección VPN", + "nodes.title": "Nodos WGTools", + "nodes.subtitle": "Conecta varios servidores WGTools en una red protegida y publica solo las redes accesibles a otros nodos.", + "nodes.enable_hub": "Habilitar HUB", + "nodes.connect_hub": "Conectar al HUB", + "nodes.settings": "Ajustes del nodo", + "nodes.settings_action": "Configuración", + "nodes.sync_now": "Sincronizar", + "nodes.disable": "Deshabilitar nodos", + "nodes.disable_action": "Desconectar", + "nodes.join_title": "Conectar nuevos nodos", + "nodes.join_help": "Crea un código de un solo uso e introdúcelo en otro panel WGTools junto con el endpoint del HUB, p. ej. vpn.example.com:51950. Dura 15 minutos y solo se usa una vez.", + "nodes.create_code": "Crear código", + "nodes.connected_nodes": "Nodos conectados", + "nodes.connected_nodes_help": "Información de otros paneles, redes publicadas y clientes. Los clientes remotos son de solo lectura.", + "nodes.enable_hub_help": "Este panel será el nodo central. El mismo puerto acepta WireGuard por UDP y el emparejamiento inicial protegido por TCP.", + "nodes.node_name": "Nombre del nodo", + "nodes.transport_network": "Red de transporte de nodos", + "nodes.transport_help": "Red privada separada solo para el transporte entre WGTools. No debe solaparse con las redes VPN/LAN.", + "nodes.panel_url": "URL del panel", + "nodes.panel_url_help": "Opcional. Solo es un enlace informativo del botón «Abrir panel» en otros nodos; no se usa para conectar nodos.", + "nodes.extra_networks": "Redes de nodo adicionales", + "nodes.extra_networks_help": "Una red por línea. Las redes VPN y las redes remotas Site-to-site se publican automáticamente. Añade solo otras LAN/redes enrutadas, p. ej. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools rellena redes VPN, Site-to-site y LAN enrutadas detectadas. Deja solo las redes que este nodo debe publicar. Una por línea.", + "nodes.published_networks_settings_help": "Una red por línea. Lista explícita de redes publicadas por este nodo. Quitar una línea deja de anunciar esa red a otros nodos.", + "nodes.available_networks_help": "Redes detectadas: {networks}. Las redes nuevas no se publican automáticamente; añade arriba las que quieras.", + "nodes.available_networks_none": "No se detectaron redes locales adicionales.", + "nodes.connect_help": "Introduce endpoint del HUB y código de un uso. La URL, el puerto HTTPS, certificado y ruta privada del panel no se usan para emparejar.", + "nodes.join_code": "Código de conexión", + "nodes.connect_reachability_note": "El emparejamiento inicial usa TCP protegido en el puerto indicado. Tras crear wgnode0, las redes, estados, versiones y datos de clientes de solo lectura se sincronizan con HUB por WireGuard interno.", + "nodes.connect": "Conectar", + "nodes.settings_help": "Nombre del nodo, enlace opcional «Abrir panel» y lista de redes publicadas. La URL del panel no se usa para emparejamiento ni sincronización.", + "nodes.details": "Detalles", + "nodes.not_configured": "WGTools Nodes sin configurar", + "nodes.not_configured_help": "Habilita HUB en este panel o conéctalo a un HUB WGTools existente.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Conectado al HUB", + "nodes.mode_none": "Sin configurar", + "nodes.role": "Rol", + "nodes.tunnel": "Túnel del nodo", + "nodes.node_ip": "Dirección del nodo", + "nodes.endpoint": "Endpoint de HUB", + "nodes.published_networks": "Redes publicadas", + "nodes.last_sync": "Última sincronización", + "nodes.no_nodes_hub": "Aún no hay nodos conectados. Crea un código y úsalo en otro panel WGTools.", + "nodes.no_nodes_spoke": "Aún no se recibió información de nodos remotos.", + "nodes.clients_short": "Clientes", + "nodes.open_panel": "Abrir panel", + "nodes.route_conflict": "Conflicto de rutas", + "nodes.no_published_networks": "Sin redes publicadas", + "nodes.load_failed": "No se pudo cargar WGTools Nodes", + "nodes.enable_hub_confirm": "¿Habilitar HUB de WGTools y crear el túnel WireGuard interno?", + "nodes.applying": "Configurando túnel WGTools Nodes…", + "nodes.enable_failed": "No se pudo habilitar HUB", + "nodes.hub_enabled": "HUB de WGTools habilitado", + "nodes.connecting": "Verificando código HUB y creando túnel protegido…", + "nodes.connect_failed": "No se pudo conectar al HUB", + "nodes.connected": "Conectado al HUB WGTools", + "nodes.settings_failed": "No se pudieron guardar los ajustes del nodo", + "nodes.settings_saved": "Ajustes del nodo guardados", + "nodes.code_failed": "No se pudo crear código de conexión", + "nodes.code_expires": "Código de un solo uso. Válido hasta {time}.", + "nodes.code_copied": "Código de conexión copiado", + "nodes.network_vpn": "Clientes VPN", + "nodes.network_site_to_site": "Red Site-to-site", + "nodes.network_custom": "Red adicional", + "nodes.conflict": "Conflicto", + "nodes.remote_clients": "Clientes (solo lectura)", + "nodes.no_clients": "Este nodo no informa de clientes", + "nodes.details_failed": "No se pudieron cargar los detalles del nodo", + "nodes.remove_confirm": "¿Quitar el nodo «{name}» del HUB? Se revocará su acceso al túnel interno.", + "nodes.remove_failed": "No se pudo quitar el nodo", + "nodes.removed": "Nodo eliminado", + "nodes.disable_hub_confirm": "¿Deshabilitar HUB y desconectar todos los nodos WGTools? Se eliminará el túnel interno.", + "nodes.disconnect_confirm": "¿Desconectar este panel WGTools del HUB y eliminar su túnel interno?", + "nodes.disable_failed": "No se pudieron deshabilitar los nodos WGTools", + "nodes.disabled": "Nodos WGTools deshabilitados", + "nodes.sync_failed": "Error de sincronización de nodos", + "nodes.synced": "Información de nodos sincronizada", + "nodes.service_port": "Puerto Nodes", + "nodes.service_port_help": "Se usa el mismo número de puerto: UDP para WireGuard y TCP para emparejamiento inicial protegido.", + "nodes.hub_port_forward_note": "Si HUB está tras NAT, redirige el mismo puerto para UDP y TCP. El puerto web WGTools, HTTPS y la ruta privada no están relacionados con Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Dominio/IP y puerto de Nodes sin http:// ni https://, p. ej. vpn.example.com:51950.", + "settings.collapse_sidebar": "Contraer barra lateral", + "settings.expand_sidebar": "Expandir barra lateral", + "settings.https_issue_fields_required": "Introduce dominio/IP pública, correo Let’s Encrypt y ruta del panel.", + "settings.https_issue_ok_saved": "Certificado listo y ajustes HTTPS guardados.", + "settings.https_enable_need_certificate": "Primero obtén un certificado.", + "settings.https_enable_certificate_mismatch": "Primero obtén un certificado para el dominio o IP actual.", + "settings.https_enable_certificate_expired": "El certificado caducó. Renuévalo antes de habilitar HTTPS.", + "settings.https_enable_certificate_ready": "Certificado listo: ya puedes habilitar HTTPS integrado.", + "settings.https_enable_active_help": "Desmarca y guarda para volver a HTTP.", + "settings.https_certificate_expired": "Caducado", + "settings.https_certificate_wrong_target": "Para otra dirección", + "nodes.network_conflict_error": "Las redes publicadas entran en conflicto con otro nodo o red de transporte Nodes: {conflicts}. Elimina o cambia la red conflictiva.", + "nodes.networks_changed": "Las redes detectadas cambiaron desde el último guardado. Nuevas: {added}. Ya no detectadas: {removed}. Revisa y guarda las redes publicadas.", + "nodes.review_networks": "Revisar redes", + "nodes.vpn_pool_mismatch": "El grupo VPN cambió: Nodes sigue publicando {old}, pero el grupo actual es {current}. Abre los ajustes y actualiza las redes publicadas.", + "server.error_vpn_network_invalid": "La red VPN debe ser una red IPv4 válida, p. ej. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Solo se admiten redes VPN IPv4.", + "server.error_vpn_network_too_small": "La red VPN debe tener al menos dos direcciones utilizables.", + "server.error_vpn_network_no_hosts": "La red VPN elegida no tiene direcciones de servidor utilizables.", + "server.error_server_address_prefix": "La dirección VPN del servidor debe incluir prefijo, p. ej. 10.0.0.1/24.", + "server.error_server_address_network": "La dirección VPN del servidor debe pertenecer al grupo elegido y usar el mismo prefijo.", + "server.error_server_address_reserved": "La dirección VPN del servidor no puede ser la de red ni la de difusión.", + "server.error_listen_port_number": "El puerto WireGuard debe ser un número.", + "server.error_listen_port_range": "El puerto WireGuard debe estar entre 1 y 65535.", + "server.error_mtu_number": "MTU debe ser un número.", + "auth.mfa_title": "Autenticación de dos factores", + "auth.mfa_login_help": "Introduce el código de 6 dígitos de Google Authenticator o un código de recuperación.", + "auth.mfa_code": "Código de autenticación", + "auth.mfa_verify": "Verificar e iniciar sesión", + "auth.mfa_back": "Volver a la contraseña", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Autenticación de dos factores (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Activado", + "settings.mfa_disabled": "Desactivado", + "settings.mfa_google_help": "Protege esta cuenta con Google Authenticator u otra app TOTP. Para comenzar se requiere tu contraseña actual.", + "settings.current_password": "Contraseña actual", + "settings.mfa_start": "Configurar Google Authenticator", + "settings.mfa_secret": "Clave de configuración manual", + "settings.mfa_scan_help": "Escanea el QR con Google Authenticator y escribe el código actual de 6 dígitos para habilitar MFA.", + "settings.mfa_code": "Código de 6 dígitos", + "settings.mfa_enable": "Habilitar MFA", + "settings.mfa_manage_help": "Para cambiar MFA, introduce la contraseña actual y un código de Authenticator o recuperación.", + "settings.mfa_code_or_recovery": "Código de Authenticator o recuperación", + "settings.mfa_regenerate": "Nuevos códigos de recuperación", + "settings.mfa_disable": "Deshabilitar MFA", + "settings.mfa_recovery_title": "Códigos de recuperación", + "settings.mfa_recovery_help": "Guarda estos códigos ahora. Cada uno se usa una vez si Google Authenticator no está disponible. No se mostrarán otra vez.", + "settings.mfa_recovery_remaining": "Códigos de recuperación restantes: {count}", + "settings.mfa_enabled_ok": "MFA habilitada.", + "settings.mfa_disabled_ok": "MFA deshabilitada.", + "settings.mfa_disable_confirm": "¿Deshabilitar la autenticación de dos factores para esta cuenta?", + "settings.mfa_regenerate_confirm": "¿Reemplazar todos los códigos de recuperación existentes?", + "settings.mfa_recovery_regenerated": "Nuevos códigos de recuperación creados.", + "audit.action.auth.mfa_failed": "Error de verificación MFA", + "audit.action.auth.mfa_recovery_used": "Código de recuperación MFA utilizado", + "audit.action.user.mfa_setup_started": "Configuración de MFA iniciada", + "audit.action.user.mfa_enabled": "MFA habilitada", + "audit.action.user.mfa_disabled": "MFA deshabilitada", + "audit.action.user.mfa_disabled_cli": "MFA deshabilitada por CLI", + "audit.action.user.mfa_recovery_regenerated": "Códigos de recuperación MFA regenerados", + "settings.mfa_error_password": "Contraseña actual incorrecta.", + "settings.mfa_error_code": "Código de autenticación no válido.", + "settings.mfa_error_already_enabled": "MFA ya está habilitada.", + "settings.mfa_error_not_enabled": "MFA no está habilitada.", + "settings.mfa_error_not_started": "Vuelve a iniciar la configuración MFA.", + "trace.title": "Traceroute, ping y mapa de ruta", + "trace.subtitle": "Mide la latencia hacia un VPS u otro servidor y detecta retrasos en la ruta.", + "trace.target": "IP o nombre de host del servidor", + "trace.show_map": "Mostrar ruta en el mapa", + "trace.run": "Iniciar traceroute", + "trace.geo_note": "La geolocalización es aproximada. Con el mapa activado, las IP públicas de los saltos se envían a ipwho.is; los mapas se cargan desde OpenStreetMap.", + "trace.latency_note": "Traceroute mide la latencia en milisegundos, no el rendimiento en Mbit/s.", + "trace.map": "Mapa de ruta", + "trace.map_hint": "Mapa interactivo: arrastra para mover, usa la rueda o +/− para ampliar y pulsa un salto para ver detalles.", + "trace.hop": "Salto / IP", + "trace.location": "Ubicación", + "trace.avg_rtt": "RTT medio", + "trace.delta": "Δ RTT", + "trace.loss": "Pérdida", + "trace.summary_target": "Destino", + "trace.summary_ping": "Ping medio", + "trace.summary_loss": "Pérdida de ping", + "trace.summary_hops": "Saltos", + "trace.no_reply": "Sin respuesta", + "trace.private": "Red privada", + "trace.unknown": "Desconocido", + "trace.running": "Ejecutando ping y traceroute… Puede tardar hasta un minuto.", + "trace.done": "Traza de red completada.", + "trace.failed": "Error de traza de red", + "trace.partial_geo": "No se pudieron geolocalizar algunos saltos públicos.", + "trace.not_reached": "Traceroute no alcanzó el destino.", + "trace.reached": "Destino alcanzado", + "trace.ms": "ms", + "server.tab_trace": "Rastreo", + "trace.map_controls": "Controles del mapa", + "trace.zoom_in": "Acercar", + "trace.zoom_out": "Alejar", + "trace.fit_route": "Ajustar a la ruta", + "trace.fit": "Ajustar", + "trace.map_click_hint": "Pulsa un salto para ver IP, ubicación, ASN y RTT.", + "trace.route_path": "Ruta", + "trace.ping_ok_trace_filtered": "El destino responde a ping, pero los últimos saltos del traceroute no responden.", + "trace.latency_legend": "Aumento de latencia entre saltos que responden", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — elevado", + "trace.latency_bad": "Δ RTT > 20 ms — salto brusco" +} diff --git a/app/static/fr.json b/app/static/fr.json new file mode 100644 index 0000000..2c3844e --- /dev/null +++ b/app/static/fr.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Créer un utilisateur", + "auth.login_subtitle": "Saisissez votre nom d’utilisateur et votre mot de passe WGTools.", + "auth.login_title": "Se connecter à WGTools", + "auth.password": "Mot de passe", + "auth.password_repeat": "Répéter le mot de passe", + "auth.setup_help": "Le premier compte dispose d’un accès complet à WGTools. D’autres utilisateurs peuvent être créés plus tard dans les paramètres.", + "auth.setup_subtitle": "Un compte WGTools est requis avant de pouvoir gérer le serveur.", + "auth.setup_title": "Créer le premier utilisateur", + "auth.sign_in": "Se connecter", + "auth.sign_out": "Se déconnecter", + "auth.username": "Nom d’utilisateur", + "clients.actions": "Actions", + "clients.add": "+ Ajouter un client", + "clients.address": "Adresse VPN", + "clients.address_hint": "La première adresse disponible est proposée automatiquement.", + "clients.allowed_ips_required": "Saisissez au moins un réseau AllowedIPs pour la configuration client.", + "clients.basic_connection": "Paramètres de connexion", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs de la configuration client", + "clients.config_private_warning": "Cette configuration contient la clé privée du client. Conservez-la en lieu sûr.", + "clients.config_title": "Configuration client", + "clients.config_unavailable": "Configuration indisponible", + "clients.connection_direct": "Directement vers WGTools", + "clients.connection_path": "Chemin de connexion", + "clients.connection_relay": "Relais VPS", + "clients.connection_via": "Se connecter via", + "clients.connection_via_hint": "Choisissez le point d’entrée public du client. Le relais n’apparaît que s’il est installé pour l’interface WireGuard sélectionnée.", + "clients.copy_config": "Copier", + "clients.copy_done": "Configuration copiée", + "clients.create_subtitle": "Créer un pair WireGuard et générer sa configuration client.", + "clients.create_title": "Créer un client", + "clients.creating": "Création des clés et application du client…", + "clients.day_fri": "Ven", + "clients.day_mon": "Lun", + "clients.day_sat": "Sam", + "clients.day_sun": "Dim", + "clients.day_thu": "Jeu", + "clients.day_tue": "Mar", + "clients.day_wed": "Mer", + "clients.delete_confirm": "Supprimer ce client de WireGuard ? WGTools créera une sauvegarde et supprimera les règles automatiques associées.", + "clients.deleted": "Client supprimé", + "clients.dns": "DNS (facultatif)", + "clients.dns_hint": "Serveurs DNS IPv4 séparés par des virgules.", + "clients.download_config": "Télécharger .conf", + "clients.duplicate": "Dupliquer", + "clients.duplicate_address_error": "Cette adresse VPN est déjà utilisée par un autre pair.", + "clients.duplicate_name_error": "Un pair portant ce nom existe déjà.", + "clients.duplicate_ready": "Copie prête. WGTools a attribué un nouveau nom et une adresse VPN. Vérifiez les paramètres avant d’enregistrer.", + "clients.duplicate_site_hint": "Les réseaux distants ont été effacés pour éviter les routes en double. Indiquez les réseaux du nouveau pair Site-to-site.", + "clients.duplicate_suffix": "copie", + "clients.edit_subtitle": "Modifier le pair côté serveur. Les changements sont appliqués sans redémarrer WireGuard.", + "clients.edit_title": "Modifier le client", + "clients.endpoint": "Endpoint du serveur", + "clients.endpoint_hint": "Pour les clients distants, utilisez l’IP publique ou le domaine qui redirige le port WireGuard vers ce serveur.", + "clients.existing": "Pair existant", + "clients.expiration": "Durée de validité", + "clients.expiration_action": "À expiration", + "clients.expiration_action_hint": "Si cette option est décochée, le client reste dans WGTools mais son accès WireGuard est désactivé. Choisissez une nouvelle durée ou aucune expiration et enregistrez pour rétablir l’accès.", + "clients.expiration_datetime": "Expire le", + "clients.expiration_datetime_hint": "Utilise la date et l’heure locales du navigateur.", + "clients.expiration_delete": "Supprimer le client", + "clients.expiration_future_required": "Choisissez une date et une heure futures.", + "clients.expiration_hint": "À expiration, WGTools exécute l’action choisie au début de la minute suivante. Une sauvegarde WireGuard est créée avant.", + "clients.expire_1d": "1 jour", + "clients.expire_1h": "1 heure", + "clients.expire_3h": "3 heures", + "clients.expire_6h": "6 heures", + "clients.expire_custom": "Date et heure personnalisées", + "clients.expire_never": "Aucune expiration", + "clients.expired": "Expiré", + "clients.expired_disabled_hint": "L’accès a expiré. Le client est conservé mais WireGuard est désactivé. Choisissez une nouvelle durée ou aucune expiration puis enregistrez.", + "clients.expired_disabled_short": "Expiré · désactivé", + "clients.expired_disabled_status": "Expiré", + "clients.expires_days": "Expire dans {n} j", + "clients.expires_hours": "Expire dans {n} h", + "clients.expires_minutes": "Expire dans {n} min", + "clients.generated_config": "Configuration client générée", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 secondes est une bonne valeur par défaut pour les clients derrière un NAT.", + "clients.local_access_exceptions": "Adresses locales autorisées", + "clients.local_access_exceptions_hint": "IP ou CIDR facultatifs restant accessibles même si leur réseau local ou Site-to-site est bloqué. Séparez-les par des virgules.", + "clients.managed": "Géré par WGTools", + "clients.name": "Nom", + "clients.no_peers": "Aucun pair trouvé", + "clients.peers": "Pairs", + "clients.peers_subtitle": "Les modifications sont sauvegardées puis appliquées avec wg syncconf sans redémarrer l’interface WireGuard.", + "clients.protected_networks_reference": "Réseaux locaux bloqués (référence)", + "clients.protected_networks_reference_hint": "Ces réseaux ne sont pas écrits dans AllowedIPs. L’accès est bloqué par la politique serveur WGTools ; des adresses individuelles peuvent être autorisées ci-dessus.", + "clients.psk": "Clé prépartagée (PSK)", + "clients.psk_enable": "Utiliser une clé WireGuard prépartagée supplémentaire", + "clients.psk_hint": "Recommandé. Ajoute un secret symétrique au handshake WireGuard. Les clients standards le prennent en charge ; WGTools inclut le PSK dans la configuration et le QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Génération du QR…", + "clients.quick_search": "Recherche rapide", + "clients.quick_search_clear": "Effacer la recherche", + "clients.quick_search_empty": "Aucun client correspondant", + "clients.relay_endpoint_note": "La configuration client générée se connectera à {endpoint}. Le serveur WireGuard reste sur cet hôte WGTools.", + "clients.relay_required": "Choisissez un relais VPS pour ce client.", + "clients.relay_short": "Relais", + "clients.relay_unknown": "indisponible", + "clients.relay_vps": "Relais VPS", + "clients.relay_vps_hint": "L’endpoint du client est généré automatiquement depuis ce relais.", + "clients.remote_hint": "Réseaux situés derrière ce pair. Un par ligne ou séparés par des virgules.", + "clients.remote_networks": "Réseaux distants", + "clients.remote_required": "Saisissez au moins un réseau distant pour le pair Site-to-site.", + "clients.required": "Le nom et l’adresse VPN sont obligatoires.", + "clients.route_custom": "Personnalisé", + "clients.route_full": "Tunnel complet", + "clients.route_full_except_local": "Tunnel complet sauf réseaux locaux", + "clients.route_hint": "Seuls ces réseaux sont écrits dans AllowedIPs de la configuration client.", + "clients.route_preset": "Trafic via VPN", + "clients.route_vpn": "Réseau VPN uniquement", + "clients.route_vpn_lan": "VPN + réseau local", + "clients.saved": "Client enregistré", + "clients.schedule_blocked_short": "Horaire · bloqué", + "clients.schedule_blocked_status": "Bloqué par la plage horaire", + "clients.schedule_days": "Jours autorisés", + "clients.schedule_days_required": "Choisissez au moins un jour pour la plage horaire.", + "clients.schedule_disabled_hint": "Ce client est actuellement bloqué par son horaire. WGTools rétablira le pair automatiquement au prochain créneau autorisé.", + "clients.schedule_enable": "Limiter l’accès selon un horaire", + "clients.schedule_from": "Accès à partir de", + "clients.schedule_hint": "WGTools peut désactiver puis réactiver le client aux jours et heures choisis sans modifier sa configuration.", + "clients.schedule_short": "Horaire", + "clients.schedule_time_required": "Définissez les heures de début et de fin.", + "clients.schedule_timezone_hint": "L’horaire utilise l’heure locale du serveur WireGuard. Les plages traversant minuit, comme 22:00–06:00, sont prises en charge.", + "clients.schedule_title": "Plage horaire d’accès", + "clients.schedule_to": "Accès jusqu’à", + "clients.security_access": "Sécurité et heures d’accès", + "clients.server_host": "Adresse / domaine du serveur", + "clients.server_host_hint": "IP publique ou domaine utilisé par ce client. Les valeurs précédentes apparaissent comme suggestions.", + "clients.server_host_required": "Une adresse / un domaine serveur est nécessaire pour la configuration client.", + "clients.server_peer": "Pair serveur", + "clients.server_port": "Port WireGuard", + "clients.server_port_hint": "Repris automatiquement de la configuration serveur.", + "clients.site_to_site": "Site à site", + "clients.status": "État", + "clients.subtitle": "Pairs WireGuard, état en direct et gestion des configurations client.", + "clients.tab_basic": "Basique", + "clients.tab_config": "Configuration", + "clients.tab_policy": "Politiques", + "clients.tab_security": "Sécurité", + "clients.title": "Clients", + "clients.type": "Type", + "clients.unmanaged_note": "Ce pair existait avant WGTools. Sa clé privée client est irrécupérable. WGTools peut modifier le pair côté serveur mais ne peut pas générer sa configuration client ou son QR.", + "clients.updating": "Mise à jour du client…", + "common.actions": "Actions", + "common.ago": "il y a", + "common.cancel": "Annuler", + "common.checking": "Vérification…", + "common.close": "Fermer", + "common.config": "Configuration", + "common.delete": "Supprimer", + "common.disabled": "Désactivé", + "common.edit": "Modifier", + "common.enabled": "Activé", + "common.loading": "Chargement…", + "common.never": "Jamais", + "common.no": "Non", + "common.not_configured": "Non configuré", + "common.not_installed": "Non installé", + "common.offline": "hors ligne", + "common.online": "en ligne", + "common.refresh": "Actualiser", + "common.running": "En cours", + "common.save": "Enregistrer", + "common.stopped": "Arrêté", + "common.total": "Total", + "common.unknown": "Inconnu", + "common.updated": "Mis à jour", + "common.yes": "Oui", + "dashboard.active_peers": "Pairs actifs", + "dashboard.active_peers_subtitle": "Données en direct issues de wg show.", + "dashboard.activity": "Vue d’ensemble du système", + "dashboard.activity_subtitle": "Vérifications en lecture seule de WireGuard en fonctionnement.", + "dashboard.cores": "cœurs", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Dernières 24 h", + "dashboard.history_avg": "Moy.", + "dashboard.history_max": "Max.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "maintenant", + "dashboard.memory": "Mémoire", + "dashboard.network": "Réseau", + "dashboard.peers": "Pairs", + "dashboard.quick_search": "Recherche rapide", + "dashboard.quick_search_clear": "Effacer la recherche", + "dashboard.quick_search_empty": "Aucun pair ne correspond à la recherche", + "dashboard.restart": "Redémarrer", + "dashboard.restart_confirm": "Redémarrer WireGuard ? Les clients VPN actifs se reconnecteront automatiquement.", + "dashboard.restart_ok": "WireGuard redémarré.", + "dashboard.routing": "Routage", + "dashboard.site_to_site": "Site à site", + "dashboard.start": "Démarrer", + "dashboard.start_ok": "WireGuard démarré.", + "dashboard.stop": "Arrêter", + "dashboard.stop_confirm": "Arrêter WireGuard ? Les clients VPN actifs seront déconnectés.", + "dashboard.stop_ok": "WireGuard arrêté.", + "dashboard.subtitle": "État du serveur WireGuard, pairs et trafic en direct.", + "dashboard.title": "Tableau de bord", + "dashboard.traffic": "Trafic", + "dashboard.uptime": "Temps de fonctionnement", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Politique d’accès au serveur", + "groups.additional_allowed": "Adresses supplémentaires autorisées", + "groups.additional_blocked": "Adresses supplémentaires bloquées", + "groups.allow": "Autoriser", + "groups.allowed": "Autorisé", + "groups.allowed_addresses": "Adresses / réseaux autorisés", + "groups.apply_current_template": "Appliquer le modèle actuel du groupe", + "groups.apply_defaults": "Appliquer le modèle actuel du groupe", + "groups.apply_defaults_hint": "Copie les routes, DNS et Keepalive du modèle de groupe vers ce client. Enregistrez-le puis générez une nouvelle configuration ou un QR si nécessaire.", + "groups.basic": "Informations de base", + "groups.block": "Bloquer", + "groups.blocked": "Bloqué", + "groups.blocked_addresses": "Adresses / réseaux bloqués", + "groups.client_config_source": "Source de configuration client", + "groups.client_defaults": "Paramètres client par défaut", + "groups.client_group_hint": "Groupe facultatif pour réutiliser les règles d’accès et paramètres client. Chaque groupe est associé à l’interface WireGuard sélectionnée.", + "groups.config_differs": "La configuration du client diffère des paramètres actuels du groupe. La politique serveur est à jour, mais le téléphone ou PC doit recevoir une nouvelle configuration ou un QR.", + "groups.config_differs_short": "Configuration client différente du groupe", + "groups.create": "Créer un groupe", + "groups.create_title": "Créer un groupe", + "groups.created": "Groupe créé", + "groups.creating": "Création du groupe…", + "groups.defaults_applied": "Modèle actuel du groupe appliqué. Enregistrez le client pour conserver les changements.", + "groups.defaults_hint": "Définit le trafic envoyé par le client via WireGuard. La politique serveur ci-dessus détermine séparément les accès autorisés. Modifier le modèle ne change jamais les configurations déjà installées.", + "groups.delete_message": "Supprimer « {name} » ? Les configurations client ne sont jamais supprimées avec le groupe.", + "groups.delete_move": "Déplacer ses clients vers un autre groupe", + "groups.delete_title": "Supprimer le groupe de clients", + "groups.delete_unassign": "Retirer l’affectation du groupe aux clients", + "groups.deleted": "Groupe supprimé", + "groups.deleting": "Mise à jour des clients et suppression du groupe…", + "groups.description": "Description", + "groups.edit_title": "Modifier le groupe", + "groups.editor_subtitle": "Un groupe associe des règles d’accès serveur actives à un modèle de configuration client.", + "groups.effective_allow": "Exceptions autorisées", + "groups.effective_deny": "Exceptions bloquées", + "groups.effective_policy": "Politique serveur effective", + "groups.empty": "Aucun groupe de clients. Créez-en un pour réutiliser les règles d’accès et les paramètres par défaut.", + "groups.group": "Groupe", + "groups.inherit": "Hériter", + "groups.internet_access": "Accès Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Réseaux locaux", + "groups.local_short": "Local", + "groups.manage": "Groupes", + "groups.members_count": "{count} clients", + "groups.name": "Nom", + "groups.name_required": "Le nom du groupe est obligatoire.", + "groups.new_client_defaults": "Modèle de configuration client", + "groups.new_clients_short": "Nouveaux clients", + "groups.no_group": "Aucun groupe", + "groups.none": "Aucun", + "groups.override_client_config": "Remplacer le modèle client du groupe pour ce client", + "groups.override_client_config_hint": "Désactivé : routes, DNS et Keepalive proviennent du groupe. Activé : ce client conserve ses valeurs. Les exceptions de politique serveur restent indépendantes.", + "groups.policy_addresses_hint": "Adresses IPv4 ou CIDR séparés par des virgules. Les exceptions client ont priorité sur celles du groupe.", + "groups.policy_custom": "Politique personnalisée", + "groups.policy_inherit": "Utiliser la politique du groupe", + "groups.policy_mode": "Source de la politique", + "groups.policy_mode_hint": "La politique du groupe s’applique par défaut. Les exceptions client ne modifient jamais le groupe.", + "groups.routes_required": "Les routes du client ne peuvent pas être vides.", + "groups.subtitle": "Réutilisez les règles d’accès serveur et les paramètres par défaut pour les clients de l’interface WireGuard sélectionnée.", + "groups.title": "Groupes de clients", + "groups.traffic_through_vpn": "Trafic via VPN", + "groups.updated": "Groupe mis à jour", + "groups.updating": "Mise à jour de la politique du groupe…", + "help.example_note": "Toutes les adresses, interfaces, noms de pairs et domaines des exemples d’aide sont fictifs. Remplacez-les par vos propres valeurs.", + "help.navigation": "Navigation de l’aide", + "help.open": "Ouvrir l’aide", + "help.subtitle": "Aide accessible pour le tableau de bord, le serveur, les clients et les paramètres, avec des exemples pratiques.", + "help.title": "Aide WGTools", + "interfaces.add": "+ Ajouter une interface", + "interfaces.create": "Créer une interface", + "interfaces.create_confirm": "Créer et démarrer l’interface {name} ?", + "interfaces.create_failed": "Impossible de créer l’interface", + "interfaces.create_hint": "Avant la création, WGTools vérifie que le réseau VPN, le port UDP et la table de routage ne sont pas déjà utilisés par une autre interface WireGuard.", + "interfaces.create_subtitle": "Créez une interface WireGuard indépendante avec son propre pool d’adresses, port UDP et paramètres de routage.", + "interfaces.create_title": "Ajouter une interface WireGuard", + "interfaces.created": "Interface créée avec succès.", + "interfaces.creating": "Génération des clés, écriture de la configuration et démarrage de WireGuard…", + "interfaces.current": "Actuelle", + "interfaces.delete": "Supprimer", + "interfaces.delete_confirm": "Supprimer l’interface {name} ? Sa configuration WireGuard et tous ses pairs seront supprimés. Une sauvegarde sera créée au préalable.", + "interfaces.delete_failed": "Impossible de supprimer l’interface", + "interfaces.delete_last": "La dernière interface WireGuard configurée ne peut pas être supprimée ici.", + "interfaces.delete_tooltip": "Supprimer cette interface WireGuard", + "interfaces.deleted": "Interface supprimée. Sauvegarde : {backup}", + "interfaces.deleting": "Arrêt de WireGuard et suppression de l’interface…", + "interfaces.display_name": "Nom affiché", + "interfaces.display_name_edit_hint": "Nom d’affichage uniquement : le nom de l’interface Linux ne change pas.", + "interfaces.display_name_hint": "Nom convivial facultatif, par exemple Travail ou Prestataires.", + "interfaces.identity": "Identité de l’interface", + "interfaces.none": "Aucune interface WireGuard trouvée", + "interfaces.none_configured": "Aucune interface WireGuard n’est encore configurée.", + "interfaces.peers_short": "pairs", + "interfaces.rename_failed": "Impossible d’enregistrer le nom affiché de l’interface.", + "interfaces.select": "Sélectionner", + "interfaces.subtitle": "Chaque interface possède son réseau VPN, son port, ses pairs et ses règles. Sélectionnez-en une pour la gérer dans WGTools.", + "interfaces.switch_title": "Interfaces WireGuard", + "interfaces.system_name": "Nom système", + "interfaces.system_name_hint": "Nom de l’interface Linux, par exemple wg1. Non modifiable après création.", + "interfaces.title": "Interfaces WireGuard", + "interfaces.unique_port_hint": "Chaque interface WireGuard de ce serveur doit utiliser un port UDP distinct.", + "interfaces.unique_table_hint": "WGTools recommande une table de routage distincte par interface. Laissez vide pour le routage standard.", + "nav.clients": "Clients", + "nav.dashboard": "Tableau de bord", + "nav.server": "Serveur", + "nav.settings": "Paramètres", + "server.access_apply_confirm": "Enregistrer et appliquer cette règle de pare-feu ? WireGuard redémarrera brièvement et une sauvegarde sera créée.", + "server.access_rule_deleted": "Règle d’accès supprimée.", + "server.access_rule_help": "Créez une règle FORWARD sans modifier manuellement les commandes iptables.", + "server.access_rule_order_hint": "WGTools insère les règles au début de la chaîne FORWARD pour appliquer les restrictions avant les règles VPN ACCEPT générales.", + "server.access_rule_saved": "Règle d’accès enregistrée et appliquée.", + "server.action": "Action", + "server.action_hint": "REJECT signale le refus au client ; DROP écarte sans réponse ; ACCEPT autorise explicitement.", + "server.add_access_rule": "Ajouter une règle d’accès", + "server.add_route": "Ajouter une route", + "server.address": "Adresse", + "server.any": "Tous", + "server.any_protocol": "Tout protocole", + "server.apply_confirm": "Enregistrer et appliquer les paramètres serveur ? WireGuard redémarrera brièvement. Une sauvegarde sera créée et la configuration précédente restaurée automatiquement si le démarrage échoue.", + "server.apply_settings": "Enregistrer et appliquer", + "server.applying_rule": "Création de sauvegarde et application…", + "server.applying_settings": "Validation, sauvegarde et application des paramètres…", + "server.basic_settings": "Paramètres de base", + "server.config_tab_help": "Ouvrir l’éditeur de configuration brute de l’interface WireGuard sélectionnée.", + "server.create_confirm": "Créer et démarrer le serveur WireGuard avec ces paramètres ?", + "server.create_server": "Créer le serveur", + "server.create_step_conf": "Créer la configuration de l’interface WireGuard avec les permissions 600.", + "server.create_step_forward": "Configurer le transfert, le NAT et éventuellement le routage par politique.", + "server.create_step_key": "Générer une nouvelle paire de clés serveur.", + "server.create_step_start": "Activer et démarrer l’interface wg-quick choisie.", + "server.create_subtitle": "WireGuard est installé, mais l’interface sélectionnée n’est pas configurée.", + "server.create_success": "Serveur WireGuard créé avec succès.", + "server.create_title": "Créer le serveur WireGuard", + "server.creating": "Génération des clés, écriture de la configuration et démarrage de WireGuard…", + "server.custom_preserved": "Les blocs de pairs, routes Site-to-site et règles PostUp/PostDown non gérées ici sont conservés.", + "server.delete_access_confirm": "Supprimer cette règle d’accès et appliquer ?", + "server.delete_route_confirm": "Supprimer cette route personnalisée et appliquer ?", + "server.destination": "Destination", + "server.destination_hint": "Vide = tous. IP, CIDR ou plage IP acceptés. Séparez plusieurs destinations par des virgules.", + "server.destination_port": "Port de destination", + "server.destination_port_hint": "Facultatif. Port comme 443 ou plage 10000:20000. Sélectionnez d’abord TCP ou UDP.", + "server.details": "Détails", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostic", + "server.diagnostics_done": "Diagnostic terminé", + "server.diagnostics_subtitle": "Contrôles système actuels. Aucune modification de configuration.", + "server.direction": "Hook", + "server.edit_access_rule": "Modifier la règle d’accès", + "server.edit_route": "Modifier la route", + "server.edit_server": "Modifier le serveur", + "server.edit_subtitle": "Modifier les paramètres WireGuard, routage et NAT courants. Les pairs et règles personnalisées sont conservés.", + "server.edit_title": "Paramètres du serveur", + "server.edit_warning": "Appliquer les paramètres d’interface, routage ou pare-feu redémarre brièvement WireGuard. Les pairs actifs se reconnectent automatiquement.", + "server.enable_forwarding": "Activer le transfert IPv4", + "server.enable_nat": "Activer NAT / Masquerade", + "server.firewall": "Pare-feu et NAT", + "server.firewall_subtitle": "Règles détectées dans les hooks WireGuard.", + "server.firewall_subtitle_v08": "Règles de transfert/NAT et d’accès de l’interface. Les règles simples se gèrent ici ; les plus avancées restent dans l’éditeur brut.", + "server.forward_from_vpn": "Autoriser le transfert depuis VPN", + "server.forward_to_vpn": "Autoriser le transfert vers VPN", + "server.forwarding_section": "Transfert et NAT", + "server.gateway": "Passerelle", + "server.gateway_hint": "Obligatoire uniquement avec une table de routage par politique.", + "server.install_success": "WireGuard installé avec succès.", + "server.install_wireguard": "Installer WireGuard", + "server.install_wireguard_help": "Exécute apt update et installe WireGuard et les outils réseau nécessaires.", + "server.install_wireguard_title": "Installer WireGuard", + "server.installing": "Installation de WireGuard… Cela peut prendre une minute.", + "server.interface": "Interface", + "server.interface_hint": "WGTools gère actuellement cette interface.", + "server.interface_name": "Interface", + "server.interface_section": "Interface WireGuard", + "server.ip_forwarding": "Transfert IPv4", + "server.kind": "Type", + "server.listen_port": "Port d’écoute", + "server.local_network": "Réseau local", + "server.local_network_hint": "Route facultative ajoutée à la table de routage.", + "server.managed_automatically": "Géré automatiquement", + "server.nat": "NAT / Masquerade", + "server.network": "Réseau", + "server.network_settings": "Réseau et NAT", + "server.no_firewall": "Aucune règle de pare-feu trouvée", + "server.no_routes": "Aucune route trouvée", + "server.not_configured": "Non configuré", + "server.not_set": "Non défini", + "server.policy_disabled_hint": "Désactivez pour le routage système normal. Activez uniquement si ce VPN requiert une table par adresse source.", + "server.policy_enabled": "Activer le routage par politique", + "server.policy_table": "Table de routage", + "server.policy_table_hint": "Laissez vide pour le routage normal ; utilisez par ex. 200 pour le routage par source.", + "server.port_word": "port", + "server.private_hidden": "Configuré (masqué)", + "server.private_key": "Clé privée", + "server.protocol": "Protocole", + "server.route_apply_confirm": "Enregistrer et appliquer cette route ? WireGuard redémarrera brièvement et une sauvegarde sera créée.", + "server.route_custom": "Personnalisée", + "server.route_deleted": "Route supprimée.", + "server.route_device_hint": "Interface de sortie facultative, par ex. wg0 ou enp6s18.", + "server.route_editor_help": "Ajoutez une route installée au démarrage de WireGuard puis retirée à l’arrêt.", + "server.route_gateway_hint": "Passerelle de prochain saut facultative. Une passerelle ou interface est requise.", + "server.route_managed_peer": "Pair Site-to-site", + "server.route_managed_server": "Paramètre serveur", + "server.route_network_hint": "Réseau IPv4 comme 10.20.0.0/24 ou 'default'.", + "server.route_saved": "Route enregistrée et appliquée.", + "server.route_table_hint": "Utilisez 'main' pour le routage normal ou une table numérique comme 200.", + "server.route_type": "Type", + "server.routes": "Routes détectées", + "server.routes_subtitle": "Routes extraites de PostUp/PostDown et de l’état actuel du routage par politique.", + "server.routes_subtitle_v08": "Routes serveur, Site-to-site et personnalisées de l’interface choisie. Vous pouvez ajouter, modifier et retirer des routes personnalisées ici.", + "server.routing": "Routage", + "server.routing_section": "Routage", + "server.rule": "Règle", + "server.rule_access": "Règle d’accès", + "server.rule_advanced": "Avancé", + "server.rule_apply_warning": "L’application d’une route ou règle de pare-feu redémarre brièvement WireGuard. WGTools sauvegarde puis restaure automatiquement en cas d’échec de démarrage.", + "server.rule_client_exception": "Exception client", + "server.rule_client_policy": "Politique client", + "server.rule_managed_server": "Paramètre serveur", + "server.rule_type": "Type", + "server.run_diagnostics": "Lancer le diagnostic", + "server.save_apply": "Enregistrer et appliquer", + "server.save_config": "SaveConfig", + "server.server_address": "Adresse VPN du serveur", + "server.server_address_hint": "Habituellement la première adresse utilisable du réseau VPN.", + "server.settings_applied": "Paramètres serveur enregistrés et appliqués avec succès.", + "server.settings_apply_failed": "Impossible d’appliquer les paramètres serveur", + "server.setup_required": "Configuration requise", + "server.source": "Source", + "server.source_hint": "Vide = tous. Accepte IP, CIDR ou plage telle que 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installation, première configuration et paramètres actuels du serveur WireGuard.", + "server.tab_config": "Configuration", + "server.tab_interface": "Interface", + "server.tab_routing": "Routage", + "server.tab_vps": "VPS", + "server.table": "Table", + "server.tabs_aria": "Sections des paramètres serveur", + "server.title": "Serveur", + "server.uplink": "Interface montante", + "server.use_raw_editor": "Utiliser l’éditeur brut", + "server.via": "Via / Interface", + "server.via_word": "via", + "server.vpn_network": "Réseau VPN", + "server.vpn_network_hint": "Les adresses client seront ensuite attribuées depuis ce réseau.", + "server.vpn_pool": "Pool d’adresses VPN", + "server.wg_not_installed": "WireGuard n’est pas installé", + "server.wg_not_installed_subtitle": "WGTools peut installer automatiquement les paquets Debian nécessaires.", + "server.what_happens": "Ce que fera WGTools", + "settings.about": "À propos", + "settings.add_user": "Ajouter un utilisateur", + "settings.advanced": "Avancé", + "settings.advanced_subtitle": "Accès direct aux outils avancés de configuration WireGuard.", + "settings.appearance": "Apparence", + "settings.applying_config": "Vérification de configuration, sauvegarde et application…", + "settings.backup_count": "Sauvegardes stockées", + "settings.backup_retention": "Nombre de sauvegardes à garder", + "settings.backup_retention_help": "Les anciennes sauvegardes automatiques sont supprimées après la création de la suivante. De 1 à 200 fichiers.", + "settings.backups": "Sauvegardes de configuration", + "settings.backups_always_on": "Activé", + "settings.backups_subtitle": "WGTools crée automatiquement une sauvegarde avant toute modification de configuration. Cette protection ne peut pas être désactivée.", + "settings.change_password": "Changer le mot de passe", + "settings.check_updates": "Rechercher des mises à jour", + "settings.config_applied": "Configuration enregistrée et appliquée avec succès.", + "settings.config_applied_restarted": "Configuration appliquée et WireGuard redémarré.", + "settings.config_applied_stopped": "Configuration enregistrée. WireGuard était arrêté et reste arrêté.", + "settings.config_apply_failed": "Impossible d’appliquer la configuration", + "settings.config_load_failed": "Impossible de charger la configuration", + "settings.current_user": "Utilisateur actuel", + "settings.current_version": "Version actuelle", + "settings.audit_action": "Action", + "settings.audit_empty": "Aucun événement d’audit", + "settings.audit_log": "Journal d’audit", + "settings.audit_log_subtitle": "Actions du panneau, connexions, Telegram et historique des clients WireGuard. Aucun secret n’est enregistré ici.", + "settings.audit_object": "Objet", + "settings.audit_result": "Résultat", + "settings.audit_retention_note": "Conservation : 30 jours", + "settings.audit_search": "Recherche rapide", + "settings.audit_search_clear": "Effacer la recherche", + "settings.audit_search_empty": "Aucun événement d’audit correspondant", + "settings.audit_time": "Date / heure", + "settings.audit_user": "Utilisateur", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Règle d’accès créée", + "audit.action.access_rule.deleted": "Règle d’accès supprimée", + "audit.action.access_rule.updated": "Règle d’accès modifiée", + "audit.action.auth.first_user_created": "Premier utilisateur créé", + "audit.action.auth.login": "Connexion réussie", + "audit.action.auth.login_failed": "Échec de connexion", + "audit.action.auth.logout": "Déconnexion effectuée", + "audit.action.backup.full_created": "Sauvegarde complète créée", + "audit.action.backup.full_restored": "Sauvegarde complète restaurée", + "audit.action.client.config_downloaded": "Configuration client téléchargée", + "audit.action.client.config_viewed": "Configuration client consultée", + "audit.action.client.created": "Client créé", + "audit.action.client.deleted": "Client supprimé", + "audit.action.client.qr_viewed": "Code QR du client consulté", + "audit.action.client.updated": "Client mis à jour", + "audit.action.client_group.created": "Groupe de clients créé", + "audit.action.client_group.deleted": "Groupe de clients supprimé", + "audit.action.client_group.updated": "Groupe de clients mis à jour", + "audit.action.interface.created": "Interface créée", + "audit.action.interface.deleted": "Interface supprimée", + "audit.action.interface.renamed": "Interface renommée", + "audit.action.route.created": "Route créée", + "audit.action.route.deleted": "Route supprimée", + "audit.action.route.updated": "Route mise à jour", + "audit.action.server.created": "Serveur créé", + "audit.action.server.raw_config_applied": "Configuration brute appliquée", + "audit.action.server.settings_applied": "Paramètres serveur appliqués", + "audit.action.settings.updated": "Paramètres du panneau modifiés", + "audit.action.telegram.action_denied": "Action Telegram refusée", + "audit.action.telegram.action_failed": "Échec de l’action Telegram", + "audit.action.telegram.connection_test": "Test de connexion Telegram", + "audit.action.telegram.settings_updated": "Paramètres Telegram modifiés", + "audit.action.update.checked": "Mise à jour vérifiée", + "audit.action.update.scheduled": "Mise à jour planifiée", + "audit.action.update.backup_created": "Sauvegarde avant mise à jour", + "audit.action.update.completed": "Mise à jour terminée", + "audit.action.update.failed": "Échec de la mise à jour", + "audit.action.update.rollback_completed": "Version précédente restaurée", + "audit.action.update.rollback_failed": "Échec du retour arrière", + "audit.action.user.created": "Utilisateur créé", + "audit.action.user.deleted": "Utilisateur supprimé", + "audit.action.user.password_changed": "Mot de passe utilisateur modifié", + "audit.action.vps.candidate_deleted": "Candidat VPS supprimé", + "audit.action.vps.candidate_saved": "Candidat VPS enregistré", + "audit.action.vps.detached": "Relais VPS détaché", + "audit.action.vps.relay_installed": "Relais VPS installé", + "audit.action.wireguard.client_connected": "Client WireGuard connecté", + "audit.action.wireguard.installed": "WireGuard installé", + "audit.action.wireguard.restarted": "WireGuard redémarré", + "audit.action.wireguard.started": "WireGuard démarré", + "audit.action.wireguard.stopped": "WireGuard arrêté", + "audit.result.applied": "appliqué", + "audit.result.available": "disponible", + "audit.result.changed": "modifié", + "audit.result.created": "créé", + "audit.result.current": "à jour", + "audit.result.deleted": "supprimé", + "audit.result.detached": "détaché", + "audit.result.denied": "refusé", + "audit.result.downloaded": "téléchargé", + "audit.result.endpoint": "Point de terminaison", + "audit.result.error": "Erreur", + "audit.result.installed": "installé", + "audit.result.invalid_credentials": "identifiants invalides", + "audit.result.ok": "OK", + "audit.result.queued": "en attente", + "audit.result.restarted": "redémarré", + "audit.result.restored": "restauré", + "audit.result.rotated": "renouvelé", + "audit.result.saved": "enregistré", + "audit.result.shown": "affiché", + "audit.result.started": "démarré", + "audit.result.stopped": "arrêté", + "audit.result.updated": "mis à jour", + "settings.delete_user": "Supprimer", + "settings.delete_user_confirm": "Supprimer l’utilisateur {name} ?", + "settings.edit_raw_config": "Modifier la configuration de l’interface", + "settings.expert_mode": "Expert", + "settings.full_backup_component_clients": "Métadonnées des clients gérés, clés privées, PSK, expirations et groupes nécessaires pour recréer leurs configurations et QR.", + "settings.full_backup_component_db": "Base WGTools : utilisateurs, préférences, messagerie/SMTP, Telegram et état enregistré des relais VPS.", + "settings.full_backup_component_relay": "Données de récupération VPS Relay : identifiants contrôleur/tenant, jeton d’administration et clé de transport domicile. WGTools pourra reconstruire le transport local et reconnecter le tenant conservé.", + "settings.full_backup_component_system": "Fichier sysctl de transfert IPv4 WGTools, noms d’affichage des interfaces, règles et modèles de groupes si présents. L’historique automatique des configurations est exclu intentionnellement.", + "settings.full_backup_component_wg": "Toutes les configurations des interfaces WireGuard détectées dans /etc/wireguard/, avec leur état actif/arrêté.", + "settings.full_backup_create_failed": "Impossible de créer la sauvegarde complète", + "settings.full_backup_creating": "Création de la sauvegarde complète…", + "settings.full_backup_download": "Créer", + "settings.full_backup_downloaded": "Sauvegarde créée et téléchargée. Conservez-la en sécurité.", + "settings.full_backup_downloaded_short": "Sauvegarde complète téléchargée.", + "settings.full_backup_help": "Crée une sauvegarde portable WGTools pour migration ou reprise après incident : configurations WireGuard, utilisateurs, paramètres, groupes, clients gérés et données nécessaires pour reconnecter les tenants VPS Relay conservés.", + "settings.full_backup_no_file": "Aucune sauvegarde sélectionnée", + "settings.full_backup_restore": "Restaurer", + "settings.full_backup_restore_confirm": "Restaurer cette sauvegarde complète ? Les utilisateurs, paramètres, clients gérés et configurations WireGuard contenus dans l’archive seront restaurés. Des interfaces peuvent redémarrer. WGTools crée d’abord une sauvegarde de sécurité et annule automatiquement en cas d’échec.", + "settings.full_backup_restore_failed": "Échec de la restauration", + "settings.full_backup_restored": "Sauvegarde restaurée. Connectez-vous avec un compte de la sauvegarde.", + "settings.full_backup_restored_short": "Sauvegarde restaurée.", + "settings.full_backup_restoring": "Validation de la sauvegarde, création d’une copie de sécurité et restauration…", + "settings.full_backup_secret_warning": "Ce fichier contient des secrets : clés privées WireGuard et clients, PSK, empreintes des mots de passe WGTools, jeton du bot Telegram et mot de passe SMTP enregistré. Protégez-le comme un mot de passe ; ne le publiez jamais dans des issues ou chats.", + "settings.full_backup_select": "Sélectionner", + "settings.full_backup_title": "Sauvegarde complète et restauration", + "settings.full_mode": "Gestion serveur et clients activée", + "settings.interface_help": "L’interface WireGuard gérée est choisie lors du déploiement WGTools.", + "settings.language": "Langue", + "settings.last_backup": "Dernière sauvegarde", + "settings.latest_version": "Dernière version", + "settings.loading_config": "Chargement de la configuration…", + "settings.mode": "Mode", + "settings.never_logged_in": "Jamais", + "settings.new_password": "Nouveau mot de passe", + "settings.no_backups": "Aucune sauvegarde", + "settings.online_help": "Un pair est en ligne si sa dernière poignée de main est plus récente que cette valeur. 30 à 3600 secondes.", + "settings.online_threshold": "Seuil de connexion", + "settings.open_release": "Ouvrir la version", + "settings.password_changed": "Mot de passe modifié.", + "settings.passwords_mismatch": "Les mots de passe ne correspondent pas.", + "settings.project_github": "Projet / GitHub", + "settings.raw_config_confirm": "Enregistrer et appliquer la configuration WireGuard ? L’interface sélectionnée redémarrera. Une sauvegarde est créée au préalable ; WGTools restaurera automatiquement l’ancienne configuration en cas d’échec.", + "settings.raw_config_help": "Ouvrir la configuration source de l’interface WireGuard sélectionnée.", + "settings.raw_config_title": "Configuration WireGuard brute", + "settings.raw_config_warning": "Mode expert : configuration réelle du serveur WireGuard contenant la clé privée du serveur et les PSK des pairs. Enregistrer et appliquer redémarre l’interface. WGTools crée une sauvegarde et restaure automatiquement en cas d’échec.", + "settings.readonly_mode": "Gestion des clients activée", + "settings.refresh_help": "Fréquence de mise à jour des données d’état. De 2 à 60 secondes.", + "settings.refresh_interval": "Intervalle d'actualisation", + "settings.release_notes": "Notes de version", + "settings.reload_config": "Recharger depuis le disque", + "settings.save_apply": "Enregistrer et appliquer", + "settings.saved": "Paramètres enregistrés.", + "settings.saved_reload": "Paramètres enregistrés. Rechargement…", + "settings.saving": "Enregistrement des paramètres…", + "settings.status": "Actualisation de l’état", + "settings.status_help": "Fréquence d’actualisation du tableau de bord et des pairs.", + "settings.subtitle": "Préférences de l’interface et paramètres d’état WGTools.", + "settings.syntax_hint": "Sections, clés, valeurs et commentaires WireGuard sont colorés pendant l’édition.", + "settings.tab_about": "À propos", + "settings.tab_backups": "Sauvegardes", + "settings.tab_general": "Général", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Utilisateurs", + "settings.tabs_aria": "Sections des paramètres", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "ID utilisateur Telegram autorisés", + "settings.telegram_allowed_ids_help": "Un ID numérique par ligne. Un message /start non autorisé renverra l’ID Telegram de l’expéditeur, pour l’ajouter ici.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connecté", + "settings.telegram_disabled": "Désactivé", + "settings.telegram_dns": "DNS client par défaut", + "settings.telegram_dns_help": "Adresses DNS IPv4 facultatives séparées par des virgules. Utilisées pour les clients créés par le bot.", + "settings.telegram_enabled": "Activer le bot Telegram", + "settings.telegram_endpoint": "Adresse / domaine serveur par défaut", + "settings.telegram_endpoint_help": "Utilisée par le bot pour créer une configuration client. Saisissez seulement IP ou domaine ; le port WireGuard vient de la configuration serveur.", + "settings.telegram_language": "Langue du bot", + "settings.telegram_language_auto": "Auto (langue Telegram)", + "settings.telegram_last_poll": "Dernier contact Telegram", + "settings.telegram_not_configured": "Non configuré", + "settings.telegram_remove_token": "Supprimer le jeton", + "settings.telegram_remove_token_confirm": "Supprimer le jeton Telegram enregistré et désactiver le bot ?", + "settings.telegram_save": "Enregistrer les paramètres Telegram", + "settings.telegram_saved": "Paramètres Telegram enregistrés.", + "settings.telegram_setup_note": "Créez un bot avec @BotFather, enregistrez son jeton, activez-le et envoyez /start. Si votre ID n’est pas autorisé, WGTools l’affichera : ajoutez-le à la liste.", + "settings.telegram_status": "Statut du bot", + "settings.telegram_subtitle": "Gestion WireGuard à distance via Telegram : état serveur, clients, création/suppression et démarrage/redémarrage/arrêt.", + "settings.telegram_test": "Tester la connexion", + "settings.telegram_test_ok": "Connexion Telegram opérationnelle : @{username}", + "settings.telegram_test_recent_ok": "Le bot Telegram fonctionne. Le test direct a expiré, mais le bot a contacté Telegram récemment.", + "settings.telegram_token": "Jeton du bot", + "settings.telegram_token_help": "Créez un bot avec @BotFather et collez son jeton API ici. Aucun API ID ni API Hash n’est nécessaire pour l’API Bot.", + "settings.telegram_token_keep": "Laissez vide pour conserver le jeton actuel.", + "settings.telegram_waiting": "Configuré, en attente du service bot", + "settings.theme": "Thème", + "settings.theme_dark": "Sombre", + "settings.theme_light": "Clair", + "settings.theme_system": "Système", + "settings.title": "Paramètres", + "settings.update_available": "Mise à jour disponible", + "settings.update_backup_queued": "Mise à jour en attente. WGTools créera une sauvegarde complète avant installation…", + "settings.update_backup_running": "Création de la sauvegarde complète avant mise à jour…", + "settings.update_check_failed": "Impossible de vérifier les mises à jour", + "settings.update_checking": "Vérification de la dernière version publiée sur GitHub…", + "settings.update_confirm": "Mettre WGTools à jour de v{current} vers v{latest} ? Une sauvegarde complète et une copie pour retour arrière seront créées. L’interface web redémarrera brièvement.", + "settings.update_current": "À jour", + "settings.update_downloading": "Téléchargement et validation de la version GitHub…", + "settings.update_failed": "Échec de la mise à jour WGTools.", + "settings.update_installing": "Installation de la mise à jour. L’interface web peut être brièvement indisponible…", + "settings.update_no_update": "WGTools est déjà à jour.", + "settings.update_not_checked": "Non vérifié", + "settings.update_queued": "Mise à jour en attente du service de mise à jour…", + "settings.update_rollback_ok": "L’application WGTools précédente a été restaurée automatiquement.", + "settings.update_rolling_back": "Échec de la mise à jour. Restauration de la version précédente…", + "settings.update_running": "Création des sauvegardes de sécurité…", + "settings.update_safety_hint": "Les mises à jour nécessitent votre accord. WGTools crée une sauvegarde complète et une copie de retour arrière avant installation. En cas d’échec, l’ancienne application est restaurée automatiquement. WireGuard n’est pas redémarré, sauf si la nouvelle version modifie explicitement sa configuration.", + "settings.update_sidebar": "Nouvelle version disponible", + "settings.update_sidebar_hint": "Paramètres → À propos", + "settings.update_starting": "Démarrage de la mise à jour…", + "settings.update_status_unknown": "État de la mise à jour indisponible. Nouvelle tentative…", + "settings.update_subtitle": "Informations du projet, vérification automatique des versions et mises à jour sécurisées depuis GitHub Releases.", + "settings.update_success": "WGTools mis à jour vers v{version}. Rechargement…", + "settings.update_wgtools": "Mettre à jour WGTools", + "settings.user_actions": "Actions", + "settings.user_created": "Créé", + "settings.user_created_ok": "Utilisateur créé.", + "settings.user_deleted": "Utilisateur supprimé.", + "settings.user_equal_rights": "Tous les utilisateurs WGTools disposent des mêmes autorisations.", + "settings.user_last_login": "Dernière connexion", + "settings.user_name": "Nom d’utilisateur", + "settings.users": "Utilisateurs", + "settings.users_subtitle": "Comptes locaux WGTools. L’e-mail est facultatif et sert uniquement à récupérer le mot de passe lorsque la messagerie est activée.", + "vps.add": "Ajouter un VPS", + "vps.add_help": "WGTools utilise SSH pour vérifier ou installer le relais. Les mots de passe et clés SSH privées ne sont jamais stockés.", + "vps.add_title": "Ajouter un VPS", + "vps.agent": "Agent relais", + "vps.agent_found": "Déjà installé", + "vps.agent_will_install": "Sera installé", + "vps.arch": "Architecture", + "vps.auth_method": "Authentification", + "vps.authentication": "Authentification SSH", + "vps.check": "Vérifier le VPS", + "vps.check_failed": "Échec de la vérification VPS", + "vps.check_link": "Vérifier la liaison", + "vps.check_ok": "VPS compatible", + "vps.checking": "Vérification SSH et compatibilité VPS…", + "vps.connections": "connexions", + "vps.credentials_not_saved": "Utilisés uniquement pour ce contrôle, sans stockage par WGTools.", + "vps.delete_candidate": "Retirer", + "vps.delete_installed": "Retirer le VPS", + "vps.delete_installed_confirm": "Retirer « {name} » de WGTools ? Le transport local sera déconnecté, mais l’agent Relay et son espace sur le VPS seront conservés. Vous pourrez ajouter ce VPS à nouveau pour réutiliser le même relais. Les clients ne pourront pas s’y connecter avant reconnexion.", + "vps.delete_installed_failed": "Impossible de retirer le VPS de WGTools", + "vps.delete_installed_ok": "VPS retiré de WGTools. Le relais distant est conservé et peut être reconnecté.", + "vps.empty_help": "Ajoutez un VPS Debian ou Ubuntu pour vérifier SSH, la compatibilité du système et les ports UDP nécessaires.", + "vps.empty_title": "Aucun VPS configuré", + "vps.endpoint": "Endpoint public", + "vps.endpoint_domain": "Domaine (recommandé)", + "vps.endpoint_domain_hint": "Si vous remplacez le VPS principal, changer le DNS peut éviter de modifier les configurations client.", + "vps.health_failed": "Échec de la vérification du relais", + "vps.host": "IP / nom d’hôte", + "vps.host_key": "Clé de l’hôte SSH", + "vps.identity": "Connexion VPS", + "vps.install_failed": "Échec de l’installation du relais", + "vps.install_ok": "Relais installé et liaison d’administration sécurisée vérifiée", + "vps.install_relay": "Installer le relais", + "vps.install_title": "Installer le relais VPS", + "vps.installed": "Installé", + "vps.installing": "Installation de l’agent Relay et établissement du tunnel sécurisé…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Phrase secrète de la clé", + "vps.link_ok": "Liaison Relay OK", + "vps.multi_tenant_note": "Un agent Relay WGTools fonctionne déjà sur ce VPS. Il ne sera pas remplacé : ce WGTools recevra une connexion isolée avec ses propres clés et ports UDP.", + "vps.name": "Nom", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Sera installé", + "vps.os": "Système d’exploitation", + "vps.password": "Mot de passe", + "vps.phase_note": "L’agent Relay accepte plusieurs contrôleurs WGTools indépendants sur un VPS. Chaque contrôleur dispose d’une connexion, de clés et ports UDP isolés ; les connexions existantes restent intactes.", + "vps.port_pair": "Ports UDP", + "vps.ports_adjusted": "ports libres sélectionnés", + "vps.private_key": "Clé privée", + "vps.privilege": "Privilèges", + "vps.public_endpoint": "Futur endpoint public", + "vps.ready_help": "Les identifiants SSH servent uniquement à vérifier la compatibilité et installer immédiatement le relais ; ils ne sont pas enregistrés.", + "vps.reconnect_note": "Une connexion Relay de ce WGTools existe déjà sur le VPS. WGTools reconnectera le même espace sans créer de nouveau tenant ni de ports UDP.", + "vps.reconnect_ok": "Relais existant reconnecté avec succès", + "vps.reconnect_relay": "Reconnecter le relais", + "vps.relay_port": "Port UDP du relais", + "vps.remove_confirm": "Retirer ce candidat VPS ? Aucune modification distante n’a été effectuée.", + "vps.save_candidate": "Enregistrer le candidat", + "vps.saved": "Candidat VPS enregistré", + "vps.ssh": "SSH", + "vps.ssh_key": "Clé SSH", + "vps.ssh_port": "Port SSH", + "vps.ssh_user": "Utilisateur SSH", + "vps.status_candidate": "Prêt à installer", + "vps.status_installed": "Relais connecté", + "vps.subtitle": "Préparez un VPS public pour l’accès distant lorsque ce serveur WGTools ne possède pas d’IP publique.", + "vps.tenant": "Connexion", + "vps.title": "Relais VPS", + "vps.transport_port": "Port UDP de transport", + "vps.transport_port_hint": "Port UDP distinct pour le tunnel de transport privé domicile ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Enregistré", + "vps.active_short": "Actif", + "dashboard.traffic_reset": "Réinitialiser", + "dashboard.traffic_reset_confirm": "Réinitialiser les compteurs de trafic WireGuard de cette interface ? Les compteurs des clients repartiront aussi de zéro.", + "dashboard.traffic_reset_done": "Compteurs de trafic réinitialisés", + "dashboard.traffic_reset_failed": "Impossible de réinitialiser les compteurs", + "audit.action.traffic.reset": "Compteurs de trafic réinitialisés", + "audit.result.reset": "réinitialisé", + "server.mtu": "MTU", + "server.mtu_auto": "Auto", + "server.mtu_hint": "Facultatif. Laissez vide pour le MTU automatique de wg-quick. Définissez 1380 ou 1420 uniquement si nécessaire pour LTE ou PPPoE.", + "clients.peer_isolation": "Isolation des clients VPN", + "clients.peer_isolation_enable": "Isoler des autres clients VPN", + "clients.peer_isolation_hint": "Bloque le trafic entre ce client et les autres adresses du pool WireGuard. Les autres politiques régissent toujours l’accès au serveur, à Internet et aux réseaux locaux ou Site-to-site.", + "clients.credentials_rotate": "Clés du client", + "clients.credentials_rotate_button": "Renouveler les clés", + "clients.credentials_rotate_confirm": "Générer de nouvelles clés pour ce client ? Si connecté, sa session WireGuard sera immédiatement interrompue. Envoyez ensuite une nouvelle configuration ou un QR.", + "clients.credentials_rotate_confirm_psk": "Générer une nouvelle paire de clés et un PSK pour ce client ? Sa session WireGuard active sera interrompue immédiatement. Envoyez ensuite une nouvelle configuration ou un QR.", + "clients.credentials_rotate_hint": "Renouvelle PrivateKey/PublicKey et, si activé, le PSK. L’adresse, les routes, le groupe, l’horaire, l’isolation et les statistiques sont conservés.", + "clients.credentials_rotating": "Génération de nouvelles clés et fermeture de l’ancienne session…", + "clients.credentials_rotated": "Clés du client modifiées. Si connecté, son ancienne session a été interrompue. L’ancienne configuration ne fonctionne plus ; envoyez une nouvelle configuration ou un QR.", + "clients.credentials_rotated_short": "Clés modifiées — nouvelle configuration requise", + "audit.action.client.credentials_rotated": "Clés du client renouvelées", + "clients.credentials_connection_lost": "Connexion à WGTools interrompue. Si ce panneau utilisait le client dont les clés viennent de changer, c’est normal : son ancienne session WireGuard est coupée. Reconnectez-vous par un autre chemin et générez une nouvelle configuration ou un QR.", + "nav.navigation": "Navigation principale", + "nav.project_github": "WGTools sur GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Facultatif pour l’instant. Utilisable pour récupérer le mot de passe une fois la messagerie configurée.", + "auth.forgot_password": "Mot de passe oublié ?", + "auth.reset_title": "Réinitialiser le mot de passe", + "auth.reset_subtitle": "Recevez un code unique par e-mail et définissez un nouveau mot de passe WGTools.", + "auth.reset_identifier": "Nom d’utilisateur ou e-mail", + "auth.reset_identifier_help": "Pour préserver la confidentialité, WGTools affiche toujours la même réponse, que le compte existe ou non.", + "auth.send_reset_code": "Envoyer le code", + "auth.reset_code_sent_generic": "Si le compte existe et possède une adresse e-mail, un code a été envoyé. Il reste valable 15 minutes.", + "auth.reset_code": "Code à 6 chiffres", + "auth.set_new_password": "Définir un nouveau mot de passe", + "auth.request_another_code": "Demander un autre code", + "auth.back_to_login": "Retour à la connexion", + "auth.reset_not_configured": "La récupération du mot de passe par e-mail n’est pas configurée. Contactez l’administrateur WGTools.", + "settings.tab_mail": "Messagerie", + "settings.mail": "Messagerie / SMTP", + "settings.mail_subtitle": "SMTP sert à récupérer les mots de passe.", + "settings.mail_not_configured": "Non configuré", + "settings.mail_enabled": "Activer la messagerie et la récupération de mot de passe", + "settings.mail_smtp_host": "Serveur SMTP", + "settings.mail_smtp_port": "Port SMTP", + "settings.mail_security": "Chiffrement", + "settings.mail_security_none": "Sans chiffrement", + "settings.mail_username": "Nom d’utilisateur SMTP", + "settings.mail_username_help": "Utilisé pour l’authentification SMTP et comme adresse d’expéditeur.", + "settings.mail_password": "Mot de passe SMTP", + "settings.mail_password_keep": "Laissez vide pour conserver le mot de passe enregistré.", + "settings.mail_from_email": "E-mail expéditeur", + "settings.mail_from_name": "Nom de l’expéditeur", + "settings.mail_test_recipient": "Destinataire du test", + "settings.mail_test_recipient_help": "Le test utilise les paramètres SMTP actuellement enregistrés.", + "settings.mail_remove_password": "Supprimer le mot de passe", + "settings.mail_test": "Envoyer un test", + "settings.mail_save": "Enregistrer les paramètres mail", + "settings.mail_enabled_badge": "Activé", + "settings.mail_disabled_badge": "Désactivé", + "settings.mail_saved": "Paramètres mail enregistrés.", + "settings.mail_remove_password_confirm": "Supprimer le mot de passe SMTP enregistré et désactiver la messagerie ?", + "settings.mail_password_removed": "Mot de passe SMTP supprimé et messagerie désactivée.", + "settings.mail_test_recipient_required": "Saisissez l’adresse e-mail du destinataire du test.", + "settings.mail_testing": "Envoi de l’e-mail de test…", + "settings.mail_test_ok": "E-mail de test envoyé.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Facultatif. Nécessaire uniquement pour récupérer soi-même le mot de passe.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail enregistré.", + "settings.send_password_reset": "Envoyer une réinitialisation", + "settings.user_reset_mail_not_configured": "Configurez et activez d’abord la messagerie.", + "settings.user_reset_email_missing": "Ajoutez d’abord une adresse e-mail.", + "settings.user_reset_confirm": "Envoyer un code de réinitialisation à {name} à l’adresse {email} ?", + "settings.user_reset_sent": "Code de réinitialisation envoyé à {email}.", + "audit.action.auth.password_reset_requested": "Réinitialisation du mot de passe demandée", + "audit.action.auth.password_reset_code_sent": "Code de réinitialisation envoyé", + "audit.action.auth.password_reset_completed": "Mot de passe réinitialisé", + "audit.action.auth.password_reset_failed": "Échec de la réinitialisation du mot de passe", + "audit.action.mail.settings_updated": "Paramètres de messagerie modifiés", + "audit.action.mail.test_sent": "E-mail de test envoyé", + "audit.action.mail.test_failed": "Échec de l’e-mail de test", + "audit.action.user.email_changed": "E-mail utilisateur modifié", + "audit.action.user.password_reset_sent": "Réinitialisation envoyée à l’utilisateur", + "audit.action.user.password_reset_failed": "Échec du reset du mot de passe utilisateur", + "audit.result.accepted": "accepté", + "audit.result.sent": "envoyé", + "audit.result.invalid_code": "code invalide", + "common.copy": "Copier", + "common.copied": "Copié", + "clients.use_panel_host": "Utiliser l’adresse du panneau", + "clients.use_panel_host_done": "Adresse du panneau insérée : {host}", + "clients.use_panel_host_failed": "Impossible de déterminer l’adresse du panneau depuis l’URL du navigateur.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS Let’s Encrypt intégré pour accéder directement à WGTools sans proxy inverse.", + "settings.https_disabled": "Désactivé", + "settings.https_enabled": "Activé", + "settings.https_enable": "Activer HTTPS intégré", + "settings.https_type": "Certificat pour", + "settings.https_domain": "Domaine", + "settings.https_public_ip": "IP publique", + "settings.https_target": "Domaine ou IP publique", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "Port HTTPS", + "settings.https_port80_note": "Le port TCP 80 doit être accessible depuis Internet pour émettre et renouveler le certificat. Ouvrez aussi le port HTTPS choisi pour le panneau.", + "settings.https_check_ports": "Vérifier les ports", + "settings.https_certificate": "Certificat", + "settings.https_certificate_ready": "Prêt", + "settings.https_certificate_missing": "Non émis", + "settings.https_expires": "Valable jusqu’au", + "settings.https_renewal": "Renouvellement automatique", + "settings.https_renewal_enabled": "Activé", + "settings.https_renewal_disabled": "Désactivé", + "settings.https_certificate_path": "Certificat", + "settings.https_private_key_path": "Clé privée", + "settings.https_issue": "Obtenir / renouveler le certificat", + "settings.https_port_free": "Libre", + "settings.https_port_busy": "Occupé", + "settings.https_ports_checked": "Vérification des ports terminée.", + "settings.https_target_email_required": "Saisissez le domaine ou l’IP publique et l’e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Demander ou renouveler le certificat Let’s Encrypt pour {target} ? Les paramètres HTTPS seront enregistrés. Le port TCP 80 doit être accessible depuis Internet.", + "settings.https_issuing": "Demande de certificat auprès de Let’s Encrypt…", + "settings.https_issue_ok": "Certificat prêt.", + "settings.https_already_enabled": "HTTPS intégré est déjà activé.", + "settings.https_already_disabled": "HTTPS intégré est déjà désactivé.", + "settings.https_enable_confirm": "Activer HTTPS intégré sur TCP {port} avec le chemin {path} ? WGTools redémarrera et la page se reconnectera à la nouvelle adresse.", + "settings.https_disable_confirm": "Désactiver HTTPS intégré et revenir à HTTP ?", + "settings.https_switching": "Activation HTTPS et redémarrage de WGTools…", + "settings.https_switching_http": "Désactivation HTTPS et redémarrage de WGTools…", + "audit.action.https.certificate_issued": "Certificat HTTPS émis", + "audit.action.https.certificate_failed": "Échec de la demande de certificat HTTPS", + "audit.action.https.enabled": "HTTPS activé", + "audit.action.https.disabled": "HTTPS désactivé", + "audit.result.issued": "émis", + "audit.result.enabled": "activé", + "audit.result.disabled": "désactivé", + "settings.https_access_path": "Chemin d’accès au panneau", + "settings.https_access_path_help": "Choisissez votre propre chemin. Avec HTTPS intégré, les requêtes hors de ce chemin obtiennent une erreur 404.", + "settings.https_enable_fields_required": "Saisissez domaine/IP publique, e-mail Let’s Encrypt et chemin du panneau.", + "settings.https_use_panel_host": "Utiliser l’adresse du panneau", + "settings.https_reconnecting": "WGTools passe à la nouvelle adresse HTTPS…", + "server.tab_nodes": "Nœuds", + "common.type": "Type", + "common.status": "État", + "common.copy_failed": "Copie impossible", + "clients.vpn_address": "Adresse VPN", + "nodes.title": "Nœuds WGTools", + "nodes.subtitle": "Reliez plusieurs serveurs WGTools dans un réseau protégé et publiez uniquement les réseaux accessibles aux autres nœuds.", + "nodes.enable_hub": "Activer le HUB", + "nodes.connect_hub": "Se connecter au HUB", + "nodes.settings": "Paramètres des nœuds", + "nodes.settings_action": "Paramètres", + "nodes.sync_now": "Synchroniser", + "nodes.disable": "Désactiver les nœuds", + "nodes.disable_action": "Déconnecter", + "nodes.join_title": "Connecter de nouveaux nœuds", + "nodes.join_help": "Créez un code à usage unique et saisissez-le sur un autre panneau WGTools avec l’endpoint du HUB, par ex. vpn.example.com:51950. Le code est valable 15 minutes et une seule fois.", + "nodes.create_code": "Créer un code", + "nodes.connected_nodes": "Nœuds connectés", + "nodes.connected_nodes_help": "Informations sur les autres panneaux, réseaux publiés et clients. Les clients distants sont en lecture seule.", + "nodes.enable_hub_help": "Ce panneau devient le nœud central. Le même port accueille WireGuard en UDP et l’appairage initial sécurisé en TCP.", + "nodes.node_name": "Nom du nœud", + "nodes.transport_network": "Réseau de transport des nœuds", + "nodes.transport_help": "Réseau privé distinct réservé au transport entre WGTools. Il ne doit pas chevaucher vos réseaux VPN/LAN.", + "nodes.panel_url": "URL du panneau", + "nodes.panel_url_help": "Facultatif. Simple lien informatif du bouton « Ouvrir le panneau » sur les autres nœuds ; non utilisé pour la connexion Nodes.", + "nodes.extra_networks": "Réseaux de nœud supplémentaires", + "nodes.extra_networks_help": "Un réseau par ligne. Les réseaux VPN et les réseaux distants Site-to-site sont publiés automatiquement. Ajoutez seulement les autres LAN/réseaux routés, par ex. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools préremplit les réseaux VPN, Site-to-site et LAN routés détectés. Gardez uniquement les réseaux à publier. Un réseau par ligne.", + "nodes.published_networks_settings_help": "Un réseau par ligne. Liste explicite des réseaux publiés par ce nœud. Retirer une ligne cesse d’annoncer ce réseau aux autres nœuds.", + "nodes.available_networks_help": "Réseaux actuellement détectés : {networks}. Les nouveaux réseaux ne sont pas publiés automatiquement ; ajoutez ceux souhaités ci-dessus.", + "nodes.available_networks_none": "Aucun réseau local supplémentaire détecté.", + "nodes.connect_help": "Saisissez l’endpoint du HUB et le code à usage unique. L’URL, le port HTTPS, le certificat et le chemin privé du panneau ne servent pas à l’appairage.", + "nodes.join_code": "Code de connexion", + "nodes.connect_reachability_note": "L’appairage initial utilise TCP sécurisé sur le port indiqué. Une fois wgnode0 créé, réseaux, état, versions et données client en lecture seule se synchronisent avec le HUB via l’adresse WireGuard interne.", + "nodes.connect": "Connecter", + "nodes.settings_help": "Nom du nœud, lien « Ouvrir le panneau » facultatif et liste des réseaux publiés. L’URL du panneau n’est utilisée ni pour l’appairage ni pour la synchronisation.", + "nodes.details": "Détails", + "nodes.not_configured": "WGTools Nodes non configuré", + "nodes.not_configured_help": "Activez le HUB sur ce panneau ou connectez-le à un HUB WGTools existant.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connecté au HUB", + "nodes.mode_none": "Non configuré", + "nodes.role": "Rôle", + "nodes.tunnel": "Tunnel du nœud", + "nodes.node_ip": "Adresse du nœud", + "nodes.endpoint": "Endpoint du HUB", + "nodes.published_networks": "Réseaux publiés", + "nodes.last_sync": "Dernière synchronisation", + "nodes.no_nodes_hub": "Aucun nœud connecté. Créez un code et utilisez-le sur un autre panneau WGTools.", + "nodes.no_nodes_spoke": "Aucune information reçue sur les nœuds distants.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Ouvrir le panneau", + "nodes.route_conflict": "Conflit de routage", + "nodes.no_published_networks": "Aucun réseau publié", + "nodes.load_failed": "Impossible de charger WGTools Nodes", + "nodes.enable_hub_confirm": "Activer le HUB WGTools et créer le tunnel WireGuard interne ?", + "nodes.applying": "Configuration du tunnel WGTools Nodes…", + "nodes.enable_failed": "Impossible d’activer le HUB", + "nodes.hub_enabled": "HUB WGTools activé", + "nodes.connecting": "Vérification du code HUB et création du tunnel sécurisé…", + "nodes.connect_failed": "Impossible de se connecter au HUB", + "nodes.connected": "Connecté au HUB WGTools", + "nodes.settings_failed": "Impossible d’enregistrer les paramètres du nœud", + "nodes.settings_saved": "Paramètres du nœud enregistrés", + "nodes.code_failed": "Impossible de créer le code de connexion", + "nodes.code_expires": "Code à usage unique. Valable jusqu’à {time}.", + "nodes.code_copied": "Code de connexion copié", + "nodes.network_vpn": "Clients VPN", + "nodes.network_site_to_site": "Réseau Site-to-site", + "nodes.network_custom": "Réseau supplémentaire", + "nodes.conflict": "Conflit", + "nodes.remote_clients": "Clients (lecture seule)", + "nodes.no_clients": "Aucun client signalé par ce nœud", + "nodes.details_failed": "Impossible de charger les détails du nœud", + "nodes.remove_confirm": "Retirer le nœud « {name} » du HUB ? Son accès au tunnel interne sera révoqué.", + "nodes.remove_failed": "Impossible de retirer le nœud", + "nodes.removed": "Nœud retiré", + "nodes.disable_hub_confirm": "Désactiver le HUB et déconnecter tous les nœuds WGTools ? Le tunnel interne sera supprimé.", + "nodes.disconnect_confirm": "Déconnecter ce panneau WGTools du HUB et supprimer le tunnel interne ?", + "nodes.disable_failed": "Impossible de désactiver WGTools Nodes", + "nodes.disabled": "WGTools Nodes désactivé", + "nodes.sync_failed": "Échec de synchronisation des nœuds", + "nodes.synced": "Informations des nœuds synchronisées", + "nodes.service_port": "Port Nodes", + "nodes.service_port_help": "Le même numéro de port sert simultanément à WireGuard en UDP et à l’appairage initial protégé en TCP.", + "nodes.hub_port_forward_note": "Si le HUB est derrière un NAT, redirigez le même port en UDP et TCP vers lui. Le port web WGTools, HTTPS et le chemin privé sont indépendants de Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Domaine/IP et port Nodes sans http:// ni https://, par ex. vpn.example.com:51950.", + "settings.collapse_sidebar": "Réduire la barre latérale", + "settings.expand_sidebar": "Développer la barre latérale", + "settings.https_issue_fields_required": "Saisissez domaine/IP publique, e-mail Let’s Encrypt et chemin du panneau.", + "settings.https_issue_ok_saved": "Certificat prêt et paramètres HTTPS enregistrés.", + "settings.https_enable_need_certificate": "Obtenez d’abord un certificat.", + "settings.https_enable_certificate_mismatch": "Obtenez d’abord un certificat pour le domaine ou l’IP actuel.", + "settings.https_enable_certificate_expired": "Certificat expiré. Renouvelez-le avant d’activer HTTPS.", + "settings.https_enable_certificate_ready": "Certificat prêt : HTTPS intégré peut être activé.", + "settings.https_enable_active_help": "Décochez puis enregistrez pour revenir à HTTP.", + "settings.https_certificate_expired": "Expiré", + "settings.https_certificate_wrong_target": "Pour une autre adresse", + "nodes.network_conflict_error": "Les réseaux publiés chevauchent un autre nœud ou le réseau de transport Nodes : {conflicts}. Supprimez ou modifiez le réseau concerné.", + "nodes.networks_changed": "Les réseaux détectés ont changé depuis l’enregistrement. Nouveaux : {added}. Plus détectés : {removed}. Vérifiez puis enregistrez la liste publiée.", + "nodes.review_networks": "Vérifier les réseaux", + "nodes.vpn_pool_mismatch": "Pool VPN modifié : Nodes publie encore {old}, alors que le pool actuel est {current}. Ouvrez les paramètres et mettez à jour les réseaux publiés.", + "server.error_vpn_network_invalid": "Le réseau VPN doit être une adresse réseau IPv4 valide, par ex. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Seuls les réseaux VPN IPv4 sont pris en charge.", + "server.error_vpn_network_too_small": "Le réseau VPN doit contenir au moins deux adresses utilisables.", + "server.error_vpn_network_no_hosts": "Le réseau VPN choisi n’a aucune adresse serveur utilisable.", + "server.error_server_address_prefix": "L’adresse VPN du serveur doit inclure un préfixe, par ex. 10.0.0.1/24.", + "server.error_server_address_network": "L’adresse VPN du serveur doit appartenir au pool choisi et utiliser le même préfixe.", + "server.error_server_address_reserved": "L’adresse VPN du serveur ne peut être celle du réseau ni celle de diffusion.", + "server.error_listen_port_number": "Le port WireGuard doit être un nombre.", + "server.error_listen_port_range": "Le port WireGuard doit être compris entre 1 et 65535.", + "server.error_mtu_number": "Le MTU doit être un nombre.", + "auth.mfa_title": "Authentification à deux facteurs", + "auth.mfa_login_help": "Saisissez le code à 6 chiffres de Google Authenticator ou un code de récupération.", + "auth.mfa_code": "Code d’authentification", + "auth.mfa_verify": "Vérifier et se connecter", + "auth.mfa_back": "Retour au mot de passe", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Authentification à deux facteurs (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Activé", + "settings.mfa_disabled": "Désactivé", + "settings.mfa_google_help": "Protégez ce compte avec Google Authenticator ou une application TOTP. Votre mot de passe actuel est requis pour commencer.", + "settings.current_password": "Mot de passe actuel", + "settings.mfa_start": "Configurer Google Authenticator", + "settings.mfa_secret": "Clé de configuration manuelle", + "settings.mfa_scan_help": "Scannez le QR avec Google Authenticator puis saisissez le code actuel à 6 chiffres pour activer MFA.", + "settings.mfa_code": "Code à 6 chiffres", + "settings.mfa_enable": "Activer MFA", + "settings.mfa_manage_help": "Pour modifier MFA, saisissez le mot de passe actuel et un code Authenticator ou de récupération.", + "settings.mfa_code_or_recovery": "Code Authenticator ou de récupération", + "settings.mfa_regenerate": "Nouveaux codes de récupération", + "settings.mfa_disable": "Désactiver MFA", + "settings.mfa_recovery_title": "Codes de récupération", + "settings.mfa_recovery_help": "Enregistrez ces codes maintenant. Chacun sert une seule fois si Google Authenticator est indisponible. Ils ne seront plus affichés.", + "settings.mfa_recovery_remaining": "Codes de récupération restants : {count}", + "settings.mfa_enabled_ok": "MFA activée.", + "settings.mfa_disabled_ok": "MFA désactivée.", + "settings.mfa_disable_confirm": "Désactiver l’authentification à deux facteurs pour ce compte ?", + "settings.mfa_regenerate_confirm": "Remplacer tous les codes de récupération existants ?", + "settings.mfa_recovery_regenerated": "Nouveaux codes de récupération générés.", + "audit.action.auth.mfa_failed": "Échec de la vérification MFA", + "audit.action.auth.mfa_recovery_used": "Code de récupération MFA utilisé", + "audit.action.user.mfa_setup_started": "Configuration MFA démarrée", + "audit.action.user.mfa_enabled": "MFA activée", + "audit.action.user.mfa_disabled": "MFA désactivée", + "audit.action.user.mfa_disabled_cli": "MFA désactivée via CLI", + "audit.action.user.mfa_recovery_regenerated": "Codes de récupération MFA régénérés", + "settings.mfa_error_password": "Mot de passe actuel incorrect.", + "settings.mfa_error_code": "Code d’authentification invalide.", + "settings.mfa_error_already_enabled": "MFA est déjà activée.", + "settings.mfa_error_not_enabled": "MFA n’est pas activée.", + "settings.mfa_error_not_started": "Recommencez la configuration MFA.", + "trace.title": "Traceroute, ping et carte de l’itinéraire", + "trace.subtitle": "Mesurez la latence vers un VPS ou un autre serveur et repérez les retards sur le trajet.", + "trace.target": "IP ou nom d’hôte du serveur", + "trace.show_map": "Afficher le trajet sur la carte", + "trace.run": "Lancer le traceroute", + "trace.geo_note": "La géolocalisation est approximative. Si la carte est activée, les IP publiques des sauts sont envoyées à ipwho.is ; les tuiles proviennent d’OpenStreetMap.", + "trace.latency_note": "Traceroute mesure la latence en millisecondes, pas le débit en Mbit/s.", + "trace.map": "Carte de l’itinéraire", + "trace.map_hint": "Carte interactive : faites glisser, zoomez avec la molette ou +/− et cliquez sur un saut pour plus de détails.", + "trace.hop": "Saut / IP", + "trace.location": "Emplacement", + "trace.avg_rtt": "RTT moyen", + "trace.delta": "Δ RTT", + "trace.loss": "Perte", + "trace.summary_target": "Cible", + "trace.summary_ping": "Ping moyen", + "trace.summary_loss": "Perte de ping", + "trace.summary_hops": "Sauts", + "trace.no_reply": "Aucune réponse", + "trace.private": "Réseau privé", + "trace.unknown": "Inconnu", + "trace.running": "Ping et traceroute en cours… Cela peut prendre une minute.", + "trace.done": "Analyse du réseau terminée.", + "trace.failed": "Échec de l’analyse du réseau", + "trace.partial_geo": "Certains sauts publics n’ont pas pu être géolocalisés.", + "trace.not_reached": "La cible n’a pas été atteinte par traceroute.", + "trace.reached": "Cible atteinte", + "trace.ms": "ms", + "server.tab_trace": "Traçage", + "trace.map_controls": "Commandes de carte", + "trace.zoom_in": "Zoom avant", + "trace.zoom_out": "Zoom arrière", + "trace.fit_route": "Afficher tout le trajet", + "trace.fit": "Ajuster", + "trace.map_click_hint": "Cliquez sur un saut pour consulter l’IP, l’emplacement, l’ASN et le RTT.", + "trace.route_path": "Trajet", + "trace.ping_ok_trace_filtered": "La cible répond au ping, mais les derniers sauts traceroute ne répondent pas.", + "trace.latency_legend": "Augmentation de la latence entre sauts répondants", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — accru", + "trace.latency_bad": "Δ RTT > 20 ms — forte hausse" +} diff --git a/app/static/img/favicon.png b/app/static/img/favicon.png new file mode 100644 index 0000000..2362bb9 Binary files /dev/null and b/app/static/img/favicon.png differ diff --git a/app/static/img/wgtools-logo.png b/app/static/img/wgtools-logo.png new file mode 100644 index 0000000..9228c70 Binary files /dev/null and b/app/static/img/wgtools-logo.png differ diff --git a/app/static/it.json b/app/static/it.json new file mode 100644 index 0000000..885d3f8 --- /dev/null +++ b/app/static/it.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Crea utente", + "auth.login_subtitle": "Inserisci nome utente e password WGTools.", + "auth.login_title": "Accedi a WGTools", + "auth.password": "Password", + "auth.password_repeat": "Ripeti la password", + "auth.setup_help": "Il primo account ha accesso completo a WGTools. Puoi creare altri utenti in seguito nelle impostazioni.", + "auth.setup_subtitle": "Per gestire il server è necessario prima creare un account WGTools.", + "auth.setup_title": "Crea il primo utente", + "auth.sign_in": "Accedi", + "auth.sign_out": "Esci", + "auth.username": "Nome utente", + "clients.actions": "Azioni", + "clients.add": "+ Aggiungi client", + "clients.address": "Indirizzo VPN", + "clients.address_hint": "Il primo indirizzo libero viene suggerito automaticamente.", + "clients.allowed_ips_required": "Inserisci almeno una rete AllowedIPs per la configurazione client.", + "clients.basic_connection": "Impostazioni connessione", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs nella configurazione client", + "clients.config_private_warning": "Questa configurazione contiene la chiave privata del client. Conservala al sicuro.", + "clients.config_title": "Configurazione client", + "clients.config_unavailable": "Configurazione non disponibile", + "clients.connection_direct": "Direttamente a WGTools", + "clients.connection_path": "Percorso di connessione", + "clients.connection_relay": "Relay VPS", + "clients.connection_via": "Connetti tramite", + "clients.connection_via_hint": "Scegli l’accesso pubblico usato dal client. Il Relay appare solo se installato per l’interfaccia WireGuard scelta.", + "clients.copy_config": "Copia", + "clients.copy_done": "Configurazione copiata", + "clients.create_subtitle": "Crea un peer WireGuard e genera la configurazione client.", + "clients.create_title": "Crea client", + "clients.creating": "Creazione chiavi e applicazione client…", + "clients.day_fri": "Ven", + "clients.day_mon": "Lun", + "clients.day_sat": "Sab", + "clients.day_sun": "Dom", + "clients.day_thu": "Gio", + "clients.day_tue": "Mar", + "clients.day_wed": "Mer", + "clients.delete_confirm": "Eliminare questo client da WireGuard? WGTools creerà un backup e rimuoverà le regole automatiche associate.", + "clients.deleted": "Client eliminato", + "clients.dns": "DNS (facoltativo)", + "clients.dns_hint": "Server DNS IPv4 separati da virgole.", + "clients.download_config": "Scarica .conf", + "clients.duplicate": "Duplica", + "clients.duplicate_address_error": "Questo indirizzo VPN è già usato da un altro peer.", + "clients.duplicate_name_error": "Esiste già un peer con questo nome.", + "clients.duplicate_ready": "Copia pronta. WGTools ha assegnato un nuovo nome e indirizzo VPN. Controlla le impostazioni prima di salvare.", + "clients.duplicate_site_hint": "Le reti remote sono state rimosse per evitare route duplicate. Inserisci le reti del nuovo peer Site-to-site.", + "clients.duplicate_suffix": "copia", + "clients.edit_subtitle": "Aggiorna il peer sul server. Le modifiche vengono applicate senza riavviare WireGuard.", + "clients.edit_title": "Modifica client", + "clients.endpoint": "Endpoint server", + "clients.endpoint_hint": "Per i client remoti usa l’IP pubblico o dominio che inoltra la porta WireGuard a questo server.", + "clients.existing": "Peer esistente", + "clients.expiration": "Durata accesso", + "clients.expiration_action": "Alla scadenza", + "clients.expiration_action_hint": "Se deselezionato, il client resta in WGTools ma l’accesso WireGuard viene disabilitato. Scegli una nuova scadenza o Nessuna scadenza e salva per riattivarlo.", + "clients.expiration_datetime": "Scade il", + "clients.expiration_datetime_hint": "Usa data e ora locali di questo browser.", + "clients.expiration_delete": "Elimina client", + "clients.expiration_future_required": "Scegli una data e ora future.", + "clients.expiration_hint": "Alla scadenza WGTools esegue l’azione selezionata al minuto successivo. Prima crea un backup WireGuard.", + "clients.expire_1d": "1 giorno", + "clients.expire_1h": "1 ora", + "clients.expire_3h": "3 ore", + "clients.expire_6h": "6 ore", + "clients.expire_custom": "Data e ora personalizzate", + "clients.expire_never": "Nessuna scadenza", + "clients.expired": "Scaduto", + "clients.expired_disabled_hint": "L’accesso è scaduto. Il client è conservato, ma WireGuard è disabilitato. Scegli una nuova durata o Nessuna scadenza e salva.", + "clients.expired_disabled_short": "Scaduto · disabilitato", + "clients.expired_disabled_status": "Scaduto", + "clients.expires_days": "Scade tra {n} g", + "clients.expires_hours": "Scade tra {n} h", + "clients.expires_minutes": "Scade tra {n} min", + "clients.generated_config": "Configurazione client generata", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 secondi è un buon valore predefinito per client dietro NAT.", + "clients.local_access_exceptions": "Indirizzi locali consentiti", + "clients.local_access_exceptions_hint": "IP o CIDR facoltativi raggiungibili anche quando la rete locale o Site-to-site è bloccata. Separa con virgole.", + "clients.managed": "Gestito da WGTools", + "clients.name": "Nome", + "clients.no_peers": "Nessun peer trovato", + "clients.peers": "Peer", + "clients.peers_subtitle": "Le modifiche vengono salvate e applicate con wg syncconf senza riavviare l’interfaccia WireGuard.", + "clients.protected_networks_reference": "Reti locali bloccate (riferimento)", + "clients.protected_networks_reference_hint": "Queste reti non sono scritte in AllowedIPs. L’accesso è bloccato dai criteri server WGTools; puoi consentire singoli indirizzi sopra.", + "clients.psk": "Chiave precondivisa (PSK)", + "clients.psk_enable": "Usa una chiave WireGuard precondivisa aggiuntiva", + "clients.psk_hint": "Consigliato. Aggiunge un segreto simmetrico all’handshake WireGuard. I client standard lo supportano; WGTools inserisce il PSK nella configurazione e nel QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generazione QR…", + "clients.quick_search": "Ricerca rapida", + "clients.quick_search_clear": "Cancella ricerca", + "clients.quick_search_empty": "Nessun client corrispondente", + "clients.relay_endpoint_note": "La configurazione generata si connetterà a {endpoint}. Il server WireGuard resta su questo host WGTools.", + "clients.relay_required": "Scegli un Relay VPS per questo client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "non disponibile", + "clients.relay_vps": "Relay VPS", + "clients.relay_vps_hint": "L’endpoint del client viene generato automaticamente da questo Relay.", + "clients.remote_hint": "Reti dietro questo peer. Una per riga o separate da virgole.", + "clients.remote_networks": "Reti remote", + "clients.remote_required": "Inserisci almeno una rete remota per il peer Site-to-site.", + "clients.required": "Nome e indirizzo VPN sono obbligatori.", + "clients.route_custom": "Personalizzato", + "clients.route_full": "Tunnel completo", + "clients.route_full_except_local": "Tunnel completo eccetto reti locali", + "clients.route_hint": "Solo queste reti vengono inserite in AllowedIPs della configurazione client.", + "clients.route_preset": "Traffico tramite VPN", + "clients.route_vpn": "Solo rete VPN", + "clients.route_vpn_lan": "VPN + LAN locale", + "clients.saved": "Client salvato", + "clients.schedule_blocked_short": "Pianificazione · bloccato", + "clients.schedule_blocked_status": "Bloccato dalla pianificazione", + "clients.schedule_days": "Giorni consentiti", + "clients.schedule_days_required": "Scegli almeno un giorno per la pianificazione.", + "clients.schedule_disabled_hint": "Questo client è bloccato dalla pianificazione. WGTools ripristinerà automaticamente il peer al prossimo intervallo consentito.", + "clients.schedule_enable": "Limita accesso con pianificazione", + "clients.schedule_from": "Accesso dalle", + "clients.schedule_hint": "WGTools può disabilitare e riattivare il client nei giorni e orari scelti senza cambiarne la configurazione.", + "clients.schedule_short": "Pianificazione", + "clients.schedule_time_required": "Imposta ora di inizio e fine della pianificazione.", + "clients.schedule_timezone_hint": "La pianificazione usa l’ora locale del server WireGuard. Sono supportati intervalli notturni come 22:00–06:00.", + "clients.schedule_title": "Pianificazione accesso", + "clients.schedule_to": "Accesso fino alle", + "clients.security_access": "Sicurezza e orari di accesso", + "clients.server_host": "Indirizzo / dominio server", + "clients.server_host_hint": "IP pubblico o dominio usato dal client. I valori inseriti in precedenza sono suggeriti.", + "clients.server_host_required": "L’indirizzo / dominio server è obbligatorio per generare la configurazione.", + "clients.server_peer": "Peer server", + "clients.server_port": "Porta WireGuard", + "clients.server_port_hint": "Preso automaticamente dalla configurazione server.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Stato", + "clients.subtitle": "Peer WireGuard, stato in tempo reale e gestione configurazioni client.", + "clients.tab_basic": "Base", + "clients.tab_config": "Configurazione", + "clients.tab_policy": "Criteri", + "clients.tab_security": "Sicurezza", + "clients.title": "Client", + "clients.type": "Tipo", + "clients.unmanaged_note": "Questo peer esisteva prima di WGTools. La sua chiave privata non può essere recuperata. WGTools può modificare il peer server ma non può generarne configurazione client o QR.", + "clients.updating": "Aggiornamento client…", + "common.actions": "Azioni", + "common.ago": "fa", + "common.cancel": "Annulla", + "common.checking": "Verifica…", + "common.close": "Chiudi", + "common.config": "Configurazione", + "common.delete": "Elimina", + "common.disabled": "Disabilitato", + "common.edit": "Modifica", + "common.enabled": "Abilitato", + "common.loading": "Caricamento…", + "common.never": "Mai", + "common.no": "No", + "common.not_configured": "Non configurato", + "common.not_installed": "Non installato", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Aggiorna", + "common.running": "In esecuzione", + "common.save": "Salva", + "common.stopped": "Arrestato", + "common.total": "Totale", + "common.unknown": "Sconosciuto", + "common.updated": "Aggiornato", + "common.yes": "Sì", + "dashboard.active_peers": "Peer attivi", + "dashboard.active_peers_subtitle": "Dati in tempo reale da wg show.", + "dashboard.activity": "Panoramica del sistema", + "dashboard.activity_subtitle": "Controlli in sola lettura sul sistema WireGuard attivo.", + "dashboard.cores": "core", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Ultime 24 ore", + "dashboard.history_avg": "Media", + "dashboard.history_max": "Max", + "dashboard.history_min": "Min", + "dashboard.history_now": "ora", + "dashboard.memory": "Memoria", + "dashboard.network": "Rete", + "dashboard.peers": "Peer", + "dashboard.quick_search": "Ricerca rapida", + "dashboard.quick_search_clear": "Cancella ricerca", + "dashboard.quick_search_empty": "Nessun peer corrisponde alla ricerca", + "dashboard.restart": "Riavvia", + "dashboard.restart_confirm": "Riavviare WireGuard? I client VPN attivi si riconnetteranno automaticamente.", + "dashboard.restart_ok": "WireGuard riavviato.", + "dashboard.routing": "Instradamento", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Avvia", + "dashboard.start_ok": "WireGuard avviato.", + "dashboard.stop": "Arresta", + "dashboard.stop_confirm": "Arrestare WireGuard? I client VPN attivi verranno disconnessi.", + "dashboard.stop_ok": "WireGuard arrestato.", + "dashboard.subtitle": "Stato del server WireGuard, peer e traffico in tempo reale.", + "dashboard.title": "Panoramica", + "dashboard.traffic": "Traffico", + "dashboard.uptime": "Tempo di attività", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Criteri di accesso al server", + "groups.additional_allowed": "Indirizzi consentiti aggiuntivi", + "groups.additional_blocked": "Indirizzi bloccati aggiuntivi", + "groups.allow": "Consenti", + "groups.allowed": "Consentito", + "groups.allowed_addresses": "Indirizzi / reti consentiti", + "groups.apply_current_template": "Applica modello corrente del gruppo", + "groups.apply_defaults": "Applica modello corrente del gruppo", + "groups.apply_defaults_hint": "Copia route, DNS e Keepalive del gruppo in questo client. Salva il client, poi genera una nuova configurazione o QR se necessario.", + "groups.basic": "Informazioni di base", + "groups.block": "Blocca", + "groups.blocked": "Bloccato", + "groups.blocked_addresses": "Indirizzi / reti bloccati", + "groups.client_config_source": "Origine configurazione client", + "groups.client_defaults": "Valori predefiniti client", + "groups.client_group_hint": "Gruppo facoltativo per riutilizzare criteri di accesso e valori predefiniti. I gruppi appartengono all’interfaccia WireGuard selezionata.", + "groups.config_differs": "La configurazione del client differisce dai valori del gruppo. I criteri server sono aggiornati, ma telefono o PC cambieranno solo dopo un nuovo file o QR.", + "groups.config_differs_short": "Configurazione client diversa dal gruppo", + "groups.create": "Crea gruppo", + "groups.create_title": "Crea gruppo", + "groups.created": "Gruppo creato", + "groups.creating": "Creazione gruppo…", + "groups.defaults_applied": "Modello del gruppo applicato. Salva il client per mantenere le modifiche.", + "groups.defaults_hint": "Definisce il traffico inviato dal client tramite WireGuard. I criteri server definiscono separatamente cosa può raggiungere. Le modifiche al modello non cambiano i file già installati.", + "groups.delete_message": "Eliminare “{name}”? Le configurazioni dei client non vengono mai eliminate insieme al gruppo.", + "groups.delete_move": "Sposta i client in un altro gruppo", + "groups.delete_title": "Elimina gruppo client", + "groups.delete_unassign": "Rimuovi assegnazione del gruppo dai client", + "groups.deleted": "Gruppo eliminato", + "groups.deleting": "Aggiornamento client ed eliminazione gruppo…", + "groups.description": "Descrizione", + "groups.edit_title": "Modifica gruppo", + "groups.editor_subtitle": "Un gruppo combina criteri di accesso server attivi e un modello per le configurazioni client.", + "groups.effective_allow": "Eccezioni consentite", + "groups.effective_deny": "Eccezioni bloccate", + "groups.effective_policy": "Criteri server effettivi", + "groups.empty": "Non ci sono gruppi client. Creane uno per riutilizzare criteri di accesso e valori predefiniti.", + "groups.group": "Gruppo", + "groups.inherit": "Eredita", + "groups.internet_access": "Accesso a Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Reti locali", + "groups.local_short": "Locale", + "groups.manage": "Gruppi", + "groups.members_count": "{count} client", + "groups.name": "Nome", + "groups.name_required": "Il nome del gruppo è obbligatorio.", + "groups.new_client_defaults": "Modello configurazione client", + "groups.new_clients_short": "Nuovi client", + "groups.no_group": "Nessun gruppo", + "groups.none": "Nessuno", + "groups.override_client_config": "Sovrascrivi il modello client del gruppo per questo client", + "groups.override_client_config_hint": "Disattivato: route, DNS e Keepalive dal gruppo. Attivato: il client usa valori propri. Le eccezioni dei criteri server restano indipendenti.", + "groups.policy_addresses_hint": "Indirizzi IPv4 o CIDR separati da virgole. Le eccezioni client hanno precedenza sulle eccezioni del gruppo.", + "groups.policy_custom": "Criteri personalizzati", + "groups.policy_inherit": "Usa criteri del gruppo", + "groups.policy_mode": "Origine criteri", + "groups.policy_mode_hint": "I criteri di gruppo si ereditano per impostazione predefinita. Le eccezioni client non modificano il gruppo.", + "groups.routes_required": "Le route client non possono essere vuote.", + "groups.subtitle": "Riutilizza criteri di accesso server e valori predefiniti per i client dell’interfaccia WireGuard selezionata.", + "groups.title": "Gruppi client", + "groups.traffic_through_vpn": "Traffico tramite VPN", + "groups.updated": "Gruppo aggiornato", + "groups.updating": "Aggiornamento criteri gruppo…", + "help.example_note": "Gli indirizzi, le interfacce, i nomi dei peer e i domini degli esempi sono fittizi. Sostituiscili con i dati della tua rete.", + "help.navigation": "Navigazione della guida", + "help.open": "Apri la guida", + "help.subtitle": "Guida semplice per Dashboard, Server, Client e Impostazioni con brevi esempi pratici.", + "help.title": "Guida WGTools", + "interfaces.add": "+ Aggiungi interfaccia", + "interfaces.create": "Crea interfaccia", + "interfaces.create_confirm": "Creare e avviare l’interfaccia {name}?", + "interfaces.create_failed": "Impossibile creare l’interfaccia", + "interfaces.create_hint": "Prima di creare la configurazione, WGTools verifica che rete VPN, porta UDP e tabella di routing non siano in conflitto con altre interfacce WireGuard.", + "interfaces.create_subtitle": "Crea un’interfaccia WireGuard indipendente con pool di indirizzi, porta UDP e impostazioni di routing propri.", + "interfaces.create_title": "Aggiungi interfaccia WireGuard", + "interfaces.created": "Interfaccia creata correttamente.", + "interfaces.creating": "Generazione chiavi, scrittura configurazione e avvio di WireGuard…", + "interfaces.current": "Attuale", + "interfaces.delete": "Elimina", + "interfaces.delete_confirm": "Eliminare l’interfaccia {name}? La configurazione WireGuard e tutti i peer saranno rimossi. Prima viene creato un backup.", + "interfaces.delete_failed": "Impossibile eliminare l’interfaccia", + "interfaces.delete_last": "Non puoi eliminare qui l’ultima interfaccia WireGuard configurata.", + "interfaces.delete_tooltip": "Elimina questa interfaccia WireGuard", + "interfaces.deleted": "Interfaccia eliminata. Backup: {backup}", + "interfaces.deleting": "Arresto WireGuard ed eliminazione interfaccia…", + "interfaces.display_name": "Nome visualizzato", + "interfaces.display_name_edit_hint": "Solo nome visualizzato: il nome dell’interfaccia Linux non cambia.", + "interfaces.display_name_hint": "Nome facoltativo, ad es. Lavoro o Collaboratori.", + "interfaces.identity": "Identità interfaccia", + "interfaces.none": "Nessuna interfaccia WireGuard trovata", + "interfaces.none_configured": "Nessuna interfaccia WireGuard configurata.", + "interfaces.peers_short": "peer", + "interfaces.rename_failed": "Impossibile salvare il nome visualizzato dell’interfaccia.", + "interfaces.select": "Seleziona", + "interfaces.subtitle": "Ogni interfaccia ha rete VPN, porta, peer e criteri propri. Selezionane una per gestirla in WGTools.", + "interfaces.switch_title": "Interfacce WireGuard", + "interfaces.system_name": "Nome di sistema", + "interfaces.system_name_hint": "Nome interfaccia Linux, ad es. wg1. Non modificabile dopo la creazione.", + "interfaces.title": "Interfacce WireGuard", + "interfaces.unique_port_hint": "Ogni interfaccia WireGuard sul server deve usare una porta UDP distinta.", + "interfaces.unique_table_hint": "WGTools consiglia una tabella di routing separata per ogni interfaccia. Lascia vuoto per il routing normale.", + "nav.clients": "Client", + "nav.dashboard": "Panoramica", + "nav.server": "Server", + "nav.settings": "Impostazioni", + "server.access_apply_confirm": "Salvare e applicare la regola firewall? WireGuard verrà riavviato brevemente dopo un backup.", + "server.access_rule_deleted": "Regola di accesso eliminata.", + "server.access_rule_help": "Crea una regola di accesso FORWARD senza modificare i comandi iptables manualmente.", + "server.access_rule_order_hint": "WGTools inserisce le regole all’inizio di FORWARD affinché quelle restrittive precedano le regole VPN ACCEPT generali.", + "server.access_rule_saved": "Regola di accesso salvata e applicata.", + "server.action": "Azione", + "server.action_hint": "REJECT comunica al client il rifiuto; DROP scarta senza risposta; ACCEPT consente esplicitamente.", + "server.add_access_rule": "Aggiungi regola di accesso", + "server.add_route": "Aggiungi route", + "server.address": "Indirizzo", + "server.any": "Qualsiasi", + "server.any_protocol": "Qualsiasi", + "server.apply_confirm": "Salvare e applicare le impostazioni server? WireGuard verrà riavviato brevemente. WGTools crea un backup e ripristina automaticamente la configurazione se l’avvio fallisce.", + "server.apply_settings": "Salva e applica", + "server.applying_rule": "Creazione backup e applicazione…", + "server.applying_settings": "Convalida impostazioni, creazione backup e applicazione…", + "server.basic_settings": "Impostazioni di base", + "server.config_tab_help": "Apri editor della configurazione grezza dell’interfaccia WireGuard scelta.", + "server.create_confirm": "Creare e avviare il server WireGuard con queste impostazioni?", + "server.create_server": "Crea server", + "server.create_step_conf": "Crea configurazione dell’interfaccia WireGuard con permessi 600.", + "server.create_step_forward": "Configura forwarding, NAT e routing per policy opzionale.", + "server.create_step_key": "Genera nuova coppia di chiavi server.", + "server.create_step_start": "Abilita e avvia l’interfaccia wg-quick scelta.", + "server.create_subtitle": "WireGuard è installato, ma l’interfaccia selezionata non è configurata.", + "server.create_success": "Server WireGuard creato correttamente.", + "server.create_title": "Crea server WireGuard", + "server.creating": "Generazione chiavi, scrittura configurazione e avvio WireGuard…", + "server.custom_preserved": "Restano invariati blocchi peer, route Site-to-site e regole PostUp/PostDown personalizzate non gestite qui.", + "server.delete_access_confirm": "Eliminare questa regola di accesso e applicare?", + "server.delete_route_confirm": "Eliminare questa route personalizzata e applicare?", + "server.destination": "Destinazione", + "server.destination_hint": "Vuoto = qualsiasi. Accetta IP, CIDR o intervallo IP. Separa più destinazioni con virgole.", + "server.destination_port": "Porta destinazione", + "server.destination_port_hint": "Facoltativo. Porta come 443 o intervallo 10000:20000. Prima scegli TCP o UDP.", + "server.details": "Dettagli", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostica", + "server.diagnostics_done": "Diagnostica completata", + "server.diagnostics_subtitle": "Controlli correnti del sistema. Nessuna modifica alla configurazione.", + "server.direction": "Hook", + "server.edit_access_rule": "Modifica regola di accesso", + "server.edit_route": "Modifica route", + "server.edit_server": "Modifica server", + "server.edit_subtitle": "Modifica impostazioni comuni WireGuard, routing e NAT. Peer e regole personalizzate esistenti vengono mantenuti.", + "server.edit_title": "Impostazioni server", + "server.edit_warning": "Applicare impostazioni di interfaccia, routing o firewall riavvia brevemente WireGuard. I peer attivi si ricollegano da soli.", + "server.enable_forwarding": "Abilita forwarding IPv4", + "server.enable_nat": "Abilita NAT / Masquerade", + "server.firewall": "Firewall e NAT", + "server.firewall_subtitle": "Regole rilevate dagli hook WireGuard.", + "server.firewall_subtitle_v08": "Regole di forwarding/NAT e accesso dall’interfaccia. Le regole semplici si gestiscono qui; quelle avanzate nell’editor grezzo.", + "server.forward_from_vpn": "Consenti forwarding da VPN", + "server.forward_to_vpn": "Consenti forwarding verso VPN", + "server.forwarding_section": "Forwarding e NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Richiesto solo con una tabella di policy routing.", + "server.install_success": "WireGuard installato correttamente.", + "server.install_wireguard": "Installa WireGuard", + "server.install_wireguard_help": "Esegue apt update e installa WireGuard e gli strumenti di rete necessari.", + "server.install_wireguard_title": "Installa WireGuard", + "server.installing": "Installazione WireGuard… Potrebbe volerci un minuto.", + "server.interface": "Interfaccia", + "server.interface_hint": "WGTools gestisce attualmente questa interfaccia.", + "server.interface_name": "Interfaccia", + "server.interface_section": "Interfaccia WireGuard", + "server.ip_forwarding": "Forwarding IPv4", + "server.kind": "Tipo", + "server.listen_port": "Porta di ascolto", + "server.local_network": "Rete locale", + "server.local_network_hint": "Route facoltativa aggiunta alla tabella di routing.", + "server.managed_automatically": "Gestito automaticamente", + "server.nat": "NAT / Masquerade", + "server.network": "Rete", + "server.network_settings": "Rete e NAT", + "server.no_firewall": "Nessuna regola firewall trovata", + "server.no_routes": "Nessuna route trovata", + "server.not_configured": "Non configurato", + "server.not_set": "Non impostato", + "server.policy_disabled_hint": "Disattiva per il routing di sistema normale. Attiva solo se la VPN richiede una propria tabella basata sull’origine.", + "server.policy_enabled": "Abilita policy routing", + "server.policy_table": "Tabella policy", + "server.policy_table_hint": "Lascia vuoto per il routing normale; usa ad es. 200 per il routing basato sull’origine.", + "server.port_word": "porta", + "server.private_hidden": "Configurato (nascosto)", + "server.private_key": "Chiave privata", + "server.protocol": "Protocollo", + "server.route_apply_confirm": "Salvare e applicare la route? WireGuard verrà riavviato brevemente dopo un backup.", + "server.route_custom": "Personalizzata", + "server.route_deleted": "Route eliminata.", + "server.route_device_hint": "Interfaccia di uscita facoltativa, ad es. wg0 o enp6s18.", + "server.route_editor_help": "Aggiungi route installata all’avvio di WireGuard e rimossa all’arresto.", + "server.route_gateway_hint": "Gateway next-hop facoltativo. Serve un gateway o un’interfaccia.", + "server.route_managed_peer": "Peer Site-to-site", + "server.route_managed_server": "Impostazione server", + "server.route_network_hint": "Rete IPv4 come 10.20.0.0/24 o 'default'.", + "server.route_saved": "Route salvata e applicata.", + "server.route_table_hint": "Usa 'main' per il routing normale o una tabella numerica come 200.", + "server.route_type": "Tipo", + "server.routes": "Rotte rilevate", + "server.routes_subtitle": "Route estratte da PostUp/PostDown e dallo stato del policy routing.", + "server.routes_subtitle_v08": "Route server, Site-to-site e personalizzate dell’interfaccia selezionata. Qui puoi aggiungere, modificare e rimuovere route.", + "server.routing": "Instradamento", + "server.routing_section": "Instradamento", + "server.rule": "Regola", + "server.rule_access": "Regola di accesso", + "server.rule_advanced": "Avanzate", + "server.rule_apply_warning": "Applicare route o regole firewall riavvia brevemente WireGuard. WGTools crea un backup e ripristina la configurazione se l’avvio fallisce.", + "server.rule_client_exception": "Eccezione client", + "server.rule_client_policy": "Criterio client", + "server.rule_managed_server": "Impostazione server", + "server.rule_type": "Tipo", + "server.run_diagnostics": "Esegui diagnostica", + "server.save_apply": "Salva e applica", + "server.save_config": "SaveConfig", + "server.server_address": "Indirizzo VPN server", + "server.server_address_hint": "Di solito il primo indirizzo utilizzabile nella rete VPN.", + "server.settings_applied": "Impostazioni server salvate e applicate correttamente.", + "server.settings_apply_failed": "Impossibile applicare le impostazioni server", + "server.setup_required": "Configurazione necessaria", + "server.source": "Origine", + "server.source_hint": "Vuoto = qualsiasi. Accetta IP, CIDR o intervallo come 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installazione, configurazione iniziale e stato del server WireGuard.", + "server.tab_config": "Configurazione", + "server.tab_interface": "Interfaccia", + "server.tab_routing": "Instradamento", + "server.tab_vps": "VPS", + "server.table": "Tabella", + "server.tabs_aria": "Sezioni delle impostazioni server", + "server.title": "Server", + "server.uplink": "Interfaccia uplink", + "server.use_raw_editor": "Usa editor configurazione grezza", + "server.via": "Via / Dispositivo", + "server.via_word": "via", + "server.vpn_network": "Rete VPN", + "server.vpn_network_hint": "Gli indirizzi client verranno assegnati da questa rete.", + "server.vpn_pool": "Pool indirizzi VPN", + "server.wg_not_installed": "WireGuard non è installato", + "server.wg_not_installed_subtitle": "WGTools può installare automaticamente i pacchetti Debian necessari.", + "server.what_happens": "Operazioni di WGTools", + "settings.about": "Informazioni", + "settings.add_user": "Aggiungi utente", + "settings.advanced": "Avanzate", + "settings.advanced_subtitle": "Accesso diretto agli strumenti avanzati di configurazione WireGuard.", + "settings.appearance": "Aspetto", + "settings.applying_config": "Validazione configurazione, creazione backup e applicazione…", + "settings.backup_count": "Backup salvati", + "settings.backup_retention": "Backup da conservare", + "settings.backup_retention_help": "I vecchi backup automatici vengono eliminati dopo la creazione del nuovo. Da 1 a 200 file.", + "settings.backups": "Backup della configurazione", + "settings.backups_always_on": "Abilitato", + "settings.backups_subtitle": "WGTools crea automaticamente un backup prima di modificare la configurazione. I backup automatici non possono essere disabilitati.", + "settings.change_password": "Cambia password", + "settings.check_updates": "Controlla aggiornamenti", + "settings.config_applied": "Configurazione salvata e applicata correttamente.", + "settings.config_applied_restarted": "Configurazione applicata e WireGuard riavviato.", + "settings.config_applied_stopped": "Configurazione salvata. WireGuard era fermo e rimane fermo.", + "settings.config_apply_failed": "Impossibile applicare la configurazione", + "settings.config_load_failed": "Impossibile caricare la configurazione", + "settings.current_user": "Utente corrente", + "settings.current_version": "Versione attuale", + "settings.audit_action": "Azione", + "settings.audit_empty": "Nessun evento audit", + "settings.audit_log": "Registro audit", + "settings.audit_log_subtitle": "Azioni nel pannello, autenticazione, Telegram e cronologia delle connessioni WireGuard. I segreti non vengono registrati.", + "settings.audit_object": "Oggetto", + "settings.audit_result": "Risultato", + "settings.audit_retention_note": "Conservazione: 30 giorni", + "settings.audit_search": "Ricerca rapida", + "settings.audit_search_clear": "Cancella ricerca", + "settings.audit_search_empty": "Nessun evento audit corrispondente", + "settings.audit_time": "Data / ora", + "settings.audit_user": "Utente", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Regola di accesso creata", + "audit.action.access_rule.deleted": "Regola di accesso eliminata", + "audit.action.access_rule.updated": "Regola di accesso aggiornata", + "audit.action.auth.first_user_created": "Primo utente creato", + "audit.action.auth.login": "Accesso effettuato", + "audit.action.auth.login_failed": "Accesso non riuscito", + "audit.action.auth.logout": "Disconnessione effettuata", + "audit.action.backup.full_created": "Backup completo creato", + "audit.action.backup.full_restored": "Backup completo ripristinato", + "audit.action.client.config_downloaded": "Configurazione client scaricata", + "audit.action.client.config_viewed": "Configurazione client visualizzata", + "audit.action.client.created": "Client creato", + "audit.action.client.deleted": "Client eliminato", + "audit.action.client.qr_viewed": "Codice QR client visualizzato", + "audit.action.client.updated": "Client aggiornato", + "audit.action.client_group.created": "Gruppo client creato", + "audit.action.client_group.deleted": "Gruppo client eliminato", + "audit.action.client_group.updated": "Gruppo client aggiornato", + "audit.action.interface.created": "Interfaccia creata", + "audit.action.interface.deleted": "Interfaccia eliminata", + "audit.action.interface.renamed": "Interfaccia rinominata", + "audit.action.route.created": "Rotta creata", + "audit.action.route.deleted": "Rotta eliminata", + "audit.action.route.updated": "Rotta aggiornata", + "audit.action.server.created": "Server creato", + "audit.action.server.raw_config_applied": "Configurazione grezza applicata", + "audit.action.server.settings_applied": "Impostazioni server applicate", + "audit.action.settings.updated": "Impostazioni pannello aggiornate", + "audit.action.telegram.action_denied": "Azione Telegram negata", + "audit.action.telegram.action_failed": "Azione Telegram non riuscita", + "audit.action.telegram.connection_test": "Test connessione Telegram", + "audit.action.telegram.settings_updated": "Impostazioni Telegram aggiornate", + "audit.action.update.checked": "Aggiornamento verificato", + "audit.action.update.scheduled": "Aggiornamento pianificato", + "audit.action.update.backup_created": "Backup pre-aggiornamento", + "audit.action.update.completed": "Aggiornamento completato", + "audit.action.update.failed": "Aggiornamento non riuscito", + "audit.action.update.rollback_completed": "Versione precedente ripristinata", + "audit.action.update.rollback_failed": "Rollback aggiornamento non riuscito", + "audit.action.user.created": "Utente creato", + "audit.action.user.deleted": "Utente eliminato", + "audit.action.user.password_changed": "Password utente modificata", + "audit.action.vps.candidate_deleted": "Candidato VPS eliminato", + "audit.action.vps.candidate_saved": "Candidato VPS salvato", + "audit.action.vps.detached": "Relay VPS scollegato", + "audit.action.vps.relay_installed": "Relay VPS installato", + "audit.action.wireguard.client_connected": "Client WireGuard connesso", + "audit.action.wireguard.installed": "WireGuard installato", + "audit.action.wireguard.restarted": "WireGuard riavviato", + "audit.action.wireguard.started": "WireGuard avviato", + "audit.action.wireguard.stopped": "WireGuard arrestato", + "audit.result.applied": "applicato", + "audit.result.available": "disponibile", + "audit.result.changed": "modificato", + "audit.result.created": "creato", + "audit.result.current": "attuale", + "audit.result.deleted": "eliminato", + "audit.result.detached": "scollegato", + "audit.result.denied": "negato", + "audit.result.downloaded": "scaricato", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Errore", + "audit.result.installed": "installato", + "audit.result.invalid_credentials": "credenziali non valide", + "audit.result.ok": "OK", + "audit.result.queued": "in coda", + "audit.result.restarted": "riavviato", + "audit.result.restored": "ripristinato", + "audit.result.rotated": "rigenerato", + "audit.result.saved": "salvato", + "audit.result.shown": "mostrato", + "audit.result.started": "avviato", + "audit.result.stopped": "arrestato", + "audit.result.updated": "aggiornato", + "settings.delete_user": "Elimina", + "settings.delete_user_confirm": "Eliminare l’utente {name}?", + "settings.edit_raw_config": "Modifica configurazione interfaccia", + "settings.expert_mode": "Esperto", + "settings.full_backup_component_clients": "Metadati dei client gestiti, chiavi private, PSK, scadenze e gruppi necessari per rigenerare configurazioni e QR.", + "settings.full_backup_component_db": "Database WGTools: utenti, preferenze, email/SMTP, Telegram e stato salvato di VPS Relay.", + "settings.full_backup_component_relay": "Dati di recupero VPS Relay: ID controller/tenant, token di gestione e chiave di trasporto Home. Dopo il ripristino WGTools può ricreare il trasporto locale e riconnettere il tenant.", + "settings.full_backup_component_system": "File sysctl IPv4 forwarding WGTools, metadati dei nomi interfaccia e criteri/modelli gruppo, se presenti. La cronologia automatica è esclusa intenzionalmente.", + "settings.full_backup_component_wg": "Tutte le configurazioni WireGuard rilevate in /etc/wireguard/, incluso lo stato attivo/fermo.", + "settings.full_backup_create_failed": "Impossibile creare backup completo", + "settings.full_backup_creating": "Creazione backup completo…", + "settings.full_backup_download": "Crea", + "settings.full_backup_downloaded": "Backup creato e scaricato. Conservalo al sicuro.", + "settings.full_backup_downloaded_short": "Backup completo scaricato.", + "settings.full_backup_help": "Crea un backup WGTools portatile per migrazione o emergenze: configurazioni WireGuard, utenti, impostazioni, gruppi, client gestiti e dati per riconnettere i tenant VPS Relay conservati.", + "settings.full_backup_no_file": "Nessun backup selezionato", + "settings.full_backup_restore": "Ripristina", + "settings.full_backup_restore_confirm": "Ripristinare il backup completo WGTools? Verranno ripristinati utenti, impostazioni, client gestiti e configurazioni WireGuard incluse. Le interfacce potrebbero riavviarsi. WGTools crea prima un backup di sicurezza e annulla automaticamente in caso di errore.", + "settings.full_backup_restore_failed": "Ripristino non riuscito", + "settings.full_backup_restored": "Backup ripristinato. Accedi con un account presente nel backup.", + "settings.full_backup_restored_short": "Backup ripristinato.", + "settings.full_backup_restoring": "Verifica backup, creazione copia di sicurezza e ripristino…", + "settings.full_backup_secret_warning": "Il file contiene dati sensibili: chiavi private WireGuard e dei client, PSK, hash delle password WGTools, token bot Telegram e password SMTP salvata. Custodiscilo come una password e non allegarlo mai a issue o chat pubbliche.", + "settings.full_backup_select": "Seleziona", + "settings.full_backup_title": "Backup completo e ripristino", + "settings.full_mode": "Gestione server e client attiva", + "settings.interface_help": "L’interfaccia WireGuard gestita viene scelta durante l’installazione di WGTools.", + "settings.language": "Lingua", + "settings.last_backup": "Ultimo backup", + "settings.latest_version": "Ultima versione", + "settings.loading_config": "Caricamento configurazione…", + "settings.mode": "Modalità", + "settings.never_logged_in": "Mai", + "settings.new_password": "Nuova password", + "settings.no_backups": "Nessun backup", + "settings.online_help": "Un peer è online se il suo ultimo handshake è più recente della soglia. 30–3600 secondi.", + "settings.online_threshold": "Soglia online", + "settings.open_release": "Apri release", + "settings.password_changed": "Password modificata.", + "settings.passwords_mismatch": "Le password non coincidono.", + "settings.project_github": "Progetto / GitHub", + "settings.raw_config_confirm": "Salvare e applicare questa configurazione WireGuard? L’interfaccia selezionata verrà riavviata. Prima viene creato un backup; WGTools ripristina quella precedente se l’avvio fallisce.", + "settings.raw_config_help": "Apri la configurazione sorgente dell’interfaccia WireGuard scelta.", + "settings.raw_config_title": "Configurazione WireGuard grezza", + "settings.raw_config_warning": "Modalità esperto: questa è la vera configurazione server WireGuard e contiene la chiave privata e i PSK dei peer. Salvare e applicare riavvia l’interfaccia. WGTools crea prima un backup e ripristina se l’avvio fallisce.", + "settings.readonly_mode": "Gestione client attiva", + "settings.refresh_help": "Frequenza di aggiornamento dello stato. Da 2 a 60 secondi.", + "settings.refresh_interval": "Intervallo di aggiornamento", + "settings.release_notes": "Note di rilascio", + "settings.reload_config": "Ricarica da disco", + "settings.save_apply": "Salva e applica", + "settings.saved": "Impostazioni salvate.", + "settings.saved_reload": "Impostazioni salvate. Ricaricamento…", + "settings.saving": "Salvataggio impostazioni…", + "settings.status": "Aggiornamento stato", + "settings.status_help": "Intervalli di aggiornamento Dashboard e stato dei peer.", + "settings.subtitle": "Preferenze interfaccia e impostazioni stato WGTools.", + "settings.syntax_hint": "Sezioni, chiavi, valori e commenti WireGuard sono evidenziati durante la modifica.", + "settings.tab_about": "Informazioni", + "settings.tab_backups": "Backup", + "settings.tab_general": "Generale", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Utenti", + "settings.tabs_aria": "Sezioni impostazioni", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "ID utenti Telegram consentiti", + "settings.telegram_allowed_ids_help": "Un ID numerico per riga. Un /start non autorizzato risponderà con l’ID Telegram del mittente, che potrai aggiungere qui.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connesso", + "settings.telegram_disabled": "Disabilitato", + "settings.telegram_dns": "DNS client predefinito", + "settings.telegram_dns_help": "Indirizzi DNS IPv4 facoltativi, separati da virgole. Usati per client creati dal bot.", + "settings.telegram_enabled": "Abilita bot Telegram", + "settings.telegram_endpoint": "Indirizzo / dominio server predefinito", + "settings.telegram_endpoint_help": "Usato dal bot per nuove configurazioni client. Inserisci solo IP o dominio; la porta WireGuard è letta dalla configurazione server.", + "settings.telegram_language": "Lingua del bot", + "settings.telegram_language_auto": "Auto (lingua Telegram)", + "settings.telegram_last_poll": "Ultimo contatto Telegram", + "settings.telegram_not_configured": "Non configurato", + "settings.telegram_remove_token": "Rimuovi token", + "settings.telegram_remove_token_confirm": "Rimuovere il token del bot Telegram salvato e disabilitare il bot?", + "settings.telegram_save": "Salva impostazioni Telegram", + "settings.telegram_saved": "Impostazioni Telegram salvate.", + "settings.telegram_setup_note": "Crea un bot con @BotFather, salva il token, attivalo e invia /start. Se il tuo ID non è autorizzato, WGTools lo mostrerà: aggiungilo alla lista degli ID consentiti.", + "settings.telegram_status": "Stato del bot", + "settings.telegram_subtitle": "Gestione WireGuard da Telegram: stato server, client, creazione/eliminazione e avvio/riavvio/arresto.", + "settings.telegram_test": "Testa connessione", + "settings.telegram_test_ok": "Connessione Telegram funzionante: @{username}", + "settings.telegram_test_recent_ok": "Il bot Telegram funziona. Il controllo diretto è scaduto, ma il bot ha contattato Telegram di recente.", + "settings.telegram_token": "Token del bot", + "settings.telegram_token_help": "Crea un bot con @BotFather e incolla qui il token Bot API. API ID e API Hash non sono richiesti.", + "settings.telegram_token_keep": "Lascia vuoto per conservare il token salvato.", + "settings.telegram_waiting": "Configurato, in attesa del servizio bot", + "settings.theme": "Tema", + "settings.theme_dark": "Scuro", + "settings.theme_light": "Chiaro", + "settings.theme_system": "Sistema", + "settings.title": "Impostazioni", + "settings.update_available": "Aggiornamento disponibile", + "settings.update_backup_queued": "Aggiornamento in coda. WGTools creerà un backup completo automatico prima dell’installazione…", + "settings.update_backup_running": "Creazione del backup completo prima dell’aggiornamento…", + "settings.update_check_failed": "Impossibile verificare aggiornamenti", + "settings.update_checking": "Verifica dell’ultima release pubblicata su GitHub…", + "settings.update_confirm": "Aggiornare WGTools da v{current} a v{latest}? Prima verranno creati un backup completo e una copia per il rollback. L’interfaccia web si riavvierà brevemente.", + "settings.update_current": "Aggiornato", + "settings.update_downloading": "Download e verifica della release GitHub…", + "settings.update_failed": "Aggiornamento WGTools non riuscito.", + "settings.update_installing": "Installazione aggiornamento. L’interfaccia web potrebbe non essere disponibile per poco…", + "settings.update_no_update": "WGTools è già aggiornato.", + "settings.update_not_checked": "Non verificato", + "settings.update_queued": "Aggiornamento in coda. In attesa del servizio updater…", + "settings.update_rollback_ok": "La precedente applicazione WGTools è stata ripristinata automaticamente.", + "settings.update_rolling_back": "Aggiornamento non riuscito. Ripristino versione WGTools precedente…", + "settings.update_running": "Creazione backup di sicurezza…", + "settings.update_safety_hint": "Gli aggiornamenti sono facoltativi. WGTools crea backup completo e copia per rollback prima di installare. In caso di errore ripristina l’applicazione precedente. WireGuard non viene riavviato, salvo modifiche esplicite della sua configurazione nella release.", + "settings.update_sidebar": "Nuova versione disponibile", + "settings.update_sidebar_hint": "Impostazioni → Info", + "settings.update_starting": "Avvio aggiornamento…", + "settings.update_status_unknown": "Stato aggiornamento non disponibile. Nuovo tentativo…", + "settings.update_subtitle": "Informazioni progetto, verifica automatica delle release e aggiornamenti sicuri da GitHub Releases.", + "settings.update_success": "WGTools aggiornato a v{version}. Ricaricamento…", + "settings.update_wgtools": "Aggiorna WGTools", + "settings.user_actions": "Azioni", + "settings.user_created": "Creato", + "settings.user_created_ok": "Utente creato.", + "settings.user_deleted": "Utente eliminato.", + "settings.user_equal_rights": "Tutti gli utenti WGTools hanno gli stessi permessi.", + "settings.user_last_login": "Ultimo accesso", + "settings.user_name": "Nome utente", + "settings.users": "Utenti", + "settings.users_subtitle": "Account locali WGTools. L’email è facoltativa ed è usata solo per recuperare la password se la posta è attiva.", + "vps.add": "Aggiungi VPS", + "vps.add_help": "WGTools usa SSH per verificare o installare Relay. Password e chiavi SSH private non vengono mai salvate.", + "vps.add_title": "Aggiungi VPS", + "vps.agent": "Agente Relay", + "vps.agent_found": "Già installato", + "vps.agent_will_install": "Verrà installato", + "vps.arch": "Architettura", + "vps.auth_method": "Autenticazione", + "vps.authentication": "Autenticazione SSH", + "vps.check": "Verifica VPS", + "vps.check_failed": "Verifica VPS non riuscita", + "vps.check_link": "Verifica collegamento", + "vps.check_ok": "VPS compatibile", + "vps.checking": "Verifica accesso SSH e compatibilità VPS…", + "vps.connections": "connessioni", + "vps.credentials_not_saved": "Usati solo per questa verifica, non salvati da WGTools.", + "vps.delete_candidate": "Rimuovi", + "vps.delete_installed": "Rimuovi VPS", + "vps.delete_installed_confirm": "Rimuovere “{name}” da WGTools? Il trasporto Relay locale verrà scollegato, ma Relay Agent e tenant sul VPS saranno conservati. Potrai aggiungere di nuovo il VPS per riconnetterti al Relay esistente. I client non potranno usarlo finché non sarà riconnesso.", + "vps.delete_installed_failed": "Impossibile rimuovere VPS da WGTools", + "vps.delete_installed_ok": "VPS rimosso da WGTools. Il Relay remoto è conservato e può essere riconnesso.", + "vps.empty_help": "Aggiungi un VPS Debian o Ubuntu per verificare SSH, compatibilità del sistema e porte UDP necessarie.", + "vps.empty_title": "Nessun VPS configurato", + "vps.endpoint": "Endpoint pubblico", + "vps.endpoint_domain": "Dominio (consigliato)", + "vps.endpoint_domain_hint": "Se cambi in futuro il VPS principale, modificare il DNS può mantenere invariate le configurazioni client.", + "vps.health_failed": "Verifica collegamento Relay non riuscita", + "vps.host": "IP / nome host", + "vps.host_key": "Chiave host SSH", + "vps.identity": "Connessione VPS", + "vps.install_failed": "Installazione Relay non riuscita", + "vps.install_ok": "Relay installato e collegamento di gestione protetto verificato", + "vps.install_relay": "Installa Relay", + "vps.install_title": "Installa Relay VPS", + "vps.installed": "Installato", + "vps.installing": "Installazione Relay Agent e creazione tunnel protetto…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Passphrase chiave", + "vps.link_ok": "Collegamento Relay OK", + "vps.multi_tenant_note": "Un Relay Agent WGTools è già in esecuzione su questo VPS. Non sarà sostituito: questo WGTools avrà connessione isolata con chiavi e porte UDP proprie.", + "vps.name": "Nome", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Verrà installato", + "vps.os": "Sistema operativo", + "vps.password": "Password", + "vps.phase_note": "Relay Agent supporta più controller WGTools indipendenti su un VPS. Ogni controller riceve connessione, chiavi e porte UDP isolate; quelle esistenti restano intatte.", + "vps.port_pair": "Porte UDP", + "vps.ports_adjusted": "selezionate porte libere", + "vps.private_key": "Chiave privata", + "vps.privilege": "Privilegi", + "vps.public_endpoint": "Futuro endpoint pubblico", + "vps.ready_help": "Le credenziali SSH servono solo per la verifica e l’installazione immediata di Relay; non vengono salvate.", + "vps.reconnect_note": "Sul VPS esiste già una connessione Relay creata da questo WGTools. Verrà riconnesso lo stesso tenant, senza crearne uno nuovo né nuove porte UDP.", + "vps.reconnect_ok": "Relay esistente riconnesso correttamente", + "vps.reconnect_relay": "Riconnetti Relay", + "vps.relay_port": "Porta UDP Relay", + "vps.remove_confirm": "Rimuovere questo candidato VPS? Nessuna modifica remota è stata effettuata.", + "vps.save_candidate": "Salva candidato", + "vps.saved": "Candidato VPS salvato", + "vps.ssh": "SSH", + "vps.ssh_key": "Chiave SSH", + "vps.ssh_port": "Porta SSH", + "vps.ssh_user": "Utente SSH", + "vps.status_candidate": "Pronto per installazione", + "vps.status_installed": "Relay connesso", + "vps.subtitle": "Prepara un VPS pubblico per l’accesso remoto quando questo server WGTools non ha IP pubblico.", + "vps.tenant": "Connessione", + "vps.title": "Relay VPS", + "vps.transport_port": "Porta UDP di trasporto", + "vps.transport_port_hint": "Porta UDP separata per il tunnel di trasporto privato Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Salvato", + "vps.active_short": "Attivo", + "dashboard.traffic_reset": "Ripristina", + "dashboard.traffic_reset_confirm": "Azzerare i contatori di traffico WireGuard per questa interfaccia? Anche quelli dei client ripartiranno da zero.", + "dashboard.traffic_reset_done": "Contatori traffico azzerati", + "dashboard.traffic_reset_failed": "Impossibile azzerare i contatori traffico", + "audit.action.traffic.reset": "Contatori traffico azzerati", + "audit.result.reset": "azzerato", + "server.mtu": "MTU", + "server.mtu_auto": "Automatico", + "server.mtu_hint": "Facoltativo. Lascia vuoto per MTU automatico di wg-quick. Imposta 1380 o 1420 solo se richiesto da LTE o PPPoE.", + "clients.peer_isolation": "Isolamento client VPN", + "clients.peer_isolation_enable": "Isola dagli altri client VPN", + "clients.peer_isolation_hint": "Blocca il traffico tra questo client e gli altri indirizzi del pool WireGuard. L’accesso al server, a Internet e alle reti locali o Site-to-site resta regolato dagli altri criteri.", + "clients.credentials_rotate": "Chiavi del client", + "clients.credentials_rotate_button": "Rigenera chiavi", + "clients.credentials_rotate_confirm": "Generare nuove chiavi per questo client? Se connesso, la sessione WireGuard verrà interrotta immediatamente. Invia poi una nuova configurazione o QR.", + "clients.credentials_rotate_confirm_psk": "Generare una nuova coppia di chiavi e un nuovo PSK? La sessione WireGuard attiva del client verrà interrotta immediatamente. Invia poi una nuova configurazione o QR.", + "clients.credentials_rotate_hint": "Rigenera PrivateKey/PublicKey e anche il PSK se attivo. Indirizzo, route, gruppo, pianificazione, isolamento e statistiche restano invariati.", + "clients.credentials_rotating": "Generazione nuove chiavi e disconnessione della vecchia sessione…", + "clients.credentials_rotated": "Chiavi del client cambiate. La vecchia sessione è stata interrotta se attiva. La precedente configurazione non funziona più; invia nuova configurazione o QR.", + "clients.credentials_rotated_short": "Chiavi cambiate — serve nuova configurazione", + "audit.action.client.credentials_rotated": "Chiavi del client rigenerate", + "clients.credentials_connection_lost": "Connessione a WGTools interrotta. Se il pannello era aperto tramite il client le cui chiavi sono state rigenerate, è normale: la vecchia sessione WireGuard è stata chiusa. Ricollegati con un altro percorso e genera nuova configurazione o QR.", + "nav.navigation": "Navigazione principale", + "nav.project_github": "WGTools su GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Facoltativo per ora. Può servire a recuperare la password dopo aver configurato la posta.", + "auth.forgot_password": "Password dimenticata?", + "auth.reset_title": "Reimposta la password", + "auth.reset_subtitle": "Ricevi un codice monouso via email e imposta una nuova password WGTools.", + "auth.reset_identifier": "Nome utente o e-mail", + "auth.reset_identifier_help": "Per la privacy, WGTools mostra sempre la stessa risposta, sia che l’account esista o no.", + "auth.send_reset_code": "Invia codice", + "auth.reset_code_sent_generic": "Se l’account esiste e ha un indirizzo email, è stato inviato un codice. È valido per 15 minuti.", + "auth.reset_code": "Codice a 6 cifre", + "auth.set_new_password": "Imposta nuova password", + "auth.request_another_code": "Richiedi un altro codice", + "auth.back_to_login": "Torna all'accesso", + "auth.reset_not_configured": "Il recupero password via email non è configurato. Contatta l’amministratore WGTools.", + "settings.tab_mail": "Posta", + "settings.mail": "Email / SMTP", + "settings.mail_subtitle": "SMTP viene usato per il recupero password.", + "settings.mail_not_configured": "Non configurato", + "settings.mail_enabled": "Abilita posta e recupero password", + "settings.mail_smtp_host": "Server SMTP", + "settings.mail_smtp_port": "Porta SMTP", + "settings.mail_security": "Crittografia", + "settings.mail_security_none": "Nessuna crittografia", + "settings.mail_username": "Nome utente SMTP", + "settings.mail_username_help": "Usato per l’autenticazione SMTP e come indirizzo email mittente.", + "settings.mail_password": "Password SMTP", + "settings.mail_password_keep": "Lascia vuoto per mantenere la password salvata.", + "settings.mail_from_email": "Email mittente", + "settings.mail_from_name": "Nome mittente", + "settings.mail_test_recipient": "Destinatario test", + "settings.mail_test_recipient_help": "Il test usa le impostazioni SMTP attualmente salvate.", + "settings.mail_remove_password": "Rimuovi password", + "settings.mail_test": "Invia test", + "settings.mail_save": "Salva impostazioni email", + "settings.mail_enabled_badge": "Abilitato", + "settings.mail_disabled_badge": "Disabilitato", + "settings.mail_saved": "Impostazioni email salvate.", + "settings.mail_remove_password_confirm": "Rimuovere la password SMTP salvata e disabilitare la posta?", + "settings.mail_password_removed": "Password SMTP rimossa e posta disabilitata.", + "settings.mail_test_recipient_required": "Inserisci l’indirizzo email del destinatario del test.", + "settings.mail_testing": "Invio email di prova…", + "settings.mail_test_ok": "Email di prova inviata correttamente.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Facoltativa. Necessaria solo per recuperare autonomamente la password.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "Email salvata.", + "settings.send_password_reset": "Invia reset", + "settings.user_reset_mail_not_configured": "Prima configura e abilita la posta.", + "settings.user_reset_email_missing": "Aggiungi prima un indirizzo email.", + "settings.user_reset_confirm": "Inviare un codice di reset password a {name} all’indirizzo {email}?", + "settings.user_reset_sent": "Codice di reset inviato a {email}.", + "audit.action.auth.password_reset_requested": "Richiesto reset password", + "audit.action.auth.password_reset_code_sent": "Codice di reset password inviato", + "audit.action.auth.password_reset_completed": "Password reimpostata", + "audit.action.auth.password_reset_failed": "Reset password non riuscito", + "audit.action.mail.settings_updated": "Impostazioni email aggiornate", + "audit.action.mail.test_sent": "Email di prova inviata", + "audit.action.mail.test_failed": "Invio email di prova non riuscito", + "audit.action.user.email_changed": "Email utente modificata", + "audit.action.user.password_reset_sent": "Reset password utente inviato", + "audit.action.user.password_reset_failed": "Reset password utente non riuscito", + "audit.result.accepted": "accettato", + "audit.result.sent": "inviato", + "audit.result.invalid_code": "codice non valido", + "common.copy": "Copia", + "common.copied": "Copiato", + "clients.use_panel_host": "Usa indirizzo pannello", + "clients.use_panel_host_done": "Indirizzo pannello inserito: {host}", + "clients.use_panel_host_failed": "Impossibile ricavare l’indirizzo del pannello dall’URL del browser.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS Let’s Encrypt integrato per accesso diretto a WGTools senza reverse proxy.", + "settings.https_disabled": "Disabilitato", + "settings.https_enabled": "Abilitato", + "settings.https_enable": "Abilita HTTPS integrato", + "settings.https_type": "Certificato per", + "settings.https_domain": "Dominio", + "settings.https_public_ip": "IP pubblico", + "settings.https_target": "Dominio o IP pubblico", + "settings.https_email": "Email Let’s Encrypt", + "settings.https_port": "Porta HTTPS", + "settings.https_port80_note": "La porta TCP 80 deve essere raggiungibile da Internet per emissione e rinnovo del certificato. Apri anche la porta HTTPS scelta per il pannello.", + "settings.https_check_ports": "Verifica porte", + "settings.https_certificate": "Certificato", + "settings.https_certificate_ready": "Pronto", + "settings.https_certificate_missing": "Non emesso", + "settings.https_expires": "Valido fino al", + "settings.https_renewal": "Rinnovo automatico", + "settings.https_renewal_enabled": "Abilitato", + "settings.https_renewal_disabled": "Disabilitato", + "settings.https_certificate_path": "Certificato", + "settings.https_private_key_path": "Chiave privata", + "settings.https_issue": "Ottieni / rinnova certificato", + "settings.https_port_free": "Libera", + "settings.https_port_busy": "Occupata", + "settings.https_ports_checked": "Verifica porte completata.", + "settings.https_target_email_required": "Inserisci dominio/IP pubblico ed email Let’s Encrypt.", + "settings.https_issue_confirm": "Richiedere o rinnovare il certificato Let’s Encrypt per {target}? Le impostazioni HTTPS verranno salvate. La porta TCP 80 deve essere accessibile da Internet.", + "settings.https_issuing": "Richiesta certificato a Let’s Encrypt…", + "settings.https_issue_ok": "Certificato pronto.", + "settings.https_already_enabled": "HTTPS integrato già attivo.", + "settings.https_already_disabled": "HTTPS integrato già disattivato.", + "settings.https_enable_confirm": "Attivare HTTPS integrato su TCP {port} con percorso {path}? WGTools si riavvierà e la pagina si riconnetterà al nuovo indirizzo.", + "settings.https_disable_confirm": "Disattivare HTTPS integrato e tornare a HTTP?", + "settings.https_switching": "Attivazione HTTPS e riavvio WGTools…", + "settings.https_switching_http": "Disattivazione HTTPS e riavvio WGTools…", + "audit.action.https.certificate_issued": "Certificato HTTPS emesso", + "audit.action.https.certificate_failed": "Richiesta certificato HTTPS non riuscita", + "audit.action.https.enabled": "HTTPS attivato", + "audit.action.https.disabled": "HTTPS disattivato", + "audit.result.issued": "emesso", + "audit.result.enabled": "attivato", + "audit.result.disabled": "disattivato", + "settings.https_access_path": "Percorso di accesso al pannello", + "settings.https_access_path_help": "Scegli un percorso personalizzato. Con HTTPS integrato, le richieste fuori percorso ricevono 404.", + "settings.https_enable_fields_required": "Inserisci dominio/IP pubblico, email Let’s Encrypt e percorso pannello.", + "settings.https_use_panel_host": "Usa indirizzo pannello", + "settings.https_reconnecting": "WGTools passa al nuovo indirizzo HTTPS…", + "server.tab_nodes": "Nodi", + "common.type": "Tipo", + "common.status": "Stato", + "common.copy_failed": "Impossibile copiare", + "clients.vpn_address": "Indirizzo VPN", + "nodes.title": "Nodi WGTools", + "nodes.subtitle": "Collega più server WGTools in una rete protetta e pubblica solo le reti accessibili agli altri nodi.", + "nodes.enable_hub": "Attiva HUB", + "nodes.connect_hub": "Connetti a HUB", + "nodes.settings": "Impostazioni nodo", + "nodes.settings_action": "Impostazioni", + "nodes.sync_now": "Sincronizza", + "nodes.disable": "Disattiva nodi", + "nodes.disable_action": "Disconnetti", + "nodes.join_title": "Connetti nuovi nodi", + "nodes.join_help": "Genera un codice monouso e inseriscilo su un altro pannello WGTools insieme all’endpoint HUB, ad es. vpn.example.com:51950. Il codice vale 15 minuti e un solo utilizzo.", + "nodes.create_code": "Crea codice", + "nodes.connected_nodes": "Nodi connessi", + "nodes.connected_nodes_help": "Informazioni su altri pannelli, reti pubblicate e client. I client remoti sono in sola lettura.", + "nodes.enable_hub_help": "Questo pannello diventa il nodo centrale. La stessa porta accetta WireGuard su UDP e l’associazione iniziale protetta su TCP.", + "nodes.node_name": "Nome nodo", + "nodes.transport_network": "Rete di trasporto nodi", + "nodes.transport_help": "Rete privata separata usata solo per il trasporto tra WGTools. Non deve sovrapporsi alle reti VPN/LAN.", + "nodes.panel_url": "URL pannello", + "nodes.panel_url_help": "Facoltativo. Solo collegamento informativo per “Apri pannello” sugli altri nodi; non usato per la connessione Nodes.", + "nodes.extra_networks": "Reti nodo aggiuntive", + "nodes.extra_networks_help": "Una rete per riga. Reti VPN delle interfacce e reti remote Site-to-site sono pubblicate automaticamente. Aggiungi solo altre LAN/reti instradate, ad es. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools inserisce reti VPN, Site-to-site e LAN instradate rilevate. Mantieni solo le reti da pubblicare. Una per riga.", + "nodes.published_networks_settings_help": "Una rete per riga. Questo è l’elenco esplicito delle reti pubblicate dal nodo. Rimuovere una riga interrompe l’annuncio agli altri nodi.", + "nodes.available_networks_help": "Reti rilevate: {networks}. Le nuove reti non vengono pubblicate automaticamente; aggiungi quelle desiderate sopra.", + "nodes.available_networks_none": "Nessuna rete locale aggiuntiva rilevata.", + "nodes.connect_help": "Inserisci endpoint HUB e codice monouso. URL web, porta HTTPS, certificato e percorso privato non sono usati per associare i nodi.", + "nodes.join_code": "Codice connessione", + "nodes.connect_reachability_note": "L’associazione iniziale usa TCP protetto sulla porta indicata. Dopo la creazione di wgnode0, reti, stato, versioni e dati client in sola lettura si sincronizzano con HUB tramite indirizzo WireGuard interno.", + "nodes.connect": "Connetti", + "nodes.settings_help": "Nome nodo, collegamento facoltativo “Apri pannello” ed elenco reti pubblicate. L’URL non è usata per associazione o sincronizzazione.", + "nodes.details": "Dettagli", + "nodes.not_configured": "WGTools Nodes non configurato", + "nodes.not_configured_help": "Attiva HUB su questo pannello o collegalo a un HUB WGTools esistente.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connesso a HUB", + "nodes.mode_none": "Non configurato", + "nodes.role": "Ruolo", + "nodes.tunnel": "Tunnel nodo", + "nodes.node_ip": "Indirizzo nodo", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Reti pubblicate", + "nodes.last_sync": "Ultima sincronizzazione", + "nodes.no_nodes_hub": "Nessun nodo connesso. Crea un codice e usalo su un altro pannello WGTools.", + "nodes.no_nodes_spoke": "Nessuna informazione ricevuta sui nodi remoti.", + "nodes.clients_short": "Client", + "nodes.open_panel": "Apri pannello", + "nodes.route_conflict": "Conflitto di route", + "nodes.no_published_networks": "Nessuna rete pubblicata", + "nodes.load_failed": "Impossibile caricare WGTools Nodes", + "nodes.enable_hub_confirm": "Attivare WGTools HUB e creare il tunnel WireGuard interno dei nodi?", + "nodes.applying": "Configurazione tunnel WGTools Nodes…", + "nodes.enable_failed": "Impossibile attivare HUB", + "nodes.hub_enabled": "WGTools HUB attivato", + "nodes.connecting": "Verifica codice HUB e creazione tunnel protetto…", + "nodes.connect_failed": "Impossibile connettersi a HUB", + "nodes.connected": "Connesso a WGTools HUB", + "nodes.settings_failed": "Impossibile salvare impostazioni nodo", + "nodes.settings_saved": "Impostazioni nodo salvate", + "nodes.code_failed": "Impossibile creare codice di connessione", + "nodes.code_expires": "Codice monouso. Valido fino alle {time}.", + "nodes.code_copied": "Codice connessione copiato", + "nodes.network_vpn": "Client VPN", + "nodes.network_site_to_site": "Rete Site-to-site", + "nodes.network_custom": "Rete aggiuntiva", + "nodes.conflict": "Conflitto", + "nodes.remote_clients": "Client (sola lettura)", + "nodes.no_clients": "Nessun client segnalato da questo nodo", + "nodes.details_failed": "Impossibile caricare dettagli nodo", + "nodes.remove_confirm": "Rimuovere il nodo “{name}” da HUB? L’accesso al tunnel interno sarà revocato.", + "nodes.remove_failed": "Impossibile rimuovere il nodo", + "nodes.removed": "Nodo rimosso", + "nodes.disable_hub_confirm": "Disattivare HUB e disconnettere tutti i nodi WGTools? Il tunnel interno sarà rimosso.", + "nodes.disconnect_confirm": "Disconnettere questo pannello WGTools da HUB e rimuovere il tunnel interno?", + "nodes.disable_failed": "Impossibile disattivare WGTools Nodes", + "nodes.disabled": "WGTools Nodes disattivato", + "nodes.sync_failed": "Sincronizzazione nodi non riuscita", + "nodes.synced": "Informazioni nodi sincronizzate", + "nodes.service_port": "Porta Nodes", + "nodes.service_port_help": "La stessa porta serve contemporaneamente WireGuard su UDP e l’associazione iniziale protetta su TCP.", + "nodes.hub_port_forward_note": "Se HUB è dietro NAT, inoltra la stessa porta UDP e TCP. Porta web WGTools, HTTPS e percorso privato del pannello non riguardano Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Dominio/IP e porta Nodes senza http:// o https://, ad es. vpn.example.com:51950.", + "settings.collapse_sidebar": "Comprimi barra laterale", + "settings.expand_sidebar": "Espandi barra laterale", + "settings.https_issue_fields_required": "Inserisci dominio/IP pubblico, email Let’s Encrypt e percorso pannello.", + "settings.https_issue_ok_saved": "Certificato pronto e impostazioni HTTPS salvate.", + "settings.https_enable_need_certificate": "Prima ottieni un certificato.", + "settings.https_enable_certificate_mismatch": "Prima ottieni un certificato per dominio o IP corrente.", + "settings.https_enable_certificate_expired": "Certificato scaduto. Rinnovalo prima di attivare HTTPS.", + "settings.https_enable_certificate_ready": "Certificato pronto: puoi attivare HTTPS integrato.", + "settings.https_enable_active_help": "Deseleziona e salva per tornare a HTTP.", + "settings.https_certificate_expired": "Scaduto", + "settings.https_certificate_wrong_target": "Per un altro indirizzo", + "nodes.network_conflict_error": "Le reti pubblicate sono in conflitto con un altro nodo o la rete di trasporto Nodes: {conflicts}. Rimuovi o modifica le reti.", + "nodes.networks_changed": "Le reti rilevate sono cambiate dall’ultimo salvataggio. Nuove: {added}. Non più rilevate: {removed}. Controlla e salva l’elenco pubblicato.", + "nodes.review_networks": "Controlla reti", + "nodes.vpn_pool_mismatch": "Pool VPN modificato: Nodes pubblica ancora {old}, mentre il pool attuale è {current}. Apri impostazioni nodo e aggiorna le reti pubblicate.", + "server.error_vpn_network_invalid": "La rete VPN deve essere una rete IPv4 valida, ad es. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Sono supportate solo reti VPN IPv4.", + "server.error_vpn_network_too_small": "La rete VPN deve contenere almeno due indirizzi utilizzabili.", + "server.error_vpn_network_no_hosts": "La rete VPN scelta non contiene indirizzi server utilizzabili.", + "server.error_server_address_prefix": "L’indirizzo VPN server deve includere un prefisso, ad es. 10.0.0.1/24.", + "server.error_server_address_network": "L’indirizzo VPN server deve appartenere al pool selezionato e usare lo stesso prefisso.", + "server.error_server_address_reserved": "L’indirizzo VPN server non può essere indirizzo di rete o broadcast.", + "server.error_listen_port_number": "La porta WireGuard deve essere un numero.", + "server.error_listen_port_range": "La porta WireGuard deve essere tra 1 e 65535.", + "server.error_mtu_number": "MTU deve essere un numero.", + "auth.mfa_title": "Autenticazione a due fattori", + "auth.mfa_login_help": "Inserisci il codice a 6 cifre di Google Authenticator o uno dei codici di recupero.", + "auth.mfa_code": "Codice di autenticazione", + "auth.mfa_verify": "Verifica e accedi", + "auth.mfa_back": "Torna alla password", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Autenticazione a due fattori (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Abilitato", + "settings.mfa_disabled": "Disabilitato", + "settings.mfa_google_help": "Proteggi l’account con Google Authenticator o un’altra app TOTP. Per iniziare serve la password corrente.", + "settings.current_password": "Password corrente", + "settings.mfa_start": "Configura Google Authenticator", + "settings.mfa_secret": "Chiave di configurazione manuale", + "settings.mfa_scan_help": "Scansiona il QR con Google Authenticator e inserisci il codice corrente a 6 cifre per abilitare MFA.", + "settings.mfa_code": "Codice a 6 cifre", + "settings.mfa_enable": "Attiva MFA", + "settings.mfa_manage_help": "Per modificare MFA, inserisci password corrente e codice Authenticator o di recupero.", + "settings.mfa_code_or_recovery": "Codice Authenticator o di recupero", + "settings.mfa_regenerate": "Nuovi codici di recupero", + "settings.mfa_disable": "Disattiva MFA", + "settings.mfa_recovery_title": "Codici di recupero", + "settings.mfa_recovery_help": "Salva questi codici ora. Ognuno può essere usato una volta se Google Authenticator non è disponibile. Non verranno mostrati di nuovo.", + "settings.mfa_recovery_remaining": "Codici di recupero rimanenti: {count}", + "settings.mfa_enabled_ok": "MFA attivata.", + "settings.mfa_disabled_ok": "MFA disattivata.", + "settings.mfa_disable_confirm": "Disattivare l’autenticazione a due fattori per questo account?", + "settings.mfa_regenerate_confirm": "Sostituire tutti i codici di recupero esistenti?", + "settings.mfa_recovery_regenerated": "Nuovi codici di recupero creati.", + "audit.action.auth.mfa_failed": "Verifica MFA non riuscita", + "audit.action.auth.mfa_recovery_used": "Codice di recupero MFA utilizzato", + "audit.action.user.mfa_setup_started": "Configurazione MFA avviata", + "audit.action.user.mfa_enabled": "MFA attivata", + "audit.action.user.mfa_disabled": "MFA disattivata", + "audit.action.user.mfa_disabled_cli": "MFA disattivata da CLI", + "audit.action.user.mfa_recovery_regenerated": "Codici di recupero MFA rigenerati", + "settings.mfa_error_password": "Password corrente non valida.", + "settings.mfa_error_code": "Codice di autenticazione non valido.", + "settings.mfa_error_already_enabled": "MFA è già attiva.", + "settings.mfa_error_not_enabled": "MFA non è attiva.", + "settings.mfa_error_not_started": "Riavvia la configurazione MFA.", + "trace.title": "Traceroute, ping e mappa del percorso", + "trace.subtitle": "Misura la latenza verso un VPS o altro server e individua i ritardi lungo il percorso.", + "trace.target": "IP o nome host del server", + "trace.show_map": "Mostra percorso sulla mappa", + "trace.run": "Avvia traceroute", + "trace.geo_note": "La geolocalizzazione è approssimativa. Con la mappa attiva, gli IP pubblici degli hop vengono inviati a ipwho.is; le mappe sono caricate da OpenStreetMap.", + "trace.latency_note": "Traceroute misura la latenza in millisecondi, non la velocità in Mbit/s.", + "trace.map": "Mappa del percorso", + "trace.map_hint": "Mappa interattiva: trascina per spostare, usa la rotella o +/− per lo zoom e clicca un hop per i dettagli.", + "trace.hop": "Hop / IP", + "trace.location": "Posizione", + "trace.avg_rtt": "RTT medio", + "trace.delta": "Δ RTT", + "trace.loss": "Perdita", + "trace.summary_target": "Destinazione", + "trace.summary_ping": "Ping medio", + "trace.summary_loss": "Perdita ping", + "trace.summary_hops": "Hop", + "trace.no_reply": "Nessuna risposta", + "trace.private": "Rete privata", + "trace.unknown": "Sconosciuto", + "trace.running": "Ping e traceroute in corso… L’operazione può durare un minuto.", + "trace.done": "Tracciamento di rete completato.", + "trace.failed": "Tracciamento di rete non riuscito", + "trace.partial_geo": "Impossibile geolocalizzare alcuni hop pubblici.", + "trace.not_reached": "Destinazione non raggiunta dal traceroute.", + "trace.reached": "Destinazione raggiunta", + "trace.ms": "ms", + "server.tab_trace": "Tracciamento", + "trace.map_controls": "Controlli mappa", + "trace.zoom_in": "Ingrandisci", + "trace.zoom_out": "Riduci", + "trace.fit_route": "Adatta al percorso", + "trace.fit": "Adatta", + "trace.map_click_hint": "Clicca un hop per visualizzare IP, posizione, ASN e RTT.", + "trace.route_path": "Percorso", + "trace.ping_ok_trace_filtered": "La destinazione risponde al ping, ma gli ultimi hop del traceroute non rispondono.", + "trace.latency_legend": "Aumento della latenza tra hop che rispondono", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normale", + "trace.latency_warn": "Δ RTT 5–20 ms — elevato", + "trace.latency_bad": "Δ RTT > 20 ms — forte aumento" +} diff --git a/app/static/js/app.js b/app/static/js/app.js new file mode 100644 index 0000000..af99d6b --- /dev/null +++ b/app/static/js/app.js @@ -0,0 +1,2985 @@ +(() => { + const basePath = String(document.body.dataset.basePath || '').replace(/\/$/, ''); + const appUrl = path => { + const value = String(path || '/'); + if (!value.startsWith('/') || value.startsWith('//')) return value; + return `${basePath}${value}` || '/'; + }; + const nativeFetch = window.fetch.bind(window); + window.fetch = (input, init) => { + if (typeof input === 'string' && input.startsWith('/') && !input.startsWith('//')) input = appUrl(input); + return nativeFetch(input, init); + }; + const page = document.body.dataset.page; + const refreshSeconds = Number(document.body.dataset.refresh || '5'); + const threshold = Number(document.body.dataset.onlineThreshold || '180'); + let snapshot = null; + let interfacesData = {interfaces:[], suggested:null}; + let timer = null; + let historyTimer = null; + let dashboardDiagnosticsTimer = null; + let serverDiagnosticsTimer = null; + let tooltipTimer = null; + let tooltipOwner = null; + + const $ = id => document.getElementById(id); + const t = (key, fallback) => window.WGToolsI18n?.t(key, fallback) || fallback || key; + const esc = value => String(value ?? '').replace(/[&<>'"]/g, c => ({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c])); + + function fmtBytes(bytes) { + const n = Number(bytes || 0); if (!n) return '0 B'; + const u = ['B','KB','MB','GB','TB']; let i = Math.floor(Math.log(n)/Math.log(1024)); i=Math.min(i,u.length-1); + return `${(n/Math.pow(1024,i)).toFixed(i ? 1 : 0)} ${u[i]}`; + } + function fmtRate(bytes){ return `${fmtBytes(bytes)}/s`; } + function fmtUptime(seconds){ + let s=Math.max(0,Number(seconds||0)); const d=Math.floor(s/86400); s%=86400; const h=Math.floor(s/3600); s%=3600; const m=Math.floor(s/60); + if(d)return `${d}d ${h}h`; if(h)return `${h}h ${m}m`; return `${m}m`; + } + function ago(ts) { + const n = Number(ts || 0); if (!n) return t('common.never','Never'); + const s = Math.max(0, Math.floor(Date.now()/1000 - n)); + if (s < 60) return `${s}s ${t('common.ago','ago')}`; + if (s < 3600) return `${Math.floor(s/60)}m ${t('common.ago','ago')}`; + if (s < 86400) return `${Math.floor(s/3600)}h ${t('common.ago','ago')}`; + return `${Math.floor(s/86400)}d ${t('common.ago','ago')}`; + } + function online(peer){ if(peer?.expired_disabled||peer?.schedule_disabled)return false; const ts=Number(peer.latest_handshake||0); return ts>0 && Date.now()/1000-ts <= threshold; } + function statusHtml(peer){ + if(peer?.expired_disabled)return `${esc(t('clients.expired_disabled_status','Expired'))}`; + if(peer?.schedule_disabled)return `${esc(t('clients.schedule_blocked_status','Blocked by schedule'))}`; + const is=online(peer); + // Offline status is never animated. The table renderer reuses this DOM node + // during normal polling, so the online CSS animation never restarts. + return `${esc(is?t('common.online','Online'):t('common.offline','Offline'))}`; + } + // Update only changed cells. Keeping the existing status cell when its state + // is unchanged preserves the CSS animation clock, even at 2-second polling. + // Peer keys and row order must match; otherwise safely rebuild the table. + function renderPeerTable(body, html, statusColumn){ + if(!body)return; + const staged=document.createElement('tbody'); + staged.innerHTML=html; + const incoming=Array.from(staged.rows), current=Array.from(body.rows); + const reusable=incoming.length===current.length && incoming.every((row,i)=> + Boolean(row.dataset.peerKey) && current[i].dataset.peerKey===row.dataset.peerKey && + row.cells.length===current[i].cells.length); + if(!reusable){body.replaceChildren(...incoming);return;} + for(let i=0;iel.classList.remove('show'),duration); } + function healthClass(ok){ return ok ? 'health-ok' : 'health-bad'; } + function setHidden(id, hidden){ const el=$(id); if(el) el.hidden=hidden; } + function operationStatus(id, text, kind='info'){ + const el=$(id); if(!el)return; + // Keep structural classes such as vps-operation-status and migration-status. + // Replacing className here used to silently remove those classes as soon as + // a status message was shown, which also discarded their layout rules. + el.classList.remove('working','success','error','info'); + if(!text){ el.hidden=true; el.textContent=''; return; } + el.hidden=false; el.textContent=text; + if(kind) el.classList.add(kind); + } + + function activeInterfaceItem(){ + const name=snapshot?.interface||document.body.dataset.interface||''; + return (interfacesData.interfaces||[]).find(item=>item.name===name)||null; + } + function interfaceDisplay(item){ + if(!item)return ''; + const alias=String(item.display_name||'').trim(); + return alias&&alias!==item.name?`${item.name} · ${alias}`:item.name; + } + function setInterfaceCookie(name){ + document.cookie=`wgtools_interface=${encodeURIComponent(name)}; Path=/; Max-Age=31536000; SameSite=Lax`; + } + function selectInterface(name){ + if(!name||name===(snapshot?.interface||document.body.dataset.interface))return; + setInterfaceCookie(name); + location.reload(); + } + function renderInterfaceSwitcher(){ + const menu=$('interface-switcher-menu'); if(!menu)return; + const items=interfacesData.interfaces||[]; + if(!items.length){menu.innerHTML=`
${esc(t('interfaces.none','No WireGuard interfaces found'))}
`;return;} + menu.innerHTML=`
${esc(t('interfaces.switch_title','WireGuard interfaces'))}
`+items.map(item=>{ + const state=item.configured?(item.running?t('common.running','Running'):t('common.stopped','Stopped')):t('common.not_configured','Not configured'); + const stateClass=item.configured?(item.running?'online':'offline'):'unknown'; + const alias=item.display_name&&item.display_name!==item.name?`${esc(item.display_name)}`:''; + const meta=[item.address,item.listen_port?`:${item.listen_port}`:'',`${Number(item.peer_count||0)} ${t('interfaces.peers_short','peers')}`].filter(Boolean).join(' · '); + return ``; + }).join(''); + } + function renderInterfaceManager(){ + const list=$('interface-manager-list'); if(!list)return; + const items=(interfacesData.interfaces||[]).filter(item=>item.configured); + if(!items.length){list.innerHTML=`
${esc(t('interfaces.none_configured','No configured WireGuard interfaces yet.'))}
`;return;} + list.innerHTML=items.map(item=>{ + const state=item.running?t('common.running','Running'):t('common.stopped','Stopped'); + const alias=item.display_name&&item.display_name!==item.name?`${esc(item.display_name)}`:''; + const canDelete=items.length>1; + const deleteButton=``; + return `
${esc(item.name)}${alias}
${esc(state)} · ${Number(item.peer_count||0)} ${esc(t('interfaces.peers_short','peers'))}
${esc(t('server.address','Address'))}${esc(item.address||'—')}
${esc(t('server.listen_port','Listen port'))}${item.listen_port?esc(item.listen_port):'—'}
${esc(t('server.policy_table','Policy table'))}${item.policy_table?esc(item.policy_table):'—'}
${deleteButton}
`; + }).join(''); + } + async function fetchInterfaces(render=true){ + try{ + const r=await fetch('/api/interfaces',{cache:'no-store'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Interface list failed'); + interfacesData=d||{interfaces:[],suggested:null}; + if(render){renderInterfaceSwitcher();renderInterfaceManager();} + return d; + }catch(e){ + if(render){const menu=$('interface-switcher-menu');if(menu)menu.innerHTML=`
${esc(e.message)}
`;} + return null; + } + } + async function toggleInterfaceMenu(){ + const button=$('interface-switcher-button'), menu=$('interface-switcher-menu');if(!button||!menu)return; + const opening=menu.hidden; + if(opening)await fetchInterfaces(true); + menu.hidden=!opening;button.setAttribute('aria-expanded',opening?'true':'false'); + } + function closeInterfaceMenu(){const button=$('interface-switcher-button'),menu=$('interface-switcher-menu');if(menu)menu.hidden=true;if(button)button.setAttribute('aria-expanded','false');} + function bindInterfaceSwitcher(){ + $('interface-switcher-button')?.addEventListener('click',e=>{e.stopPropagation();toggleInterfaceMenu();}); + $('interface-switcher-menu')?.addEventListener('click',e=>{const target=e.target.closest('[data-interface-select]');if(!target)return;selectInterface(target.dataset.interfaceSelect);}); + document.addEventListener('click',e=>{if(!e.target.closest('.interface-switcher-wrap'))closeInterfaceMenu();}); + $('interface-manager-list')?.addEventListener('click',e=>{ + const deleteTarget=e.target.closest('[data-interface-delete]'); + if(deleteTarget){e.stopPropagation();deleteInterface(deleteTarget.dataset.interfaceDelete);return;} + const target=e.target.closest('[data-interface-select]');if(!target)return;selectInterface(target.dataset.interfaceSelect); + }); + } + + function tooltipTextFor(el){ + if(!el)return ''; + const explicit=el.dataset?.tooltip||el.getAttribute('aria-label')||el.getAttribute('title')||''; + if(explicit.trim())return explicit.trim(); + if(el.matches('button,.btn,.nav-item'))return String(el.textContent||'').replace(/\s+/g,' ').trim(); + return ''; + } + function hideTooltip(){ + if(tooltipTimer){clearTimeout(tooltipTimer);tooltipTimer=null;} + tooltipOwner=null; const tip=$('wg-delayed-tooltip'); if(tip)tip.classList.remove('show'); + } + function showTooltipFor(el){ + const text=tooltipTextFor(el); if(!text)return; + let tip=$('wg-delayed-tooltip'); + if(!tip){tip=document.createElement('div');tip.id='wg-delayed-tooltip';tip.className='wg-tooltip';document.body.appendChild(tip);} + tip.textContent=text; tip.classList.remove('show'); tip.style.left='0px';tip.style.top='0px'; + const rect=el.getBoundingClientRect(); const width=Math.min(280,Math.max(80,tip.offsetWidth||180)); + let left=rect.left+(rect.width-width)/2; left=Math.max(8,Math.min(window.innerWidth-width-8,left)); + let top=rect.bottom+8; const height=tip.offsetHeight||32; if(top+height>window.innerHeight-8)top=Math.max(8,rect.top-height-8); + tip.style.left=`${Math.round(left)}px`;tip.style.top=`${Math.round(top)}px`;requestAnimationFrame(()=>tip.classList.add('show')); + } + function bindDelayedTooltips(){ + document.querySelectorAll('[title]').forEach(el=>{if(!el.dataset.tooltip)el.dataset.tooltip=el.getAttribute('title')||'';el.removeAttribute('title');}); + document.addEventListener('mouseover',e=>{ + const el=e.target.closest('[data-tooltip],button,.btn,.nav-item'); if(!el||el===tooltipOwner)return; + hideTooltip(); const text=tooltipTextFor(el); if(!text)return; tooltipOwner=el; tooltipTimer=setTimeout(()=>{if(tooltipOwner===el)showTooltipFor(el);},700); + }); + document.addEventListener('mouseout',e=>{const el=e.target.closest('[data-tooltip],button,.btn,.nav-item');if(el&&tooltipOwner===el&&!el.contains(e.relatedTarget))hideTooltip();}); + document.addEventListener('mousedown',hideTooltip); document.addEventListener('scroll',hideTooltip,true); window.addEventListener('resize',hideTooltip); + } + + function serverStateText(data){ + const state=data?.wireguard?.state; + if(state==='not_installed') return t('common.not_installed','Not installed'); + if(state==='not_configured') return t('common.not_configured','Not configured'); + if(data?.running) return t('common.running','Running'); + return t('common.stopped','Stopped'); + } + + function snapshotView(){ return page==='dashboard'?'dashboard':page==='clients'?'clients':page==='server'?'server':'full'; } + async function fetchSnapshot(showToast=false){ + try{ + const r=await fetch(`/api/snapshot?view=${encodeURIComponent(snapshotView())}`,{cache:'no-store'}); const data=await r.json(); if(!r.ok) throw new Error(data.error||'Server error'); + snapshot=data; renderHeader(data); renderCurrent(); if(page==='server'&&activeServerTab==='nodes')loadNodes(false); if(showToast) toast(t('common.updated','Updated')); + }catch(e){ renderHeader({running:false,error:e.message}); if(showToast) toast(e.message); } + } + function renderHeader(data){ + const dot=$('header-dot'), status=$('header-status'); if(!dot||!status)return; + const active=Boolean(data.running); + dot.className=`status-dot ${active?'online':'offline'}`; + const item=(interfacesData.interfaces||[]).find(x=>x.name===(data.interface||'')); + const name=item?interfaceDisplay(item):(data.interface||'wg0'); + status.textContent=`${name} · ${serverStateText(data)}`; + if(item){item.running=Boolean(data.running);item.configured=Boolean(data.wireguard?.config_exists);renderInterfaceSwitcher();renderInterfaceManager();} + } + function renderCurrent(){ if(!snapshot)return; if(page==='dashboard') renderDashboard(snapshot); if(page==='server') renderServer(snapshot); if(page==='clients') renderClients(snapshot); if(page==='settings') renderSettings(snapshot); } + + function renderDashboard(d){ + const peers=d.peers||[]; const on=peers.filter(online); const s2s=peers.filter(p=>(p.remote_networks||[]).length); + $('wg-state').textContent=serverStateText(d); $('wg-state-dot').className=`status-dot ${d.running?'online':'offline'}`; + $('wg-interface').textContent=`${t('server.interface','Interface')}: ${d.interface||'—'}`; + $('wg-address').textContent=`${t('server.address','Address')}: ${d.config?.interface?.address||'—'}`; + $('wg-port').textContent=`${t('server.listen_port','Listen port')}: ${d.listen_port||d.config?.interface?.listen_port||'—'}`; + $('peer-online').textContent=on.length; $('peer-total').textContent=peers.length; $('peer-s2s').textContent=s2s.length; + const traffic=d.traffic_totals||{}; + $('rx-total').textContent=fmtBytes(traffic.rx_bytes ?? peers.reduce((a,p)=>a+Number(p.rx_bytes||0),0)); $('tx-total').textContent=fmtBytes(traffic.tx_bytes ?? peers.reduce((a,p)=>a+Number(p.tx_bytes||0),0)); + $('forwarding-icon').textContent=d.system?.ip_forwarding?'✓':'✕'; $('forwarding-icon').className=healthClass(d.system?.ip_forwarding); + $('nat-icon').textContent=d.config?.detected?.nat_enabled?'✓':'✕'; $('nat-icon').className=healthClass(d.config?.detected?.nat_enabled); + $('table-icon').textContent=d.config?.detected?.policy_table?'✓':'○'; $('table-icon').className=d.config?.detected?.policy_table?'health-ok':'health-warn'; $('policy-table').textContent=d.config?.detected?.policy_table||'—'; + const cpu=d.metrics?.cpu||{}, mem=d.metrics?.memory||{}, net=d.metrics?.network||{}; + if($('cpu-percent')) $('cpu-percent').textContent=cpu.percent==null?'—':Number(cpu.percent).toFixed(1); + if($('cpu-detail')) $('cpu-detail').textContent=`${cpu.cores||'—'} ${t('dashboard.cores','cores')} · Load ${cpu.load1??'—'}`; + if($('cpu-bar')) $('cpu-bar').style.width=`${Math.max(0,Math.min(100,Number(cpu.percent||0)))}%`; + if($('memory-percent')) $('memory-percent').textContent=Number(mem.percent||0).toFixed(1); + if($('memory-detail')) $('memory-detail').textContent=`${fmtBytes(mem.used_bytes)} / ${fmtBytes(mem.total_bytes)}`; + if($('memory-bar')) $('memory-bar').style.width=`${Math.max(0,Math.min(100,Number(mem.percent||0)))}%`; + if($('network-rx-rate')) $('network-rx-rate').textContent=fmtRate(net.rx_bytes_per_second); + if($('network-tx-rate')) $('network-tx-rate').textContent=fmtRate(net.tx_bytes_per_second); + if($('network-interface')) $('network-interface').textContent=net.interface||'—'; + if($('server-uptime')) $('server-uptime').textContent=`${t('dashboard.uptime','Uptime')}: ${fmtUptime(d.metrics?.uptime_seconds)}`; + updateWireGuardControls(d); + const body=$('dashboard-peer-body'); + const search=String($('dashboard-peer-search')?.value||'').trim().toLocaleLowerCase(); + const visiblePeers=search?peers.filter(p=>{ + const status=p?.expired_disabled?t('clients.expired_disabled_status','Expired'):p?.schedule_disabled?t('clients.schedule_blocked_status','Blocked by schedule'):online(p)?t('common.online','Online'):t('common.offline','Offline'); + const haystack=[p?.name,p?.vpn_address,typeOf(p),p?.endpoint,status].map(v=>String(v||'').toLocaleLowerCase()).join(' '); + return haystack.includes(search); + }):peers; + if(!peers.length){body.innerHTML=`${esc(t('clients.no_peers','No peers found'))}`;} else if(!visiblePeers.length){body.innerHTML=`${esc(t('dashboard.quick_search_empty','No peers match the search'))}`;} else renderPeerTable(body,visiblePeers.map(p=>`
${esc(p.name||'Unnamed')}
${online(p)&&p.endpoint?`
Endpoint: ${esc(p.endpoint)}
`:''}${esc(p.vpn_address||'—')}${esc(typeOf(p))}${statusHtml(p)}${esc(ago(p.latest_handshake))}${fmtBytes(p.rx_bytes)}${fmtBytes(p.tx_bytes)}`).join(''),3); + $('last-update').textContent=new Date().toLocaleTimeString(); + if(Array.isArray(d.diagnostics)) renderDashboardDiagnostics(d.diagnostics); + } + function renderDashboardDiagnostics(checks){ + const strip=$('diagnostic-strip');if(!strip)return; + strip.innerHTML=(checks||[]).slice(0,6).map(c=>`
${c.ok?'✓':'✕'}${esc(c.label)}
`).join(''); + } + async function loadDashboardDiagnostics(){ + if(page!=='dashboard')return; + try{const r=await fetch('/api/diagnostics',{cache:'no-store'});const d=await r.json();if(r.ok)renderDashboardDiagnostics(d.diagnostics||[]);}catch(_){} + } + async function loadServerDiagnostics(){ + if(page!=='server'||!$('diagnostics-list'))return; + try{const r=await fetch('/api/diagnostics',{cache:'no-store'});const d=await r.json();if(r.ok)renderDiagnostics(d.diagnostics||[]);}catch(_){} + } + + async function resetTraffic(){ + const button=$('traffic-reset-button'); + if(!confirm(t('dashboard.traffic_reset_confirm','Reset accumulated WireGuard traffic counters for this interface? Client counters will also restart from zero.')))return; + if(button)button.disabled=true; + try{ + const r=await fetch('/api/traffic/reset',{method:'POST',headers:{'Content-Type':'application/json'}}); + const d=await r.json(); + if(!r.ok)throw new Error(d.error||t('dashboard.traffic_reset_failed','Could not reset traffic counters')); + await fetchSnapshot(false); + toast(t('dashboard.traffic_reset_done','Traffic counters reset')); + }catch(e){toast(e.message,5000);} + finally{if(button)button.disabled=false;} + } + + function metricHistoryPath(history,key,{min=0,max=null}={}){ + const points=(history||[]).filter(p=>Number.isFinite(Number(p?.timestamp))&&Number.isFinite(Number(p?.[key]))); + if(!points.length)return ''; + const now=Date.now()/1000, start=now-24*60*60, width=320, height=64; + const values=points.map(p=>Number(p[key])); + const top=max==null?Math.max(1,...values):max; const bottom=min; const span=Math.max(.0001,top-bottom); + const coords=points.map(p=>{const x=Math.max(0,Math.min(width,(Number(p.timestamp)-start)/(24*60*60)*width));const v=Math.max(bottom,Math.min(top,Number(p[key])));const y=height-(v-bottom)/span*height;return [x,y];}); + if(coords.length===1){const [x,y]=coords[0];return `M${x.toFixed(2)} ${y.toFixed(2)}L${Math.min(width,x+.2).toFixed(2)} ${y.toFixed(2)}`;} + return coords.map(([x,y],i)=>`${i?'L':'M'}${x.toFixed(2)} ${y.toFixed(2)}`).join(''); + } + function metricHistoryStats(history,key){ + const values=(history||[]).map(p=>Number(p?.[key])).filter(Number.isFinite); + if(!values.length)return null; + const sum=values.reduce((acc,value)=>acc+value,0); + return {min:Math.min(...values),avg:sum/values.length,max:Math.max(...values)}; + } + function renderHistoryStats(prefix,stats,formatter){ + for(const name of ['min','avg','max']){ + const el=$(`${prefix}-${name}`); + if(el)el.textContent=stats?formatter(stats[name]):'—'; + } + } + function renderMetricsHistory(data){ + const history=(data?.history||[]).filter(p=>Number(p.timestamp)>=Date.now()/1000-24*60*60); + const cpu=$('cpu-history-line'), mem=$('memory-history-line'), rx=$('network-rx-history-line'), tx=$('network-tx-history-line'); + if(cpu)cpu.setAttribute('d',metricHistoryPath(history,'cpu',{min:0,max:100})); + if(mem)mem.setAttribute('d',metricHistoryPath(history,'memory',{min:0,max:100})); + const networkMax=Math.max(1,...history.flatMap(p=>[Number(p.rx||0),Number(p.tx||0)])); + if(rx)rx.setAttribute('d',metricHistoryPath(history,'rx',{min:0,max:networkMax})); + if(tx)tx.setAttribute('d',metricHistoryPath(history,'tx',{min:0,max:networkMax})); + renderHistoryStats('cpu-history',metricHistoryStats(history,'cpu'),value=>`${value.toFixed(1)}%`); + renderHistoryStats('memory-history',metricHistoryStats(history,'memory'),value=>`${value.toFixed(1)}%`); + renderHistoryStats('network-rx-history',metricHistoryStats(history,'rx'),fmtRate); + renderHistoryStats('network-tx-history',metricHistoryStats(history,'tx'),fmtRate); + document.querySelectorAll('.history-chart').forEach(svg=>svg.classList.toggle('is-empty',history.length<2)); + } + async function loadMetricsHistory(){ + if(page!=='dashboard')return; + try{const r=await fetch('/api/metrics/history',{cache:'no-store'});const d=await r.json();if(r.ok)renderMetricsHistory(d);}catch(_){} + } + + function updateWireGuardControls(d){ + const configured=Boolean(d?.wireguard?.config_exists), running=Boolean(d?.running); + const start=$('wg-start-button'), restart=$('wg-restart-button'), stop=$('wg-stop-button'); + if(start) start.disabled=!configured||running; + if(restart) restart.disabled=!configured||!running; + if(stop) stop.disabled=!configured||!running; + } + + async function wireGuardControl(action){ + const labels={start:t('dashboard.start','Start'),stop:t('dashboard.stop','Stop'),restart:t('dashboard.restart','Restart')}; + if(action==='stop'&&!confirm(t('dashboard.stop_confirm','Stop WireGuard? Active VPN clients will be disconnected.')))return; + if(action==='restart'&&!confirm(t('dashboard.restart_confirm','Restart WireGuard? Active VPN clients will reconnect automatically.')))return; + const buttons=['wg-start-button','wg-restart-button','wg-stop-button'].map($).filter(Boolean); buttons.forEach(b=>b.disabled=true); + try{ + const r=await fetch(`/api/server/${action}`,{method:'POST'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||`${labels[action]} failed`); + toast(t(`dashboard.${action}_ok`,`${labels[action]} completed`)); await fetchSnapshot(); + }catch(e){toast(e.message); await fetchSnapshot();} + } + + function bindWireGuardControls(){ + $('wg-start-button')?.addEventListener('click',()=>wireGuardControl('start')); + $('wg-restart-button')?.addEventListener('click',()=>wireGuardControl('restart')); + $('wg-stop-button')?.addEventListener('click',()=>wireGuardControl('stop')); + } + + let activeServerTab = 'interface'; + let vpsPreflight = null; + + function updateServerTabActions(){ + if(page!=='server')return; + const configured=Boolean(snapshot?.wireguard?.config_exists); + const installed=Boolean(snapshot?.wireguard?.installed); + const configuredInterfaces=(interfacesData.interfaces||[]).filter(item=>item.configured); + const interfaceTab=activeServerTab==='interface'; + setHidden('edit-server-button', !interfaceTab || !configured); + setHidden('add-interface-button', !interfaceTab || !installed || configuredInterfaces.length===0); + } + + function activateServerTab(name){ + if(page!=='server')return; + const allowed=['interface','routing','nodes','vps','trace','config']; + activeServerTab=allowed.includes(name)?name:'interface'; + document.querySelectorAll('[data-server-tab]').forEach(button=>{ + const active=button.dataset.serverTab===activeServerTab; + button.classList.toggle('active',active); + button.setAttribute('aria-selected',active?'true':'false'); + button.tabIndex=active?0:-1; + }); + document.querySelectorAll('[data-server-tab-panel]').forEach(panel=>{panel.hidden=panel.dataset.serverTabPanel!==activeServerTab;}); + try{sessionStorage.setItem('wgtools.server.tab',activeServerTab);}catch(_){} + updateServerTabActions(); + if(activeServerTab==='vps')loadVpsList(); + if(activeServerTab==='nodes')loadNodes(); + if(activeServerTab==='trace')window.requestAnimationFrame(()=>renderTraceSlippyMap()); + } + + function bindServerTabs(){ + if(page!=='server')return; + document.querySelectorAll('[data-server-tab]').forEach(button=>{ + button.addEventListener('click',()=>activateServerTab(button.dataset.serverTab)); + button.addEventListener('keydown',event=>{ + if(!['ArrowLeft','ArrowRight'].includes(event.key))return; + const buttons=[...document.querySelectorAll('[data-server-tab]')].filter(x=>!x.hidden&&!x.disabled); + const index=buttons.indexOf(button);if(index<0||!buttons.length)return; + event.preventDefault();const next=buttons[(index+(event.key==='ArrowRight'?1:-1)+buttons.length)%buttons.length]; + activateServerTab(next.dataset.serverTab);next.focus(); + }); + }); + let remembered='interface';try{remembered=sessionStorage.getItem('wgtools.server.tab')||'interface';}catch(_){} + activateServerTab(remembered); + } + + let nodesData = null; + + function currentPanelUrl(){ + const path=basePath?`${basePath}/`:'/'; + return `${location.origin}${path}`; + } + + function nodeNetworks(node){ + return (node?.exports||[]).map(x=>typeof x==='string'?x:x?.network).filter(Boolean); + } + + function availableNodeNetworks(){ + return (nodesData?.available_networks||[]).map(x=>typeof x==='string'?x:x?.network).filter(Boolean); + } + + function detectedNodeNetworks(){ + return (nodesData?.detected_networks||[]).map(x=>typeof x==='string'?x:x?.network).filter(Boolean); + } + + function nodeNetworkChangeMessage(changes){ + if(!changes?.changed)return ''; + const added=(changes.added||[]).join(', ')||'—'; + const removed=(changes.removed||[]).join(', ')||'—'; + return t('nodes.networks_changed','Detected local networks changed after the published list was last saved. New: {added}. No longer detected: {removed}. Review the published networks.') + .replace('{added}',added).replace('{removed}',removed); + } + + function nodeVpnPoolMismatchMessage(mismatch){ + if(!mismatch?.changed)return ''; + const oldPools=(mismatch.published_old||[]).join(', ')||'—'; + const currentPools=(mismatch.current_vpn||[]).join(', ')||'—'; + return t('nodes.vpn_pool_mismatch','VPN pool changed: Nodes still publishes {old}, while the current WireGuard VPN pool is {current}. Open Node settings and update the published networks.') + .replace('{old}',oldPools).replace('{current}',currentPools); + } + + function nodeReviewMessage(data){ + const vpn=nodeVpnPoolMismatchMessage(data?.vpn_pool_mismatch); + if(vpn)return vpn; + return nodeNetworkChangeMessage(data?.network_changes); + } + + function nodeApiErrorMessage(data,fallback){ + if(data?.error_code==='network_conflict'){ + const conflicts=(data.conflicts||[]).map(item=>{ + const left=item?.network||'—', right=item?.owner_network||'—'; + const owner=item?.owner_type==='transport'?t('nodes.transport_network','Node transport network'):(item?.owner_name||'WGTools'); + return `${left} ↔ ${right} (${owner})`; + }).filter(Boolean).join('; '); + return t('nodes.network_conflict_error','Published networks conflict with another Node or the Nodes transport network: {conflicts}. Remove or change the conflicting network.') + .replace('{conflicts}',conflicts||data.error||'—'); + } + return data?.error||fallback; + } + + function nodeModeText(mode){ + if(mode==='hub')return t('nodes.mode_hub','HUB'); + if(mode==='spoke')return t('nodes.mode_spoke','Connected to HUB'); + return t('nodes.mode_none','Not configured'); + } + + function renderNodes(data){ + nodesData=data||{mode:'none',nodes:[]}; + const mode=nodesData.mode||'none'; + const configured=mode==='hub'||mode==='spoke'; + setHidden('nodes-enable-hub-button',configured); + setHidden('nodes-connect-button',configured); + setHidden('nodes-settings-button',!configured); + setHidden('nodes-disable-button',!configured); + setHidden('nodes-sync-button',mode!=='spoke'); + setHidden('nodes-join-card',mode!=='hub'); + setHidden('nodes-list-card',!configured); + + const status=$('nodes-status'); + if(status){ + if(!configured){ + status.innerHTML=`
${esc(t('nodes.not_configured','WGTools Nodes is not configured'))}

${esc(t('nodes.not_configured_help','Enable HUB on this panel or connect it to an existing WGTools HUB.'))}

`; + }else{ + const local=nodesData.local||{}, hub=nodesData.hub||{}; + const exports=nodeNetworks(local); + const service=nodesData.service_active; + const role=mode==='hub'?t('nodes.mode_hub','HUB'):t('nodes.mode_spoke','Spoke'); + const endpoint=mode==='hub'?`TCP/UDP :${hub.endpoint_port||'—'}`:(hub.endpoint_host?`${hub.endpoint_host}:${hub.endpoint_port||'—'}`:'—'); + const sync=mode==='spoke'?(nodesData.last_sync?ago(nodesData.last_sync):t('common.never','Never')):'—'; + const nodeError=nodesData.last_error||nodesData.control_error||''; + const error=nodeError?`
${esc(nodeError)}
`:''; + const networkChange=nodeReviewMessage(nodesData); + const networkReview=networkChange?` ${esc(t('nodes.review_networks','Review networks'))}`:''; + const networkWarning=networkChange?`
${esc(networkChange)}
`:''; + status.classList.toggle('nodes-network-drift',Boolean(networkChange)); + status.innerHTML=`
${esc(t('nodes.role','Role'))}
${esc(role)}
${esc(t('nodes.tunnel','Node tunnel'))}
${service?esc(t('common.running','Running')):esc(t('common.stopped','Stopped'))} · ${esc(nodesData.interface||'wgnode0')}
${esc(t('nodes.node_name','Node name'))}
${esc(local.name||'—')}
${esc(t('nodes.node_ip','Node IP'))}
${esc(local.transport_ip||nodesData.hub?.transport_ip||'—')}
${esc(t('nodes.endpoint','HUB endpoint'))}
${esc(endpoint)}
${esc(t('nodes.published_networks','Published networks'))}${networkReview}
${esc(exports.join(', ')||'—')}
${mode==='spoke'?`
${esc(t('nodes.last_sync','Last sync'))}
${esc(sync)}
`:''}
${networkWarning}${error}`; + } + } + + const list=$('nodes-list'); + if(list&&configured){ + const nodes=nodesData.nodes||[]; + if(!nodes.length){list.innerHTML=`
${esc(mode==='hub'?t('nodes.no_nodes_hub','No nodes are connected yet. Create a connection code and use it on another WGTools panel.'):t('nodes.no_nodes_spoke','No remote node information has been received yet.'))}
`;return;} + list.innerHTML=nodes.map(node=>{ + const networks=nodeNetworks(node); + const conflicts=node.conflicts||[]; + const status=node.online?t('common.online','Online'):t('common.offline','Offline'); + const panel=node.panel_url?``:''; + const remove=mode==='hub'?``:''; + const conflictBadge=conflicts.length?`${esc(t('nodes.route_conflict','Route conflict'))}`:''; + return `
${esc(node.name||'WGTools')}${esc(status)}${conflictBadge}
${esc(node.transport_ip||'—')}WGTools v${esc(node.version||'—')}${esc(t('nodes.clients_short','Clients'))}: ${esc(node.online_clients||0)}/${esc(node.client_count||0)}${esc(networks.join(', ')||t('nodes.no_published_networks','No published networks'))}
${panel}${remove}
`; + }).join(''); + } + } + + async function loadNodes(showToast=false){ + if(page!=='server'||!$('nodes-status'))return; + try{ + const r=await fetch('/api/nodes',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.load_failed','Could not load WGTools Nodes')); + renderNodes(d);if(showToast)toast(t('common.updated','Updated')); + }catch(e){operationStatus('nodes-operation-status',e.message,'error');} + } + + function openNodeHubModal(){ + $('node-hub-name').value=nodesData?.local?.name||location.hostname||'WGTools HUB'; + $('node-hub-port').value='51950';$('node-hub-network').value='10.254.240.0/24'; + $('node-hub-extra').value=availableNodeNetworks().join('\n');operationStatus('node-hub-status','');modalShow('node-hub-modal',true); + } + + async function enableNodeHub(event){ + event.preventDefault();const button=$('node-hub-save');if(!button)return; + const payload={node_name:$('node-hub-name').value.trim(),listen_port:Number($('node-hub-port').value||51950),transport_network:$('node-hub-network').value.trim(),published_networks:splitList($('node-hub-extra').value)}; + if(!confirm(t('nodes.enable_hub_confirm','Enable WGTools HUB and create the internal Node WireGuard tunnel?')))return; + button.disabled=true;operationStatus('node-hub-status',t('nodes.applying','Configuring the WGTools Node tunnel…'),'working'); + try{const r=await fetch('/api/nodes/hub/enable',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(nodeApiErrorMessage(d,t('nodes.enable_failed','Could not enable HUB')));renderNodes(d);modalShow('node-hub-modal',false);toast(t('nodes.hub_enabled','WGTools HUB enabled'));}catch(e){operationStatus('node-hub-status',e.message,'error');}finally{button.disabled=false;} + } + + function openNodeConnectModal(){ + $('node-connect-name').value=location.hostname||'WGTools Node';$('node-connect-hub-endpoint').value='';$('node-connect-code').value='';$('node-connect-extra').value=availableNodeNetworks().join('\n');operationStatus('node-connect-status','');modalShow('node-connect-modal',true); + } + + async function connectNode(event){ + event.preventDefault();const button=$('node-connect-save');if(!button)return; + const payload={node_name:$('node-connect-name').value.trim(),hub_endpoint:$('node-connect-hub-endpoint').value.trim(),join_code:$('node-connect-code').value.trim(),published_networks:splitList($('node-connect-extra').value)}; + button.disabled=true;operationStatus('node-connect-status',t('nodes.connecting','Pairing panels and creating the protected Node tunnel…'),'working'); + try{const r=await fetch('/api/nodes/connect',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(nodeApiErrorMessage(d,t('nodes.connect_failed','Could not connect to HUB')));renderNodes(d);modalShow('node-connect-modal',false);toast(t('nodes.connected','Connected to WGTools HUB'));}catch(e){operationStatus('node-connect-status',e.message,'error');}finally{button.disabled=false;} + } + + function openNodeSettings(){ + const local=nodesData?.local||{}; + const selected=(nodesData?.published_networks||nodeNetworks(local)); + $('node-settings-name').value=local.name||'';$('node-settings-panel-url').value=local.panel_url||currentPanelUrl();$('node-settings-extra').value=selected.join('\n'); + const detected=$('node-settings-available');if(detected){const available=detectedNodeNetworks();detected.textContent=available.length?t('nodes.available_networks_help','Currently detected: {networks}').replace('{networks}',available.join(', ')):t('nodes.available_networks_none','No additional local networks detected.');} + const changed=$('node-settings-network-change'),changeText=nodeReviewMessage(nodesData);if(changed){changed.textContent=changeText;setHidden('node-settings-network-change',!changeText);} + $('node-settings-extra')?.classList.toggle('network-drift-field',Boolean(changeText)); + operationStatus('node-settings-status','');modalShow('node-settings-modal',true); + } + + async function saveNodeSettings(event){ + event.preventDefault();const button=$('node-settings-save');if(!button)return; + const payload={node_name:$('node-settings-name').value.trim(),panel_url:$('node-settings-panel-url').value.trim(),published_networks:splitList($('node-settings-extra').value)}; + button.disabled=true;operationStatus('node-settings-status',t('nodes.applying','Applying Node settings…'),'working'); + try{const r=await fetch('/api/nodes/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(nodeApiErrorMessage(d,t('nodes.settings_failed','Could not save Node settings')));renderNodes(d);modalShow('node-settings-modal',false);toast(t('nodes.settings_saved','Node settings saved'));}catch(e){operationStatus('node-settings-status',e.message,'error');}finally{button.disabled=false;} + } + + async function createNodeCode(){ + const button=$('nodes-create-code-button');if(button)button.disabled=true; + try{const r=await fetch('/api/nodes/hub/code',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.code_failed','Could not create connection code'));$('nodes-join-code').value=d.code||'';setHidden('nodes-code-row',false);$('nodes-code-expiry').textContent=d.expires_at?t('nodes.code_expires','One-time code. Valid until {time}.').replace('{time}',new Date(Number(d.expires_at)*1000).toLocaleTimeString()):'';}catch(e){toast(e.message,5000);}finally{if(button)button.disabled=false;} + } + + async function copyNodeCode(){ + const field=$('nodes-join-code'),value=field?.value||'';if(!value)return; + try{ + if(navigator.clipboard?.writeText&&window.isSecureContext){await navigator.clipboard.writeText(value);} + else{ + field.focus();field.select();field.setSelectionRange(0,value.length); + if(!document.execCommand('copy'))throw new Error('copy failed'); + window.getSelection()?.removeAllRanges(); + } + toast(t('nodes.code_copied','Connection code copied')); + }catch{ + try{ + field.focus();field.select();field.setSelectionRange(0,value.length); + if(!document.execCommand('copy'))throw new Error('copy failed'); + window.getSelection()?.removeAllRanges();toast(t('nodes.code_copied','Connection code copied')); + }catch{toast(t('common.copy_failed','Could not copy'));} + } + } + + function renderNodeDetails(node){ + const title=$('node-details-title'),sub=$('node-details-subtitle'),body=$('node-details-body');if(!body)return; + if(title)title.textContent=node.name||t('nodes.details','Node details');if(sub)sub.textContent=`${node.online?t('common.online','Online'):t('common.offline','Offline')} · ${node.transport_ip||'—'} · WGTools v${node.version||'—'}`; + const exports=node.exports||[], clients=node.clients||[], conflicts=new Set(node.conflicts||[]); + const networkRows=exports.length?exports.map(item=>{const net=typeof item==='string'?item:item.network;const kind=typeof item==='string'?'':item.kind;return `${esc(net||'—')}${esc(kind==='vpn'?t('nodes.network_vpn','VPN clients'):kind==='site_to_site'?t('nodes.network_site_to_site','Site-to-site network'):kind==='custom'?t('nodes.network_custom','Additional network'):kind||'—')}${conflicts.has(net)?`${esc(t('nodes.conflict','Conflict'))}`:`${esc(t('common.enabled','Enabled'))}`}`;}).join(''):`${esc(t('nodes.no_published_networks','No published networks'))}`; + const clientRows=clients.length?clients.map(c=>` ${esc(c.name||'—')}${esc(c.interface||'—')}${esc(c.vpn_address||'—')}${esc(c.type==='site_to_site'?t('clients.site_to_site','Site-to-site'):t('clients.client','Client'))}${esc(c.last_seen?ago(c.last_seen):t('common.never','Never'))}`).join(''):`${esc(t('nodes.no_clients','No clients reported'))}`; + const searchEmpty=clients.length?`${esc(t('clients.quick_search_empty','No clients match the search'))}`:''; + const error=node.last_error?`
${esc(node.last_error)}
`:''; + body.innerHTML=`${error}
${esc(t('nodes.published_networks','Published networks'))}
${networkRows}
${esc(t('server.network','Network'))}${esc(t('common.type','Type'))}${esc(t('common.status','Status'))}
${esc(t('nodes.remote_clients','Clients (read-only)'))}
${clientRows}${searchEmpty}
${esc(t('clients.name','Name'))}${esc(t('server.interface','Interface'))}${esc(t('clients.vpn_address','VPN address'))}${esc(t('common.type','Type'))}${esc(t('clients.handshake','Handshake'))}
`; + const search=$('node-details-client-search'),clear=$('node-details-client-search-clear'),empty=$('node-details-client-search-empty'); + const applySearch=()=>{const query=String(search?.value||'').trim().toLocaleLowerCase();let visible=0;body.querySelectorAll('[data-node-client-row]').forEach(row=>{const show=!query||String(row.textContent||'').toLocaleLowerCase().includes(query);row.hidden=!show;if(show)visible+=1;});if(clear)clear.hidden=!query;if(empty)empty.hidden=!(query&&clients.length&&visible===0);}; + search?.addEventListener('input',applySearch);search?.addEventListener('search',applySearch);clear?.addEventListener('click',()=>{if(!search)return;search.value='';applySearch();search.focus();}); + modalShow('node-details-modal',true); + } + + async function openNodeDetails(id){ + try{const r=await fetch(`/api/nodes/${encodeURIComponent(id)}/details`,{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.details_failed','Could not load Node details'));renderNodeDetails(d.node||{});}catch(e){toast(e.message,5000);} + } + + function openRemoteNodePanel(id){const node=(nodesData?.nodes||[]).find(x=>String(x.node_id)===String(id));if(node?.panel_url)window.open(node.panel_url,'_blank','noopener');} + + async function removeNode(id){ + const node=(nodesData?.nodes||[]).find(x=>String(x.node_id)===String(id));if(!confirm(t('nodes.remove_confirm','Remove node “{name}” from this HUB? Its Node tunnel access will be revoked.').replace('{name}',node?.name||id)))return; + try{const r=await fetch(`/api/nodes/${encodeURIComponent(id)}`,{method:'DELETE'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.remove_failed','Could not remove Node'));renderNodes(d);toast(t('nodes.removed','Node removed'));}catch(e){toast(e.message,5000);} + } + + async function disableNodes(){ + const message=nodesData?.mode==='hub'?t('nodes.disable_hub_confirm','Disable HUB and disconnect all WGTools Nodes? The internal Node tunnel will be removed.'):t('nodes.disconnect_confirm','Disconnect this WGTools panel from its HUB and remove the internal Node tunnel?');if(!confirm(message))return; + try{const r=await fetch('/api/nodes/disable',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.disable_failed','Could not disable WGTools Nodes'));renderNodes(d);toast(t('nodes.disabled','WGTools Nodes disabled'));}catch(e){toast(e.message,5000);} + } + + async function syncNodes(){const button=$('nodes-sync-button');if(button)button.disabled=true;try{const r=await fetch('/api/nodes/sync-now',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(nodeApiErrorMessage(d,t('nodes.sync_failed','Node synchronization failed')));await loadNodes();toast(t('nodes.synced','Node information synchronized'));}catch(e){toast(e.message,5000);}finally{if(button)button.disabled=false;}} + + function bindNodes(){ + if(page!=='server')return; + $('nodes-enable-hub-button')?.addEventListener('click',openNodeHubModal);$('node-hub-form')?.addEventListener('submit',enableNodeHub); + $('nodes-connect-button')?.addEventListener('click',openNodeConnectModal);$('node-connect-form')?.addEventListener('submit',connectNode); + $('nodes-settings-button')?.addEventListener('click',openNodeSettings);$('node-settings-form')?.addEventListener('submit',saveNodeSettings); + $('nodes-create-code-button')?.addEventListener('click',createNodeCode);$('nodes-copy-code-button')?.addEventListener('click',copyNodeCode); + $('nodes-refresh-button')?.addEventListener('click',()=>loadNodes(true));$('nodes-sync-button')?.addEventListener('click',syncNodes);$('nodes-disable-button')?.addEventListener('click',disableNodes); + $('nodes-list')?.addEventListener('click',e=>{const details=e.target.closest('[data-node-details]');if(details){openNodeDetails(details.dataset.nodeDetails);return;}const open=e.target.closest('[data-node-open]');if(open){openRemoteNodePanel(open.dataset.nodeOpen);return;}const remove=e.target.closest('[data-node-remove]');if(remove)removeNode(remove.dataset.nodeRemove);}); + } + + let activeSettingsTab = 'general'; + + function activateSettingsTab(name,{updateHash=true}={}){ + if(page!=='settings')return; + const allowed=['general','backups','telegram','mail','https','users','about']; + activeSettingsTab=allowed.includes(name)?name:'general'; + document.querySelectorAll('[data-settings-tab]').forEach(button=>{ + const active=button.dataset.settingsTab===activeSettingsTab; + button.classList.toggle('active',active); + button.setAttribute('aria-selected',active?'true':'false'); + button.tabIndex=active?0:-1; + }); + document.querySelectorAll('[data-settings-tab-panel]').forEach(panel=>{panel.hidden=panel.dataset.settingsTabPanel!==activeSettingsTab;}); + try{sessionStorage.setItem('wgtools.settings.tab',activeSettingsTab);}catch(_){} + if(updateHash){ + try{history.replaceState(null,'',`${location.pathname}${location.search}#${activeSettingsTab}`);}catch(_){} + } + } + + function bindSettingsTabs(){ + if(page!=='settings')return; + const allowed=['general','backups','telegram','mail','https','users','about']; + document.querySelectorAll('[data-settings-tab]').forEach(button=>{ + button.addEventListener('click',()=>activateSettingsTab(button.dataset.settingsTab)); + button.addEventListener('keydown',event=>{ + if(!['ArrowLeft','ArrowRight'].includes(event.key))return; + const buttons=[...document.querySelectorAll('[data-settings-tab]')].filter(x=>!x.hidden&&!x.disabled); + const index=buttons.indexOf(button);if(index<0||!buttons.length)return; + event.preventDefault();const next=buttons[(index+(event.key==='ArrowRight'?1:-1)+buttons.length)%buttons.length]; + activateSettingsTab(next.dataset.settingsTab);next.focus(); + }); + }); + let initial=String(location.hash||'').replace(/^#/,''); + if(!allowed.includes(initial)){ + try{initial=sessionStorage.getItem('wgtools.settings.tab')||'general';}catch(_){initial='general';} + } + activateSettingsTab(initial,{updateHash:false}); + window.addEventListener('hashchange',()=>{ + const hash=String(location.hash||'').replace(/^#/,''); + if(allowed.includes(hash))activateSettingsTab(hash,{updateHash:false}); + }); + } + + let vpsItems = []; + let vpsEditingId = ''; + let vpsModalMode = 'new'; + + function vpsPayload(){ + return { + name:$('vps-name')?.value.trim()||'',host:$('vps-host')?.value.trim()||'', + ssh_port:Number($('vps-ssh-port')?.value||22),ssh_user:$('vps-ssh-user')?.value.trim()||'', + auth_method:$('vps-auth-method')?.value||'password',password:$('vps-password')?.value||'', + private_key:$('vps-private-key')?.value||'',key_passphrase:$('vps-key-passphrase')?.value||'', + endpoint_domain:$('vps-endpoint-domain')?.value.trim()||'',relay_port:Number($('vps-relay-port')?.value||51820), + transport_port:Number($('vps-transport-port')?.value||51900), + }; + } + + function vpsCredentialPayload(){ + return {auth_method:$('vps-auth-method')?.value||'password',password:$('vps-password')?.value||'',private_key:$('vps-private-key')?.value||'',key_passphrase:$('vps-key-passphrase')?.value||''}; + } + + function setVpsIdentityReadonly(value){ + ['vps-name','vps-host','vps-ssh-port','vps-ssh-user','vps-endpoint-domain','vps-relay-port','vps-transport-port'].forEach(id=>{if($(id))$(id).readOnly=Boolean(value);}); + } + + function resetVpsVerification(){ + vpsPreflight=null; + if($('vps-save-button'))$('vps-save-button').disabled=true; + if($('vps-install-button'))$('vps-install-button').disabled=true; + setHidden('vps-preflight-result',true);operationStatus('vps-preflight-status',''); + } + + function syncVpsAuthFields(){ + const key=$('vps-auth-method')?.value==='key';setHidden('vps-password-wrap',key);setHidden('vps-key-wrap',!key);setHidden('vps-key-passphrase-wrap',!key); + resetVpsVerification(); + } + + function openVpsModal(item=null,mode='new'){ + const form=$('vps-form');if(!form)return;form.reset();vpsEditingId=item?.id||'';vpsModalMode=mode; + $('vps-ssh-port').value=String(item?.ssh_port||22);$('vps-ssh-user').value=item?.ssh_user||'root'; + $('vps-name').value=item?.name||'';$('vps-host').value=item?.host||'';$('vps-endpoint-domain').value=item?.endpoint_domain||''; + $('vps-relay-port').value=String(item?.relay_port||snapshot?.listen_port||snapshot?.config?.interface?.listen_port||51820); + $('vps-transport-port').value=String(item?.transport_port||51900); + $('vps-auth-method').value='password';setVpsIdentityReadonly(mode==='install');syncVpsAuthFields(); + setHidden('vps-save-button',true);setHidden('vps-install-button',mode!=='install'); + if($('vps-modal-title'))$('vps-modal-title').textContent=mode==='install'?t('vps.install_title','Install Relay'):t('vps.add_title','Add VPS'); + if($('vps-install-button'))$('vps-install-button').textContent=t('vps.install_relay','Install Relay'); + modalShow('vps-modal',true);setTimeout(()=>$(mode==='install'?'vps-password':'vps-name')?.focus(),30); + } + + function renderVpsPreflight(data){ + const el=$('vps-preflight-result');if(!el)return; + const yes=t('common.yes','Yes'); + const agent=data.relay_agent_installed + ? `
${esc(t('vps.agent','Relay Agent'))}
${esc(t('vps.agent_found','Already installed'))} · ${esc(t('vps.saved_short','Saved'))}: ${esc(data.relay_tenant_count||0)} · ${esc(t('vps.active_short','Active'))}: ${esc(data.relay_active_tenant_count||0)}
` + : `
${esc(t('vps.agent','Relay Agent'))}
${esc(t('vps.agent_will_install','Will be installed'))}
`; + const portNote=data.ports_adjusted?` ${esc(t('vps.ports_adjusted','free ports selected'))}`:''; + const note=data.reconnect_available + ? `
${esc(t('vps.reconnect_note','An existing Relay connection created by this WGTools was found. WGTools will reconnect to it; no new tenant or UDP ports will be created.'))}
` + : (data.relay_agent_installed?`
${esc(t('vps.multi_tenant_note','The existing Relay Agent will not be replaced. WGTools will create a separate isolated connection for this controller.'))}
`:''); + el.innerHTML=`
${esc(t('vps.check_ok','VPS is compatible'))}
${esc(t('vps.os','Operating system'))}
${esc(data.os_name||'—')}
${esc(t('vps.arch','Architecture'))}
${esc(data.architecture||'—')}
${esc(t('vps.privilege','Privileges'))}
${esc(data.privilege_mode||'—')}
${esc(t('vps.host_key','SSH host key'))}
${esc(data.host_key_fingerprint||'—')}
${esc(t('vps.wireguard','WireGuard'))}
${esc(data.wireguard_installed?yes:t('vps.not_installed','Will be installed'))}
${esc(t('vps.iptables','iptables'))}
${esc(data.iptables_installed?yes:t('vps.not_installed','Will be installed'))}
${agent}
${esc(t('vps.port_pair','UDP ports'))}
${esc(data.relay_port)} / ${esc(data.transport_port)}${portNote}
${note}`; + el.hidden=false; + } + + async function checkVps(){ + const button=$('vps-check-button');if(!button)return;button.disabled=true; + if($('vps-save-button'))$('vps-save-button').disabled=true;if($('vps-install-button'))$('vps-install-button').disabled=true; + vpsPreflight=null;setHidden('vps-preflight-result',true);operationStatus('vps-preflight-status',t('vps.checking','Checking SSH access and VPS compatibility…'),'working'); + try{ + const r=await fetch('/api/vps/preflight',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(vpsPayload())});const d=await r.json();if(!r.ok)throw new Error(d.error||t('vps.check_failed','VPS check failed')); + vpsPreflight=d; + if(d.relay_port)$('vps-relay-port').value=String(d.relay_port);if(d.transport_port)$('vps-transport-port').value=String(d.transport_port); + operationStatus('vps-preflight-status','');renderVpsPreflight(d); + setHidden('vps-install-button',false);$('vps-install-button').disabled=false; + $('vps-install-button').textContent=d.reconnect_available?t('vps.reconnect_relay','Reconnect Relay'):t('vps.install_relay','Install Relay'); + }catch(e){operationStatus('vps-preflight-status',e.message,'error');}finally{button.disabled=false;} + } + + function renderVpsList(items){ + const list=$('vps-list'),empty=$('vps-empty');if(!list)return;vpsItems=items||[];if(empty)empty.hidden=vpsItems.length>0; + list.innerHTML=vpsItems.map(item=>{ + const endpoint=item.endpoint_domain?`${item.endpoint_domain}:${item.relay_port}`:`${item.host}:${item.relay_port}`; + const installed=item.status==='installed'; + const status=installed?t('vps.status_installed','Relay connected'):t('vps.status_candidate','Ready for installation'); + const meta=[item.os_name||item.os_id||'—',item.architecture||'—',endpoint]; + if(installed&&item.published_interface){ + const transport=item.transport_interface?` · ${item.transport_interface}`:''; + meta.push(`${item.published_interface}${transport} → ${item.home_transport_ip||'—'} ↔ ${item.relay_transport_ip||'—'}`); + } + const side=installed + ? `${esc(t('vps.tenant','Tenant'))}: ${esc((item.tenant_id||'').slice(0,10))}` + : `${esc(t('vps.ready_help','SSH credentials are requested again only for installation.'))}`; + return `
${esc(item.name)}${esc(status)}
${meta.map(x=>`${esc(x)}`).join('')}
${side}
`; + }).join(''); + } + + async function loadVpsList(){ + if(page!=='server'||!$('vps-list'))return;try{const r=await fetch('/api/vps',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'VPS list failed');renderVpsList(d.items||[]);}catch(e){$('vps-list').innerHTML=`
${esc(e.message)}
`;} + } + + async function saveVpsCandidate(event){ + event.preventDefault();if(vpsModalMode==='install')return;if(!vpsPreflight)return;const button=$('vps-save-button');button.disabled=true; + try{const payload={...vpsPayload(),preflight:vpsPreflight};const r=await fetch('/api/vps/candidates',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Save failed');modalShow('vps-modal',false);toast(t('vps.saved','VPS candidate saved'));await loadVpsList();}catch(e){operationStatus('vps-preflight-status',e.message,'error');}finally{button.disabled=false;} + } + + async function installVpsRelay(){ + if(!vpsPreflight)return;const button=$('vps-install-button');if(!button)return;button.disabled=true;$('vps-check-button').disabled=true; + operationStatus('vps-preflight-status',t('vps.installing','Installing Relay Agent and establishing the protected transport tunnel…'),'working'); + let createdCandidate=false; + try{ + if(!vpsEditingId){ + const savePayload={...vpsPayload(),preflight:vpsPreflight}; + const sr=await fetch('/api/vps/candidates',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(savePayload)});const sd=await sr.json();if(!sr.ok)throw new Error(sd.error||'Could not prepare VPS installation'); + vpsEditingId=sd.item?.id||'';createdCandidate=Boolean(vpsEditingId)&&!Boolean(vpsPreflight?.reconnect_available);if(!vpsEditingId)throw new Error('WGTools did not return a VPS installation id'); + } + const r=await fetch(`/api/vps/${encodeURIComponent(vpsEditingId)}/install`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(vpsCredentialPayload())});const d=await r.json();if(!r.ok)throw new Error(d.error||'Relay installation failed'); + modalShow('vps-modal',false);toast(d.reconnected?t('vps.reconnect_ok','Existing Relay reconnected successfully'):t('vps.install_ok','Relay installed and management tunnel verified'));await loadVpsList(); + }catch(e){ + if(createdCandidate&&vpsEditingId){try{await fetch(`/api/vps/candidates/${encodeURIComponent(vpsEditingId)}`,{method:'DELETE'});}catch{}vpsEditingId='';} + operationStatus('vps-preflight-status',e.message,'error');button.disabled=false; + }finally{$('vps-check-button').disabled=false;} + } + + async function deleteVpsCandidate(id){ + if(!confirm(t('vps.remove_confirm','Remove this VPS candidate? No remote changes have been made.')))return;try{const r=await fetch(`/api/vps/candidates/${encodeURIComponent(id)}`,{method:'DELETE'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');await loadVpsList();}catch(e){toast(e.message);} + } + + async function removeInstalledVps(id){ + const item=vpsItems.find(x=>x.id===id); + const message=t('vps.delete_installed_confirm','Remove “{name}” from WGTools? The local Relay transport will be disconnected, but the Relay Agent and tenant on the VPS will be preserved so a WGTools backup can reconnect to it later. Clients using this Relay will stop connecting through it until the state is restored or they are reconfigured.').replace('{name}',item?.name||'VPS'); + if(!confirm(message))return; + try{ + const r=await fetch(`/api/vps/${encodeURIComponent(id)}`,{method:'DELETE'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('vps.delete_installed_failed','Could not remove VPS from WGTools')); + toast(t('vps.delete_installed_ok','VPS removed from WGTools. The Relay on the remote VPS was preserved.'),5000); + await loadVpsList(); + }catch(e){toast(e.message,5000);} + } + + function bindVps(){ + if(page!=='server')return; + $('vps-add-button')?.addEventListener('click',()=>openVpsModal());$('vps-auth-method')?.addEventListener('change',syncVpsAuthFields);$('vps-check-button')?.addEventListener('click',checkVps);$('vps-form')?.addEventListener('submit',e=>e.preventDefault());$('vps-install-button')?.addEventListener('click',installVpsRelay); + $('vps-list')?.addEventListener('click',e=>{ + const del=e.target.closest('[data-vps-delete]');if(del){deleteVpsCandidate(del.dataset.vpsDelete);return;} + const remove=e.target.closest('[data-vps-remove]');if(remove){removeInstalledVps(remove.dataset.vpsRemove);return;} + const install=e.target.closest('[data-vps-install]');if(install){const item=vpsItems.find(x=>x.id===install.dataset.vpsInstall);if(item)openVpsModal(item,'install');return;} + const health=e.target.closest('[data-vps-health]');if(health){checkVpsHealth(health.dataset.vpsHealth);} + }); + ['vps-name','vps-host','vps-ssh-port','vps-ssh-user','vps-password','vps-private-key','vps-key-passphrase','vps-endpoint-domain','vps-relay-port','vps-transport-port'].forEach(id=>$(id)?.addEventListener('input',resetVpsVerification)); + } + + function renderServer(d){ + const installed=Boolean(d.wireguard?.installed); + const configured=Boolean(d.wireguard?.config_exists); + const configuredInterfaces=(interfacesData.interfaces||[]).filter(item=>item.configured); + setHidden('edit-server-button', !configured); + setHidden('add-interface-button', !installed || configuredInterfaces.length===0); + setHidden('interface-manager-card', !installed || configuredInterfaces.length===0); + setHidden('wireguard-install-card', installed); + setHidden('create-server-card', !installed || configured || configuredInterfaces.length>0); + setHidden('configured-server', !configured); + renderInterfaceManager(); + + if(installed && !configured && configuredInterfaces.length===0){ + const uplink=$('setup-uplink'), gateway=$('setup-gateway'), local=$('setup-local-network'); + if(uplink && !uplink.dataset.touched) uplink.value=d.system?.default_uplink||''; + if(gateway && !gateway.dataset.touched) gateway.value=d.system?.default_gateway||''; + if(local && !local.dataset.touched) local.value=d.system?.local_network||''; + } + + if(configured){ + const i=d.config?.interface||{}, x=d.config?.detected||{}; + $('interface-kv').innerHTML=[['Interface',d.interface], [t('server.address','Address'),i.address], [t('server.listen_port','Listen port'),i.listen_port||d.listen_port], [t('server.mtu','MTU'),i.mtu||t('server.mtu_auto','Auto')], [t('server.private_key','Private key'),i.private_key_set?t('server.private_hidden','Configured (hidden)'):t('server.not_set','Not set')], [t('server.save_config','SaveConfig'),i.save_config||'false']].map(([a,b])=>`
${esc(a)}
${esc(b||'—')}
`).join(''); + $('routing-kv').innerHTML=[[t('server.vpn_network','VPN network'),x.vpn_network],[t('server.policy_table','Policy table'),x.policy_table],[t('server.uplink','Uplink interface'),x.uplink_interface||d.system?.default_uplink],[t('server.gateway','Gateway'),x.gateway||d.system?.default_gateway],[t('server.local_network','Local network'),x.local_network||d.system?.local_network],[t('server.ip_forwarding','IPv4 forwarding'),d.system?.ip_forwarding?t('common.enabled','Enabled'):t('common.disabled','Disabled')]].map(([a,b])=>`
${esc(a)}
${esc(b||'—')}
`).join(''); + renderRoutes(d); + renderFirewall(d); + } + if(Array.isArray(d.diagnostics)) renderDiagnostics(d.diagnostics); + updateServerTabActions(); + } + + + function routeTypeText(category){ + if(category==='server')return t('server.route_managed_server','Server setting'); + if(category==='site_to_site')return t('server.route_managed_peer','Site-to-site peer'); + return t('server.route_custom','Custom'); + } + + function routeViaText(r){ + const parts=[]; if(r.via)parts.push(`${t('server.via_word','via')} ${r.via}`); if(r.device)parts.push(`${t('server.dev_word','dev')} ${r.device}`); return parts.join(' · ')||'—'; + } + + function renderRoutes(d){ + const body=$('route-body'); if(!body)return; + const routes=d.route_items||[]; + if(!routes.length){body.innerHTML=`${esc(t('server.no_routes','No routes detected'))}`;return;} + body.innerHTML=routes.map((r,index)=>` + ${esc(r.network||'default')} + ${esc(routeViaText(r))} + ${esc(r.table||'main')} + ${esc(routeTypeText(r.category))} + ${r.editable?`
`:`${esc(t('server.managed_automatically','Managed automatically'))}`} + `).join(''); + } + + function firewallTypeText(item){ + if(item.category==='server')return t('server.rule_managed_server','Server setting'); + if(item.category==='access'&&item.access?.managed_tag&&item.access?.action==='ACCEPT')return t('server.rule_client_exception','Client exception'); + if(item.category==='access'&&item.access?.managed_tag)return t('server.rule_client_policy','Client policy'); + if(item.category==='access')return t('server.rule_access','Access rule'); + return t('server.rule_advanced','Advanced'); + } + + function commandAction(command){ + const c=String(command||''); if(c.includes('MASQUERADE'))return 'MASQUERADE'; const m=c.match(/\s-j\s+(ACCEPT|REJECT|DROP)\b/); return m?m[1]:'—'; + } + + function renderFirewall(d){ + const body=$('firewall-body'); if(!body)return; + const rules=d.firewall_items||[]; + if(!rules.length){body.innerHTML=`${esc(t('server.no_firewall','No firewall rules detected'))}`;return;} + body.innerHTML=rules.map((r,index)=>{ + const a=r.access||{}; const simple=r.category==='access'; + const source=simple?(a.source||t('server.any','Any')):'—'; + const destination=simple?(a.destination||t('server.any','Any')):'—'; + const action=simple?(a.action||'—'):commandAction(r.command); + const details=simple?[a.protocol&&a.protocol!=='any'?String(a.protocol).toUpperCase():'',a.destination_port?`${t('server.port_word','port')} ${a.destination_port}`:''].filter(Boolean).join(' · ')||'—':r.command; + return ` + ${esc(firewallTypeText(r))} + ${esc(source)}${esc(destination)}${esc(action)} + ${esc(details)} + ${r.editable?`
`:`${esc(r.category==='advanced'?t('server.use_raw_editor','Use raw editor'):t('server.managed_automatically','Managed automatically'))}`} + `; + }).join(''); + } + + function openRouteEditor(item=null){ + const form=$('route-edit-form'); if(!form)return; + form.dataset.mode=item?'edit':'create'; form.dataset.originalCommand=item?.command||''; + $('route-edit-title').textContent=item?t('server.edit_route','Edit route'):t('server.add_route','Add route'); + $('route-network').value=item?.network||''; $('route-gateway').value=item?.via||''; $('route-device').value=item?.device||''; $('route-table').value=item?.table||'main'; + operationStatus('route-edit-status',''); modalShow('route-edit-modal',true); setTimeout(()=>$('route-network')?.focus(),30); + } + + function routePayload(){ + return {network:$('route-network').value.trim(),gateway:$('route-gateway').value.trim(),device:$('route-device').value.trim(),table:$('route-table').value.trim()||'main'}; + } + + async function saveRoute(event){ + event.preventDefault(); const form=$('route-edit-form'), button=$('route-edit-save'); if(!form||!button)return; + const editing=form.dataset.mode==='edit'; const payload=routePayload(); if(editing)payload.original_command=form.dataset.originalCommand; + if(!confirm(t('server.route_apply_confirm','Save this route and apply it now? WireGuard will be restarted briefly and a backup will be created.')))return; + button.disabled=true; operationStatus('route-edit-status',t('server.applying_rule','Creating backup and applying…'),'working'); + try{ + const r=await fetch(editing?'/api/server/routes/update':'/api/server/routes/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Operation failed'); + await fetchSnapshot(false); modalShow('route-edit-modal',false); toast(t('server.route_saved','Route saved and applied.')); + }catch(e){operationStatus('route-edit-status',e.message,'error');toast(e.message);}finally{button.disabled=false;} + } + + async function deleteRoute(item){ + if(!item?.editable)return; if(!confirm(t('server.delete_route_confirm','Delete this custom route and apply the change?')))return; + try{const r=await fetch('/api/server/routes/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({original_command:item.command})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');toast(t('server.route_deleted','Route deleted.'));await fetchSnapshot(false);}catch(e){toast(e.message);} + } + + function openAccessRuleEditor(item=null){ + const form=$('access-rule-form'); if(!form)return; const a=item?.access||{}; + form.dataset.mode=item?'edit':'create'; form.dataset.originalCommand=item?.command||''; + $('access-rule-title').textContent=item?t('server.edit_access_rule','Edit access rule'):t('server.add_access_rule','Add access rule'); + $('access-source').value=a.source||''; $('access-destination').value=a.destination||''; $('access-action').value=a.action||'REJECT'; $('access-protocol').value=a.protocol||'any'; $('access-dport').value=a.destination_port||''; + operationStatus('access-rule-status',''); modalShow('access-rule-modal',true); setTimeout(()=>$('access-source')?.focus(),30); + } + + function accessPayload(){ + return {source:$('access-source').value.trim(),destination:$('access-destination').value.trim(),action:$('access-action').value,protocol:$('access-protocol').value,destination_port:$('access-dport').value.trim()}; + } + + async function saveAccessRule(event){ + event.preventDefault(); const form=$('access-rule-form'), button=$('access-rule-save'); if(!form||!button)return; + const editing=form.dataset.mode==='edit'; const payload=accessPayload(); if(editing)payload.original_command=form.dataset.originalCommand; + if(!confirm(t('server.access_apply_confirm','Save this firewall rule and apply it now? WireGuard will be restarted briefly and a backup will be created.')))return; + button.disabled=true; operationStatus('access-rule-status',t('server.applying_rule','Creating backup and applying…'),'working'); + try{ + const r=await fetch(editing?'/api/server/access-rules/update':'/api/server/access-rules/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Operation failed'); + await fetchSnapshot(false); modalShow('access-rule-modal',false); toast(t('server.access_rule_saved','Access rule saved and applied.')); + }catch(e){operationStatus('access-rule-status',e.message,'error');toast(e.message);}finally{button.disabled=false;} + } + + async function deleteAccessRule(item){ + if(!item?.editable)return; if(!confirm(t('server.delete_access_confirm','Delete this access rule and apply the change?')))return; + try{const r=await fetch('/api/server/access-rules/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({original_command:item.command})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');toast(t('server.access_rule_deleted','Access rule deleted.'));await fetchSnapshot(false);}catch(e){toast(e.message);} + } + + function bindServerRules(){ + $('add-route-button')?.addEventListener('click',()=>openRouteEditor()); $('route-edit-form')?.addEventListener('submit',saveRoute); + $('route-body')?.addEventListener('click',e=>{const b=e.target.closest('[data-route-action]');if(!b)return;const item=snapshot?.route_items?.[Number(b.dataset.routeIndex)];if(!item)return;if(b.dataset.routeAction==='edit')openRouteEditor(item);else if(b.dataset.routeAction==='delete')deleteRoute(item);}); + $('add-access-rule-button')?.addEventListener('click',()=>openAccessRuleEditor()); $('access-rule-form')?.addEventListener('submit',saveAccessRule); + $('firewall-body')?.addEventListener('click',e=>{const b=e.target.closest('[data-firewall-action]');if(!b)return;const item=snapshot?.firewall_items?.[Number(b.dataset.firewallIndex)];if(!item)return;if(b.dataset.firewallAction==='edit')openAccessRuleEditor(item);else if(b.dataset.firewallAction==='delete')deleteAccessRule(item);}); + } + + + function setPolicyFieldsEnabled(enabled){ + ['server-edit-policy-table','server-edit-gateway'].forEach(id=>{const el=$(id);if(el)el.disabled=!enabled;}); + const box=$('server-policy-fields'); if(box)box.classList.toggle('disabled-fields',!enabled); + } + + function openServerEditor(){ + if(!snapshot?.wireguard?.config_exists)return; + const i=snapshot.config?.interface||{}, x=snapshot.config?.detected||{}; + $('server-edit-interface').value=snapshot.interface||'wg0'; + const activeItem=activeInterfaceItem(); + $('server-edit-display-name').value=(activeItem?.display_name&&activeItem.display_name!==snapshot.interface)?activeItem.display_name:''; + $('server-edit-vpn-network').value=x.vpn_network||''; + $('server-edit-address').value=i.address||''; + const serverAddress=$('server-edit-address');if(serverAddress)delete serverAddress.dataset.touched; + $('server-edit-port').value=i.listen_port||snapshot.listen_port||51820; + $('server-edit-mtu').value=i.mtu||''; + $('server-edit-uplink').value=x.uplink_interface||snapshot.system?.default_uplink||''; + $('server-edit-local-network').value=x.local_network||snapshot.system?.local_network||''; + const policy=Boolean(x.policy_table); + $('server-edit-policy-enabled').checked=policy; + $('server-edit-policy-table').value=x.policy_table||'200'; + $('server-edit-gateway').value=x.gateway||snapshot.system?.default_gateway||''; + $('server-edit-ip-forwarding').checked=Boolean(snapshot.system?.ip_forwarding); + $('server-edit-forward-from').checked=x.forward_from_vpn !== false; + $('server-edit-forward-to').checked=x.forward_to_vpn !== false; + $('server-edit-nat').checked=Boolean(x.nat_enabled); + setPolicyFieldsEnabled(policy); + operationStatus('server-edit-status',''); + modalShow('server-edit-modal',true); + } + + function syncServerEditAddress(){ + const net=$('server-edit-vpn-network'),addr=$('server-edit-address'); + if(!net||!addr||addr.dataset.touched)return; + const first=firstHostFromCidr(net.value); + if(first)addr.value=first; + } + + function localizedServerError(message){ + const raw=String(message||''); + const map=[ + ['VPN network must be a valid IPv4 network such as 10.77.0.0/24','server.error_vpn_network_invalid','VPN-сеть должна быть корректной IPv4-сетью, например 10.0.0.0/24.'], + ['Only IPv4 VPN networks are supported in this version','server.error_vpn_ipv4_only','Поддерживаются только IPv4 VPN-сети.'], + ['VPN network must contain at least two usable addresses','server.error_vpn_network_too_small','VPN-сеть должна содержать как минимум два доступных адреса.'], + ['VPN network has no usable host addresses','server.error_vpn_network_no_hosts','В выбранной VPN-сети нет доступных адресов для сервера.'], + ['Server address must include a prefix, for example 10.77.0.1/24','server.error_server_address_prefix','VPN-адрес сервера должен содержать префикс, например 10.0.0.1/24.'], + ['Server address must belong to the selected VPN network and use the same prefix','server.error_server_address_network','VPN-адрес сервера должен принадлежать выбранному пулу VPN-адресов и использовать тот же префикс.'], + ['Server address cannot be the network or broadcast address','server.error_server_address_reserved','VPN-адрес сервера не может быть адресом сети или широковещательным адресом.'], + ['Listen port must be a number','server.error_listen_port_number','Порт WireGuard должен быть числом.'], + ['Listen port must be between 1 and 65535','server.error_listen_port_range','Порт WireGuard должен быть в диапазоне от 1 до 65535.'], + ['MTU must be a number','server.error_mtu_number','MTU должен быть числом.'] + ]; + for(const [needle,key,fallback] of map){if(raw.includes(needle))return t(key,fallback);} + return raw; + } + + async function applyServerSettings(event){ + event.preventDefault(); + const button=$('server-edit-save'); if(!button)return; + const policy=$('server-edit-policy-enabled').checked; + const payload={ + vpn_network:$('server-edit-vpn-network').value.trim(), + server_address:$('server-edit-address').value.trim(), + listen_port:Number($('server-edit-port').value), + mtu:Number($('server-edit-mtu').value||0), + uplink_interface:$('server-edit-uplink').value.trim(), + gateway:policy?$('server-edit-gateway').value.trim():'', + local_network:$('server-edit-local-network').value.trim(), + policy_table:policy?$('server-edit-policy-table').value.trim():'', + nat_enabled:$('server-edit-nat').checked, + ip_forwarding:$('server-edit-ip-forwarding').checked, + forward_from_vpn:$('server-edit-forward-from').checked, + forward_to_vpn:$('server-edit-forward-to').checked, + }; + if(!confirm(t('server.apply_confirm','Save these server settings and apply them now? WireGuard will be restarted briefly. A backup is created first and WGTools will roll back automatically if the new configuration does not start.')))return; + button.disabled=true; + operationStatus('server-edit-status',t('server.applying_settings','Validating settings, creating backup and applying…'),'working'); + try{ + const r=await fetch('/api/server/settings/apply',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||t('server.settings_apply_failed','Server settings could not be applied')); + const iface=snapshot?.interface||document.body.dataset.interface||'wg0'; + const displayName=$('server-edit-display-name').value.trim(); + const nr=await fetch('/api/interfaces/name',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({interface:iface,display_name:displayName})}); + const nd=await nr.json(); if(!nr.ok)throw new Error(nd.error||t('interfaces.rename_failed','Interface display name could not be saved')); + operationStatus('server-edit-status',t('server.settings_applied','Server settings saved and applied successfully.'),'success'); + toast(t('server.settings_applied','Server settings saved and applied successfully.')); + await fetchInterfaces(true); + await fetchSnapshot(false); + setTimeout(()=>modalShow('server-edit-modal',false),450); + }catch(e){const message=localizedServerError(e.message);operationStatus('server-edit-status',message,'error');toast(message);}finally{button.disabled=false;} + } + + function bindServerEditor(){ + if(page==='server' && $('extended-group-form')){ + const loadGroups=async()=>{ + try{const r=await fetch(appUrl('/api/extended/ip-groups'));const d=await r.json();if(!r.ok)throw new Error(d.error); + $('extended-groups-list').innerHTML=Object.entries(d.groups||{}).map(([name,g])=>`
${esc(name)}

${esc((g.addresses||[]).join(', '))}

Sieci: ${esc((g.interfaces||[]).join(', '))}

`).join('')||'

Brak grup adresów.

'; + $('extended-groups-list').insertAdjacentHTML('beforeend',`

Przegląd przekierowań

`+(d.forwards||[]).map(f=>`

${esc(f.interface)}: ${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}

`).join('')); + return d.groups||{}; + }catch(err){operationStatus('extended-group-status',err.message,'error');return {};} + }; + const save=async p=>{const r=await fetch(appUrl('/api/extended/ip-groups'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(p)});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadGroups();}; + $('extended-group-form').addEventListener('submit',async e=>{e.preventDefault();try{await save({name:$('extended-group-name').value.trim(),addresses:$('extended-group-addresses').value.split(',').map(x=>x.trim()).filter(Boolean),interfaces:$('extended-group-interfaces').value.split(',').map(x=>x.trim()).filter(Boolean)});operationStatus('extended-group-status','Zapisano grupę.','success');}catch(err){operationStatus('extended-group-status',err.message,'error');}}); + $('extended-groups-list').addEventListener('click',async e=>{const edit=e.target.closest('[data-ext-group-edit]'), del=e.target.closest('[data-ext-group-delete]');try{if(edit){const groups=await loadGroups(),name=edit.dataset.extGroupEdit,g=groups[name];if(g){$('extended-group-name').value=name;$('extended-group-addresses').value=g.addresses.join(', ');$('extended-group-interfaces').value=g.interfaces.join(', ');}}else if(del && confirm('Usunąć grupę adresów?')){await save({name:del.dataset.extGroupDelete,delete:true});}}catch(err){operationStatus('extended-group-status',err.message,'error');}}); + loadGroups(); + } + if(page==='clients' && $('extended-forward-form')){ + const loadForwards=async()=>{const r=await fetch(appUrl('/api/extended/forwardings'));const d=await r.json();if(!r.ok)throw new Error(d.error);$('extended-forward-public').innerHTML=(d.addresses||[]).map(ip=>``).join('');$('extended-forward-list').innerHTML=(d.forwards||[]).map(f=>`
${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}
`).join('')||'

Brak przekierowań.

';}; + $('extended-forward-form').addEventListener('submit',async e=>{e.preventDefault();try{const r=await fetch(appUrl('/api/extended/forwardings'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_ip:$('extended-forward-public').value,public_port:Number($('extended-forward-public-port').value),target_ip:$('extended-forward-target').value.trim(),target_port:Number($('extended-forward-target-port').value),protocol:$('extended-forward-protocol').value})});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadForwards();operationStatus('extended-forward-status','Dodano przekierowanie.','success');}catch(err){operationStatus('extended-forward-status',err.message,'error');}}); + $('extended-forward-list').addEventListener('click',async e=>{const b=e.target.closest('[data-ext-forward-delete]');if(!b||!confirm('Usunąć przekierowanie?'))return;try{const r=await fetch(appUrl('/api/extended/forwardings/delete'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:b.dataset.extForwardDelete})});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadForwards();}catch(err){operationStatus('extended-forward-status',err.message,'error');}}); + loadForwards().catch(err=>operationStatus('extended-forward-status',err.message,'error')); + } + if(page==='server' && $('extended-listen-form')){ + fetch(appUrl('/api/server/extended-listen')).then(async r=>{const d=await r.json();if(!r.ok)throw new Error(d.error);$('extended-listen-address').value=d.address||'';$('extended-listen-interface').value=d.interface||'';}).catch(e=>operationStatus('extended-listen-status',e.message,'error')); + $('extended-listen-form').addEventListener('submit',async e=>{ + e.preventDefault(); const button=e.currentTarget.querySelector('button'); button.disabled=true; + try{const r=await fetch(appUrl('/api/server/extended-listen'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({address:$('extended-listen-address').value.trim(),interface:$('extended-listen-interface').value.trim()})});const d=await r.json();if(!r.ok)throw new Error(d.error);operationStatus('extended-listen-status','Zapisano ograniczenie nasłuchiwania.','success');await fetchSnapshot(false);}catch(err){operationStatus('extended-listen-status',err.message,'error');}finally{button.disabled=false;} + }); + } + if(page==='server' && $('extended-snat-form')){ + fetch(appUrl('/api/server/extended-snat')).then(async r=>{const d=await r.json();if(!r.ok)throw new Error(d.error);$('extended-snat-address').value=d.address||'';$('extended-snat-uplink').value=d.uplink||'';}).catch(e=>operationStatus('extended-snat-status',e.message,'error')); + $('extended-snat-form').addEventListener('submit',async e=>{ + e.preventDefault(); + const button=e.currentTarget.querySelector('button'); button.disabled=true; + try{const r=await fetch(appUrl('/api/server/extended-snat'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({address:$('extended-snat-address').value.trim(),uplink:$('extended-snat-uplink').value.trim()})});const d=await r.json();if(!r.ok)throw new Error(d.error);operationStatus('extended-snat-status','Zapisano ustawienia SNAT.','success');await fetchSnapshot(false);}catch(err){operationStatus('extended-snat-status',err.message,'error');}finally{button.disabled=false;} + }); + } + $('edit-server-button')?.addEventListener('click',openServerEditor); + $('server-edit-form')?.addEventListener('submit',applyServerSettings); + $('server-edit-policy-enabled')?.addEventListener('change',e=>setPolicyFieldsEnabled(e.currentTarget.checked)); + $('server-edit-vpn-network')?.addEventListener('input',syncServerEditAddress); + $('server-edit-address')?.addEventListener('input',e=>e.currentTarget.dataset.touched='1'); + } + + function renderDiagnostics(checks){ const el=$('diagnostics-list'); if(!el)return; el.innerHTML=checks.map(c=>`
${c.ok?'✓':'✕'}${esc(c.label)}${esc(c.detail||'')}
`).join(''); } + + function clientGroups(){ return snapshot?.client_groups||[]; } + function groupById(id){ return clientGroups().find(g=>String(g.id||'')===String(id||''))||null; } + function accessWord(value){ return value==='block'?t('groups.blocked','Blocked'):t('groups.allowed','Allowed'); } + function renderGroupSelect(select,selected='',includeNone=true){ + if(!select)return; + const options=[]; + if(includeNone)options.push(``); + for(const g of clientGroups())options.push(``); + select.innerHTML=options.join(''); select.value=selected||''; + } + function clientQuickSearchValue(){ return String($('client-quick-search')?.value||'').trim().toLocaleLowerCase(); } + function clientMatchesQuickSearch(peer){ + const query=clientQuickSearchValue(); + if(!query)return true; + const statusBits=[]; + if(peer?.schedule_disabled)statusBits.push(t('clients.status_schedule_blocked','Blocked by schedule'),t('clients.schedule_blocked_short','Schedule · blocked')); + else if(peer?.expired_disabled)statusBits.push(t('clients.status_expired_disabled','Expired · disabled'),t('clients.expired_disabled_short','Expired · disabled')); + else statusBits.push(online(peer)?t('common.online','Online'):t('common.offline','Offline')); + const haystack=[ + peer?.name, peer?.group_name, peer?.vpn_address, (peer?.remote_networks||[]).join(' '), + peer?.persistent_keepalive, peer?.endpoint, peer?.client_endpoint, relayItems().find(item=>item.id===peer?.relay_vps_id)?.name, typeOf(peer), ...statusBits, + peer?.preshared_key_enabled?t('clients.psk_short','PSK'):'', + peer?.access_schedule_enabled?t('clients.schedule_short','Schedule'):'', + ].map(value=>String(value||'').toLocaleLowerCase()).join(' '); + return haystack.includes(query); + } + function syncClientQuickSearchClear(){ + const clear=$('client-quick-search-clear'); + if(clear)clear.hidden=!String($('client-quick-search')?.value||'').length; + } + function renderClients(d){ + const peers=d.peers||[]; const body=$('client-body'); const add=$('add-client-button'); const manage=$('manage-groups-button'); + if(add)add.disabled=!d.wireguard?.config_exists; if(manage)manage.disabled=!d.wireguard?.config_exists; syncClientQuickSearchClear(); + if(!peers.length){body.innerHTML=`${esc(t('clients.no_peers','No peers found'))}`;return;} + const visible=peers.map((p,index)=>({p,index})).filter(item=>clientMatchesQuickSearch(item.p)); + if(!visible.length){body.innerHTML=`${esc(t('clients.quick_search_empty','No clients match the search'))}`;return;} + const rowsHtml=visible.map(({p,index})=>{ + const grouped=Boolean(p.group_id&&p.group_name); const groupCell=grouped?`${esc(p.group_name)}${p.group_config_differs?`⚠`:''}`:'—'; + const metaBits=[]; if(p.preshared_key_enabled)metaBits.push(t('clients.psk_short','PSK')); if(p.connection_mode==='relay'){const relay=relayItems().find(item=>item.id===p.relay_vps_id);metaBits.push(`${t('clients.relay_short','Relay')}: ${relay?.name||t('clients.relay_unknown','unavailable')}`);} if(p.expired_disabled)metaBits.push(t('clients.expired_disabled_short','Expired · disabled')); else if(Number(p.expires_at||0)>0)metaBits.push(expiryShort(Number(p.expires_at))); if(p.access_schedule_enabled)metaBits.push(p.schedule_disabled?t('clients.schedule_blocked_short','Schedule · blocked'):t('clients.schedule_short','Schedule')); + const metaSuffix=metaBits.length?` · ${metaBits.map(esc).join(' · ')}`:''; + return ` +
${esc(p.name||'Unnamed')}
${esc(typeOf(p))} · ${p.managed?esc(t('clients.managed','WGTools managed')):esc(t('clients.existing','Existing peer'))}${metaSuffix}
+ ${(p.remote_networks||[]).length?'—':groupCell} + ${esc(p.vpn_address||'—')} + ${(p.remote_networks||[]).length?(p.remote_networks||[]).map(n=>`${esc(n)}`).join(''):'—'} + ${esc(p.persistent_keepalive||'—')}${statusHtml(p)}${esc(ago(p.latest_handshake))}${fmtBytes(p.rx_bytes)} / ${fmtBytes(p.tx_bytes)} +
${p.managed?``:''}${document.body.dataset.role==='admin'?``:''}
+ `}).join(''); + renderPeerTable(body,rowsHtml,5); + } + + function splitList(value){ return String(value||'').split(/[\n,]+/).map(x=>x.trim()).filter(Boolean); } + function sameList(a,b){ const x=[...(a||[])].sort(), y=[...(b||[])].sort(); return x.length===y.length && x.every((v,i)=>v===y[i]); } + function modalShow(id,show=true){ const el=$(id); if(el)el.hidden=!show; if(id==='audit-modal'&&!show)stopAuditAutoRefresh(); document.body.style.overflow=show?'hidden':''; } + const CLIENT_EDITOR_TABS=['basic','policy','config','security']; + function activateClientTab(name,focusId=''){ + let target=CLIENT_EDITOR_TABS.includes(name)?name:'basic'; + const wanted=$(`client-tab-button-${target}`); if(!wanted||wanted.hidden||wanted.disabled)target='basic'; + document.querySelectorAll('[data-client-tab]').forEach(button=>{const active=button.dataset.clientTab===target;button.classList.toggle('active',active);button.setAttribute('aria-selected',active?'true':'false');button.tabIndex=active?0:-1;}); + document.querySelectorAll('[data-client-tab-panel]').forEach(panel=>{panel.hidden=panel.dataset.clientTabPanel!==target;}); + const body=document.querySelector('.client-editor-body'); if(body)body.scrollTop=0; + if(focusId)setTimeout(()=>$(`${focusId}`)?.focus(),20); + } + function syncClientTabAvailability(){ + const form=$('client-editor-form'); const managed=form?.dataset.managed==='true'; const site=$('client-type')?.value==='site_to_site'; const grouped=Boolean($('client-group')?.value)&&managed&&!site; + const visibility={basic:true,policy:grouped,config:managed,security:managed}; + for(const name of CLIENT_EDITOR_TABS){const button=$(`client-tab-button-${name}`);if(button)button.hidden=!visibility[name];} + const active=document.querySelector('[data-client-tab].active')?.dataset.clientTab||'basic'; if(!visibility[active])activateClientTab('basic'); + } + const ENDPOINT_HISTORY_KEY='wgtools.endpointHistory'; + function serverListenPort(){ return Number(snapshot?.listen_port||snapshot?.config?.interface?.listen_port||51820); } + function relayItems(){ return (snapshot?.vps_relays||[]).filter(item=>item&&item.status==='installed'); } + function relayEndpoint(item){ + if(!item)return {host:'',port:0,text:''}; + const host=String(item.endpoint_domain||item.host||'').trim(); const port=Number(item.relay_port||0); + return {host,port,text:host&&port?`${host}:${port}`:''}; + } + function renderClientRelaySelect(selected=''){ + const select=$('client-relay-vps'); if(!select)return; const items=relayItems(); + select.innerHTML=items.map(item=>``).join(''); + if(selected&&items.some(item=>item.id===selected))select.value=selected; else if(items.length)select.value=items[0].id; + } + function selectedClientRelay(){ const id=$('client-relay-vps')?.value||''; return relayItems().find(item=>item.id===id)||null; } + function syncClientConnectionFields(){ + const form=$('client-editor-form'); const managed=form?.dataset.managed==='true'; const items=relayItems(); const hasRelay=managed&&items.length>0; + setHidden('client-relay-connection-section',!hasRelay); + const mode=hasRelay?($('client-connection-mode')?.value||'direct'):'direct'; + if($('client-connection-mode')&&!hasRelay)$('client-connection-mode').value='direct'; + const relayMode=hasRelay&&mode==='relay'; setHidden('client-relay-vps-field',!relayMode); setHidden('client-relay-endpoint-note',!relayMode); + const host=$('client-server-host'),port=$('client-server-port'); + if(!managed)return; + if(relayMode){ + if(form&&form.dataset.connectionPrevious!=='relay'){form.dataset.directHost=host?.value||'';form.dataset.directPort=String(port?.value||serverListenPort());} + const relay=selectedClientRelay(); const endpoint=relayEndpoint(relay); + if(host){host.value=endpoint.host;host.readOnly=true;host.required=false;} if(port){port.value=String(endpoint.port||serverListenPort());port.readOnly=true;} + const note=$('client-relay-endpoint-note'); if(note)note.textContent=t('clients.relay_endpoint_note','The generated client config will connect to {endpoint}. The WireGuard server itself remains on this WGTools host.').replace('{endpoint}',endpoint.text||'—'); + }else{ + if(host){host.readOnly=false;host.required=true;if(form?.dataset.connectionPrevious==='relay')host.value=form.dataset.directHost||'';} + if(port){port.value=String(form?.dataset.directPort||serverListenPort());port.readOnly=true;} + } + if(form)form.dataset.connectionPrevious=relayMode?'relay':'direct'; + } + function loadEndpointHistory(){ + try{ const value=JSON.parse(localStorage.getItem(ENDPOINT_HISTORY_KEY)||'[]'); return Array.isArray(value)?value.filter(x=>typeof x==='string'&&x.trim()).slice(0,12):[]; } + catch{return [];} + } + function saveEndpointHistory(host){ + const value=String(host||'').trim(); if(!value)return; + const next=[value,...loadEndpointHistory().filter(x=>x!==value)].slice(0,12); + try{localStorage.setItem(ENDPOINT_HISTORY_KEY,JSON.stringify(next));}catch{} + renderEndpointHistory(); + } + function renderEndpointHistory(){ const list=$('client-endpoint-history'); if(list)list.innerHTML=loadEndpointHistory().map(host=>``).join(''); } + function splitEndpoint(endpoint){ + const value=String(endpoint||'').trim(); const fallbackPort=serverListenPort(); + if(!value)return {host:'',port:fallbackPort}; + const bracket=value.match(/^\[([^\]]+)\](?::(\d+))?$/); if(bracket)return {host:`[${bracket[1]}]`,port:Number(bracket[2]||fallbackPort)}; + const m=value.match(/^(.*):(\d+)$/); if(m&&m[1])return {host:m[1],port:Number(m[2])}; + return {host:value,port:fallbackPort}; + } + function joinEndpoint(host,port){ const h=String(host||'').trim(); return h?`${h}:${Number(port||serverListenPort())}`:''; } + function siteToSiteNetworks(){ + const out=[]; const seen=new Set(); + for(const peer of (snapshot?.peers||[]))for(const raw of (peer?.remote_networks||[])){const value=String(raw||'').trim();if(!value||seen.has(value))continue;seen.add(value);out.push(value);} + return out; + } + function localProtectedNetworks(){ const lan=snapshot?.config?.detected?.local_network||snapshot?.system?.local_network; return [lan,...siteToSiteNetworks()].filter(Boolean); } + function presetRoutes(preset){ + const vpn=snapshot?.config?.detected?.vpn_network; const lan=snapshot?.config?.detected?.local_network||snapshot?.system?.local_network; const site=siteToSiteNetworks(); + if(preset==='full'||preset==='full_except_local')return ['0.0.0.0/0']; + if(preset==='vpn')return vpn?[vpn]:[]; + if(preset==='vpn_lan')return [vpn,lan,...site].filter(Boolean); + return []; + } + function routePresetFor(routes, protectLocal=false){ + const vpn=snapshot?.config?.detected?.vpn_network; const lan=snapshot?.config?.detected?.local_network||snapshot?.system?.local_network; const list=routes||[]; const site=siteToSiteNetworks(); + if(protectLocal&&list.includes('0.0.0.0/0'))return 'full_except_local'; + if(sameList(list,['0.0.0.0/0']))return 'full'; + if(vpn&&sameList(list,[vpn]))return 'vpn'; + if(vpn&&sameList(list,[vpn,lan,...site].filter(Boolean)))return 'vpn_lan'; + return 'custom'; + } + function syncRoutePresetFields(){ + const preset=$('client-route-preset')?.value; const grouped=Boolean($('client-group')?.value); const protectLocal=preset==='full_except_local'&&!grouped; + setHidden('client-local-access-exceptions-field',!protectLocal); setHidden('client-protected-networks-reference',!protectLocal); + if(!protectLocal&&$('client-local-access-exceptions'))$('client-local-access-exceptions').value=''; + const list=$('client-protected-networks-list'); if(list)list.textContent=protectLocal?localProtectedNetworks().join('\n'):''; + } + function applyRoutePreset(clearCustom=false){ + const preset=$('client-route-preset')?.value; const field=$('client-allowed-ips'); if(!field)return; syncRoutePresetFields(); + if(preset==='custom'){if(clearCustom)field.value='';return;} field.value=presetRoutes(preset).join('\n'); + } + function setClientEditorManaged(managed){ + setHidden('client-basic-managed-fields',!managed); setHidden('client-config-fields',!managed); setHidden('client-managed-options-section',!managed); setHidden('unmanaged-client-note',managed); + const host=$('client-server-host'),allowed=$('client-allowed-ips'); if(host){host.required=managed;host.disabled=!managed;} if(allowed){allowed.required=managed;allowed.disabled=!managed;} + syncClientTabAvailability(); syncClientConnectionFields(); + } + function syncClientTypeFields(){ + const siteToSite=$('client-type')?.value==='site_to_site'; setHidden('client-remote-networks-field',!siteToSite); + const remote=$('client-remote-networks');if(remote)remote.required=siteToSite; + setHidden('client-group-field',siteToSite||$('client-editor-form')?.dataset.managed!=='true'); + if(siteToSite&&$('client-group'))$('client-group').value=''; + syncClientGroupFields(); syncClientExpiryFields(); syncClientScheduleFields(); + } + function uniqueDuplicateName(base){ + const suffix=t('clients.duplicate_suffix','copy'); const stem=String(base||'Peer').trim()||'Peer'; + const used=new Set((snapshot?.peers||[]).map(p=>String(p.name||'').trim().toLocaleLowerCase())); let candidate=`${stem} ${suffix}`; let n=2; while(used.has(candidate.toLocaleLowerCase()))candidate=`${stem} ${suffix} ${n++}`; return candidate; + } + function policySelectOptions(select,mode,current,groupValue){ + if(!select)return; const items=[]; + if(mode==='inherit')items.push({v:'inherit',label:`${t('groups.inherit','Inherit')} (${accessWord(groupValue)})`}); + items.push({v:'allow',label:t('groups.allow','Allow')},{v:'block',label:t('groups.block','Block')}); + select.innerHTML=items.map(x=>``).join(''); + select.value=items.some(x=>x.v===current)?current:(mode==='inherit'?'inherit':'allow'); + } + function effectiveClientPolicy(){ + const group=groupById($('client-group')?.value); if(!group)return null; const gp=group.policy||{}; const mode=$('client-policy-mode')?.value||'inherit'; + const internetValue=$('client-internet-access')?.value||'inherit'; const localValue=$('client-local-access')?.value||'inherit'; + const internet=mode==='inherit'&&internetValue==='inherit'?(gp.internet_access||'allow'):internetValue; + const local=mode==='inherit'&&localValue==='inherit'?(gp.local_access||'allow'):localValue; + const groupAllow=mode==='inherit'?(gp.allow||[]):[]; const groupDeny=mode==='inherit'?(gp.deny||[]):[]; + return {internet,local,allow:[...groupAllow,...splitList($('client-policy-allow')?.value)],deny:[...groupDeny,...splitList($('client-policy-deny')?.value)]}; + } + function renderClientPolicyPreview(){ + const el=$('client-policy-preview'); const policy=effectiveClientPolicy(); if(!el)return; if(!policy){el.innerHTML='';return;} + const allow=policy.allow.length?policy.allow.join(', '):t('groups.none','None'); const deny=policy.deny.length?policy.deny.join(', '):t('groups.none','None'); + el.innerHTML=`
${esc(t('groups.internet_access','Internet access'))}${esc(accessWord(policy.internet))}
${esc(t('groups.local_access','Local networks'))}${esc(accessWord(policy.local))}
${esc(t('groups.effective_allow','Allowed exceptions'))}${esc(allow)}
${esc(t('groups.effective_deny','Blocked exceptions'))}${esc(deny)}
`; + } + function syncClientGroupPolicyMode(){ + const group=groupById($('client-group')?.value); const mode=$('client-policy-mode')?.value||'inherit'; if(!group)return; + const internet=$('client-internet-access')?.value||'inherit', local=$('client-local-access')?.value||'inherit'; + policySelectOptions($('client-internet-access'),mode,internet,group.policy?.internet_access||'allow'); policySelectOptions($('client-local-access'),mode,local,group.policy?.local_access||'allow'); + const allowLabel=$('client-policy-allow-label'),denyLabel=$('client-policy-deny-label'); + if(allowLabel)allowLabel.textContent=mode==='inherit'?t('groups.additional_allowed','Additional allowed addresses'):t('groups.allowed_addresses','Allowed addresses / networks'); + if(denyLabel)denyLabel.textContent=mode==='inherit'?t('groups.additional_blocked','Additional blocked addresses'):t('groups.blocked_addresses','Blocked addresses / networks'); + renderClientPolicyPreview(); + } + function clientFormDiffersFromGroup(){ + const form=$('client-editor-form'),group=groupById($('client-group')?.value); if(form?.dataset.mode!=='edit'||!group||$('client-config-override')?.checked)return false; + const d=group.resolved_defaults||group.defaults||{}; + return ($('client-route-preset')?.value||'')!==(d.route_preset||'full') + || !sameList(splitList($('client-allowed-ips')?.value),(d.client_allowed_ips||presetRoutes(d.route_preset||'full'))) + || !sameList(splitList($('client-dns')?.value),(d.dns||[])) + || Number($('client-keepalive')?.value||0)!==Number(d.persistent_keepalive??25); + } + function setClientConfigFieldsDisabled(disabled){ + for(const id of ['client-route-preset','client-dns','client-allowed-ips','client-keepalive']){const el=$(id);if(el)el.disabled=Boolean(disabled);} + } + function syncClientGroupConfigMode(){ + const form=$('client-editor-form'); const group=groupById($('client-group')?.value); const grouped=Boolean(group)&&form?.dataset.managed==='true'&&$('client-type')?.value!=='site_to_site'; + setHidden('client-group-defaults-wrap',!grouped); + if(!grouped){setClientConfigFieldsDisabled(false);setHidden('client-group-config-warning',true);setHidden('apply-group-defaults-button',true);return;} + const custom=Boolean($('client-config-override')?.checked); setClientConfigFieldsDisabled(!custom); + const differs=!custom&&clientFormDiffersFromGroup(); setHidden('client-group-config-warning',!differs); setHidden('apply-group-defaults-button',!differs); + } + function syncClientGroupConfigWarning(){syncClientGroupConfigMode();} + function syncClientGroupFields(){ + const form=$('client-editor-form'); const managed=form?.dataset.managed==='true'; const site=$('client-type')?.value==='site_to_site'; const group=managed&&!site?groupById($('client-group')?.value):null; + setHidden('client-group-policy-section',!group); syncClientTabAvailability(); + if(!group){syncRoutePresetFields();syncClientGroupConfigMode();return;} + syncClientGroupPolicyMode(); syncRoutePresetFields(); syncClientGroupConfigMode(); + } + function applySelectedGroupDefaults(showToast=true){ + const group=groupById($('client-group')?.value); if(!group)return; const d=group.resolved_defaults||group.defaults||{}; + $('client-keepalive').value=d.persistent_keepalive??25; $('client-dns').value=(d.dns||[]).join(', '); $('client-route-preset').value=d.route_preset||'full'; $('client-allowed-ips').value=(d.client_allowed_ips||presetRoutes(d.route_preset||'full')).join('\n'); syncRoutePresetFields(); + syncClientGroupConfigMode(); + if(showToast)toast(t('groups.defaults_applied','Group client defaults applied. Save the client to use the updated template.')); + } + function toLocalDateTimeValue(timestamp){ + if(!timestamp)return ''; const d=new Date(Number(timestamp)*1000); if(Number.isNaN(d.getTime()))return ''; const local=new Date(d.getTime()-d.getTimezoneOffset()*60000); return local.toISOString().slice(0,16); + } + function syncClientExpiryFields(){ + const preset=$('client-expiry-preset')?.value||'never'; + const siteToSite=$('client-type')?.value==='site_to_site'; + setHidden('client-expiry-custom-field',preset!=='custom'); + setHidden('client-expiry-action-field',preset==='never'||siteToSite); + if(preset==='custom')ensureExpiryDateTimeValue(); + if(siteToSite&&$('client-expiry-delete'))$('client-expiry-delete').checked=true; + } + function expiryFromForm(){ + const preset=$('client-expiry-preset')?.value||'never'; const now=Math.floor(Date.now()/1000); const seconds={"1h":3600,"3h":10800,"6h":21600,"1d":86400}[preset]; + if(seconds)return now+seconds; if(preset!=='custom')return 0; const raw=$('client-expiry-custom')?.value||''; const ms=Date.parse(raw); return Number.isFinite(ms)?Math.floor(ms/1000):0; + } + function ensureExpiryDateTimeValue(){ + const field=$('client-expiry-custom'); if(!field||field.value)return; field.value=toLocalDateTimeValue(Math.floor(Date.now()/1000)); + } + function selectedScheduleDays(){return [...document.querySelectorAll('[data-schedule-day]')].filter(el=>el.checked).map(el=>Number(el.dataset.scheduleDay)).filter(n=>Number.isInteger(n)&&n>=0&&n<=6);} + function setScheduleDays(days){const chosen=new Set((days||[]).map(Number));document.querySelectorAll('[data-schedule-day]').forEach(el=>{el.checked=chosen.has(Number(el.dataset.scheduleDay));});} + function syncClientScheduleFields(){ + const siteToSite=$('client-type')?.value==='site_to_site'; const enabled=Boolean($('client-schedule-enabled')?.checked)&&!siteToSite; + setHidden('client-schedule-title',siteToSite); setHidden('client-schedule-section',siteToSite); setHidden('client-schedule-editor',!enabled); setHidden('client-peer-isolation-field',siteToSite); + if(siteToSite&&$('client-schedule-enabled'))$('client-schedule-enabled').checked=false; if(siteToSite&&$('client-peer-isolation'))$('client-peer-isolation').checked=false; + } + function expiryShort(timestamp){ + const seconds=Math.max(0,Number(timestamp||0)-Math.floor(Date.now()/1000)); if(seconds<=0)return t('clients.expired','Expired'); + if(seconds<3600)return t('clients.expires_minutes','Expires in {n}m').replace('{n}',String(Math.max(1,Math.ceil(seconds/60)))); + if(seconds<86400)return t('clients.expires_hours','Expires in {n}h').replace('{n}',String(Math.max(1,Math.ceil(seconds/3600)))); + return t('clients.expires_days','Expires in {n}d').replace('{n}',String(Math.max(1,Math.ceil(seconds/86400)))); + } + function syncClientPskFields(){ + const form=$('client-editor-form'); const editing=form?.dataset.mode==='edit'; const managed=form?.dataset.managed==='true'; + setHidden('client-rotate-credentials-wrap',!(editing&&managed)); + } + async function rotateClientCredentials(){ + const form=$('client-editor-form'),button=$('rotate-credentials-button'); const publicKey=form?.dataset.publicKey||''; if(!publicKey||!button)return; + const pskEnabled=form?.dataset.hadPsk==='true'; + const fallback=pskEnabled?'Generate a new client key pair and a new PSK now? An active session for this client will be disconnected immediately. Send a new config or QR afterward.':'Generate a new client key pair now? An active session for this client will be disconnected immediately. Send a new config or QR afterward.'; + if(!confirm(t(pskEnabled?'clients.credentials_rotate_confirm_psk':'clients.credentials_rotate_confirm',fallback)))return; + button.disabled=true; operationStatus('client-editor-status',t('clients.credentials_rotating','Generating new client keys and disconnecting the old client session…'),'working'); + try{ + const r=await fetch('/api/clients/credentials/rotate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:publicKey}),keepalive:true}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||'Client key rotation failed'); + if(d.public_key)form.dataset.publicKey=d.public_key; form.dataset.hadPsk=String(Boolean(d.psk_enabled)); + syncClientPskFields(); + operationStatus('client-editor-status',t('clients.credentials_rotated','Client keys changed. If the client was connected, its old session was disconnected. The old config no longer works; send a new config or QR before reconnecting.'),'success'); + toast(t('clients.credentials_rotated_short','Client keys changed — new config required')); + // Key rotation intentionally removes the old runtime peer. If this panel + // is being reached through that very client, the next status refresh can + // lose its network path even though the rotation itself succeeded. A + // refresh failure must therefore never overwrite the successful result. + fetchSnapshot().then(()=>syncClientPskFields()).catch(()=>{}); + }catch(e){ + const message=String(e?.message||e||''); + const networkLost=/networkerror|failed to fetch|network request failed|load failed/i.test(message); + operationStatus( + 'client-editor-status', + networkLost + ? t('clients.credentials_connection_lost','The connection to WGTools was interrupted. If this panel was opened through the client whose keys were just rotated, this is expected: its old WireGuard session is disconnected immediately. Reconnect to WGTools by another path and issue the new config/QR.') + : message, + networkLost?'working':'error' + ); + }finally{button.disabled=false;} + } + function usePanelHostForClient(){ + const field=$('client-server-host');if(!field)return; + let host=String(location.hostname||'').trim(); + if(host.startsWith('[')&&host.endsWith(']'))host=host.slice(1,-1); + if(!host){toast(t('clients.use_panel_host_failed','Could not determine the panel address from the browser URL.'));return;} + field.value=host;field.dispatchEvent(new Event('input',{bubbles:true}));field.focus(); + toast(t('clients.use_panel_host_done','Panel address inserted: {host}').replace('{host}',host)); + } + + function openClientEditor(peer=null,options={}){ + const duplicate=Boolean(options.duplicate&&peer); const editing=Boolean(peer)&&!duplicate; const source=peer; const form=$('client-editor-form'); if(!form)return; + form.dataset.mode=editing?'edit':'create'; form.dataset.duplicate=String(duplicate); form.dataset.publicKey=editing?(source?.public_key||''):''; form.dataset.managed=editing?String(Boolean(source?.managed)):'true'; form.dataset.hadPsk=String(Boolean(editing&&source?.preshared_key_enabled)); + $('client-editor-title').textContent=editing?t('clients.edit_title','Edit client'):t('clients.create_title','Create client'); $('client-editor-subtitle').textContent=editing?t('clients.edit_subtitle','Update the server-side peer. Changes are applied without restarting WireGuard.'):t('clients.create_subtitle','Create a WireGuard peer and generate its client configuration.'); + $('client-name').value=duplicate?uniqueDuplicateName(source?.name):source?.name||''; $('client-type').value=(source?.remote_networks||[]).length?'site_to_site':'client'; + $('client-vpn-address').value=duplicate?(snapshot?.next_free_address||''):(source?.vpn_address||snapshot?.next_free_address||''); $('client-keepalive').value=source?.persistent_keepalive??25; $('client-remote-networks').value=duplicate&&$('client-type').value==='site_to_site'?'':(source?.remote_networks||[]).join('\n'); + const managed=duplicate||!editing||Boolean(source?.managed); setClientEditorManaged(managed); form.dataset.managed=String(managed); renderGroupSelect($('client-group'),source?.group_id||'',true); + if($('client-type').value==='site_to_site'||!managed)$('client-group').value=''; + $('client-policy-mode').value=source?.policy_mode||'inherit'; $('client-policy-allow').value=(source?.policy_allow||[]).join(', '); $('client-policy-deny').value=(source?.policy_deny||[]).join(', '); + if(managed){ + const routes=source?.managed&&source?.client_allowed_ips?.length?source.client_allowed_ips:['0.0.0.0/0']; const endpoint=splitEndpoint(source?.managed?source?.client_endpoint:''); $('client-server-host').value=endpoint.host; $('client-server-port').value=serverListenPort(); $('client-dns').value=source?.managed?(source?.client_dns||[]).join(', '):''; $('client-allowed-ips').value=routes.join('\n'); $('client-local-access-exceptions').value=(source?.managed?source?.local_access_exceptions||[]:[]).join(', '); + const wantedRelay=(editing||duplicate)?(source?.relay_vps_id||''):''; renderClientRelaySelect(wantedRelay); const sourceRelayAvailable=Boolean(wantedRelay&&relayItems().some(item=>item.id===wantedRelay)); $('client-connection-mode').value=(editing||duplicate)&&source?.connection_mode==='relay'&&sourceRelayAvailable?'relay':'direct'; form.dataset.directHost=$('client-connection-mode').value==='relay'?'':endpoint.host; form.dataset.directPort=String(serverListenPort()); form.dataset.connectionPrevious=''; + $('client-route-preset').value=source?.client_route_preset||routePresetFor(routes,Boolean(source?.managed&&source?.protect_local_networks)); + $('client-use-psk').checked=(editing||duplicate)?Boolean(source?.preshared_key_enabled):true; $('client-expiry-preset').value=(editing&&Number(source?.expires_at||0)>0)?'custom':'never'; $('client-expiry-custom').value=(editing&&Number(source?.expires_at||0)>0)?toLocalDateTimeValue(source.expires_at):''; $('client-expiry-delete').checked=(source?.expiration_action||'delete')!=='disable'; setHidden('client-expired-disabled-note',!Boolean(editing&&source?.expired_disabled)); + $('client-peer-isolation').checked=Boolean((editing||duplicate)&&source?.peer_isolation); $('client-schedule-enabled').checked=Boolean((editing||duplicate)&&source?.access_schedule_enabled); setScheduleDays((editing||duplicate)&&source?.access_schedule_days?.length?source.access_schedule_days:[0,1,2,3,4]); $('client-schedule-start').value=(editing||duplicate)?(source?.access_schedule_start||'08:00'):'08:00'; $('client-schedule-end').value=(editing||duplicate)?(source?.access_schedule_end||'19:00'):'19:00'; setHidden('client-schedule-disabled-note',!Boolean(editing&&source?.schedule_disabled)); + }else{$('client-server-host').value='';$('client-server-port').value=serverListenPort();$('client-dns').value='';$('client-allowed-ips').value='';$('client-local-access-exceptions').value='';$('client-route-preset').value='custom';$('client-use-psk').checked=true;$('client-expiry-preset').value='never';$('client-expiry-custom').value='';$('client-expiry-delete').checked=true;setHidden('client-expired-disabled-note',true);$('client-peer-isolation').checked=false;$('client-schedule-enabled').checked=false;setScheduleDays([0,1,2,3,4]);$('client-schedule-start').value='08:00';$('client-schedule-end').value='19:00';setHidden('client-schedule-disabled-note',true);if($('client-connection-mode'))$('client-connection-mode').value='direct';renderClientRelaySelect();} + syncClientTypeFields(); + const group=groupById($('client-group').value); policySelectOptions($('client-internet-access'),$('client-policy-mode').value,source?.internet_access||'inherit',group?.policy?.internet_access||'allow'); policySelectOptions($('client-local-access'),$('client-policy-mode').value,source?.local_access||'inherit',group?.policy?.local_access||'allow'); + if(group){const legacyCustom=editing&&!source?.config_mode&&Boolean(source?.group_config_differs);$('client-config-override').checked=duplicate?Boolean(source?.config_mode==='custom'):(editing?Boolean(source?.config_mode==='custom'||legacyCustom):false);if(!editing&&!duplicate)applySelectedGroupDefaults(false);}else $('client-config-override').checked=false; + syncClientGroupFields(); syncClientGroupConfigWarning(); syncClientExpiryFields(); syncClientScheduleFields(); syncClientPskFields(); syncClientConnectionFields(); renderEndpointHistory(); activateClientTab('basic'); + operationStatus('client-editor-status',duplicate?(($('client-type').value==='site_to_site'?`${t('clients.duplicate_ready','A copy is ready.')}\n${t('clients.duplicate_site_hint','Remote networks were cleared to prevent duplicate routes.')}`:t('clients.duplicate_ready','A copy is ready.'))):'','info'); modalShow('client-editor-modal',true); setTimeout(()=>$('client-name')?.focus(),30); + } + function clientPayloadFromForm(){ + const managed=$('client-editor-form')?.dataset.managed==='true'; const siteToSite=$('client-type').value==='site_to_site'; const host=managed?$('client-server-host').value.trim():''; const port=managed?Number($('client-server-port').value||serverListenPort()):serverListenPort(); const groupId=managed&&!siteToSite?$('client-group')?.value||'':''; const protectLocal=managed&&!groupId&&$('client-route-preset')?.value==='full_except_local'; + const connectionMode=managed&&relayItems().length?($('client-connection-mode')?.value||'direct'):'direct'; + return {name:$('client-name').value.trim(),type:$('client-type').value,vpn_address:$('client-vpn-address').value.trim(),remote_networks:siteToSite?splitList($('client-remote-networks').value):[],persistent_keepalive:Number($('client-keepalive').value||0),endpoint:managed&&connectionMode==='direct'?joinEndpoint(host,port):'',client_allowed_ips:managed?splitList($('client-allowed-ips').value):[],route_preset:managed?$('client-route-preset').value:'',protect_local_networks:protectLocal,local_access_exceptions:protectLocal?splitList($('client-local-access-exceptions').value):[],dns:managed?splitList($('client-dns').value):[],group_id:groupId,policy_mode:groupId?$('client-policy-mode').value:'',internet_access:groupId?$('client-internet-access').value:'',local_access:groupId?$('client-local-access').value:'',policy_allow:groupId?splitList($('client-policy-allow').value):[],policy_deny:groupId?splitList($('client-policy-deny').value):[],config_mode:groupId?($('client-config-override')?.checked?'custom':'inherit'):'',use_preshared_key:managed?Boolean($('client-use-psk')?.checked):false,peer_isolation:managed&&!siteToSite?Boolean($('client-peer-isolation')?.checked):false,expires_at:managed?expiryFromForm():0,expiration_action:managed&&!siteToSite&&$('client-expiry-preset')?.value!=='never'&&!$('client-expiry-delete')?.checked?'disable':'delete',access_schedule_enabled:managed&&!siteToSite?Boolean($('client-schedule-enabled')?.checked):false,access_schedule_days:managed&&!siteToSite&&$('client-schedule-enabled')?.checked?selectedScheduleDays():[],access_schedule_start:managed?($('client-schedule-start')?.value||'08:00'):'08:00',access_schedule_end:managed?($('client-schedule-end')?.value||'19:00'):'19:00',connection_mode:connectionMode,relay_vps_id:connectionMode==='relay'?($('client-relay-vps')?.value||''):''}; + } + async function saveClient(event){ + event.preventDefault(); const form=$('client-editor-form'),button=$('save-client-button');if(!form||!button)return;const editing=form.dataset.mode==='edit',managed=form.dataset.managed==='true',payload=clientPayloadFromForm();if(editing)payload.public_key=form.dataset.publicKey; + if(!payload.name||!payload.vpn_address){operationStatus('client-editor-status',t('clients.required','Name and VPN address are required.'),'error');activateClientTab('basic',!payload.name?'client-name':'client-vpn-address');return;} + if(managed&&payload.connection_mode==='direct'&&!$('client-server-host')?.value.trim()){operationStatus('client-editor-status',t('clients.server_host_required','Server address / domain is required for a generated client configuration.'),'error');activateClientTab('basic','client-server-host');return;} + if(managed&&payload.connection_mode==='relay'&&!payload.relay_vps_id){operationStatus('client-editor-status',t('clients.relay_required','Choose a VPS Relay for this client.'),'error');activateClientTab('config','client-relay-vps');return;} + if(managed&&!payload.client_allowed_ips.length){operationStatus('client-editor-status',t('clients.allowed_ips_required','Enter at least one AllowedIPs network for the client configuration.'),'error');activateClientTab('config','client-allowed-ips');return;} + if(managed&&$('client-expiry-preset')?.value==='custom'&&(!payload.expires_at||payload.expires_at<=Math.floor(Date.now()/1000))){operationStatus('client-editor-status',t('clients.expiration_future_required','Choose a future expiration date and time.'),'error');activateClientTab('security','client-expiry-custom');return;} + if(managed&&payload.access_schedule_enabled&&!payload.access_schedule_days.length){operationStatus('client-editor-status',t('clients.schedule_days_required','Choose at least one day for the access schedule.'),'error');activateClientTab('security');return;} + if(managed&&payload.access_schedule_enabled&&(!payload.access_schedule_start||!payload.access_schedule_end)){operationStatus('client-editor-status',t('clients.schedule_time_required','Set both start and end times for the access schedule.'),'error');activateClientTab('security',!payload.access_schedule_start?'client-schedule-start':'client-schedule-end');return;} + if(payload.type==='site_to_site'&&!payload.remote_networks.length){operationStatus('client-editor-status',t('clients.remote_required','Enter at least one remote network for a Site-to-site peer.'),'error');activateClientTab('basic','client-remote-networks');return;} + const others=(snapshot?.peers||[]).filter(p=>!editing||p.public_key!==form.dataset.publicKey); if(others.some(p=>String(p.name||'').trim().toLocaleLowerCase()===payload.name.toLocaleLowerCase())){operationStatus('client-editor-status',t('clients.duplicate_name_error','A peer with this name already exists.'),'error');activateClientTab('basic','client-name');return;} const wantedIp=payload.vpn_address.split('/')[0]; if(others.some(p=>String(p.vpn_address||'').split('/')[0]===wantedIp)){operationStatus('client-editor-status',t('clients.duplicate_address_error','This VPN address is already used by another peer.'),'error');activateClientTab('basic','client-vpn-address');return;} + button.disabled=true; operationStatus('client-editor-status',editing?t('clients.updating','Updating client…'):t('clients.creating','Creating keys and applying client…'),'working'); + try{const r=await fetch(editing?'/api/clients/update':'/api/clients/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Operation failed');operationStatus('client-editor-status',d.message||t('clients.saved','Client saved'),'success');if(managed&&payload.connection_mode==='direct')saveEndpointHistory($('client-server-host')?.value);await fetchSnapshot();modalShow('client-editor-modal',false);toast(t('clients.saved','Client saved'));if(!editing&&managed&&d.public_key)await openClientConfig(d.public_key);}catch(e){operationStatus('client-editor-status',e.message,'error');}finally{button.disabled=false;} + } + async function deleteClient(peer){if(!peer)return;if(!confirm(`${t('clients.delete_confirm','Delete this client from WireGuard? A backup of the selected interface configuration will be created first.')}\n\n${peer.name||peer.vpn_address||''}`))return;try{const r=await fetch('/api/clients/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:peer.public_key})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');toast(t('clients.deleted','Client deleted'));await fetchSnapshot();}catch(e){toast(e.message);}} + + function groupPolicySummary(group){const p=group.policy||{};return `${t('groups.internet_short','Internet')}: ${accessWord(p.internet_access||'allow')} · ${t('groups.local_short','Local')}: ${accessWord(p.local_access||'allow')}`;} + function groupDefaultsSummary(group){const d=group.resolved_defaults||group.defaults||{};const routeKey={full:'clients.route_full',full_except_local:'clients.route_full_except_local',vpn_lan:'clients.route_vpn_lan',vpn:'clients.route_vpn',custom:'clients.route_custom'}[d.route_preset]||'clients.route_custom';return `${t('groups.new_clients_short','New clients')}: ${t(routeKey,d.route_preset||'Custom')} · DNS ${(d.dns||[]).join(', ')||'—'} · KA ${d.persistent_keepalive??25}`;} + function renderGroups(){ + const list=$('groups-list');if(!list)return;const groups=clientGroups();if(!groups.length){list.innerHTML=`
${esc(t('groups.empty','No client groups yet. Create one to reuse access policies and client defaults.'))}
`;return;} + list.innerHTML=groups.map((g,i)=>`
${esc(g.name||'')}${esc(t('groups.members_count','{count} clients').replace('{count}',String(g.member_count||0)))}
${g.description?`
${esc(g.description)}
`:''}
${esc(groupPolicySummary(g))}
${esc(groupDefaultsSummary(g))}
`).join(''); + } + function openGroups(){renderGroups();modalShow('groups-modal',true);} + function applyGroupRoutePreset(clearCustom=false){const preset=$('group-route-preset')?.value,field=$('group-allowed-ips');if(!field)return;if(preset==='custom'){if(clearCustom)field.value='';return;}field.value=presetRoutes(preset).join('\n');} + function openGroupEditor(group=null){ + const form=$('group-editor-form');if(!form)return;form.dataset.mode=group?'edit':'create';form.dataset.groupId=group?.id||'';$('group-editor-title').textContent=group?t('groups.edit_title','Edit group'):t('groups.create_title','Create group');$('group-name').value=group?.name||'';$('group-description').value=group?.description||'';$('group-internet-access').value=group?.policy?.internet_access||'allow';$('group-local-access').value=group?.policy?.local_access||'allow';$('group-policy-allow').value=(group?.policy?.allow||[]).join(', ');$('group-policy-deny').value=(group?.policy?.deny||[]).join(', ');const d=group?.resolved_defaults||group?.defaults||{};$('group-route-preset').value=d.route_preset||'full';$('group-allowed-ips').value=(d.client_allowed_ips||presetRoutes(d.route_preset||'full')).join('\n');$('group-dns').value=(d.dns||[]).join(', ');$('group-keepalive').value=d.persistent_keepalive??25;operationStatus('group-editor-status','');modalShow('group-editor-modal',true);setTimeout(()=>$('group-name')?.focus(),30); + } + function groupPayload(){return {name:$('group-name').value.trim(),description:$('group-description').value.trim(),internet_access:$('group-internet-access').value,local_access:$('group-local-access').value,policy_allow:splitList($('group-policy-allow').value),policy_deny:splitList($('group-policy-deny').value),route_preset:$('group-route-preset').value,client_allowed_ips:splitList($('group-allowed-ips').value),dns:splitList($('group-dns').value),persistent_keepalive:Number($('group-keepalive').value||0)};} + async function saveGroup(event){event.preventDefault();const form=$('group-editor-form'),button=$('save-group-button');if(!form||!button)return;const editing=form.dataset.mode==='edit',payload=groupPayload();if(editing)payload.group_id=form.dataset.groupId;if(!payload.name){operationStatus('group-editor-status',t('groups.name_required','Group name is required.'),'error');$('group-name')?.focus();return;}if(!payload.client_allowed_ips.length){operationStatus('group-editor-status',t('groups.routes_required','Client routes cannot be empty.'),'error');return;}button.disabled=true;operationStatus('group-editor-status',editing?t('groups.updating','Updating group policy…'):t('groups.creating','Creating group…'),'working');try{const r=await fetch(editing?'/api/client-groups/update':'/api/client-groups/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Operation failed');await fetchSnapshot();renderGroups();modalShow('group-editor-modal',false);toast(editing?t('groups.updated','Group updated'):t('groups.created','Group created'));}catch(e){operationStatus('group-editor-status',e.message,'error');}finally{button.disabled=false;}} + let deletingGroupId=''; + function openGroupDelete(group){deletingGroupId=group?.id||'';if(!deletingGroupId)return;$('group-delete-text').textContent=t('groups.delete_message','Delete “{name}”? Client configurations are never deleted with a group.').replace('{name}',group.name||'');const targets=clientGroups().filter(g=>g.id!==deletingGroupId),target=$('group-delete-target');if(target){target.innerHTML=targets.map(g=>``).join('');target.value=targets[0]?.id||'';target.disabled=true;}const moveRadio=document.querySelector('input[name="group-delete-mode"][value="move"]');if(moveRadio)moveRadio.disabled=!targets.length;const unassignRadio=document.querySelector('input[name="group-delete-mode"][value="unassign"]');if(unassignRadio)unassignRadio.checked=true;operationStatus('group-delete-status','');modalShow('group-delete-modal',true);} + async function confirmDeleteGroup(){const button=$('confirm-delete-group-button');if(!button||!deletingGroupId)return;const mode=document.querySelector('input[name="group-delete-mode"]:checked')?.value||'unassign';const moveTo=mode==='move'?$('group-delete-target').value:'';button.disabled=true;operationStatus('group-delete-status',t('groups.deleting','Updating clients and deleting group…'),'working');try{const r=await fetch('/api/client-groups/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({group_id:deletingGroupId,move_to_group_id:moveTo})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');await fetchSnapshot();renderGroups();modalShow('group-delete-modal',false);toast(t('groups.deleted','Group deleted'));}catch(e){operationStatus('group-delete-status',e.message,'error');}finally{button.disabled=false;}} + + let currentConfigKey=''; let qrObjectUrl=''; let configFilename='wireguard-client.conf'; + async function openClientConfig(publicKey){currentConfigKey=publicKey;modalShow('client-config-modal',true);$('client-config-text').value='';$('client-qr-image').hidden=true;$('client-qr-loading').hidden=false;$('client-qr-loading').textContent=t('clients.qr_loading','Generating QR…');try{const r=await fetch('/api/clients/config',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:publicKey})});const d=await r.json();if(!r.ok)throw new Error(d.error||t('clients.config_unavailable','Configuration unavailable'));$('client-config-text').value=d.config||'';configFilename=d.filename||'wireguard-client.conf';$('client-config-title').textContent=d.name||t('clients.config_title','Client configuration');const qr=await fetch('/api/clients/qr',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:publicKey})});if(!qr.ok){const err=await qr.json().catch(()=>({}));throw new Error(err.error||'QR failed');}const blob=await qr.blob();if(qrObjectUrl)URL.revokeObjectURL(qrObjectUrl);qrObjectUrl=URL.createObjectURL(blob);$('client-qr-image').src=qrObjectUrl;$('client-qr-image').hidden=false;$('client-qr-loading').hidden=true;}catch(e){$('client-qr-loading').textContent=e.message;toast(e.message);}} + async function downloadClientConfig(){if(!currentConfigKey)return;try{const r=await fetch('/api/clients/config/download',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:currentConfigKey})});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.error||'Download failed');}const blob=await r.blob();const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download=configFilename;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}catch(e){toast(e.message);}} + async function copyClientConfig(){const text=$('client-config-text')?.value||'';if(!text)return;try{await navigator.clipboard.writeText(text);toast(t('clients.copy_done','Configuration copied'));}catch{toast('Clipboard unavailable');}} + function bindClientManagement(){ + document.querySelectorAll('[data-client-tab]').forEach(button=>{button.addEventListener('click',()=>activateClientTab(button.dataset.clientTab));button.addEventListener('keydown',event=>{if(!['ArrowLeft','ArrowRight'].includes(event.key))return;const visible=CLIENT_EDITOR_TABS.map(name=>$(`client-tab-button-${name}`)).filter(item=>item&&!item.hidden&&!item.disabled);const index=visible.indexOf(button);if(index<0||!visible.length)return;event.preventDefault();const step=event.key==='ArrowRight'?1:-1;const next=visible[(index+step+visible.length)%visible.length];activateClientTab(next.dataset.clientTab);next.focus();});}); + const clientSearch=$('client-quick-search'), clientSearchClear=$('client-quick-search-clear'); + clientSearch?.addEventListener('input',()=>{syncClientQuickSearchClear();if(snapshot)renderClients(snapshot);}); + clientSearchClear?.addEventListener('click',()=>{if(!clientSearch)return;clientSearch.value='';syncClientQuickSearchClear();clientSearch.focus();if(snapshot)renderClients(snapshot);}); + syncClientQuickSearchClear(); + $('client-expiry-custom')?.addEventListener('pointerdown',ensureExpiryDateTimeValue);$('client-expiry-custom')?.addEventListener('focus',ensureExpiryDateTimeValue); + $('client-schedule-enabled')?.addEventListener('change',syncClientScheduleFields); + $('add-client-button')?.addEventListener('click',()=>openClientEditor());$('manage-groups-button')?.addEventListener('click',openGroups);$('client-use-panel-host')?.addEventListener('click',usePanelHostForClient);$('client-editor-form')?.addEventListener('submit',saveClient);$('client-type')?.addEventListener('change',syncClientTypeFields);$('client-route-preset')?.addEventListener('change',()=>{applyRoutePreset(true);syncClientGroupConfigWarning();});$('client-allowed-ips')?.addEventListener('input',()=>{if($('client-route-preset')){$('client-route-preset').value='custom';syncRoutePresetFields();syncClientGroupConfigWarning();}});$('client-group')?.addEventListener('change',()=>{const form=$('client-editor-form');$('client-policy-mode').value='inherit';$('client-internet-access').value='inherit';$('client-local-access').value='inherit';$('client-policy-allow').value='';$('client-policy-deny').value='';$('client-config-override').checked=false;if($('client-group').value)applySelectedGroupDefaults(false);syncClientGroupFields();});$('client-policy-mode')?.addEventListener('change',syncClientGroupPolicyMode);$('client-internet-access')?.addEventListener('change',renderClientPolicyPreview);$('client-local-access')?.addEventListener('change',renderClientPolicyPreview);$('client-policy-allow')?.addEventListener('input',renderClientPolicyPreview);$('client-policy-deny')?.addEventListener('input',renderClientPolicyPreview);$('apply-group-defaults-button')?.addEventListener('click',()=>applySelectedGroupDefaults(true));$('client-config-override')?.addEventListener('change',syncClientGroupConfigMode);$('client-dns')?.addEventListener('input',syncClientGroupConfigWarning);$('client-keepalive')?.addEventListener('input',syncClientGroupConfigWarning);$('client-expiry-preset')?.addEventListener('change',syncClientExpiryFields);$('client-use-psk')?.addEventListener('change',syncClientPskFields);$('client-connection-mode')?.addEventListener('change',syncClientConnectionFields);$('client-relay-vps')?.addEventListener('change',syncClientConnectionFields);$('rotate-credentials-button')?.addEventListener('click',rotateClientCredentials);renderEndpointHistory(); + $('client-body')?.addEventListener('click',e=>{const b=e.target.closest('[data-client-action]');if(!b||!snapshot)return;const peer=(snapshot.peers||[])[Number(b.dataset.clientIndex)];if(!peer)return;if(b.dataset.clientAction==='duplicate')openClientEditor(peer,{duplicate:true});else if(b.dataset.clientAction==='edit')openClientEditor(peer);else if(b.dataset.clientAction==='delete')deleteClient(peer);else if(b.dataset.clientAction==='config')openClientConfig(peer.public_key);}); + $('create-group-button')?.addEventListener('click',()=>openGroupEditor());$('group-editor-form')?.addEventListener('submit',saveGroup);$('group-route-preset')?.addEventListener('change',()=>applyGroupRoutePreset(true));$('group-allowed-ips')?.addEventListener('input',()=>{if($('group-route-preset'))$('group-route-preset').value='custom';});$('groups-list')?.addEventListener('click',e=>{const b=e.target.closest('[data-group-action]');if(!b)return;const g=clientGroups()[Number(b.dataset.groupIndex)];if(!g)return;if(b.dataset.groupAction==='edit')openGroupEditor(g);else if(b.dataset.groupAction==='delete')openGroupDelete(g);});document.querySelectorAll('input[name="group-delete-mode"]').forEach(r=>r.addEventListener('change',()=>{$('group-delete-target').disabled=document.querySelector('input[name="group-delete-mode"]:checked')?.value!=='move';}));$('confirm-delete-group-button')?.addEventListener('click',confirmDeleteGroup); + document.querySelectorAll('[data-modal-close]').forEach(b=>b.addEventListener('click',()=>modalShow(b.dataset.modalClose,false)));document.querySelectorAll('.modal-backdrop').forEach(m=>m.addEventListener('click',e=>{if(e.target===m)modalShow(m.id,false);}));document.addEventListener('keydown',e=>{if(e.key==='Escape')document.querySelectorAll('.modal-backdrop:not([hidden])').forEach(m=>modalShow(m.id,false));});$('download-config-button')?.addEventListener('click',downloadClientConfig);$('copy-config-button')?.addEventListener('click',copyClientConfig); + } + + function traceMs(value){ + if(value===null||value===undefined||value==='')return '—'; + const n=Number(value); if(!Number.isFinite(n))return '—'; + return `${n<10?n.toFixed(1):n.toFixed(0)} ${t('trace.ms','ms')}`; + } + function tracePrivateIpv4(ip){ + const parts=String(ip||'').split('.').map(Number); if(parts.length!==4||parts.some(x=>!Number.isInteger(x)||x<0||x>255))return false; + return parts[0]===10||parts[0]===127||(parts[0]===192&&parts[1]===168)||(parts[0]===172&&parts[1]>=16&&parts[1]<=31)||(parts[0]===169&&parts[1]===254); + } + function traceLocation(hop){ + if(!hop?.ip)return t('trace.no_reply','No reply'); + const g=hop.geo; + if(g){ + const place=[g.city,g.region,g.country].filter(Boolean).filter((v,i,a)=>a.indexOf(v)===i).join(', '); + const net=[g.asn,g.org].filter(Boolean).join(' · '); + return [place,net].filter(Boolean).join(' — ')||t('trace.unknown','Unknown'); + } + if(tracePrivateIpv4(hop.ip))return t('trace.private','Private network'); + return t('trace.unknown','Unknown'); + } + function traceRttClass(value){ + if(value===null||value===undefined||value==='')return ''; + const n=Number(value); if(!Number.isFinite(n))return ''; + if(n>=120)return 'trace-rtt-bad'; if(n>=50)return 'trace-rtt-warn'; return ''; + } + function traceDeltaLevel(value){ + if(value===null||value===undefined||value==='')return 'unknown'; + const n=Number(value); if(!Number.isFinite(n))return 'unknown'; + if(n>20)return 'bad'; if(n>5)return 'warn'; return 'ok'; + } + function traceDeltaClass(value){ + const level=traceDeltaLevel(value); + return level==='bad'?'trace-delta-bad':level==='warn'?'trace-delta-warn':level==='ok'?'trace-delta-ok':''; + } + function traceHopRowClass(hop){ + const level=traceDeltaLevel(hop?.delta_ms); + return level==='bad'?'trace-hop-latency-bad':level==='warn'?'trace-hop-latency-warn':''; + } + function traceSegmentClass(hop){ + const level=traceDeltaLevel(hop?.delta_ms); + return level==='bad'?'latency-bad':level==='warn'?'latency-warn':level==='ok'?'latency-ok':'latency-unknown'; + } + const traceMapState={ + center:{lon:30,lat:35},zoom:2,minZoom:2,maxZoom:12,points:[],fitted:false, + drag:null,resizeObserver:null,popupIndex:null + }; + function traceGeoPoint(geo){ + const lon=Number(geo?.longitude),lat=Number(geo?.latitude); + if(!Number.isFinite(lon)||!Number.isFinite(lat))return null; + return {lon:Math.max(-180,Math.min(180,lon)),lat:Math.max(-85.0511,Math.min(85.0511,lat))}; + } + function traceWorldPoint(lon,lat,zoom){ + const size=256*Math.pow(2,zoom),x=(lon+180)/360*size; + const clamped=Math.max(-85.0511,Math.min(85.0511,lat)); + const sin=Math.sin(clamped*Math.PI/180); + const y=(0.5-Math.log((1+sin)/(1-sin))/(4*Math.PI))*size; + return {x,y,size}; + } + function traceWorldToLonLat(x,y,zoom){ + const size=256*Math.pow(2,zoom); + x=((x%size)+size)%size;y=Math.max(0,Math.min(size,y)); + const lon=x/size*360-180; + const n=Math.PI-2*Math.PI*y/size; + const lat=180/Math.PI*Math.atan(Math.sinh(n)); + return {lon,lat}; + } + function traceMapViewport(){return $('network-trace-map');} + function traceMapScreenPoint(point,width,height){ + const z=traceMapState.zoom,center=traceWorldPoint(traceMapState.center.lon,traceMapState.center.lat,z),p=traceWorldPoint(point.lon,point.lat,z); + let dx=p.x-center.x;if(dx>p.size/2)dx-=p.size;if(dx<-p.size/2)dx+=p.size; + return {x:width/2+dx,y:height/2+(p.y-center.y)}; + } + function traceMapClosePopup(){const pop=$('network-trace-map-popup');if(pop)pop.hidden=true;traceMapState.popupIndex=null;} + function traceMapShowPopup(index,screen){ + const item=traceMapState.points[index],pop=$('network-trace-map-popup'),map=traceMapViewport();if(!item||!pop||!map)return; + const h=item.hop||{},location=traceLocation(h),hasReply=!!h.ip&&Array.isArray(h.samples_ms)&&h.samples_ms.length>0; + const loss=hasReply&&Number.isFinite(Number(h.loss_percent))?`${Number(h.loss_percent).toFixed(0)}%`:t('trace.no_reply','No reply'); + const delta=h.delta_ms===null||h.delta_ms===undefined?null:Number(h.delta_ms); + const deltaText=delta!==null&&Number.isFinite(delta)?`${delta>=0?'+':''}${delta.toFixed(Math.abs(delta)<10?1:0)} ${t('trace.ms','ms')}`:'—'; + pop.innerHTML=`#${esc(h.hop)} · ${esc(h.ip||'')}${esc(location)}RTT: ${esc(traceMs(h.avg_ms))} · Δ RTT: ${esc(deltaText)} · ${esc(t('trace.loss','Loss'))}: ${esc(loss)}`; + pop.hidden=false;traceMapState.popupIndex=index; + const mw=map.clientWidth,mh=map.clientHeight,pw=pop.offsetWidth,ph=pop.offsetHeight; + pop.style.left=`${Math.max(8,Math.min(mw-pw-8,screen.x+14))}px`; + pop.style.top=`${Math.max(8,Math.min(mh-ph-8,screen.y-ph/2))}px`; + } + function traceMapFitRoute(){ + const map=traceMapViewport(),points=traceMapState.points;if(!map||!points.length)return; + const w=map.clientWidth||900,h=map.clientHeight||420,pad=88; + let chosen=traceMapState.minZoom,center={lon:points[0].p.lon,lat:points[0].p.lat}; + for(let z=traceMapState.maxZoom;z>=traceMapState.minZoom;z--){ + const ps=points.map(x=>traceWorldPoint(x.p.lon,x.p.lat,z)); + let xs=ps.map(x=>x.x),ys=ps.map(x=>x.y),size=ps[0].size; + // unwrap around first point so routes close to the date line still fit correctly + const anchor=xs[0];xs=xs.map(x=>{while(x-anchor>size/2)x-=size;while(x-anchor<-size/2)x+=size;return x;}); + const minX=Math.min(...xs),maxX=Math.max(...xs),minY=Math.min(...ys),maxY=Math.max(...ys); + if(maxX-minX<=Math.max(60,w-pad*2)&&maxY-minY<=Math.max(60,h-pad*2)){ + chosen=z;center=traceWorldToLonLat((minX+maxX)/2,(minY+maxY)/2,z);break; + } + } + traceMapState.zoom=chosen;traceMapState.center=center;traceMapState.fitted=true;traceMapClosePopup();renderTraceSlippyMap(); + } + function traceMapSetZoom(next,anchorX,anchorY){ + const map=traceMapViewport();if(!map)return; + next=Math.max(traceMapState.minZoom,Math.min(traceMapState.maxZoom,next));if(next===traceMapState.zoom)return; + const w=map.clientWidth,h=map.clientHeight,ax=Number.isFinite(anchorX)?anchorX:w/2,ay=Number.isFinite(anchorY)?anchorY:h/2; + const old=traceWorldPoint(traceMapState.center.lon,traceMapState.center.lat,traceMapState.zoom); + const geo=traceWorldToLonLat(old.x+(ax-w/2),old.y+(ay-h/2),traceMapState.zoom); + const gp=traceWorldPoint(geo.lon,geo.lat,next); + const newCenter=traceWorldToLonLat(gp.x-(ax-w/2),gp.y-(ay-h/2),next); + traceMapState.zoom=next;traceMapState.center=newCenter;traceMapClosePopup();renderTraceSlippyMap(); + } + function renderTraceSlippyMap(){ + const map=traceMapViewport(),tiles=$('network-trace-map-tiles'),svg=$('network-trace-map-svg');if(!map||!tiles||!svg||map.hidden||!map.offsetParent)return; + const w=map.clientWidth,h=map.clientHeight,z=traceMapState.zoom,center=traceWorldPoint(traceMapState.center.lon,traceMapState.center.lat,z),size=center.size; + const left=center.x-w/2,top=center.y-h/2,tileSize=256,n=Math.pow(2,z); + const minTX=Math.floor(left/tileSize),maxTX=Math.floor((left+w)/tileSize),minTY=Math.max(0,Math.floor(top/tileSize)),maxTY=Math.min(n-1,Math.floor((top+h)/tileSize)); + const tileHtml=[]; + for(let ty=minTY;ty<=maxTY;ty++)for(let tx=minTX;tx<=maxTX;tx++){ + const wrap=((tx%n)+n)%n,x=tx*tileSize-left,y=ty*tileSize-top; + tileHtml.push(``); + } + tiles.innerHTML=tileHtml.join('');svg.setAttribute('viewBox',`0 0 ${w} ${h}`);svg.setAttribute('width',w);svg.setAttribute('height',h); + const screen=traceMapState.points.map((item,index)=>({item,index,...traceMapScreenPoint(item.p,w,h)})); + // Fan out hops that geolocate to the same city so they remain individually clickable. + const buckets=new Map();screen.forEach(p=>{const key=`${Math.round(p.x/5)}:${Math.round(p.y/5)}`;(buckets.get(key)||buckets.set(key,[]).get(key)).push(p);}); + buckets.forEach(group=>{if(group.length<2)return;group.forEach((p,i)=>{const a=Math.PI*2*i/group.length,r=Math.min(58,16+group.length*2.2);p.x+=Math.cos(a)*r;p.y+=Math.sin(a)*r;});}); + const chunks=[]; + for(let i=1;i`); + chunks.push(``); + } + screen.forEach(p=>{const h=p.item.hop||{},label=String(h.hop),latency=p.item.synthetic?'latency-unknown':traceSegmentClass(h);chunks.push(`${esc(label)}`);}); + svg.innerHTML=chunks.join(''); + if(traceMapState.popupIndex!==null){const p=screen.find(x=>x.index===traceMapState.popupIndex);if(p)traceMapShowPopup(p.index,p);} + } + function renderNetworkTraceMap(hops,targetGeo,targetIp){ + const panel=$('network-trace-map-panel'),summary=$('network-trace-map-route-summary');if(!panel)return; + const points=(hops||[]).map(h=>({hop:h,p:traceGeoPoint(h.geo)})).filter(x=>x.p); + const hasTarget=points.some(x=>x.hop?.reached||String(x.hop?.ip||'')===String(targetIp||'')); + if(!hasTarget&&targetGeo){const p=traceGeoPoint(targetGeo);if(p)points.push({hop:{hop:'T',ip:targetIp,avg_ms:null,reached:true,geo:targetGeo},p,synthetic:true});} + panel.hidden=!points.length;traceMapState.points=points;traceMapState.fitted=false;traceMapClosePopup(); + if(summary){ + const labels=[]; + points.forEach(({hop})=>{ + const g=hop?.geo||{}; + const label=[g.city,g.country].filter(Boolean).filter((v,i,a)=>a.indexOf(v)===i).join(', ')||String(hop?.ip||''); + if(label&&labels[labels.length-1]!==label)labels.push(label); + }); + summary.innerHTML=labels.length?`${esc(t('trace.route_path','Route'))}: ${labels.map(esc).join(' ')}`:''; + summary.hidden=!labels.length; + } + if(points.length){ + // Wait until the newly-unhidden tab and map have a real layout size before fitting. + window.requestAnimationFrame(()=>window.requestAnimationFrame(traceMapFitRoute)); + }else{ + $('network-trace-map-tiles')?.replaceChildren();$('network-trace-map-svg')?.replaceChildren(); + } + } + function bindTraceMap(){ + const map=traceMapViewport(),svg=$('network-trace-map-svg');if(!map||map.dataset.traceBound==='1')return;map.dataset.traceBound='1'; + $('network-trace-map-zoom-in')?.addEventListener('click',()=>traceMapSetZoom(traceMapState.zoom+1)); + $('network-trace-map-zoom-out')?.addEventListener('click',()=>traceMapSetZoom(traceMapState.zoom-1)); + $('network-trace-map-fit')?.addEventListener('click',traceMapFitRoute); + map.addEventListener('wheel',e=>{e.preventDefault();const r=map.getBoundingClientRect();traceMapSetZoom(traceMapState.zoom+(e.deltaY<0?1:-1),e.clientX-r.left,e.clientY-r.top);},{passive:false}); + map.addEventListener('pointerdown',e=>{if(e.button!==0||e.target.closest('.trace-map-control,.trace-route-marker,.trace-map-popup,a'))return;map.setPointerCapture?.(e.pointerId);const c=traceWorldPoint(traceMapState.center.lon,traceMapState.center.lat,traceMapState.zoom);traceMapState.drag={x:e.clientX,y:e.clientY,cx:c.x,cy:c.y,moved:false};map.classList.add('dragging');traceMapClosePopup();}); + map.addEventListener('pointermove',e=>{const d=traceMapState.drag;if(!d)return;const dx=e.clientX-d.x,dy=e.clientY-d.y;if(Math.abs(dx)+Math.abs(dy)>3)d.moved=true;traceMapState.center=traceWorldToLonLat(d.cx-dx,d.cy-dy,traceMapState.zoom);renderTraceSlippyMap();}); + const endDrag=()=>{traceMapState.drag=null;map.classList.remove('dragging');};map.addEventListener('pointerup',endDrag);map.addEventListener('pointercancel',endDrag); + svg?.addEventListener('click',e=>{const marker=e.target.closest?.('.trace-route-marker');if(!marker)return;e.stopPropagation();const index=Number(marker.dataset.tracePoint),r=map.getBoundingClientRect(),m=marker.getCTM(),pt=svg.createSVGPoint();pt.x=0;pt.y=0;const screen=pt.matrixTransform(m);traceMapShowPopup(index,{x:screen.x,y:screen.y});}); + map.addEventListener('click',e=>{if(!e.target.closest?.('.trace-route-marker,.trace-map-popup,.trace-map-control,a')&&!traceMapState.drag?.moved)traceMapClosePopup();}); + if(window.ResizeObserver){traceMapState.resizeObserver=new ResizeObserver(()=>renderTraceSlippyMap());traceMapState.resizeObserver.observe(map);} + } + function renderNetworkTrace(data){ + const results=$('network-trace-results'),summary=$('network-trace-summary'),body=$('network-trace-body'); + if(!results||!summary||!body)return; + results.hidden=false; + const ping=data.ping||{}; + const pingText=ping.avg_ms!==null&&ping.avg_ms!==undefined&&Number.isFinite(Number(ping.avg_ms))?traceMs(ping.avg_ms):t('trace.no_reply','No reply'); + const loss=Number.isFinite(Number(ping.loss_percent))?`${Number(ping.loss_percent).toFixed(Number(ping.loss_percent)%1?1:0)}%`:'—'; + summary.innerHTML=[ + [t('trace.summary_target','Target'),data.target_ip||data.target||'—',data.target&&data.target!==data.target_ip?data.target:''], + [t('trace.summary_ping','Average ping'),pingText,data.reached?t('trace.reached','Target reached'):(ping.reachable?t('trace.ping_ok_trace_filtered','Target responds to ping; final traceroute hops do not reply.'):t('trace.not_reached','Target was not reached by traceroute.'))], + [t('trace.summary_loss','Ping loss'),loss,`${Number(ping.received||0)}/${Number(ping.sent||0)}`], + [t('trace.summary_hops','Hops'),String(data.hop_count||0),`${Number(data.trace_seconds||0).toFixed(1)} s`] + ].map(([label,value,small])=>`
${esc(label)}${esc(value)}${small?`${esc(small)}`:''}
`).join(''); + const hops=data.hops||[]; + // Keep unanswered hops only when they are inside the observed route. Once the + // last responding router has been passed, the remaining probe ceiling adds no + // useful information and only stretches the table. + let lastReplyIndex=-1; + for(let i=hops.length-1;i>=0;i--){ + const h=hops[i]; + if(h?.ip&&Array.isArray(h.samples_ms)&&h.samples_ms.length>0){lastReplyIndex=i;break;} + } + const visibleHops=lastReplyIndex>=0?hops.slice(0,lastReplyIndex+1):[]; + const lastVisibleHop=visibleHops.length?Number(visibleHops[visibleHops.length-1].hop)||visibleHops.length:0; + const hopSummary=summary.querySelector('.trace-summary-item:last-child b'); + if(hopSummary)hopSummary.textContent=String(lastVisibleHop||0); + body.innerHTML=visibleHops.length?visibleHops.map(h=>{ + const hasReply=!!h.ip&&Array.isArray(h.samples_ms)&&h.samples_ms.length>0; + const ip=h.ip||'*'; const location=traceLocation(h); const delta=h.delta_ms===null||h.delta_ms===undefined?null:Number(h.delta_ms); + const deltaText=delta!==null&&Number.isFinite(delta)?`${delta>=0?'+':''}${delta.toFixed(Math.abs(delta)<10?1:0)} ${t('trace.ms','ms')}`:'—'; + const loss=hasReply&&Number.isFinite(Number(h.loss_percent))?`${Number(h.loss_percent).toFixed(0)}%`:t('trace.no_reply','No reply'); + const lossClass=!hasReply?'trace-loss-none':Number(h.loss_percent)>=50?'trace-loss-bad':Number(h.loss_percent)>0?'trace-loss-warn':''; + const rowClass=traceHopRowClass(h); + return `${h.hop}
${esc(ip)}${h.reached?' ✓':''}
${esc(location)}${esc(traceMs(h.avg_ms))}${esc(deltaText)}${esc(loss)}`; + }).join(''):`${esc(t('trace.no_reply','No reply'))}`; + renderNetworkTraceMap(visibleHops,data.target_geo,data.target_ip); + } + async function runNetworkTrace(event){ + event?.preventDefault(); + const button=$('network-trace-button'),target=$('network-trace-target'),geo=$('network-trace-geolocate'); + if(!target||!button)return; + const value=String(target.value||'').trim(); if(!value)return; + button.disabled=true; + $('network-trace-results')?.setAttribute('hidden',''); + operationStatus('network-trace-status',t('trace.running','Running ping and traceroute… This can take up to a minute.'),'working'); + try{ + const r=await fetch('/api/network/trace',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({target:value,geolocate:!!geo?.checked,language:window.WGToolsI18n?.getLanguage?.()||'en'})}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||t('trace.failed','Network trace failed')); + renderNetworkTrace(d); + let message=t('trace.done','Network trace completed.'); if(d.geo_partial)message+=` ${t('trace.partial_geo','Some public hops could not be geolocated.')}`; + operationStatus('network-trace-status',message,(d.reached||d.ping?.reachable)?'success':'info'); + }catch(e){operationStatus('network-trace-status',e.message||t('trace.failed','Network trace failed'),'error');} + finally{button.disabled=false;} + } + + async function diagnostics(){ + const b=$('diagnostics-button'); if(b)b.disabled=true; + try{const r=await fetch('/api/diagnostics',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderDiagnostics(d.diagnostics||[]);toast(t('server.diagnostics_done','Diagnostics completed'));} + catch(e){toast(e.message);}finally{if(b)b.disabled=false;} + } + + async function installWireGuard(){ + const b=$('install-wireguard-button'); if(!b)return; + b.disabled=true; operationStatus('install-status',t('server.installing','Installing WireGuard… This may take a minute.'),'working'); + try{ + const r=await fetch('/api/server/install',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'}); + const d=await r.json(); if(!r.ok) throw new Error(d.error||'Installation failed'); + operationStatus('install-status',d.message||t('server.install_success','WireGuard installed successfully.'),'success'); + toast(t('server.install_success','WireGuard installed successfully.')); + await fetchSnapshot(); + }catch(e){ operationStatus('install-status',e.message,'error'); toast(e.message); } + finally{ b.disabled=false; } + } + + function ipToInt(ip){ + const parts=String(ip).split('.').map(Number); if(parts.length!==4||parts.some(x=>!Number.isInteger(x)||x<0||x>255)) return null; + return (((parts[0]<<24)>>>0)+((parts[1]<<16)>>>0)+((parts[2]<<8)>>>0)+parts[3])>>>0; + } + function intToIp(n){ return [n>>>24,(n>>>16)&255,(n>>>8)&255,n&255].join('.'); } + function firstHostFromCidr(cidr){ + const [ip,prefixRaw]=String(cidr).trim().split('/'); const prefix=Number(prefixRaw); const n=ipToInt(ip); + if(n===null||!Number.isInteger(prefix)||prefix<0||prefix>30)return null; + const mask=prefix===0?0:((0xffffffff << (32-prefix))>>>0); const network=(n&mask)>>>0; return `${intToIp((network+1)>>>0)}/${prefix}`; + } + function syncServerAddress(){ const net=$('setup-vpn-network'),addr=$('setup-server-address'); if(!net||!addr||addr.dataset.touched)return; const first=firstHostFromCidr(net.value); if(first)addr.value=first; } + + async function createServer(event){ + event.preventDefault(); + const b=$('create-server-button'); if(!b)return; + const payload={ + display_name:$('setup-display-name').value.trim(), + vpn_network:$('setup-vpn-network').value.trim(), + server_address:$('setup-server-address').value.trim(), + listen_port:Number($('setup-port').value), + mtu:Number($('setup-mtu').value||0), + uplink_interface:$('setup-uplink').value.trim(), + gateway:$('setup-gateway').value.trim(), + local_network:$('setup-local-network').value.trim(), + policy_table:$('setup-policy-table').value.trim(), + nat_enabled:$('setup-nat').checked, + ip_forwarding:$('setup-forwarding').checked, + }; + const ok=confirm(t('server.create_confirm','Create and start the WireGuard server with these settings?')); + if(!ok)return; + b.disabled=true; operationStatus('create-status',t('server.creating','Generating keys, writing configuration and starting WireGuard…'),'working'); + try{ + const r=await fetch('/api/server/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||'Server creation failed'); + operationStatus('create-status',d.message||t('server.create_success','WireGuard server created successfully.'),'success'); + toast(t('server.create_success','WireGuard server created successfully.')); + await fetchInterfaces(true); + await fetchSnapshot(); + }catch(e){ const message=localizedServerError(e.message); operationStatus('create-status',message,'error'); toast(message); } + finally{ b.disabled=false; } + } + + function renderSettings(d){ + const button=$('raw-config-button'); + if(button) button.disabled=!d.wireguard?.config_exists; + if($('settings-backup-count')) $('settings-backup-count').textContent=String(d.backups?.count??0); + if($('settings-last-backup')) $('settings-last-backup').textContent=d.backups?.latest_modified_at?formatDate(d.backups.latest_modified_at):t('settings.no_backups','No backups yet'); + } + + function highlightWireGuardConfig(text){ + return String(text||'').split('\n').map(line=>{ + if(/^\s*[#;]/.test(line)) return `${esc(line)}`; + if(/^\s*\[[^\]]+\]\s*$/.test(line)) return `${esc(line)}`; + const match=line.match(/^(\s*)([A-Za-z][A-Za-z0-9]*)(\s*=\s*)(.*)$/); + if(match){ + return `${esc(match[1])}${esc(match[2])}${esc(match[3])}${esc(match[4])}`; + } + return esc(line); + }).join('\n')+'\n'; + } + + function updateRawConfigHighlight(){ + const textarea=$('raw-config-text'), pre=$('raw-config-highlight'); if(!textarea||!pre)return; + pre.innerHTML=highlightWireGuardConfig(textarea.value); + pre.scrollTop=textarea.scrollTop; pre.scrollLeft=textarea.scrollLeft; + } + + async function loadRawConfig(){ + const button=$('raw-config-button'); if(button)button.disabled=true; + operationStatus('raw-config-status',t('settings.loading_config','Loading configuration…'),'working'); + try{ + const r=await fetch('/api/server/config/raw',{cache:'no-store'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||t('settings.config_load_failed','Could not load configuration')); + $('raw-config-text').value=d.content||''; $('raw-config-path').textContent=d.path||`/etc/wireguard/${snapshot?.interface||'wg0'}.conf`; + updateRawConfigHighlight(); operationStatus('raw-config-status',''); modalShow('raw-config-modal',true); setTimeout(()=>$('raw-config-text')?.focus(),30); + }catch(e){operationStatus('raw-config-status',e.message,'error');toast(e.message);}finally{if(button)button.disabled=!snapshot?.wireguard?.config_exists;} + } + + async function applyRawConfig(){ + const textarea=$('raw-config-text'), button=$('apply-raw-config-button'); if(!textarea||!button)return; + const ok=confirm(t('settings.raw_config_confirm','Save this WireGuard configuration and apply it now? The selected interface will be restarted. A backup is created first and WGTools will roll back automatically if the new configuration does not start.')); + if(!ok)return; + button.disabled=true; operationStatus('raw-config-status',t('settings.applying_config','Validating configuration, creating backup and applying…'),'working'); + try{ + const r=await fetch('/api/server/config/apply',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({content:textarea.value})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||t('settings.config_apply_failed','Configuration could not be applied')); + await fetchSnapshot(false); + const message=d.restarted?t('settings.config_applied_restarted','Configuration applied and WireGuard restarted.'):t('settings.config_applied_stopped','Configuration saved. WireGuard remains stopped.'); + operationStatus('raw-config-status',''); modalShow('raw-config-modal',false); toast(message,4200); + }catch(e){operationStatus('raw-config-status',e.message,'error');toast(e.message);}finally{button.disabled=false;} + } + + function bindRawConfigEditor(){ + $('raw-config-button')?.addEventListener('click',loadRawConfig); + $('reload-raw-config-button')?.addEventListener('click',loadRawConfig); + $('apply-raw-config-button')?.addEventListener('click',applyRawConfig); + const textarea=$('raw-config-text'); + if(textarea){ + textarea.addEventListener('input',updateRawConfigHighlight); + textarea.addEventListener('scroll',updateRawConfigHighlight); + textarea.addEventListener('keydown',e=>{ + if(e.key==='Tab'){ + e.preventDefault(); const start=textarea.selectionStart, end=textarea.selectionEnd; textarea.setRangeText(' ',start,end,'end'); updateRawConfigHighlight(); + } + }); + } + } + + function formatDate(ts){ + const n=Number(ts||0); if(!n)return t('settings.never_logged_in','Never'); + try{return new Intl.DateTimeFormat(window.WGToolsI18n?.getLanguage?.()==='ru'?'ru-RU':'en-GB',{dateStyle:'medium',timeStyle:'short'}).format(new Date(n*1000));} + catch(_){return new Date(n*1000).toLocaleString();} + } + + async function loadUsers(){ + const body=$('users-table-body'); if(!body)return; + try{ + const r=await fetch('/api/users',{cache:'no-store'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + const users=d.users||[]; const current=Number(d.current_user_id||0); const mailConfigured=Boolean(d.mail_configured); + body.innerHTML=users.map(u=>{ + const email=String(u.email||''); + const isCurrent=Number(u.id)===current; + const mfaEnabled=Boolean(u.mfa_enabled); + const resetDisabled=!mailConfigured||!email; + const resetTitle=!mailConfigured?t('settings.user_reset_mail_not_configured','Configure and enable mail first.'):(!email?t('settings.user_reset_email_missing','Add an email address first.'):''); + const mfaBadge=mfaEnabled?`${esc(t('settings.mfa_enabled','Enabled'))}`:`${esc(t('settings.mfa_disabled','Disabled'))}`; + const mfaButton=isCurrent?``:''; + return `
${esc(u.username)}
${isCurrent?`
${esc(t('settings.current_user','Current user'))}
`:''}${email?esc(email):'—'}${mfaBadge}${esc(formatDate(u.created_at))}${esc(formatDate(u.last_login))}
${mfaButton}
`; + }).join('') || `—`; + }catch(e){body.innerHTML=`${esc(e.message)}`;} + } + + function openAddUser(){ + $('user-form')?.reset(); operationStatus('user-form-status',''); modalShow('user-modal',true); setTimeout(()=>$('new-user-name')?.focus(),30); + } + + async function createUser(event){ + event.preventDefault(); const password=$('new-user-password').value; const repeat=$('new-user-password-repeat').value; + if(password!==repeat){operationStatus('user-form-status',t('settings.passwords_mismatch','Passwords do not match.'),'error');return;} + const button=event.currentTarget.querySelector('button[type="submit"]'); button.disabled=true; + try{ + const r=await fetch('/api/users',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:$('new-user-name').value.trim(),email:$('new-user-email')?.value.trim()||'',password})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + modalShow('user-modal',false); toast(t('settings.user_created_ok','User created.')); await loadUsers(); + }catch(e){operationStatus('user-form-status',e.message,'error');}finally{button.disabled=false;} + } + + function openPasswordUser(id,name){ + $('password-form')?.reset(); $('password-user-id').value=String(id); $('password-user-name').textContent=name; operationStatus('password-form-status',''); modalShow('password-modal',true); setTimeout(()=>$('password-new')?.focus(),30); + } + + async function saveUserPassword(event){ + event.preventDefault(); const password=$('password-new').value; const repeat=$('password-repeat').value; + if(password!==repeat){operationStatus('password-form-status',t('settings.passwords_mismatch','Passwords do not match.'),'error');return;} + const id=Number($('password-user-id').value); const button=event.currentTarget.querySelector('button[type="submit"]'); button.disabled=true; + try{ + const r=await fetch(`/api/users/${id}/password`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({password})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + modalShow('password-modal',false); toast(t('settings.password_changed','Password changed.')); + if(d.reauthenticate){setTimeout(()=>location.replace(appUrl('/login')),450);} + }catch(e){operationStatus('password-form-status',e.message,'error');}finally{button.disabled=false;} + } + + function openEmailUser(id,name,email){ + $('email-form')?.reset(); $('email-user-id').value=String(id); $('email-user-name').textContent=name; $('email-new').value=email||''; operationStatus('email-form-status',''); modalShow('email-modal',true); setTimeout(()=>$('email-new')?.focus(),30); + } + + async function saveUserEmail(event){ + event.preventDefault(); const id=Number($('email-user-id').value); const button=event.currentTarget.querySelector('button[type="submit"]'); if(button)button.disabled=true; + try{ + const r=await fetch(`/api/users/${id}/email`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:$('email-new').value.trim()})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + modalShow('email-modal',false); toast(t('settings.user_email_saved','E-mail saved.')); await loadUsers(); + }catch(e){operationStatus('email-form-status',e.message,'error');}finally{if(button)button.disabled=false;} + } + + async function sendUserPasswordReset(id,name,email){ + const template=t('settings.user_reset_confirm','Send a password reset code to {name} at {email}?'); + if(!confirm(template.replace('{name}',name).replace('{email}',email)))return; + try{ + const r=await fetch(`/api/users/${id}/password-reset`,{method:'POST'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + toast(t('settings.user_reset_sent','Password reset code sent to {email}.').replace('{email}',d.masked_email||email),4200); + }catch(e){toast(e.message,4200);} + } + + async function deleteUser(id,name){ + const template=t('settings.delete_user_confirm','Delete user {name}?'); if(!confirm(template.replace('{name}',name)))return; + try{const r=await fetch(`/api/users/${id}`,{method:'DELETE'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');toast(t('settings.user_deleted','User deleted.'));await loadUsers();}catch(e){toast(e.message);} + } + + function mfaErrorText(message){ + const value=String(message||''); + const map={ + 'Invalid current password':t('settings.mfa_error_password','Invalid current password.'), + 'Invalid authentication code':t('settings.mfa_error_code','Invalid authentication code.'), + 'MFA is already enabled':t('settings.mfa_error_already_enabled','MFA is already enabled.'), + 'MFA is not enabled':t('settings.mfa_error_not_enabled','MFA is not enabled.'), + 'MFA setup has not been started':t('settings.mfa_error_not_started','Start MFA setup again.'), + }; + return map[value]||value; + } + + function setMfaMode(enabled,recoveryRemaining=0){ + const disabled=$('mfa-disabled-panel'), active=$('mfa-enabled-panel'); + if(disabled)disabled.hidden=Boolean(enabled); + if(active)active.hidden=!enabled; + const remain=$('mfa-recovery-remaining'); + if(remain)remain.textContent=t('settings.mfa_recovery_remaining','Recovery codes remaining: {count}').replace('{count}',String(Number(recoveryRemaining||0))); + } + + function showMfaRecoveryCodes(codes){ + const list=Array.isArray(codes)?codes:[]; + const panel=$('mfa-recovery-panel'), pre=$('mfa-recovery-codes'); + if(pre)pre.textContent=list.join('\n'); + if(panel)panel.hidden=list.length===0; + } + + function openMfaUser(id,name,enabled,recoveryRemaining){ + $('mfa-user-name').textContent=name; + $('mfa-modal').dataset.userId=String(id); + $('mfa-setup-password').value=''; $('mfa-confirm-code').value=''; + $('mfa-manage-password').value=''; $('mfa-manage-code').value=''; + $('mfa-start-button').hidden=false; $('mfa-qr-image').removeAttribute('src'); $('mfa-secret').textContent=''; + $('mfa-setup-details').hidden=true; showMfaRecoveryCodes([]); + operationStatus('mfa-form-status',''); setMfaMode(enabled,recoveryRemaining); + modalShow('mfa-modal',true); + setTimeout(()=>$(enabled?'mfa-manage-password':'mfa-setup-password')?.focus(),30); + } + + async function startMfaSetup(){ + const button=$('mfa-start-button'); if(button)button.disabled=true; operationStatus('mfa-form-status',''); + try{ + const r=await fetch('/api/users/mfa/setup',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({password:$('mfa-setup-password').value})}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + $('mfa-qr-image').src=d.qr||''; $('mfa-secret').textContent=d.secret||''; $('mfa-setup-details').hidden=false; + $('mfa-start-button').hidden=true; setTimeout(()=>$('mfa-confirm-code')?.focus(),30); + }catch(e){operationStatus('mfa-form-status',mfaErrorText(e.message),'error');}finally{if(button)button.disabled=false;} + } + + async function confirmMfaSetup(){ + const button=$('mfa-confirm-button'); if(button)button.disabled=true; operationStatus('mfa-form-status',''); + try{ + const r=await fetch('/api/users/mfa/confirm',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code:$('mfa-confirm-code').value.trim()})}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + setMfaMode(true,(d.recovery_codes||[]).length); showMfaRecoveryCodes(d.recovery_codes||[]); + $('mfa-setup-details').hidden=true; $('mfa-start-button').hidden=false; + toast(t('settings.mfa_enabled_ok','MFA enabled.')); await loadUsers(); + }catch(e){operationStatus('mfa-form-status',mfaErrorText(e.message),'error');}finally{if(button)button.disabled=false;} + } + + function mfaManagePayload(){return {password:$('mfa-manage-password').value,code:$('mfa-manage-code').value.trim()};} + + async function disableMfa(){ + if(!confirm(t('settings.mfa_disable_confirm','Disable two-factor authentication for this account?')))return; + const button=$('mfa-disable-button'); if(button)button.disabled=true; operationStatus('mfa-form-status',''); + try{ + const r=await fetch('/api/users/mfa/disable',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(mfaManagePayload())}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + setMfaMode(false,0); showMfaRecoveryCodes([]); $('mfa-start-button').hidden=false; $('mfa-setup-password').value=''; + toast(t('settings.mfa_disabled_ok','MFA disabled.')); await loadUsers(); + }catch(e){operationStatus('mfa-form-status',mfaErrorText(e.message),'error');}finally{if(button)button.disabled=false;} + } + + async function regenerateMfaRecovery(){ + if(!confirm(t('settings.mfa_regenerate_confirm','Replace all existing recovery codes?')))return; + const button=$('mfa-regenerate-button'); if(button)button.disabled=true; operationStatus('mfa-form-status',''); + try{ + const r=await fetch('/api/users/mfa/recovery-codes',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(mfaManagePayload())}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + showMfaRecoveryCodes(d.recovery_codes||[]); setMfaMode(true,(d.recovery_codes||[]).length); + $('mfa-manage-code').value=''; toast(t('settings.mfa_recovery_regenerated','New recovery codes created.')); await loadUsers(); + }catch(e){operationStatus('mfa-form-status',mfaErrorText(e.message),'error');}finally{if(button)button.disabled=false;} + } + + async function copyMfaRecovery(){ + const text=$('mfa-recovery-codes')?.textContent||''; if(!text)return; + try{ + if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(text); + else throw new Error('clipboard unavailable'); + toast(t('common.copied','Copied.')); return; + }catch(_){ + try{const area=document.createElement('textarea');area.value=text;area.style.position='fixed';area.style.opacity='0';document.body.appendChild(area);area.focus();area.select();const ok=document.execCommand('copy');area.remove();if(!ok)throw new Error('copy failed');toast(t('common.copied','Copied.'));return;}catch(__){} + } + toast(t('common.copy_failed','Copy failed.')); + } + + async function logout(){ + try{await fetch('/api/auth/logout',{method:'POST'});}finally{location.replace(appUrl('/login'));} + } + + function bindUserManagement(){ + $('branding-form')?.addEventListener('submit', async e=>{ + e.preventDefault(); + try { + const file=$('branding-logo').files[0]; + let logo=$('branding-reset-logo').checked?'':$('branding-current-logo').value; + if(file){ + if(file.type!=='image/png'||file.size>300000)throw new Error('Wybierz plik PNG o rozmiarze do 300 KB.'); + logo=await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=()=>reject(new Error('Nie udało się odczytać logo.'));reader.readAsDataURL(file);}); + } + const r=await fetch(appUrl('/api/branding'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:$('branding-name').value,color:$('branding-color').value,logo})}); + const data=await r.json(); if(!r.ok)throw new Error(data.error||'Nie udało się zapisać.'); + location.reload(); + } catch(err){operationStatus('branding-status',err.message,'error');} + }); + $('add-user-button')?.addEventListener('click',openAddUser); $('user-form')?.addEventListener('submit',createUser); $('password-form')?.addEventListener('submit',saveUserPassword); $('email-form')?.addEventListener('submit',saveUserEmail); $('logout-button')?.addEventListener('click',logout); + $('mfa-start-button')?.addEventListener('click',startMfaSetup); $('mfa-confirm-button')?.addEventListener('click',confirmMfaSetup); $('mfa-disable-button')?.addEventListener('click',disableMfa); $('mfa-regenerate-button')?.addEventListener('click',regenerateMfaRecovery); $('mfa-copy-recovery-button')?.addEventListener('click',copyMfaRecovery); + $('users-table-body')?.addEventListener('click',async e=>{const b=e.target.closest('[data-user-action]');if(!b||b.disabled)return;const id=Number(b.dataset.userId),name=b.dataset.userName||'',email=b.dataset.userEmail||'';if(b.dataset.userAction==='access'){ + const roleInput=prompt('Rola: administrator albo użytkownik',b.dataset.role==='admin'?'administrator':'użytkownik'); if(roleInput===null)return; + const role=({administrator:'admin',użytkownik:'user',admin:'admin',user:'user'})[roleInput.trim().toLowerCase()]||roleInput.trim(); + const interfaces=prompt('Dozwolone interfejsy, oddzielone przecinkami (np. wg1, wg2)',b.dataset.interfaces||''); if(interfaces===null)return; + const names=interfaces.split(',').map(s=>s.trim()).filter(Boolean), permissions={}; + let previous={};try{previous=JSON.parse(b.dataset.permissions||'{}');}catch(_){} + if(role==='user')for(const iface of names){ + const labels={add:'dodawanie',edit:'edycja',forward:'porty'}, reverse={dodawanie:'add',edycja:'edit',porty:'forward'}; + const defaults=(previous[iface]||['add','edit','forward']).map(x=>labels[x]||x).join(', '); + const answer=prompt(`Uprawnienia dla ${iface}: dodawanie, edycja, porty (oddziel przecinkami; puste = tylko podgląd)`,defaults);if(answer===null)return; + permissions[iface]=answer.split(',').map(x=>x.trim().toLowerCase()).filter(Boolean).map(x=>reverse[x]||x); + } else for(const iface of names)permissions[iface]=[]; + try{const r=await fetch(appUrl(`/api/users/${id}/access`),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({role,interfaces:names,permissions})});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadUsers();}catch(err){alert(err.message);} + }else if(b.dataset.userAction==='mfa')openMfaUser(id,name,b.dataset.mfaEnabled==='1',Number(b.dataset.mfaRecovery||0));else if(b.dataset.userAction==='password')openPasswordUser(id,name);else if(b.dataset.userAction==='email')openEmailUser(id,name,email);else if(b.dataset.userAction==='reset')sendUserPasswordReset(id,name,email);else if(b.dataset.userAction==='delete')deleteUser(id,name);}); + if(page==='settings')loadUsers(); + } + + function auditActionLabel(action){ + const key=`audit.action.${String(action||'').replace(/[^a-z0-9_.-]/gi,'_')}`; + return t(key,String(action||'—').replace(/[._-]+/g,' ')); + } + + function auditResultLabel(result){ + const value=String(result||'—'); + const lower=value.toLocaleLowerCase(); + if(lower.startsWith('endpoint '))return `${t('audit.result.endpoint','Endpoint')} ${value.slice(9)}`; + if(lower.startsWith('error:'))return `${t('audit.result.error','Error')}: ${value.slice(value.indexOf(':')+1).trim()}`; + const key=`audit.result.${value.replace(/[^a-z0-9_.-]/gi,'_')}`; + return t(key,value); + } + + let auditItems=[]; + let auditLoaded=false; + let auditLoadPromise=null; + let auditAutoRefreshTimer=null; + + function auditRefreshSeconds(){ + const value=Number($('audit-modal')?.dataset.refreshSeconds||5); + return Number.isFinite(value)?Math.max(2,Math.min(value,60)):5; + } + function stopAuditAutoRefresh(){ + if(auditAutoRefreshTimer){clearInterval(auditAutoRefreshTimer);auditAutoRefreshTimer=null;} + } + function startAuditAutoRefresh(){ + stopAuditAutoRefresh(); + const interval=auditRefreshSeconds()*1000; + auditAutoRefreshTimer=setInterval(()=>{ + const modal=$('audit-modal'); + if(!modal||modal.hidden){stopAuditAutoRefresh();return;} + loadAudit({showLoading:false}); + },interval); + } + + function auditTone(item){ + const action=String(item?.action||'').toLocaleLowerCase(), result=String(item?.result||'').toLocaleLowerCase(); + if(action==='wireguard.client_connected')return 'connection'; + if(/failed|deleted|stopped|detached/.test(action)||/failed|error|invalid|denied/.test(result))return 'danger'; + if(/created|started|installed|restored|completed|auth\.login$/.test(action))return 'success'; + if(/updated|applied|changed|rotated|scheduled|restarted/.test(action))return 'warning'; + return 'info'; + } + + function compactAuditUsername(username){ + const value=String(username||'system'); + if(value.startsWith('Telegram ·'))return `${t('audit.user.telegram_short','TG')} ·${value.slice('Telegram ·'.length)}`; + return value; + } + + function syncAuditSearchClear(){ + const clear=$('audit-quick-search-clear'); + if(clear)clear.hidden=!String($('audit-quick-search')?.value||'').length; + } + + function renderAudit(){ + const body=$('audit-table-body'); if(!body)return; + const query=String($('audit-quick-search')?.value||'').trim().toLocaleLowerCase(); + const items=query?auditItems.filter(item=>{ + const haystack=[formatDate(item.created_at),item.username,compactAuditUsername(item.username),auditActionLabel(item.action),item.action,item.object,auditResultLabel(item.result),item.result].map(value=>String(value||'').toLocaleLowerCase()).join(' '); + return haystack.includes(query); + }):auditItems; + syncAuditSearchClear(); + if(!auditItems.length){body.innerHTML=`${esc(t('settings.audit_empty','No audit events yet'))}`;return;} + if(!items.length){body.innerHTML=`${esc(t('settings.audit_search_empty','No audit events match the search'))}`;return;} + body.innerHTML=items.map(item=>{ + const tone=auditTone(item); + const rawUsername=item.username||'system', username=compactAuditUsername(rawUsername), userClass=rawUsername==='system'?'system':'user'; + return `${esc(formatDate(item.created_at))}${esc(username)}${esc(auditActionLabel(item.action))}${esc(item.object||'—')}${esc(auditResultLabel(item.result))}`; + }).join(''); + } + + async function loadAudit({showLoading=true}={}){ + const body=$('audit-table-body'); if(!body)return; + if(auditLoadPromise)return auditLoadPromise; + if(showLoading&&!auditLoaded)body.innerHTML=`${esc(t('common.loading','Loading…'))}`; + auditLoadPromise=(async()=>{ + try{ + const r=await fetch('/api/audit?limit=1000',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); + auditItems=d.items||[];auditLoaded=true;renderAudit(); + }catch(e){ + if(showLoading||!auditLoaded)body.innerHTML=`${esc(e.message)}`; + }finally{auditLoadPromise=null;} + })(); + return auditLoadPromise; + } + + function bindAudit(){ + const search=$('audit-quick-search'), clear=$('audit-quick-search-clear'); + const openAudit=()=>{ + modalShow('audit-modal'); + if(auditLoaded)renderAudit();else loadAudit(); + startAuditAutoRefresh(); + }; + $('audit-log-button')?.addEventListener('click',openAudit); + $('topbar-audit-button')?.addEventListener('click',openAudit); + $('audit-refresh-button')?.addEventListener('click',()=>loadAudit({showLoading:false})); + search?.addEventListener('input',renderAudit); + clear?.addEventListener('click',()=>{if(!search)return;search.value='';syncAuditSearchClear();search.focus();renderAudit();}); + syncAuditSearchClear(); + if(page==='settings')loadAudit({showLoading:false}); + } + + let mailState = null; + + function renderMailSettings(data){ + mailState=data||{}; + if($('mail-enabled'))$('mail-enabled').checked=Boolean(data?.enabled); + if($('mail-smtp-host'))$('mail-smtp-host').value=data?.smtp_host||''; + if($('mail-smtp-port'))$('mail-smtp-port').value=Number(data?.smtp_port||587); + if($('mail-security'))$('mail-security').value=data?.security||'starttls'; + if($('mail-username'))$('mail-username').value=data?.username||''; + if($('mail-password')){$('mail-password').value='';$('mail-password').placeholder=data?.password_masked||'';} + if($('mail-from-name'))$('mail-from-name').value=data?.from_name||'WGTools'; + const remove=$('mail-remove-password-button');if(remove)remove.disabled=!data?.password_configured; + const badge=$('mail-status-badge'); + if(badge){ + let label=t('settings.mail_not_configured','Not configured'),cls='badge'; + if(data?.enabled&&data?.configured){label=t('settings.mail_enabled_badge','Enabled');cls='badge managed';} + else if(data?.configured){label=t('settings.mail_disabled_badge','Disabled');cls='badge';} + badge.className=cls;badge.textContent=label; + } + } + + async function loadMailSettings(){ + if(page!=='settings'||!$('mail-settings-form'))return; + try{const r=await fetch('/api/mail/settings',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderMailSettings(d.settings||{});} + catch(e){operationStatus('mail-settings-status',e.message,'error');} + } + + async function saveMailSettings(event){ + event.preventDefault();const button=event.currentTarget.querySelector('button[type="submit"]');if(button)button.disabled=true;operationStatus('mail-settings-status',t('settings.saving','Saving settings…'),'working'); + try{ + const username=$('mail-username')?.value.trim()||''; + const payload={enabled:Boolean($('mail-enabled')?.checked),smtp_host:$('mail-smtp-host')?.value.trim()||'',smtp_port:Number($('mail-smtp-port')?.value||587),security:$('mail-security')?.value||'starttls',username,password:$('mail-password')?.value||'',clear_password:false,from_email:username||(mailState?.from_email||''),from_name:$('mail-from-name')?.value.trim()||'WGTools'}; + const r=await fetch('/api/mail/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); + renderMailSettings(d.settings||{});operationStatus('mail-settings-status',t('settings.mail_saved','Mail settings saved.'),'success');toast(t('settings.mail_saved','Mail settings saved.'));await loadUsers(); + }catch(e){operationStatus('mail-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} + } + + async function removeMailPassword(){ + if(!confirm(t('settings.mail_remove_password_confirm','Remove the saved SMTP password?')))return; + const current=mailState||{}; + try{ + const payload={enabled:false,smtp_host:current.smtp_host||'',smtp_port:Number(current.smtp_port||587),security:current.security||'starttls',username:current.username||'',password:'',clear_password:true,from_email:current.username||current.from_email||'',from_name:current.from_name||'WGTools'}; + const r=await fetch('/api/mail/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderMailSettings(d.settings||{});operationStatus('mail-settings-status',t('settings.mail_password_removed','SMTP password removed and mail disabled.'),'success');await loadUsers(); + }catch(e){operationStatus('mail-settings-status',e.message,'error');} + } + + async function testMail(){ + const recipient=$('mail-test-recipient')?.value.trim()||'';if(!recipient){operationStatus('mail-settings-status',t('settings.mail_test_recipient_required','Enter a test recipient email.'),'error');return;} + const button=$('mail-test-button');if(button)button.disabled=true;operationStatus('mail-settings-status',t('settings.mail_testing','Sending a test email…'),'working'); + try{const r=await fetch('/api/mail/test',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({recipient})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');operationStatus('mail-settings-status',t('settings.mail_test_ok','Test email sent successfully.'),'success');toast(t('settings.mail_test_ok','Test email sent successfully.'));} + catch(e){operationStatus('mail-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} + } + + function defaultSmtpPort(security){ + if(security==='tls')return 465; + if(security==='none')return 25; + return 587; + } + + function bindMailSettings(){ + $('mail-settings-form')?.addEventListener('submit',saveMailSettings); + $('mail-test-button')?.addEventListener('click',testMail); + $('mail-remove-password-button')?.addEventListener('click',removeMailPassword); + $('mail-security')?.addEventListener('change',event=>{ + const port=$('mail-smtp-port'); + if(port)port.value=String(defaultSmtpPort(event.currentTarget.value)); + }); + if(page==='settings')loadMailSettings(); + } + + let httpsState = null; + + function normalizedHttpsAccessPath(value){ + const core=String(value||'').trim().replace(/^\/+|\/+$/g,''); + return core?`/${core}/`:''; + } + function httpsPayload(){ + return { + target_type:$('https-target-type')?.value||'domain', + target:$('https-target')?.value.trim()||'', + email:$('https-email')?.value.trim()||'', + https_port:Number($('https-port')?.value||443), + access_path:normalizedHttpsAccessPath($('https-access-path')?.value||''), + }; + } + function httpsUrlHost(value){const host=String(value||'').trim().replace(/^\[|\]$/g,'');return host.includes(':')?`[${host}]`:host;} + function httpsOrigin(host,port){const p=Number(port||443);return `https://${httpsUrlHost(host)}${p===443?'':`:${p}`}`;} + function httpsPanelUrl(host,port,path,suffix=''){return `${httpsOrigin(host,port)}${normalizedHttpsAccessPath(path)}${String(suffix||'').replace(/^\//,'')}`;} + + function usePanelHostForHttps(){ + const field=$('https-target'),type=$('https-target-type'); + if(!field)return; + const host=String(location.hostname||'').replace(/^\[|\]$/g,''); + if(!host)return; + field.value=host; + if(type){ + const isIpv4=/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host); + const isIpv6=host.includes(':'); + type.value=(isIpv4||isIpv6)?'ip':'domain'; + field.placeholder=type.value==='ip'?'203.0.113.10':'wg.example.com'; + } + } + + function httpsReconnectUrl(payload,suffix='settings#https'){ + return httpsPanelUrl(payload.target||location.hostname,payload.https_port||443,payload.access_path||'',suffix); + } + + const wait = ms => new Promise(resolve=>setTimeout(resolve,ms)); + + async function currentPanelInstance(){ + try{ + const r=await fetch('/healthz',{cache:'no-store'}); + if(!r.ok)return ''; + const d=await r.json(); + return String(d?.instance||''); + }catch(_){return '';} + } + + async function waitForHttpsReady(payload,previousInstance='',timeoutMs=35000){ + const health=httpsPanelUrl(payload.target||location.hostname,payload.https_port||443,payload.access_path||'','healthz'); + const deadline=Date.now()+Math.max(5000,Number(timeoutMs||35000)); + while(Date.now()null); + const instance=String(d?.instance||''); + if(d?.ok && (!previousInstance || (instance && instance!==previousInstance)))return true; + } + }catch(_){} + await wait(650); + } + return false; + } + + async function reconnectAfterHttpsSwitch(payload,previousInstance='',initialDelay=4800){ + const destination=httpsReconnectUrl(payload); + // The privileged helper schedules a guarded service restart after the API + // response has had time to flush. Do not navigate on a fixed timer: the + // first browser request can otherwise hit the old route (404) or the TLS + // socket while Uvicorn is still coming up (PR_END_OF_FILE_ERROR). + await wait(Math.max(0,Number(initialDelay||0))); + await waitForHttpsReady(payload,previousInstance); + location.replace(destination); + } + + function httpsPortLabel(item,port){ + if(!item)return '—'; + if(item.free)return t('settings.https_port_free','Free'); + if(item.wgtools)return 'WGTools'; + return `${t('settings.https_port_busy','Busy')}${item.owner?` · ${item.owner}`:''}`; + } + + function renderHttpsPorts(ports,httpsPort){ + const port=Number(httpsPort||$('https-port')?.value||443),p80=ports?.['80'],panel=ports?.[String(port)]; + const e80=$('https-port-80'),ep=$('https-panel-port'),label=$('https-panel-port-label'); + if(label)label.textContent=`TCP ${port}`; + if(e80){e80.textContent=httpsPortLabel(p80,80);e80.className=p80?.free?'text-ok':'text-warn';} + if(ep){const ok=Boolean(panel?.free||panel?.wgtools);ep.textContent=httpsPortLabel(panel,port);ep.className=ok?'text-ok':'text-warn';} + } + + function httpsCertificateMatchesTarget(cert,targetType,target){ + if(!cert?.exists||!target)return false; + const expires=Number(cert?.expires_at||0); + if(!expires||expires<=Math.floor(Date.now()/1000)+300)return false; + const wanted=String(target||'').trim(); + const sans=Array.isArray(cert?.sans)?cert.sans:[]; + if(targetType==='ip')return sans.some(item=>String(item||'').trim()===wanted); + const normalized=wanted.replace(/\.$/,'').toLowerCase(); + return sans.some(item=>String(item||'').trim().replace(/\.$/,'').toLowerCase()===normalized); + } + + function httpsEnableRequirement(){ + const cert=httpsState?.certificate||{},payload=httpsPayload(); + if(!cert.exists)return {ready:false,message:t('settings.https_enable_need_certificate','First obtain a certificate.')}; + if(Number(cert.expires_at||0)<=Math.floor(Date.now()/1000)+300)return {ready:false,message:t('settings.https_enable_certificate_expired','The certificate has expired. Renew it before enabling HTTPS.')}; + if(!httpsCertificateMatchesTarget(cert,payload.target_type,payload.target))return {ready:false,message:t('settings.https_enable_certificate_mismatch','Obtain a certificate for the current domain/public IP first.')}; + return {ready:true,message:t('settings.https_enable_certificate_ready','Certificate is ready. Built-in HTTPS can now be enabled.')}; + } + + function syncHttpsEnableAvailability(){ + const checkbox=$('https-enabled'),help=$('https-enable-help'),certState=$('https-certificate-state'); + if(!checkbox)return; + const cert=httpsState?.certificate||{},payload=httpsPayload(); + const expired=Boolean(cert.exists&&Number(cert.expires_at||0)<=Math.floor(Date.now()/1000)+300); + const matches=Boolean(cert.exists&&!expired&&httpsCertificateMatchesTarget(cert,payload.target_type,payload.target)); + if(certState){ + if(!cert.exists)certState.textContent=t('settings.https_certificate_missing','Not issued'); + else if(expired)certState.textContent=t('settings.https_certificate_expired','Expired'); + else if(!matches)certState.textContent=t('settings.https_certificate_wrong_target','For another address'); + else certState.textContent=t('settings.https_certificate_ready','Ready'); + } + if(httpsState?.enabled){ + checkbox.disabled=false; + if(help)help.textContent=t('settings.https_enable_active_help','Clear the checkbox and save to return to HTTP.'); + return; + } + const requirement=httpsEnableRequirement(); + checkbox.disabled=!requirement.ready; + checkbox.checked=false; + if(help)help.textContent=requirement.message; + } + + function localizedHttpsError(message){ + const raw=String(message||''); + if(raw.includes("Obtain a Let's Encrypt certificate before enabling HTTPS"))return t('settings.https_enable_need_certificate','First obtain a certificate.'); + if(raw.includes('existing certificate does not contain the requested domain/IP')||raw.includes('existing certificate belongs to a different domain/IP'))return t('settings.https_enable_certificate_mismatch','Obtain a certificate for the current domain/public IP first.'); + if(raw.includes('existing certificate is expired'))return t('settings.https_enable_certificate_expired','The certificate has expired. Renew it before enabling HTTPS.'); + return raw; + } + + function renderHttpsStatus(data){ + httpsState=data||{}; + if($('https-enabled'))$('https-enabled').checked=Boolean(data?.enabled); + if($('https-target-type'))$('https-target-type').value=data?.target_type||'domain'; + if($('https-target'))$('https-target').value=data?.target||''; + if($('https-email'))$('https-email').value=data?.email||''; + if($('https-port'))$('https-port').value=String(data?.https_port||443); + if($('https-access-path'))$('https-access-path').value=data?.access_path||''; + const badge=$('https-status-badge');if(badge){badge.textContent=data?.enabled?t('settings.https_enabled','Enabled'):t('settings.https_disabled','Disabled');badge.className=data?.enabled?'badge managed':'badge';} + const cert=data?.certificate||{}; + if($('https-certificate-state'))$('https-certificate-state').textContent=cert.exists?t('settings.https_certificate_ready','Ready'):t('settings.https_certificate_missing','Not issued'); + if($('https-certificate-expiry'))$('https-certificate-expiry').textContent=cert.expires_at?formatDate(cert.expires_at):'—'; + if($('https-renewal-state'))$('https-renewal-state').textContent=data?.renewal_timer_enabled?t('settings.https_renewal_enabled','Enabled'):t('settings.https_renewal_disabled','Disabled'); + if($('https-certbot-version'))$('https-certbot-version').textContent=data?.certbot_version?`v${data.certbot_version}`:'—'; + const paths=$('https-paths');if(paths)paths.hidden=!cert.exists; + if($('https-certificate-path'))$('https-certificate-path').value=cert.certificate_path||''; + if($('https-private-key-path'))$('https-private-key-path').value=cert.private_key_path||''; + renderHttpsPorts(data?.ports||{},data?.https_port||443); + const target=$('https-target');if(target)target.placeholder=(data?.target_type||'domain')==='ip'?'203.0.113.10':'wg.example.com'; + syncHttpsEnableAvailability(); + } + + async function loadHttpsStatus(){ + if(page!=='settings'||!$('https-settings-form'))return; + try{const r=await fetch('/api/https/status',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderHttpsStatus(d);} + catch(e){operationStatus('https-settings-status',e.message,'error');} + } + + async function checkHttpsPorts(){ + const button=$('https-check-ports-button'),port=Number($('https-port')?.value||443);if(button)button.disabled=true; + try{const r=await fetch('/api/https/ports',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({https_port:port})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderHttpsPorts(d.ports||{},d.https_port||port);operationStatus('https-settings-status',t('settings.https_ports_checked','Port check completed.'),'success');} + catch(e){operationStatus('https-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} + } + + async function issueHttpsCertificate(){ + const payload=httpsPayload(),button=$('https-issue-button'),wasEnabled=Boolean(httpsState?.enabled); + if(!payload.target||!payload.email||!payload.access_path){operationStatus('https-settings-status',t('settings.https_issue_fields_required','Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.'),'error');return;} + if(!confirm(t('settings.https_issue_confirm','Request or renew the Let’s Encrypt certificate for {target}? The entered HTTPS settings will be saved. TCP port 80 must be reachable from the Internet.').replace('{target}',payload.target)))return; + if(button)button.disabled=true;operationStatus('https-settings-status',t('settings.https_issuing','Requesting certificate from Let’s Encrypt…'),'working'); + try{ + const previousInstance=wasEnabled?await currentPanelInstance():''; + const r=await fetch('/api/https/issue',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); + const d=await r.json(); + if(!r.ok)throw new Error(d.error||'Failed'); + operationStatus('https-settings-status',t('settings.https_issue_ok_saved','Certificate is ready and HTTPS settings are saved.'),'success'); + toast(t('settings.https_issue_ok','Certificate is ready.')); + if(wasEnabled){ + const host=httpsState?.target||location.hostname,port=httpsState?.https_port||443,path=httpsState?.access_path||basePath; + void reconnectAfterHttpsSwitch({target:host,https_port:port,access_path:path},previousInstance,4800); + }else{ + await loadHttpsStatus(); + } + } + catch(e){ + const message=localizedHttpsError(e.message); + if(!wasEnabled)await loadHttpsStatus(); + operationStatus('https-settings-status',message,'error'); + }finally{if(button)button.disabled=false;} + } + + async function saveHttpsSettings(event){ + event.preventDefault();const enabled=Boolean($('https-enabled')?.checked),payload=httpsPayload();const button=event.currentTarget.querySelector('button[type="submit"]');if(button)button.disabled=true; + try{ + if(enabled){ + if(!payload.target||!payload.email||!payload.access_path)throw new Error(t('settings.https_enable_fields_required','Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.')); + const requirement=httpsEnableRequirement(); + if(!requirement.ready)throw new Error(requirement.message); + const unchanged=Boolean(httpsState?.enabled&&httpsState?.target===payload.target&&httpsState?.target_type===payload.target_type&&Number(httpsState?.https_port||443)===payload.https_port&&normalizedHttpsAccessPath(httpsState?.access_path)===payload.access_path); + if(unchanged){operationStatus('https-settings-status',t('settings.https_already_enabled','Built-in HTTPS is already enabled.'),'success');return;} + const confirmText=t('settings.https_enable_confirm','Enable built-in HTTPS on TCP {port} with path {path}? WGTools will restart and this page will reconnect at the new address.').replace('{port}',String(payload.https_port)).replace('{path}',payload.access_path); + if(!confirm(confirmText))return; + const previousInstance=await currentPanelInstance(); + operationStatus('https-settings-status',t('settings.https_switching','Enabling HTTPS and restarting WGTools…'),'working'); + let r; + try{ + r=await fetch('/api/https/enable',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),keepalive:true}); + }catch(networkError){ + // Changing the HTTPS port/path restarts this very web service. If the + // response socket is cut during the hand-off, continue to the exact + // requested HTTPS URL instead of leaving the browser on the old origin. + operationStatus('https-settings-status',t('settings.https_reconnecting','WGTools is switching to the new HTTPS address…'),'working'); + void reconnectAfterHttpsSwitch(payload,previousInstance,4800); + return; + } + const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); + const destination={target:String(d.redirect_host||payload.target),https_port:Number(d.redirect_port||payload.https_port),access_path:d.access_path||payload.access_path}; + operationStatus('https-settings-status',t('settings.https_reconnecting','WGTools is switching to the new HTTPS address…'),'working'); + void reconnectAfterHttpsSwitch(destination,previousInstance,4800); + }else{ + if(!httpsState?.enabled){operationStatus('https-settings-status',t('settings.https_already_disabled','Built-in HTTPS is already disabled.'),'success');return;} + if(!confirm(t('settings.https_disable_confirm','Disable built-in HTTPS and return WGTools to HTTP?')))return; + operationStatus('https-settings-status',t('settings.https_switching_http','Disabling HTTPS and restarting WGTools…'),'working'); + const r=await fetch('/api/https/disable',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); + const host=httpsUrlHost(location.hostname),port=Number(d.http_port||8341);setTimeout(()=>{location.replace(`http://${host}:${port}/settings#https`);},6500); + } + }catch(e){operationStatus('https-settings-status',localizedHttpsError(e.message),'error');if(httpsState)$('https-enabled').checked=Boolean(httpsState.enabled);syncHttpsEnableAvailability();}finally{if(button)button.disabled=false;} + } + + async function copyHttpsPath(id){ + const field=$(id);if(!field?.value)return; + try{await navigator.clipboard.writeText(field.value);toast(t('common.copied','Copied'));} + catch(_){field.focus();field.select();document.execCommand('copy');field.setSelectionRange(0,0);toast(t('common.copied','Copied'));} + } + + function bindHttpsSettings(){ + $('https-settings-form')?.addEventListener('submit',saveHttpsSettings); + $('https-check-ports-button')?.addEventListener('click',checkHttpsPorts); + $('https-issue-button')?.addEventListener('click',issueHttpsCertificate); + $('https-use-panel-host')?.addEventListener('click',()=>{usePanelHostForHttps();syncHttpsEnableAvailability();}); + $('https-port')?.addEventListener('input',()=>renderHttpsPorts(httpsState?.ports||{},Number($('https-port')?.value||443))); + $('https-target')?.addEventListener('input',syncHttpsEnableAvailability); + $('https-target-type')?.addEventListener('change',e=>{const f=$('https-target');if(f)f.placeholder=e.currentTarget.value==='ip'?'203.0.113.10':'wg.example.com';syncHttpsEnableAvailability();}); + document.querySelectorAll('[data-copy-path]').forEach(button=>button.addEventListener('click',()=>copyHttpsPath(button.dataset.copyPath))); + if(page==='settings')loadHttpsStatus(); + } + + let telegramState = null; + + function parseNumericLines(value){ + const items=String(value||'').split(/[\s,;]+/).map(x=>x.trim()).filter(Boolean); + const result=[]; + for(const item of items){ + if(!/^\d+$/.test(item) || Number(item)<=0) throw new Error(`${t('settings.telegram_allowed_ids','Allowed Telegram user IDs')}: ${item}`); + const n=Number(item); if(!result.includes(n))result.push(n); + } + return result; + } + + function parseTextList(value){ return String(value||'').split(/[\s,;]+/).map(x=>x.trim()).filter(Boolean); } + + function renderTelegramSettings(data){ + telegramState=data||{}; + const enabled=$('telegram-enabled'); if(enabled)enabled.checked=Boolean(data?.enabled); + const token=$('telegram-token'); if(token){token.value='';token.placeholder=data?.token_masked||t('settings.telegram_not_configured','Not configured');} + const ids=$('telegram-allowed-ids'); if(ids)ids.value=(data?.allowed_user_ids||[]).join('\n'); + const endpoint=$('telegram-endpoint'); if(endpoint)endpoint.value=data?.default_endpoint||''; + const dns=$('telegram-dns'); if(dns)dns.value=(data?.default_dns||[]).join(', '); + const language=$('telegram-language'); if(language)language.value=data?.language||'auto'; + const remove=$('telegram-remove-token-button'); if(remove)remove.disabled=!data?.token_configured; + const botName=$('telegram-bot-name'); if(botName)botName.textContent=data?.bot_username?`@${data.bot_username}`:t('settings.telegram_not_configured','Not configured'); + const last=$('telegram-last-poll'); if(last)last.textContent=`${t('settings.telegram_last_poll','Last Telegram contact')}: ${data?.last_poll_at?formatDate(data.last_poll_at):'—'}`; + const badge=$('telegram-status-badge'); + if(badge){ + let label=t('settings.telegram_not_configured','Not configured'), cls='badge'; + if(!data?.enabled){label=data?.token_configured?t('settings.telegram_disabled','Disabled'):t('settings.telegram_not_configured','Not configured');cls='badge';} + else if(data?.last_error){label=t('common.error','Error');cls='badge warn';} + else if(data?.last_poll_at && (Date.now()/1000-Number(data.last_poll_at)<90)){label=t('settings.telegram_connected','Connected');cls='badge managed';} + else if(data?.token_configured){label=t('settings.telegram_waiting','Configured, waiting for bot service');cls='badge warn';} + badge.textContent=label;badge.className=cls; + } + if(data?.last_error)operationStatus('telegram-settings-status',data.last_error,'error'); + else operationStatus('telegram-settings-status',''); + } + + async function loadTelegramSettings(){ + if(page!=='settings'||!$('telegram-settings-form'))return; + try{ + const r=await fetch('/api/telegram/settings',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderTelegramSettings(d.settings||{}); + }catch(e){operationStatus('telegram-settings-status',e.message,'error');} + } + + async function saveTelegramSettings(event){ + event.preventDefault(); + const button=event.currentTarget.querySelector('button[type="submit"]');if(button)button.disabled=true; + operationStatus('telegram-settings-status',t('settings.saving','Saving settings…'),'working'); + try{ + const payload={ + enabled:Boolean($('telegram-enabled')?.checked), + bot_token:$('telegram-token')?.value.trim()||'', + clear_token:false, + allowed_user_ids:parseNumericLines($('telegram-allowed-ids')?.value||''), + default_endpoint:$('telegram-endpoint')?.value.trim()||'', + default_dns:parseTextList($('telegram-dns')?.value||''), + language:$('telegram-language')?.value||'auto', + }; + const r=await fetch('/api/telegram/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); + renderTelegramSettings(d.settings||{});operationStatus('telegram-settings-status',t('settings.telegram_saved','Telegram settings saved.'),'success');toast(t('settings.telegram_saved','Telegram settings saved.')); + setTimeout(loadTelegramSettings,1800); + }catch(e){operationStatus('telegram-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} + } + + async function testTelegram(){ + const button=$('telegram-test-button');if(button)button.disabled=true;operationStatus('telegram-settings-status',t('common.checking','Checking…'),'working'); + try{ + const r=await fetch('/api/telegram/test',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); + const text=d.verified_by_last_poll + ? t('settings.telegram_test_recent_ok','Telegram bot is working. The direct check timed out, but the bot contacted Telegram recently.') + : t('settings.telegram_test_ok','Telegram connection is working: @{username}').replace('{username}',d.username||'bot'); + operationStatus('telegram-settings-status',text,'success');toast(text);await loadTelegramSettings(); + }catch(e){operationStatus('telegram-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} + } + + async function removeTelegramToken(){ + if(!confirm(t('settings.telegram_remove_token_confirm','Remove the saved Telegram bot token and disable the bot?')))return; + const button=$('telegram-remove-token-button');if(button)button.disabled=true; + try{ + const current=telegramState||{}; + const payload={enabled:false,bot_token:'',clear_token:true,allowed_user_ids:current.allowed_user_ids||[],default_endpoint:current.default_endpoint||'',default_dns:current.default_dns||[],language:current.language||'auto'}; + const r=await fetch('/api/telegram/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderTelegramSettings(d.settings||{});toast(t('settings.telegram_saved','Telegram settings saved.')); + }catch(e){operationStatus('telegram-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} + } + + function bindTelegramSettings(){ + $('telegram-settings-form')?.addEventListener('submit',saveTelegramSettings); + $('telegram-test-button')?.addEventListener('click',testTelegram); + $('telegram-remove-token-button')?.addEventListener('click',removeTelegramToken); + if(page==='settings')loadTelegramSettings(); + } + + async function saveAppSettings(event){ + event.preventDefault(); + const payload={ + refresh_seconds:Number($('settings-refresh-seconds')?.value||5), + online_threshold_seconds:Number($('settings-online-threshold')?.value||180), + backup_retention:Number($('settings-backup-retention')?.value||20), + }; + const button=event.currentTarget.querySelector('button[type="submit"]'); if(button)button.disabled=true; + operationStatus('app-settings-status',t('settings.saving','Saving settings…'),'working'); + try{ + const r=await fetch('/api/app-settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); + operationStatus('app-settings-status',t('settings.saved_reload','Settings saved. Reloading…'),'success'); toast(t('settings.saved','Settings saved.')); setTimeout(()=>location.reload(),450); + }catch(e){operationStatus('app-settings-status',e.message,'error'); if(button)button.disabled=false;} + } + + function bindHelp(){ + const button=$('help-button'); + if(!button)return; + const selectSection=id=>{ + document.querySelectorAll('[data-help-target]').forEach(b=>b.classList.toggle('active',b.dataset.helpTarget===id)); + document.querySelectorAll('[data-help-section]').forEach(section=>section.hidden=section.dataset.helpSection!==id); + const content=document.querySelector('#help-modal .help-content'); if(content)content.scrollTop=0; + }; + button.addEventListener('click',()=>{ + const current={dashboard:'dashboard',server:'server',clients:'clients',settings:'settings'}[page]||'dashboard'; + selectSection(current); + modalShow('help-modal',true); + }); + document.querySelectorAll('[data-help-target]').forEach(b=>b.addEventListener('click',()=>selectSection(b.dataset.helpTarget))); + } + + + function migrationFilenameFromDisposition(value){ + const text=String(value||''); + const utf=text.match(/filename\*=UTF-8''([^;]+)/i); + if(utf){try{return decodeURIComponent(utf[1].replace(/^"|"$/g,''));}catch(_){}} + const plain=text.match(/filename="?([^";]+)"?/i); + return plain?plain[1]:'WGTools-backup.wgtbackup'; + } + + async function downloadMigrationBackup(){ + const button=$('migration-backup-download-button'); if(!button)return; + button.disabled=true; operationStatus('migration-backup-status',t('settings.full_backup_creating','Creating a complete backup…'),'working'); + try{ + const r=await fetch('/api/migration/backup',{cache:'no-store'}); + if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.error||t('settings.full_backup_create_failed','Could not create the full backup'));} + const blob=await r.blob(); + const name=migrationFilenameFromDisposition(r.headers.get('content-disposition')); + const url=URL.createObjectURL(blob); + const a=document.createElement('a'); a.href=url; a.download=name; document.body.appendChild(a); a.click(); a.remove(); + setTimeout(()=>URL.revokeObjectURL(url),2000); + operationStatus('migration-backup-status',t('settings.full_backup_downloaded','Backup created and downloaded. Store it securely.'),'success'); + toast(t('settings.full_backup_downloaded_short','Full backup downloaded.')); + }catch(e){operationStatus('migration-backup-status',e.message,'error');toast(e.message);} + finally{button.disabled=false;} + } + + function migrationFileChanged(){ + const input=$('migration-backup-file'), label=$('migration-selected-file'), restore=$('migration-backup-restore-button'); + const file=input?.files?.[0]||null; + if(label) label.textContent=file?`${file.name} · ${fmtBytes(file.size)}`:t('settings.full_backup_no_file','No backup selected'); + if(restore) restore.disabled=!file; + operationStatus('migration-backup-status',''); + } + + async function restoreMigrationBackup(){ + const input=$('migration-backup-file'), file=input?.files?.[0], button=$('migration-backup-restore-button'); + if(!file||!button)return; + if(!confirm(t('settings.full_backup_restore_confirm','Restore this full WGTools backup? Current users, settings, managed client data and WireGuard configuration will be replaced. WireGuard may restart.')))return; + button.disabled=true; + const download=$('migration-backup-download-button'), select=$('migration-backup-select-button'); if(download)download.disabled=true;if(select)select.disabled=true; + operationStatus('migration-backup-status',t('settings.full_backup_restoring','Validating backup, creating a safety copy and restoring…'),'working'); + try{ + const r=await fetch('/api/migration/restore',{method:'POST',headers:{'Content-Type':'application/octet-stream','X-WGTools-Backup-Name':file.name},body:file}); + const d=await r.json(); if(!r.ok)throw new Error(d.error||t('settings.full_backup_restore_failed','Restore failed')); + operationStatus('migration-backup-status',t('settings.full_backup_restored','Backup restored successfully. Sign in with an account from the restored backup.'),'success'); + toast(t('settings.full_backup_restored_short','Backup restored.')); + setTimeout(()=>{location.href=appUrl('/login');},1200); + }catch(e){ + operationStatus('migration-backup-status',e.message,'error'); toast(e.message); + button.disabled=false; if(download)download.disabled=false;if(select)select.disabled=false; + } + } + + function bindMigrationBackup(){ + const input=$('migration-backup-file'); + $('migration-backup-download-button')?.addEventListener('click',downloadMigrationBackup); + $('migration-backup-select-button')?.addEventListener('click',()=>input?.click()); + input?.addEventListener('change',migrationFileChanged); + $('migration-backup-restore-button')?.addEventListener('click',restoreMigrationBackup); + } + + let updateRelease=null; + let updatePollTimer=null; + let updateNoticeTimer=null; + const updateNoticeStorageKey='wgtools.updateNotice'; + + function rememberUpdateNotice(data){ + try{ + if(data?.update_available&&data?.latest_version)localStorage.setItem(updateNoticeStorageKey,JSON.stringify({update_available:true,latest_version:data.latest_version,current_version:data.current_version||'',tag_name:data.tag_name||'',checked_at:data.checked_at||Math.floor(Date.now()/1000)})); + else if(data&&data.update_available===false&&data.latest_version&&!data.check_error)localStorage.removeItem(updateNoticeStorageKey); + }catch(_){} + } + + function restoreUpdateNotice(){ + try{ + const raw=localStorage.getItem(updateNoticeStorageKey); if(!raw)return; + const data=JSON.parse(raw); if(data?.update_available&&data?.latest_version)renderSidebarUpdateNotice(data); + }catch(_){} + } + + function renderSidebarUpdateNotice(data){ + const notice=null; // The topbar is the sole update notification. + const header=$('topbar-update-notice'); + const available=Boolean(data?.update_available&&data?.latest_version); + if(notice)notice.hidden=!available; + if(header)header.hidden=!available; + if(!available)return; + const version=$('sidebar-update-version'); if(version)version.textContent=`v${data.latest_version}`; + const headVersion=$('topbar-update-version'); if(headVersion)headVersion.textContent=`v${data.latest_version}`; + const label=`${t('settings.update_sidebar','Update available')} · v${data.latest_version}`; + if(notice)notice.setAttribute('aria-label',label); + if(header)header.setAttribute('aria-label',label); + } + + async function refreshUpdateNotice(){ + try{ + const r=await fetch('/api/update/notice',{cache:'no-store'});const d=await r.json();if(!r.ok)return; + if(d?.check_error&&!d?.latest_version){ + if(page==='settings'&&$('check-updates-button')){ + setUpdateBadge(t('settings.update_check_failed','Check failed'),'warn'); + operationStatus('update-operation-status',d.check_error,'error'); + } + return; // Network failure must not clear a previously confirmed update. + } + rememberUpdateNotice(d); + renderSidebarUpdateNotice(d); + if(page==='settings'&&$('check-updates-button')&&d?.latest_version)renderUpdateRelease(d); + }catch(_){} + } + + function setUpdateBadge(text,kind=''){ + const badge=$('update-status-badge'); if(!badge)return; + badge.textContent=text; badge.className=`badge ${kind}`.trim(); + } + + function renderUpdateRelease(data){ + updateRelease=data||null; + rememberUpdateNotice(data); + renderSidebarUpdateNotice(data); + const latest=$('update-latest-version'); if(latest)latest.textContent=data?.latest_version?`v${data.latest_version}`:'—'; + const current=$('update-current-version'); if(current&&data?.current_version)current.textContent=data.current_version; + const notesWrap=$('update-release-notes-wrap'), notes=$('update-release-notes'), link=$('update-release-link'); + if(notesWrap)notesWrap.hidden=!data?.release_notes; + if(notes)notes.textContent=data?.release_notes||''; + if(link&&data?.release_url)link.href=data.release_url; + const apply=$('apply-update-button'); + if(data?.check_error&&(!data?.latest_version||data?.stale)){ + setUpdateBadge(t('settings.update_check_failed','Check failed'),'warn'); + operationStatus('update-operation-status',String(data.check_error),'error'); + }else if(data?.update_available){ + setUpdateBadge(t('settings.update_available','Update available'),'warn'); + if(apply){apply.hidden=false;apply.disabled=false;apply.textContent=`${t('settings.update_wgtools','Update WGTools')} · v${data.latest_version}`;} + operationStatus('update-operation-status',`${t('settings.update_available','Update available')}: v${data.current_version} → v${data.latest_version}`,'working'); + }else{ + setUpdateBadge(t('settings.update_current','Up to date'),'managed'); + if(apply){apply.hidden=true;apply.disabled=true;} + operationStatus('update-operation-status',t('settings.update_no_update','WGTools is already up to date.'),'success'); + } + } + + async function checkUpdates(){ + const check=$('check-updates-button'), apply=$('apply-update-button'); + if(check)check.disabled=true;if(apply)apply.disabled=true; + setUpdateBadge(t('common.checking','Checking…'),'warn'); + operationStatus('update-operation-status',t('settings.update_checking','Checking the latest published GitHub Release…'),'working'); + try{ + const r=await fetch('/api/update/check',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('settings.update_check_failed','Could not check for updates')); + renderUpdateRelease(d); + }catch(e){ + setUpdateBadge(t('settings.update_check_failed','Check failed'),''); + operationStatus('update-operation-status',e.message,'error');toast(e.message); + }finally{ + if(check)check.disabled=false; + if(apply&&updateRelease?.update_available)apply.disabled=false; + } + } + + function updateProgressText(data){ + if(data?.state==='queued')return t('settings.update_queued','Update queued. Waiting for the updater service…'); + if(data?.state==='rolling_back')return t('settings.update_rolling_back','Update failed. Restoring the previous WGTools application…'); + if(data?.state==='running'){ + if(data.phase==='backup')return t('settings.update_backup_running','Creating the automatic full backup before update…'); + if(data.phase==='download')return t('settings.update_downloading','Downloading and validating the GitHub release…'); + if(data.phase==='install')return t('settings.update_installing','Installing the update. The web interface may be unavailable briefly…'); + return t('settings.update_running','Creating safety backups…'); + } + return data?.message||t('settings.update_status_unknown','Update status is unavailable. Retrying…'); + } + + async function pollUpdateStatus(deadline=Date.now()+12*60*1000){ + if(updatePollTimer){clearTimeout(updatePollTimer);updatePollTimer=null;} + if(Date.now()>deadline){operationStatus('update-operation-status',t('settings.update_status_unknown','Update status is unavailable. Retrying…'),'error');return;} + try{ + const r=await fetch('/api/update/status',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Status unavailable'); + if(d.state==='success'){ + const version=d.target_version||d.current_version||''; + rememberUpdateNotice({update_available:false}); + setUpdateBadge(t('settings.update_current','Up to date'),'managed'); + operationStatus('update-operation-status',t('settings.update_success','WGTools was updated successfully to v{version}. Reloading…').replace('{version}',version),'success'); + setTimeout(()=>location.reload(),1400);return; + } + if(d.state==='error'){ + setUpdateBadge(t('settings.update_failed','Update failed'),''); + let message=d.error||d.message||t('settings.update_failed','WGTools update failed.'); + if(d.rollback_ok)message+=`\n${t('settings.update_rollback_ok','The previous WGTools application was restored automatically.')}`; + operationStatus('update-operation-status',message,'error'); + const check=$('check-updates-button'), apply=$('apply-update-button');if(check)check.disabled=false;if(apply)apply.disabled=false;if($('update-upload-button'))$('update-upload-button').disabled=false; + return; + } + setUpdateBadge(d.state==='rolling_back'?t('settings.update_failed','Update failed'):t('settings.update_available','Updating…'),'warn'); + operationStatus('update-operation-status',updateProgressText(d),'working'); + }catch(_){ + operationStatus('update-operation-status',t('settings.update_installing','Installing the update. The web interface may be unavailable briefly…'),'working'); + } + updatePollTimer=setTimeout(()=>pollUpdateStatus(deadline),2000); + } + + async function applyUpdate(){ + if(!updateRelease?.update_available||!updateRelease?.tag_name)return; + const current=updateRelease.current_version||$('update-current-version')?.textContent||''; + const latest=updateRelease.latest_version||''; + const question=t('settings.update_confirm','Update WGTools from v{current} to v{latest}? A full backup and application rollback copy will be created first. The web interface will restart briefly.').replace('{current}',current).replace('{latest}',latest); + if(!confirm(question))return; + const check=$('check-updates-button'), apply=$('apply-update-button');if(check)check.disabled=true;if(apply)apply.disabled=true; + setUpdateBadge(t('settings.update_available','Updating…'),'warn'); + operationStatus('update-operation-status',t('settings.update_starting','Starting the update…'),'working'); + try{ + const r=await fetch('/api/update/apply',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({tag:updateRelease.tag_name})}); + const d=await r.json();if(!r.ok)throw new Error(d.error||t('settings.update_failed','WGTools update failed.')); + if(!d.scheduled){operationStatus('update-operation-status',d.message||t('settings.update_no_update','WGTools is already up to date.'),'success');if(check)check.disabled=false;return;} + operationStatus('update-operation-status',t('settings.update_backup_queued','Update queued. WGTools will create an automatic full backup before installing it…'),'working'); + setTimeout(()=>pollUpdateStatus(),1200); + }catch(e){operationStatus('update-operation-status',e.message,'error');setUpdateBadge(t('settings.update_failed','Update failed'),'');if(check)check.disabled=false;if(apply)apply.disabled=false;} + } + + async function resumeUpdateStatus(){ + if(page!=='settings'||!$('check-updates-button'))return; + try{ + const r=await fetch('/api/update/status',{cache:'no-store'});const d=await r.json();if(!r.ok)return; + const age=Date.now()/1000-Number(d.updated_at||0); + if(['queued','running','rolling_back'].includes(d.state)){const check=$('check-updates-button'),apply=$('apply-update-button');if(check)check.disabled=true;if(apply)apply.disabled=true;pollUpdateStatus();} + else if(d.state==='success'&&age<300){operationStatus('update-operation-status',String(d.message||''),'success');} + else if(d.state==='error'&&age<300){let msg=d.error||d.message||t('settings.update_failed','WGTools update failed.');if(d.rollback_ok)msg+=`\n${t('settings.update_rollback_ok','The previous WGTools application was restored automatically.')}`;operationStatus('update-operation-status',msg,'error');} + }catch(_){} + } + + function bindUpdates(){ + $('update-upload-button')?.addEventListener('click',async()=>{ + const file=$('update-upload-file')?.files[0]; + if(!file){operationStatus('update-operation-status','Wybierz pakiet .bin.','error');return;} + if(file.size>64*1024*1024){operationStatus('update-operation-status','Pakiet przekracza 64 MB.','error');return;} + if(!confirm('Zainstalować wybrany pakiet? Aplikacja zostanie na chwilę uruchomiona ponownie.'))return; + const button=$('update-upload-button');button.disabled=true;operationStatus('update-operation-status','Sprawdzanie pakietu aktualizacji…','working'); + try{const r=await fetch(appUrl('/api/update/upload'),{method:'POST',headers:{'Content-Type':'application/octet-stream'},body:file});const d=await r.json();if(!r.ok)throw new Error(d.error||'Nie udało się uruchomić aktualizacji.');operationStatus('update-operation-status','Aktualizacja została uruchomiona.','working');pollUpdateStatus();}catch(err){operationStatus('update-operation-status',err.message,'error');button.disabled=false;} + }); + $('check-updates-button')?.addEventListener('click',checkUpdates); + $('apply-update-button')?.addEventListener('click',applyUpdate); + resumeUpdateStatus(); + } + + function bindAppSettings(){ $('app-settings-form')?.addEventListener('submit',saveAppSettings); $('save-backup-settings-button')?.addEventListener('click',()=>$('app-settings-form')?.requestSubmit()); } + + function setTheme(value){ + localStorage.setItem('wgtools.theme',value); + let actual=value; + if(value==='system')actual=matchMedia('(prefers-color-scheme: light)').matches?'light':'dark'; + document.documentElement.dataset.theme=actual; + const select=$('theme-select');if(select)select.value=value; + const button=$('topbar-theme-toggle');if(button){ + const label=actual==='dark'?t('settings.theme_light','Light theme'):t('settings.theme_dark','Dark theme'); + button.setAttribute('aria-label',label);button.dataset.tooltip=label;button.removeAttribute('title'); + } + } + function setSidebarCollapsed(collapsed,persist=true){ + const next=Boolean(collapsed); + document.body.classList.toggle('sidebar-collapsed',next); + document.documentElement.classList.remove('sidebar-pref-collapsed'); + if(persist){try{localStorage.setItem('wgtools.sidebar.collapsed',next?'1':'0');}catch(_){}} + const toggle=$('sidebar-collapsed-toggle');if(toggle)toggle.checked=next; + const button=$('sidebar-collapse-button');if(button){button.setAttribute('aria-expanded',String(!next));const label=next?t('settings.expand_sidebar','Expand sidebar'):t('settings.collapse_sidebar','Collapse sidebar');button.dataset.tooltip=label;button.setAttribute('aria-label',label);button.classList.toggle('is-collapsed',next);} + } + function initSettings(){ + const theme=localStorage.getItem('wgtools.theme')||'dark';setTheme(theme); + const s=$('theme-select');if(s){s.value=theme;s.addEventListener('change',()=>setTheme(s.value));} + $('topbar-theme-toggle')?.addEventListener('click',()=>setTheme(document.documentElement.dataset.theme==='dark'?'light':'dark')); + try{matchMedia('(prefers-color-scheme: light)').addEventListener('change',()=>{if(localStorage.getItem('wgtools.theme')==='system')setTheme('system');});}catch(_){} + const l=$('language-select');if(l){l.value=window.WGToolsI18n.getLanguage();l.addEventListener('change',()=>window.WGToolsI18n.setLanguage(l.value));} + const sidebarToggle=$('sidebar-collapsed-toggle'); + if(sidebarToggle){ + let collapsed=false;try{collapsed=localStorage.getItem('wgtools.sidebar.collapsed')==='1';}catch(_){} + sidebarToggle.checked=collapsed; + sidebarToggle.addEventListener('change',()=>setSidebarCollapsed(sidebarToggle.checked)); + } + } + function initSidebar(){ + let collapsed=false; + try{collapsed=localStorage.getItem('wgtools.sidebar.collapsed')==='1';}catch(_){} + setSidebarCollapsed(collapsed,false); + $('sidebar-collapse-button')?.addEventListener('click',()=>setSidebarCollapsed(!document.body.classList.contains('sidebar-collapsed'))); + } + + function fillCreateInterfaceForm(){ + const x=interfacesData.suggested||{}; + if($('new-interface-name'))$('new-interface-name').value=x.interface||'wg1'; + if($('new-interface-display-name'))$('new-interface-display-name').value=x.display_name||''; + if($('new-interface-vpn-network'))$('new-interface-vpn-network').value=x.vpn_network||'10.0.1.0/24'; + if($('new-interface-server-address'))$('new-interface-server-address').value=x.server_address||firstHostFromCidr(x.vpn_network||'10.0.1.0/24')||''; + if($('new-interface-port'))$('new-interface-port').value=x.listen_port||51821; + if($('new-interface-mtu'))$('new-interface-mtu').value=x.mtu||''; + if($('new-interface-uplink'))$('new-interface-uplink').value=x.uplink_interface||snapshot?.system?.default_uplink||''; + if($('new-interface-gateway'))$('new-interface-gateway').value=x.gateway||snapshot?.system?.default_gateway||''; + if($('new-interface-local-network'))$('new-interface-local-network').value=x.local_network||snapshot?.system?.local_network||''; + if($('new-interface-policy-table'))$('new-interface-policy-table').value=x.policy_table||''; + if($('new-interface-forwarding'))$('new-interface-forwarding').checked=x.ip_forwarding!==false; + if($('new-interface-nat'))$('new-interface-nat').checked=x.nat_enabled!==false; + const addr=$('new-interface-server-address');if(addr)delete addr.dataset.touched; + operationStatus('interface-create-status',''); + } + async function openCreateInterface(){ + await fetchInterfaces(true);fillCreateInterfaceForm();modalShow('interface-create-modal',true);setTimeout(()=>$('new-interface-display-name')?.focus(),30); + } + function syncNewInterfaceAddress(){const net=$('new-interface-vpn-network'),addr=$('new-interface-server-address');if(!net||!addr||addr.dataset.touched)return;const first=firstHostFromCidr(net.value);if(first)addr.value=first;} + async function createInterface(event){ + event.preventDefault();const button=$('interface-create-save');if(!button)return; + const payload={ + interface:$('new-interface-name').value.trim(),display_name:$('new-interface-display-name').value.trim(), + vpn_network:$('new-interface-vpn-network').value.trim(),server_address:$('new-interface-server-address').value.trim(),listen_port:Number($('new-interface-port').value),mtu:Number($('new-interface-mtu').value||0), + uplink_interface:$('new-interface-uplink').value.trim(),gateway:$('new-interface-gateway').value.trim(),local_network:$('new-interface-local-network').value.trim(),policy_table:$('new-interface-policy-table').value.trim(), + nat_enabled:$('new-interface-nat').checked,ip_forwarding:$('new-interface-forwarding').checked, + }; + const label=payload.display_name?`${payload.interface} · ${payload.display_name}`:payload.interface; + if(!confirm(t('interfaces.create_confirm','Create and start interface {name}?').replace('{name}',label)))return; + button.disabled=true;operationStatus('interface-create-status',t('interfaces.creating','Generating keys, writing the new configuration and starting WireGuard…'),'working'); + try{ + const r=await fetch('/api/interfaces/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||t('interfaces.create_failed','Interface could not be created')); + operationStatus('interface-create-status',t('interfaces.created','Interface created successfully.'),'success');toast(t('interfaces.created','Interface created successfully.')); + setInterfaceCookie(payload.interface);setTimeout(()=>{location.href=appUrl('/server');},500); + }catch(e){const message=localizedServerError(e.message);operationStatus('interface-create-status',message,'error');toast(message);}finally{button.disabled=false;} + } + async function deleteInterface(name){ + const item=(interfacesData.interfaces||[]).find(x=>x.name===name);if(!item)return; + const configured=(interfacesData.interfaces||[]).filter(x=>x.configured); + if(configured.length<=1){toast(t('interfaces.delete_last','The last configured WireGuard interface cannot be deleted here.'));return;} + const label=interfaceDisplay(item); + const message=t('interfaces.delete_confirm','Delete interface {name}? This removes its WireGuard configuration and all peers on this interface. A configuration backup is created first.').replace('{name}',label); + if(!confirm(message))return; + const button=document.querySelector(`[data-interface-delete="${CSS.escape(name)}"]`);if(button)button.disabled=true; + toast(t('interfaces.deleting','Stopping WireGuard and deleting the interface…'),5000); + try{ + const r=await fetch('/api/interfaces/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({interface:name})});const d=await r.json();if(!r.ok)throw new Error(d.error||t('interfaces.delete_failed','Interface could not be deleted')); + const backupName=String(d.backup||'').split('/').pop()||'—'; + toast(t('interfaces.deleted','Interface deleted. Backup: {backup}').replace('{backup}',backupName),5000); + if(d.next_interface)setInterfaceCookie(d.next_interface); + setTimeout(()=>{location.href=appUrl('/server');},600); + }catch(e){toast(e.message,5000);if(button)button.disabled=false;} + } + + function bindInterfaceManager(){ + $('add-interface-button')?.addEventListener('click',openCreateInterface);$('interface-create-form')?.addEventListener('submit',createInterface); + $('new-interface-vpn-network')?.addEventListener('input',syncNewInterfaceAddress);$('new-interface-server-address')?.addEventListener('input',e=>e.currentTarget.dataset.touched='1'); + } + + function bindProvisioning(){ + $('install-wireguard-button')?.addEventListener('click',installWireGuard); + $('create-server-form')?.addEventListener('submit',createServer); + $('setup-vpn-network')?.addEventListener('input',syncServerAddress); + $('setup-server-address')?.addEventListener('input',e=>e.currentTarget.dataset.touched='1'); + ['setup-uplink','setup-gateway','setup-local-network'].forEach(id=>$(id)?.addEventListener('input',e=>e.currentTarget.dataset.touched='1')); + } + + async function boot(){ + setTheme(localStorage.getItem('wgtools.theme')||'dark'); initSettings(); initSidebar(); bindDelayedTooltips(); bindHelp(); bindInterfaceSwitcher(); bindInterfaceManager(); bindServerTabs(); bindSettingsTabs(); bindNodes(); bindVps(); bindAppSettings(); bindUpdates(); bindMigrationBackup(); bindTelegramSettings(); bindMailSettings(); bindHttpsSettings(); bindWireGuardControls(); bindProvisioning(); bindServerEditor(); bindServerRules(); bindClientManagement(); bindRawConfigEditor(); bindUserManagement(); bindAudit(); + try{localStorage.removeItem(updateNoticeStorageKey);}catch(_){} + $('refresh-button')?.addEventListener('click',()=>fetchSnapshot(true)); + $('traffic-reset-button')?.addEventListener('click',resetTraffic); + const dashboardSearch=$('dashboard-peer-search'), dashboardSearchClear=$('dashboard-peer-search-clear'); + const syncDashboardSearchClear=()=>{if(dashboardSearchClear) dashboardSearchClear.hidden=!String(dashboardSearch?.value||'').length;}; + dashboardSearch?.addEventListener('input',()=>{syncDashboardSearchClear();if(snapshot)renderDashboard(snapshot);}); + dashboardSearchClear?.addEventListener('click',()=>{if(!dashboardSearch)return;dashboardSearch.value='';syncDashboardSearchClear();dashboardSearch.focus();if(snapshot)renderDashboard(snapshot);}); + syncDashboardSearchClear(); + $('diagnostics-button')?.addEventListener('click',diagnostics); + $('network-trace-form')?.addEventListener('submit',runNetworkTrace);bindTraceMap(); + await Promise.all([fetchInterfaces(true),fetchSnapshot()]); + if(snapshot)renderHeader(snapshot); + if(page==='dashboard'){ + loadMetricsHistory(); + loadDashboardDiagnostics(); + historyTimer=setInterval(loadMetricsHistory,60*1000); + dashboardDiagnosticsTimer=setInterval(loadDashboardDiagnostics,60*1000); + } + if(page==='server'){ + loadServerDiagnostics(); + serverDiagnosticsTimer=setInterval(loadServerDiagnostics,60*1000); + } + if(page!=='settings') timer=setInterval(()=>fetchSnapshot(false),Math.max(2,refreshSeconds)*1000); + } + boot(); +})(); diff --git a/app/static/js/auth.js b/app/static/js/auth.js new file mode 100644 index 0000000..33587ee --- /dev/null +++ b/app/static/js/auth.js @@ -0,0 +1,160 @@ +(() => { + const basePath = String(document.body.dataset.basePath || '').replace(/\/$/, ''); + const appUrl = path => { + const value = String(path || '/'); + if (!value.startsWith('/') || value.startsWith('//')) return value; + return `${basePath}${value}` || '/'; + }; + const $ = id => document.getElementById(id); + const error = message => { + const el = $('auth-error'); + if (!el) return; + el.hidden = !message; + el.textContent = message || ''; + }; + const status = (id, message, kind='') => { + const el = $(id); + if (!el) return; + el.hidden = !message; + el.className = `operation-status${kind ? ` ${kind}` : ''}`; + el.textContent = message || ''; + }; + + async function submit(endpoint, payload) { + const response = await fetch(appUrl(endpoint), { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify(payload), + }); + const data = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(data.error || 'Request failed'); + return data; + } + + $('setup-user-form')?.addEventListener('submit', async event => { + event.preventDefault(); + error(''); + const password = $('auth-password').value; + if (password !== $('auth-password-repeat').value) { + error(document.documentElement.lang === 'ru' ? 'Пароли не совпадают.' : 'Passwords do not match.'); + return; + } + const button = event.currentTarget.querySelector('button[type="submit"]'); + button.disabled = true; + try { + await submit('/api/auth/setup', {username: $('auth-username').value.trim(), email: $('auth-email')?.value.trim() || '', password}); + location.replace(appUrl('/')); + } catch (e) { + error(e.message); + button.disabled = false; + } + }); + + $('login-form')?.addEventListener('submit', async event => { + event.preventDefault(); + error(''); + const form = event.currentTarget; + const button = form.querySelector('button[type="submit"]'); + button.disabled = true; + try { + const data = await submit('/api/auth/login', {username: $('auth-username').value.trim(), password: $('auth-password').value}); + if (data.mfa_required) { + form.hidden = true; + $('mfa-login-form').hidden = false; + $('auth-mfa-code').value = ''; + button.disabled = false; + setTimeout(() => $('auth-mfa-code')?.focus(), 30); + return; + } + const next = new URLSearchParams(location.search).get('next'); + location.replace(appUrl(next && next.startsWith('/') && !next.startsWith('//') ? next : '/')); + } catch (e) { + error(document.documentElement.lang === 'ru' && e.message === 'Invalid username or password' ? 'Неверный логин или пароль.' : e.message); + button.disabled = false; + } + }); + + $('mfa-login-form')?.addEventListener('submit', async event => { + event.preventDefault(); + status('mfa-auth-error', ''); + const button = event.currentTarget.querySelector('button[type="submit"]'); + button.disabled = true; + try { + await submit('/api/auth/mfa', {code: $('auth-mfa-code').value.trim()}); + const next = new URLSearchParams(location.search).get('next'); + location.replace(appUrl(next && next.startsWith('/') && !next.startsWith('//') ? next : '/')); + } catch (e) { + let text = e.message; + if (document.documentElement.lang === 'ru') { + if (text === 'Invalid authentication code') text = 'Неверный код аутентификации.'; + if (text === 'MFA challenge expired. Sign in again.') text = 'Время проверки MFA истекло. Войдите заново.'; + if (text === 'Too many invalid MFA attempts. Sign in again.') text = 'Слишком много неверных кодов MFA. Войдите заново.'; + } + status('mfa-auth-error', text, 'error'); + button.disabled = false; + } + }); + + $('mfa-login-back')?.addEventListener('click', () => { + $('mfa-login-form').hidden = true; + $('login-form').hidden = false; + status('mfa-auth-error', ''); + $('auth-mfa-code').value = ''; + setTimeout(() => $('auth-password')?.focus(), 30); + }); + + $('password-reset-request-form')?.addEventListener('submit', async event => { + event.preventDefault(); + error(''); + const form = event.currentTarget; + const identifier = $('reset-identifier').value.trim(); + const button = form.querySelector('button[type="submit"]'); + button.disabled = true; + try { + await submit('/api/auth/password-reset/request', {identifier}); + $('reset-confirm-identifier').value = identifier; + form.hidden = true; + $('password-reset-confirm-form').hidden = false; + setTimeout(() => $('reset-code')?.focus(), 30); + } catch (e) { + // This endpoint normally returns a generic success response even when delivery is unavailable. + error(e.message); + button.disabled = false; + } + }); + + $('password-reset-confirm-form')?.addEventListener('submit', async event => { + event.preventDefault(); + status('reset-confirm-status', ''); + const password = $('reset-password').value; + if (password !== $('reset-password-repeat').value) { + status('reset-confirm-status', document.documentElement.lang === 'ru' ? 'Пароли не совпадают.' : 'Passwords do not match.', 'error'); + return; + } + const button = event.currentTarget.querySelector('button[type="submit"]'); + button.disabled = true; + try { + await submit('/api/auth/password-reset/confirm', { + identifier: $('reset-confirm-identifier').value, + code: $('reset-code').value.trim(), + password, + }); + status('reset-confirm-status', document.documentElement.lang === 'ru' ? 'Пароль изменён. Сейчас откроется страница входа.' : 'Password changed. Redirecting to sign in…', 'success'); + setTimeout(() => location.replace(appUrl('/login')), 900); + } catch (e) { + const text = document.documentElement.lang === 'ru' && e.message === 'Invalid or expired reset code' ? 'Неверный или просроченный код.' : e.message; + status('reset-confirm-status', text, 'error'); + button.disabled = false; + } + }); + + $('reset-request-again')?.addEventListener('click', () => { + $('password-reset-confirm-form').hidden = true; + $('password-reset-request-form').hidden = false; + $('reset-code').value = ''; + $('reset-password').value = ''; + $('reset-password-repeat').value = ''; + status('reset-confirm-status', ''); + setTimeout(() => $('reset-identifier')?.focus(), 30); + }); +})(); diff --git a/app/static/js/i18n.js b/app/static/js/i18n.js new file mode 100644 index 0000000..c75a0d0 --- /dev/null +++ b/app/static/js/i18n.js @@ -0,0 +1,20 @@ +window.WGToolsI18n = (() => { + const boot = window.WGTOOLS_I18N || {}; + const messages = boot.messages || {}; + const lang = boot.language || 'en'; + const supported = ['en','ru','de','fr','it','es','pl']; + + function t(key, fallback = key) { return messages[key] || fallback; } + function getLanguage() { return lang; } + function setLanguage(language) { + if (!supported.includes(language)) return; + try { localStorage.setItem('wgtools.language', language); } catch (_) {} + document.cookie = `wgtools_language=${encodeURIComponent(language)}; Path=/; Max-Age=31536000; SameSite=Lax`; + window.location.reload(); + } + async function load(language = lang) { + if (language !== lang) setLanguage(language); + return messages; + } + return { load, t, getLanguage, setLanguage }; +})(); diff --git a/app/static/locales/de.json b/app/static/locales/de.json new file mode 100644 index 0000000..492122e --- /dev/null +++ b/app/static/locales/de.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Benutzer erstellen", + "auth.login_subtitle": "Gib deinen WGTools-Benutzernamen und dein Passwort ein.", + "auth.login_title": "Bei WGTools anmelden", + "auth.password": "Passwort", + "auth.password_repeat": "Passwort wiederholen", + "auth.setup_help": "Das erste Konto erhält vollen Zugriff auf WGTools. Weitere Benutzer können später in den Einstellungen erstellt werden.", + "auth.setup_subtitle": "Vor der Serververwaltung muss ein WGTools-Konto eingerichtet werden.", + "auth.setup_title": "Ersten Benutzer erstellen", + "auth.sign_in": "Anmelden", + "auth.sign_out": "Abmelden", + "auth.username": "Benutzername", + "clients.actions": "Aktionen", + "clients.add": "+ Client hinzufügen", + "clients.address": "VPN-Adresse", + "clients.address_hint": "Die erste freie Adresse wird automatisch vorgeschlagen.", + "clients.allowed_ips_required": "Gib mindestens ein AllowedIPs-Netz für die Client-Konfiguration ein.", + "clients.basic_connection": "Verbindungseinstellungen", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs in Client-Konfiguration", + "clients.config_private_warning": "Diese Konfiguration enthält den privaten Client-Schlüssel. Bewahre sie sicher auf.", + "clients.config_title": "Client-Konfiguration", + "clients.config_unavailable": "Konfiguration nicht verfügbar", + "clients.connection_direct": "Direkt zu WGTools", + "clients.connection_path": "Verbindungsweg", + "clients.connection_relay": "VPS-Relay", + "clients.connection_via": "Verbinden über", + "clients.connection_via_hint": "Wähle den öffentlichen Zugang für diesen Client. Relay ist nur sichtbar, wenn es für die ausgewählte WireGuard-Schnittstelle installiert ist.", + "clients.copy_config": "Kopieren", + "clients.copy_done": "Konfiguration kopiert", + "clients.create_subtitle": "WireGuard-Peer erstellen und Client-Konfiguration erzeugen.", + "clients.create_title": "Client erstellen", + "clients.creating": "Schlüssel werden erstellt und Client angewendet…", + "clients.day_fri": "Fr", + "clients.day_mon": "Mo", + "clients.day_sat": "Sa", + "clients.day_sun": "So", + "clients.day_thu": "Do", + "clients.day_tue": "Di", + "clients.day_wed": "Mi", + "clients.delete_confirm": "Diesen Client aus WireGuard löschen? WGTools erstellt ein Backup und entfernt die automatisch generierten Richtlinienregeln dieses Clients.", + "clients.deleted": "Client gelöscht", + "clients.dns": "DNS (optional)", + "clients.dns_hint": "IPv4-DNS-Server durch Komma trennen.", + "clients.download_config": ".conf herunterladen", + "clients.duplicate": "Duplizieren", + "clients.duplicate_address_error": "Diese VPN-Adresse wird bereits von einem anderen Peer verwendet.", + "clients.duplicate_name_error": "Ein Peer mit diesem Namen existiert bereits.", + "clients.duplicate_ready": "Kopie bereit. WGTools hat einen neuen Namen und eine VPN-Adresse vergeben. Prüfe die Einstellungen vor dem Speichern.", + "clients.duplicate_site_hint": "Remote-Netze wurden entfernt, um doppelte Routen zu vermeiden. Gib die Netze für den neuen Site-to-site-Peer ein.", + "clients.duplicate_suffix": "Kopie", + "clients.edit_subtitle": "Serverseitigen Peer aktualisieren. Änderungen werden ohne WireGuard-Neustart angewendet.", + "clients.edit_title": "Client bearbeiten", + "clients.endpoint": "Server-Endpoint", + "clients.endpoint_hint": "Für Remote-Clients die öffentliche IP oder Domain verwenden, die den WireGuard-Port an diesen Server weiterleitet.", + "clients.existing": "Vorhandener Peer", + "clients.expiration": "Gültigkeitsdauer", + "clients.expiration_action": "Bei Ablauf", + "clients.expiration_action_hint": "Ohne Haken bleibt der Client in WGTools, aber WireGuard-Zugriff wird gesperrt. Neue Laufzeit oder „Kein Ablaufdatum“ wählen und speichern, um ihn freizugeben.", + "clients.expiration_datetime": "Läuft ab am", + "clients.expiration_datetime_hint": "Verwendet lokales Datum und Uhrzeit dieses Browsers.", + "clients.expiration_delete": "Client löschen", + "clients.expiration_future_required": "Wähle Datum und Uhrzeit in der Zukunft.", + "clients.expiration_hint": "Bei Ablauf führt WGTools die gewählte Aktion zur nächsten vollen Minute aus. Zuvor wird ein WireGuard-Backup erstellt.", + "clients.expire_1d": "1 Tag", + "clients.expire_1h": "1 Stunde", + "clients.expire_3h": "3 Stunden", + "clients.expire_6h": "6 Stunden", + "clients.expire_custom": "Eigenes Datum und Uhrzeit", + "clients.expire_never": "Kein Ablaufdatum", + "clients.expired": "Abgelaufen", + "clients.expired_disabled_hint": "Die Gültigkeit ist abgelaufen. Der Client bleibt erhalten, aber WireGuard-Zugriff ist gesperrt. Wähle eine neue Laufzeit oder „Kein Ablaufdatum“ und speichere.", + "clients.expired_disabled_short": "Abgelaufen · deaktiviert", + "clients.expired_disabled_status": "Abgelaufen", + "clients.expires_days": "Läuft in {n} Tagen ab", + "clients.expires_hours": "Läuft in {n} Std. ab", + "clients.expires_minutes": "Läuft in {n} Min. ab", + "clients.generated_config": "Erstellte Client-Konfiguration", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 Sekunden sind ein guter Standardwert für Clients hinter NAT.", + "clients.local_access_exceptions": "Erlaubte lokale Adressen", + "clients.local_access_exceptions_hint": "Optionale IPs oder CIDRs, die trotz Sperre ihres lokalen oder Site-to-site-Netzes erreichbar bleiben. Kommagetrennt eingeben.", + "clients.managed": "Von WGTools verwaltet", + "clients.name": "Name", + "clients.no_peers": "Keine Peers gefunden", + "clients.peers": "Peers", + "clients.peers_subtitle": "Änderungen werden gesichert und mit wg syncconf ohne Neustart der WireGuard-Schnittstelle angewendet.", + "clients.protected_networks_reference": "Gesperrte lokale Netze (Referenz)", + "clients.protected_networks_reference_hint": "Diese Netze erscheinen nicht in AllowedIPs. Der Zugriff wird durch WGTools-Serverregeln gesperrt; einzelne Adressen können oben erlaubt werden.", + "clients.psk": "Zusätzlicher Schlüssel (PSK)", + "clients.psk_enable": "Zusätzlichen WireGuard-PSK verwenden", + "clients.psk_hint": "Empfohlen. Fügt dem WireGuard-Handshake ein zusätzliches symmetrisches Geheimnis hinzu. Standard-Clients unterstützen es; WGTools fügt den PSK in Konfiguration und QR ein.", + "clients.psk_short": "PSK", + "clients.qr_loading": "QR-Code wird erstellt…", + "clients.quick_search": "Schnellsuche", + "clients.quick_search_clear": "Suche löschen", + "clients.quick_search_empty": "Keine passenden Clients gefunden", + "clients.relay_endpoint_note": "Die erstellte Client-Konfiguration verbindet sich mit {endpoint}. Der WireGuard-Server bleibt auf diesem WGTools-Host.", + "clients.relay_required": "Wähle einen VPS-Relay für diesen Client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "nicht verfügbar", + "clients.relay_vps": "VPS-Relay", + "clients.relay_vps_hint": "Der Client-Endpoint wird automatisch aus diesem Relay erstellt.", + "clients.remote_hint": "Netze hinter diesem Peer. Ein Netz pro Zeile oder durch Komma getrennt.", + "clients.remote_networks": "Entfernte Netzwerke", + "clients.remote_required": "Gib mindestens ein Remote-Netz für den Site-to-site-Peer an.", + "clients.required": "Name und VPN-Adresse sind erforderlich.", + "clients.route_custom": "Benutzerdefiniert", + "clients.route_full": "Vollständiger Tunnel", + "clients.route_full_except_local": "Vollständiger Tunnel außer lokalen Netzen", + "clients.route_hint": "Nur diese Netze werden in AllowedIPs der Client-Konfiguration geschrieben.", + "clients.route_preset": "Verkehr über VPN", + "clients.route_vpn": "Nur VPN-Netzwerk", + "clients.route_vpn_lan": "VPN + lokales LAN", + "clients.saved": "Client gespeichert", + "clients.schedule_blocked_short": "Zeitplan · gesperrt", + "clients.schedule_blocked_status": "Durch Zeitplan gesperrt", + "clients.schedule_days": "Erlaubte Tage", + "clients.schedule_days_required": "Wähle mindestens einen Tag für den Zeitplan.", + "clients.schedule_disabled_hint": "Dieser Client wird derzeit durch seinen Zeitplan gesperrt. WGTools stellt den Peer beim nächsten erlaubten Zeitfenster automatisch wieder her.", + "clients.schedule_enable": "Zugriff nach Zeitplan begrenzen", + "clients.schedule_from": "Zugriff ab", + "clients.schedule_hint": "WGTools kann diesen Client an ausgewählten Tagen und Zeiten automatisch sperren und wieder freigeben, ohne seine Konfiguration zu ändern.", + "clients.schedule_short": "Zeitplan", + "clients.schedule_time_required": "Lege Start- und Endzeit des Zeitplans fest.", + "clients.schedule_timezone_hint": "Der Zeitplan verwendet die lokale Uhrzeit des WireGuard-Servers. Zeitfenster über Mitternacht, z. B. 22:00–06:00, werden unterstützt.", + "clients.schedule_title": "Zugriffszeitplan", + "clients.schedule_to": "Zugriff bis", + "clients.security_access": "Sicherheit und Zugriffszeiten", + "clients.server_host": "Serveradresse / Domain", + "clients.server_host_hint": "Öffentliche IP oder Domain dieses Clients. Früher verwendete Werte werden vorgeschlagen.", + "clients.server_host_required": "Serveradresse / Domain ist für die Client-Konfiguration erforderlich.", + "clients.server_peer": "Server-Peer", + "clients.server_port": "WireGuard-Port", + "clients.server_port_hint": "Wird automatisch aus der Serverkonfiguration übernommen.", + "clients.site_to_site": "Standort-zu-Standort", + "clients.status": "Status", + "clients.subtitle": "WireGuard-Peers, Live-Status und Verwaltung der Client-Konfigurationen.", + "clients.tab_basic": "Grundlagen", + "clients.tab_config": "Konfiguration", + "clients.tab_policy": "Richtlinien", + "clients.tab_security": "Sicherheit", + "clients.title": "Clients", + "clients.type": "Typ", + "clients.unmanaged_note": "Dieser Peer existierte vor WGTools. Sein privater Client-Schlüssel kann nicht wiederhergestellt werden. WGTools kann den serverseitigen Peer bearbeiten, aber keine Client-Konfiguration oder QR erzeugen.", + "clients.updating": "Client wird aktualisiert…", + "common.actions": "Aktionen", + "common.ago": "vor", + "common.cancel": "Abbrechen", + "common.checking": "Prüfung läuft…", + "common.close": "Schließen", + "common.config": "Konfiguration", + "common.delete": "Löschen", + "common.disabled": "Deaktiviert", + "common.edit": "Bearbeiten", + "common.enabled": "Aktiviert", + "common.loading": "Wird geladen…", + "common.never": "Nie", + "common.no": "Nein", + "common.not_configured": "Nicht konfiguriert", + "common.not_installed": "Nicht installiert", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Aktualisieren", + "common.running": "Läuft", + "common.save": "Speichern", + "common.stopped": "Angehalten", + "common.total": "Gesamt", + "common.unknown": "Unbekannt", + "common.updated": "Aktualisiert", + "common.yes": "Ja", + "dashboard.active_peers": "Aktive Peers", + "dashboard.active_peers_subtitle": "Live-Daten aus wg show.", + "dashboard.activity": "Systemübersicht", + "dashboard.activity_subtitle": "Schreibgeschützte Prüfungen des laufenden WireGuard-Systems.", + "dashboard.cores": "Kerne", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Letzte 24 Std.", + "dashboard.history_avg": "Ø", + "dashboard.history_max": "Max.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "jetzt", + "dashboard.memory": "Arbeitsspeicher", + "dashboard.network": "Netzwerk", + "dashboard.peers": "Peers", + "dashboard.quick_search": "Schnellsuche", + "dashboard.quick_search_clear": "Suche löschen", + "dashboard.quick_search_empty": "Keine passenden Peers gefunden", + "dashboard.restart": "Neustart", + "dashboard.restart_confirm": "WireGuard neu starten? Aktive VPN-Clients werden automatisch wieder verbunden.", + "dashboard.restart_ok": "WireGuard neu gestartet.", + "dashboard.routing": "Routing", + "dashboard.site_to_site": "Standort-zu-Standort", + "dashboard.start": "Starten", + "dashboard.start_ok": "WireGuard gestartet.", + "dashboard.stop": "Stoppen", + "dashboard.stop_confirm": "WireGuard stoppen? Aktive VPN-Clients werden getrennt.", + "dashboard.stop_ok": "WireGuard gestoppt.", + "dashboard.subtitle": "WireGuard-Serverstatus, Peers und Live-Traffic.", + "dashboard.title": "Übersicht", + "dashboard.traffic": "Datenverkehr", + "dashboard.uptime": "Betriebszeit", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Server-Zugriffsregeln", + "groups.additional_allowed": "Zusätzlich erlaubte Adressen", + "groups.additional_blocked": "Zusätzlich gesperrte Adressen", + "groups.allow": "Erlauben", + "groups.allowed": "Erlaubt", + "groups.allowed_addresses": "Erlaubte Adressen / Netze", + "groups.apply_current_template": "Aktuelle Gruppenvorlage anwenden", + "groups.apply_defaults": "Aktuelle Gruppenvorlage anwenden", + "groups.apply_defaults_hint": "Übernimmt Routen, DNS und Keepalive der Gruppenvorlage für diesen Client. Client speichern und bei Bedarf neue Konfiguration oder QR ausgeben.", + "groups.basic": "Grunddaten", + "groups.block": "Sperren", + "groups.blocked": "Gesperrt", + "groups.blocked_addresses": "Gesperrte Adressen / Netze", + "groups.client_config_source": "Quelle der Client-Konfiguration", + "groups.client_defaults": "Client-Standardwerte", + "groups.client_group_hint": "Optionale Gruppe für wiederverwendbare Zugriffsregeln und Client-Standardwerte. Gruppen gelten nur für die ausgewählte WireGuard-Schnittstelle.", + "groups.config_differs": "Die Client-Konfiguration weicht von den aktuellen Gruppenvorgaben ab. Die Serverregeln sind aktuell; die Konfiguration auf Handy oder PC ändert sich erst nach Ausgabe einer neuen Konfiguration oder eines QR-Codes.", + "groups.config_differs_short": "Client-Konfiguration weicht von Gruppe ab", + "groups.create": "Gruppe erstellen", + "groups.create_title": "Gruppe erstellen", + "groups.created": "Gruppe erstellt", + "groups.creating": "Gruppe wird erstellt…", + "groups.defaults_applied": "Aktuelle Gruppenvorlage übernommen. Client zum Speichern sichern.", + "groups.defaults_hint": "Legt fest, welchen Traffic das Client-Gerät über WireGuard sendet. Die obigen Serverregeln bestimmen separat den erlaubten Zugriff. Änderungen an der Vorlage ändern nie heimlich bereits installierte Konfigurationen.", + "groups.delete_message": "„{name}“ löschen? Client-Konfigurationen werden beim Löschen einer Gruppe nie entfernt.", + "groups.delete_move": "Clients in andere Gruppe verschieben", + "groups.delete_title": "Client-Gruppe löschen", + "groups.delete_unassign": "Gruppenzuordnung der Clients entfernen", + "groups.deleted": "Gruppe gelöscht", + "groups.deleting": "Clients werden aktualisiert und Gruppe gelöscht…", + "groups.description": "Beschreibung", + "groups.edit_title": "Gruppe bearbeiten", + "groups.editor_subtitle": "Eine Gruppe kombiniert aktive Server-Zugriffsregeln mit einer Vorlage für neue Client-Konfigurationen.", + "groups.effective_allow": "Erlaubte Ausnahmen", + "groups.effective_deny": "Gesperrte Ausnahmen", + "groups.effective_policy": "Wirksame Serverregeln", + "groups.empty": "Noch keine Client-Gruppen. Erstelle eine Gruppe, um Zugriffsregeln und Client-Standardwerte wiederzuverwenden.", + "groups.group": "Gruppe", + "groups.inherit": "Übernehmen", + "groups.internet_access": "Internetzugriff", + "groups.internet_short": "Internet", + "groups.local_access": "Lokale Netzwerke", + "groups.local_short": "Lokal", + "groups.manage": "Gruppen", + "groups.members_count": "{count} Clients", + "groups.name": "Name", + "groups.name_required": "Gruppenname erforderlich.", + "groups.new_client_defaults": "Client-Konfigurationsvorlage", + "groups.new_clients_short": "Neue Clients", + "groups.no_group": "Keine Gruppe", + "groups.none": "Keine", + "groups.override_client_config": "Gruppenvorlage für diesen Client überschreiben", + "groups.override_client_config_hint": "Aus: Routen, DNS und Keepalive kommen aus der Gruppenvorlage. Ein: Dieser Client nutzt eigene Werte. Änderungen an den Serverregeln oben bleiben unabhängig.", + "groups.policy_addresses_hint": "IPv4-Adressen oder CIDRs, durch Komma getrennt. Client-Ausnahmen haben Vorrang vor Gruppenausnahmen.", + "groups.policy_custom": "Eigene Regeln", + "groups.policy_inherit": "Gruppenregeln verwenden", + "groups.policy_mode": "Regelquelle", + "groups.policy_mode_hint": "Standardmäßig gelten die Gruppenregeln. Client-Ausnahmen ändern nie die Gruppe selbst.", + "groups.routes_required": "Client-Routen dürfen nicht leer sein.", + "groups.subtitle": "Server-Zugriffsregeln und Standardwerte für normale Clients auf der gewählten WireGuard-Schnittstelle wiederverwenden.", + "groups.title": "Client-Gruppen", + "groups.traffic_through_vpn": "Verkehr über VPN", + "groups.updated": "Gruppe aktualisiert", + "groups.updating": "Gruppenregeln werden aktualisiert…", + "help.example_note": "Alle Adressen, Schnittstellen, Peer-Namen und Domains in der Hilfe sind fiktiv. Ersetze sie durch Werte aus deinem Netzwerk.", + "help.navigation": "Hilfe-Navigation", + "help.open": "Hilfe öffnen", + "help.subtitle": "Verständliche Hilfe für Dashboard, Server, Clients und Einstellungen mit kurzen Beispielen.", + "help.title": "WGTools-Hilfe", + "interfaces.add": "+ Schnittstelle hinzufügen", + "interfaces.create": "Schnittstelle erstellen", + "interfaces.create_confirm": "Schnittstelle {name} erstellen und starten?", + "interfaces.create_failed": "Schnittstelle konnte nicht erstellt werden", + "interfaces.create_hint": "WGTools prüft vor der Erstellung, dass VPN-Netz, UDP-Port und Policy-Routing-Tabelle nicht mit anderen WireGuard-Schnittstellen kollidieren.", + "interfaces.create_subtitle": "Eine unabhängige WireGuard-Schnittstelle mit eigenem Adresspool, UDP-Port und Routing-Einstellungen erstellen.", + "interfaces.create_title": "WireGuard-Schnittstelle hinzufügen", + "interfaces.created": "Schnittstelle erfolgreich erstellt.", + "interfaces.creating": "Schlüssel werden erzeugt, Konfiguration gespeichert und WireGuard gestartet…", + "interfaces.current": "Aktuell", + "interfaces.delete": "Löschen", + "interfaces.delete_confirm": "Schnittstelle {name} löschen? Ihre WireGuard-Konfiguration und alle Peers werden entfernt. Zuvor wird ein Backup erstellt.", + "interfaces.delete_failed": "Schnittstelle konnte nicht gelöscht werden", + "interfaces.delete_last": "Die letzte konfigurierte WireGuard-Schnittstelle kann hier nicht gelöscht werden.", + "interfaces.delete_tooltip": "Diese WireGuard-Schnittstelle löschen", + "interfaces.deleted": "Schnittstelle gelöscht. Backup: {backup}", + "interfaces.deleting": "WireGuard wird gestoppt und Schnittstelle gelöscht…", + "interfaces.display_name": "Anzeigename", + "interfaces.display_name_edit_hint": "Nur Anzeigename; der Linux-Schnittstellenname bleibt unverändert.", + "interfaces.display_name_hint": "Optionaler Anzeigename, z. B. Arbeit oder Auftragnehmer.", + "interfaces.identity": "Schnittstellenkennung", + "interfaces.none": "Keine WireGuard-Schnittstellen gefunden", + "interfaces.none_configured": "Noch keine WireGuard-Schnittstellen konfiguriert.", + "interfaces.peers_short": "Peers", + "interfaces.rename_failed": "Anzeigename der Schnittstelle konnte nicht gespeichert werden.", + "interfaces.select": "Auswählen", + "interfaces.subtitle": "Jede Schnittstelle hat ein eigenes VPN-Netz, einen Port, Peers und Regeln. Wähle eine, um sie in WGTools zu verwalten.", + "interfaces.switch_title": "WireGuard-Schnittstellen", + "interfaces.system_name": "Systemname", + "interfaces.system_name_hint": "Linux-Schnittstellenname, z. B. wg1. Nach der Erstellung unveränderbar.", + "interfaces.title": "WireGuard-Schnittstellen", + "interfaces.unique_port_hint": "Jede WireGuard-Schnittstelle auf diesem Server muss einen eigenen UDP-Port verwenden.", + "interfaces.unique_table_hint": "WGTools empfiehlt eine eigene Routing-Tabelle pro Schnittstelle. Für normales Routing leer lassen.", + "nav.clients": "Clients", + "nav.dashboard": "Übersicht", + "nav.server": "Server", + "nav.settings": "Einstellungen", + "server.access_apply_confirm": "Diese Firewall-Regel speichern und anwenden? WireGuard wird kurz neu gestartet und ein Backup erstellt.", + "server.access_rule_deleted": "Zugriffsregel gelöscht.", + "server.access_rule_help": "Allgemeine FORWARD-Zugriffsregel erstellen, ohne iptables-Befehle manuell zu bearbeiten.", + "server.access_rule_order_hint": "WGTools fügt Zugriffsregeln am Anfang der FORWARD-Kette ein, damit Einschränkungen vor allgemeinen VPN-ACCEPT-Regeln greifen.", + "server.access_rule_saved": "Zugriffsregel gespeichert und angewendet.", + "server.action": "Aktion", + "server.action_hint": "REJECT meldet dem Client die Ablehnung; DROP verwirft still; ACCEPT erlaubt ausdrücklich.", + "server.add_access_rule": "Zugriffsregel hinzufügen", + "server.add_route": "Route hinzufügen", + "server.address": "Adresse", + "server.any": "Beliebig", + "server.any_protocol": "Beliebig", + "server.apply_confirm": "Servereinstellungen speichern und anwenden? WireGuard wird kurz neu gestartet. Zuvor erstellt WGTools ein Backup und stellt bei Startfehlern automatisch die vorherige Konfiguration wieder her.", + "server.apply_settings": "Speichern und anwenden", + "server.applying_rule": "Backup wird erstellt und Änderungen angewendet…", + "server.applying_settings": "Einstellungen werden geprüft, Backup erstellt und angewendet…", + "server.basic_settings": "Grundeinstellungen", + "server.config_tab_help": "Rohkonfigurationseditor der ausgewählten WireGuard-Schnittstelle öffnen.", + "server.create_confirm": "WireGuard-Server mit diesen Einstellungen erstellen und starten?", + "server.create_server": "Server erstellen", + "server.create_step_conf": "Konfiguration der ausgewählten WireGuard-Schnittstelle mit Modus 600 erstellen.", + "server.create_step_forward": "Forwarding, NAT und optionales Policy-Routing einrichten.", + "server.create_step_key": "Neues Server-Schlüsselpaar erzeugen.", + "server.create_step_start": "Ausgewählte wg-quick-Schnittstelle aktivieren und starten.", + "server.create_subtitle": "WireGuard ist installiert, aber die ausgewählte Schnittstelle ist noch nicht konfiguriert.", + "server.create_success": "WireGuard-Server erfolgreich erstellt.", + "server.create_title": "WireGuard-Server erstellen", + "server.creating": "Schlüssel werden erzeugt, Konfiguration gespeichert und WireGuard gestartet…", + "server.custom_preserved": "Peer-Blöcke, Site-to-site-Routen und eigene PostUp/PostDown-Regeln außerhalb dieser Felder bleiben erhalten.", + "server.delete_access_confirm": "Diese Zugriffsregel löschen und Änderung anwenden?", + "server.delete_route_confirm": "Diese eigene Route löschen und Änderung anwenden?", + "server.destination": "Ziel", + "server.destination_hint": "Leer = beliebig. IP, CIDR oder IP-Bereich. Mehrere Ziele durch Komma trennen.", + "server.destination_port": "Zielport", + "server.destination_port_hint": "Optional. Port wie 443 oder Bereich wie 10000:20000. Erst TCP oder UDP auswählen.", + "server.details": "Details", + "server.dev_word": "dev", + "server.diagnostics": "Diagnose", + "server.diagnostics_done": "Diagnose abgeschlossen", + "server.diagnostics_subtitle": "Aktuelle Systemprüfungen. Keine Konfigurationsänderung.", + "server.direction": "Hook", + "server.edit_access_rule": "Zugriffsregel bearbeiten", + "server.edit_route": "Route bearbeiten", + "server.edit_server": "Server bearbeiten", + "server.edit_subtitle": "Allgemeine WireGuard-, Routing- und NAT-Einstellungen bearbeiten. Vorhandene Peers und eigene Regeln bleiben erhalten.", + "server.edit_title": "Servereinstellungen", + "server.edit_warning": "Beim Anwenden von Schnittstellen-, Routing- oder Firewall-Einstellungen wird WireGuard kurz neu gestartet. Aktive Peers verbinden sich automatisch neu.", + "server.enable_forwarding": "IPv4-Forwarding aktivieren", + "server.enable_nat": "NAT / Masquerade aktivieren", + "server.firewall": "Firewall & NAT", + "server.firewall_subtitle": "Erkannte Regeln aus WireGuard-Hooks.", + "server.firewall_subtitle_v08": "Allgemeine Forwarding-/NAT- und Zugriffsregeln der Schnittstelle. Einfache Regeln können hier bearbeitet werden, komplexe im Rohkonfigurationseditor.", + "server.forward_from_vpn": "Weiterleitung aus VPN erlauben", + "server.forward_to_vpn": "Weiterleitung ins VPN erlauben", + "server.forwarding_section": "Forwarding und NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Nur bei Verwendung einer Policy-Routing-Tabelle erforderlich.", + "server.install_success": "WireGuard erfolgreich installiert.", + "server.install_wireguard": "WireGuard installieren", + "server.install_wireguard_help": "Führt apt update aus und installiert WireGuard sowie benötigte Netzwerktools.", + "server.install_wireguard_title": "WireGuard installieren", + "server.installing": "WireGuard wird installiert… Kann eine Minute dauern.", + "server.interface": "Schnittstelle", + "server.interface_hint": "WGTools verwaltet derzeit diese Schnittstelle.", + "server.interface_name": "Schnittstelle", + "server.interface_section": "WireGuard-Schnittstelle", + "server.ip_forwarding": "IPv4-Forwarding", + "server.kind": "Art", + "server.listen_port": "Listen-Port", + "server.local_network": "Lokales Netz", + "server.local_network_hint": "Optionale Route zur Policy-Tabelle hinzufügen.", + "server.managed_automatically": "Automatisch verwaltet", + "server.nat": "NAT / Masquerade", + "server.network": "Netzwerk", + "server.network_settings": "Netzwerk und NAT", + "server.no_firewall": "Keine Firewall-Regeln gefunden", + "server.no_routes": "Keine Routen gefunden", + "server.not_configured": "Nicht konfiguriert", + "server.not_set": "Nicht gesetzt", + "server.policy_disabled_hint": "Für normales System-Routing deaktivieren. Nur aktivieren, wenn dieses VPN eine eigene quellbasierte Routing-Tabelle benötigt.", + "server.policy_enabled": "Policy-Routing aktivieren", + "server.policy_table": "Policy-Tabelle", + "server.policy_table_hint": "Für normales Routing leer lassen; für quellbasiertes Policy-Routing z. B. 200 verwenden.", + "server.port_word": "Port", + "server.private_hidden": "Konfiguriert (ausgeblendet)", + "server.private_key": "Privater Schlüssel", + "server.protocol": "Protokoll", + "server.route_apply_confirm": "Diese Route speichern und anwenden? WireGuard wird kurz neu gestartet und ein Backup erstellt.", + "server.route_custom": "Benutzerdefiniert", + "server.route_deleted": "Route gelöscht.", + "server.route_device_hint": "Optionale Ausgabeschnittstelle, z. B. wg0 oder enp6s18.", + "server.route_editor_help": "Route hinzufügen, die beim WireGuard-Start erstellt und beim Stoppen entfernt wird.", + "server.route_gateway_hint": "Optionales Next-Hop-Gateway. Gateway oder Schnittstelle ist erforderlich.", + "server.route_managed_peer": "Site-to-site-Peer", + "server.route_managed_server": "Servereinstellung", + "server.route_network_hint": "IPv4-Netz, z. B. 10.20.0.0/24, oder 'default'.", + "server.route_saved": "Route gespeichert und angewendet.", + "server.route_table_hint": "Für normales Routing 'main' oder eine numerische Tabelle wie 200 verwenden.", + "server.route_type": "Typ", + "server.routes": "Erkannte Routen", + "server.routes_subtitle": "Aus PostUp/PostDown und aktuellem Policy-Routing gelesene Routen.", + "server.routes_subtitle_v08": "Server-, Site-to-site- und eigene Routen der ausgewählten Schnittstelle. Eigene Routen können hier erstellt, bearbeitet und entfernt werden.", + "server.routing": "Routing", + "server.routing_section": "Routing", + "server.rule": "Regel", + "server.rule_access": "Zugriffsregel", + "server.rule_advanced": "Erweitert", + "server.rule_apply_warning": "Beim Anwenden einer Route oder Firewall-Regel wird WireGuard kurz neu gestartet. WGTools erstellt ein Backup und stellt die vorherige Konfiguration bei Startfehlern automatisch wieder her.", + "server.rule_client_exception": "Ausnahme für Client", + "server.rule_client_policy": "Client-Regel", + "server.rule_managed_server": "Servereinstellung", + "server.rule_type": "Typ", + "server.run_diagnostics": "Diagnose starten", + "server.save_apply": "Speichern und anwenden", + "server.save_config": "SaveConfig", + "server.server_address": "Server-VPN-Adresse", + "server.server_address_hint": "Gewöhnlich die erste nutzbare Adresse im VPN-Netz.", + "server.settings_applied": "Servereinstellungen erfolgreich gespeichert und angewendet.", + "server.settings_apply_failed": "Servereinstellungen konnten nicht angewendet werden", + "server.setup_required": "Einrichtung erforderlich", + "server.source": "Quelle", + "server.source_hint": "Leer = beliebig. IP, CIDR oder Bereich wie 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installation, Ersteinrichtung und aktuelle Konfiguration des WireGuard-Servers.", + "server.tab_config": "Konfiguration", + "server.tab_interface": "Schnittstelle", + "server.tab_routing": "Routing", + "server.tab_vps": "VPS", + "server.table": "Tabelle", + "server.tabs_aria": "Abschnitte der Servereinstellungen", + "server.title": "Server", + "server.uplink": "Uplink-Schnittstelle", + "server.use_raw_editor": "Rohkonfigurationseditor verwenden", + "server.via": "Über / Gerät", + "server.via_word": "via", + "server.vpn_network": "VPN-Netzwerk", + "server.vpn_network_hint": "Client-Adressen werden später aus diesem Netz vergeben.", + "server.vpn_pool": "VPN-Adresspool", + "server.wg_not_installed": "WireGuard ist nicht installiert", + "server.wg_not_installed_subtitle": "WGTools kann die benötigten Debian-Pakete automatisch installieren.", + "server.what_happens": "Was WGTools ausführt", + "settings.about": "Über", + "settings.add_user": "Benutzer hinzufügen", + "settings.advanced": "Erweitert", + "settings.advanced_subtitle": "Direkter Zugriff auf erweiterte WireGuard-Konfiguration.", + "settings.appearance": "Darstellung", + "settings.applying_config": "Konfiguration wird geprüft, Backup erstellt und angewendet…", + "settings.backup_count": "Gespeicherte Backups", + "settings.backup_retention": "Anzahl aufzubewahrender Backups", + "settings.backup_retention_help": "Alte automatische Backups werden nach Erstellung eines neuen Backups entfernt. 1–200 Dateien.", + "settings.backups": "Konfigurations-Backups", + "settings.backups_always_on": "Aktiviert", + "settings.backups_subtitle": "WGTools erstellt vor Änderungen an der Konfiguration automatisch ein Backup. Automatische Backups können nicht deaktiviert werden.", + "settings.change_password": "Passwort ändern", + "settings.check_updates": "Auf Updates prüfen", + "settings.config_applied": "Konfiguration erfolgreich gespeichert und angewendet.", + "settings.config_applied_restarted": "Konfiguration angewendet, WireGuard neu gestartet.", + "settings.config_applied_stopped": "Konfiguration gespeichert. WireGuard war gestoppt und bleibt gestoppt.", + "settings.config_apply_failed": "Konfiguration konnte nicht angewendet werden", + "settings.config_load_failed": "Konfiguration konnte nicht geladen werden", + "settings.current_user": "Aktueller Benutzer", + "settings.current_version": "Aktuelle Version", + "settings.audit_action": "Aktion", + "settings.audit_empty": "Noch keine Audit-Ereignisse", + "settings.audit_log": "Audit-Protokoll", + "settings.audit_log_subtitle": "Aktionen im Panel, Anmeldungen, Telegram und WireGuard-Verbindungsverlauf. Geheimnisse werden hier nie protokolliert.", + "settings.audit_object": "Objekt", + "settings.audit_result": "Ergebnis", + "settings.audit_retention_note": "Aufbewahrung: 30 Tage", + "settings.audit_search": "Schnellsuche", + "settings.audit_search_clear": "Suche löschen", + "settings.audit_search_empty": "Keine passenden Audit-Ereignisse", + "settings.audit_time": "Datum / Uhrzeit", + "settings.audit_user": "Benutzer", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Zugriffsregel erstellt", + "audit.action.access_rule.deleted": "Zugriffsregel gelöscht", + "audit.action.access_rule.updated": "Zugriffsregel geändert", + "audit.action.auth.first_user_created": "Erster Benutzer erstellt", + "audit.action.auth.login": "Angemeldet", + "audit.action.auth.login_failed": "Anmeldung fehlgeschlagen", + "audit.action.auth.logout": "Abgemeldet", + "audit.action.backup.full_created": "Vollständiges Backup erstellt", + "audit.action.backup.full_restored": "Vollständiges Backup wiederhergestellt", + "audit.action.client.config_downloaded": "Client-Konfiguration heruntergeladen", + "audit.action.client.config_viewed": "Client-Konfiguration angezeigt", + "audit.action.client.created": "Client erstellt", + "audit.action.client.deleted": "Client gelöscht", + "audit.action.client.qr_viewed": "Client-QR-Code angezeigt", + "audit.action.client.updated": "Client aktualisiert", + "audit.action.client_group.created": "Client-Gruppe erstellt", + "audit.action.client_group.deleted": "Client-Gruppe gelöscht", + "audit.action.client_group.updated": "Client-Gruppe aktualisiert", + "audit.action.interface.created": "Schnittstelle erstellt", + "audit.action.interface.deleted": "Schnittstelle gelöscht", + "audit.action.interface.renamed": "Schnittstelle umbenannt", + "audit.action.route.created": "Route erstellt", + "audit.action.route.deleted": "Route gelöscht", + "audit.action.route.updated": "Route aktualisiert", + "audit.action.server.created": "Server erstellt", + "audit.action.server.raw_config_applied": "Rohkonfiguration angewendet", + "audit.action.server.settings_applied": "Servereinstellungen angewendet", + "audit.action.settings.updated": "Panel-Einstellungen geändert", + "audit.action.telegram.action_denied": "Telegram-Aktion verweigert", + "audit.action.telegram.action_failed": "Telegram-Aktion fehlgeschlagen", + "audit.action.telegram.connection_test": "Telegram-Verbindungstest", + "audit.action.telegram.settings_updated": "Telegram-Einstellungen geändert", + "audit.action.update.checked": "Auf Update geprüft", + "audit.action.update.scheduled": "Update geplant", + "audit.action.update.backup_created": "Backup vor Update", + "audit.action.update.completed": "Update abgeschlossen", + "audit.action.update.failed": "Update fehlgeschlagen", + "audit.action.update.rollback_completed": "Vorherige Version wiederhergestellt", + "audit.action.update.rollback_failed": "Update-Rollback fehlgeschlagen", + "audit.action.user.created": "Benutzer erstellt", + "audit.action.user.deleted": "Benutzer gelöscht", + "audit.action.user.password_changed": "Benutzerpasswort geändert", + "audit.action.vps.candidate_deleted": "VPS-Kandidat gelöscht", + "audit.action.vps.candidate_saved": "VPS-Kandidat gespeichert", + "audit.action.vps.detached": "VPS-Relay getrennt", + "audit.action.vps.relay_installed": "VPS-Relay installiert", + "audit.action.wireguard.client_connected": "WireGuard-Client verbunden", + "audit.action.wireguard.installed": "WireGuard installiert", + "audit.action.wireguard.restarted": "WireGuard neu gestartet", + "audit.action.wireguard.started": "WireGuard gestartet", + "audit.action.wireguard.stopped": "WireGuard gestoppt", + "audit.result.applied": "angewendet", + "audit.result.available": "verfügbar", + "audit.result.changed": "geändert", + "audit.result.created": "erstellt", + "audit.result.current": "aktuell", + "audit.result.deleted": "gelöscht", + "audit.result.detached": "getrennt", + "audit.result.denied": "verweigert", + "audit.result.downloaded": "heruntergeladen", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Fehler", + "audit.result.installed": "installiert", + "audit.result.invalid_credentials": "ungültige Zugangsdaten", + "audit.result.ok": "OK", + "audit.result.queued": "in Warteschlange", + "audit.result.restarted": "neu gestartet", + "audit.result.restored": "wiederhergestellt", + "audit.result.rotated": "erneuert", + "audit.result.saved": "gespeichert", + "audit.result.shown": "angezeigt", + "audit.result.started": "gestartet", + "audit.result.stopped": "gestoppt", + "audit.result.updated": "aktualisiert", + "settings.delete_user": "Löschen", + "settings.delete_user_confirm": "Benutzer {name} löschen?", + "settings.edit_raw_config": "Schnittstellenkonfiguration bearbeiten", + "settings.expert_mode": "Experte", + "settings.full_backup_component_clients": "Von WGTools verwaltete Client-Metadaten, private Schlüssel, PSKs, Ablaufzeiten und Gruppenzuordnungen zur Wiederherstellung von Konfigurationen/QR-Codes.", + "settings.full_backup_component_db": "WGTools-Datenbank: Benutzer, App-Einstellungen, E-Mail/SMTP, Telegram und gespeicherter VPS-Relay-Status.", + "settings.full_backup_component_relay": "VPS-Relay-Wiederherstellungsdaten: Controller-/Tenant-IDs, Verwaltungstoken und Home-Transportschlüssel. Danach kann WGTools den lokalen Transport wieder aufbauen und sich mit dem bestehenden VPS-Tenant verbinden.", + "settings.full_backup_component_system": "WGTools-sysctl-Datei für IPv4-Forwarding, Anzeigenamen der Schnittstellen sowie Gruppenregeln und Standardvorlagen (falls vorhanden). Der automatische Konfigurationsverlauf je Schnittstelle ist absichtlich ausgeschlossen.", + "settings.full_backup_component_wg": "Alle erkannten WireGuard-Schnittstellenkonfigurationen aus /etc/wireguard/ samt Status (gestartet/gestoppt).", + "settings.full_backup_create_failed": "Vollständiges Backup konnte nicht erstellt werden", + "settings.full_backup_creating": "Vollständiges Backup wird erstellt…", + "settings.full_backup_download": "Erstellen", + "settings.full_backup_downloaded": "Backup erstellt und heruntergeladen. Sicher aufbewahren.", + "settings.full_backup_downloaded_short": "Vollständiges Backup heruntergeladen.", + "settings.full_backup_help": "Erstellt ein übertragbares WGTools-Backup für Umzug oder Notfall. Enthält WireGuard-Konfigurationen, Benutzer, Einstellungen, Gruppen, verwaltete Clients und Daten zum Wiederverbinden bestehender VPS-Relay-Tenants.", + "settings.full_backup_no_file": "Kein Backup ausgewählt", + "settings.full_backup_restore": "Wiederherstellen", + "settings.full_backup_restore_confirm": "Vollständiges WGTools-Backup wiederherstellen? Aktuelle Benutzer, Einstellungen, verwaltete Clients und alle im Backup enthaltenen WireGuard-Konfigurationen werden ersetzt. Schnittstellen können neu starten. WGTools erstellt vorher ein Sicherheitsbackup und stellt bei Fehlern den vorherigen Zustand wieder her.", + "settings.full_backup_restore_failed": "Wiederherstellung fehlgeschlagen", + "settings.full_backup_restored": "Backup erfolgreich wiederhergestellt. Melde dich mit einem Konto aus dem Backup an.", + "settings.full_backup_restored_short": "Backup wiederhergestellt.", + "settings.full_backup_restoring": "Backup wird geprüft, Sicherheitskopie erstellt und wiederhergestellt…", + "settings.full_backup_secret_warning": "Diese Datei enthält geheime Daten: private WireGuard- und Client-Schlüssel, PSKs, WGTools-Passworthashes, Telegram-Bot-Token und gespeichertes SMTP-Passwort. Wie ein Passwort schützen und niemals an öffentliche Issues oder Chats anhängen.", + "settings.full_backup_select": "Auswählen", + "settings.full_backup_title": "Vollständiges Backup und Wiederherstellung", + "settings.full_mode": "Server- und Client-Verwaltung aktiviert", + "settings.interface_help": "Die verwaltete WireGuard-Schnittstelle wird bei der WGTools-Installation ausgewählt.", + "settings.language": "Sprache", + "settings.last_backup": "Letztes Backup", + "settings.latest_version": "Neueste Version", + "settings.loading_config": "Konfiguration wird geladen…", + "settings.mode": "Modus", + "settings.never_logged_in": "Nie", + "settings.new_password": "Neues Passwort", + "settings.no_backups": "Noch keine Backups", + "settings.online_help": "Ein Peer gilt als online, wenn sein letzter Handshake jünger als dieser Wert ist. 30–3600 Sekunden.", + "settings.online_threshold": "Online-Schwelle", + "settings.open_release": "Release öffnen", + "settings.password_changed": "Passwort geändert.", + "settings.passwords_mismatch": "Passwörter stimmen nicht überein.", + "settings.project_github": "Projekt / GitHub", + "settings.raw_config_confirm": "WireGuard-Konfiguration speichern und anwenden? Die ausgewählte Schnittstelle wird neu gestartet. Zuvor wird ein Backup erstellt. Bei Startfehlern stellt WGTools den vorherigen Zustand automatisch wieder her.", + "settings.raw_config_help": "Quellkonfiguration der ausgewählten WireGuard-Schnittstelle öffnen.", + "settings.raw_config_title": "WireGuard-Rohkonfiguration", + "settings.raw_config_warning": "Expertenmodus: Dies ist die echte WireGuard-Serverkonfiguration einschließlich privatem Server-Schlüssel und Peer-PSKs. Speichern und Anwenden startet die Schnittstelle neu. WGTools erstellt vorher ein Backup und stellt bei Startfehlern automatisch wieder her.", + "settings.readonly_mode": "Client-Verwaltung aktiviert", + "settings.refresh_help": "Intervall der Live-Statusabfrage durch WGTools. 2–60 Sekunden.", + "settings.refresh_interval": "Aktualisierungsintervall", + "settings.release_notes": "Versionshinweise", + "settings.reload_config": "Von Datenträger neu laden", + "settings.save_apply": "Speichern und anwenden", + "settings.saved": "Einstellungen gespeichert.", + "settings.saved_reload": "Einstellungen gespeichert. Seite wird neu geladen…", + "settings.saving": "Einstellungen werden gespeichert…", + "settings.status": "Statusaktualisierung", + "settings.status_help": "Aktualisierungsintervall für Dashboard und Peer-Status.", + "settings.subtitle": "WGTools-Oberfläche und Status-Einstellungen.", + "settings.syntax_hint": "WireGuard-Abschnitte, Schlüssel, Werte und Kommentare werden beim Bearbeiten hervorgehoben.", + "settings.tab_about": "Über", + "settings.tab_backups": "Backups", + "settings.tab_general": "Allgemein", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Benutzer", + "settings.tabs_aria": "Einstellungsbereiche", + "settings.telegram": "Telegram-Bot", + "settings.telegram_allowed_ids": "Zugelassene Telegram-Benutzer-IDs", + "settings.telegram_allowed_ids_help": "Eine numerische Benutzer-ID pro Zeile. Ein nicht autorisierter /start-Aufruf zeigt die Telegram-ID des Absenders, die du hier hinzufügen kannst.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Verbunden", + "settings.telegram_disabled": "Deaktiviert", + "settings.telegram_dns": "Standard-Client-DNS", + "settings.telegram_dns_help": "Optionale IPv4-DNS-Adressen, durch Komma getrennt. Für vom Bot erstellte Clients.", + "settings.telegram_enabled": "Telegram-Bot aktivieren", + "settings.telegram_endpoint": "Standard-Serveradresse / Domain", + "settings.telegram_endpoint_help": "Für neue Client-Konfigurationen des Bots. Nur IP oder Domain eingeben; WireGuard-Port wird aus der Serverkonfiguration gelesen.", + "settings.telegram_language": "Bot-Sprache", + "settings.telegram_language_auto": "Automatisch (Telegram-Sprache)", + "settings.telegram_last_poll": "Letzter Telegram-Kontakt", + "settings.telegram_not_configured": "Nicht konfiguriert", + "settings.telegram_remove_token": "Token entfernen", + "settings.telegram_remove_token_confirm": "Gespeicherten Telegram-Bot-Token entfernen und Bot deaktivieren?", + "settings.telegram_save": "Telegram-Einstellungen speichern", + "settings.telegram_saved": "Telegram-Einstellungen gespeichert.", + "settings.telegram_setup_note": "Bot mit @BotFather erstellen, Token speichern, Bot aktivieren und /start senden. Falls deine Benutzer-ID nicht autorisiert ist, zeigt WGTools sie an — füge sie zur Liste zugelassener Telegram-IDs hinzu.", + "settings.telegram_status": "Bot-Status", + "settings.telegram_subtitle": "WireGuard-Verwaltung über Telegram: Serverstatus, Clients, Erstellen/Löschen und Start/Neustart/Stopp.", + "settings.telegram_test": "Verbindung testen", + "settings.telegram_test_ok": "Telegram-Verbindung funktioniert: @{username}", + "settings.telegram_test_recent_ok": "Telegram-Bot funktioniert. Direkte Prüfung hat Zeitlimit überschritten, aber Bot hat Telegram kürzlich erreicht.", + "settings.telegram_token": "Bot-Token", + "settings.telegram_token_help": "Bot mit @BotFather erstellen und Bot-API-Token hier einfügen. API ID und API Hash sind für die Telegram Bot API nicht nötig.", + "settings.telegram_token_keep": "Leer lassen, um gespeicherten Token zu behalten.", + "settings.telegram_waiting": "Konfiguriert, wartet auf Bot-Dienst", + "settings.theme": "Darstellung", + "settings.theme_dark": "Dunkel", + "settings.theme_light": "Hell", + "settings.theme_system": "System", + "settings.title": "Einstellungen", + "settings.update_available": "Update verfügbar", + "settings.update_backup_queued": "Update vorgemerkt. WGTools erstellt vor Installation automatisch ein vollständiges Backup…", + "settings.update_backup_running": "Vollständiges Backup vor Update wird erstellt…", + "settings.update_check_failed": "Prüfung auf Updates fehlgeschlagen", + "settings.update_checking": "Neueste veröffentlichte GitHub Release wird geprüft…", + "settings.update_confirm": "WGTools von v{current} auf v{latest} aktualisieren? Zuvor werden ein vollständiges Backup und eine Rollback-Kopie erstellt. Die Weboberfläche wird kurz neu gestartet.", + "settings.update_current": "Aktuell", + "settings.update_downloading": "GitHub-Release wird heruntergeladen und geprüft…", + "settings.update_failed": "WGTools-Update fehlgeschlagen.", + "settings.update_installing": "Update wird installiert. Die Weboberfläche kann kurz nicht erreichbar sein…", + "settings.update_no_update": "WGTools ist bereits auf dem neuesten Stand.", + "settings.update_not_checked": "Nicht geprüft", + "settings.update_queued": "Update vorgemerkt. Warte auf den Update-Dienst…", + "settings.update_rollback_ok": "Vorherige WGTools-Version wurde automatisch wiederhergestellt.", + "settings.update_rolling_back": "Update fehlgeschlagen. Vorherige WGTools-Version wird wiederhergestellt…", + "settings.update_running": "Sicherheits-Backups werden erstellt…", + "settings.update_safety_hint": "Updates erfolgen nur auf Wunsch. WGTools erstellt vor der Installation ein vollständiges Backup und eine Rollback-Kopie. Bei Fehlern wird die vorherige Anwendung automatisch wiederhergestellt. WireGuard selbst wird nur neu gestartet, wenn das neue Release ausdrücklich seine Konfiguration ändert.", + "settings.update_sidebar": "Neue Version verfügbar", + "settings.update_sidebar_hint": "Einstellungen → Über", + "settings.update_starting": "Update wird gestartet…", + "settings.update_status_unknown": "Update-Status nicht verfügbar. Neuer Versuch…", + "settings.update_subtitle": "Projektinformationen, automatische Release-Prüfung und sichere Updates über GitHub Releases.", + "settings.update_success": "WGTools erfolgreich auf v{version} aktualisiert. Seite wird neu geladen…", + "settings.update_wgtools": "WGTools aktualisieren", + "settings.user_actions": "Aktionen", + "settings.user_created": "Erstellt", + "settings.user_created_ok": "Benutzer erstellt.", + "settings.user_deleted": "Benutzer gelöscht.", + "settings.user_equal_rights": "Alle WGTools-Benutzer haben dieselben Berechtigungen.", + "settings.user_last_login": "Letzte Anmeldung", + "settings.user_name": "Benutzername", + "settings.users": "Benutzer", + "settings.users_subtitle": "Lokale WGTools-Konten. E-Mail ist optional und wird bei aktivierter E-Mail-Funktion nur für Passwortwiederherstellung genutzt.", + "vps.add": "VPS hinzufügen", + "vps.add_help": "WGTools prüft oder installiert Relay per SSH. Passwörter und private SSH-Schlüssel werden nie gespeichert.", + "vps.add_title": "VPS hinzufügen", + "vps.agent": "Relay-Agent", + "vps.agent_found": "Bereits installiert", + "vps.agent_will_install": "Wird installiert", + "vps.arch": "Architektur", + "vps.auth_method": "Authentifizierung", + "vps.authentication": "SSH-Authentifizierung", + "vps.check": "VPS prüfen", + "vps.check_failed": "VPS-Prüfung fehlgeschlagen", + "vps.check_link": "Verbindung prüfen", + "vps.check_ok": "VPS ist kompatibel", + "vps.checking": "SSH-Zugang und VPS-Kompatibilität werden geprüft…", + "vps.connections": "Verbindungen", + "vps.credentials_not_saved": "Nur für diese Prüfung verwendet und nicht von WGTools gespeichert.", + "vps.delete_candidate": "Entfernen", + "vps.delete_installed": "VPS entfernen", + "vps.delete_installed_confirm": "„{name}“ aus WGTools entfernen? Der lokale Relay-Transport wird getrennt, aber Relay-Agent und Tenant bleiben auf dem VPS erhalten. Wenn du den VPS erneut hinzufügst, verbindet sich WGTools mit dem bestehenden Relay, statt einen neuen zu erstellen. Clients dieses Relay können bis zur Wiederverbindung nicht darauf zugreifen.", + "vps.delete_installed_failed": "VPS konnte nicht aus WGTools entfernt werden", + "vps.delete_installed_ok": "VPS aus WGTools entfernt. Remote-Relay bleibt erhalten und kann wiederverbunden werden.", + "vps.empty_help": "Füge einen Debian- oder Ubuntu-VPS hinzu, um SSH-Zugang, Systemkompatibilität und erforderliche UDP-Ports zu prüfen.", + "vps.empty_title": "Kein VPS eingerichtet", + "vps.endpoint": "Öffentlicher Endpoint", + "vps.endpoint_domain": "Domain (empfohlen)", + "vps.endpoint_domain_hint": "Wenn du später den Haupt-VPS austauschst, können Client-Konfigurationen durch eine DNS-Änderung unverändert bleiben.", + "vps.health_failed": "Relay-Verbindungsprüfung fehlgeschlagen", + "vps.host": "IP / Hostname", + "vps.host_key": "SSH-Hostschlüssel", + "vps.identity": "VPS-Verbindung", + "vps.install_failed": "Relay-Installation fehlgeschlagen", + "vps.install_ok": "Relay installiert und geschützte Verwaltungsverbindung geprüft", + "vps.install_relay": "Relay installieren", + "vps.install_title": "VPS-Relay installieren", + "vps.installed": "Installiert", + "vps.installing": "Relay-Agent wird installiert und geschützter Transporttunnel aufgebaut…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Schlüssel-Passphrase", + "vps.link_ok": "Relay-Verbindung OK", + "vps.multi_tenant_note": "Auf diesem VPS läuft bereits ein WGTools-Relay-Agent. Er wird nicht ersetzt: Dieses WGTools erhält eine eigene isolierte Verbindung mit eigenen Schlüsseln und UDP-Ports.", + "vps.name": "Name", + "vps.no_domain": "IP-Endpoint", + "vps.not_installed": "Wird installiert", + "vps.os": "Betriebssystem", + "vps.password": "Passwort", + "vps.phase_note": "Relay-Agent unterstützt mehrere unabhängige WGTools-Controller auf einem VPS. Jeder Controller erhält isolierte Verbindung, Schlüssel und UDP-Ports; bestehende Verbindungen bleiben unberührt.", + "vps.port_pair": "UDP-Ports", + "vps.ports_adjusted": "freie Ports ausgewählt", + "vps.private_key": "Privater Schlüssel", + "vps.privilege": "Berechtigungen", + "vps.public_endpoint": "Künftiger öffentlicher Endpoint", + "vps.ready_help": "SSH-Zugangsdaten werden nur für Kompatibilitätsprüfung und direkte Relay-Installation verwendet; sie werden nicht gespeichert.", + "vps.reconnect_note": "Auf diesem VPS wurde eine bestehende Relay-Verbindung dieses WGTools gefunden. WGTools verbindet sich mit demselben Tenant; neue Tenants oder UDP-Ports werden nicht erstellt.", + "vps.reconnect_ok": "Bestehenden Relay erfolgreich wiederverbunden", + "vps.reconnect_relay": "Relay wiederverbinden", + "vps.relay_port": "Relay-UDP-Port", + "vps.remove_confirm": "Diesen VPS-Kandidaten entfernen? Es wurden keine Remote-Änderungen vorgenommen.", + "vps.save_candidate": "Kandidaten speichern", + "vps.saved": "VPS-Kandidat gespeichert", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH-Schlüssel", + "vps.ssh_port": "SSH-Port", + "vps.ssh_user": "SSH-Benutzer", + "vps.status_candidate": "Bereit zur Installation", + "vps.status_installed": "Relay verbunden", + "vps.subtitle": "Öffentlichen VPS für Remote-Zugriff vorbereiten, wenn dieser WGTools-Server keine öffentliche IP hat.", + "vps.tenant": "Verbindung", + "vps.title": "VPS-Relay", + "vps.transport_port": "Transport-UDP-Port", + "vps.transport_port_hint": "Separater UDP-Port für privaten Home-↔-VPS-Transporttunnel.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Gespeichert", + "vps.active_short": "Aktiv", + "dashboard.traffic_reset": "Zurücksetzen", + "dashboard.traffic_reset_confirm": "Aufgelaufene WireGuard-Traffic-Zähler dieser Schnittstelle zurücksetzen? Auch die Client-Zähler beginnen bei null.", + "dashboard.traffic_reset_done": "Traffic-Zähler zurückgesetzt", + "dashboard.traffic_reset_failed": "Traffic-Zähler konnten nicht zurückgesetzt werden", + "audit.action.traffic.reset": "Traffic-Zähler zurückgesetzt", + "audit.result.reset": "zurückgesetzt", + "server.mtu": "MTU", + "server.mtu_auto": "Automatisch", + "server.mtu_hint": "Optional. Für automatische MTU durch wg-quick leer lassen. Nur bei Bedarf, z. B. LTE oder PPPoE, 1380 oder 1420 einstellen.", + "clients.peer_isolation": "VPN-Client-Isolation", + "clients.peer_isolation_enable": "Von anderen VPN-Clients isolieren", + "clients.peer_isolation_hint": "Blockiert den Verkehr zwischen diesem Client und anderen Adressen im WireGuard-Pool. Der Zugriff auf Server, Internet, lokale und Site-to-site-Netze wird weiterhin durch andere Regeln gesteuert.", + "clients.credentials_rotate": "Client-Schlüssel", + "clients.credentials_rotate_button": "Schlüssel erneuern", + "clients.credentials_rotate_confirm": "Neue Schlüssel für diesen Client erzeugen? Bei aktiver Verbindung wird seine WireGuard-Sitzung sofort getrennt. Anschließend neue Konfiguration oder QR übermitteln.", + "clients.credentials_rotate_confirm_psk": "Neues Schlüsselpaar und neuen PSK für diesen Client erzeugen? Bei aktiver Verbindung wird seine WireGuard-Sitzung sofort getrennt. Anschließend neue Konfiguration oder QR senden.", + "clients.credentials_rotate_hint": "Erneuert PrivateKey/PublicKey und bei aktiviertem PSK auch diesen. Adresse, Routen, Gruppe, Zeitplan, Isolation und gespeicherte Statistiken bleiben erhalten.", + "clients.credentials_rotating": "Neue Schlüssel werden erstellt, alte Sitzung getrennt…", + "clients.credentials_rotated": "Client-Schlüssel geändert. Die alte Sitzung wurde gegebenenfalls getrennt. Die alte Konfiguration funktioniert nicht mehr; sende vor dem nächsten Verbindungsaufbau neue Konfiguration oder QR.", + "clients.credentials_rotated_short": "Client-Schlüssel geändert — neue Konfiguration nötig", + "audit.action.client.credentials_rotated": "Client-Schlüssel erneuert", + "clients.credentials_connection_lost": "Verbindung zu WGTools unterbrochen. Falls dieses Panel über den Client mit gerade erneuerten Schlüsseln geöffnet war, ist das normal: seine alte WireGuard-Sitzung wurde sofort getrennt. Verbinde dich über einen anderen Weg und erstelle neue Konfiguration oder QR.", + "nav.navigation": "Hauptnavigation", + "nav.project_github": "WGTools auf GitHub", + "auth.email": "E-Mail", + "auth.email_optional_help": "Jetzt optional. Kann nach Einrichtung der E-Mail-Funktion zur Passwortwiederherstellung dienen.", + "auth.forgot_password": "Passwort vergessen?", + "auth.reset_title": "Passwort zurücksetzen", + "auth.reset_subtitle": "Einmalcode per E-Mail erhalten und neues WGTools-Passwort festlegen.", + "auth.reset_identifier": "Benutzername oder E-Mail", + "auth.reset_identifier_help": "Zum Schutz der Privatsphäre zeigt WGTools immer dieselbe Antwort, ob das Konto existiert oder nicht.", + "auth.send_reset_code": "Code senden", + "auth.reset_code_sent_generic": "Wenn das Konto existiert und eine E-Mail-Adresse hat, wurde ein Reset-Code gesendet. Er ist 15 Minuten gültig.", + "auth.reset_code": "6-stelliger Code", + "auth.set_new_password": "Neues Passwort festlegen", + "auth.request_another_code": "Neuen Code anfordern", + "auth.back_to_login": "Zur Anmeldung", + "auth.reset_not_configured": "E-Mail-Passwortwiederherstellung ist nicht eingerichtet. Wende dich an den WGTools-Administrator.", + "settings.tab_mail": "E-Mail", + "settings.mail": "E-Mail / SMTP", + "settings.mail_subtitle": "SMTP dient zur Passwortwiederherstellung.", + "settings.mail_not_configured": "Nicht konfiguriert", + "settings.mail_enabled": "E-Mail und Passwortwiederherstellung aktivieren", + "settings.mail_smtp_host": "SMTP-Server", + "settings.mail_smtp_port": "SMTP-Port", + "settings.mail_security": "Verschlüsselung", + "settings.mail_security_none": "Keine Verschlüsselung", + "settings.mail_username": "SMTP-Benutzername", + "settings.mail_username_help": "Für SMTP-Anmeldung und als Absender-E-Mail-Adresse verwendet.", + "settings.mail_password": "SMTP-Passwort", + "settings.mail_password_keep": "Leer lassen, um gespeichertes Passwort beizubehalten.", + "settings.mail_from_email": "Absender-E-Mail", + "settings.mail_from_name": "Absendername", + "settings.mail_test_recipient": "Testempfänger", + "settings.mail_test_recipient_help": "Der Test verwendet die aktuell gespeicherten SMTP-Einstellungen.", + "settings.mail_remove_password": "Passwort entfernen", + "settings.mail_test": "Test senden", + "settings.mail_save": "E-Mail-Einstellungen speichern", + "settings.mail_enabled_badge": "Aktiviert", + "settings.mail_disabled_badge": "Deaktiviert", + "settings.mail_saved": "E-Mail-Einstellungen gespeichert.", + "settings.mail_remove_password_confirm": "Gespeichertes SMTP-Passwort entfernen und E-Mail deaktivieren?", + "settings.mail_password_removed": "SMTP-Passwort entfernt und E-Mail deaktiviert.", + "settings.mail_test_recipient_required": "E-Mail-Adresse des Testempfängers eingeben.", + "settings.mail_testing": "Test-E-Mail wird gesendet…", + "settings.mail_test_ok": "Test-E-Mail erfolgreich gesendet.", + "settings.user_email": "E-Mail", + "settings.user_email_help": "Optional. Nur für eigenständige Passwortwiederherstellung nötig.", + "settings.change_email": "E-Mail", + "settings.user_email_saved": "E-Mail gespeichert.", + "settings.send_password_reset": "Reset senden", + "settings.user_reset_mail_not_configured": "Zuerst E-Mail einrichten und aktivieren.", + "settings.user_reset_email_missing": "Zuerst E-Mail-Adresse hinzufügen.", + "settings.user_reset_confirm": "Passwort-Reset-Code an {name} unter {email} senden?", + "settings.user_reset_sent": "Passwort-Reset-Code an {email} gesendet.", + "audit.action.auth.password_reset_requested": "Passwortzurücksetzung angefordert", + "audit.action.auth.password_reset_code_sent": "Passwort-Reset-Code gesendet", + "audit.action.auth.password_reset_completed": "Passwort zurückgesetzt", + "audit.action.auth.password_reset_failed": "Passwortzurücksetzung fehlgeschlagen", + "audit.action.mail.settings_updated": "E-Mail-Einstellungen geändert", + "audit.action.mail.test_sent": "Test-E-Mail gesendet", + "audit.action.mail.test_failed": "Test-E-Mail fehlgeschlagen", + "audit.action.user.email_changed": "Benutzer-E-Mail geändert", + "audit.action.user.password_reset_sent": "Passwort-Reset an Benutzer gesendet", + "audit.action.user.password_reset_failed": "Benutzer-Passwort-Reset fehlgeschlagen", + "audit.result.accepted": "angenommen", + "audit.result.sent": "gesendet", + "audit.result.invalid_code": "ungültiger Code", + "common.copy": "Kopieren", + "common.copied": "Kopiert", + "clients.use_panel_host": "Paneladresse verwenden", + "clients.use_panel_host_done": "Paneladresse eingefügt: {host}", + "clients.use_panel_host_failed": "Paneladresse konnte nicht aus der Browser-URL ermittelt werden.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Integriertes Let’s-Encrypt-HTTPS für direkten WGTools-Zugriff ohne Reverse-Proxy.", + "settings.https_disabled": "Deaktiviert", + "settings.https_enabled": "Aktiviert", + "settings.https_enable": "Integriertes HTTPS aktivieren", + "settings.https_type": "Zertifikat für", + "settings.https_domain": "Domain", + "settings.https_public_ip": "Öffentliche IP", + "settings.https_target": "Domain oder öffentliche IP", + "settings.https_email": "Let’s-Encrypt-E-Mail", + "settings.https_port": "HTTPS-Port", + "settings.https_port80_note": "TCP-Port 80 muss für die Ausstellung und Verlängerung des Zertifikats aus dem Internet erreichbar sein. Den gewählten HTTPS-Port für das Panel ebenfalls öffnen.", + "settings.https_check_ports": "Ports prüfen", + "settings.https_certificate": "Zertifikat", + "settings.https_certificate_ready": "Bereit", + "settings.https_certificate_missing": "Nicht ausgestellt", + "settings.https_expires": "Gültig bis", + "settings.https_renewal": "Automatische Verlängerung", + "settings.https_renewal_enabled": "Aktiviert", + "settings.https_renewal_disabled": "Deaktiviert", + "settings.https_certificate_path": "Zertifikat", + "settings.https_private_key_path": "Privater Schlüssel", + "settings.https_issue": "Zertifikat anfordern / erneuern", + "settings.https_port_free": "Frei", + "settings.https_port_busy": "Belegt", + "settings.https_ports_checked": "Portprüfung abgeschlossen.", + "settings.https_target_email_required": "Domain/öffentliche IP und Let’s-Encrypt-E-Mail eingeben.", + "settings.https_issue_confirm": "Let’s-Encrypt-Zertifikat für {target} anfordern oder erneuern? Die HTTPS-Einstellungen werden gespeichert. TCP-Port 80 muss aus dem Internet erreichbar sein.", + "settings.https_issuing": "Let’s-Encrypt-Zertifikat wird angefordert…", + "settings.https_issue_ok": "Zertifikat bereit.", + "settings.https_already_enabled": "Integriertes HTTPS ist bereits aktiviert.", + "settings.https_already_disabled": "Integriertes HTTPS ist bereits deaktiviert.", + "settings.https_enable_confirm": "Integriertes HTTPS auf TCP {port} mit Pfad {path} aktivieren? WGTools wird neu gestartet und die Seite unter der neuen Adresse wiederverbunden.", + "settings.https_disable_confirm": "Integriertes HTTPS deaktivieren und WGTools wieder über HTTP öffnen?", + "settings.https_switching": "HTTPS wird aktiviert und WGTools neu gestartet…", + "settings.https_switching_http": "HTTPS wird deaktiviert und WGTools neu gestartet…", + "audit.action.https.certificate_issued": "HTTPS-Zertifikat ausgestellt", + "audit.action.https.certificate_failed": "HTTPS-Zertifikatsanfrage fehlgeschlagen", + "audit.action.https.enabled": "HTTPS aktiviert", + "audit.action.https.disabled": "HTTPS deaktiviert", + "audit.result.issued": "ausgestellt", + "audit.result.enabled": "aktiviert", + "audit.result.disabled": "deaktiviert", + "settings.https_access_path": "Panel-Zugriffspfad", + "settings.https_access_path_help": "Eigenen Pfad wählen. Bei integriertem HTTPS erhalten Anfragen außerhalb dieses Pfads einen 404-Fehler.", + "settings.https_enable_fields_required": "Domain/öffentliche IP, Let’s-Encrypt-E-Mail und Panel-Pfad eingeben.", + "settings.https_use_panel_host": "Paneladresse verwenden", + "settings.https_reconnecting": "WGTools wechselt zur neuen HTTPS-Adresse…", + "server.tab_nodes": "Knoten", + "common.type": "Typ", + "common.status": "Status", + "common.copy_failed": "Kopieren fehlgeschlagen", + "clients.vpn_address": "VPN-Adresse", + "nodes.title": "WGTools Nodes", + "nodes.subtitle": "Mehrere WGTools-Server sicher verbinden und nur die Netze veröffentlichen, die andere Nodes erreichen dürfen.", + "nodes.enable_hub": "HUB aktivieren", + "nodes.connect_hub": "Mit HUB verbinden", + "nodes.settings": "Node-Einstellungen", + "nodes.settings_action": "Einstellungen", + "nodes.sync_now": "Synchronisieren", + "nodes.disable": "Nodes deaktivieren", + "nodes.disable_action": "Trennen", + "nodes.join_title": "Neue Nodes verbinden", + "nodes.join_help": "Einmalcode erzeugen und zusammen mit dem HUB-Service-Endpoint (z. B. vpn.example.com:51950) in einer anderen WGTools-Oberfläche eingeben. Der Code ist 15 Minuten gültig und einmal verwendbar.", + "nodes.create_code": "Code erstellen", + "nodes.connected_nodes": "Verbundene Nodes", + "nodes.connected_nodes_help": "Informationen zu anderen Panels, veröffentlichten Netzen und Clients. Remote-Clients sind schreibgeschützt.", + "nodes.enable_hub_help": "Dieses Panel wird zum zentralen Node. Über denselben Port akzeptiert HUB WireGuard per UDP und die geschützte Erstkopplung per TCP.", + "nodes.node_name": "Node-Name", + "nodes.transport_network": "Node-Transportnetz", + "nodes.transport_help": "Eigenes privates Netz nur für die WGTools-zu-WGTools-Verbindung. Darf sich nicht mit VPN-/LAN-Netzen überschneiden.", + "nodes.panel_url": "Panel-URL", + "nodes.panel_url_help": "Optional. Nur ein Informationslink für „Panel öffnen“ auf anderen Nodes; wird nie für die Node-Verbindung genutzt.", + "nodes.extra_networks": "Zusätzliche Node-Netze", + "nodes.extra_networks_help": "Ein Netz pro Zeile. VPN-Netze der Schnittstellen und Remote-Netze von Site-to-site-Clients werden automatisch veröffentlicht. Hier nur weitere geroutete LAN-/Netze ergänzen, z. B. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools trägt erkannte VPN-, Site-to-site- und lokale geroutete LAN-Netze ein. Behalte nur die Netze, die dieser Node veröffentlichen soll. Ein Netz pro Zeile.", + "nodes.published_networks_settings_help": "Ein Netz pro Zeile. Dies ist die explizite Liste der von diesem Node veröffentlichten Netze. Entfernen einer Zeile beendet die Ankündigung an andere Nodes.", + "nodes.available_networks_help": "Aktuell erkannt: {networks}. Neue Netze werden nicht automatisch veröffentlicht; füge gewünschte oben hinzu.", + "nodes.available_networks_none": "Zurzeit keine weiteren lokalen Netze erkannt.", + "nodes.connect_help": "HUB-Service-Endpoint und Einmalcode eingeben. Panel-URL, HTTPS-Port, Zertifikat und privater Pfad werden für die Nodes-Kopplung nicht verwendet.", + "nodes.join_code": "Code zum Verbinden", + "nodes.connect_reachability_note": "Die Erstkopplung erfolgt über geschütztes TCP auf dem angegebenen Port. Nach Erstellung von wgnode0 werden Netze, Status, Versionen und schreibgeschützte Client-Daten über die interne WireGuard-Adresse mit HUB synchronisiert.", + "nodes.connect": "Verbinden", + "nodes.settings_help": "Node-Name, optionaler Link „Panel öffnen“ und Liste veröffentlichter Netze. Panel-URL wird weder zur Kopplung noch zur Synchronisierung verwendet.", + "nodes.details": "Details", + "nodes.not_configured": "WGTools Nodes nicht eingerichtet", + "nodes.not_configured_help": "Aktiviere HUB auf diesem Panel oder verbinde es mit einem bestehenden WGTools-HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Mit HUB verbunden", + "nodes.mode_none": "Nicht konfiguriert", + "nodes.role": "Rolle", + "nodes.tunnel": "Node-Tunnel", + "nodes.node_ip": "Node-Adresse", + "nodes.endpoint": "HUB-Endpoint", + "nodes.published_networks": "Veröffentlichte Netze", + "nodes.last_sync": "Letzte Synchronisierung", + "nodes.no_nodes_hub": "Noch keine Nodes verbunden. Erstelle einen Verbindungscode und verwende ihn auf einem anderen WGTools-Panel.", + "nodes.no_nodes_spoke": "Noch keine Informationen zu anderen Nodes empfangen.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Panel öffnen", + "nodes.route_conflict": "Routenkonflikt", + "nodes.no_published_networks": "Keine veröffentlichten Netze", + "nodes.load_failed": "WGTools Nodes konnte nicht geladen werden", + "nodes.enable_hub_confirm": "WGTools HUB aktivieren und internen WireGuard-Node-Tunnel erstellen?", + "nodes.applying": "WGTools-Node-Tunnel wird eingerichtet…", + "nodes.enable_failed": "HUB konnte nicht aktiviert werden", + "nodes.hub_enabled": "WGTools HUB aktiviert", + "nodes.connecting": "HUB-Code wird geprüft und geschützter Node-Tunnel erstellt…", + "nodes.connect_failed": "Verbindung mit HUB fehlgeschlagen", + "nodes.connected": "Mit WGTools HUB verbunden", + "nodes.settings_failed": "Node-Einstellungen konnten nicht gespeichert werden", + "nodes.settings_saved": "Node-Einstellungen gespeichert", + "nodes.code_failed": "Verbindungscode konnte nicht erstellt werden", + "nodes.code_expires": "Einmalcode. Gültig bis {time}.", + "nodes.code_copied": "Verbindungscode kopiert", + "nodes.network_vpn": "VPN-Clients", + "nodes.network_site_to_site": "Site-to-site-Netz", + "nodes.network_custom": "Zusätzliches Netz", + "nodes.conflict": "Konflikt", + "nodes.remote_clients": "Clients (schreibgeschützt)", + "nodes.no_clients": "Dieser Node meldet keine Clients", + "nodes.details_failed": "Node-Details konnten nicht geladen werden", + "nodes.remove_confirm": "Node „{name}“ aus HUB entfernen? Sein Zugang zum internen Tunnel wird widerrufen.", + "nodes.remove_failed": "Node konnte nicht entfernt werden", + "nodes.removed": "Node entfernt", + "nodes.disable_hub_confirm": "HUB deaktivieren und alle WGTools Nodes trennen? Der interne Node-Tunnel wird entfernt.", + "nodes.disconnect_confirm": "Dieses WGTools-Panel vom HUB trennen und internen Node-Tunnel entfernen?", + "nodes.disable_failed": "WGTools Nodes konnte nicht deaktiviert werden", + "nodes.disabled": "WGTools Nodes deaktiviert", + "nodes.sync_failed": "Node-Synchronisierung fehlgeschlagen", + "nodes.synced": "Node-Informationen synchronisiert", + "nodes.service_port": "Nodes-Port", + "nodes.service_port_help": "Dieselbe Portnummer wird gleichzeitig genutzt: UDP für WireGuard und TCP für die geschützte Erstkopplung.", + "nodes.hub_port_forward_note": "Liegt HUB hinter NAT, leite denselben Port für UDP und TCP an ihn weiter. WGTools-Webport, HTTPS und privater Panel-Pfad gehören nicht zu Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Nodes-Domain/IP und Port ohne http:// oder https://, z. B. vpn.example.com:51950.", + "settings.collapse_sidebar": "Seitenleiste einklappen", + "settings.expand_sidebar": "Seitenleiste ausklappen", + "settings.https_issue_fields_required": "Domain/öffentliche IP, Let’s-Encrypt-E-Mail und Panel-Pfad eingeben.", + "settings.https_issue_ok_saved": "Zertifikat bereit und HTTPS-Einstellungen gespeichert.", + "settings.https_enable_need_certificate": "Zuerst ein Zertifikat anfordern.", + "settings.https_enable_certificate_mismatch": "Zuerst Zertifikat für die aktuelle Domain oder IP anfordern.", + "settings.https_enable_certificate_expired": "Zertifikat abgelaufen. Vor HTTPS-Aktivierung erneuern.", + "settings.https_enable_certificate_ready": "Zertifikat bereit — integriertes HTTPS kann aktiviert werden.", + "settings.https_enable_active_help": "Haken entfernen und speichern, um zu HTTP zurückzukehren.", + "settings.https_certificate_expired": "Abgelaufen", + "settings.https_certificate_wrong_target": "Für andere Adresse", + "nodes.network_conflict_error": "Veröffentlichte Netze überschneiden sich mit anderem Node oder dem Nodes-Transportnetz: {conflicts}. Entferne oder ändere das betroffene Netz.", + "nodes.networks_changed": "Erkannte Netze haben sich seit dem Speichern geändert. Neu: {added}. Nicht mehr erkannt: {removed}. Prüfe die veröffentlichte Liste und speichere nach Kontrolle.", + "nodes.review_networks": "Netze prüfen", + "nodes.vpn_pool_mismatch": "VPN-Pool geändert: Nodes veröffentlicht weiterhin {old}, aktuell ist {current}. Öffne die Node-Einstellungen und aktualisiere die veröffentlichten Netze.", + "server.error_vpn_network_invalid": "VPN-Netz muss ein gültiges IPv4-Netz sein, z. B. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Nur IPv4-VPN-Netze werden unterstützt.", + "server.error_vpn_network_too_small": "Das VPN-Netz muss mindestens zwei nutzbare Adressen enthalten.", + "server.error_vpn_network_no_hosts": "Das gewählte VPN-Netz hat keine nutzbaren Serveradressen.", + "server.error_server_address_prefix": "Server-VPN-Adresse muss ein Präfix enthalten, z. B. 10.0.0.1/24.", + "server.error_server_address_network": "Die Server-VPN-Adresse muss zum gewählten Adresspool gehören und das gleiche Präfix verwenden.", + "server.error_server_address_reserved": "Die Server-VPN-Adresse darf nicht die Netz- oder Broadcast-Adresse sein.", + "server.error_listen_port_number": "Der WireGuard-Port muss eine Zahl sein.", + "server.error_listen_port_range": "Der WireGuard-Port muss zwischen 1 und 65535 liegen.", + "server.error_mtu_number": "MTU muss eine Zahl sein.", + "auth.mfa_title": "Zwei-Faktor-Authentifizierung", + "auth.mfa_login_help": "Gib den sechsstelligen Code aus Google Authenticator oder einen Wiederherstellungscode ein.", + "auth.mfa_code": "Authentifizierungscode", + "auth.mfa_verify": "Prüfen und anmelden", + "auth.mfa_back": "Zurück zum Passwort", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Zwei-Faktor-Authentifizierung (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Aktiviert", + "settings.mfa_disabled": "Deaktiviert", + "settings.mfa_google_help": "Schütze dieses Konto mit Google Authenticator oder einer anderen TOTP-App. Für die Einrichtung ist dein aktuelles Passwort nötig.", + "settings.current_password": "Aktuelles Passwort", + "settings.mfa_start": "Google Authenticator einrichten", + "settings.mfa_secret": "Manueller Einrichtungsschlüssel", + "settings.mfa_scan_help": "QR-Code mit Google Authenticator scannen und aktuellen sechsstelligen Code eingeben, um MFA zu aktivieren.", + "settings.mfa_code": "6-stelliger Code", + "settings.mfa_enable": "MFA aktivieren", + "settings.mfa_manage_help": "Zum Ändern von MFA aktuelles Passwort und Google-Authenticator-Code oder Wiederherstellungscode eingeben.", + "settings.mfa_code_or_recovery": "Authenticator- oder Wiederherstellungscode", + "settings.mfa_regenerate": "Neue Wiederherstellungscodes", + "settings.mfa_disable": "MFA deaktivieren", + "settings.mfa_recovery_title": "Wiederherstellungscodes", + "settings.mfa_recovery_help": "Speichere diese Codes jetzt. Jeder kann einmalig genutzt werden, wenn Google Authenticator nicht verfügbar ist. Sie werden nicht erneut angezeigt.", + "settings.mfa_recovery_remaining": "Verbleibende Wiederherstellungscodes: {count}", + "settings.mfa_enabled_ok": "MFA aktiviert.", + "settings.mfa_disabled_ok": "MFA deaktiviert.", + "settings.mfa_disable_confirm": "Zwei-Faktor-Authentifizierung für dieses Konto deaktivieren?", + "settings.mfa_regenerate_confirm": "Alle bestehenden Wiederherstellungscodes ersetzen?", + "settings.mfa_recovery_regenerated": "Neue Wiederherstellungscodes erstellt.", + "audit.action.auth.mfa_failed": "MFA-Prüfung fehlgeschlagen", + "audit.action.auth.mfa_recovery_used": "MFA-Wiederherstellungscode verwendet", + "audit.action.user.mfa_setup_started": "MFA-Einrichtung begonnen", + "audit.action.user.mfa_enabled": "MFA aktiviert", + "audit.action.user.mfa_disabled": "MFA deaktiviert", + "audit.action.user.mfa_disabled_cli": "MFA über CLI deaktiviert", + "audit.action.user.mfa_recovery_regenerated": "MFA-Wiederherstellungscodes erneuert", + "settings.mfa_error_password": "Aktuelles Passwort ungültig.", + "settings.mfa_error_code": "Authentifizierungscode ungültig.", + "settings.mfa_error_already_enabled": "MFA ist bereits aktiviert.", + "settings.mfa_error_not_enabled": "MFA ist nicht aktiviert.", + "settings.mfa_error_not_started": "MFA-Einrichtung erneut beginnen.", + "trace.title": "Traceroute, Ping und Routenkarte", + "trace.subtitle": "Latenz zu einem VPS oder Server messen und Verzögerungen entlang der Route erkennen.", + "trace.target": "Server-IP oder Hostname", + "trace.show_map": "Route auf Karte zeigen", + "trace.run": "Traceroute starten", + "trace.geo_note": "Geolokalisierung ist ungenau. Bei aktivierter Karte werden öffentliche Hop-IPs zur Standortabfrage an ipwho.is gesendet; Kartenkacheln stammen von OpenStreetMap.", + "trace.latency_note": "Traceroute misst die Latenz in Millisekunden, nicht den Durchsatz in Mbit/s.", + "trace.map": "Routenkarte", + "trace.map_hint": "Interaktive Karte: ziehen zum Verschieben, Mausrad oder +/− zum Zoomen, Hop anklicken für Details.", + "trace.hop": "Hop / IP", + "trace.location": "Standort", + "trace.avg_rtt": "Ø RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Verlust", + "trace.summary_target": "Ziel", + "trace.summary_ping": "Durchschnittlicher Ping", + "trace.summary_loss": "Ping-Verlust", + "trace.summary_hops": "Hops", + "trace.no_reply": "Keine Antwort", + "trace.private": "Privates Netzwerk", + "trace.unknown": "Unbekannt", + "trace.running": "Ping und Traceroute laufen… Das kann bis zu einer Minute dauern.", + "trace.done": "Netzwerktrace abgeschlossen.", + "trace.failed": "Netzwerktrace fehlgeschlagen", + "trace.partial_geo": "Einige öffentliche Hops konnten nicht geolokalisiert werden.", + "trace.not_reached": "Ziel per Traceroute nicht erreicht.", + "trace.reached": "Ziel erreicht", + "trace.ms": "ms", + "server.tab_trace": "Routenverfolgung", + "trace.map_controls": "Kartensteuerung", + "trace.zoom_in": "Vergrößern", + "trace.zoom_out": "Verkleinern", + "trace.fit_route": "Gesamte Route anzeigen", + "trace.fit": "Anpassen", + "trace.map_click_hint": "Für IP, Standort, ASN und RTT auf einen Hop klicken.", + "trace.route_path": "Route", + "trace.ping_ok_trace_filtered": "Ziel antwortet auf Ping, die letzten Traceroute-Hops nicht.", + "trace.latency_legend": "Latenzanstieg zwischen antwortenden Hops", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — erhöht", + "trace.latency_bad": "Δ RTT > 20 ms — starker Sprung" +} diff --git a/app/static/locales/en.json b/app/static/locales/en.json new file mode 100644 index 0000000..0c385e2 --- /dev/null +++ b/app/static/locales/en.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Create user", + "auth.login_subtitle": "Enter your WGTools username and password.", + "auth.login_title": "Sign in to WGTools", + "auth.password": "Password", + "auth.password_repeat": "Repeat password", + "auth.setup_help": "The first account has full WGTools access. Additional users can be created later in Settings.", + "auth.setup_subtitle": "WGTools requires an account before server management is available.", + "auth.setup_title": "Create the first user", + "auth.sign_in": "Sign in", + "auth.sign_out": "Sign out", + "auth.username": "Username", + "clients.actions": "Actions", + "clients.add": "+ Add client", + "clients.address": "VPN address", + "clients.address_hint": "The first free address is suggested automatically.", + "clients.allowed_ips_required": "Enter at least one AllowedIPs network for the client configuration.", + "clients.basic_connection": "Connection settings", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs in client config", + "clients.config_private_warning": "This configuration contains the client's private key. Store it securely.", + "clients.config_title": "Client configuration", + "clients.config_unavailable": "Configuration unavailable", + "clients.connection_direct": "Directly to WGTools", + "clients.connection_path": "Connection path", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Connect through", + "clients.connection_via_hint": "Choose the public entry point used by this client. Relay is shown only when one is installed for the selected WireGuard interface.", + "clients.copy_config": "Copy", + "clients.copy_done": "Configuration copied", + "clients.create_subtitle": "Create a WireGuard peer and generate its client configuration.", + "clients.create_title": "Create client", + "clients.creating": "Creating keys and applying client…", + "clients.day_fri": "Fri", + "clients.day_mon": "Mon", + "clients.day_sat": "Sat", + "clients.day_sun": "Sun", + "clients.day_thu": "Thu", + "clients.day_tue": "Tue", + "clients.day_wed": "Wed", + "clients.delete_confirm": "Delete this client from WireGuard? WGTools will create a backup and remove the automatically generated policy rules tied to this client.", + "clients.deleted": "Client deleted", + "clients.dns": "DNS (optional)", + "clients.dns_hint": "Comma-separated IPv4 DNS servers.", + "clients.download_config": "Download .conf", + "clients.duplicate": "Duplicate", + "clients.duplicate_address_error": "This VPN address is already used by another peer.", + "clients.duplicate_name_error": "A peer with this name already exists.", + "clients.duplicate_ready": "A copy is ready. WGTools assigned a new name and VPN address; review the settings before saving.", + "clients.duplicate_site_hint": "Remote networks were cleared to prevent duplicate routes. Enter the networks for the new Site-to-site peer.", + "clients.duplicate_suffix": "copy", + "clients.edit_subtitle": "Update the server-side peer. Changes are applied without restarting WireGuard.", + "clients.edit_title": "Edit client", + "clients.endpoint": "Server endpoint", + "clients.endpoint_hint": "For remote clients use the public IP/domain that forwards the WireGuard port to this server.", + "clients.existing": "Existing peer", + "clients.expiration": "Access lifetime", + "clients.expiration_action": "At expiration", + "clients.expiration_action_hint": "If unchecked, the client remains in WGTools but WireGuard access is disabled. Set a new lifetime or No expiration and save to restore access.", + "clients.expiration_datetime": "Expires at", + "clients.expiration_datetime_hint": "Uses the local date and time of this browser.", + "clients.expiration_delete": "Delete client", + "clients.expiration_future_required": "Choose a future expiration date and time.", + "clients.expiration_hint": "At expiration WGTools performs the selected action on the next minute boundary. A WireGuard config backup is created first.", + "clients.expire_1d": "1 day", + "clients.expire_1h": "1 hour", + "clients.expire_3h": "3 hours", + "clients.expire_6h": "6 hours", + "clients.expire_custom": "Custom date and time", + "clients.expire_never": "No expiration", + "clients.expired": "Expired", + "clients.expired_disabled_hint": "This access lifetime has expired. The client is kept, but WireGuard access is disabled. Choose a future lifetime or No expiration and save to restore access.", + "clients.expired_disabled_short": "Expired · disabled", + "clients.expired_disabled_status": "Expired", + "clients.expires_days": "Expires in {n}d", + "clients.expires_hours": "Expires in {n}h", + "clients.expires_minutes": "Expires in {n}m", + "clients.generated_config": "Generated client configuration", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 seconds is a good default for clients behind NAT.", + "clients.local_access_exceptions": "Allowed local addresses", + "clients.local_access_exceptions_hint": "Optional IPs or CIDRs that stay reachable even while their local or Site-to-site network is blocked. Separate values with commas.", + "clients.managed": "WGTools managed", + "clients.name": "Name", + "clients.no_peers": "No peers found", + "clients.peers": "Peers", + "clients.peers_subtitle": "Changes are backed up and applied with wg syncconf without restarting the WireGuard interface.", + "clients.protected_networks_reference": "Blocked local networks (reference)", + "clients.protected_networks_reference_hint": "These networks are not written to AllowedIPs. Access is blocked by the WGTools server policy; individual addresses can be allowed in the field above.", + "clients.psk": "Preshared key (PSK)", + "clients.psk_enable": "Use an additional WireGuard preshared key", + "clients.psk_hint": "Recommended. Adds an extra symmetric secret to the WireGuard handshake. Standard WireGuard clients support it; WGTools includes the PSK in the generated config and QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generating QR…", + "clients.quick_search": "Quick search", + "clients.quick_search_clear": "Clear search", + "clients.quick_search_empty": "No clients match the search", + "clients.relay_endpoint_note": "The generated client config will connect to {endpoint}. The WireGuard server itself remains on this WGTools host.", + "clients.relay_required": "Choose a VPS Relay for this client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "unavailable", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "The client Endpoint is generated automatically from this Relay.", + "clients.remote_hint": "Networks located behind this peer. One network per line or separated by commas.", + "clients.remote_networks": "Remote networks", + "clients.remote_required": "Enter at least one remote network for a Site-to-site peer.", + "clients.required": "Name and VPN address are required.", + "clients.route_custom": "Custom", + "clients.route_full": "Full tunnel", + "clients.route_full_except_local": "Full tunnel except local networks", + "clients.route_hint": "Only these networks are written to AllowedIPs in the generated client config.", + "clients.route_preset": "Traffic through VPN", + "clients.route_vpn": "VPN network only", + "clients.route_vpn_lan": "VPN + local LAN", + "clients.saved": "Client saved", + "clients.schedule_blocked_short": "Schedule · blocked", + "clients.schedule_blocked_status": "Blocked by schedule", + "clients.schedule_days": "Allowed days", + "clients.schedule_days_required": "Choose at least one day for the access schedule.", + "clients.schedule_disabled_hint": "This client is currently blocked by its access schedule. WGTools will restore the same peer automatically when the next allowed window begins.", + "clients.schedule_enable": "Limit access by schedule", + "clients.schedule_from": "Access from", + "clients.schedule_hint": "WGTools can automatically disable and restore this client on selected days and times without changing the client config.", + "clients.schedule_short": "Schedule", + "clients.schedule_time_required": "Set both start and end times for the access schedule.", + "clients.schedule_timezone_hint": "The schedule uses the WireGuard server local time. Overnight windows such as 22:00–06:00 are supported.", + "clients.schedule_title": "Access schedule", + "clients.schedule_to": "Access until", + "clients.security_access": "Security and access time", + "clients.server_host": "Server address / domain", + "clients.server_host_hint": "Public IP or domain used by this client. Previously entered values are available as suggestions.", + "clients.server_host_required": "Server address / domain is required for a generated client configuration.", + "clients.server_peer": "Server peer", + "clients.server_port": "WireGuard port", + "clients.server_port_hint": "Taken automatically from the server configuration.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Status", + "clients.subtitle": "WireGuard peers, live status and client configuration management.", + "clients.tab_basic": "Basic", + "clients.tab_config": "Configuration", + "clients.tab_policy": "Policies", + "clients.tab_security": "Security", + "clients.title": "Clients", + "clients.type": "Type", + "clients.unmanaged_note": "This peer existed before WGTools. Its client private key cannot be recovered, so WGTools can edit the server-side peer but cannot generate its client configuration or QR code.", + "clients.updating": "Updating client…", + "common.actions": "Actions", + "common.ago": "ago", + "common.cancel": "Cancel", + "common.checking": "Checking…", + "common.close": "Close", + "common.config": "Config", + "common.delete": "Delete", + "common.disabled": "Disabled", + "common.edit": "Edit", + "common.enabled": "Enabled", + "common.loading": "Loading…", + "common.never": "Never", + "common.no": "No", + "common.not_configured": "Not configured", + "common.not_installed": "Not installed", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Refresh", + "common.running": "Running", + "common.save": "Save", + "common.stopped": "Stopped", + "common.total": "Total", + "common.unknown": "Unknown", + "common.updated": "Updated", + "common.yes": "Yes", + "dashboard.active_peers": "Active peers", + "dashboard.active_peers_subtitle": "Live information from wg show.", + "dashboard.activity": "System overview", + "dashboard.activity_subtitle": "Read-only checks for the running WireGuard stack.", + "dashboard.cores": "cores", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Last 24 h", + "dashboard.history_avg": "Avg", + "dashboard.history_max": "Max", + "dashboard.history_min": "Min", + "dashboard.history_now": "now", + "dashboard.memory": "Memory", + "dashboard.network": "Network", + "dashboard.peers": "Peers", + "dashboard.quick_search": "Quick search", + "dashboard.quick_search_clear": "Clear search", + "dashboard.quick_search_empty": "No peers match the search", + "dashboard.restart": "Restart", + "dashboard.restart_confirm": "Restart WireGuard? Active VPN clients will reconnect automatically.", + "dashboard.restart_ok": "WireGuard restarted.", + "dashboard.routing": "Routing", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Start", + "dashboard.start_ok": "WireGuard started.", + "dashboard.stop": "Stop", + "dashboard.stop_confirm": "Stop WireGuard? Active VPN clients will be disconnected.", + "dashboard.stop_ok": "WireGuard stopped.", + "dashboard.subtitle": "WireGuard server status, peers and live traffic.", + "dashboard.title": "Dashboard", + "dashboard.traffic": "Traffic", + "dashboard.uptime": "Uptime", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Server access policy", + "groups.additional_allowed": "Additional allowed addresses", + "groups.additional_blocked": "Additional blocked addresses", + "groups.allow": "Allow", + "groups.allowed": "Allowed", + "groups.allowed_addresses": "Allowed addresses / networks", + "groups.apply_current_template": "Apply current group template", + "groups.apply_defaults": "Apply current group template", + "groups.apply_defaults_hint": "Copies the current group route, DNS and Keepalive template into this client. Save the client, then issue a new config or QR if the installed device must be updated.", + "groups.basic": "Basic information", + "groups.block": "Block", + "groups.blocked": "Blocked", + "groups.blocked_addresses": "Blocked addresses / networks", + "groups.client_config_source": "Client configuration source", + "groups.client_defaults": "Client defaults", + "groups.client_group_hint": "Optional group for reusable access policy and client defaults. Groups are scoped to the selected WireGuard interface.", + "groups.config_differs": "This client configuration differs from the current group defaults. Server policy is current, but the installed phone/PC configuration changes only when you issue a new config or QR.", + "groups.config_differs_short": "Client config differs from group defaults", + "groups.create": "Create group", + "groups.create_title": "Create group", + "groups.created": "Group created", + "groups.creating": "Creating group…", + "groups.defaults_applied": "Current group template applied. Save the client to keep it.", + "groups.defaults_hint": "Defines what the client device sends through WireGuard. The server policy above independently decides what that traffic may access. Changing the template later never silently changes configs already installed on devices.", + "groups.delete_message": "Delete “{name}”? Client configurations are never deleted with a group.", + "groups.delete_move": "Move its clients to another group", + "groups.delete_title": "Delete client group", + "groups.delete_unassign": "Remove the group assignment from its clients", + "groups.deleted": "Group deleted", + "groups.deleting": "Updating clients and deleting group…", + "groups.description": "Description", + "groups.edit_title": "Edit group", + "groups.editor_subtitle": "A group combines a live server access policy with a template used when creating client configurations.", + "groups.effective_allow": "Allowed exceptions", + "groups.effective_deny": "Blocked exceptions", + "groups.effective_policy": "Effective server policy", + "groups.empty": "No client groups yet. Create one to reuse access policies and client defaults.", + "groups.group": "Group", + "groups.inherit": "Inherit", + "groups.internet_access": "Internet access", + "groups.internet_short": "Internet", + "groups.local_access": "Local networks", + "groups.local_short": "Local", + "groups.manage": "Groups", + "groups.members_count": "{count} clients", + "groups.name": "Name", + "groups.name_required": "Group name is required.", + "groups.new_client_defaults": "Client configuration template", + "groups.new_clients_short": "New clients", + "groups.no_group": "No group", + "groups.none": "None", + "groups.override_client_config": "Override the group client template for this client", + "groups.override_client_config_hint": "Off: Routes, DNS and Keepalive come from the group template. On: this client keeps its own values. Server access-policy overrides above remain independent.", + "groups.policy_addresses_hint": "IPv4 addresses or CIDRs, comma separated. Client exceptions take priority over group exceptions.", + "groups.policy_custom": "Custom policy", + "groups.policy_inherit": "Use group policy", + "groups.policy_mode": "Policy source", + "groups.policy_mode_hint": "Group policy is inherited by default. Client overrides never modify the group itself.", + "groups.routes_required": "Client routes cannot be empty.", + "groups.subtitle": "Reuse server access policies and defaults for normal clients on the selected WireGuard interface.", + "groups.title": "Client groups", + "groups.traffic_through_vpn": "Traffic through VPN", + "groups.updated": "Group updated", + "groups.updating": "Updating group policy…", + "help.example_note": "All addresses, interface names, peer names and domains in Help examples are fictional documentation values. Replace them with values from your own network.", + "help.navigation": "Help navigation", + "help.open": "Open help", + "help.subtitle": "Plain-language help for Dashboard, Server, Clients and Settings with short practical examples.", + "help.title": "WGTools Help", + "interfaces.add": "+ Add interface", + "interfaces.create": "Create interface", + "interfaces.create_confirm": "Create and start interface {name}?", + "interfaces.create_failed": "Interface could not be created", + "interfaces.create_hint": "WGTools checks that the VPN network, UDP port and policy routing table do not conflict with other WireGuard interfaces before creating the configuration.", + "interfaces.create_subtitle": "Create an independent WireGuard interface with its own address pool, UDP port and routing settings.", + "interfaces.create_title": "Add WireGuard interface", + "interfaces.created": "Interface created successfully.", + "interfaces.creating": "Generating keys, writing the new configuration and starting WireGuard…", + "interfaces.current": "Current", + "interfaces.delete": "Delete", + "interfaces.delete_confirm": "Delete interface {name}? This removes its WireGuard configuration and all peers on this interface. A configuration backup is created first.", + "interfaces.delete_failed": "Interface could not be deleted", + "interfaces.delete_last": "The last configured WireGuard interface cannot be deleted here.", + "interfaces.delete_tooltip": "Delete this WireGuard interface", + "interfaces.deleted": "Interface deleted. Backup: {backup}", + "interfaces.deleting": "Stopping WireGuard and deleting the interface…", + "interfaces.display_name": "Display name", + "interfaces.display_name_edit_hint": "Friendly name only; the Linux interface name does not change.", + "interfaces.display_name_hint": "Optional friendly name, for example Work or Contractors.", + "interfaces.identity": "Interface identity", + "interfaces.none": "No WireGuard interfaces found", + "interfaces.none_configured": "No configured WireGuard interfaces yet.", + "interfaces.peers_short": "peers", + "interfaces.rename_failed": "Interface display name could not be saved.", + "interfaces.select": "Select", + "interfaces.subtitle": "Each interface has its own VPN network, listen port, peers and policies. Select one to manage it throughout WGTools.", + "interfaces.switch_title": "WireGuard interfaces", + "interfaces.system_name": "System name", + "interfaces.system_name_hint": "Linux interface name, for example wg1. It cannot be changed after creation.", + "interfaces.title": "WireGuard interfaces", + "interfaces.unique_port_hint": "Each WireGuard interface on this server must use its own UDP listen port.", + "interfaces.unique_table_hint": "WGTools recommends a separate policy table for each interface. Leave empty for normal system routing.", + "nav.clients": "Clients", + "nav.dashboard": "Dashboard", + "nav.server": "Server", + "nav.settings": "Settings", + "server.access_apply_confirm": "Save this firewall rule and apply it now? WireGuard will be restarted briefly and a backup will be created.", + "server.access_rule_deleted": "Access rule deleted.", + "server.access_rule_help": "Create a common FORWARD access rule without editing iptables commands manually.", + "server.access_rule_order_hint": "WGTools inserts access rules at the beginning of the FORWARD chain so restrictive rules take effect before the general VPN ACCEPT rules.", + "server.access_rule_saved": "Access rule saved and applied.", + "server.action": "Action", + "server.action_hint": "REJECT tells the client the traffic was refused; DROP silently discards it; ACCEPT explicitly allows it.", + "server.add_access_rule": "Add access rule", + "server.add_route": "Add route", + "server.address": "Address", + "server.any": "Any", + "server.any_protocol": "Any", + "server.apply_confirm": "Save these server settings and apply them now? WireGuard will be restarted briefly. A backup is created first and WGTools will roll back automatically if the new configuration does not start.", + "server.apply_settings": "Save and apply", + "server.applying_rule": "Creating backup and applying…", + "server.applying_settings": "Validating settings, creating backup and applying…", + "server.basic_settings": "Basic settings", + "server.config_tab_help": "Open the raw configuration editor for the currently selected WireGuard interface.", + "server.create_confirm": "Create and start the WireGuard server with these settings?", + "server.create_server": "Create server", + "server.create_step_conf": "Create the configuration for the selected WireGuard interface with mode 600.", + "server.create_step_forward": "Configure forwarding, NAT and optional policy routing.", + "server.create_step_key": "Generate a new server key pair.", + "server.create_step_start": "Enable and start the selected wg-quick interface.", + "server.create_subtitle": "WireGuard is installed, but the selected interface is not configured yet.", + "server.create_success": "WireGuard server created successfully.", + "server.create_title": "Create WireGuard server", + "server.creating": "Generating keys, writing configuration and starting WireGuard…", + "server.custom_preserved": "Peer blocks, site-to-site routes and custom PostUp/PostDown rules that are not managed by these fields are preserved.", + "server.delete_access_confirm": "Delete this access rule and apply the change?", + "server.delete_route_confirm": "Delete this custom route and apply the change?", + "server.destination": "Destination", + "server.destination_hint": "Empty = any. Accepts an IP, CIDR or IP range. Separate multiple destinations with commas.", + "server.destination_port": "Destination port", + "server.destination_port_hint": "Optional. Enter a port such as 443 or a range such as 10000:20000. Select TCP or UDP first.", + "server.details": "Details", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostics", + "server.diagnostics_done": "Diagnostics completed", + "server.diagnostics_subtitle": "Current system checks. No configuration is changed.", + "server.direction": "Hook", + "server.edit_access_rule": "Edit access rule", + "server.edit_route": "Edit route", + "server.edit_server": "Edit server", + "server.edit_subtitle": "Edit the common WireGuard, routing and NAT settings. Existing peers and custom rules are preserved.", + "server.edit_title": "Server settings", + "server.edit_warning": "Applying interface, routing or firewall settings briefly restarts the WireGuard interface. Active peers will reconnect automatically.", + "server.enable_forwarding": "Enable IPv4 forwarding", + "server.enable_nat": "Enable NAT / Masquerade", + "server.firewall": "Firewall & NAT", + "server.firewall_subtitle": "Detected rules from WireGuard hooks.", + "server.firewall_subtitle_v08": "Common forwarding/NAT rules and access rules from the selected interface configuration. Simple access rules can be managed here; advanced rules stay available in the raw editor.", + "server.forward_from_vpn": "Allow forwarding from VPN", + "server.forward_to_vpn": "Allow forwarding to VPN", + "server.forwarding_section": "Forwarding and NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Required only when a policy routing table is used.", + "server.install_success": "WireGuard installed successfully.", + "server.install_wireguard": "Install WireGuard", + "server.install_wireguard_help": "Runs apt update and installs WireGuard plus the networking tools needed by WGTools.", + "server.install_wireguard_title": "Install WireGuard", + "server.installing": "Installing WireGuard… This may take a minute.", + "server.interface": "Interface", + "server.interface_hint": "WGTools currently manages this interface.", + "server.interface_name": "Interface", + "server.interface_section": "WireGuard interface", + "server.ip_forwarding": "IPv4 forwarding", + "server.kind": "Kind", + "server.listen_port": "Listen port", + "server.local_network": "Local network", + "server.local_network_hint": "Optional route added to the policy table.", + "server.managed_automatically": "Managed automatically", + "server.nat": "NAT / Masquerade", + "server.network": "Network", + "server.network_settings": "Network and NAT", + "server.no_firewall": "No firewall rules detected", + "server.no_routes": "No routes detected", + "server.not_configured": "Not configured", + "server.not_set": "Not set", + "server.policy_disabled_hint": "Disable this for normal system routing. Enable it only when this VPN needs its own source policy routing table.", + "server.policy_enabled": "Enable policy routing", + "server.policy_table": "Policy table", + "server.policy_table_hint": "Leave empty for normal system routing; use e.g. 200 for source policy routing.", + "server.port_word": "port", + "server.private_hidden": "Configured (hidden)", + "server.private_key": "Private key", + "server.protocol": "Protocol", + "server.route_apply_confirm": "Save this route and apply it now? WireGuard will be restarted briefly and a backup will be created.", + "server.route_custom": "Custom", + "server.route_deleted": "Route deleted.", + "server.route_device_hint": "Optional output interface, for example wg0 or enp6s18.", + "server.route_editor_help": "Add a route that should be installed when WireGuard starts and removed when it stops.", + "server.route_gateway_hint": "Optional next-hop gateway. A gateway or interface is required.", + "server.route_managed_peer": "Site-to-site peer", + "server.route_managed_server": "Server setting", + "server.route_network_hint": "IPv4 network such as 10.20.0.0/24, or 'default'.", + "server.route_saved": "Route saved and applied.", + "server.route_table_hint": "Use 'main' for normal routing or a numeric table such as 200.", + "server.route_type": "Type", + "server.routes": "Detected routes", + "server.routes_subtitle": "Routes parsed from PostUp/PostDown and current policy routing state.", + "server.routes_subtitle_v08": "Server-managed, site-to-site and custom routes from the selected interface configuration. Custom routes can be added, edited and removed here.", + "server.routing": "Routing", + "server.routing_section": "Routing", + "server.rule": "Rule", + "server.rule_access": "Access rule", + "server.rule_advanced": "Advanced", + "server.rule_apply_warning": "Applying a route or firewall rule briefly restarts the WireGuard interface. WGTools creates a backup and rolls back automatically if startup fails.", + "server.rule_client_exception": "Client exception", + "server.rule_client_policy": "Client policy", + "server.rule_managed_server": "Server setting", + "server.rule_type": "Type", + "server.run_diagnostics": "Run diagnostics", + "server.save_apply": "Save and apply", + "server.save_config": "SaveConfig", + "server.server_address": "Server VPN address", + "server.server_address_hint": "Usually the first usable address in the VPN network.", + "server.settings_applied": "Server settings saved and applied successfully.", + "server.settings_apply_failed": "Server settings could not be applied", + "server.setup_required": "Setup required", + "server.source": "Source", + "server.source_hint": "Empty = any. Accepts an IP, CIDR or range such as 10.0.0.100-10.0.0.120.", + "server.subtitle": "WireGuard installation, initial setup and current server configuration.", + "server.tab_config": "Config", + "server.tab_interface": "Interface", + "server.tab_routing": "Routing", + "server.tab_vps": "VPS", + "server.table": "Table", + "server.tabs_aria": "Server settings sections", + "server.title": "Server", + "server.uplink": "Uplink interface", + "server.use_raw_editor": "Use raw editor", + "server.via": "Via / Device", + "server.via_word": "via", + "server.vpn_network": "VPN network", + "server.vpn_network_hint": "Client addresses will later be allocated from this network.", + "server.vpn_pool": "VPN address pool", + "server.wg_not_installed": "WireGuard is not installed", + "server.wg_not_installed_subtitle": "WGTools can install the required Debian packages automatically.", + "server.what_happens": "What WGTools will do", + "settings.about": "About", + "settings.add_user": "Add user", + "settings.advanced": "Advanced", + "settings.advanced_subtitle": "Direct access to expert WireGuard configuration tools.", + "settings.appearance": "Appearance", + "settings.applying_config": "Validating configuration, creating backup and applying…", + "settings.backup_count": "Stored backups", + "settings.backup_retention": "Backups to keep", + "settings.backup_retention_help": "Old automatic backups are removed after a new backup is created. 1–200 files.", + "settings.backups": "Configuration backups", + "settings.backups_always_on": "Enabled", + "settings.backups_subtitle": "WGTools automatically creates a backup before configuration-changing operations. Automatic backups cannot be disabled.", + "settings.change_password": "Change password", + "settings.check_updates": "Check for updates", + "settings.config_applied": "Configuration saved and applied successfully.", + "settings.config_applied_restarted": "Configuration applied and WireGuard restarted.", + "settings.config_applied_stopped": "Configuration saved. WireGuard was already stopped and remains stopped.", + "settings.config_apply_failed": "Configuration could not be applied", + "settings.config_load_failed": "Could not load configuration", + "settings.current_user": "Current user", + "settings.current_version": "Current version", + "settings.audit_action": "Action", + "settings.audit_empty": "No audit events yet", + "settings.audit_log": "Audit", + "settings.audit_log_subtitle": "Panel, authentication and Telegram actions plus WireGuard client connection history. Secrets are never written here.", + "settings.audit_object": "Object", + "settings.audit_result": "Result", + "settings.audit_retention_note": "Retention: 30 days", + "settings.audit_search": "Quick search", + "settings.audit_search_clear": "Clear search", + "settings.audit_search_empty": "No audit events match the search", + "settings.audit_time": "Date / time", + "settings.audit_user": "User", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Access rule created", + "audit.action.access_rule.deleted": "Access rule deleted", + "audit.action.access_rule.updated": "Access rule updated", + "audit.action.auth.first_user_created": "First user created", + "audit.action.auth.login": "Signed in", + "audit.action.auth.login_failed": "Sign-in failed", + "audit.action.auth.logout": "Signed out", + "audit.action.backup.full_created": "Full backup created", + "audit.action.backup.full_restored": "Full backup restored", + "audit.action.client.config_downloaded": "Client config downloaded", + "audit.action.client.config_viewed": "Client config viewed", + "audit.action.client.created": "Client created", + "audit.action.client.deleted": "Client deleted", + "audit.action.client.qr_viewed": "Client QR viewed", + "audit.action.client.updated": "Client updated", + "audit.action.client_group.created": "Client group created", + "audit.action.client_group.deleted": "Client group deleted", + "audit.action.client_group.updated": "Client group updated", + "audit.action.interface.created": "Interface created", + "audit.action.interface.deleted": "Interface deleted", + "audit.action.interface.renamed": "Interface renamed", + "audit.action.route.created": "Route created", + "audit.action.route.deleted": "Route deleted", + "audit.action.route.updated": "Route updated", + "audit.action.server.created": "Server created", + "audit.action.server.raw_config_applied": "Raw config applied", + "audit.action.server.settings_applied": "Server settings applied", + "audit.action.settings.updated": "Panel settings updated", + "audit.action.telegram.action_denied": "Telegram action denied", + "audit.action.telegram.action_failed": "Telegram action failed", + "audit.action.telegram.connection_test": "Telegram connection test", + "audit.action.telegram.settings_updated": "Telegram settings updated", + "audit.action.update.checked": "Update checked", + "audit.action.update.scheduled": "Update scheduled", + "audit.action.update.backup_created": "Pre-update backup", + "audit.action.update.completed": "Update completed", + "audit.action.update.failed": "Update failed", + "audit.action.update.rollback_completed": "Previous version restored", + "audit.action.update.rollback_failed": "Update rollback failed", + "audit.action.user.created": "User created", + "audit.action.user.deleted": "User deleted", + "audit.action.user.password_changed": "User password changed", + "audit.action.vps.candidate_deleted": "VPS candidate deleted", + "audit.action.vps.candidate_saved": "VPS candidate saved", + "audit.action.vps.detached": "VPS Relay detached", + "audit.action.vps.relay_installed": "VPS Relay installed", + "audit.action.wireguard.client_connected": "WireGuard client connected", + "audit.action.wireguard.installed": "WireGuard installed", + "audit.action.wireguard.restarted": "WireGuard restarted", + "audit.action.wireguard.started": "WireGuard started", + "audit.action.wireguard.stopped": "WireGuard stopped", + "audit.result.applied": "applied", + "audit.result.available": "available", + "audit.result.changed": "changed", + "audit.result.created": "created", + "audit.result.current": "current", + "audit.result.deleted": "deleted", + "audit.result.detached": "detached", + "audit.result.denied": "denied", + "audit.result.downloaded": "downloaded", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Error", + "audit.result.installed": "installed", + "audit.result.invalid_credentials": "invalid credentials", + "audit.result.ok": "ok", + "audit.result.queued": "queued", + "audit.result.restarted": "restarted", + "audit.result.restored": "restored", + "audit.result.rotated": "rotated", + "audit.result.saved": "saved", + "audit.result.shown": "shown", + "audit.result.started": "started", + "audit.result.stopped": "stopped", + "audit.result.updated": "updated", + "settings.delete_user": "Delete", + "settings.delete_user_confirm": "Delete user {name}?", + "settings.edit_raw_config": "Edit interface config", + "settings.expert_mode": "Expert", + "settings.full_backup_component_clients": "WGTools-managed client metadata, private keys, PSKs, expiration settings, and client-group assignments required to regenerate client configs/QR codes.", + "settings.full_backup_component_db": "WGTools database: users, application preferences, mail/SMTP, Telegram settings and saved VPS Relay state.", + "settings.full_backup_component_relay": "VPS Relay recovery data: controller/tenant IDs, management token and home transport key. After restore WGTools can rebuild the local transport and reconnect to the preserved VPS tenant.", + "settings.full_backup_component_system": "WGTools IPv4-forwarding sysctl file, interface display-name metadata, and client-group policy/default definitions, when present. Automatic per-interface configuration history is intentionally excluded.", + "settings.full_backup_component_wg": "All detected WireGuard interface configurations from /etc/wireguard/, including their running/stopped state.", + "settings.full_backup_create_failed": "Could not create the full backup", + "settings.full_backup_creating": "Creating a complete backup…", + "settings.full_backup_download": "Create", + "settings.full_backup_downloaded": "Backup created and downloaded. Store it securely.", + "settings.full_backup_downloaded_short": "Full backup downloaded.", + "settings.full_backup_help": "Creates a portable WGTools backup for migration or disaster recovery. It includes WireGuard configs, users, settings, groups, managed-client data and the state required to reconnect to preserved VPS Relay tenants.", + "settings.full_backup_no_file": "No backup selected", + "settings.full_backup_restore": "Restore", + "settings.full_backup_restore_confirm": "Restore this full WGTools backup? Current users, settings, managed client data and all WireGuard configurations included in the backup will be restored. WireGuard interfaces may restart. WGTools creates a safety backup first and rolls back automatically if applying the restored state fails.", + "settings.full_backup_restore_failed": "Restore failed", + "settings.full_backup_restored": "Backup restored successfully. Sign in with an account from the restored backup.", + "settings.full_backup_restored_short": "Backup restored.", + "settings.full_backup_restoring": "Validating backup, creating a safety copy and restoring…", + "settings.full_backup_secret_warning": "This file contains sensitive data: WireGuard private keys, client private keys, preshared keys (PSKs), WGTools password hashes, the Telegram Bot token and the saved SMTP password. Store it like a password and never attach it to public issues or chats.", + "settings.full_backup_select": "Select", + "settings.full_backup_title": "Full backup and restore", + "settings.full_mode": "Server and client management enabled", + "settings.interface_help": "The managed WireGuard interface is selected when WGTools is deployed.", + "settings.language": "Language", + "settings.last_backup": "Last backup", + "settings.latest_version": "Latest release", + "settings.loading_config": "Loading configuration…", + "settings.mode": "Mode", + "settings.never_logged_in": "Never", + "settings.new_password": "New password", + "settings.no_backups": "No backups yet", + "settings.online_help": "A peer is considered online while its latest handshake is newer than this value. 30–3600 seconds.", + "settings.online_threshold": "Online threshold", + "settings.open_release": "Open release", + "settings.password_changed": "Password changed.", + "settings.passwords_mismatch": "Passwords do not match.", + "settings.project_github": "Project / GitHub", + "settings.raw_config_confirm": "Save this WireGuard configuration and apply it now? The selected interface will be restarted. A backup is created first and WGTools will roll back automatically if the new configuration does not start.", + "settings.raw_config_help": "Open the source configuration of the selected WireGuard interface.", + "settings.raw_config_title": "Raw WireGuard configuration", + "settings.raw_config_warning": "Expert mode: this is the real WireGuard server configuration and includes the server private key and any peer PSKs. Saving and applying restarts the WireGuard interface. WGTools creates a backup first and automatically rolls back if the new configuration cannot start.", + "settings.readonly_mode": "Client management enabled", + "settings.refresh_help": "How often WGTools requests fresh status data. 2–60 seconds.", + "settings.refresh_interval": "Refresh interval", + "settings.release_notes": "Release notes", + "settings.reload_config": "Reload from disk", + "settings.save_apply": "Save & Apply", + "settings.saved": "Settings saved.", + "settings.saved_reload": "Settings saved. Reloading…", + "settings.saving": "Saving settings…", + "settings.status": "Status refresh", + "settings.status_help": "Live dashboard and peer status refresh settings.", + "settings.subtitle": "WGTools interface preferences and status settings.", + "settings.syntax_hint": "WireGuard sections, keys, values and comments are highlighted while you edit.", + "settings.tab_about": "About", + "settings.tab_backups": "Backups", + "settings.tab_general": "General", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Users", + "settings.tabs_aria": "Settings sections", + "settings.telegram": "Telegram Bot", + "settings.telegram_allowed_ids": "Allowed Telegram user IDs", + "settings.telegram_allowed_ids_help": "One numeric user ID per line. An unauthorized /start message will reply with the sender’s Telegram user ID so you can add it here.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connected", + "settings.telegram_disabled": "Disabled", + "settings.telegram_dns": "Default client DNS", + "settings.telegram_dns_help": "Optional IPv4 DNS addresses separated by commas. Used for clients created by the bot.", + "settings.telegram_enabled": "Enable Telegram bot", + "settings.telegram_endpoint": "Default server address / domain", + "settings.telegram_endpoint_help": "Used when the bot creates a new client configuration. Enter only an IP address or domain; the WireGuard port is read from the server configuration.", + "settings.telegram_language": "Bot language", + "settings.telegram_language_auto": "Auto (Telegram language)", + "settings.telegram_last_poll": "Last Telegram contact", + "settings.telegram_not_configured": "Not configured", + "settings.telegram_remove_token": "Remove token", + "settings.telegram_remove_token_confirm": "Remove the saved Telegram bot token and disable the bot?", + "settings.telegram_save": "Save Telegram settings", + "settings.telegram_saved": "Telegram settings saved.", + "settings.telegram_setup_note": "Create a bot with @BotFather, save its token, enable the bot and send /start. If your user ID is not authorized yet, WGTools will show it — add that ID to the Allowed Telegram user IDs list.", + "settings.telegram_status": "Bot status", + "settings.telegram_subtitle": "Remote WireGuard management from Telegram: server status, clients, client creation/deletion and WireGuard start/restart/stop.", + "settings.telegram_test": "Test connection", + "settings.telegram_test_ok": "Telegram connection is working: @{username}", + "settings.telegram_test_recent_ok": "Telegram bot is working. The direct check timed out, but the bot contacted Telegram recently.", + "settings.telegram_token": "Bot token", + "settings.telegram_token_help": "Create a bot with @BotFather and paste its Bot API token here. API ID and API Hash are not required for the Telegram Bot API.", + "settings.telegram_token_keep": "Leave empty to keep the saved token.", + "settings.telegram_waiting": "Configured, waiting for bot service", + "settings.theme": "Theme", + "settings.theme_dark": "Dark", + "settings.theme_light": "Light", + "settings.theme_system": "System", + "settings.title": "Settings", + "settings.update_available": "Update available", + "settings.update_backup_queued": "Update queued. WGTools will create an automatic full backup before installing it…", + "settings.update_backup_running": "Creating the automatic full backup before update…", + "settings.update_check_failed": "Could not check for updates", + "settings.update_checking": "Checking the latest published GitHub Release…", + "settings.update_confirm": "Update WGTools from v{current} to v{latest}? A full backup and application rollback copy will be created first. The web interface will restart briefly.", + "settings.update_current": "Up to date", + "settings.update_downloading": "Downloading and validating the GitHub release…", + "settings.update_failed": "WGTools update failed.", + "settings.update_installing": "Installing the update. The web interface may be unavailable briefly…", + "settings.update_no_update": "WGTools is already up to date.", + "settings.update_not_checked": "Not checked", + "settings.update_queued": "Update queued. Waiting for the updater service…", + "settings.update_rollback_ok": "The previous WGTools application was restored automatically.", + "settings.update_rolling_back": "Update failed. Restoring the previous WGTools application…", + "settings.update_running": "Creating safety backups…", + "settings.update_safety_hint": "Updates are opt-in. Before installation WGTools creates a full state backup and an application rollback copy. If installation fails, the previous application is restored automatically. WireGuard itself is not restarted by the updater unless the new release explicitly changes its configuration.", + "settings.update_sidebar": "New version available", + "settings.update_sidebar_hint": "Open Settings → About", + "settings.update_starting": "Starting the update…", + "settings.update_status_unknown": "Update status is unavailable. Retrying…", + "settings.update_subtitle": "Project information, automatic release checks and safe updates from GitHub Releases.", + "settings.update_success": "WGTools was updated successfully to v{version}. Reloading…", + "settings.update_wgtools": "Update WGTools", + "settings.user_actions": "Actions", + "settings.user_created": "Created", + "settings.user_created_ok": "User created.", + "settings.user_deleted": "User deleted.", + "settings.user_equal_rights": "All WGTools users have the same permissions.", + "settings.user_last_login": "Last login", + "settings.user_name": "Username", + "settings.users": "Users", + "settings.users_subtitle": "Local WGTools accounts. E-mail is optional and is used only for password recovery when mail is enabled.", + "vps.add": "Add VPS", + "vps.add_help": "WGTools uses SSH to check or install Relay. Passwords and private SSH keys are never stored.", + "vps.add_title": "Add VPS", + "vps.agent": "Relay Agent", + "vps.agent_found": "Already installed", + "vps.agent_will_install": "Will be installed", + "vps.arch": "Architecture", + "vps.auth_method": "Authentication", + "vps.authentication": "SSH authentication", + "vps.check": "Check VPS", + "vps.check_failed": "VPS check failed", + "vps.check_link": "Check link", + "vps.check_ok": "VPS is compatible", + "vps.checking": "Checking SSH access and VPS compatibility…", + "vps.connections": "connections", + "vps.credentials_not_saved": "Used only for this check and not stored by WGTools.", + "vps.delete_candidate": "Remove", + "vps.delete_installed": "Remove VPS", + "vps.delete_installed_confirm": "Remove “{name}” from WGTools? The local Relay transport will be disconnected, but the Relay Agent and tenant on the VPS will be preserved. You can add this VPS again and WGTools will reconnect to the existing Relay instead of creating a new one. Clients using this Relay cannot connect through it until the VPS is reconnected.", + "vps.delete_installed_failed": "Could not remove VPS from WGTools", + "vps.delete_installed_ok": "VPS removed from WGTools. The remote Relay was preserved and can be reconnected.", + "vps.empty_help": "Add a Debian or Ubuntu VPS to check SSH access, operating system compatibility and required UDP ports.", + "vps.empty_title": "No VPS configured", + "vps.endpoint": "Public endpoint", + "vps.endpoint_domain": "Domain (recommended)", + "vps.endpoint_domain_hint": "If you later replace the primary VPS, changing DNS can keep existing client configurations unchanged.", + "vps.health_failed": "Relay link check failed", + "vps.host": "IP / hostname", + "vps.host_key": "SSH host key", + "vps.identity": "VPS connection", + "vps.install_failed": "Relay installation failed", + "vps.install_ok": "Relay installed and protected management link verified", + "vps.install_relay": "Install Relay", + "vps.install_title": "Install VPS Relay", + "vps.installed": "Installed", + "vps.installing": "Installing Relay Agent and establishing the protected transport tunnel…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Key passphrase", + "vps.link_ok": "Relay link OK", + "vps.multi_tenant_note": "A WGTools Relay Agent is already running on this VPS. It will not be replaced: this WGTools will get a separate isolated connection with its own keys and UDP ports.", + "vps.name": "Name", + "vps.no_domain": "IP endpoint", + "vps.not_installed": "Will be installed", + "vps.os": "Operating system", + "vps.password": "Password", + "vps.phase_note": "Relay Agent supports multiple independent WGTools controllers on one VPS. Each controller gets an isolated connection, keys and UDP ports; existing connections are left untouched.", + "vps.port_pair": "UDP ports", + "vps.ports_adjusted": "free ports selected", + "vps.private_key": "Private key", + "vps.privilege": "Privileges", + "vps.public_endpoint": "Future public endpoint", + "vps.ready_help": "SSH credentials are used for the compatibility check and immediate Relay installation; they are never saved.", + "vps.reconnect_note": "An existing Relay connection created by this WGTools was found on the VPS. WGTools will reconnect to that same tenant; no new tenant or UDP ports will be created.", + "vps.reconnect_ok": "Existing Relay reconnected successfully", + "vps.reconnect_relay": "Reconnect Relay", + "vps.relay_port": "Relay UDP port", + "vps.remove_confirm": "Remove this VPS candidate? No remote changes have been made.", + "vps.save_candidate": "Save candidate", + "vps.saved": "VPS candidate saved", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH key", + "vps.ssh_port": "SSH port", + "vps.ssh_user": "SSH user", + "vps.status_candidate": "Ready for installation", + "vps.status_installed": "Relay connected", + "vps.subtitle": "Prepare a public VPS for remote access when this WGTools server has no public IP.", + "vps.tenant": "Connection", + "vps.title": "VPS Relay", + "vps.transport_port": "Transport UDP port", + "vps.transport_port_hint": "Separate UDP port for the private Home ↔ VPS transport tunnel.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Saved", + "vps.active_short": "Active", + "dashboard.traffic_reset": "Reset", + "dashboard.traffic_reset_confirm": "Reset accumulated WireGuard traffic counters for this interface? Client counters will also restart from zero.", + "dashboard.traffic_reset_done": "Traffic counters reset", + "dashboard.traffic_reset_failed": "Could not reset traffic counters", + "audit.action.traffic.reset": "Traffic counters reset", + "audit.result.reset": "reset", + "server.mtu": "MTU", + "server.mtu_auto": "Auto", + "server.mtu_hint": "Optional. Leave empty for wg-quick automatic MTU. Set a value such as 1380 or 1420 only when required by the network, LTE or PPPoE path.", + "clients.peer_isolation": "VPN client isolation", + "clients.peer_isolation_enable": "Isolate from other VPN clients", + "clients.peer_isolation_hint": "Blocks traffic between this client and other addresses in the WireGuard pool. Access to the server itself, Internet, local networks and Site-to-site networks is still controlled by the other policies.", + "clients.credentials_rotate": "Client keys", + "clients.credentials_rotate_button": "Rotate keys", + "clients.credentials_rotate_confirm": "Generate new keys for this client? If it is currently connected, its active WireGuard session will be forcibly disconnected. Send a new config or QR afterward.", + "clients.credentials_rotate_confirm_psk": "Generate a new key pair and a new PSK for this client? If it is currently connected, its active WireGuard session will be forcibly disconnected. Send a new config or QR afterward.", + "clients.credentials_rotate_hint": "One action rotates PrivateKey/PublicKey and, when PSK is enabled, the PSK as well. Address, routes, group, schedule, isolation and accumulated statistics are preserved.", + "clients.credentials_rotating": "Generating new keys and disconnecting the old client session…", + "clients.credentials_rotated": "Client keys changed. If the client was connected, its old session was forcibly disconnected. The old config no longer works; send a new config or QR before reconnecting.", + "clients.credentials_rotated_short": "Client keys changed — new config required", + "audit.action.client.credentials_rotated": "Client keys rotated", + "clients.credentials_connection_lost": "The connection to WGTools was interrupted. If this panel was opened through the client whose keys were just rotated, this is expected: its old WireGuard session is disconnected immediately. Reconnect to WGTools by another path and issue the new config or QR.", + "nav.navigation": "Main navigation", + "nav.project_github": "WGTools on GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Optional now. It can be used for password recovery after mail is configured.", + "auth.forgot_password": "Forgot password?", + "auth.reset_title": "Reset password", + "auth.reset_subtitle": "Receive a one-time code by email and set a new WGTools password.", + "auth.reset_identifier": "Username or e-mail", + "auth.reset_identifier_help": "For privacy, WGTools always shows the same response whether the account exists or not.", + "auth.send_reset_code": "Send reset code", + "auth.reset_code_sent_generic": "If the account exists and has an e-mail address, a reset code has been sent. The code is valid for 15 minutes.", + "auth.reset_code": "6-digit code", + "auth.set_new_password": "Set new password", + "auth.request_another_code": "Request another code", + "auth.back_to_login": "Back to sign in", + "auth.reset_not_configured": "Password recovery by e-mail is not configured. Contact the WGTools administrator.", + "settings.tab_mail": "Mail", + "settings.mail": "Mail / SMTP", + "settings.mail_subtitle": "SMTP is used for password recovery.", + "settings.mail_not_configured": "Not configured", + "settings.mail_enabled": "Enable mail and password recovery", + "settings.mail_smtp_host": "SMTP server", + "settings.mail_smtp_port": "SMTP port", + "settings.mail_security": "Encryption", + "settings.mail_security_none": "No encryption", + "settings.mail_username": "SMTP username", + "settings.mail_username_help": "Used for SMTP authentication and as the sender e-mail address.", + "settings.mail_password": "SMTP password", + "settings.mail_password_keep": "Leave empty to keep the saved password.", + "settings.mail_from_email": "Sender e-mail", + "settings.mail_from_name": "Sender name", + "settings.mail_test_recipient": "Test recipient", + "settings.mail_test_recipient_help": "The test uses the currently saved SMTP settings.", + "settings.mail_remove_password": "Remove password", + "settings.mail_test": "Send test", + "settings.mail_save": "Save mail settings", + "settings.mail_enabled_badge": "Enabled", + "settings.mail_disabled_badge": "Disabled", + "settings.mail_saved": "Mail settings saved.", + "settings.mail_remove_password_confirm": "Remove the saved SMTP password and disable mail?", + "settings.mail_password_removed": "SMTP password removed and mail disabled.", + "settings.mail_test_recipient_required": "Enter a test recipient e-mail address.", + "settings.mail_testing": "Sending a test e-mail…", + "settings.mail_test_ok": "Test e-mail sent successfully.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Optional. Required only for self-service password recovery.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail saved.", + "settings.send_password_reset": "Send reset", + "settings.user_reset_mail_not_configured": "Configure and enable mail first.", + "settings.user_reset_email_missing": "Add an e-mail address first.", + "settings.user_reset_confirm": "Send a password reset code to {name} at {email}?", + "settings.user_reset_sent": "Password reset code sent to {email}.", + "audit.action.auth.password_reset_requested": "Password reset requested", + "audit.action.auth.password_reset_code_sent": "Password reset code sent", + "audit.action.auth.password_reset_completed": "Password reset completed", + "audit.action.auth.password_reset_failed": "Password reset failed", + "audit.action.mail.settings_updated": "Mail settings updated", + "audit.action.mail.test_sent": "Test e-mail sent", + "audit.action.mail.test_failed": "Test e-mail failed", + "audit.action.user.email_changed": "User e-mail changed", + "audit.action.user.password_reset_sent": "User password reset sent", + "audit.action.user.password_reset_failed": "User password reset failed", + "audit.result.accepted": "accepted", + "audit.result.sent": "sent", + "audit.result.invalid_code": "invalid code", + "common.copy": "Copy", + "common.copied": "Copied", + "clients.use_panel_host": "Use panel address", + "clients.use_panel_host_done": "Panel address inserted: {host}", + "clients.use_panel_host_failed": "Could not determine the panel address from the browser URL.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Built-in Let’s Encrypt HTTPS for direct WGTools access without a reverse proxy.", + "settings.https_disabled": "Disabled", + "settings.https_enabled": "Enabled", + "settings.https_enable": "Enable built-in HTTPS", + "settings.https_type": "Certificate for", + "settings.https_domain": "Domain", + "settings.https_public_ip": "Public IP", + "settings.https_target": "Domain or public IP", + "settings.https_email": "Let’s Encrypt e-mail", + "settings.https_port": "HTTPS port", + "settings.https_port80_note": "TCP port 80 must be reachable from the Internet for certificate issuance and automatic renewal. Open the selected HTTPS port for the WGTools panel itself.", + "settings.https_check_ports": "Check ports", + "settings.https_certificate": "Certificate", + "settings.https_certificate_ready": "Ready", + "settings.https_certificate_missing": "Not issued", + "settings.https_expires": "Valid until", + "settings.https_renewal": "Automatic renewal", + "settings.https_renewal_enabled": "Enabled", + "settings.https_renewal_disabled": "Disabled", + "settings.https_certificate_path": "Certificate", + "settings.https_private_key_path": "Private key", + "settings.https_issue": "Obtain / renew certificate", + "settings.https_port_free": "Free", + "settings.https_port_busy": "Busy", + "settings.https_ports_checked": "Port check completed.", + "settings.https_target_email_required": "Enter the domain/public IP and Let’s Encrypt e-mail.", + "settings.https_issue_confirm": "Request or renew the Let’s Encrypt certificate for {target}? The entered HTTPS settings will be saved. TCP port 80 must be reachable from the Internet.", + "settings.https_issuing": "Requesting certificate from Let’s Encrypt…", + "settings.https_issue_ok": "Certificate is ready.", + "settings.https_already_enabled": "Built-in HTTPS is already enabled.", + "settings.https_already_disabled": "Built-in HTTPS is already disabled.", + "settings.https_enable_confirm": "Enable built-in HTTPS on TCP {port} with path {path}? WGTools will restart and this page will reconnect at the new address.", + "settings.https_disable_confirm": "Disable built-in HTTPS and return WGTools to HTTP?", + "settings.https_switching": "Enabling HTTPS and restarting WGTools…", + "settings.https_switching_http": "Disabling HTTPS and restarting WGTools…", + "audit.action.https.certificate_issued": "HTTPS certificate issued", + "audit.action.https.certificate_failed": "HTTPS certificate request failed", + "audit.action.https.enabled": "HTTPS enabled", + "audit.action.https.disabled": "HTTPS disabled", + "audit.result.issued": "issued", + "audit.result.enabled": "enabled", + "audit.result.disabled": "disabled", + "settings.https_access_path": "Panel access path", + "settings.https_access_path_help": "Choose your own path. With built-in HTTPS enabled, requests outside it receive 404.", + "settings.https_enable_fields_required": "Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.", + "settings.https_use_panel_host": "Use panel address", + "settings.https_reconnecting": "WGTools is switching to the new HTTPS address…", + "server.tab_nodes": "Nodes", + "common.type": "Type", + "common.status": "Status", + "common.copy_failed": "Could not copy", + "clients.vpn_address": "VPN address", + "nodes.title": "WGTools Nodes", + "nodes.subtitle": "Link multiple WGTools servers into one protected network and publish only the networks that other nodes should be able to reach.", + "nodes.enable_hub": "Enable HUB", + "nodes.connect_hub": "Connect to HUB", + "nodes.settings": "Node settings", + "nodes.settings_action": "Settings", + "nodes.sync_now": "Synchronize", + "nodes.disable": "Disable Nodes", + "nodes.disable_action": "Disconnect", + "nodes.join_title": "Connect new nodes", + "nodes.join_help": "Create a one-time code and enter it on another WGTools panel together with the HUB service endpoint, for example vpn.example.com:51950. The code is valid for 15 minutes and can be used once.", + "nodes.create_code": "Create code", + "nodes.connected_nodes": "Connected nodes", + "nodes.connected_nodes_help": "Information about other panels, their published networks and clients. Remote clients are read-only.", + "nodes.enable_hub_help": "This panel becomes the central node. On the same port number the HUB accepts WireGuard over UDP and protected initial pairing over TCP.", + "nodes.node_name": "Node name", + "nodes.transport_network": "Node transport network", + "nodes.transport_help": "A separate private network used only for WGTools ↔ WGTools transport. It must not overlap your VPN/LAN networks.", + "nodes.panel_url": "Panel URL", + "nodes.panel_url_help": "Optional. This is only an informational link for the “Open panel” button on other nodes and is never used by the Nodes connection itself.", + "nodes.extra_networks": "Additional node networks", + "nodes.extra_networks_help": "One network per line. Interface VPN networks and Site-to-site client remote networks are published automatically. Add only other routed LAN/networks here, for example 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools pre-fills detected VPN networks, Site-to-Site networks and locally routed LANs. Keep only the networks this node should publish into Nodes. One network per line.", + "nodes.published_networks_settings_help": "One network per line. This is the explicit list of networks this node publishes into Nodes. Removing a line stops advertising that network to other nodes.", + "nodes.available_networks_help": "Currently detected: {networks}. Newly detected networks are not published automatically; add the ones you want to the list above.", + "nodes.available_networks_none": "No additional local networks are currently detected.", + "nodes.connect_help": "Enter the HUB service endpoint and one-time code. The web panel URL, HTTPS port, certificate and private path are not used for Nodes pairing.", + "nodes.join_code": "Connection code", + "nodes.connect_reachability_note": "Initial pairing uses protected TCP on the specified port. After wgnode0 is created, networks, status, versions and read-only client data synchronize with the HUB over its internal WireGuard address.", + "nodes.connect": "Connect", + "nodes.settings_help": "Node name, optional “Open panel” link and the explicit published-network list. The panel URL is not used for Nodes pairing or synchronization.", + "nodes.details": "Details", + "nodes.not_configured": "WGTools Nodes is not configured", + "nodes.not_configured_help": "Enable HUB on this panel or connect it to an existing WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connected to HUB", + "nodes.mode_none": "Not configured", + "nodes.role": "Role", + "nodes.tunnel": "Node tunnel", + "nodes.node_ip": "Node address", + "nodes.endpoint": "HUB endpoint", + "nodes.published_networks": "Published networks", + "nodes.last_sync": "Last sync", + "nodes.no_nodes_hub": "No nodes are connected yet. Create a connection code and use it on another WGTools panel.", + "nodes.no_nodes_spoke": "No remote node information has been received yet.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Open panel", + "nodes.route_conflict": "Route conflict", + "nodes.no_published_networks": "No published networks", + "nodes.load_failed": "Could not load WGTools Nodes", + "nodes.enable_hub_confirm": "Enable WGTools HUB and create the internal Node WireGuard tunnel?", + "nodes.applying": "Configuring the WGTools Nodes tunnel…", + "nodes.enable_failed": "Could not enable HUB", + "nodes.hub_enabled": "WGTools HUB enabled", + "nodes.connecting": "Verifying the HUB code and creating the protected Node tunnel…", + "nodes.connect_failed": "Could not connect to HUB", + "nodes.connected": "Connected to WGTools HUB", + "nodes.settings_failed": "Could not save Node settings", + "nodes.settings_saved": "Node settings saved", + "nodes.code_failed": "Could not create connection code", + "nodes.code_expires": "One-time code. Valid until {time}.", + "nodes.code_copied": "Connection code copied", + "nodes.network_vpn": "VPN clients", + "nodes.network_site_to_site": "Site-to-site network", + "nodes.network_custom": "Additional network", + "nodes.conflict": "Conflict", + "nodes.remote_clients": "Clients (read-only)", + "nodes.no_clients": "No clients reported by this node", + "nodes.details_failed": "Could not load Node details", + "nodes.remove_confirm": "Remove node “{name}” from this HUB? Its internal tunnel access will be revoked.", + "nodes.remove_failed": "Could not remove Node", + "nodes.removed": "Node removed", + "nodes.disable_hub_confirm": "Disable HUB and disconnect all WGTools Nodes? The internal Node tunnel will be removed.", + "nodes.disconnect_confirm": "Disconnect this WGTools panel from its HUB and remove the internal Node tunnel?", + "nodes.disable_failed": "Could not disable WGTools Nodes", + "nodes.disabled": "WGTools Nodes disabled", + "nodes.sync_failed": "Node synchronization failed", + "nodes.synced": "Node information synchronized", + "nodes.service_port": "Nodes port", + "nodes.service_port_help": "The same port number is used simultaneously: UDP for WireGuard and TCP for protected initial pairing.", + "nodes.hub_port_forward_note": "If the HUB is behind NAT, forward the same port to it for both UDP and TCP. The WGTools web port, HTTPS and private panel path are unrelated to Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Nodes domain/IP and port without http:// or https://, for example vpn.example.com:51950.", + "settings.collapse_sidebar": "Collapse sidebar", + "settings.expand_sidebar": "Expand sidebar", + "settings.https_issue_fields_required": "Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.", + "settings.https_issue_ok_saved": "Certificate is ready and HTTPS settings are saved.", + "settings.https_enable_need_certificate": "First obtain a certificate.", + "settings.https_enable_certificate_mismatch": "Obtain a certificate for the current domain or public IP first.", + "settings.https_enable_certificate_expired": "The certificate has expired. Renew it before enabling HTTPS.", + "settings.https_enable_certificate_ready": "Certificate is ready — built-in HTTPS can now be enabled.", + "settings.https_enable_active_help": "Clear the checkbox and save to return to HTTP.", + "settings.https_certificate_expired": "Expired", + "settings.https_certificate_wrong_target": "For another address", + "nodes.network_conflict_error": "Published networks conflict with another Node or the Nodes transport network: {conflicts}. Remove or change the conflicting network.", + "nodes.networks_changed": "Detected networks changed after the published list was last saved. New: {added}. No longer detected: {removed}. Review the published network list and save the settings after checking it.", + "nodes.review_networks": "Review networks", + "nodes.vpn_pool_mismatch": "VPN pool changed: Nodes still publishes {old}, while the current WireGuard VPN pool is {current}. Open Node settings and update the published networks.", + "server.error_vpn_network_invalid": "VPN network must be a valid IPv4 network, for example 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Only IPv4 VPN networks are supported.", + "server.error_vpn_network_too_small": "The VPN network must contain at least two usable addresses.", + "server.error_vpn_network_no_hosts": "The selected VPN network has no usable server addresses.", + "server.error_server_address_prefix": "The server VPN address must include a prefix, for example 10.0.0.1/24.", + "server.error_server_address_network": "The server VPN address must belong to the selected VPN address pool and use the same prefix.", + "server.error_server_address_reserved": "The server VPN address cannot be the network or broadcast address.", + "server.error_listen_port_number": "The WireGuard port must be a number.", + "server.error_listen_port_range": "The WireGuard port must be between 1 and 65535.", + "server.error_mtu_number": "MTU must be a number.", + "auth.mfa_title": "Two-factor authentication", + "auth.mfa_login_help": "Enter the 6-digit code from Google Authenticator or one of your recovery codes.", + "auth.mfa_code": "Authentication code", + "auth.mfa_verify": "Verify and sign in", + "auth.mfa_back": "Back to password", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Two-factor authentication (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Enabled", + "settings.mfa_disabled": "Disabled", + "settings.mfa_google_help": "Protect this account with Google Authenticator or another TOTP-compatible authenticator. Your current password is required to start setup.", + "settings.current_password": "Current password", + "settings.mfa_start": "Set up Google Authenticator", + "settings.mfa_secret": "Manual setup key", + "settings.mfa_scan_help": "Scan the QR code in Google Authenticator, then enter the current 6-digit code to finish enabling MFA.", + "settings.mfa_code": "6-digit code", + "settings.mfa_enable": "Enable MFA", + "settings.mfa_manage_help": "To change MFA, enter your current password and a Google Authenticator code or recovery code.", + "settings.mfa_code_or_recovery": "Authenticator or recovery code", + "settings.mfa_regenerate": "New recovery codes", + "settings.mfa_disable": "Disable MFA", + "settings.mfa_recovery_title": "Recovery codes", + "settings.mfa_recovery_help": "Save these codes now. Each code can be used once if Google Authenticator is unavailable. They are not shown again.", + "settings.mfa_recovery_remaining": "Recovery codes remaining: {count}", + "settings.mfa_enabled_ok": "MFA enabled.", + "settings.mfa_disabled_ok": "MFA disabled.", + "settings.mfa_disable_confirm": "Disable two-factor authentication for this account?", + "settings.mfa_regenerate_confirm": "Replace all existing recovery codes?", + "settings.mfa_recovery_regenerated": "New recovery codes created.", + "audit.action.auth.mfa_failed": "MFA verification failed", + "audit.action.auth.mfa_recovery_used": "MFA recovery code used", + "audit.action.user.mfa_setup_started": "MFA setup started", + "audit.action.user.mfa_enabled": "MFA enabled", + "audit.action.user.mfa_disabled": "MFA disabled", + "audit.action.user.mfa_disabled_cli": "MFA disabled from CLI", + "audit.action.user.mfa_recovery_regenerated": "MFA recovery codes regenerated", + "settings.mfa_error_password": "Invalid current password.", + "settings.mfa_error_code": "Invalid authentication code.", + "settings.mfa_error_already_enabled": "MFA is already enabled.", + "settings.mfa_error_not_enabled": "MFA is not enabled.", + "settings.mfa_error_not_started": "Start MFA setup again.", + "trace.title": "Traceroute, ping and route map", + "trace.subtitle": "Measure latency to a VPS or other server and see where delay appears along the route.", + "trace.target": "Server IP or hostname", + "trace.show_map": "Show route on map", + "trace.run": "Run trace", + "trace.geo_note": "Geolocation is approximate. When the map is enabled, public hop IP addresses are sent to ipwho.is for location lookup; map tiles are loaded from OpenStreetMap.", + "trace.latency_note": "Traceroute measures latency in milliseconds, not throughput in Mbit/s.", + "trace.map": "Route map", + "trace.map_hint": "Interactive map: drag to pan, use the mouse wheel or +/− to zoom, and click a hop for details.", + "trace.hop": "Hop / IP", + "trace.location": "Location", + "trace.avg_rtt": "Avg RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Loss", + "trace.summary_target": "Target", + "trace.summary_ping": "Average ping", + "trace.summary_loss": "Ping loss", + "trace.summary_hops": "Hops", + "trace.no_reply": "No reply", + "trace.private": "Private network", + "trace.unknown": "Unknown", + "trace.running": "Running ping and traceroute… This can take up to a minute.", + "trace.done": "Network trace completed.", + "trace.failed": "Network trace failed", + "trace.partial_geo": "Some public hops could not be geolocated.", + "trace.not_reached": "Target was not reached by traceroute.", + "trace.reached": "Target reached", + "trace.ms": "ms", + "server.tab_trace": "Trace", + "trace.map_controls": "Map controls", + "trace.zoom_in": "Zoom in", + "trace.zoom_out": "Zoom out", + "trace.fit_route": "Fit route", + "trace.fit": "Fit", + "trace.map_click_hint": "Click a hop for IP, location, ASN and RTT details.", + "trace.route_path": "Route", + "trace.ping_ok_trace_filtered": "Target responds to ping; final traceroute hops do not reply.", + "trace.latency_legend": "Latency growth between responding hops", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — increased", + "trace.latency_bad": "Δ RTT > 20 ms — sharp jump" +} diff --git a/app/static/locales/es.json b/app/static/locales/es.json new file mode 100644 index 0000000..8c90bb0 --- /dev/null +++ b/app/static/locales/es.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Crear usuario", + "auth.login_subtitle": "Introduce tu usuario y contraseña de WGTools.", + "auth.login_title": "Iniciar sesión en WGTools", + "auth.password": "Contraseña", + "auth.password_repeat": "Repetir contraseña", + "auth.setup_help": "La primera cuenta tiene acceso completo a WGTools. Puedes crear más usuarios después en Ajustes.", + "auth.setup_subtitle": "Para gestionar el servidor, primero debes crear una cuenta de WGTools.", + "auth.setup_title": "Crear el primer usuario", + "auth.sign_in": "Iniciar sesión", + "auth.sign_out": "Cerrar sesión", + "auth.username": "Nombre de usuario", + "clients.actions": "Acciones", + "clients.add": "+ Añadir cliente", + "clients.address": "Dirección VPN", + "clients.address_hint": "Se sugiere automáticamente la primera dirección libre.", + "clients.allowed_ips_required": "Introduce al menos una red AllowedIPs para la configuración del cliente.", + "clients.basic_connection": "Ajustes de conexión", + "clients.basic_details": "Cliente", + "clients.client": "Cliente", + "clients.client_allowed_ips": "AllowedIPs en la configuración del cliente", + "clients.config_private_warning": "Esta configuración contiene la clave privada del cliente. Guárdala de forma segura.", + "clients.config_title": "Configuración del cliente", + "clients.config_unavailable": "Configuración no disponible", + "clients.connection_direct": "Directamente a WGTools", + "clients.connection_path": "Ruta de conexión", + "clients.connection_relay": "Relay VPS", + "clients.connection_via": "Conectar a través de", + "clients.connection_via_hint": "Elige la entrada pública usada por el cliente. Relay solo aparece si está instalado en la interfaz WireGuard seleccionada.", + "clients.copy_config": "Copiar", + "clients.copy_done": "Configuración copiada", + "clients.create_subtitle": "Crea un par WireGuard y genera su configuración de cliente.", + "clients.create_title": "Crear cliente", + "clients.creating": "Generando claves y aplicando cliente…", + "clients.day_fri": "Vie", + "clients.day_mon": "Lun", + "clients.day_sat": "Sáb", + "clients.day_sun": "Dom", + "clients.day_thu": "Jue", + "clients.day_tue": "Mar", + "clients.day_wed": "Mié", + "clients.delete_confirm": "¿Eliminar este cliente de WireGuard? WGTools creará una copia y eliminará las reglas automáticas asociadas.", + "clients.deleted": "Cliente eliminado", + "clients.dns": "DNS (opcional)", + "clients.dns_hint": "Servidores DNS IPv4 separados por comas.", + "clients.download_config": "Descargar .conf", + "clients.duplicate": "Duplicar", + "clients.duplicate_address_error": "Otro par ya usa esta dirección VPN.", + "clients.duplicate_name_error": "Ya existe un par con ese nombre.", + "clients.duplicate_ready": "Copia lista. WGTools asignó un nombre y una dirección VPN nuevos. Revisa los ajustes antes de guardar.", + "clients.duplicate_site_hint": "Se han borrado las redes remotas para evitar rutas duplicadas. Introduce las redes del nuevo par Site-to-site.", + "clients.duplicate_suffix": "copia", + "clients.edit_subtitle": "Actualiza el par del servidor. Los cambios se aplican sin reiniciar WireGuard.", + "clients.edit_title": "Editar cliente", + "clients.endpoint": "Endpoint del servidor", + "clients.endpoint_hint": "Para clientes remotos, usa la IP pública o el dominio que redirige el puerto WireGuard a este servidor.", + "clients.existing": "Par existente", + "clients.expiration": "Duración del acceso", + "clients.expiration_action": "Al caducar", + "clients.expiration_action_hint": "Si se desmarca, el cliente sigue en WGTools pero pierde acceso a WireGuard. Elige una nueva duración o Sin caducidad y guarda para restaurarlo.", + "clients.expiration_datetime": "Caduca el", + "clients.expiration_datetime_hint": "Usa la fecha y hora locales del navegador.", + "clients.expiration_delete": "Eliminar cliente", + "clients.expiration_future_required": "Elige una fecha y hora futuras.", + "clients.expiration_hint": "Al caducar, WGTools ejecuta la acción elegida en el siguiente minuto. Antes crea una copia de WireGuard.", + "clients.expire_1d": "1 día", + "clients.expire_1h": "1 hora", + "clients.expire_3h": "3 horas", + "clients.expire_6h": "6 horas", + "clients.expire_custom": "Fecha y hora personalizadas", + "clients.expire_never": "Sin caducidad", + "clients.expired": "Caducado", + "clients.expired_disabled_hint": "El acceso ha caducado. El cliente se conserva, pero WireGuard está deshabilitado. Elige otra duración o Sin caducidad y guarda.", + "clients.expired_disabled_short": "Caducado · desactivado", + "clients.expired_disabled_status": "Caducado", + "clients.expires_days": "Caduca en {n} d", + "clients.expires_hours": "Caduca en {n} h", + "clients.expires_minutes": "Caduca en {n} min", + "clients.generated_config": "Configuración del cliente generada", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 segundos es un buen valor por defecto para clientes tras NAT.", + "clients.local_access_exceptions": "Direcciones locales permitidas", + "clients.local_access_exceptions_hint": "IP o CIDR opcionales accesibles aunque su red local o Site-to-site esté bloqueada. Sepáralos por comas.", + "clients.managed": "Gestionado por WGTools", + "clients.name": "Nombre", + "clients.no_peers": "No se encontraron pares", + "clients.peers": "Pares", + "clients.peers_subtitle": "Los cambios se respaldan y aplican con wg syncconf sin reiniciar la interfaz WireGuard.", + "clients.protected_networks_reference": "Redes locales bloqueadas (referencia)", + "clients.protected_networks_reference_hint": "Estas redes no se escriben en AllowedIPs. La política del servidor WGTools bloquea su acceso; arriba pueden permitirse direcciones individuales.", + "clients.psk": "Clave precompartida (PSK)", + "clients.psk_enable": "Usar una clave WireGuard precompartida adicional", + "clients.psk_hint": "Recomendado. Añade un secreto simétrico al handshake WireGuard. Los clientes estándar lo admiten; WGTools incluye el PSK en la configuración y el QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generando QR…", + "clients.quick_search": "Búsqueda rápida", + "clients.quick_search_clear": "Borrar búsqueda", + "clients.quick_search_empty": "Ningún cliente coincide", + "clients.relay_endpoint_note": "La configuración generada se conectará a {endpoint}. El servidor WireGuard sigue en este host WGTools.", + "clients.relay_required": "Elige un Relay VPS para este cliente.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "no disponible", + "clients.relay_vps": "Relay VPS", + "clients.relay_vps_hint": "El endpoint del cliente se genera automáticamente desde este Relay.", + "clients.remote_hint": "Redes detrás de este par. Una por línea o separadas por comas.", + "clients.remote_networks": "Redes remotas", + "clients.remote_required": "Introduce al menos una red remota para el par Site-to-site.", + "clients.required": "Se requieren nombre y dirección VPN.", + "clients.route_custom": "Personalizada", + "clients.route_full": "Túnel completo", + "clients.route_full_except_local": "Túnel completo excepto redes locales", + "clients.route_hint": "Solo estas redes se escriben en AllowedIPs de la configuración del cliente.", + "clients.route_preset": "Tráfico por VPN", + "clients.route_vpn": "Solo red VPN", + "clients.route_vpn_lan": "VPN + LAN local", + "clients.saved": "Cliente guardado", + "clients.schedule_blocked_short": "Horario · bloqueado", + "clients.schedule_blocked_status": "Bloqueado por horario", + "clients.schedule_days": "Días permitidos", + "clients.schedule_days_required": "Elige al menos un día para el horario.", + "clients.schedule_disabled_hint": "Este cliente está bloqueado por su horario. WGTools restaurará el par automáticamente en el próximo periodo permitido.", + "clients.schedule_enable": "Limitar acceso por horario", + "clients.schedule_from": "Acceso desde", + "clients.schedule_hint": "WGTools puede deshabilitar y restaurar el cliente en días y horas seleccionados sin cambiar su configuración.", + "clients.schedule_short": "Horario", + "clients.schedule_time_required": "Define las horas de inicio y fin del horario.", + "clients.schedule_timezone_hint": "El horario usa la hora local del servidor WireGuard. Admite periodos nocturnos como 22:00–06:00.", + "clients.schedule_title": "Horario de acceso", + "clients.schedule_to": "Acceso hasta", + "clients.security_access": "Seguridad y horario de acceso", + "clients.server_host": "Dirección / dominio del servidor", + "clients.server_host_hint": "IP pública o dominio usado por el cliente. Se sugieren valores anteriores.", + "clients.server_host_required": "Se requiere dirección / dominio del servidor para generar la configuración.", + "clients.server_peer": "Par servidor", + "clients.server_port": "Puerto WireGuard", + "clients.server_port_hint": "Se obtiene automáticamente de la configuración del servidor.", + "clients.site_to_site": "Sitio a sitio", + "clients.status": "Estado", + "clients.subtitle": "Pares WireGuard, estado en directo y gestión de configuraciones de clientes.", + "clients.tab_basic": "Básico", + "clients.tab_config": "Configuración", + "clients.tab_policy": "Políticas", + "clients.tab_security": "Seguridad", + "clients.title": "Clientes", + "clients.type": "Tipo", + "clients.unmanaged_note": "Este par existía antes de WGTools. Su clave privada no se puede recuperar. WGTools puede editarlo en el servidor pero no generar su configuración de cliente ni QR.", + "clients.updating": "Actualizando cliente…", + "common.actions": "Acciones", + "common.ago": "hace", + "common.cancel": "Cancelar", + "common.checking": "Comprobando…", + "common.close": "Cerrar", + "common.config": "Configuración", + "common.delete": "Eliminar", + "common.disabled": "Desactivado", + "common.edit": "Editar", + "common.enabled": "Activado", + "common.loading": "Cargando…", + "common.never": "Nunca", + "common.no": "No", + "common.not_configured": "Sin configurar", + "common.not_installed": "No instalado", + "common.offline": "desconectado", + "common.online": "conectado", + "common.refresh": "Actualizar", + "common.running": "En ejecución", + "common.save": "Guardar", + "common.stopped": "Detenido", + "common.total": "Total", + "common.unknown": "Desconocido", + "common.updated": "Actualizado", + "common.yes": "Sí", + "dashboard.active_peers": "Pares activos", + "dashboard.active_peers_subtitle": "Datos en directo de wg show.", + "dashboard.activity": "Resumen del sistema", + "dashboard.activity_subtitle": "Comprobaciones de solo lectura de WireGuard en ejecución.", + "dashboard.cores": "núcleos", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Últimas 24 h", + "dashboard.history_avg": "Prom.", + "dashboard.history_max": "Máx.", + "dashboard.history_min": "Mín.", + "dashboard.history_now": "ahora", + "dashboard.memory": "Memoria", + "dashboard.network": "Red", + "dashboard.peers": "Pares", + "dashboard.quick_search": "Búsqueda rápida", + "dashboard.quick_search_clear": "Borrar búsqueda", + "dashboard.quick_search_empty": "Ningún par coincide con la búsqueda", + "dashboard.restart": "Reiniciar", + "dashboard.restart_confirm": "¿Reiniciar WireGuard? Los clientes VPN activos se reconectarán automáticamente.", + "dashboard.restart_ok": "WireGuard reiniciado.", + "dashboard.routing": "Enrutamiento", + "dashboard.site_to_site": "Sitio a sitio", + "dashboard.start": "Iniciar", + "dashboard.start_ok": "WireGuard iniciado.", + "dashboard.stop": "Detener", + "dashboard.stop_confirm": "¿Detener WireGuard? Se desconectarán los clientes VPN activos.", + "dashboard.stop_ok": "WireGuard detenido.", + "dashboard.subtitle": "Estado del servidor WireGuard, pares y tráfico en directo.", + "dashboard.title": "Panel principal", + "dashboard.traffic": "Tráfico", + "dashboard.uptime": "Tiempo de actividad", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Política de acceso al servidor", + "groups.additional_allowed": "Direcciones adicionales permitidas", + "groups.additional_blocked": "Direcciones adicionales bloqueadas", + "groups.allow": "Permitir", + "groups.allowed": "Permitido", + "groups.allowed_addresses": "Direcciones / redes permitidas", + "groups.apply_current_template": "Aplicar plantilla actual del grupo", + "groups.apply_defaults": "Aplicar plantilla actual del grupo", + "groups.apply_defaults_hint": "Copia rutas, DNS y Keepalive de la plantilla al cliente. Guarda el cliente y genera nueva configuración o QR si debes actualizar el dispositivo.", + "groups.basic": "Información básica", + "groups.block": "Bloquear", + "groups.blocked": "Bloqueado", + "groups.blocked_addresses": "Direcciones / redes bloqueadas", + "groups.client_config_source": "Origen de configuración del cliente", + "groups.client_defaults": "Valores predeterminados del cliente", + "groups.client_group_hint": "Grupo opcional para reutilizar políticas de acceso y valores del cliente. Los grupos corresponden a la interfaz WireGuard seleccionada.", + "groups.config_differs": "La configuración del cliente difiere de la plantilla del grupo. La política del servidor está actualizada, pero el dispositivo requiere una nueva configuración o QR.", + "groups.config_differs_short": "Configuración distinta de la del grupo", + "groups.create": "Crear grupo", + "groups.create_title": "Crear grupo", + "groups.created": "Grupo creado", + "groups.creating": "Creando grupo…", + "groups.defaults_applied": "Plantilla del grupo aplicada. Guarda el cliente para conservarla.", + "groups.defaults_hint": "Define qué tráfico envía el cliente mediante WireGuard. La política del servidor determina los accesos permitidos. Los cambios de plantilla nunca modifican configuraciones ya instaladas.", + "groups.delete_message": "¿Eliminar «{name}»? Las configuraciones de clientes nunca se borran con el grupo.", + "groups.delete_move": "Mover sus clientes a otro grupo", + "groups.delete_title": "Eliminar grupo de clientes", + "groups.delete_unassign": "Quitar la asignación de grupo a sus clientes", + "groups.deleted": "Grupo eliminado", + "groups.deleting": "Actualizando clientes y eliminando grupo…", + "groups.description": "Descripción", + "groups.edit_title": "Editar grupo", + "groups.editor_subtitle": "Un grupo combina una política de acceso activa con una plantilla de configuración de clientes.", + "groups.effective_allow": "Excepciones permitidas", + "groups.effective_deny": "Excepciones bloqueadas", + "groups.effective_policy": "Política efectiva del servidor", + "groups.empty": "Aún no hay grupos de clientes. Crea uno para reutilizar políticas y configuraciones predeterminadas.", + "groups.group": "Grupo", + "groups.inherit": "Heredar", + "groups.internet_access": "Acceso a Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Redes locales", + "groups.local_short": "Local", + "groups.manage": "Grupos", + "groups.members_count": "{count} clientes", + "groups.name": "Nombre", + "groups.name_required": "Se requiere el nombre del grupo.", + "groups.new_client_defaults": "Plantilla de configuración del cliente", + "groups.new_clients_short": "Clientes nuevos", + "groups.no_group": "Sin grupo", + "groups.none": "Ninguno", + "groups.override_client_config": "Anular la plantilla de grupo para este cliente", + "groups.override_client_config_hint": "Desactivado: rutas, DNS y Keepalive vienen del grupo. Activado: el cliente conserva sus valores. Las excepciones de política del servidor siguen independientes.", + "groups.policy_addresses_hint": "Direcciones IPv4 o CIDR separados por comas. Las excepciones del cliente prevalecen sobre las del grupo.", + "groups.policy_custom": "Política personalizada", + "groups.policy_inherit": "Usar política del grupo", + "groups.policy_mode": "Origen de la política", + "groups.policy_mode_hint": "La política del grupo se hereda por defecto. Las excepciones del cliente no modifican el grupo.", + "groups.routes_required": "Las rutas del cliente no pueden estar vacías.", + "groups.subtitle": "Reutiliza políticas de acceso y valores predeterminados para los clientes de la interfaz WireGuard elegida.", + "groups.title": "Grupos de clientes", + "groups.traffic_through_vpn": "Tráfico por VPN", + "groups.updated": "Grupo actualizado", + "groups.updating": "Actualizando política del grupo…", + "help.example_note": "Todas las direcciones, interfaces, nombres de pares y dominios de los ejemplos son ficticios. Sustitúyelos por los datos de tu red.", + "help.navigation": "Navegación de ayuda", + "help.open": "Abrir ayuda", + "help.subtitle": "Ayuda clara para Panel, Servidor, Clientes y Ajustes con ejemplos prácticos.", + "help.title": "Ayuda de WGTools", + "interfaces.add": "+ Añadir interfaz", + "interfaces.create": "Crear interfaz", + "interfaces.create_confirm": "¿Crear e iniciar la interfaz {name}?", + "interfaces.create_failed": "No se pudo crear la interfaz", + "interfaces.create_hint": "Antes de crear la configuración, WGTools comprueba que la red VPN, el puerto UDP y la tabla de enrutamiento no entren en conflicto con otras interfaces WireGuard.", + "interfaces.create_subtitle": "Crea una interfaz WireGuard independiente con su propio grupo de direcciones, puerto UDP y opciones de enrutamiento.", + "interfaces.create_title": "Añadir interfaz WireGuard", + "interfaces.created": "Interfaz creada correctamente.", + "interfaces.creating": "Generando claves, guardando configuración e iniciando WireGuard…", + "interfaces.current": "Actual", + "interfaces.delete": "Eliminar", + "interfaces.delete_confirm": "¿Eliminar la interfaz {name}? Se borrarán su configuración WireGuard y todos sus pares. Antes se creará una copia.", + "interfaces.delete_failed": "No se pudo eliminar la interfaz", + "interfaces.delete_last": "No se puede eliminar aquí la última interfaz WireGuard configurada.", + "interfaces.delete_tooltip": "Eliminar esta interfaz WireGuard", + "interfaces.deleted": "Interfaz eliminada. Copia: {backup}", + "interfaces.deleting": "Deteniendo WireGuard y eliminando interfaz…", + "interfaces.display_name": "Nombre visible", + "interfaces.display_name_edit_hint": "Solo nombre visible: el nombre de la interfaz Linux no cambia.", + "interfaces.display_name_hint": "Nombre opcional, p. ej. Trabajo o Contratistas.", + "interfaces.identity": "Identidad de la interfaz", + "interfaces.none": "No se encontraron interfaces WireGuard", + "interfaces.none_configured": "Aún no hay interfaces WireGuard configuradas.", + "interfaces.peers_short": "pares", + "interfaces.rename_failed": "No se pudo guardar el nombre de la interfaz.", + "interfaces.select": "Seleccionar", + "interfaces.subtitle": "Cada interfaz tiene su red VPN, puerto, pares y políticas. Selecciona una para gestionarla en WGTools.", + "interfaces.switch_title": "Interfaces WireGuard", + "interfaces.system_name": "Nombre del sistema", + "interfaces.system_name_hint": "Nombre de la interfaz Linux, p. ej. wg1. No se puede cambiar después.", + "interfaces.title": "Interfaces WireGuard", + "interfaces.unique_port_hint": "Cada interfaz WireGuard del servidor debe usar un puerto UDP distinto.", + "interfaces.unique_table_hint": "WGTools recomienda una tabla de rutas distinta por interfaz. Déjala vacía para el enrutamiento normal.", + "nav.clients": "Clientes", + "nav.dashboard": "Panel principal", + "nav.server": "Servidor", + "nav.settings": "Configuración", + "server.access_apply_confirm": "¿Guardar y aplicar esta regla de firewall? WireGuard se reiniciará brevemente y se creará una copia.", + "server.access_rule_deleted": "Regla de acceso eliminada.", + "server.access_rule_help": "Crea una regla FORWARD sin editar comandos iptables manualmente.", + "server.access_rule_order_hint": "WGTools inserta reglas al inicio de FORWARD para aplicar restricciones antes de las reglas VPN ACCEPT generales.", + "server.access_rule_saved": "Regla de acceso guardada y aplicada.", + "server.action": "Acción", + "server.action_hint": "REJECT notifica el rechazo al cliente; DROP descarta sin respuesta; ACCEPT permite explícitamente.", + "server.add_access_rule": "Añadir regla de acceso", + "server.add_route": "Añadir ruta", + "server.address": "Dirección", + "server.any": "Cualquiera", + "server.any_protocol": "Cualquiera", + "server.apply_confirm": "¿Guardar y aplicar los ajustes del servidor? WireGuard se reiniciará brevemente. Se creará una copia y, si falla el arranque, WGTools restaurará la configuración anterior.", + "server.apply_settings": "Guardar y aplicar", + "server.applying_rule": "Creando copia y aplicando…", + "server.applying_settings": "Validando ajustes, creando copia y aplicando…", + "server.basic_settings": "Ajustes básicos", + "server.config_tab_help": "Abrir el editor de configuración sin procesar de la interfaz WireGuard seleccionada.", + "server.create_confirm": "¿Crear e iniciar el servidor WireGuard con estos ajustes?", + "server.create_server": "Crear servidor", + "server.create_step_conf": "Crear configuración de la interfaz WireGuard con permisos 600.", + "server.create_step_forward": "Configurar reenvío, NAT y enrutamiento por políticas opcional.", + "server.create_step_key": "Generar nuevo par de claves del servidor.", + "server.create_step_start": "Habilitar e iniciar la interfaz wg-quick seleccionada.", + "server.create_subtitle": "WireGuard está instalado, pero la interfaz seleccionada aún no está configurada.", + "server.create_success": "Servidor WireGuard creado correctamente.", + "server.create_title": "Crear servidor WireGuard", + "server.creating": "Generando claves, escribiendo configuración e iniciando WireGuard…", + "server.custom_preserved": "Se conservan bloques de pares, rutas Site-to-site y reglas PostUp/PostDown no gestionadas por estos campos.", + "server.delete_access_confirm": "¿Eliminar esta regla de acceso y aplicar el cambio?", + "server.delete_route_confirm": "¿Eliminar esta ruta personalizada y aplicar el cambio?", + "server.destination": "Destino", + "server.destination_hint": "Vacío = cualquiera. Admite IP, CIDR o rango de IP. Separa destinos con comas.", + "server.destination_port": "Puerto de destino", + "server.destination_port_hint": "Opcional. Puerto como 443 o rango 10000:20000. Selecciona antes TCP o UDP.", + "server.details": "Detalles", + "server.dev_word": "dev", + "server.diagnostics": "Diagnóstico", + "server.diagnostics_done": "Diagnóstico completado", + "server.diagnostics_subtitle": "Comprobaciones actuales del sistema. No se cambia la configuración.", + "server.direction": "Hook", + "server.edit_access_rule": "Editar regla de acceso", + "server.edit_route": "Editar ruta", + "server.edit_server": "Editar servidor", + "server.edit_subtitle": "Editar ajustes generales WireGuard, rutas y NAT. Se conservan los pares y reglas personalizadas.", + "server.edit_title": "Ajustes del servidor", + "server.edit_warning": "Aplicar cambios de interfaz, rutas o firewall reinicia brevemente WireGuard. Los pares activos se reconectarán automáticamente.", + "server.enable_forwarding": "Habilitar reenvío IPv4", + "server.enable_nat": "Habilitar NAT / Masquerade", + "server.firewall": "Cortafuegos y NAT", + "server.firewall_subtitle": "Reglas detectadas de hooks WireGuard.", + "server.firewall_subtitle_v08": "Reglas de reenvío/NAT y acceso de la interfaz. Las simples se gestionan aquí y las avanzadas en el editor sin procesar.", + "server.forward_from_vpn": "Permitir reenvío desde VPN", + "server.forward_to_vpn": "Permitir reenvío hacia VPN", + "server.forwarding_section": "Reenvío y NAT", + "server.gateway": "Puerta de enlace", + "server.gateway_hint": "Solo necesario si se usa una tabla de enrutamiento por políticas.", + "server.install_success": "WireGuard instalado correctamente.", + "server.install_wireguard": "Instalar WireGuard", + "server.install_wireguard_help": "Ejecuta apt update e instala WireGuard y herramientas de red necesarias.", + "server.install_wireguard_title": "Instalar WireGuard", + "server.installing": "Instalando WireGuard… Puede tardar un minuto.", + "server.interface": "Interfaz", + "server.interface_hint": "WGTools gestiona actualmente esta interfaz.", + "server.interface_name": "Interfaz", + "server.interface_section": "Interfaz WireGuard", + "server.ip_forwarding": "Reenvío IPv4", + "server.kind": "Tipo", + "server.listen_port": "Puerto de escucha", + "server.local_network": "Red local", + "server.local_network_hint": "Ruta opcional añadida a la tabla de políticas.", + "server.managed_automatically": "Gestionado automáticamente", + "server.nat": "NAT / Masquerade", + "server.network": "Red", + "server.network_settings": "Red y NAT", + "server.no_firewall": "No se encontraron reglas de firewall", + "server.no_routes": "No se encontraron rutas", + "server.not_configured": "Sin configurar", + "server.not_set": "Sin definir", + "server.policy_disabled_hint": "Desactiva para rutas normales del sistema. Habilita solo si esta VPN necesita su tabla de rutas por origen.", + "server.policy_enabled": "Habilitar enrutamiento por políticas", + "server.policy_table": "Tabla de políticas", + "server.policy_table_hint": "Déjalo vacío para rutas normales; usa p. ej. 200 para rutas por origen.", + "server.port_word": "puerto", + "server.private_hidden": "Configurado (oculto)", + "server.private_key": "Clave privada", + "server.protocol": "Protocolo", + "server.route_apply_confirm": "¿Guardar y aplicar esta ruta? WireGuard se reiniciará brevemente tras crear una copia.", + "server.route_custom": "Personalizada", + "server.route_deleted": "Ruta eliminada.", + "server.route_device_hint": "Interfaz de salida opcional, p. ej. wg0 o enp6s18.", + "server.route_editor_help": "Añade una ruta instalada cuando inicia WireGuard y eliminada cuando se detiene.", + "server.route_gateway_hint": "Puerta de enlace de siguiente salto opcional. Se requiere puerta o interfaz.", + "server.route_managed_peer": "Par Site-to-site", + "server.route_managed_server": "Ajuste del servidor", + "server.route_network_hint": "Red IPv4 como 10.20.0.0/24 o 'default'.", + "server.route_saved": "Ruta guardada y aplicada.", + "server.route_table_hint": "Usa 'main' para rutas normales o una tabla numérica como 200.", + "server.route_type": "Tipo", + "server.routes": "Rutas detectadas", + "server.routes_subtitle": "Rutas extraídas de PostUp/PostDown y del estado actual de rutas por políticas.", + "server.routes_subtitle_v08": "Rutas del servidor, Site-to-site y personalizadas de la interfaz elegida. Aquí puedes añadir, editar o eliminar rutas propias.", + "server.routing": "Enrutamiento", + "server.routing_section": "Enrutamiento", + "server.rule": "Regla", + "server.rule_access": "Regla de acceso", + "server.rule_advanced": "Avanzado", + "server.rule_apply_warning": "Aplicar una ruta o regla de firewall reinicia brevemente WireGuard. WGTools crea una copia y restaura automáticamente si falla el arranque.", + "server.rule_client_exception": "Excepción de cliente", + "server.rule_client_policy": "Política del cliente", + "server.rule_managed_server": "Ajuste del servidor", + "server.rule_type": "Tipo", + "server.run_diagnostics": "Ejecutar diagnóstico", + "server.save_apply": "Guardar y aplicar", + "server.save_config": "SaveConfig", + "server.server_address": "Dirección VPN del servidor", + "server.server_address_hint": "Normalmente la primera dirección utilizable de la red VPN.", + "server.settings_applied": "Ajustes del servidor guardados y aplicados correctamente.", + "server.settings_apply_failed": "No se pudieron aplicar los ajustes del servidor", + "server.setup_required": "Configuración necesaria", + "server.source": "Origen", + "server.source_hint": "Vacío = cualquiera. Admite IP, CIDR o rango como 10.0.0.100-10.0.0.120.", + "server.subtitle": "Instalación, configuración inicial y configuración actual del servidor WireGuard.", + "server.tab_config": "Configuración", + "server.tab_interface": "Interfaz", + "server.tab_routing": "Enrutamiento", + "server.tab_vps": "VPS", + "server.table": "Tabla", + "server.tabs_aria": "Secciones de ajustes del servidor", + "server.title": "Servidor", + "server.uplink": "Interfaz de enlace ascendente", + "server.use_raw_editor": "Usar editor sin procesar", + "server.via": "Vía / Dispositivo", + "server.via_word": "via", + "server.vpn_network": "Red VPN", + "server.vpn_network_hint": "Las direcciones de clientes se asignarán desde esta red.", + "server.vpn_pool": "Grupo de direcciones VPN", + "server.wg_not_installed": "WireGuard no está instalado", + "server.wg_not_installed_subtitle": "WGTools puede instalar automáticamente los paquetes Debian necesarios.", + "server.what_happens": "Qué hará WGTools", + "settings.about": "Acerca de", + "settings.add_user": "Añadir usuario", + "settings.advanced": "Avanzado", + "settings.advanced_subtitle": "Acceso directo a herramientas avanzadas de configuración WireGuard.", + "settings.appearance": "Apariencia", + "settings.applying_config": "Validando configuración, creando copia y aplicando…", + "settings.backup_count": "Copias guardadas", + "settings.backup_retention": "Copias a conservar", + "settings.backup_retention_help": "Las copias automáticas antiguas se eliminan tras crear una nueva. De 1 a 200 archivos.", + "settings.backups": "Copias de configuración", + "settings.backups_always_on": "Activado", + "settings.backups_subtitle": "WGTools crea automáticamente una copia antes de modificar la configuración. Las copias automáticas no se pueden desactivar.", + "settings.change_password": "Cambiar contraseña", + "settings.check_updates": "Buscar actualizaciones", + "settings.config_applied": "Configuración guardada y aplicada correctamente.", + "settings.config_applied_restarted": "Configuración aplicada y WireGuard reiniciado.", + "settings.config_applied_stopped": "Configuración guardada. WireGuard estaba detenido y sigue detenido.", + "settings.config_apply_failed": "No se pudo aplicar la configuración", + "settings.config_load_failed": "No se pudo cargar la configuración", + "settings.current_user": "Usuario actual", + "settings.current_version": "Versión actual", + "settings.audit_action": "Acción", + "settings.audit_empty": "Aún no hay eventos de auditoría", + "settings.audit_log": "Auditoría", + "settings.audit_log_subtitle": "Acciones del panel, acceso, Telegram e historial de conexiones WireGuard. Nunca se guardan secretos.", + "settings.audit_object": "Objeto", + "settings.audit_result": "Resultado", + "settings.audit_retention_note": "Retención: 30 días", + "settings.audit_search": "Búsqueda rápida", + "settings.audit_search_clear": "Borrar búsqueda", + "settings.audit_search_empty": "Ningún evento de auditoría coincide", + "settings.audit_time": "Fecha / hora", + "settings.audit_user": "Usuario", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Regla de acceso creada", + "audit.action.access_rule.deleted": "Regla de acceso eliminada", + "audit.action.access_rule.updated": "Regla de acceso actualizada", + "audit.action.auth.first_user_created": "Primer usuario creado", + "audit.action.auth.login": "Sesión iniciada", + "audit.action.auth.login_failed": "Error de inicio de sesión", + "audit.action.auth.logout": "Sesión cerrada", + "audit.action.backup.full_created": "Copia de seguridad completa creada", + "audit.action.backup.full_restored": "Copia de seguridad completa restaurada", + "audit.action.client.config_downloaded": "Configuración del cliente descargada", + "audit.action.client.config_viewed": "Configuración del cliente consultada", + "audit.action.client.created": "Cliente creado", + "audit.action.client.deleted": "Cliente eliminado", + "audit.action.client.qr_viewed": "Código QR del cliente consultado", + "audit.action.client.updated": "Cliente actualizado", + "audit.action.client_group.created": "Grupo de clientes creado", + "audit.action.client_group.deleted": "Grupo de clientes eliminado", + "audit.action.client_group.updated": "Grupo de clientes actualizado", + "audit.action.interface.created": "Interfaz creada", + "audit.action.interface.deleted": "Interfaz eliminada", + "audit.action.interface.renamed": "Interfaz renombrada", + "audit.action.route.created": "Ruta creada", + "audit.action.route.deleted": "Ruta eliminada", + "audit.action.route.updated": "Ruta actualizada", + "audit.action.server.created": "Servidor creado", + "audit.action.server.raw_config_applied": "Configuración sin procesar aplicada", + "audit.action.server.settings_applied": "Ajustes del servidor aplicados", + "audit.action.settings.updated": "Ajustes del panel actualizados", + "audit.action.telegram.action_denied": "Acción de Telegram denegada", + "audit.action.telegram.action_failed": "Error de acción de Telegram", + "audit.action.telegram.connection_test": "Prueba de conexión de Telegram", + "audit.action.telegram.settings_updated": "Ajustes de Telegram actualizados", + "audit.action.update.checked": "Actualización comprobada", + "audit.action.update.scheduled": "Actualización programada", + "audit.action.update.backup_created": "Copia previa a la actualización", + "audit.action.update.completed": "Actualización completada", + "audit.action.update.failed": "Error de actualización", + "audit.action.update.rollback_completed": "Versión anterior restaurada", + "audit.action.update.rollback_failed": "Error al revertir la actualización", + "audit.action.user.created": "Usuario creado", + "audit.action.user.deleted": "Usuario eliminado", + "audit.action.user.password_changed": "Contraseña de usuario cambiada", + "audit.action.vps.candidate_deleted": "Candidato VPS eliminado", + "audit.action.vps.candidate_saved": "Candidato VPS guardado", + "audit.action.vps.detached": "Relay VPS desconectado", + "audit.action.vps.relay_installed": "Relay VPS instalado", + "audit.action.wireguard.client_connected": "Cliente WireGuard conectado", + "audit.action.wireguard.installed": "WireGuard instalado", + "audit.action.wireguard.restarted": "WireGuard reiniciado", + "audit.action.wireguard.started": "WireGuard iniciado", + "audit.action.wireguard.stopped": "WireGuard detenido", + "audit.result.applied": "aplicado", + "audit.result.available": "disponible", + "audit.result.changed": "cambiado", + "audit.result.created": "creado", + "audit.result.current": "actual", + "audit.result.deleted": "eliminado", + "audit.result.detached": "desconectado", + "audit.result.denied": "denegado", + "audit.result.downloaded": "descargado", + "audit.result.endpoint": "Punto final", + "audit.result.error": "Error", + "audit.result.installed": "instalado", + "audit.result.invalid_credentials": "credenciales no válidas", + "audit.result.ok": "Correcto", + "audit.result.queued": "en cola", + "audit.result.restarted": "reiniciado", + "audit.result.restored": "restaurado", + "audit.result.rotated": "renovado", + "audit.result.saved": "guardado", + "audit.result.shown": "mostrado", + "audit.result.started": "iniciado", + "audit.result.stopped": "detenido", + "audit.result.updated": "actualizado", + "settings.delete_user": "Eliminar", + "settings.delete_user_confirm": "¿Eliminar al usuario {name}?", + "settings.edit_raw_config": "Editar configuración de interfaz", + "settings.expert_mode": "Experto", + "settings.full_backup_component_clients": "Metadatos de clientes gestionados, claves privadas, PSK, caducidad y grupos para regenerar configuraciones y QR.", + "settings.full_backup_component_db": "Base de datos WGTools: usuarios, preferencias, correo/SMTP, Telegram y estado guardado de VPS Relay.", + "settings.full_backup_component_relay": "Datos de recuperación VPS Relay: ID de controlador/tenant, token de administración y clave de transporte doméstico. Tras restaurar, WGTools puede reconstruir el transporte y reconectar el tenant conservado.", + "settings.full_backup_component_system": "Archivo sysctl IPv4 de WGTools, nombres visibles de interfaces y políticas/plantillas de grupos, si existen. Se excluye deliberadamente el historial automático por interfaz.", + "settings.full_backup_component_wg": "Todas las configuraciones WireGuard detectadas en /etc/wireguard/, incluido su estado activo/detenido.", + "settings.full_backup_create_failed": "No se pudo crear la copia completa", + "settings.full_backup_creating": "Creando copia completa…", + "settings.full_backup_download": "Crear", + "settings.full_backup_downloaded": "Copia creada y descargada. Guárdala de forma segura.", + "settings.full_backup_downloaded_short": "Copia completa descargada.", + "settings.full_backup_help": "Crea una copia portátil de WGTools para migración o recuperación: configuraciones WireGuard, usuarios, ajustes, grupos, clientes gestionados y datos para reconectar tenants VPS Relay.", + "settings.full_backup_no_file": "No se seleccionó ninguna copia", + "settings.full_backup_restore": "Restaurar", + "settings.full_backup_restore_confirm": "¿Restaurar esta copia completa de WGTools? Se restaurarán usuarios, ajustes, clientes gestionados y configuraciones WireGuard incluidos. Las interfaces pueden reiniciarse. WGTools crea una copia de seguridad previa y revierte automáticamente si falla.", + "settings.full_backup_restore_failed": "Error de restauración", + "settings.full_backup_restored": "Copia restaurada correctamente. Inicia sesión con una cuenta de esa copia.", + "settings.full_backup_restored_short": "Copia restaurada.", + "settings.full_backup_restoring": "Validando copia, creando respaldo de seguridad y restaurando…", + "settings.full_backup_secret_warning": "Este archivo contiene datos sensibles: claves privadas WireGuard y clientes, PSK, hashes de contraseñas WGTools, token de Telegram y contraseña SMTP guardada. Protégelo como una contraseña y nunca lo adjuntes a incidencias o chats públicos.", + "settings.full_backup_select": "Seleccionar", + "settings.full_backup_title": "Copia completa y restauración", + "settings.full_mode": "Gestión del servidor y clientes habilitada", + "settings.interface_help": "La interfaz WireGuard gestionada se elige al desplegar WGTools.", + "settings.language": "Idioma", + "settings.last_backup": "Última copia", + "settings.latest_version": "Última versión", + "settings.loading_config": "Cargando configuración…", + "settings.mode": "Modo", + "settings.never_logged_in": "Nunca", + "settings.new_password": "Nueva contraseña", + "settings.no_backups": "Aún no hay copias", + "settings.online_help": "Un par está en línea si el último handshake es más reciente que este valor. 30–3600 segundos.", + "settings.online_threshold": "Umbral de conexión", + "settings.open_release": "Abrir versión", + "settings.password_changed": "Contraseña cambiada.", + "settings.passwords_mismatch": "Las contraseñas no coinciden.", + "settings.project_github": "Proyecto / GitHub", + "settings.raw_config_confirm": "¿Guardar y aplicar la configuración WireGuard? Se reiniciará la interfaz seleccionada. Antes se creará una copia y WGTools revertirá automáticamente si el arranque falla.", + "settings.raw_config_help": "Abrir la configuración de origen de la interfaz WireGuard elegida.", + "settings.raw_config_title": "Configuración WireGuard sin procesar", + "settings.raw_config_warning": "Modo experto: esta es la configuración real del servidor WireGuard con clave privada y PSK de pares. Guardar y aplicar reinicia la interfaz. WGTools crea antes una copia y revierte si el arranque falla.", + "settings.readonly_mode": "Gestión de clientes habilitada", + "settings.refresh_help": "Frecuencia de actualización de datos de estado. De 2 a 60 segundos.", + "settings.refresh_interval": "Intervalo de actualización", + "settings.release_notes": "Notas de versión", + "settings.reload_config": "Recargar del disco", + "settings.save_apply": "Guardar y aplicar", + "settings.saved": "Ajustes guardados.", + "settings.saved_reload": "Ajustes guardados. Recargando…", + "settings.saving": "Guardando ajustes…", + "settings.status": "Actualización de estado", + "settings.status_help": "Frecuencia de actualización del panel y estado de los pares.", + "settings.subtitle": "Preferencias de interfaz y ajustes de estado de WGTools.", + "settings.syntax_hint": "Se resaltan secciones, claves, valores y comentarios WireGuard al editar.", + "settings.tab_about": "Acerca de", + "settings.tab_backups": "Copias", + "settings.tab_general": "General", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Usuarios", + "settings.tabs_aria": "Secciones de ajustes", + "settings.telegram": "Bot de Telegram", + "settings.telegram_allowed_ids": "ID de usuario de Telegram permitidos", + "settings.telegram_allowed_ids_help": "Un ID numérico por línea. Un /start no autorizado responde con el ID Telegram del remitente para añadirlo aquí.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Conectado", + "settings.telegram_disabled": "Desactivado", + "settings.telegram_dns": "DNS predeterminado del cliente", + "settings.telegram_dns_help": "Direcciones DNS IPv4 opcionales separadas por comas. Se usan en clientes creados por el bot.", + "settings.telegram_enabled": "Activar bot Telegram", + "settings.telegram_endpoint": "Dirección / dominio predeterminado del servidor", + "settings.telegram_endpoint_help": "Se usa cuando el bot crea un cliente. Introduce solo IP o dominio; el puerto WireGuard viene de la configuración del servidor.", + "settings.telegram_language": "Idioma del bot", + "settings.telegram_language_auto": "Auto (idioma de Telegram)", + "settings.telegram_last_poll": "Último contacto con Telegram", + "settings.telegram_not_configured": "Sin configurar", + "settings.telegram_remove_token": "Eliminar token", + "settings.telegram_remove_token_confirm": "¿Eliminar el token guardado de Telegram y deshabilitar el bot?", + "settings.telegram_save": "Guardar ajustes de Telegram", + "settings.telegram_saved": "Ajustes de Telegram guardados.", + "settings.telegram_setup_note": "Crea un bot con @BotFather, guarda su token, habilítalo y envía /start. Si tu ID no está autorizado, WGTools lo mostrará: añádelo a la lista permitida.", + "settings.telegram_status": "Estado del bot", + "settings.telegram_subtitle": "Gestión WireGuard desde Telegram: estado del servidor, clientes, creación/eliminación e inicio/reinicio/parada.", + "settings.telegram_test": "Probar conexión", + "settings.telegram_test_ok": "Conexión Telegram correcta: @{username}", + "settings.telegram_test_recent_ok": "El bot Telegram funciona. La prueba directa expiró, pero el bot contactó con Telegram recientemente.", + "settings.telegram_token": "Token del bot", + "settings.telegram_token_help": "Crea un bot con @BotFather y pega aquí el token Bot API. No se necesitan API ID ni API Hash.", + "settings.telegram_token_keep": "Deja en blanco para conservar el token guardado.", + "settings.telegram_waiting": "Configurado, esperando servicio del bot", + "settings.theme": "Tema", + "settings.theme_dark": "Oscuro", + "settings.theme_light": "Claro", + "settings.theme_system": "Sistema", + "settings.title": "Configuración", + "settings.update_available": "Actualización disponible", + "settings.update_backup_queued": "Actualización en cola. WGTools creará una copia completa automática antes de instalar…", + "settings.update_backup_running": "Creando copia completa antes de actualizar…", + "settings.update_check_failed": "No se pudieron comprobar las actualizaciones", + "settings.update_checking": "Comprobando el último lanzamiento publicado en GitHub…", + "settings.update_confirm": "¿Actualizar WGTools de v{current} a v{latest}? Se crearán una copia completa y otra para revertir. La interfaz web se reiniciará brevemente.", + "settings.update_current": "Actualizado", + "settings.update_downloading": "Descargando y validando la versión de GitHub…", + "settings.update_failed": "La actualización de WGTools falló.", + "settings.update_installing": "Instalando actualización. La interfaz web puede no estar disponible por un momento…", + "settings.update_no_update": "WGTools ya está actualizado.", + "settings.update_not_checked": "Sin comprobar", + "settings.update_queued": "Actualización en cola. Esperando al servicio actualizador…", + "settings.update_rollback_ok": "Se restauró automáticamente la versión anterior de WGTools.", + "settings.update_rolling_back": "Falló la actualización. Restaurando la versión anterior…", + "settings.update_running": "Creando copias de seguridad…", + "settings.update_safety_hint": "Las actualizaciones son opcionales. WGTools crea una copia completa y una para revertir. Si falla, restaura automáticamente la aplicación anterior. WireGuard no se reinicia salvo que la nueva versión modifique expresamente su configuración.", + "settings.update_sidebar": "Nueva versión disponible", + "settings.update_sidebar_hint": "Ajustes → Acerca de", + "settings.update_starting": "Iniciando actualización…", + "settings.update_status_unknown": "Estado de actualización no disponible. Reintentando…", + "settings.update_subtitle": "Información del proyecto, comprobación automática de versiones y actualizaciones seguras desde GitHub Releases.", + "settings.update_success": "WGTools actualizado a v{version}. Recargando…", + "settings.update_wgtools": "Actualizar WGTools", + "settings.user_actions": "Acciones", + "settings.user_created": "Creado", + "settings.user_created_ok": "Usuario creado.", + "settings.user_deleted": "Usuario eliminado.", + "settings.user_equal_rights": "Todos los usuarios WGTools tienen los mismos permisos.", + "settings.user_last_login": "Último inicio de sesión", + "settings.user_name": "Nombre de usuario", + "settings.users": "Usuarios", + "settings.users_subtitle": "Cuentas locales WGTools. El correo es opcional y solo se usa para recuperar la contraseña cuando está habilitado.", + "vps.add": "Añadir VPS", + "vps.add_help": "WGTools usa SSH para comprobar o instalar Relay. Nunca guarda contraseñas ni claves SSH privadas.", + "vps.add_title": "Añadir VPS", + "vps.agent": "Agente Relay", + "vps.agent_found": "Ya instalado", + "vps.agent_will_install": "Se instalará", + "vps.arch": "Arquitectura", + "vps.auth_method": "Autenticación", + "vps.authentication": "Autenticación SSH", + "vps.check": "Comprobar VPS", + "vps.check_failed": "Error al comprobar el VPS", + "vps.check_link": "Comprobar enlace", + "vps.check_ok": "VPS compatible", + "vps.checking": "Comprobando acceso SSH y compatibilidad VPS…", + "vps.connections": "conexiones", + "vps.credentials_not_saved": "Solo se usan para esta comprobación; WGTools no los guarda.", + "vps.delete_candidate": "Quitar", + "vps.delete_installed": "Eliminar VPS", + "vps.delete_installed_confirm": "¿Quitar «{name}» de WGTools? Se desconectará el transporte Relay local, pero se conservarán el agente y el tenant del VPS. Puedes añadirlo otra vez y WGTools reutilizará el Relay existente. Los clientes no podrán usarlo hasta reconectarlo.", + "vps.delete_installed_failed": "No se pudo eliminar el VPS de WGTools", + "vps.delete_installed_ok": "VPS eliminado de WGTools. El Relay remoto se conserva y puede reconectarse.", + "vps.empty_help": "Añade un VPS Debian o Ubuntu para comprobar SSH, compatibilidad del sistema y puertos UDP necesarios.", + "vps.empty_title": "Ningún VPS configurado", + "vps.endpoint": "Endpoint público", + "vps.endpoint_domain": "Dominio (recomendado)", + "vps.endpoint_domain_hint": "Si reemplazas el VPS principal, cambiar DNS puede mantener intactas las configuraciones del cliente.", + "vps.health_failed": "Error al comprobar el enlace Relay", + "vps.host": "IP / nombre de host", + "vps.host_key": "Clave de host SSH", + "vps.identity": "Conexión VPS", + "vps.install_failed": "Error al instalar Relay", + "vps.install_ok": "Relay instalado y enlace de administración protegido verificado", + "vps.install_relay": "Instalar Relay", + "vps.install_title": "Instalar Relay VPS", + "vps.installed": "Instalado", + "vps.installing": "Instalando agente Relay y estableciendo túnel protegido…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Frase de acceso de la clave", + "vps.link_ok": "Enlace Relay correcto", + "vps.multi_tenant_note": "Ya funciona un agente Relay WGTools en este VPS. No se reemplazará: este WGTools tendrá una conexión aislada con claves y puertos UDP propios.", + "vps.name": "Nombre", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Se instalará", + "vps.os": "Sistema operativo", + "vps.password": "Contraseña", + "vps.phase_note": "El agente Relay admite varios controladores WGTools independientes en un VPS. Cada uno tiene conexión, claves y puertos UDP aislados; los existentes no se modifican.", + "vps.port_pair": "Puertos UDP", + "vps.ports_adjusted": "puertos libres seleccionados", + "vps.private_key": "Clave privada", + "vps.privilege": "Privilegios", + "vps.public_endpoint": "Futuro endpoint público", + "vps.ready_help": "Las credenciales SSH solo se usan para comprobar compatibilidad e instalar Relay inmediatamente; no se guardan.", + "vps.reconnect_note": "Se encontró una conexión Relay creada antes por este WGTools. Se reutilizará el mismo tenant sin crear nuevos ni puertos UDP.", + "vps.reconnect_ok": "Relay existente reconectado correctamente", + "vps.reconnect_relay": "Reconectar Relay", + "vps.relay_port": "Puerto UDP Relay", + "vps.remove_confirm": "¿Quitar este candidato VPS? No se han hecho cambios remotos.", + "vps.save_candidate": "Guardar candidato", + "vps.saved": "Candidato VPS guardado", + "vps.ssh": "SSH", + "vps.ssh_key": "Clave SSH", + "vps.ssh_port": "Puerto SSH", + "vps.ssh_user": "Usuario SSH", + "vps.status_candidate": "Listo para instalar", + "vps.status_installed": "Relay conectado", + "vps.subtitle": "Prepara un VPS público para acceso remoto cuando este servidor WGTools no tiene IP pública.", + "vps.tenant": "Conexión", + "vps.title": "Relay VPS", + "vps.transport_port": "Puerto UDP de transporte", + "vps.transport_port_hint": "Puerto UDP separado para el túnel de transporte privado Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Guardado", + "vps.active_short": "Activo", + "dashboard.traffic_reset": "Restablecer", + "dashboard.traffic_reset_confirm": "¿Restablecer los contadores de tráfico WireGuard de esta interfaz? Los contadores de clientes también volverán a cero.", + "dashboard.traffic_reset_done": "Contadores de tráfico restablecidos", + "dashboard.traffic_reset_failed": "No se pudieron restablecer los contadores", + "audit.action.traffic.reset": "Contadores de tráfico restablecidos", + "audit.result.reset": "restablecido", + "server.mtu": "MTU", + "server.mtu_auto": "Automático", + "server.mtu_hint": "Opcional. Déjalo vacío para MTU automática de wg-quick. Usa 1380 o 1420 solo si es necesario por LTE o PPPoE.", + "clients.peer_isolation": "Aislamiento de clientes VPN", + "clients.peer_isolation_enable": "Aislar de otros clientes VPN", + "clients.peer_isolation_hint": "Bloquea el tráfico entre este cliente y otras direcciones del grupo WireGuard. El acceso al servidor, Internet y redes locales o Site-to-site sigue controlado por otras políticas.", + "clients.credentials_rotate": "Claves del cliente", + "clients.credentials_rotate_button": "Renovar claves", + "clients.credentials_rotate_confirm": "¿Generar claves nuevas para este cliente? Si está conectado, su sesión WireGuard se desconectará inmediatamente. Envía después nueva configuración o QR.", + "clients.credentials_rotate_confirm_psk": "¿Generar un nuevo par de claves y un PSK para este cliente? Su sesión WireGuard activa se cortará inmediatamente. Envía después nueva configuración o QR.", + "clients.credentials_rotate_hint": "Renueva PrivateKey/PublicKey y el PSK si está habilitado. Conserva dirección, rutas, grupo, horario, aislamiento y estadísticas.", + "clients.credentials_rotating": "Generando claves nuevas y cerrando la sesión anterior…", + "clients.credentials_rotated": "Claves del cliente cambiadas. Si estaba conectado, su sesión anterior se cortó. La configuración antigua ya no funciona; envía una nueva o QR.", + "clients.credentials_rotated_short": "Claves cambiadas — se requiere nueva configuración", + "audit.action.client.credentials_rotated": "Claves del cliente renovadas", + "clients.credentials_connection_lost": "Se perdió la conexión a WGTools. Si el panel se abrió a través del cliente cuyas claves se renovaron, es normal: su sesión antigua se cerró. Vuelve a entrar por otra vía y genera nueva configuración o QR.", + "nav.navigation": "Navegación principal", + "nav.project_github": "WGTools en GitHub", + "auth.email": "Correo electrónico", + "auth.email_optional_help": "Opcional por ahora. Permite recuperar la contraseña después de configurar el correo.", + "auth.forgot_password": "¿Olvidaste la contraseña?", + "auth.reset_title": "Restablecer contraseña", + "auth.reset_subtitle": "Recibe un código de un solo uso por correo y establece una nueva contraseña de WGTools.", + "auth.reset_identifier": "Usuario o correo", + "auth.reset_identifier_help": "Por privacidad, WGTools siempre muestra la misma respuesta tanto si la cuenta existe como si no.", + "auth.send_reset_code": "Enviar código", + "auth.reset_code_sent_generic": "Si la cuenta existe y tiene correo, se envió un código. Es válido durante 15 minutos.", + "auth.reset_code": "Código de 6 dígitos", + "auth.set_new_password": "Establecer nueva contraseña", + "auth.request_another_code": "Solicitar otro código", + "auth.back_to_login": "Volver al inicio de sesión", + "auth.reset_not_configured": "La recuperación de contraseña por correo no está configurada. Contacta con el administrador de WGTools.", + "settings.tab_mail": "Correo", + "settings.mail": "Correo / SMTP", + "settings.mail_subtitle": "SMTP se usa para recuperar contraseñas.", + "settings.mail_not_configured": "Sin configurar", + "settings.mail_enabled": "Habilitar correo y recuperación de contraseña", + "settings.mail_smtp_host": "Servidor SMTP", + "settings.mail_smtp_port": "Puerto SMTP", + "settings.mail_security": "Cifrado", + "settings.mail_security_none": "Sin cifrado", + "settings.mail_username": "Usuario SMTP", + "settings.mail_username_help": "Se usa para autenticación SMTP y como correo remitente.", + "settings.mail_password": "Contraseña SMTP", + "settings.mail_password_keep": "Deja vacío para conservar la contraseña guardada.", + "settings.mail_from_email": "Correo del remitente", + "settings.mail_from_name": "Nombre del remitente", + "settings.mail_test_recipient": "Destinatario de prueba", + "settings.mail_test_recipient_help": "La prueba utiliza los ajustes SMTP guardados actualmente.", + "settings.mail_remove_password": "Eliminar contraseña", + "settings.mail_test": "Enviar prueba", + "settings.mail_save": "Guardar ajustes de correo", + "settings.mail_enabled_badge": "Activado", + "settings.mail_disabled_badge": "Desactivado", + "settings.mail_saved": "Ajustes de correo guardados.", + "settings.mail_remove_password_confirm": "¿Eliminar la contraseña SMTP guardada y deshabilitar el correo?", + "settings.mail_password_removed": "Contraseña SMTP eliminada y correo deshabilitado.", + "settings.mail_test_recipient_required": "Introduce la dirección de correo del destinatario de prueba.", + "settings.mail_testing": "Enviando correo de prueba…", + "settings.mail_test_ok": "Correo de prueba enviado correctamente.", + "settings.user_email": "Correo electrónico", + "settings.user_email_help": "Opcional. Solo necesario para recuperar la contraseña por cuenta propia.", + "settings.change_email": "Correo electrónico", + "settings.user_email_saved": "Correo guardado.", + "settings.send_password_reset": "Enviar restablecimiento", + "settings.user_reset_mail_not_configured": "Configura y habilita primero el correo.", + "settings.user_reset_email_missing": "Añade primero una dirección de correo.", + "settings.user_reset_confirm": "¿Enviar código de restablecimiento a {name} en {email}?", + "settings.user_reset_sent": "Código de restablecimiento enviado a {email}.", + "audit.action.auth.password_reset_requested": "Restablecimiento de contraseña solicitado", + "audit.action.auth.password_reset_code_sent": "Código de restablecimiento enviado", + "audit.action.auth.password_reset_completed": "Contraseña restablecida", + "audit.action.auth.password_reset_failed": "Error al restablecer la contraseña", + "audit.action.mail.settings_updated": "Configuración de correo actualizada", + "audit.action.mail.test_sent": "Correo de prueba enviado", + "audit.action.mail.test_failed": "Error en el correo de prueba", + "audit.action.user.email_changed": "Correo del usuario cambiado", + "audit.action.user.password_reset_sent": "Restablecimiento enviado al usuario", + "audit.action.user.password_reset_failed": "Error al restablecer la contraseña del usuario", + "audit.result.accepted": "aceptado", + "audit.result.sent": "enviado", + "audit.result.invalid_code": "código no válido", + "common.copy": "Copiar", + "common.copied": "Copiado", + "clients.use_panel_host": "Usar dirección del panel", + "clients.use_panel_host_done": "Dirección del panel insertada: {host}", + "clients.use_panel_host_failed": "No se pudo obtener la dirección del panel de la URL del navegador.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS de Let’s Encrypt integrado para acceso directo a WGTools sin proxy inverso.", + "settings.https_disabled": "Desactivado", + "settings.https_enabled": "Activado", + "settings.https_enable": "Habilitar HTTPS integrado", + "settings.https_type": "Certificado para", + "settings.https_domain": "Dominio", + "settings.https_public_ip": "IP pública", + "settings.https_target": "Dominio o IP pública", + "settings.https_email": "Correo de Let’s Encrypt", + "settings.https_port": "Puerto HTTPS", + "settings.https_port80_note": "El puerto TCP 80 debe ser accesible desde Internet para emitir y renovar el certificado. Abre también el puerto HTTPS elegido para el panel.", + "settings.https_check_ports": "Comprobar puertos", + "settings.https_certificate": "Certificado", + "settings.https_certificate_ready": "Listo", + "settings.https_certificate_missing": "No emitido", + "settings.https_expires": "Válido hasta", + "settings.https_renewal": "Renovación automática", + "settings.https_renewal_enabled": "Activado", + "settings.https_renewal_disabled": "Desactivado", + "settings.https_certificate_path": "Certificado", + "settings.https_private_key_path": "Clave privada", + "settings.https_issue": "Obtener / renovar certificado", + "settings.https_port_free": "Libre", + "settings.https_port_busy": "Ocupado", + "settings.https_ports_checked": "Comprobación de puertos terminada.", + "settings.https_target_email_required": "Introduce dominio/IP pública y correo de Let’s Encrypt.", + "settings.https_issue_confirm": "¿Solicitar o renovar el certificado Let’s Encrypt para {target}? Se guardarán los ajustes HTTPS. El puerto TCP 80 debe ser accesible desde Internet.", + "settings.https_issuing": "Solicitando certificado a Let’s Encrypt…", + "settings.https_issue_ok": "Certificado listo.", + "settings.https_already_enabled": "HTTPS integrado ya está habilitado.", + "settings.https_already_disabled": "HTTPS integrado ya está deshabilitado.", + "settings.https_enable_confirm": "¿Habilitar HTTPS integrado en TCP {port} con ruta {path}? WGTools se reiniciará y la página volverá a conectarse a la nueva dirección.", + "settings.https_disable_confirm": "¿Deshabilitar HTTPS integrado y volver a HTTP?", + "settings.https_switching": "Habilitando HTTPS y reiniciando WGTools…", + "settings.https_switching_http": "Deshabilitando HTTPS y reiniciando WGTools…", + "audit.action.https.certificate_issued": "Certificado HTTPS emitido", + "audit.action.https.certificate_failed": "Error al solicitar el certificado HTTPS", + "audit.action.https.enabled": "HTTPS habilitado", + "audit.action.https.disabled": "HTTPS deshabilitado", + "audit.result.issued": "emitido", + "audit.result.enabled": "habilitado", + "audit.result.disabled": "deshabilitado", + "settings.https_access_path": "Ruta de acceso al panel", + "settings.https_access_path_help": "Elige tu propia ruta. Con HTTPS integrado, las solicitudes fuera de ella reciben 404.", + "settings.https_enable_fields_required": "Introduce dominio/IP pública, correo Let’s Encrypt y ruta del panel.", + "settings.https_use_panel_host": "Usar dirección del panel", + "settings.https_reconnecting": "WGTools cambiando a la nueva dirección HTTPS…", + "server.tab_nodes": "Nodos", + "common.type": "Tipo", + "common.status": "Estado", + "common.copy_failed": "No se pudo copiar", + "clients.vpn_address": "Dirección VPN", + "nodes.title": "Nodos WGTools", + "nodes.subtitle": "Conecta varios servidores WGTools en una red protegida y publica solo las redes accesibles a otros nodos.", + "nodes.enable_hub": "Habilitar HUB", + "nodes.connect_hub": "Conectar al HUB", + "nodes.settings": "Ajustes del nodo", + "nodes.settings_action": "Configuración", + "nodes.sync_now": "Sincronizar", + "nodes.disable": "Deshabilitar nodos", + "nodes.disable_action": "Desconectar", + "nodes.join_title": "Conectar nuevos nodos", + "nodes.join_help": "Crea un código de un solo uso e introdúcelo en otro panel WGTools junto con el endpoint del HUB, p. ej. vpn.example.com:51950. Dura 15 minutos y solo se usa una vez.", + "nodes.create_code": "Crear código", + "nodes.connected_nodes": "Nodos conectados", + "nodes.connected_nodes_help": "Información de otros paneles, redes publicadas y clientes. Los clientes remotos son de solo lectura.", + "nodes.enable_hub_help": "Este panel será el nodo central. El mismo puerto acepta WireGuard por UDP y el emparejamiento inicial protegido por TCP.", + "nodes.node_name": "Nombre del nodo", + "nodes.transport_network": "Red de transporte de nodos", + "nodes.transport_help": "Red privada separada solo para el transporte entre WGTools. No debe solaparse con las redes VPN/LAN.", + "nodes.panel_url": "URL del panel", + "nodes.panel_url_help": "Opcional. Solo es un enlace informativo del botón «Abrir panel» en otros nodos; no se usa para conectar nodos.", + "nodes.extra_networks": "Redes de nodo adicionales", + "nodes.extra_networks_help": "Una red por línea. Las redes VPN y las redes remotas Site-to-site se publican automáticamente. Añade solo otras LAN/redes enrutadas, p. ej. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools rellena redes VPN, Site-to-site y LAN enrutadas detectadas. Deja solo las redes que este nodo debe publicar. Una por línea.", + "nodes.published_networks_settings_help": "Una red por línea. Lista explícita de redes publicadas por este nodo. Quitar una línea deja de anunciar esa red a otros nodos.", + "nodes.available_networks_help": "Redes detectadas: {networks}. Las redes nuevas no se publican automáticamente; añade arriba las que quieras.", + "nodes.available_networks_none": "No se detectaron redes locales adicionales.", + "nodes.connect_help": "Introduce endpoint del HUB y código de un uso. La URL, el puerto HTTPS, certificado y ruta privada del panel no se usan para emparejar.", + "nodes.join_code": "Código de conexión", + "nodes.connect_reachability_note": "El emparejamiento inicial usa TCP protegido en el puerto indicado. Tras crear wgnode0, las redes, estados, versiones y datos de clientes de solo lectura se sincronizan con HUB por WireGuard interno.", + "nodes.connect": "Conectar", + "nodes.settings_help": "Nombre del nodo, enlace opcional «Abrir panel» y lista de redes publicadas. La URL del panel no se usa para emparejamiento ni sincronización.", + "nodes.details": "Detalles", + "nodes.not_configured": "WGTools Nodes sin configurar", + "nodes.not_configured_help": "Habilita HUB en este panel o conéctalo a un HUB WGTools existente.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Conectado al HUB", + "nodes.mode_none": "Sin configurar", + "nodes.role": "Rol", + "nodes.tunnel": "Túnel del nodo", + "nodes.node_ip": "Dirección del nodo", + "nodes.endpoint": "Endpoint de HUB", + "nodes.published_networks": "Redes publicadas", + "nodes.last_sync": "Última sincronización", + "nodes.no_nodes_hub": "Aún no hay nodos conectados. Crea un código y úsalo en otro panel WGTools.", + "nodes.no_nodes_spoke": "Aún no se recibió información de nodos remotos.", + "nodes.clients_short": "Clientes", + "nodes.open_panel": "Abrir panel", + "nodes.route_conflict": "Conflicto de rutas", + "nodes.no_published_networks": "Sin redes publicadas", + "nodes.load_failed": "No se pudo cargar WGTools Nodes", + "nodes.enable_hub_confirm": "¿Habilitar HUB de WGTools y crear el túnel WireGuard interno?", + "nodes.applying": "Configurando túnel WGTools Nodes…", + "nodes.enable_failed": "No se pudo habilitar HUB", + "nodes.hub_enabled": "HUB de WGTools habilitado", + "nodes.connecting": "Verificando código HUB y creando túnel protegido…", + "nodes.connect_failed": "No se pudo conectar al HUB", + "nodes.connected": "Conectado al HUB WGTools", + "nodes.settings_failed": "No se pudieron guardar los ajustes del nodo", + "nodes.settings_saved": "Ajustes del nodo guardados", + "nodes.code_failed": "No se pudo crear código de conexión", + "nodes.code_expires": "Código de un solo uso. Válido hasta {time}.", + "nodes.code_copied": "Código de conexión copiado", + "nodes.network_vpn": "Clientes VPN", + "nodes.network_site_to_site": "Red Site-to-site", + "nodes.network_custom": "Red adicional", + "nodes.conflict": "Conflicto", + "nodes.remote_clients": "Clientes (solo lectura)", + "nodes.no_clients": "Este nodo no informa de clientes", + "nodes.details_failed": "No se pudieron cargar los detalles del nodo", + "nodes.remove_confirm": "¿Quitar el nodo «{name}» del HUB? Se revocará su acceso al túnel interno.", + "nodes.remove_failed": "No se pudo quitar el nodo", + "nodes.removed": "Nodo eliminado", + "nodes.disable_hub_confirm": "¿Deshabilitar HUB y desconectar todos los nodos WGTools? Se eliminará el túnel interno.", + "nodes.disconnect_confirm": "¿Desconectar este panel WGTools del HUB y eliminar su túnel interno?", + "nodes.disable_failed": "No se pudieron deshabilitar los nodos WGTools", + "nodes.disabled": "Nodos WGTools deshabilitados", + "nodes.sync_failed": "Error de sincronización de nodos", + "nodes.synced": "Información de nodos sincronizada", + "nodes.service_port": "Puerto Nodes", + "nodes.service_port_help": "Se usa el mismo número de puerto: UDP para WireGuard y TCP para emparejamiento inicial protegido.", + "nodes.hub_port_forward_note": "Si HUB está tras NAT, redirige el mismo puerto para UDP y TCP. El puerto web WGTools, HTTPS y la ruta privada no están relacionados con Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Dominio/IP y puerto de Nodes sin http:// ni https://, p. ej. vpn.example.com:51950.", + "settings.collapse_sidebar": "Contraer barra lateral", + "settings.expand_sidebar": "Expandir barra lateral", + "settings.https_issue_fields_required": "Introduce dominio/IP pública, correo Let’s Encrypt y ruta del panel.", + "settings.https_issue_ok_saved": "Certificado listo y ajustes HTTPS guardados.", + "settings.https_enable_need_certificate": "Primero obtén un certificado.", + "settings.https_enable_certificate_mismatch": "Primero obtén un certificado para el dominio o IP actual.", + "settings.https_enable_certificate_expired": "El certificado caducó. Renuévalo antes de habilitar HTTPS.", + "settings.https_enable_certificate_ready": "Certificado listo: ya puedes habilitar HTTPS integrado.", + "settings.https_enable_active_help": "Desmarca y guarda para volver a HTTP.", + "settings.https_certificate_expired": "Caducado", + "settings.https_certificate_wrong_target": "Para otra dirección", + "nodes.network_conflict_error": "Las redes publicadas entran en conflicto con otro nodo o red de transporte Nodes: {conflicts}. Elimina o cambia la red conflictiva.", + "nodes.networks_changed": "Las redes detectadas cambiaron desde el último guardado. Nuevas: {added}. Ya no detectadas: {removed}. Revisa y guarda las redes publicadas.", + "nodes.review_networks": "Revisar redes", + "nodes.vpn_pool_mismatch": "El grupo VPN cambió: Nodes sigue publicando {old}, pero el grupo actual es {current}. Abre los ajustes y actualiza las redes publicadas.", + "server.error_vpn_network_invalid": "La red VPN debe ser una red IPv4 válida, p. ej. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Solo se admiten redes VPN IPv4.", + "server.error_vpn_network_too_small": "La red VPN debe tener al menos dos direcciones utilizables.", + "server.error_vpn_network_no_hosts": "La red VPN elegida no tiene direcciones de servidor utilizables.", + "server.error_server_address_prefix": "La dirección VPN del servidor debe incluir prefijo, p. ej. 10.0.0.1/24.", + "server.error_server_address_network": "La dirección VPN del servidor debe pertenecer al grupo elegido y usar el mismo prefijo.", + "server.error_server_address_reserved": "La dirección VPN del servidor no puede ser la de red ni la de difusión.", + "server.error_listen_port_number": "El puerto WireGuard debe ser un número.", + "server.error_listen_port_range": "El puerto WireGuard debe estar entre 1 y 65535.", + "server.error_mtu_number": "MTU debe ser un número.", + "auth.mfa_title": "Autenticación de dos factores", + "auth.mfa_login_help": "Introduce el código de 6 dígitos de Google Authenticator o un código de recuperación.", + "auth.mfa_code": "Código de autenticación", + "auth.mfa_verify": "Verificar e iniciar sesión", + "auth.mfa_back": "Volver a la contraseña", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Autenticación de dos factores (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Activado", + "settings.mfa_disabled": "Desactivado", + "settings.mfa_google_help": "Protege esta cuenta con Google Authenticator u otra app TOTP. Para comenzar se requiere tu contraseña actual.", + "settings.current_password": "Contraseña actual", + "settings.mfa_start": "Configurar Google Authenticator", + "settings.mfa_secret": "Clave de configuración manual", + "settings.mfa_scan_help": "Escanea el QR con Google Authenticator y escribe el código actual de 6 dígitos para habilitar MFA.", + "settings.mfa_code": "Código de 6 dígitos", + "settings.mfa_enable": "Habilitar MFA", + "settings.mfa_manage_help": "Para cambiar MFA, introduce la contraseña actual y un código de Authenticator o recuperación.", + "settings.mfa_code_or_recovery": "Código de Authenticator o recuperación", + "settings.mfa_regenerate": "Nuevos códigos de recuperación", + "settings.mfa_disable": "Deshabilitar MFA", + "settings.mfa_recovery_title": "Códigos de recuperación", + "settings.mfa_recovery_help": "Guarda estos códigos ahora. Cada uno se usa una vez si Google Authenticator no está disponible. No se mostrarán otra vez.", + "settings.mfa_recovery_remaining": "Códigos de recuperación restantes: {count}", + "settings.mfa_enabled_ok": "MFA habilitada.", + "settings.mfa_disabled_ok": "MFA deshabilitada.", + "settings.mfa_disable_confirm": "¿Deshabilitar la autenticación de dos factores para esta cuenta?", + "settings.mfa_regenerate_confirm": "¿Reemplazar todos los códigos de recuperación existentes?", + "settings.mfa_recovery_regenerated": "Nuevos códigos de recuperación creados.", + "audit.action.auth.mfa_failed": "Error de verificación MFA", + "audit.action.auth.mfa_recovery_used": "Código de recuperación MFA utilizado", + "audit.action.user.mfa_setup_started": "Configuración de MFA iniciada", + "audit.action.user.mfa_enabled": "MFA habilitada", + "audit.action.user.mfa_disabled": "MFA deshabilitada", + "audit.action.user.mfa_disabled_cli": "MFA deshabilitada por CLI", + "audit.action.user.mfa_recovery_regenerated": "Códigos de recuperación MFA regenerados", + "settings.mfa_error_password": "Contraseña actual incorrecta.", + "settings.mfa_error_code": "Código de autenticación no válido.", + "settings.mfa_error_already_enabled": "MFA ya está habilitada.", + "settings.mfa_error_not_enabled": "MFA no está habilitada.", + "settings.mfa_error_not_started": "Vuelve a iniciar la configuración MFA.", + "trace.title": "Traceroute, ping y mapa de ruta", + "trace.subtitle": "Mide la latencia hacia un VPS u otro servidor y detecta retrasos en la ruta.", + "trace.target": "IP o nombre de host del servidor", + "trace.show_map": "Mostrar ruta en el mapa", + "trace.run": "Iniciar traceroute", + "trace.geo_note": "La geolocalización es aproximada. Con el mapa activado, las IP públicas de los saltos se envían a ipwho.is; los mapas se cargan desde OpenStreetMap.", + "trace.latency_note": "Traceroute mide la latencia en milisegundos, no el rendimiento en Mbit/s.", + "trace.map": "Mapa de ruta", + "trace.map_hint": "Mapa interactivo: arrastra para mover, usa la rueda o +/− para ampliar y pulsa un salto para ver detalles.", + "trace.hop": "Salto / IP", + "trace.location": "Ubicación", + "trace.avg_rtt": "RTT medio", + "trace.delta": "Δ RTT", + "trace.loss": "Pérdida", + "trace.summary_target": "Destino", + "trace.summary_ping": "Ping medio", + "trace.summary_loss": "Pérdida de ping", + "trace.summary_hops": "Saltos", + "trace.no_reply": "Sin respuesta", + "trace.private": "Red privada", + "trace.unknown": "Desconocido", + "trace.running": "Ejecutando ping y traceroute… Puede tardar hasta un minuto.", + "trace.done": "Traza de red completada.", + "trace.failed": "Error de traza de red", + "trace.partial_geo": "No se pudieron geolocalizar algunos saltos públicos.", + "trace.not_reached": "Traceroute no alcanzó el destino.", + "trace.reached": "Destino alcanzado", + "trace.ms": "ms", + "server.tab_trace": "Rastreo", + "trace.map_controls": "Controles del mapa", + "trace.zoom_in": "Acercar", + "trace.zoom_out": "Alejar", + "trace.fit_route": "Ajustar a la ruta", + "trace.fit": "Ajustar", + "trace.map_click_hint": "Pulsa un salto para ver IP, ubicación, ASN y RTT.", + "trace.route_path": "Ruta", + "trace.ping_ok_trace_filtered": "El destino responde a ping, pero los últimos saltos del traceroute no responden.", + "trace.latency_legend": "Aumento de latencia entre saltos que responden", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — elevado", + "trace.latency_bad": "Δ RTT > 20 ms — salto brusco" +} diff --git a/app/static/locales/fr.json b/app/static/locales/fr.json new file mode 100644 index 0000000..2c3844e --- /dev/null +++ b/app/static/locales/fr.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Créer un utilisateur", + "auth.login_subtitle": "Saisissez votre nom d’utilisateur et votre mot de passe WGTools.", + "auth.login_title": "Se connecter à WGTools", + "auth.password": "Mot de passe", + "auth.password_repeat": "Répéter le mot de passe", + "auth.setup_help": "Le premier compte dispose d’un accès complet à WGTools. D’autres utilisateurs peuvent être créés plus tard dans les paramètres.", + "auth.setup_subtitle": "Un compte WGTools est requis avant de pouvoir gérer le serveur.", + "auth.setup_title": "Créer le premier utilisateur", + "auth.sign_in": "Se connecter", + "auth.sign_out": "Se déconnecter", + "auth.username": "Nom d’utilisateur", + "clients.actions": "Actions", + "clients.add": "+ Ajouter un client", + "clients.address": "Adresse VPN", + "clients.address_hint": "La première adresse disponible est proposée automatiquement.", + "clients.allowed_ips_required": "Saisissez au moins un réseau AllowedIPs pour la configuration client.", + "clients.basic_connection": "Paramètres de connexion", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs de la configuration client", + "clients.config_private_warning": "Cette configuration contient la clé privée du client. Conservez-la en lieu sûr.", + "clients.config_title": "Configuration client", + "clients.config_unavailable": "Configuration indisponible", + "clients.connection_direct": "Directement vers WGTools", + "clients.connection_path": "Chemin de connexion", + "clients.connection_relay": "Relais VPS", + "clients.connection_via": "Se connecter via", + "clients.connection_via_hint": "Choisissez le point d’entrée public du client. Le relais n’apparaît que s’il est installé pour l’interface WireGuard sélectionnée.", + "clients.copy_config": "Copier", + "clients.copy_done": "Configuration copiée", + "clients.create_subtitle": "Créer un pair WireGuard et générer sa configuration client.", + "clients.create_title": "Créer un client", + "clients.creating": "Création des clés et application du client…", + "clients.day_fri": "Ven", + "clients.day_mon": "Lun", + "clients.day_sat": "Sam", + "clients.day_sun": "Dim", + "clients.day_thu": "Jeu", + "clients.day_tue": "Mar", + "clients.day_wed": "Mer", + "clients.delete_confirm": "Supprimer ce client de WireGuard ? WGTools créera une sauvegarde et supprimera les règles automatiques associées.", + "clients.deleted": "Client supprimé", + "clients.dns": "DNS (facultatif)", + "clients.dns_hint": "Serveurs DNS IPv4 séparés par des virgules.", + "clients.download_config": "Télécharger .conf", + "clients.duplicate": "Dupliquer", + "clients.duplicate_address_error": "Cette adresse VPN est déjà utilisée par un autre pair.", + "clients.duplicate_name_error": "Un pair portant ce nom existe déjà.", + "clients.duplicate_ready": "Copie prête. WGTools a attribué un nouveau nom et une adresse VPN. Vérifiez les paramètres avant d’enregistrer.", + "clients.duplicate_site_hint": "Les réseaux distants ont été effacés pour éviter les routes en double. Indiquez les réseaux du nouveau pair Site-to-site.", + "clients.duplicate_suffix": "copie", + "clients.edit_subtitle": "Modifier le pair côté serveur. Les changements sont appliqués sans redémarrer WireGuard.", + "clients.edit_title": "Modifier le client", + "clients.endpoint": "Endpoint du serveur", + "clients.endpoint_hint": "Pour les clients distants, utilisez l’IP publique ou le domaine qui redirige le port WireGuard vers ce serveur.", + "clients.existing": "Pair existant", + "clients.expiration": "Durée de validité", + "clients.expiration_action": "À expiration", + "clients.expiration_action_hint": "Si cette option est décochée, le client reste dans WGTools mais son accès WireGuard est désactivé. Choisissez une nouvelle durée ou aucune expiration et enregistrez pour rétablir l’accès.", + "clients.expiration_datetime": "Expire le", + "clients.expiration_datetime_hint": "Utilise la date et l’heure locales du navigateur.", + "clients.expiration_delete": "Supprimer le client", + "clients.expiration_future_required": "Choisissez une date et une heure futures.", + "clients.expiration_hint": "À expiration, WGTools exécute l’action choisie au début de la minute suivante. Une sauvegarde WireGuard est créée avant.", + "clients.expire_1d": "1 jour", + "clients.expire_1h": "1 heure", + "clients.expire_3h": "3 heures", + "clients.expire_6h": "6 heures", + "clients.expire_custom": "Date et heure personnalisées", + "clients.expire_never": "Aucune expiration", + "clients.expired": "Expiré", + "clients.expired_disabled_hint": "L’accès a expiré. Le client est conservé mais WireGuard est désactivé. Choisissez une nouvelle durée ou aucune expiration puis enregistrez.", + "clients.expired_disabled_short": "Expiré · désactivé", + "clients.expired_disabled_status": "Expiré", + "clients.expires_days": "Expire dans {n} j", + "clients.expires_hours": "Expire dans {n} h", + "clients.expires_minutes": "Expire dans {n} min", + "clients.generated_config": "Configuration client générée", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 secondes est une bonne valeur par défaut pour les clients derrière un NAT.", + "clients.local_access_exceptions": "Adresses locales autorisées", + "clients.local_access_exceptions_hint": "IP ou CIDR facultatifs restant accessibles même si leur réseau local ou Site-to-site est bloqué. Séparez-les par des virgules.", + "clients.managed": "Géré par WGTools", + "clients.name": "Nom", + "clients.no_peers": "Aucun pair trouvé", + "clients.peers": "Pairs", + "clients.peers_subtitle": "Les modifications sont sauvegardées puis appliquées avec wg syncconf sans redémarrer l’interface WireGuard.", + "clients.protected_networks_reference": "Réseaux locaux bloqués (référence)", + "clients.protected_networks_reference_hint": "Ces réseaux ne sont pas écrits dans AllowedIPs. L’accès est bloqué par la politique serveur WGTools ; des adresses individuelles peuvent être autorisées ci-dessus.", + "clients.psk": "Clé prépartagée (PSK)", + "clients.psk_enable": "Utiliser une clé WireGuard prépartagée supplémentaire", + "clients.psk_hint": "Recommandé. Ajoute un secret symétrique au handshake WireGuard. Les clients standards le prennent en charge ; WGTools inclut le PSK dans la configuration et le QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Génération du QR…", + "clients.quick_search": "Recherche rapide", + "clients.quick_search_clear": "Effacer la recherche", + "clients.quick_search_empty": "Aucun client correspondant", + "clients.relay_endpoint_note": "La configuration client générée se connectera à {endpoint}. Le serveur WireGuard reste sur cet hôte WGTools.", + "clients.relay_required": "Choisissez un relais VPS pour ce client.", + "clients.relay_short": "Relais", + "clients.relay_unknown": "indisponible", + "clients.relay_vps": "Relais VPS", + "clients.relay_vps_hint": "L’endpoint du client est généré automatiquement depuis ce relais.", + "clients.remote_hint": "Réseaux situés derrière ce pair. Un par ligne ou séparés par des virgules.", + "clients.remote_networks": "Réseaux distants", + "clients.remote_required": "Saisissez au moins un réseau distant pour le pair Site-to-site.", + "clients.required": "Le nom et l’adresse VPN sont obligatoires.", + "clients.route_custom": "Personnalisé", + "clients.route_full": "Tunnel complet", + "clients.route_full_except_local": "Tunnel complet sauf réseaux locaux", + "clients.route_hint": "Seuls ces réseaux sont écrits dans AllowedIPs de la configuration client.", + "clients.route_preset": "Trafic via VPN", + "clients.route_vpn": "Réseau VPN uniquement", + "clients.route_vpn_lan": "VPN + réseau local", + "clients.saved": "Client enregistré", + "clients.schedule_blocked_short": "Horaire · bloqué", + "clients.schedule_blocked_status": "Bloqué par la plage horaire", + "clients.schedule_days": "Jours autorisés", + "clients.schedule_days_required": "Choisissez au moins un jour pour la plage horaire.", + "clients.schedule_disabled_hint": "Ce client est actuellement bloqué par son horaire. WGTools rétablira le pair automatiquement au prochain créneau autorisé.", + "clients.schedule_enable": "Limiter l’accès selon un horaire", + "clients.schedule_from": "Accès à partir de", + "clients.schedule_hint": "WGTools peut désactiver puis réactiver le client aux jours et heures choisis sans modifier sa configuration.", + "clients.schedule_short": "Horaire", + "clients.schedule_time_required": "Définissez les heures de début et de fin.", + "clients.schedule_timezone_hint": "L’horaire utilise l’heure locale du serveur WireGuard. Les plages traversant minuit, comme 22:00–06:00, sont prises en charge.", + "clients.schedule_title": "Plage horaire d’accès", + "clients.schedule_to": "Accès jusqu’à", + "clients.security_access": "Sécurité et heures d’accès", + "clients.server_host": "Adresse / domaine du serveur", + "clients.server_host_hint": "IP publique ou domaine utilisé par ce client. Les valeurs précédentes apparaissent comme suggestions.", + "clients.server_host_required": "Une adresse / un domaine serveur est nécessaire pour la configuration client.", + "clients.server_peer": "Pair serveur", + "clients.server_port": "Port WireGuard", + "clients.server_port_hint": "Repris automatiquement de la configuration serveur.", + "clients.site_to_site": "Site à site", + "clients.status": "État", + "clients.subtitle": "Pairs WireGuard, état en direct et gestion des configurations client.", + "clients.tab_basic": "Basique", + "clients.tab_config": "Configuration", + "clients.tab_policy": "Politiques", + "clients.tab_security": "Sécurité", + "clients.title": "Clients", + "clients.type": "Type", + "clients.unmanaged_note": "Ce pair existait avant WGTools. Sa clé privée client est irrécupérable. WGTools peut modifier le pair côté serveur mais ne peut pas générer sa configuration client ou son QR.", + "clients.updating": "Mise à jour du client…", + "common.actions": "Actions", + "common.ago": "il y a", + "common.cancel": "Annuler", + "common.checking": "Vérification…", + "common.close": "Fermer", + "common.config": "Configuration", + "common.delete": "Supprimer", + "common.disabled": "Désactivé", + "common.edit": "Modifier", + "common.enabled": "Activé", + "common.loading": "Chargement…", + "common.never": "Jamais", + "common.no": "Non", + "common.not_configured": "Non configuré", + "common.not_installed": "Non installé", + "common.offline": "hors ligne", + "common.online": "en ligne", + "common.refresh": "Actualiser", + "common.running": "En cours", + "common.save": "Enregistrer", + "common.stopped": "Arrêté", + "common.total": "Total", + "common.unknown": "Inconnu", + "common.updated": "Mis à jour", + "common.yes": "Oui", + "dashboard.active_peers": "Pairs actifs", + "dashboard.active_peers_subtitle": "Données en direct issues de wg show.", + "dashboard.activity": "Vue d’ensemble du système", + "dashboard.activity_subtitle": "Vérifications en lecture seule de WireGuard en fonctionnement.", + "dashboard.cores": "cœurs", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Dernières 24 h", + "dashboard.history_avg": "Moy.", + "dashboard.history_max": "Max.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "maintenant", + "dashboard.memory": "Mémoire", + "dashboard.network": "Réseau", + "dashboard.peers": "Pairs", + "dashboard.quick_search": "Recherche rapide", + "dashboard.quick_search_clear": "Effacer la recherche", + "dashboard.quick_search_empty": "Aucun pair ne correspond à la recherche", + "dashboard.restart": "Redémarrer", + "dashboard.restart_confirm": "Redémarrer WireGuard ? Les clients VPN actifs se reconnecteront automatiquement.", + "dashboard.restart_ok": "WireGuard redémarré.", + "dashboard.routing": "Routage", + "dashboard.site_to_site": "Site à site", + "dashboard.start": "Démarrer", + "dashboard.start_ok": "WireGuard démarré.", + "dashboard.stop": "Arrêter", + "dashboard.stop_confirm": "Arrêter WireGuard ? Les clients VPN actifs seront déconnectés.", + "dashboard.stop_ok": "WireGuard arrêté.", + "dashboard.subtitle": "État du serveur WireGuard, pairs et trafic en direct.", + "dashboard.title": "Tableau de bord", + "dashboard.traffic": "Trafic", + "dashboard.uptime": "Temps de fonctionnement", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Politique d’accès au serveur", + "groups.additional_allowed": "Adresses supplémentaires autorisées", + "groups.additional_blocked": "Adresses supplémentaires bloquées", + "groups.allow": "Autoriser", + "groups.allowed": "Autorisé", + "groups.allowed_addresses": "Adresses / réseaux autorisés", + "groups.apply_current_template": "Appliquer le modèle actuel du groupe", + "groups.apply_defaults": "Appliquer le modèle actuel du groupe", + "groups.apply_defaults_hint": "Copie les routes, DNS et Keepalive du modèle de groupe vers ce client. Enregistrez-le puis générez une nouvelle configuration ou un QR si nécessaire.", + "groups.basic": "Informations de base", + "groups.block": "Bloquer", + "groups.blocked": "Bloqué", + "groups.blocked_addresses": "Adresses / réseaux bloqués", + "groups.client_config_source": "Source de configuration client", + "groups.client_defaults": "Paramètres client par défaut", + "groups.client_group_hint": "Groupe facultatif pour réutiliser les règles d’accès et paramètres client. Chaque groupe est associé à l’interface WireGuard sélectionnée.", + "groups.config_differs": "La configuration du client diffère des paramètres actuels du groupe. La politique serveur est à jour, mais le téléphone ou PC doit recevoir une nouvelle configuration ou un QR.", + "groups.config_differs_short": "Configuration client différente du groupe", + "groups.create": "Créer un groupe", + "groups.create_title": "Créer un groupe", + "groups.created": "Groupe créé", + "groups.creating": "Création du groupe…", + "groups.defaults_applied": "Modèle actuel du groupe appliqué. Enregistrez le client pour conserver les changements.", + "groups.defaults_hint": "Définit le trafic envoyé par le client via WireGuard. La politique serveur ci-dessus détermine séparément les accès autorisés. Modifier le modèle ne change jamais les configurations déjà installées.", + "groups.delete_message": "Supprimer « {name} » ? Les configurations client ne sont jamais supprimées avec le groupe.", + "groups.delete_move": "Déplacer ses clients vers un autre groupe", + "groups.delete_title": "Supprimer le groupe de clients", + "groups.delete_unassign": "Retirer l’affectation du groupe aux clients", + "groups.deleted": "Groupe supprimé", + "groups.deleting": "Mise à jour des clients et suppression du groupe…", + "groups.description": "Description", + "groups.edit_title": "Modifier le groupe", + "groups.editor_subtitle": "Un groupe associe des règles d’accès serveur actives à un modèle de configuration client.", + "groups.effective_allow": "Exceptions autorisées", + "groups.effective_deny": "Exceptions bloquées", + "groups.effective_policy": "Politique serveur effective", + "groups.empty": "Aucun groupe de clients. Créez-en un pour réutiliser les règles d’accès et les paramètres par défaut.", + "groups.group": "Groupe", + "groups.inherit": "Hériter", + "groups.internet_access": "Accès Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Réseaux locaux", + "groups.local_short": "Local", + "groups.manage": "Groupes", + "groups.members_count": "{count} clients", + "groups.name": "Nom", + "groups.name_required": "Le nom du groupe est obligatoire.", + "groups.new_client_defaults": "Modèle de configuration client", + "groups.new_clients_short": "Nouveaux clients", + "groups.no_group": "Aucun groupe", + "groups.none": "Aucun", + "groups.override_client_config": "Remplacer le modèle client du groupe pour ce client", + "groups.override_client_config_hint": "Désactivé : routes, DNS et Keepalive proviennent du groupe. Activé : ce client conserve ses valeurs. Les exceptions de politique serveur restent indépendantes.", + "groups.policy_addresses_hint": "Adresses IPv4 ou CIDR séparés par des virgules. Les exceptions client ont priorité sur celles du groupe.", + "groups.policy_custom": "Politique personnalisée", + "groups.policy_inherit": "Utiliser la politique du groupe", + "groups.policy_mode": "Source de la politique", + "groups.policy_mode_hint": "La politique du groupe s’applique par défaut. Les exceptions client ne modifient jamais le groupe.", + "groups.routes_required": "Les routes du client ne peuvent pas être vides.", + "groups.subtitle": "Réutilisez les règles d’accès serveur et les paramètres par défaut pour les clients de l’interface WireGuard sélectionnée.", + "groups.title": "Groupes de clients", + "groups.traffic_through_vpn": "Trafic via VPN", + "groups.updated": "Groupe mis à jour", + "groups.updating": "Mise à jour de la politique du groupe…", + "help.example_note": "Toutes les adresses, interfaces, noms de pairs et domaines des exemples d’aide sont fictifs. Remplacez-les par vos propres valeurs.", + "help.navigation": "Navigation de l’aide", + "help.open": "Ouvrir l’aide", + "help.subtitle": "Aide accessible pour le tableau de bord, le serveur, les clients et les paramètres, avec des exemples pratiques.", + "help.title": "Aide WGTools", + "interfaces.add": "+ Ajouter une interface", + "interfaces.create": "Créer une interface", + "interfaces.create_confirm": "Créer et démarrer l’interface {name} ?", + "interfaces.create_failed": "Impossible de créer l’interface", + "interfaces.create_hint": "Avant la création, WGTools vérifie que le réseau VPN, le port UDP et la table de routage ne sont pas déjà utilisés par une autre interface WireGuard.", + "interfaces.create_subtitle": "Créez une interface WireGuard indépendante avec son propre pool d’adresses, port UDP et paramètres de routage.", + "interfaces.create_title": "Ajouter une interface WireGuard", + "interfaces.created": "Interface créée avec succès.", + "interfaces.creating": "Génération des clés, écriture de la configuration et démarrage de WireGuard…", + "interfaces.current": "Actuelle", + "interfaces.delete": "Supprimer", + "interfaces.delete_confirm": "Supprimer l’interface {name} ? Sa configuration WireGuard et tous ses pairs seront supprimés. Une sauvegarde sera créée au préalable.", + "interfaces.delete_failed": "Impossible de supprimer l’interface", + "interfaces.delete_last": "La dernière interface WireGuard configurée ne peut pas être supprimée ici.", + "interfaces.delete_tooltip": "Supprimer cette interface WireGuard", + "interfaces.deleted": "Interface supprimée. Sauvegarde : {backup}", + "interfaces.deleting": "Arrêt de WireGuard et suppression de l’interface…", + "interfaces.display_name": "Nom affiché", + "interfaces.display_name_edit_hint": "Nom d’affichage uniquement : le nom de l’interface Linux ne change pas.", + "interfaces.display_name_hint": "Nom convivial facultatif, par exemple Travail ou Prestataires.", + "interfaces.identity": "Identité de l’interface", + "interfaces.none": "Aucune interface WireGuard trouvée", + "interfaces.none_configured": "Aucune interface WireGuard n’est encore configurée.", + "interfaces.peers_short": "pairs", + "interfaces.rename_failed": "Impossible d’enregistrer le nom affiché de l’interface.", + "interfaces.select": "Sélectionner", + "interfaces.subtitle": "Chaque interface possède son réseau VPN, son port, ses pairs et ses règles. Sélectionnez-en une pour la gérer dans WGTools.", + "interfaces.switch_title": "Interfaces WireGuard", + "interfaces.system_name": "Nom système", + "interfaces.system_name_hint": "Nom de l’interface Linux, par exemple wg1. Non modifiable après création.", + "interfaces.title": "Interfaces WireGuard", + "interfaces.unique_port_hint": "Chaque interface WireGuard de ce serveur doit utiliser un port UDP distinct.", + "interfaces.unique_table_hint": "WGTools recommande une table de routage distincte par interface. Laissez vide pour le routage standard.", + "nav.clients": "Clients", + "nav.dashboard": "Tableau de bord", + "nav.server": "Serveur", + "nav.settings": "Paramètres", + "server.access_apply_confirm": "Enregistrer et appliquer cette règle de pare-feu ? WireGuard redémarrera brièvement et une sauvegarde sera créée.", + "server.access_rule_deleted": "Règle d’accès supprimée.", + "server.access_rule_help": "Créez une règle FORWARD sans modifier manuellement les commandes iptables.", + "server.access_rule_order_hint": "WGTools insère les règles au début de la chaîne FORWARD pour appliquer les restrictions avant les règles VPN ACCEPT générales.", + "server.access_rule_saved": "Règle d’accès enregistrée et appliquée.", + "server.action": "Action", + "server.action_hint": "REJECT signale le refus au client ; DROP écarte sans réponse ; ACCEPT autorise explicitement.", + "server.add_access_rule": "Ajouter une règle d’accès", + "server.add_route": "Ajouter une route", + "server.address": "Adresse", + "server.any": "Tous", + "server.any_protocol": "Tout protocole", + "server.apply_confirm": "Enregistrer et appliquer les paramètres serveur ? WireGuard redémarrera brièvement. Une sauvegarde sera créée et la configuration précédente restaurée automatiquement si le démarrage échoue.", + "server.apply_settings": "Enregistrer et appliquer", + "server.applying_rule": "Création de sauvegarde et application…", + "server.applying_settings": "Validation, sauvegarde et application des paramètres…", + "server.basic_settings": "Paramètres de base", + "server.config_tab_help": "Ouvrir l’éditeur de configuration brute de l’interface WireGuard sélectionnée.", + "server.create_confirm": "Créer et démarrer le serveur WireGuard avec ces paramètres ?", + "server.create_server": "Créer le serveur", + "server.create_step_conf": "Créer la configuration de l’interface WireGuard avec les permissions 600.", + "server.create_step_forward": "Configurer le transfert, le NAT et éventuellement le routage par politique.", + "server.create_step_key": "Générer une nouvelle paire de clés serveur.", + "server.create_step_start": "Activer et démarrer l’interface wg-quick choisie.", + "server.create_subtitle": "WireGuard est installé, mais l’interface sélectionnée n’est pas configurée.", + "server.create_success": "Serveur WireGuard créé avec succès.", + "server.create_title": "Créer le serveur WireGuard", + "server.creating": "Génération des clés, écriture de la configuration et démarrage de WireGuard…", + "server.custom_preserved": "Les blocs de pairs, routes Site-to-site et règles PostUp/PostDown non gérées ici sont conservés.", + "server.delete_access_confirm": "Supprimer cette règle d’accès et appliquer ?", + "server.delete_route_confirm": "Supprimer cette route personnalisée et appliquer ?", + "server.destination": "Destination", + "server.destination_hint": "Vide = tous. IP, CIDR ou plage IP acceptés. Séparez plusieurs destinations par des virgules.", + "server.destination_port": "Port de destination", + "server.destination_port_hint": "Facultatif. Port comme 443 ou plage 10000:20000. Sélectionnez d’abord TCP ou UDP.", + "server.details": "Détails", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostic", + "server.diagnostics_done": "Diagnostic terminé", + "server.diagnostics_subtitle": "Contrôles système actuels. Aucune modification de configuration.", + "server.direction": "Hook", + "server.edit_access_rule": "Modifier la règle d’accès", + "server.edit_route": "Modifier la route", + "server.edit_server": "Modifier le serveur", + "server.edit_subtitle": "Modifier les paramètres WireGuard, routage et NAT courants. Les pairs et règles personnalisées sont conservés.", + "server.edit_title": "Paramètres du serveur", + "server.edit_warning": "Appliquer les paramètres d’interface, routage ou pare-feu redémarre brièvement WireGuard. Les pairs actifs se reconnectent automatiquement.", + "server.enable_forwarding": "Activer le transfert IPv4", + "server.enable_nat": "Activer NAT / Masquerade", + "server.firewall": "Pare-feu et NAT", + "server.firewall_subtitle": "Règles détectées dans les hooks WireGuard.", + "server.firewall_subtitle_v08": "Règles de transfert/NAT et d’accès de l’interface. Les règles simples se gèrent ici ; les plus avancées restent dans l’éditeur brut.", + "server.forward_from_vpn": "Autoriser le transfert depuis VPN", + "server.forward_to_vpn": "Autoriser le transfert vers VPN", + "server.forwarding_section": "Transfert et NAT", + "server.gateway": "Passerelle", + "server.gateway_hint": "Obligatoire uniquement avec une table de routage par politique.", + "server.install_success": "WireGuard installé avec succès.", + "server.install_wireguard": "Installer WireGuard", + "server.install_wireguard_help": "Exécute apt update et installe WireGuard et les outils réseau nécessaires.", + "server.install_wireguard_title": "Installer WireGuard", + "server.installing": "Installation de WireGuard… Cela peut prendre une minute.", + "server.interface": "Interface", + "server.interface_hint": "WGTools gère actuellement cette interface.", + "server.interface_name": "Interface", + "server.interface_section": "Interface WireGuard", + "server.ip_forwarding": "Transfert IPv4", + "server.kind": "Type", + "server.listen_port": "Port d’écoute", + "server.local_network": "Réseau local", + "server.local_network_hint": "Route facultative ajoutée à la table de routage.", + "server.managed_automatically": "Géré automatiquement", + "server.nat": "NAT / Masquerade", + "server.network": "Réseau", + "server.network_settings": "Réseau et NAT", + "server.no_firewall": "Aucune règle de pare-feu trouvée", + "server.no_routes": "Aucune route trouvée", + "server.not_configured": "Non configuré", + "server.not_set": "Non défini", + "server.policy_disabled_hint": "Désactivez pour le routage système normal. Activez uniquement si ce VPN requiert une table par adresse source.", + "server.policy_enabled": "Activer le routage par politique", + "server.policy_table": "Table de routage", + "server.policy_table_hint": "Laissez vide pour le routage normal ; utilisez par ex. 200 pour le routage par source.", + "server.port_word": "port", + "server.private_hidden": "Configuré (masqué)", + "server.private_key": "Clé privée", + "server.protocol": "Protocole", + "server.route_apply_confirm": "Enregistrer et appliquer cette route ? WireGuard redémarrera brièvement et une sauvegarde sera créée.", + "server.route_custom": "Personnalisée", + "server.route_deleted": "Route supprimée.", + "server.route_device_hint": "Interface de sortie facultative, par ex. wg0 ou enp6s18.", + "server.route_editor_help": "Ajoutez une route installée au démarrage de WireGuard puis retirée à l’arrêt.", + "server.route_gateway_hint": "Passerelle de prochain saut facultative. Une passerelle ou interface est requise.", + "server.route_managed_peer": "Pair Site-to-site", + "server.route_managed_server": "Paramètre serveur", + "server.route_network_hint": "Réseau IPv4 comme 10.20.0.0/24 ou 'default'.", + "server.route_saved": "Route enregistrée et appliquée.", + "server.route_table_hint": "Utilisez 'main' pour le routage normal ou une table numérique comme 200.", + "server.route_type": "Type", + "server.routes": "Routes détectées", + "server.routes_subtitle": "Routes extraites de PostUp/PostDown et de l’état actuel du routage par politique.", + "server.routes_subtitle_v08": "Routes serveur, Site-to-site et personnalisées de l’interface choisie. Vous pouvez ajouter, modifier et retirer des routes personnalisées ici.", + "server.routing": "Routage", + "server.routing_section": "Routage", + "server.rule": "Règle", + "server.rule_access": "Règle d’accès", + "server.rule_advanced": "Avancé", + "server.rule_apply_warning": "L’application d’une route ou règle de pare-feu redémarre brièvement WireGuard. WGTools sauvegarde puis restaure automatiquement en cas d’échec de démarrage.", + "server.rule_client_exception": "Exception client", + "server.rule_client_policy": "Politique client", + "server.rule_managed_server": "Paramètre serveur", + "server.rule_type": "Type", + "server.run_diagnostics": "Lancer le diagnostic", + "server.save_apply": "Enregistrer et appliquer", + "server.save_config": "SaveConfig", + "server.server_address": "Adresse VPN du serveur", + "server.server_address_hint": "Habituellement la première adresse utilisable du réseau VPN.", + "server.settings_applied": "Paramètres serveur enregistrés et appliqués avec succès.", + "server.settings_apply_failed": "Impossible d’appliquer les paramètres serveur", + "server.setup_required": "Configuration requise", + "server.source": "Source", + "server.source_hint": "Vide = tous. Accepte IP, CIDR ou plage telle que 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installation, première configuration et paramètres actuels du serveur WireGuard.", + "server.tab_config": "Configuration", + "server.tab_interface": "Interface", + "server.tab_routing": "Routage", + "server.tab_vps": "VPS", + "server.table": "Table", + "server.tabs_aria": "Sections des paramètres serveur", + "server.title": "Serveur", + "server.uplink": "Interface montante", + "server.use_raw_editor": "Utiliser l’éditeur brut", + "server.via": "Via / Interface", + "server.via_word": "via", + "server.vpn_network": "Réseau VPN", + "server.vpn_network_hint": "Les adresses client seront ensuite attribuées depuis ce réseau.", + "server.vpn_pool": "Pool d’adresses VPN", + "server.wg_not_installed": "WireGuard n’est pas installé", + "server.wg_not_installed_subtitle": "WGTools peut installer automatiquement les paquets Debian nécessaires.", + "server.what_happens": "Ce que fera WGTools", + "settings.about": "À propos", + "settings.add_user": "Ajouter un utilisateur", + "settings.advanced": "Avancé", + "settings.advanced_subtitle": "Accès direct aux outils avancés de configuration WireGuard.", + "settings.appearance": "Apparence", + "settings.applying_config": "Vérification de configuration, sauvegarde et application…", + "settings.backup_count": "Sauvegardes stockées", + "settings.backup_retention": "Nombre de sauvegardes à garder", + "settings.backup_retention_help": "Les anciennes sauvegardes automatiques sont supprimées après la création de la suivante. De 1 à 200 fichiers.", + "settings.backups": "Sauvegardes de configuration", + "settings.backups_always_on": "Activé", + "settings.backups_subtitle": "WGTools crée automatiquement une sauvegarde avant toute modification de configuration. Cette protection ne peut pas être désactivée.", + "settings.change_password": "Changer le mot de passe", + "settings.check_updates": "Rechercher des mises à jour", + "settings.config_applied": "Configuration enregistrée et appliquée avec succès.", + "settings.config_applied_restarted": "Configuration appliquée et WireGuard redémarré.", + "settings.config_applied_stopped": "Configuration enregistrée. WireGuard était arrêté et reste arrêté.", + "settings.config_apply_failed": "Impossible d’appliquer la configuration", + "settings.config_load_failed": "Impossible de charger la configuration", + "settings.current_user": "Utilisateur actuel", + "settings.current_version": "Version actuelle", + "settings.audit_action": "Action", + "settings.audit_empty": "Aucun événement d’audit", + "settings.audit_log": "Journal d’audit", + "settings.audit_log_subtitle": "Actions du panneau, connexions, Telegram et historique des clients WireGuard. Aucun secret n’est enregistré ici.", + "settings.audit_object": "Objet", + "settings.audit_result": "Résultat", + "settings.audit_retention_note": "Conservation : 30 jours", + "settings.audit_search": "Recherche rapide", + "settings.audit_search_clear": "Effacer la recherche", + "settings.audit_search_empty": "Aucun événement d’audit correspondant", + "settings.audit_time": "Date / heure", + "settings.audit_user": "Utilisateur", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Règle d’accès créée", + "audit.action.access_rule.deleted": "Règle d’accès supprimée", + "audit.action.access_rule.updated": "Règle d’accès modifiée", + "audit.action.auth.first_user_created": "Premier utilisateur créé", + "audit.action.auth.login": "Connexion réussie", + "audit.action.auth.login_failed": "Échec de connexion", + "audit.action.auth.logout": "Déconnexion effectuée", + "audit.action.backup.full_created": "Sauvegarde complète créée", + "audit.action.backup.full_restored": "Sauvegarde complète restaurée", + "audit.action.client.config_downloaded": "Configuration client téléchargée", + "audit.action.client.config_viewed": "Configuration client consultée", + "audit.action.client.created": "Client créé", + "audit.action.client.deleted": "Client supprimé", + "audit.action.client.qr_viewed": "Code QR du client consulté", + "audit.action.client.updated": "Client mis à jour", + "audit.action.client_group.created": "Groupe de clients créé", + "audit.action.client_group.deleted": "Groupe de clients supprimé", + "audit.action.client_group.updated": "Groupe de clients mis à jour", + "audit.action.interface.created": "Interface créée", + "audit.action.interface.deleted": "Interface supprimée", + "audit.action.interface.renamed": "Interface renommée", + "audit.action.route.created": "Route créée", + "audit.action.route.deleted": "Route supprimée", + "audit.action.route.updated": "Route mise à jour", + "audit.action.server.created": "Serveur créé", + "audit.action.server.raw_config_applied": "Configuration brute appliquée", + "audit.action.server.settings_applied": "Paramètres serveur appliqués", + "audit.action.settings.updated": "Paramètres du panneau modifiés", + "audit.action.telegram.action_denied": "Action Telegram refusée", + "audit.action.telegram.action_failed": "Échec de l’action Telegram", + "audit.action.telegram.connection_test": "Test de connexion Telegram", + "audit.action.telegram.settings_updated": "Paramètres Telegram modifiés", + "audit.action.update.checked": "Mise à jour vérifiée", + "audit.action.update.scheduled": "Mise à jour planifiée", + "audit.action.update.backup_created": "Sauvegarde avant mise à jour", + "audit.action.update.completed": "Mise à jour terminée", + "audit.action.update.failed": "Échec de la mise à jour", + "audit.action.update.rollback_completed": "Version précédente restaurée", + "audit.action.update.rollback_failed": "Échec du retour arrière", + "audit.action.user.created": "Utilisateur créé", + "audit.action.user.deleted": "Utilisateur supprimé", + "audit.action.user.password_changed": "Mot de passe utilisateur modifié", + "audit.action.vps.candidate_deleted": "Candidat VPS supprimé", + "audit.action.vps.candidate_saved": "Candidat VPS enregistré", + "audit.action.vps.detached": "Relais VPS détaché", + "audit.action.vps.relay_installed": "Relais VPS installé", + "audit.action.wireguard.client_connected": "Client WireGuard connecté", + "audit.action.wireguard.installed": "WireGuard installé", + "audit.action.wireguard.restarted": "WireGuard redémarré", + "audit.action.wireguard.started": "WireGuard démarré", + "audit.action.wireguard.stopped": "WireGuard arrêté", + "audit.result.applied": "appliqué", + "audit.result.available": "disponible", + "audit.result.changed": "modifié", + "audit.result.created": "créé", + "audit.result.current": "à jour", + "audit.result.deleted": "supprimé", + "audit.result.detached": "détaché", + "audit.result.denied": "refusé", + "audit.result.downloaded": "téléchargé", + "audit.result.endpoint": "Point de terminaison", + "audit.result.error": "Erreur", + "audit.result.installed": "installé", + "audit.result.invalid_credentials": "identifiants invalides", + "audit.result.ok": "OK", + "audit.result.queued": "en attente", + "audit.result.restarted": "redémarré", + "audit.result.restored": "restauré", + "audit.result.rotated": "renouvelé", + "audit.result.saved": "enregistré", + "audit.result.shown": "affiché", + "audit.result.started": "démarré", + "audit.result.stopped": "arrêté", + "audit.result.updated": "mis à jour", + "settings.delete_user": "Supprimer", + "settings.delete_user_confirm": "Supprimer l’utilisateur {name} ?", + "settings.edit_raw_config": "Modifier la configuration de l’interface", + "settings.expert_mode": "Expert", + "settings.full_backup_component_clients": "Métadonnées des clients gérés, clés privées, PSK, expirations et groupes nécessaires pour recréer leurs configurations et QR.", + "settings.full_backup_component_db": "Base WGTools : utilisateurs, préférences, messagerie/SMTP, Telegram et état enregistré des relais VPS.", + "settings.full_backup_component_relay": "Données de récupération VPS Relay : identifiants contrôleur/tenant, jeton d’administration et clé de transport domicile. WGTools pourra reconstruire le transport local et reconnecter le tenant conservé.", + "settings.full_backup_component_system": "Fichier sysctl de transfert IPv4 WGTools, noms d’affichage des interfaces, règles et modèles de groupes si présents. L’historique automatique des configurations est exclu intentionnellement.", + "settings.full_backup_component_wg": "Toutes les configurations des interfaces WireGuard détectées dans /etc/wireguard/, avec leur état actif/arrêté.", + "settings.full_backup_create_failed": "Impossible de créer la sauvegarde complète", + "settings.full_backup_creating": "Création de la sauvegarde complète…", + "settings.full_backup_download": "Créer", + "settings.full_backup_downloaded": "Sauvegarde créée et téléchargée. Conservez-la en sécurité.", + "settings.full_backup_downloaded_short": "Sauvegarde complète téléchargée.", + "settings.full_backup_help": "Crée une sauvegarde portable WGTools pour migration ou reprise après incident : configurations WireGuard, utilisateurs, paramètres, groupes, clients gérés et données nécessaires pour reconnecter les tenants VPS Relay conservés.", + "settings.full_backup_no_file": "Aucune sauvegarde sélectionnée", + "settings.full_backup_restore": "Restaurer", + "settings.full_backup_restore_confirm": "Restaurer cette sauvegarde complète ? Les utilisateurs, paramètres, clients gérés et configurations WireGuard contenus dans l’archive seront restaurés. Des interfaces peuvent redémarrer. WGTools crée d’abord une sauvegarde de sécurité et annule automatiquement en cas d’échec.", + "settings.full_backup_restore_failed": "Échec de la restauration", + "settings.full_backup_restored": "Sauvegarde restaurée. Connectez-vous avec un compte de la sauvegarde.", + "settings.full_backup_restored_short": "Sauvegarde restaurée.", + "settings.full_backup_restoring": "Validation de la sauvegarde, création d’une copie de sécurité et restauration…", + "settings.full_backup_secret_warning": "Ce fichier contient des secrets : clés privées WireGuard et clients, PSK, empreintes des mots de passe WGTools, jeton du bot Telegram et mot de passe SMTP enregistré. Protégez-le comme un mot de passe ; ne le publiez jamais dans des issues ou chats.", + "settings.full_backup_select": "Sélectionner", + "settings.full_backup_title": "Sauvegarde complète et restauration", + "settings.full_mode": "Gestion serveur et clients activée", + "settings.interface_help": "L’interface WireGuard gérée est choisie lors du déploiement WGTools.", + "settings.language": "Langue", + "settings.last_backup": "Dernière sauvegarde", + "settings.latest_version": "Dernière version", + "settings.loading_config": "Chargement de la configuration…", + "settings.mode": "Mode", + "settings.never_logged_in": "Jamais", + "settings.new_password": "Nouveau mot de passe", + "settings.no_backups": "Aucune sauvegarde", + "settings.online_help": "Un pair est en ligne si sa dernière poignée de main est plus récente que cette valeur. 30 à 3600 secondes.", + "settings.online_threshold": "Seuil de connexion", + "settings.open_release": "Ouvrir la version", + "settings.password_changed": "Mot de passe modifié.", + "settings.passwords_mismatch": "Les mots de passe ne correspondent pas.", + "settings.project_github": "Projet / GitHub", + "settings.raw_config_confirm": "Enregistrer et appliquer la configuration WireGuard ? L’interface sélectionnée redémarrera. Une sauvegarde est créée au préalable ; WGTools restaurera automatiquement l’ancienne configuration en cas d’échec.", + "settings.raw_config_help": "Ouvrir la configuration source de l’interface WireGuard sélectionnée.", + "settings.raw_config_title": "Configuration WireGuard brute", + "settings.raw_config_warning": "Mode expert : configuration réelle du serveur WireGuard contenant la clé privée du serveur et les PSK des pairs. Enregistrer et appliquer redémarre l’interface. WGTools crée une sauvegarde et restaure automatiquement en cas d’échec.", + "settings.readonly_mode": "Gestion des clients activée", + "settings.refresh_help": "Fréquence de mise à jour des données d’état. De 2 à 60 secondes.", + "settings.refresh_interval": "Intervalle d'actualisation", + "settings.release_notes": "Notes de version", + "settings.reload_config": "Recharger depuis le disque", + "settings.save_apply": "Enregistrer et appliquer", + "settings.saved": "Paramètres enregistrés.", + "settings.saved_reload": "Paramètres enregistrés. Rechargement…", + "settings.saving": "Enregistrement des paramètres…", + "settings.status": "Actualisation de l’état", + "settings.status_help": "Fréquence d’actualisation du tableau de bord et des pairs.", + "settings.subtitle": "Préférences de l’interface et paramètres d’état WGTools.", + "settings.syntax_hint": "Sections, clés, valeurs et commentaires WireGuard sont colorés pendant l’édition.", + "settings.tab_about": "À propos", + "settings.tab_backups": "Sauvegardes", + "settings.tab_general": "Général", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Utilisateurs", + "settings.tabs_aria": "Sections des paramètres", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "ID utilisateur Telegram autorisés", + "settings.telegram_allowed_ids_help": "Un ID numérique par ligne. Un message /start non autorisé renverra l’ID Telegram de l’expéditeur, pour l’ajouter ici.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connecté", + "settings.telegram_disabled": "Désactivé", + "settings.telegram_dns": "DNS client par défaut", + "settings.telegram_dns_help": "Adresses DNS IPv4 facultatives séparées par des virgules. Utilisées pour les clients créés par le bot.", + "settings.telegram_enabled": "Activer le bot Telegram", + "settings.telegram_endpoint": "Adresse / domaine serveur par défaut", + "settings.telegram_endpoint_help": "Utilisée par le bot pour créer une configuration client. Saisissez seulement IP ou domaine ; le port WireGuard vient de la configuration serveur.", + "settings.telegram_language": "Langue du bot", + "settings.telegram_language_auto": "Auto (langue Telegram)", + "settings.telegram_last_poll": "Dernier contact Telegram", + "settings.telegram_not_configured": "Non configuré", + "settings.telegram_remove_token": "Supprimer le jeton", + "settings.telegram_remove_token_confirm": "Supprimer le jeton Telegram enregistré et désactiver le bot ?", + "settings.telegram_save": "Enregistrer les paramètres Telegram", + "settings.telegram_saved": "Paramètres Telegram enregistrés.", + "settings.telegram_setup_note": "Créez un bot avec @BotFather, enregistrez son jeton, activez-le et envoyez /start. Si votre ID n’est pas autorisé, WGTools l’affichera : ajoutez-le à la liste.", + "settings.telegram_status": "Statut du bot", + "settings.telegram_subtitle": "Gestion WireGuard à distance via Telegram : état serveur, clients, création/suppression et démarrage/redémarrage/arrêt.", + "settings.telegram_test": "Tester la connexion", + "settings.telegram_test_ok": "Connexion Telegram opérationnelle : @{username}", + "settings.telegram_test_recent_ok": "Le bot Telegram fonctionne. Le test direct a expiré, mais le bot a contacté Telegram récemment.", + "settings.telegram_token": "Jeton du bot", + "settings.telegram_token_help": "Créez un bot avec @BotFather et collez son jeton API ici. Aucun API ID ni API Hash n’est nécessaire pour l’API Bot.", + "settings.telegram_token_keep": "Laissez vide pour conserver le jeton actuel.", + "settings.telegram_waiting": "Configuré, en attente du service bot", + "settings.theme": "Thème", + "settings.theme_dark": "Sombre", + "settings.theme_light": "Clair", + "settings.theme_system": "Système", + "settings.title": "Paramètres", + "settings.update_available": "Mise à jour disponible", + "settings.update_backup_queued": "Mise à jour en attente. WGTools créera une sauvegarde complète avant installation…", + "settings.update_backup_running": "Création de la sauvegarde complète avant mise à jour…", + "settings.update_check_failed": "Impossible de vérifier les mises à jour", + "settings.update_checking": "Vérification de la dernière version publiée sur GitHub…", + "settings.update_confirm": "Mettre WGTools à jour de v{current} vers v{latest} ? Une sauvegarde complète et une copie pour retour arrière seront créées. L’interface web redémarrera brièvement.", + "settings.update_current": "À jour", + "settings.update_downloading": "Téléchargement et validation de la version GitHub…", + "settings.update_failed": "Échec de la mise à jour WGTools.", + "settings.update_installing": "Installation de la mise à jour. L’interface web peut être brièvement indisponible…", + "settings.update_no_update": "WGTools est déjà à jour.", + "settings.update_not_checked": "Non vérifié", + "settings.update_queued": "Mise à jour en attente du service de mise à jour…", + "settings.update_rollback_ok": "L’application WGTools précédente a été restaurée automatiquement.", + "settings.update_rolling_back": "Échec de la mise à jour. Restauration de la version précédente…", + "settings.update_running": "Création des sauvegardes de sécurité…", + "settings.update_safety_hint": "Les mises à jour nécessitent votre accord. WGTools crée une sauvegarde complète et une copie de retour arrière avant installation. En cas d’échec, l’ancienne application est restaurée automatiquement. WireGuard n’est pas redémarré, sauf si la nouvelle version modifie explicitement sa configuration.", + "settings.update_sidebar": "Nouvelle version disponible", + "settings.update_sidebar_hint": "Paramètres → À propos", + "settings.update_starting": "Démarrage de la mise à jour…", + "settings.update_status_unknown": "État de la mise à jour indisponible. Nouvelle tentative…", + "settings.update_subtitle": "Informations du projet, vérification automatique des versions et mises à jour sécurisées depuis GitHub Releases.", + "settings.update_success": "WGTools mis à jour vers v{version}. Rechargement…", + "settings.update_wgtools": "Mettre à jour WGTools", + "settings.user_actions": "Actions", + "settings.user_created": "Créé", + "settings.user_created_ok": "Utilisateur créé.", + "settings.user_deleted": "Utilisateur supprimé.", + "settings.user_equal_rights": "Tous les utilisateurs WGTools disposent des mêmes autorisations.", + "settings.user_last_login": "Dernière connexion", + "settings.user_name": "Nom d’utilisateur", + "settings.users": "Utilisateurs", + "settings.users_subtitle": "Comptes locaux WGTools. L’e-mail est facultatif et sert uniquement à récupérer le mot de passe lorsque la messagerie est activée.", + "vps.add": "Ajouter un VPS", + "vps.add_help": "WGTools utilise SSH pour vérifier ou installer le relais. Les mots de passe et clés SSH privées ne sont jamais stockés.", + "vps.add_title": "Ajouter un VPS", + "vps.agent": "Agent relais", + "vps.agent_found": "Déjà installé", + "vps.agent_will_install": "Sera installé", + "vps.arch": "Architecture", + "vps.auth_method": "Authentification", + "vps.authentication": "Authentification SSH", + "vps.check": "Vérifier le VPS", + "vps.check_failed": "Échec de la vérification VPS", + "vps.check_link": "Vérifier la liaison", + "vps.check_ok": "VPS compatible", + "vps.checking": "Vérification SSH et compatibilité VPS…", + "vps.connections": "connexions", + "vps.credentials_not_saved": "Utilisés uniquement pour ce contrôle, sans stockage par WGTools.", + "vps.delete_candidate": "Retirer", + "vps.delete_installed": "Retirer le VPS", + "vps.delete_installed_confirm": "Retirer « {name} » de WGTools ? Le transport local sera déconnecté, mais l’agent Relay et son espace sur le VPS seront conservés. Vous pourrez ajouter ce VPS à nouveau pour réutiliser le même relais. Les clients ne pourront pas s’y connecter avant reconnexion.", + "vps.delete_installed_failed": "Impossible de retirer le VPS de WGTools", + "vps.delete_installed_ok": "VPS retiré de WGTools. Le relais distant est conservé et peut être reconnecté.", + "vps.empty_help": "Ajoutez un VPS Debian ou Ubuntu pour vérifier SSH, la compatibilité du système et les ports UDP nécessaires.", + "vps.empty_title": "Aucun VPS configuré", + "vps.endpoint": "Endpoint public", + "vps.endpoint_domain": "Domaine (recommandé)", + "vps.endpoint_domain_hint": "Si vous remplacez le VPS principal, changer le DNS peut éviter de modifier les configurations client.", + "vps.health_failed": "Échec de la vérification du relais", + "vps.host": "IP / nom d’hôte", + "vps.host_key": "Clé de l’hôte SSH", + "vps.identity": "Connexion VPS", + "vps.install_failed": "Échec de l’installation du relais", + "vps.install_ok": "Relais installé et liaison d’administration sécurisée vérifiée", + "vps.install_relay": "Installer le relais", + "vps.install_title": "Installer le relais VPS", + "vps.installed": "Installé", + "vps.installing": "Installation de l’agent Relay et établissement du tunnel sécurisé…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Phrase secrète de la clé", + "vps.link_ok": "Liaison Relay OK", + "vps.multi_tenant_note": "Un agent Relay WGTools fonctionne déjà sur ce VPS. Il ne sera pas remplacé : ce WGTools recevra une connexion isolée avec ses propres clés et ports UDP.", + "vps.name": "Nom", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Sera installé", + "vps.os": "Système d’exploitation", + "vps.password": "Mot de passe", + "vps.phase_note": "L’agent Relay accepte plusieurs contrôleurs WGTools indépendants sur un VPS. Chaque contrôleur dispose d’une connexion, de clés et ports UDP isolés ; les connexions existantes restent intactes.", + "vps.port_pair": "Ports UDP", + "vps.ports_adjusted": "ports libres sélectionnés", + "vps.private_key": "Clé privée", + "vps.privilege": "Privilèges", + "vps.public_endpoint": "Futur endpoint public", + "vps.ready_help": "Les identifiants SSH servent uniquement à vérifier la compatibilité et installer immédiatement le relais ; ils ne sont pas enregistrés.", + "vps.reconnect_note": "Une connexion Relay de ce WGTools existe déjà sur le VPS. WGTools reconnectera le même espace sans créer de nouveau tenant ni de ports UDP.", + "vps.reconnect_ok": "Relais existant reconnecté avec succès", + "vps.reconnect_relay": "Reconnecter le relais", + "vps.relay_port": "Port UDP du relais", + "vps.remove_confirm": "Retirer ce candidat VPS ? Aucune modification distante n’a été effectuée.", + "vps.save_candidate": "Enregistrer le candidat", + "vps.saved": "Candidat VPS enregistré", + "vps.ssh": "SSH", + "vps.ssh_key": "Clé SSH", + "vps.ssh_port": "Port SSH", + "vps.ssh_user": "Utilisateur SSH", + "vps.status_candidate": "Prêt à installer", + "vps.status_installed": "Relais connecté", + "vps.subtitle": "Préparez un VPS public pour l’accès distant lorsque ce serveur WGTools ne possède pas d’IP publique.", + "vps.tenant": "Connexion", + "vps.title": "Relais VPS", + "vps.transport_port": "Port UDP de transport", + "vps.transport_port_hint": "Port UDP distinct pour le tunnel de transport privé domicile ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Enregistré", + "vps.active_short": "Actif", + "dashboard.traffic_reset": "Réinitialiser", + "dashboard.traffic_reset_confirm": "Réinitialiser les compteurs de trafic WireGuard de cette interface ? Les compteurs des clients repartiront aussi de zéro.", + "dashboard.traffic_reset_done": "Compteurs de trafic réinitialisés", + "dashboard.traffic_reset_failed": "Impossible de réinitialiser les compteurs", + "audit.action.traffic.reset": "Compteurs de trafic réinitialisés", + "audit.result.reset": "réinitialisé", + "server.mtu": "MTU", + "server.mtu_auto": "Auto", + "server.mtu_hint": "Facultatif. Laissez vide pour le MTU automatique de wg-quick. Définissez 1380 ou 1420 uniquement si nécessaire pour LTE ou PPPoE.", + "clients.peer_isolation": "Isolation des clients VPN", + "clients.peer_isolation_enable": "Isoler des autres clients VPN", + "clients.peer_isolation_hint": "Bloque le trafic entre ce client et les autres adresses du pool WireGuard. Les autres politiques régissent toujours l’accès au serveur, à Internet et aux réseaux locaux ou Site-to-site.", + "clients.credentials_rotate": "Clés du client", + "clients.credentials_rotate_button": "Renouveler les clés", + "clients.credentials_rotate_confirm": "Générer de nouvelles clés pour ce client ? Si connecté, sa session WireGuard sera immédiatement interrompue. Envoyez ensuite une nouvelle configuration ou un QR.", + "clients.credentials_rotate_confirm_psk": "Générer une nouvelle paire de clés et un PSK pour ce client ? Sa session WireGuard active sera interrompue immédiatement. Envoyez ensuite une nouvelle configuration ou un QR.", + "clients.credentials_rotate_hint": "Renouvelle PrivateKey/PublicKey et, si activé, le PSK. L’adresse, les routes, le groupe, l’horaire, l’isolation et les statistiques sont conservés.", + "clients.credentials_rotating": "Génération de nouvelles clés et fermeture de l’ancienne session…", + "clients.credentials_rotated": "Clés du client modifiées. Si connecté, son ancienne session a été interrompue. L’ancienne configuration ne fonctionne plus ; envoyez une nouvelle configuration ou un QR.", + "clients.credentials_rotated_short": "Clés modifiées — nouvelle configuration requise", + "audit.action.client.credentials_rotated": "Clés du client renouvelées", + "clients.credentials_connection_lost": "Connexion à WGTools interrompue. Si ce panneau utilisait le client dont les clés viennent de changer, c’est normal : son ancienne session WireGuard est coupée. Reconnectez-vous par un autre chemin et générez une nouvelle configuration ou un QR.", + "nav.navigation": "Navigation principale", + "nav.project_github": "WGTools sur GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Facultatif pour l’instant. Utilisable pour récupérer le mot de passe une fois la messagerie configurée.", + "auth.forgot_password": "Mot de passe oublié ?", + "auth.reset_title": "Réinitialiser le mot de passe", + "auth.reset_subtitle": "Recevez un code unique par e-mail et définissez un nouveau mot de passe WGTools.", + "auth.reset_identifier": "Nom d’utilisateur ou e-mail", + "auth.reset_identifier_help": "Pour préserver la confidentialité, WGTools affiche toujours la même réponse, que le compte existe ou non.", + "auth.send_reset_code": "Envoyer le code", + "auth.reset_code_sent_generic": "Si le compte existe et possède une adresse e-mail, un code a été envoyé. Il reste valable 15 minutes.", + "auth.reset_code": "Code à 6 chiffres", + "auth.set_new_password": "Définir un nouveau mot de passe", + "auth.request_another_code": "Demander un autre code", + "auth.back_to_login": "Retour à la connexion", + "auth.reset_not_configured": "La récupération du mot de passe par e-mail n’est pas configurée. Contactez l’administrateur WGTools.", + "settings.tab_mail": "Messagerie", + "settings.mail": "Messagerie / SMTP", + "settings.mail_subtitle": "SMTP sert à récupérer les mots de passe.", + "settings.mail_not_configured": "Non configuré", + "settings.mail_enabled": "Activer la messagerie et la récupération de mot de passe", + "settings.mail_smtp_host": "Serveur SMTP", + "settings.mail_smtp_port": "Port SMTP", + "settings.mail_security": "Chiffrement", + "settings.mail_security_none": "Sans chiffrement", + "settings.mail_username": "Nom d’utilisateur SMTP", + "settings.mail_username_help": "Utilisé pour l’authentification SMTP et comme adresse d’expéditeur.", + "settings.mail_password": "Mot de passe SMTP", + "settings.mail_password_keep": "Laissez vide pour conserver le mot de passe enregistré.", + "settings.mail_from_email": "E-mail expéditeur", + "settings.mail_from_name": "Nom de l’expéditeur", + "settings.mail_test_recipient": "Destinataire du test", + "settings.mail_test_recipient_help": "Le test utilise les paramètres SMTP actuellement enregistrés.", + "settings.mail_remove_password": "Supprimer le mot de passe", + "settings.mail_test": "Envoyer un test", + "settings.mail_save": "Enregistrer les paramètres mail", + "settings.mail_enabled_badge": "Activé", + "settings.mail_disabled_badge": "Désactivé", + "settings.mail_saved": "Paramètres mail enregistrés.", + "settings.mail_remove_password_confirm": "Supprimer le mot de passe SMTP enregistré et désactiver la messagerie ?", + "settings.mail_password_removed": "Mot de passe SMTP supprimé et messagerie désactivée.", + "settings.mail_test_recipient_required": "Saisissez l’adresse e-mail du destinataire du test.", + "settings.mail_testing": "Envoi de l’e-mail de test…", + "settings.mail_test_ok": "E-mail de test envoyé.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Facultatif. Nécessaire uniquement pour récupérer soi-même le mot de passe.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail enregistré.", + "settings.send_password_reset": "Envoyer une réinitialisation", + "settings.user_reset_mail_not_configured": "Configurez et activez d’abord la messagerie.", + "settings.user_reset_email_missing": "Ajoutez d’abord une adresse e-mail.", + "settings.user_reset_confirm": "Envoyer un code de réinitialisation à {name} à l’adresse {email} ?", + "settings.user_reset_sent": "Code de réinitialisation envoyé à {email}.", + "audit.action.auth.password_reset_requested": "Réinitialisation du mot de passe demandée", + "audit.action.auth.password_reset_code_sent": "Code de réinitialisation envoyé", + "audit.action.auth.password_reset_completed": "Mot de passe réinitialisé", + "audit.action.auth.password_reset_failed": "Échec de la réinitialisation du mot de passe", + "audit.action.mail.settings_updated": "Paramètres de messagerie modifiés", + "audit.action.mail.test_sent": "E-mail de test envoyé", + "audit.action.mail.test_failed": "Échec de l’e-mail de test", + "audit.action.user.email_changed": "E-mail utilisateur modifié", + "audit.action.user.password_reset_sent": "Réinitialisation envoyée à l’utilisateur", + "audit.action.user.password_reset_failed": "Échec du reset du mot de passe utilisateur", + "audit.result.accepted": "accepté", + "audit.result.sent": "envoyé", + "audit.result.invalid_code": "code invalide", + "common.copy": "Copier", + "common.copied": "Copié", + "clients.use_panel_host": "Utiliser l’adresse du panneau", + "clients.use_panel_host_done": "Adresse du panneau insérée : {host}", + "clients.use_panel_host_failed": "Impossible de déterminer l’adresse du panneau depuis l’URL du navigateur.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS Let’s Encrypt intégré pour accéder directement à WGTools sans proxy inverse.", + "settings.https_disabled": "Désactivé", + "settings.https_enabled": "Activé", + "settings.https_enable": "Activer HTTPS intégré", + "settings.https_type": "Certificat pour", + "settings.https_domain": "Domaine", + "settings.https_public_ip": "IP publique", + "settings.https_target": "Domaine ou IP publique", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "Port HTTPS", + "settings.https_port80_note": "Le port TCP 80 doit être accessible depuis Internet pour émettre et renouveler le certificat. Ouvrez aussi le port HTTPS choisi pour le panneau.", + "settings.https_check_ports": "Vérifier les ports", + "settings.https_certificate": "Certificat", + "settings.https_certificate_ready": "Prêt", + "settings.https_certificate_missing": "Non émis", + "settings.https_expires": "Valable jusqu’au", + "settings.https_renewal": "Renouvellement automatique", + "settings.https_renewal_enabled": "Activé", + "settings.https_renewal_disabled": "Désactivé", + "settings.https_certificate_path": "Certificat", + "settings.https_private_key_path": "Clé privée", + "settings.https_issue": "Obtenir / renouveler le certificat", + "settings.https_port_free": "Libre", + "settings.https_port_busy": "Occupé", + "settings.https_ports_checked": "Vérification des ports terminée.", + "settings.https_target_email_required": "Saisissez le domaine ou l’IP publique et l’e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Demander ou renouveler le certificat Let’s Encrypt pour {target} ? Les paramètres HTTPS seront enregistrés. Le port TCP 80 doit être accessible depuis Internet.", + "settings.https_issuing": "Demande de certificat auprès de Let’s Encrypt…", + "settings.https_issue_ok": "Certificat prêt.", + "settings.https_already_enabled": "HTTPS intégré est déjà activé.", + "settings.https_already_disabled": "HTTPS intégré est déjà désactivé.", + "settings.https_enable_confirm": "Activer HTTPS intégré sur TCP {port} avec le chemin {path} ? WGTools redémarrera et la page se reconnectera à la nouvelle adresse.", + "settings.https_disable_confirm": "Désactiver HTTPS intégré et revenir à HTTP ?", + "settings.https_switching": "Activation HTTPS et redémarrage de WGTools…", + "settings.https_switching_http": "Désactivation HTTPS et redémarrage de WGTools…", + "audit.action.https.certificate_issued": "Certificat HTTPS émis", + "audit.action.https.certificate_failed": "Échec de la demande de certificat HTTPS", + "audit.action.https.enabled": "HTTPS activé", + "audit.action.https.disabled": "HTTPS désactivé", + "audit.result.issued": "émis", + "audit.result.enabled": "activé", + "audit.result.disabled": "désactivé", + "settings.https_access_path": "Chemin d’accès au panneau", + "settings.https_access_path_help": "Choisissez votre propre chemin. Avec HTTPS intégré, les requêtes hors de ce chemin obtiennent une erreur 404.", + "settings.https_enable_fields_required": "Saisissez domaine/IP publique, e-mail Let’s Encrypt et chemin du panneau.", + "settings.https_use_panel_host": "Utiliser l’adresse du panneau", + "settings.https_reconnecting": "WGTools passe à la nouvelle adresse HTTPS…", + "server.tab_nodes": "Nœuds", + "common.type": "Type", + "common.status": "État", + "common.copy_failed": "Copie impossible", + "clients.vpn_address": "Adresse VPN", + "nodes.title": "Nœuds WGTools", + "nodes.subtitle": "Reliez plusieurs serveurs WGTools dans un réseau protégé et publiez uniquement les réseaux accessibles aux autres nœuds.", + "nodes.enable_hub": "Activer le HUB", + "nodes.connect_hub": "Se connecter au HUB", + "nodes.settings": "Paramètres des nœuds", + "nodes.settings_action": "Paramètres", + "nodes.sync_now": "Synchroniser", + "nodes.disable": "Désactiver les nœuds", + "nodes.disable_action": "Déconnecter", + "nodes.join_title": "Connecter de nouveaux nœuds", + "nodes.join_help": "Créez un code à usage unique et saisissez-le sur un autre panneau WGTools avec l’endpoint du HUB, par ex. vpn.example.com:51950. Le code est valable 15 minutes et une seule fois.", + "nodes.create_code": "Créer un code", + "nodes.connected_nodes": "Nœuds connectés", + "nodes.connected_nodes_help": "Informations sur les autres panneaux, réseaux publiés et clients. Les clients distants sont en lecture seule.", + "nodes.enable_hub_help": "Ce panneau devient le nœud central. Le même port accueille WireGuard en UDP et l’appairage initial sécurisé en TCP.", + "nodes.node_name": "Nom du nœud", + "nodes.transport_network": "Réseau de transport des nœuds", + "nodes.transport_help": "Réseau privé distinct réservé au transport entre WGTools. Il ne doit pas chevaucher vos réseaux VPN/LAN.", + "nodes.panel_url": "URL du panneau", + "nodes.panel_url_help": "Facultatif. Simple lien informatif du bouton « Ouvrir le panneau » sur les autres nœuds ; non utilisé pour la connexion Nodes.", + "nodes.extra_networks": "Réseaux de nœud supplémentaires", + "nodes.extra_networks_help": "Un réseau par ligne. Les réseaux VPN et les réseaux distants Site-to-site sont publiés automatiquement. Ajoutez seulement les autres LAN/réseaux routés, par ex. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools préremplit les réseaux VPN, Site-to-site et LAN routés détectés. Gardez uniquement les réseaux à publier. Un réseau par ligne.", + "nodes.published_networks_settings_help": "Un réseau par ligne. Liste explicite des réseaux publiés par ce nœud. Retirer une ligne cesse d’annoncer ce réseau aux autres nœuds.", + "nodes.available_networks_help": "Réseaux actuellement détectés : {networks}. Les nouveaux réseaux ne sont pas publiés automatiquement ; ajoutez ceux souhaités ci-dessus.", + "nodes.available_networks_none": "Aucun réseau local supplémentaire détecté.", + "nodes.connect_help": "Saisissez l’endpoint du HUB et le code à usage unique. L’URL, le port HTTPS, le certificat et le chemin privé du panneau ne servent pas à l’appairage.", + "nodes.join_code": "Code de connexion", + "nodes.connect_reachability_note": "L’appairage initial utilise TCP sécurisé sur le port indiqué. Une fois wgnode0 créé, réseaux, état, versions et données client en lecture seule se synchronisent avec le HUB via l’adresse WireGuard interne.", + "nodes.connect": "Connecter", + "nodes.settings_help": "Nom du nœud, lien « Ouvrir le panneau » facultatif et liste des réseaux publiés. L’URL du panneau n’est utilisée ni pour l’appairage ni pour la synchronisation.", + "nodes.details": "Détails", + "nodes.not_configured": "WGTools Nodes non configuré", + "nodes.not_configured_help": "Activez le HUB sur ce panneau ou connectez-le à un HUB WGTools existant.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connecté au HUB", + "nodes.mode_none": "Non configuré", + "nodes.role": "Rôle", + "nodes.tunnel": "Tunnel du nœud", + "nodes.node_ip": "Adresse du nœud", + "nodes.endpoint": "Endpoint du HUB", + "nodes.published_networks": "Réseaux publiés", + "nodes.last_sync": "Dernière synchronisation", + "nodes.no_nodes_hub": "Aucun nœud connecté. Créez un code et utilisez-le sur un autre panneau WGTools.", + "nodes.no_nodes_spoke": "Aucune information reçue sur les nœuds distants.", + "nodes.clients_short": "Clients", + "nodes.open_panel": "Ouvrir le panneau", + "nodes.route_conflict": "Conflit de routage", + "nodes.no_published_networks": "Aucun réseau publié", + "nodes.load_failed": "Impossible de charger WGTools Nodes", + "nodes.enable_hub_confirm": "Activer le HUB WGTools et créer le tunnel WireGuard interne ?", + "nodes.applying": "Configuration du tunnel WGTools Nodes…", + "nodes.enable_failed": "Impossible d’activer le HUB", + "nodes.hub_enabled": "HUB WGTools activé", + "nodes.connecting": "Vérification du code HUB et création du tunnel sécurisé…", + "nodes.connect_failed": "Impossible de se connecter au HUB", + "nodes.connected": "Connecté au HUB WGTools", + "nodes.settings_failed": "Impossible d’enregistrer les paramètres du nœud", + "nodes.settings_saved": "Paramètres du nœud enregistrés", + "nodes.code_failed": "Impossible de créer le code de connexion", + "nodes.code_expires": "Code à usage unique. Valable jusqu’à {time}.", + "nodes.code_copied": "Code de connexion copié", + "nodes.network_vpn": "Clients VPN", + "nodes.network_site_to_site": "Réseau Site-to-site", + "nodes.network_custom": "Réseau supplémentaire", + "nodes.conflict": "Conflit", + "nodes.remote_clients": "Clients (lecture seule)", + "nodes.no_clients": "Aucun client signalé par ce nœud", + "nodes.details_failed": "Impossible de charger les détails du nœud", + "nodes.remove_confirm": "Retirer le nœud « {name} » du HUB ? Son accès au tunnel interne sera révoqué.", + "nodes.remove_failed": "Impossible de retirer le nœud", + "nodes.removed": "Nœud retiré", + "nodes.disable_hub_confirm": "Désactiver le HUB et déconnecter tous les nœuds WGTools ? Le tunnel interne sera supprimé.", + "nodes.disconnect_confirm": "Déconnecter ce panneau WGTools du HUB et supprimer le tunnel interne ?", + "nodes.disable_failed": "Impossible de désactiver WGTools Nodes", + "nodes.disabled": "WGTools Nodes désactivé", + "nodes.sync_failed": "Échec de synchronisation des nœuds", + "nodes.synced": "Informations des nœuds synchronisées", + "nodes.service_port": "Port Nodes", + "nodes.service_port_help": "Le même numéro de port sert simultanément à WireGuard en UDP et à l’appairage initial protégé en TCP.", + "nodes.hub_port_forward_note": "Si le HUB est derrière un NAT, redirigez le même port en UDP et TCP vers lui. Le port web WGTools, HTTPS et le chemin privé sont indépendants de Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Domaine/IP et port Nodes sans http:// ni https://, par ex. vpn.example.com:51950.", + "settings.collapse_sidebar": "Réduire la barre latérale", + "settings.expand_sidebar": "Développer la barre latérale", + "settings.https_issue_fields_required": "Saisissez domaine/IP publique, e-mail Let’s Encrypt et chemin du panneau.", + "settings.https_issue_ok_saved": "Certificat prêt et paramètres HTTPS enregistrés.", + "settings.https_enable_need_certificate": "Obtenez d’abord un certificat.", + "settings.https_enable_certificate_mismatch": "Obtenez d’abord un certificat pour le domaine ou l’IP actuel.", + "settings.https_enable_certificate_expired": "Certificat expiré. Renouvelez-le avant d’activer HTTPS.", + "settings.https_enable_certificate_ready": "Certificat prêt : HTTPS intégré peut être activé.", + "settings.https_enable_active_help": "Décochez puis enregistrez pour revenir à HTTP.", + "settings.https_certificate_expired": "Expiré", + "settings.https_certificate_wrong_target": "Pour une autre adresse", + "nodes.network_conflict_error": "Les réseaux publiés chevauchent un autre nœud ou le réseau de transport Nodes : {conflicts}. Supprimez ou modifiez le réseau concerné.", + "nodes.networks_changed": "Les réseaux détectés ont changé depuis l’enregistrement. Nouveaux : {added}. Plus détectés : {removed}. Vérifiez puis enregistrez la liste publiée.", + "nodes.review_networks": "Vérifier les réseaux", + "nodes.vpn_pool_mismatch": "Pool VPN modifié : Nodes publie encore {old}, alors que le pool actuel est {current}. Ouvrez les paramètres et mettez à jour les réseaux publiés.", + "server.error_vpn_network_invalid": "Le réseau VPN doit être une adresse réseau IPv4 valide, par ex. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Seuls les réseaux VPN IPv4 sont pris en charge.", + "server.error_vpn_network_too_small": "Le réseau VPN doit contenir au moins deux adresses utilisables.", + "server.error_vpn_network_no_hosts": "Le réseau VPN choisi n’a aucune adresse serveur utilisable.", + "server.error_server_address_prefix": "L’adresse VPN du serveur doit inclure un préfixe, par ex. 10.0.0.1/24.", + "server.error_server_address_network": "L’adresse VPN du serveur doit appartenir au pool choisi et utiliser le même préfixe.", + "server.error_server_address_reserved": "L’adresse VPN du serveur ne peut être celle du réseau ni celle de diffusion.", + "server.error_listen_port_number": "Le port WireGuard doit être un nombre.", + "server.error_listen_port_range": "Le port WireGuard doit être compris entre 1 et 65535.", + "server.error_mtu_number": "Le MTU doit être un nombre.", + "auth.mfa_title": "Authentification à deux facteurs", + "auth.mfa_login_help": "Saisissez le code à 6 chiffres de Google Authenticator ou un code de récupération.", + "auth.mfa_code": "Code d’authentification", + "auth.mfa_verify": "Vérifier et se connecter", + "auth.mfa_back": "Retour au mot de passe", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Authentification à deux facteurs (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Activé", + "settings.mfa_disabled": "Désactivé", + "settings.mfa_google_help": "Protégez ce compte avec Google Authenticator ou une application TOTP. Votre mot de passe actuel est requis pour commencer.", + "settings.current_password": "Mot de passe actuel", + "settings.mfa_start": "Configurer Google Authenticator", + "settings.mfa_secret": "Clé de configuration manuelle", + "settings.mfa_scan_help": "Scannez le QR avec Google Authenticator puis saisissez le code actuel à 6 chiffres pour activer MFA.", + "settings.mfa_code": "Code à 6 chiffres", + "settings.mfa_enable": "Activer MFA", + "settings.mfa_manage_help": "Pour modifier MFA, saisissez le mot de passe actuel et un code Authenticator ou de récupération.", + "settings.mfa_code_or_recovery": "Code Authenticator ou de récupération", + "settings.mfa_regenerate": "Nouveaux codes de récupération", + "settings.mfa_disable": "Désactiver MFA", + "settings.mfa_recovery_title": "Codes de récupération", + "settings.mfa_recovery_help": "Enregistrez ces codes maintenant. Chacun sert une seule fois si Google Authenticator est indisponible. Ils ne seront plus affichés.", + "settings.mfa_recovery_remaining": "Codes de récupération restants : {count}", + "settings.mfa_enabled_ok": "MFA activée.", + "settings.mfa_disabled_ok": "MFA désactivée.", + "settings.mfa_disable_confirm": "Désactiver l’authentification à deux facteurs pour ce compte ?", + "settings.mfa_regenerate_confirm": "Remplacer tous les codes de récupération existants ?", + "settings.mfa_recovery_regenerated": "Nouveaux codes de récupération générés.", + "audit.action.auth.mfa_failed": "Échec de la vérification MFA", + "audit.action.auth.mfa_recovery_used": "Code de récupération MFA utilisé", + "audit.action.user.mfa_setup_started": "Configuration MFA démarrée", + "audit.action.user.mfa_enabled": "MFA activée", + "audit.action.user.mfa_disabled": "MFA désactivée", + "audit.action.user.mfa_disabled_cli": "MFA désactivée via CLI", + "audit.action.user.mfa_recovery_regenerated": "Codes de récupération MFA régénérés", + "settings.mfa_error_password": "Mot de passe actuel incorrect.", + "settings.mfa_error_code": "Code d’authentification invalide.", + "settings.mfa_error_already_enabled": "MFA est déjà activée.", + "settings.mfa_error_not_enabled": "MFA n’est pas activée.", + "settings.mfa_error_not_started": "Recommencez la configuration MFA.", + "trace.title": "Traceroute, ping et carte de l’itinéraire", + "trace.subtitle": "Mesurez la latence vers un VPS ou un autre serveur et repérez les retards sur le trajet.", + "trace.target": "IP ou nom d’hôte du serveur", + "trace.show_map": "Afficher le trajet sur la carte", + "trace.run": "Lancer le traceroute", + "trace.geo_note": "La géolocalisation est approximative. Si la carte est activée, les IP publiques des sauts sont envoyées à ipwho.is ; les tuiles proviennent d’OpenStreetMap.", + "trace.latency_note": "Traceroute mesure la latence en millisecondes, pas le débit en Mbit/s.", + "trace.map": "Carte de l’itinéraire", + "trace.map_hint": "Carte interactive : faites glisser, zoomez avec la molette ou +/− et cliquez sur un saut pour plus de détails.", + "trace.hop": "Saut / IP", + "trace.location": "Emplacement", + "trace.avg_rtt": "RTT moyen", + "trace.delta": "Δ RTT", + "trace.loss": "Perte", + "trace.summary_target": "Cible", + "trace.summary_ping": "Ping moyen", + "trace.summary_loss": "Perte de ping", + "trace.summary_hops": "Sauts", + "trace.no_reply": "Aucune réponse", + "trace.private": "Réseau privé", + "trace.unknown": "Inconnu", + "trace.running": "Ping et traceroute en cours… Cela peut prendre une minute.", + "trace.done": "Analyse du réseau terminée.", + "trace.failed": "Échec de l’analyse du réseau", + "trace.partial_geo": "Certains sauts publics n’ont pas pu être géolocalisés.", + "trace.not_reached": "La cible n’a pas été atteinte par traceroute.", + "trace.reached": "Cible atteinte", + "trace.ms": "ms", + "server.tab_trace": "Traçage", + "trace.map_controls": "Commandes de carte", + "trace.zoom_in": "Zoom avant", + "trace.zoom_out": "Zoom arrière", + "trace.fit_route": "Afficher tout le trajet", + "trace.fit": "Ajuster", + "trace.map_click_hint": "Cliquez sur un saut pour consulter l’IP, l’emplacement, l’ASN et le RTT.", + "trace.route_path": "Trajet", + "trace.ping_ok_trace_filtered": "La cible répond au ping, mais les derniers sauts traceroute ne répondent pas.", + "trace.latency_legend": "Augmentation de la latence entre sauts répondants", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normal", + "trace.latency_warn": "Δ RTT 5–20 ms — accru", + "trace.latency_bad": "Δ RTT > 20 ms — forte hausse" +} diff --git a/app/static/locales/it.json b/app/static/locales/it.json new file mode 100644 index 0000000..885d3f8 --- /dev/null +++ b/app/static/locales/it.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Crea utente", + "auth.login_subtitle": "Inserisci nome utente e password WGTools.", + "auth.login_title": "Accedi a WGTools", + "auth.password": "Password", + "auth.password_repeat": "Ripeti la password", + "auth.setup_help": "Il primo account ha accesso completo a WGTools. Puoi creare altri utenti in seguito nelle impostazioni.", + "auth.setup_subtitle": "Per gestire il server è necessario prima creare un account WGTools.", + "auth.setup_title": "Crea il primo utente", + "auth.sign_in": "Accedi", + "auth.sign_out": "Esci", + "auth.username": "Nome utente", + "clients.actions": "Azioni", + "clients.add": "+ Aggiungi client", + "clients.address": "Indirizzo VPN", + "clients.address_hint": "Il primo indirizzo libero viene suggerito automaticamente.", + "clients.allowed_ips_required": "Inserisci almeno una rete AllowedIPs per la configurazione client.", + "clients.basic_connection": "Impostazioni connessione", + "clients.basic_details": "Client", + "clients.client": "Client", + "clients.client_allowed_ips": "AllowedIPs nella configurazione client", + "clients.config_private_warning": "Questa configurazione contiene la chiave privata del client. Conservala al sicuro.", + "clients.config_title": "Configurazione client", + "clients.config_unavailable": "Configurazione non disponibile", + "clients.connection_direct": "Direttamente a WGTools", + "clients.connection_path": "Percorso di connessione", + "clients.connection_relay": "Relay VPS", + "clients.connection_via": "Connetti tramite", + "clients.connection_via_hint": "Scegli l’accesso pubblico usato dal client. Il Relay appare solo se installato per l’interfaccia WireGuard scelta.", + "clients.copy_config": "Copia", + "clients.copy_done": "Configurazione copiata", + "clients.create_subtitle": "Crea un peer WireGuard e genera la configurazione client.", + "clients.create_title": "Crea client", + "clients.creating": "Creazione chiavi e applicazione client…", + "clients.day_fri": "Ven", + "clients.day_mon": "Lun", + "clients.day_sat": "Sab", + "clients.day_sun": "Dom", + "clients.day_thu": "Gio", + "clients.day_tue": "Mar", + "clients.day_wed": "Mer", + "clients.delete_confirm": "Eliminare questo client da WireGuard? WGTools creerà un backup e rimuoverà le regole automatiche associate.", + "clients.deleted": "Client eliminato", + "clients.dns": "DNS (facoltativo)", + "clients.dns_hint": "Server DNS IPv4 separati da virgole.", + "clients.download_config": "Scarica .conf", + "clients.duplicate": "Duplica", + "clients.duplicate_address_error": "Questo indirizzo VPN è già usato da un altro peer.", + "clients.duplicate_name_error": "Esiste già un peer con questo nome.", + "clients.duplicate_ready": "Copia pronta. WGTools ha assegnato un nuovo nome e indirizzo VPN. Controlla le impostazioni prima di salvare.", + "clients.duplicate_site_hint": "Le reti remote sono state rimosse per evitare route duplicate. Inserisci le reti del nuovo peer Site-to-site.", + "clients.duplicate_suffix": "copia", + "clients.edit_subtitle": "Aggiorna il peer sul server. Le modifiche vengono applicate senza riavviare WireGuard.", + "clients.edit_title": "Modifica client", + "clients.endpoint": "Endpoint server", + "clients.endpoint_hint": "Per i client remoti usa l’IP pubblico o dominio che inoltra la porta WireGuard a questo server.", + "clients.existing": "Peer esistente", + "clients.expiration": "Durata accesso", + "clients.expiration_action": "Alla scadenza", + "clients.expiration_action_hint": "Se deselezionato, il client resta in WGTools ma l’accesso WireGuard viene disabilitato. Scegli una nuova scadenza o Nessuna scadenza e salva per riattivarlo.", + "clients.expiration_datetime": "Scade il", + "clients.expiration_datetime_hint": "Usa data e ora locali di questo browser.", + "clients.expiration_delete": "Elimina client", + "clients.expiration_future_required": "Scegli una data e ora future.", + "clients.expiration_hint": "Alla scadenza WGTools esegue l’azione selezionata al minuto successivo. Prima crea un backup WireGuard.", + "clients.expire_1d": "1 giorno", + "clients.expire_1h": "1 ora", + "clients.expire_3h": "3 ore", + "clients.expire_6h": "6 ore", + "clients.expire_custom": "Data e ora personalizzate", + "clients.expire_never": "Nessuna scadenza", + "clients.expired": "Scaduto", + "clients.expired_disabled_hint": "L’accesso è scaduto. Il client è conservato, ma WireGuard è disabilitato. Scegli una nuova durata o Nessuna scadenza e salva.", + "clients.expired_disabled_short": "Scaduto · disabilitato", + "clients.expired_disabled_status": "Scaduto", + "clients.expires_days": "Scade tra {n} g", + "clients.expires_hours": "Scade tra {n} h", + "clients.expires_minutes": "Scade tra {n} min", + "clients.generated_config": "Configurazione client generata", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 secondi è un buon valore predefinito per client dietro NAT.", + "clients.local_access_exceptions": "Indirizzi locali consentiti", + "clients.local_access_exceptions_hint": "IP o CIDR facoltativi raggiungibili anche quando la rete locale o Site-to-site è bloccata. Separa con virgole.", + "clients.managed": "Gestito da WGTools", + "clients.name": "Nome", + "clients.no_peers": "Nessun peer trovato", + "clients.peers": "Peer", + "clients.peers_subtitle": "Le modifiche vengono salvate e applicate con wg syncconf senza riavviare l’interfaccia WireGuard.", + "clients.protected_networks_reference": "Reti locali bloccate (riferimento)", + "clients.protected_networks_reference_hint": "Queste reti non sono scritte in AllowedIPs. L’accesso è bloccato dai criteri server WGTools; puoi consentire singoli indirizzi sopra.", + "clients.psk": "Chiave precondivisa (PSK)", + "clients.psk_enable": "Usa una chiave WireGuard precondivisa aggiuntiva", + "clients.psk_hint": "Consigliato. Aggiunge un segreto simmetrico all’handshake WireGuard. I client standard lo supportano; WGTools inserisce il PSK nella configurazione e nel QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generazione QR…", + "clients.quick_search": "Ricerca rapida", + "clients.quick_search_clear": "Cancella ricerca", + "clients.quick_search_empty": "Nessun client corrispondente", + "clients.relay_endpoint_note": "La configurazione generata si connetterà a {endpoint}. Il server WireGuard resta su questo host WGTools.", + "clients.relay_required": "Scegli un Relay VPS per questo client.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "non disponibile", + "clients.relay_vps": "Relay VPS", + "clients.relay_vps_hint": "L’endpoint del client viene generato automaticamente da questo Relay.", + "clients.remote_hint": "Reti dietro questo peer. Una per riga o separate da virgole.", + "clients.remote_networks": "Reti remote", + "clients.remote_required": "Inserisci almeno una rete remota per il peer Site-to-site.", + "clients.required": "Nome e indirizzo VPN sono obbligatori.", + "clients.route_custom": "Personalizzato", + "clients.route_full": "Tunnel completo", + "clients.route_full_except_local": "Tunnel completo eccetto reti locali", + "clients.route_hint": "Solo queste reti vengono inserite in AllowedIPs della configurazione client.", + "clients.route_preset": "Traffico tramite VPN", + "clients.route_vpn": "Solo rete VPN", + "clients.route_vpn_lan": "VPN + LAN locale", + "clients.saved": "Client salvato", + "clients.schedule_blocked_short": "Pianificazione · bloccato", + "clients.schedule_blocked_status": "Bloccato dalla pianificazione", + "clients.schedule_days": "Giorni consentiti", + "clients.schedule_days_required": "Scegli almeno un giorno per la pianificazione.", + "clients.schedule_disabled_hint": "Questo client è bloccato dalla pianificazione. WGTools ripristinerà automaticamente il peer al prossimo intervallo consentito.", + "clients.schedule_enable": "Limita accesso con pianificazione", + "clients.schedule_from": "Accesso dalle", + "clients.schedule_hint": "WGTools può disabilitare e riattivare il client nei giorni e orari scelti senza cambiarne la configurazione.", + "clients.schedule_short": "Pianificazione", + "clients.schedule_time_required": "Imposta ora di inizio e fine della pianificazione.", + "clients.schedule_timezone_hint": "La pianificazione usa l’ora locale del server WireGuard. Sono supportati intervalli notturni come 22:00–06:00.", + "clients.schedule_title": "Pianificazione accesso", + "clients.schedule_to": "Accesso fino alle", + "clients.security_access": "Sicurezza e orari di accesso", + "clients.server_host": "Indirizzo / dominio server", + "clients.server_host_hint": "IP pubblico o dominio usato dal client. I valori inseriti in precedenza sono suggeriti.", + "clients.server_host_required": "L’indirizzo / dominio server è obbligatorio per generare la configurazione.", + "clients.server_peer": "Peer server", + "clients.server_port": "Porta WireGuard", + "clients.server_port_hint": "Preso automaticamente dalla configurazione server.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Stato", + "clients.subtitle": "Peer WireGuard, stato in tempo reale e gestione configurazioni client.", + "clients.tab_basic": "Base", + "clients.tab_config": "Configurazione", + "clients.tab_policy": "Criteri", + "clients.tab_security": "Sicurezza", + "clients.title": "Client", + "clients.type": "Tipo", + "clients.unmanaged_note": "Questo peer esisteva prima di WGTools. La sua chiave privata non può essere recuperata. WGTools può modificare il peer server ma non può generarne configurazione client o QR.", + "clients.updating": "Aggiornamento client…", + "common.actions": "Azioni", + "common.ago": "fa", + "common.cancel": "Annulla", + "common.checking": "Verifica…", + "common.close": "Chiudi", + "common.config": "Configurazione", + "common.delete": "Elimina", + "common.disabled": "Disabilitato", + "common.edit": "Modifica", + "common.enabled": "Abilitato", + "common.loading": "Caricamento…", + "common.never": "Mai", + "common.no": "No", + "common.not_configured": "Non configurato", + "common.not_installed": "Non installato", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Aggiorna", + "common.running": "In esecuzione", + "common.save": "Salva", + "common.stopped": "Arrestato", + "common.total": "Totale", + "common.unknown": "Sconosciuto", + "common.updated": "Aggiornato", + "common.yes": "Sì", + "dashboard.active_peers": "Peer attivi", + "dashboard.active_peers_subtitle": "Dati in tempo reale da wg show.", + "dashboard.activity": "Panoramica del sistema", + "dashboard.activity_subtitle": "Controlli in sola lettura sul sistema WireGuard attivo.", + "dashboard.cores": "core", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Ultime 24 ore", + "dashboard.history_avg": "Media", + "dashboard.history_max": "Max", + "dashboard.history_min": "Min", + "dashboard.history_now": "ora", + "dashboard.memory": "Memoria", + "dashboard.network": "Rete", + "dashboard.peers": "Peer", + "dashboard.quick_search": "Ricerca rapida", + "dashboard.quick_search_clear": "Cancella ricerca", + "dashboard.quick_search_empty": "Nessun peer corrisponde alla ricerca", + "dashboard.restart": "Riavvia", + "dashboard.restart_confirm": "Riavviare WireGuard? I client VPN attivi si riconnetteranno automaticamente.", + "dashboard.restart_ok": "WireGuard riavviato.", + "dashboard.routing": "Instradamento", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Avvia", + "dashboard.start_ok": "WireGuard avviato.", + "dashboard.stop": "Arresta", + "dashboard.stop_confirm": "Arrestare WireGuard? I client VPN attivi verranno disconnessi.", + "dashboard.stop_ok": "WireGuard arrestato.", + "dashboard.subtitle": "Stato del server WireGuard, peer e traffico in tempo reale.", + "dashboard.title": "Panoramica", + "dashboard.traffic": "Traffico", + "dashboard.uptime": "Tempo di attività", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Criteri di accesso al server", + "groups.additional_allowed": "Indirizzi consentiti aggiuntivi", + "groups.additional_blocked": "Indirizzi bloccati aggiuntivi", + "groups.allow": "Consenti", + "groups.allowed": "Consentito", + "groups.allowed_addresses": "Indirizzi / reti consentiti", + "groups.apply_current_template": "Applica modello corrente del gruppo", + "groups.apply_defaults": "Applica modello corrente del gruppo", + "groups.apply_defaults_hint": "Copia route, DNS e Keepalive del gruppo in questo client. Salva il client, poi genera una nuova configurazione o QR se necessario.", + "groups.basic": "Informazioni di base", + "groups.block": "Blocca", + "groups.blocked": "Bloccato", + "groups.blocked_addresses": "Indirizzi / reti bloccati", + "groups.client_config_source": "Origine configurazione client", + "groups.client_defaults": "Valori predefiniti client", + "groups.client_group_hint": "Gruppo facoltativo per riutilizzare criteri di accesso e valori predefiniti. I gruppi appartengono all’interfaccia WireGuard selezionata.", + "groups.config_differs": "La configurazione del client differisce dai valori del gruppo. I criteri server sono aggiornati, ma telefono o PC cambieranno solo dopo un nuovo file o QR.", + "groups.config_differs_short": "Configurazione client diversa dal gruppo", + "groups.create": "Crea gruppo", + "groups.create_title": "Crea gruppo", + "groups.created": "Gruppo creato", + "groups.creating": "Creazione gruppo…", + "groups.defaults_applied": "Modello del gruppo applicato. Salva il client per mantenere le modifiche.", + "groups.defaults_hint": "Definisce il traffico inviato dal client tramite WireGuard. I criteri server definiscono separatamente cosa può raggiungere. Le modifiche al modello non cambiano i file già installati.", + "groups.delete_message": "Eliminare “{name}”? Le configurazioni dei client non vengono mai eliminate insieme al gruppo.", + "groups.delete_move": "Sposta i client in un altro gruppo", + "groups.delete_title": "Elimina gruppo client", + "groups.delete_unassign": "Rimuovi assegnazione del gruppo dai client", + "groups.deleted": "Gruppo eliminato", + "groups.deleting": "Aggiornamento client ed eliminazione gruppo…", + "groups.description": "Descrizione", + "groups.edit_title": "Modifica gruppo", + "groups.editor_subtitle": "Un gruppo combina criteri di accesso server attivi e un modello per le configurazioni client.", + "groups.effective_allow": "Eccezioni consentite", + "groups.effective_deny": "Eccezioni bloccate", + "groups.effective_policy": "Criteri server effettivi", + "groups.empty": "Non ci sono gruppi client. Creane uno per riutilizzare criteri di accesso e valori predefiniti.", + "groups.group": "Gruppo", + "groups.inherit": "Eredita", + "groups.internet_access": "Accesso a Internet", + "groups.internet_short": "Internet", + "groups.local_access": "Reti locali", + "groups.local_short": "Locale", + "groups.manage": "Gruppi", + "groups.members_count": "{count} client", + "groups.name": "Nome", + "groups.name_required": "Il nome del gruppo è obbligatorio.", + "groups.new_client_defaults": "Modello configurazione client", + "groups.new_clients_short": "Nuovi client", + "groups.no_group": "Nessun gruppo", + "groups.none": "Nessuno", + "groups.override_client_config": "Sovrascrivi il modello client del gruppo per questo client", + "groups.override_client_config_hint": "Disattivato: route, DNS e Keepalive dal gruppo. Attivato: il client usa valori propri. Le eccezioni dei criteri server restano indipendenti.", + "groups.policy_addresses_hint": "Indirizzi IPv4 o CIDR separati da virgole. Le eccezioni client hanno precedenza sulle eccezioni del gruppo.", + "groups.policy_custom": "Criteri personalizzati", + "groups.policy_inherit": "Usa criteri del gruppo", + "groups.policy_mode": "Origine criteri", + "groups.policy_mode_hint": "I criteri di gruppo si ereditano per impostazione predefinita. Le eccezioni client non modificano il gruppo.", + "groups.routes_required": "Le route client non possono essere vuote.", + "groups.subtitle": "Riutilizza criteri di accesso server e valori predefiniti per i client dell’interfaccia WireGuard selezionata.", + "groups.title": "Gruppi client", + "groups.traffic_through_vpn": "Traffico tramite VPN", + "groups.updated": "Gruppo aggiornato", + "groups.updating": "Aggiornamento criteri gruppo…", + "help.example_note": "Gli indirizzi, le interfacce, i nomi dei peer e i domini degli esempi sono fittizi. Sostituiscili con i dati della tua rete.", + "help.navigation": "Navigazione della guida", + "help.open": "Apri la guida", + "help.subtitle": "Guida semplice per Dashboard, Server, Client e Impostazioni con brevi esempi pratici.", + "help.title": "Guida WGTools", + "interfaces.add": "+ Aggiungi interfaccia", + "interfaces.create": "Crea interfaccia", + "interfaces.create_confirm": "Creare e avviare l’interfaccia {name}?", + "interfaces.create_failed": "Impossibile creare l’interfaccia", + "interfaces.create_hint": "Prima di creare la configurazione, WGTools verifica che rete VPN, porta UDP e tabella di routing non siano in conflitto con altre interfacce WireGuard.", + "interfaces.create_subtitle": "Crea un’interfaccia WireGuard indipendente con pool di indirizzi, porta UDP e impostazioni di routing propri.", + "interfaces.create_title": "Aggiungi interfaccia WireGuard", + "interfaces.created": "Interfaccia creata correttamente.", + "interfaces.creating": "Generazione chiavi, scrittura configurazione e avvio di WireGuard…", + "interfaces.current": "Attuale", + "interfaces.delete": "Elimina", + "interfaces.delete_confirm": "Eliminare l’interfaccia {name}? La configurazione WireGuard e tutti i peer saranno rimossi. Prima viene creato un backup.", + "interfaces.delete_failed": "Impossibile eliminare l’interfaccia", + "interfaces.delete_last": "Non puoi eliminare qui l’ultima interfaccia WireGuard configurata.", + "interfaces.delete_tooltip": "Elimina questa interfaccia WireGuard", + "interfaces.deleted": "Interfaccia eliminata. Backup: {backup}", + "interfaces.deleting": "Arresto WireGuard ed eliminazione interfaccia…", + "interfaces.display_name": "Nome visualizzato", + "interfaces.display_name_edit_hint": "Solo nome visualizzato: il nome dell’interfaccia Linux non cambia.", + "interfaces.display_name_hint": "Nome facoltativo, ad es. Lavoro o Collaboratori.", + "interfaces.identity": "Identità interfaccia", + "interfaces.none": "Nessuna interfaccia WireGuard trovata", + "interfaces.none_configured": "Nessuna interfaccia WireGuard configurata.", + "interfaces.peers_short": "peer", + "interfaces.rename_failed": "Impossibile salvare il nome visualizzato dell’interfaccia.", + "interfaces.select": "Seleziona", + "interfaces.subtitle": "Ogni interfaccia ha rete VPN, porta, peer e criteri propri. Selezionane una per gestirla in WGTools.", + "interfaces.switch_title": "Interfacce WireGuard", + "interfaces.system_name": "Nome di sistema", + "interfaces.system_name_hint": "Nome interfaccia Linux, ad es. wg1. Non modificabile dopo la creazione.", + "interfaces.title": "Interfacce WireGuard", + "interfaces.unique_port_hint": "Ogni interfaccia WireGuard sul server deve usare una porta UDP distinta.", + "interfaces.unique_table_hint": "WGTools consiglia una tabella di routing separata per ogni interfaccia. Lascia vuoto per il routing normale.", + "nav.clients": "Client", + "nav.dashboard": "Panoramica", + "nav.server": "Server", + "nav.settings": "Impostazioni", + "server.access_apply_confirm": "Salvare e applicare la regola firewall? WireGuard verrà riavviato brevemente dopo un backup.", + "server.access_rule_deleted": "Regola di accesso eliminata.", + "server.access_rule_help": "Crea una regola di accesso FORWARD senza modificare i comandi iptables manualmente.", + "server.access_rule_order_hint": "WGTools inserisce le regole all’inizio di FORWARD affinché quelle restrittive precedano le regole VPN ACCEPT generali.", + "server.access_rule_saved": "Regola di accesso salvata e applicata.", + "server.action": "Azione", + "server.action_hint": "REJECT comunica al client il rifiuto; DROP scarta senza risposta; ACCEPT consente esplicitamente.", + "server.add_access_rule": "Aggiungi regola di accesso", + "server.add_route": "Aggiungi route", + "server.address": "Indirizzo", + "server.any": "Qualsiasi", + "server.any_protocol": "Qualsiasi", + "server.apply_confirm": "Salvare e applicare le impostazioni server? WireGuard verrà riavviato brevemente. WGTools crea un backup e ripristina automaticamente la configurazione se l’avvio fallisce.", + "server.apply_settings": "Salva e applica", + "server.applying_rule": "Creazione backup e applicazione…", + "server.applying_settings": "Convalida impostazioni, creazione backup e applicazione…", + "server.basic_settings": "Impostazioni di base", + "server.config_tab_help": "Apri editor della configurazione grezza dell’interfaccia WireGuard scelta.", + "server.create_confirm": "Creare e avviare il server WireGuard con queste impostazioni?", + "server.create_server": "Crea server", + "server.create_step_conf": "Crea configurazione dell’interfaccia WireGuard con permessi 600.", + "server.create_step_forward": "Configura forwarding, NAT e routing per policy opzionale.", + "server.create_step_key": "Genera nuova coppia di chiavi server.", + "server.create_step_start": "Abilita e avvia l’interfaccia wg-quick scelta.", + "server.create_subtitle": "WireGuard è installato, ma l’interfaccia selezionata non è configurata.", + "server.create_success": "Server WireGuard creato correttamente.", + "server.create_title": "Crea server WireGuard", + "server.creating": "Generazione chiavi, scrittura configurazione e avvio WireGuard…", + "server.custom_preserved": "Restano invariati blocchi peer, route Site-to-site e regole PostUp/PostDown personalizzate non gestite qui.", + "server.delete_access_confirm": "Eliminare questa regola di accesso e applicare?", + "server.delete_route_confirm": "Eliminare questa route personalizzata e applicare?", + "server.destination": "Destinazione", + "server.destination_hint": "Vuoto = qualsiasi. Accetta IP, CIDR o intervallo IP. Separa più destinazioni con virgole.", + "server.destination_port": "Porta destinazione", + "server.destination_port_hint": "Facoltativo. Porta come 443 o intervallo 10000:20000. Prima scegli TCP o UDP.", + "server.details": "Dettagli", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostica", + "server.diagnostics_done": "Diagnostica completata", + "server.diagnostics_subtitle": "Controlli correnti del sistema. Nessuna modifica alla configurazione.", + "server.direction": "Hook", + "server.edit_access_rule": "Modifica regola di accesso", + "server.edit_route": "Modifica route", + "server.edit_server": "Modifica server", + "server.edit_subtitle": "Modifica impostazioni comuni WireGuard, routing e NAT. Peer e regole personalizzate esistenti vengono mantenuti.", + "server.edit_title": "Impostazioni server", + "server.edit_warning": "Applicare impostazioni di interfaccia, routing o firewall riavvia brevemente WireGuard. I peer attivi si ricollegano da soli.", + "server.enable_forwarding": "Abilita forwarding IPv4", + "server.enable_nat": "Abilita NAT / Masquerade", + "server.firewall": "Firewall e NAT", + "server.firewall_subtitle": "Regole rilevate dagli hook WireGuard.", + "server.firewall_subtitle_v08": "Regole di forwarding/NAT e accesso dall’interfaccia. Le regole semplici si gestiscono qui; quelle avanzate nell’editor grezzo.", + "server.forward_from_vpn": "Consenti forwarding da VPN", + "server.forward_to_vpn": "Consenti forwarding verso VPN", + "server.forwarding_section": "Forwarding e NAT", + "server.gateway": "Gateway", + "server.gateway_hint": "Richiesto solo con una tabella di policy routing.", + "server.install_success": "WireGuard installato correttamente.", + "server.install_wireguard": "Installa WireGuard", + "server.install_wireguard_help": "Esegue apt update e installa WireGuard e gli strumenti di rete necessari.", + "server.install_wireguard_title": "Installa WireGuard", + "server.installing": "Installazione WireGuard… Potrebbe volerci un minuto.", + "server.interface": "Interfaccia", + "server.interface_hint": "WGTools gestisce attualmente questa interfaccia.", + "server.interface_name": "Interfaccia", + "server.interface_section": "Interfaccia WireGuard", + "server.ip_forwarding": "Forwarding IPv4", + "server.kind": "Tipo", + "server.listen_port": "Porta di ascolto", + "server.local_network": "Rete locale", + "server.local_network_hint": "Route facoltativa aggiunta alla tabella di routing.", + "server.managed_automatically": "Gestito automaticamente", + "server.nat": "NAT / Masquerade", + "server.network": "Rete", + "server.network_settings": "Rete e NAT", + "server.no_firewall": "Nessuna regola firewall trovata", + "server.no_routes": "Nessuna route trovata", + "server.not_configured": "Non configurato", + "server.not_set": "Non impostato", + "server.policy_disabled_hint": "Disattiva per il routing di sistema normale. Attiva solo se la VPN richiede una propria tabella basata sull’origine.", + "server.policy_enabled": "Abilita policy routing", + "server.policy_table": "Tabella policy", + "server.policy_table_hint": "Lascia vuoto per il routing normale; usa ad es. 200 per il routing basato sull’origine.", + "server.port_word": "porta", + "server.private_hidden": "Configurato (nascosto)", + "server.private_key": "Chiave privata", + "server.protocol": "Protocollo", + "server.route_apply_confirm": "Salvare e applicare la route? WireGuard verrà riavviato brevemente dopo un backup.", + "server.route_custom": "Personalizzata", + "server.route_deleted": "Route eliminata.", + "server.route_device_hint": "Interfaccia di uscita facoltativa, ad es. wg0 o enp6s18.", + "server.route_editor_help": "Aggiungi route installata all’avvio di WireGuard e rimossa all’arresto.", + "server.route_gateway_hint": "Gateway next-hop facoltativo. Serve un gateway o un’interfaccia.", + "server.route_managed_peer": "Peer Site-to-site", + "server.route_managed_server": "Impostazione server", + "server.route_network_hint": "Rete IPv4 come 10.20.0.0/24 o 'default'.", + "server.route_saved": "Route salvata e applicata.", + "server.route_table_hint": "Usa 'main' per il routing normale o una tabella numerica come 200.", + "server.route_type": "Tipo", + "server.routes": "Rotte rilevate", + "server.routes_subtitle": "Route estratte da PostUp/PostDown e dallo stato del policy routing.", + "server.routes_subtitle_v08": "Route server, Site-to-site e personalizzate dell’interfaccia selezionata. Qui puoi aggiungere, modificare e rimuovere route.", + "server.routing": "Instradamento", + "server.routing_section": "Instradamento", + "server.rule": "Regola", + "server.rule_access": "Regola di accesso", + "server.rule_advanced": "Avanzate", + "server.rule_apply_warning": "Applicare route o regole firewall riavvia brevemente WireGuard. WGTools crea un backup e ripristina la configurazione se l’avvio fallisce.", + "server.rule_client_exception": "Eccezione client", + "server.rule_client_policy": "Criterio client", + "server.rule_managed_server": "Impostazione server", + "server.rule_type": "Tipo", + "server.run_diagnostics": "Esegui diagnostica", + "server.save_apply": "Salva e applica", + "server.save_config": "SaveConfig", + "server.server_address": "Indirizzo VPN server", + "server.server_address_hint": "Di solito il primo indirizzo utilizzabile nella rete VPN.", + "server.settings_applied": "Impostazioni server salvate e applicate correttamente.", + "server.settings_apply_failed": "Impossibile applicare le impostazioni server", + "server.setup_required": "Configurazione necessaria", + "server.source": "Origine", + "server.source_hint": "Vuoto = qualsiasi. Accetta IP, CIDR o intervallo come 10.0.0.100-10.0.0.120.", + "server.subtitle": "Installazione, configurazione iniziale e stato del server WireGuard.", + "server.tab_config": "Configurazione", + "server.tab_interface": "Interfaccia", + "server.tab_routing": "Instradamento", + "server.tab_vps": "VPS", + "server.table": "Tabella", + "server.tabs_aria": "Sezioni delle impostazioni server", + "server.title": "Server", + "server.uplink": "Interfaccia uplink", + "server.use_raw_editor": "Usa editor configurazione grezza", + "server.via": "Via / Dispositivo", + "server.via_word": "via", + "server.vpn_network": "Rete VPN", + "server.vpn_network_hint": "Gli indirizzi client verranno assegnati da questa rete.", + "server.vpn_pool": "Pool indirizzi VPN", + "server.wg_not_installed": "WireGuard non è installato", + "server.wg_not_installed_subtitle": "WGTools può installare automaticamente i pacchetti Debian necessari.", + "server.what_happens": "Operazioni di WGTools", + "settings.about": "Informazioni", + "settings.add_user": "Aggiungi utente", + "settings.advanced": "Avanzate", + "settings.advanced_subtitle": "Accesso diretto agli strumenti avanzati di configurazione WireGuard.", + "settings.appearance": "Aspetto", + "settings.applying_config": "Validazione configurazione, creazione backup e applicazione…", + "settings.backup_count": "Backup salvati", + "settings.backup_retention": "Backup da conservare", + "settings.backup_retention_help": "I vecchi backup automatici vengono eliminati dopo la creazione del nuovo. Da 1 a 200 file.", + "settings.backups": "Backup della configurazione", + "settings.backups_always_on": "Abilitato", + "settings.backups_subtitle": "WGTools crea automaticamente un backup prima di modificare la configurazione. I backup automatici non possono essere disabilitati.", + "settings.change_password": "Cambia password", + "settings.check_updates": "Controlla aggiornamenti", + "settings.config_applied": "Configurazione salvata e applicata correttamente.", + "settings.config_applied_restarted": "Configurazione applicata e WireGuard riavviato.", + "settings.config_applied_stopped": "Configurazione salvata. WireGuard era fermo e rimane fermo.", + "settings.config_apply_failed": "Impossibile applicare la configurazione", + "settings.config_load_failed": "Impossibile caricare la configurazione", + "settings.current_user": "Utente corrente", + "settings.current_version": "Versione attuale", + "settings.audit_action": "Azione", + "settings.audit_empty": "Nessun evento audit", + "settings.audit_log": "Registro audit", + "settings.audit_log_subtitle": "Azioni nel pannello, autenticazione, Telegram e cronologia delle connessioni WireGuard. I segreti non vengono registrati.", + "settings.audit_object": "Oggetto", + "settings.audit_result": "Risultato", + "settings.audit_retention_note": "Conservazione: 30 giorni", + "settings.audit_search": "Ricerca rapida", + "settings.audit_search_clear": "Cancella ricerca", + "settings.audit_search_empty": "Nessun evento audit corrispondente", + "settings.audit_time": "Data / ora", + "settings.audit_user": "Utente", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Regola di accesso creata", + "audit.action.access_rule.deleted": "Regola di accesso eliminata", + "audit.action.access_rule.updated": "Regola di accesso aggiornata", + "audit.action.auth.first_user_created": "Primo utente creato", + "audit.action.auth.login": "Accesso effettuato", + "audit.action.auth.login_failed": "Accesso non riuscito", + "audit.action.auth.logout": "Disconnessione effettuata", + "audit.action.backup.full_created": "Backup completo creato", + "audit.action.backup.full_restored": "Backup completo ripristinato", + "audit.action.client.config_downloaded": "Configurazione client scaricata", + "audit.action.client.config_viewed": "Configurazione client visualizzata", + "audit.action.client.created": "Client creato", + "audit.action.client.deleted": "Client eliminato", + "audit.action.client.qr_viewed": "Codice QR client visualizzato", + "audit.action.client.updated": "Client aggiornato", + "audit.action.client_group.created": "Gruppo client creato", + "audit.action.client_group.deleted": "Gruppo client eliminato", + "audit.action.client_group.updated": "Gruppo client aggiornato", + "audit.action.interface.created": "Interfaccia creata", + "audit.action.interface.deleted": "Interfaccia eliminata", + "audit.action.interface.renamed": "Interfaccia rinominata", + "audit.action.route.created": "Rotta creata", + "audit.action.route.deleted": "Rotta eliminata", + "audit.action.route.updated": "Rotta aggiornata", + "audit.action.server.created": "Server creato", + "audit.action.server.raw_config_applied": "Configurazione grezza applicata", + "audit.action.server.settings_applied": "Impostazioni server applicate", + "audit.action.settings.updated": "Impostazioni pannello aggiornate", + "audit.action.telegram.action_denied": "Azione Telegram negata", + "audit.action.telegram.action_failed": "Azione Telegram non riuscita", + "audit.action.telegram.connection_test": "Test connessione Telegram", + "audit.action.telegram.settings_updated": "Impostazioni Telegram aggiornate", + "audit.action.update.checked": "Aggiornamento verificato", + "audit.action.update.scheduled": "Aggiornamento pianificato", + "audit.action.update.backup_created": "Backup pre-aggiornamento", + "audit.action.update.completed": "Aggiornamento completato", + "audit.action.update.failed": "Aggiornamento non riuscito", + "audit.action.update.rollback_completed": "Versione precedente ripristinata", + "audit.action.update.rollback_failed": "Rollback aggiornamento non riuscito", + "audit.action.user.created": "Utente creato", + "audit.action.user.deleted": "Utente eliminato", + "audit.action.user.password_changed": "Password utente modificata", + "audit.action.vps.candidate_deleted": "Candidato VPS eliminato", + "audit.action.vps.candidate_saved": "Candidato VPS salvato", + "audit.action.vps.detached": "Relay VPS scollegato", + "audit.action.vps.relay_installed": "Relay VPS installato", + "audit.action.wireguard.client_connected": "Client WireGuard connesso", + "audit.action.wireguard.installed": "WireGuard installato", + "audit.action.wireguard.restarted": "WireGuard riavviato", + "audit.action.wireguard.started": "WireGuard avviato", + "audit.action.wireguard.stopped": "WireGuard arrestato", + "audit.result.applied": "applicato", + "audit.result.available": "disponibile", + "audit.result.changed": "modificato", + "audit.result.created": "creato", + "audit.result.current": "attuale", + "audit.result.deleted": "eliminato", + "audit.result.detached": "scollegato", + "audit.result.denied": "negato", + "audit.result.downloaded": "scaricato", + "audit.result.endpoint": "Endpoint", + "audit.result.error": "Errore", + "audit.result.installed": "installato", + "audit.result.invalid_credentials": "credenziali non valide", + "audit.result.ok": "OK", + "audit.result.queued": "in coda", + "audit.result.restarted": "riavviato", + "audit.result.restored": "ripristinato", + "audit.result.rotated": "rigenerato", + "audit.result.saved": "salvato", + "audit.result.shown": "mostrato", + "audit.result.started": "avviato", + "audit.result.stopped": "arrestato", + "audit.result.updated": "aggiornato", + "settings.delete_user": "Elimina", + "settings.delete_user_confirm": "Eliminare l’utente {name}?", + "settings.edit_raw_config": "Modifica configurazione interfaccia", + "settings.expert_mode": "Esperto", + "settings.full_backup_component_clients": "Metadati dei client gestiti, chiavi private, PSK, scadenze e gruppi necessari per rigenerare configurazioni e QR.", + "settings.full_backup_component_db": "Database WGTools: utenti, preferenze, email/SMTP, Telegram e stato salvato di VPS Relay.", + "settings.full_backup_component_relay": "Dati di recupero VPS Relay: ID controller/tenant, token di gestione e chiave di trasporto Home. Dopo il ripristino WGTools può ricreare il trasporto locale e riconnettere il tenant.", + "settings.full_backup_component_system": "File sysctl IPv4 forwarding WGTools, metadati dei nomi interfaccia e criteri/modelli gruppo, se presenti. La cronologia automatica è esclusa intenzionalmente.", + "settings.full_backup_component_wg": "Tutte le configurazioni WireGuard rilevate in /etc/wireguard/, incluso lo stato attivo/fermo.", + "settings.full_backup_create_failed": "Impossibile creare backup completo", + "settings.full_backup_creating": "Creazione backup completo…", + "settings.full_backup_download": "Crea", + "settings.full_backup_downloaded": "Backup creato e scaricato. Conservalo al sicuro.", + "settings.full_backup_downloaded_short": "Backup completo scaricato.", + "settings.full_backup_help": "Crea un backup WGTools portatile per migrazione o emergenze: configurazioni WireGuard, utenti, impostazioni, gruppi, client gestiti e dati per riconnettere i tenant VPS Relay conservati.", + "settings.full_backup_no_file": "Nessun backup selezionato", + "settings.full_backup_restore": "Ripristina", + "settings.full_backup_restore_confirm": "Ripristinare il backup completo WGTools? Verranno ripristinati utenti, impostazioni, client gestiti e configurazioni WireGuard incluse. Le interfacce potrebbero riavviarsi. WGTools crea prima un backup di sicurezza e annulla automaticamente in caso di errore.", + "settings.full_backup_restore_failed": "Ripristino non riuscito", + "settings.full_backup_restored": "Backup ripristinato. Accedi con un account presente nel backup.", + "settings.full_backup_restored_short": "Backup ripristinato.", + "settings.full_backup_restoring": "Verifica backup, creazione copia di sicurezza e ripristino…", + "settings.full_backup_secret_warning": "Il file contiene dati sensibili: chiavi private WireGuard e dei client, PSK, hash delle password WGTools, token bot Telegram e password SMTP salvata. Custodiscilo come una password e non allegarlo mai a issue o chat pubbliche.", + "settings.full_backup_select": "Seleziona", + "settings.full_backup_title": "Backup completo e ripristino", + "settings.full_mode": "Gestione server e client attiva", + "settings.interface_help": "L’interfaccia WireGuard gestita viene scelta durante l’installazione di WGTools.", + "settings.language": "Lingua", + "settings.last_backup": "Ultimo backup", + "settings.latest_version": "Ultima versione", + "settings.loading_config": "Caricamento configurazione…", + "settings.mode": "Modalità", + "settings.never_logged_in": "Mai", + "settings.new_password": "Nuova password", + "settings.no_backups": "Nessun backup", + "settings.online_help": "Un peer è online se il suo ultimo handshake è più recente della soglia. 30–3600 secondi.", + "settings.online_threshold": "Soglia online", + "settings.open_release": "Apri release", + "settings.password_changed": "Password modificata.", + "settings.passwords_mismatch": "Le password non coincidono.", + "settings.project_github": "Progetto / GitHub", + "settings.raw_config_confirm": "Salvare e applicare questa configurazione WireGuard? L’interfaccia selezionata verrà riavviata. Prima viene creato un backup; WGTools ripristina quella precedente se l’avvio fallisce.", + "settings.raw_config_help": "Apri la configurazione sorgente dell’interfaccia WireGuard scelta.", + "settings.raw_config_title": "Configurazione WireGuard grezza", + "settings.raw_config_warning": "Modalità esperto: questa è la vera configurazione server WireGuard e contiene la chiave privata e i PSK dei peer. Salvare e applicare riavvia l’interfaccia. WGTools crea prima un backup e ripristina se l’avvio fallisce.", + "settings.readonly_mode": "Gestione client attiva", + "settings.refresh_help": "Frequenza di aggiornamento dello stato. Da 2 a 60 secondi.", + "settings.refresh_interval": "Intervallo di aggiornamento", + "settings.release_notes": "Note di rilascio", + "settings.reload_config": "Ricarica da disco", + "settings.save_apply": "Salva e applica", + "settings.saved": "Impostazioni salvate.", + "settings.saved_reload": "Impostazioni salvate. Ricaricamento…", + "settings.saving": "Salvataggio impostazioni…", + "settings.status": "Aggiornamento stato", + "settings.status_help": "Intervalli di aggiornamento Dashboard e stato dei peer.", + "settings.subtitle": "Preferenze interfaccia e impostazioni stato WGTools.", + "settings.syntax_hint": "Sezioni, chiavi, valori e commenti WireGuard sono evidenziati durante la modifica.", + "settings.tab_about": "Informazioni", + "settings.tab_backups": "Backup", + "settings.tab_general": "Generale", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Utenti", + "settings.tabs_aria": "Sezioni impostazioni", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "ID utenti Telegram consentiti", + "settings.telegram_allowed_ids_help": "Un ID numerico per riga. Un /start non autorizzato risponderà con l’ID Telegram del mittente, che potrai aggiungere qui.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Connesso", + "settings.telegram_disabled": "Disabilitato", + "settings.telegram_dns": "DNS client predefinito", + "settings.telegram_dns_help": "Indirizzi DNS IPv4 facoltativi, separati da virgole. Usati per client creati dal bot.", + "settings.telegram_enabled": "Abilita bot Telegram", + "settings.telegram_endpoint": "Indirizzo / dominio server predefinito", + "settings.telegram_endpoint_help": "Usato dal bot per nuove configurazioni client. Inserisci solo IP o dominio; la porta WireGuard è letta dalla configurazione server.", + "settings.telegram_language": "Lingua del bot", + "settings.telegram_language_auto": "Auto (lingua Telegram)", + "settings.telegram_last_poll": "Ultimo contatto Telegram", + "settings.telegram_not_configured": "Non configurato", + "settings.telegram_remove_token": "Rimuovi token", + "settings.telegram_remove_token_confirm": "Rimuovere il token del bot Telegram salvato e disabilitare il bot?", + "settings.telegram_save": "Salva impostazioni Telegram", + "settings.telegram_saved": "Impostazioni Telegram salvate.", + "settings.telegram_setup_note": "Crea un bot con @BotFather, salva il token, attivalo e invia /start. Se il tuo ID non è autorizzato, WGTools lo mostrerà: aggiungilo alla lista degli ID consentiti.", + "settings.telegram_status": "Stato del bot", + "settings.telegram_subtitle": "Gestione WireGuard da Telegram: stato server, client, creazione/eliminazione e avvio/riavvio/arresto.", + "settings.telegram_test": "Testa connessione", + "settings.telegram_test_ok": "Connessione Telegram funzionante: @{username}", + "settings.telegram_test_recent_ok": "Il bot Telegram funziona. Il controllo diretto è scaduto, ma il bot ha contattato Telegram di recente.", + "settings.telegram_token": "Token del bot", + "settings.telegram_token_help": "Crea un bot con @BotFather e incolla qui il token Bot API. API ID e API Hash non sono richiesti.", + "settings.telegram_token_keep": "Lascia vuoto per conservare il token salvato.", + "settings.telegram_waiting": "Configurato, in attesa del servizio bot", + "settings.theme": "Tema", + "settings.theme_dark": "Scuro", + "settings.theme_light": "Chiaro", + "settings.theme_system": "Sistema", + "settings.title": "Impostazioni", + "settings.update_available": "Aggiornamento disponibile", + "settings.update_backup_queued": "Aggiornamento in coda. WGTools creerà un backup completo automatico prima dell’installazione…", + "settings.update_backup_running": "Creazione del backup completo prima dell’aggiornamento…", + "settings.update_check_failed": "Impossibile verificare aggiornamenti", + "settings.update_checking": "Verifica dell’ultima release pubblicata su GitHub…", + "settings.update_confirm": "Aggiornare WGTools da v{current} a v{latest}? Prima verranno creati un backup completo e una copia per il rollback. L’interfaccia web si riavvierà brevemente.", + "settings.update_current": "Aggiornato", + "settings.update_downloading": "Download e verifica della release GitHub…", + "settings.update_failed": "Aggiornamento WGTools non riuscito.", + "settings.update_installing": "Installazione aggiornamento. L’interfaccia web potrebbe non essere disponibile per poco…", + "settings.update_no_update": "WGTools è già aggiornato.", + "settings.update_not_checked": "Non verificato", + "settings.update_queued": "Aggiornamento in coda. In attesa del servizio updater…", + "settings.update_rollback_ok": "La precedente applicazione WGTools è stata ripristinata automaticamente.", + "settings.update_rolling_back": "Aggiornamento non riuscito. Ripristino versione WGTools precedente…", + "settings.update_running": "Creazione backup di sicurezza…", + "settings.update_safety_hint": "Gli aggiornamenti sono facoltativi. WGTools crea backup completo e copia per rollback prima di installare. In caso di errore ripristina l’applicazione precedente. WireGuard non viene riavviato, salvo modifiche esplicite della sua configurazione nella release.", + "settings.update_sidebar": "Nuova versione disponibile", + "settings.update_sidebar_hint": "Impostazioni → Info", + "settings.update_starting": "Avvio aggiornamento…", + "settings.update_status_unknown": "Stato aggiornamento non disponibile. Nuovo tentativo…", + "settings.update_subtitle": "Informazioni progetto, verifica automatica delle release e aggiornamenti sicuri da GitHub Releases.", + "settings.update_success": "WGTools aggiornato a v{version}. Ricaricamento…", + "settings.update_wgtools": "Aggiorna WGTools", + "settings.user_actions": "Azioni", + "settings.user_created": "Creato", + "settings.user_created_ok": "Utente creato.", + "settings.user_deleted": "Utente eliminato.", + "settings.user_equal_rights": "Tutti gli utenti WGTools hanno gli stessi permessi.", + "settings.user_last_login": "Ultimo accesso", + "settings.user_name": "Nome utente", + "settings.users": "Utenti", + "settings.users_subtitle": "Account locali WGTools. L’email è facoltativa ed è usata solo per recuperare la password se la posta è attiva.", + "vps.add": "Aggiungi VPS", + "vps.add_help": "WGTools usa SSH per verificare o installare Relay. Password e chiavi SSH private non vengono mai salvate.", + "vps.add_title": "Aggiungi VPS", + "vps.agent": "Agente Relay", + "vps.agent_found": "Già installato", + "vps.agent_will_install": "Verrà installato", + "vps.arch": "Architettura", + "vps.auth_method": "Autenticazione", + "vps.authentication": "Autenticazione SSH", + "vps.check": "Verifica VPS", + "vps.check_failed": "Verifica VPS non riuscita", + "vps.check_link": "Verifica collegamento", + "vps.check_ok": "VPS compatibile", + "vps.checking": "Verifica accesso SSH e compatibilità VPS…", + "vps.connections": "connessioni", + "vps.credentials_not_saved": "Usati solo per questa verifica, non salvati da WGTools.", + "vps.delete_candidate": "Rimuovi", + "vps.delete_installed": "Rimuovi VPS", + "vps.delete_installed_confirm": "Rimuovere “{name}” da WGTools? Il trasporto Relay locale verrà scollegato, ma Relay Agent e tenant sul VPS saranno conservati. Potrai aggiungere di nuovo il VPS per riconnetterti al Relay esistente. I client non potranno usarlo finché non sarà riconnesso.", + "vps.delete_installed_failed": "Impossibile rimuovere VPS da WGTools", + "vps.delete_installed_ok": "VPS rimosso da WGTools. Il Relay remoto è conservato e può essere riconnesso.", + "vps.empty_help": "Aggiungi un VPS Debian o Ubuntu per verificare SSH, compatibilità del sistema e porte UDP necessarie.", + "vps.empty_title": "Nessun VPS configurato", + "vps.endpoint": "Endpoint pubblico", + "vps.endpoint_domain": "Dominio (consigliato)", + "vps.endpoint_domain_hint": "Se cambi in futuro il VPS principale, modificare il DNS può mantenere invariate le configurazioni client.", + "vps.health_failed": "Verifica collegamento Relay non riuscita", + "vps.host": "IP / nome host", + "vps.host_key": "Chiave host SSH", + "vps.identity": "Connessione VPS", + "vps.install_failed": "Installazione Relay non riuscita", + "vps.install_ok": "Relay installato e collegamento di gestione protetto verificato", + "vps.install_relay": "Installa Relay", + "vps.install_title": "Installa Relay VPS", + "vps.installed": "Installato", + "vps.installing": "Installazione Relay Agent e creazione tunnel protetto…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Passphrase chiave", + "vps.link_ok": "Collegamento Relay OK", + "vps.multi_tenant_note": "Un Relay Agent WGTools è già in esecuzione su questo VPS. Non sarà sostituito: questo WGTools avrà connessione isolata con chiavi e porte UDP proprie.", + "vps.name": "Nome", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Verrà installato", + "vps.os": "Sistema operativo", + "vps.password": "Password", + "vps.phase_note": "Relay Agent supporta più controller WGTools indipendenti su un VPS. Ogni controller riceve connessione, chiavi e porte UDP isolate; quelle esistenti restano intatte.", + "vps.port_pair": "Porte UDP", + "vps.ports_adjusted": "selezionate porte libere", + "vps.private_key": "Chiave privata", + "vps.privilege": "Privilegi", + "vps.public_endpoint": "Futuro endpoint pubblico", + "vps.ready_help": "Le credenziali SSH servono solo per la verifica e l’installazione immediata di Relay; non vengono salvate.", + "vps.reconnect_note": "Sul VPS esiste già una connessione Relay creata da questo WGTools. Verrà riconnesso lo stesso tenant, senza crearne uno nuovo né nuove porte UDP.", + "vps.reconnect_ok": "Relay esistente riconnesso correttamente", + "vps.reconnect_relay": "Riconnetti Relay", + "vps.relay_port": "Porta UDP Relay", + "vps.remove_confirm": "Rimuovere questo candidato VPS? Nessuna modifica remota è stata effettuata.", + "vps.save_candidate": "Salva candidato", + "vps.saved": "Candidato VPS salvato", + "vps.ssh": "SSH", + "vps.ssh_key": "Chiave SSH", + "vps.ssh_port": "Porta SSH", + "vps.ssh_user": "Utente SSH", + "vps.status_candidate": "Pronto per installazione", + "vps.status_installed": "Relay connesso", + "vps.subtitle": "Prepara un VPS pubblico per l’accesso remoto quando questo server WGTools non ha IP pubblico.", + "vps.tenant": "Connessione", + "vps.title": "Relay VPS", + "vps.transport_port": "Porta UDP di trasporto", + "vps.transport_port_hint": "Porta UDP separata per il tunnel di trasporto privato Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Salvato", + "vps.active_short": "Attivo", + "dashboard.traffic_reset": "Ripristina", + "dashboard.traffic_reset_confirm": "Azzerare i contatori di traffico WireGuard per questa interfaccia? Anche quelli dei client ripartiranno da zero.", + "dashboard.traffic_reset_done": "Contatori traffico azzerati", + "dashboard.traffic_reset_failed": "Impossibile azzerare i contatori traffico", + "audit.action.traffic.reset": "Contatori traffico azzerati", + "audit.result.reset": "azzerato", + "server.mtu": "MTU", + "server.mtu_auto": "Automatico", + "server.mtu_hint": "Facoltativo. Lascia vuoto per MTU automatico di wg-quick. Imposta 1380 o 1420 solo se richiesto da LTE o PPPoE.", + "clients.peer_isolation": "Isolamento client VPN", + "clients.peer_isolation_enable": "Isola dagli altri client VPN", + "clients.peer_isolation_hint": "Blocca il traffico tra questo client e gli altri indirizzi del pool WireGuard. L’accesso al server, a Internet e alle reti locali o Site-to-site resta regolato dagli altri criteri.", + "clients.credentials_rotate": "Chiavi del client", + "clients.credentials_rotate_button": "Rigenera chiavi", + "clients.credentials_rotate_confirm": "Generare nuove chiavi per questo client? Se connesso, la sessione WireGuard verrà interrotta immediatamente. Invia poi una nuova configurazione o QR.", + "clients.credentials_rotate_confirm_psk": "Generare una nuova coppia di chiavi e un nuovo PSK? La sessione WireGuard attiva del client verrà interrotta immediatamente. Invia poi una nuova configurazione o QR.", + "clients.credentials_rotate_hint": "Rigenera PrivateKey/PublicKey e anche il PSK se attivo. Indirizzo, route, gruppo, pianificazione, isolamento e statistiche restano invariati.", + "clients.credentials_rotating": "Generazione nuove chiavi e disconnessione della vecchia sessione…", + "clients.credentials_rotated": "Chiavi del client cambiate. La vecchia sessione è stata interrotta se attiva. La precedente configurazione non funziona più; invia nuova configurazione o QR.", + "clients.credentials_rotated_short": "Chiavi cambiate — serve nuova configurazione", + "audit.action.client.credentials_rotated": "Chiavi del client rigenerate", + "clients.credentials_connection_lost": "Connessione a WGTools interrotta. Se il pannello era aperto tramite il client le cui chiavi sono state rigenerate, è normale: la vecchia sessione WireGuard è stata chiusa. Ricollegati con un altro percorso e genera nuova configurazione o QR.", + "nav.navigation": "Navigazione principale", + "nav.project_github": "WGTools su GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Facoltativo per ora. Può servire a recuperare la password dopo aver configurato la posta.", + "auth.forgot_password": "Password dimenticata?", + "auth.reset_title": "Reimposta la password", + "auth.reset_subtitle": "Ricevi un codice monouso via email e imposta una nuova password WGTools.", + "auth.reset_identifier": "Nome utente o e-mail", + "auth.reset_identifier_help": "Per la privacy, WGTools mostra sempre la stessa risposta, sia che l’account esista o no.", + "auth.send_reset_code": "Invia codice", + "auth.reset_code_sent_generic": "Se l’account esiste e ha un indirizzo email, è stato inviato un codice. È valido per 15 minuti.", + "auth.reset_code": "Codice a 6 cifre", + "auth.set_new_password": "Imposta nuova password", + "auth.request_another_code": "Richiedi un altro codice", + "auth.back_to_login": "Torna all'accesso", + "auth.reset_not_configured": "Il recupero password via email non è configurato. Contatta l’amministratore WGTools.", + "settings.tab_mail": "Posta", + "settings.mail": "Email / SMTP", + "settings.mail_subtitle": "SMTP viene usato per il recupero password.", + "settings.mail_not_configured": "Non configurato", + "settings.mail_enabled": "Abilita posta e recupero password", + "settings.mail_smtp_host": "Server SMTP", + "settings.mail_smtp_port": "Porta SMTP", + "settings.mail_security": "Crittografia", + "settings.mail_security_none": "Nessuna crittografia", + "settings.mail_username": "Nome utente SMTP", + "settings.mail_username_help": "Usato per l’autenticazione SMTP e come indirizzo email mittente.", + "settings.mail_password": "Password SMTP", + "settings.mail_password_keep": "Lascia vuoto per mantenere la password salvata.", + "settings.mail_from_email": "Email mittente", + "settings.mail_from_name": "Nome mittente", + "settings.mail_test_recipient": "Destinatario test", + "settings.mail_test_recipient_help": "Il test usa le impostazioni SMTP attualmente salvate.", + "settings.mail_remove_password": "Rimuovi password", + "settings.mail_test": "Invia test", + "settings.mail_save": "Salva impostazioni email", + "settings.mail_enabled_badge": "Abilitato", + "settings.mail_disabled_badge": "Disabilitato", + "settings.mail_saved": "Impostazioni email salvate.", + "settings.mail_remove_password_confirm": "Rimuovere la password SMTP salvata e disabilitare la posta?", + "settings.mail_password_removed": "Password SMTP rimossa e posta disabilitata.", + "settings.mail_test_recipient_required": "Inserisci l’indirizzo email del destinatario del test.", + "settings.mail_testing": "Invio email di prova…", + "settings.mail_test_ok": "Email di prova inviata correttamente.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Facoltativa. Necessaria solo per recuperare autonomamente la password.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "Email salvata.", + "settings.send_password_reset": "Invia reset", + "settings.user_reset_mail_not_configured": "Prima configura e abilita la posta.", + "settings.user_reset_email_missing": "Aggiungi prima un indirizzo email.", + "settings.user_reset_confirm": "Inviare un codice di reset password a {name} all’indirizzo {email}?", + "settings.user_reset_sent": "Codice di reset inviato a {email}.", + "audit.action.auth.password_reset_requested": "Richiesto reset password", + "audit.action.auth.password_reset_code_sent": "Codice di reset password inviato", + "audit.action.auth.password_reset_completed": "Password reimpostata", + "audit.action.auth.password_reset_failed": "Reset password non riuscito", + "audit.action.mail.settings_updated": "Impostazioni email aggiornate", + "audit.action.mail.test_sent": "Email di prova inviata", + "audit.action.mail.test_failed": "Invio email di prova non riuscito", + "audit.action.user.email_changed": "Email utente modificata", + "audit.action.user.password_reset_sent": "Reset password utente inviato", + "audit.action.user.password_reset_failed": "Reset password utente non riuscito", + "audit.result.accepted": "accettato", + "audit.result.sent": "inviato", + "audit.result.invalid_code": "codice non valido", + "common.copy": "Copia", + "common.copied": "Copiato", + "clients.use_panel_host": "Usa indirizzo pannello", + "clients.use_panel_host_done": "Indirizzo pannello inserito: {host}", + "clients.use_panel_host_failed": "Impossibile ricavare l’indirizzo del pannello dall’URL del browser.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "HTTPS Let’s Encrypt integrato per accesso diretto a WGTools senza reverse proxy.", + "settings.https_disabled": "Disabilitato", + "settings.https_enabled": "Abilitato", + "settings.https_enable": "Abilita HTTPS integrato", + "settings.https_type": "Certificato per", + "settings.https_domain": "Dominio", + "settings.https_public_ip": "IP pubblico", + "settings.https_target": "Dominio o IP pubblico", + "settings.https_email": "Email Let’s Encrypt", + "settings.https_port": "Porta HTTPS", + "settings.https_port80_note": "La porta TCP 80 deve essere raggiungibile da Internet per emissione e rinnovo del certificato. Apri anche la porta HTTPS scelta per il pannello.", + "settings.https_check_ports": "Verifica porte", + "settings.https_certificate": "Certificato", + "settings.https_certificate_ready": "Pronto", + "settings.https_certificate_missing": "Non emesso", + "settings.https_expires": "Valido fino al", + "settings.https_renewal": "Rinnovo automatico", + "settings.https_renewal_enabled": "Abilitato", + "settings.https_renewal_disabled": "Disabilitato", + "settings.https_certificate_path": "Certificato", + "settings.https_private_key_path": "Chiave privata", + "settings.https_issue": "Ottieni / rinnova certificato", + "settings.https_port_free": "Libera", + "settings.https_port_busy": "Occupata", + "settings.https_ports_checked": "Verifica porte completata.", + "settings.https_target_email_required": "Inserisci dominio/IP pubblico ed email Let’s Encrypt.", + "settings.https_issue_confirm": "Richiedere o rinnovare il certificato Let’s Encrypt per {target}? Le impostazioni HTTPS verranno salvate. La porta TCP 80 deve essere accessibile da Internet.", + "settings.https_issuing": "Richiesta certificato a Let’s Encrypt…", + "settings.https_issue_ok": "Certificato pronto.", + "settings.https_already_enabled": "HTTPS integrato già attivo.", + "settings.https_already_disabled": "HTTPS integrato già disattivato.", + "settings.https_enable_confirm": "Attivare HTTPS integrato su TCP {port} con percorso {path}? WGTools si riavvierà e la pagina si riconnetterà al nuovo indirizzo.", + "settings.https_disable_confirm": "Disattivare HTTPS integrato e tornare a HTTP?", + "settings.https_switching": "Attivazione HTTPS e riavvio WGTools…", + "settings.https_switching_http": "Disattivazione HTTPS e riavvio WGTools…", + "audit.action.https.certificate_issued": "Certificato HTTPS emesso", + "audit.action.https.certificate_failed": "Richiesta certificato HTTPS non riuscita", + "audit.action.https.enabled": "HTTPS attivato", + "audit.action.https.disabled": "HTTPS disattivato", + "audit.result.issued": "emesso", + "audit.result.enabled": "attivato", + "audit.result.disabled": "disattivato", + "settings.https_access_path": "Percorso di accesso al pannello", + "settings.https_access_path_help": "Scegli un percorso personalizzato. Con HTTPS integrato, le richieste fuori percorso ricevono 404.", + "settings.https_enable_fields_required": "Inserisci dominio/IP pubblico, email Let’s Encrypt e percorso pannello.", + "settings.https_use_panel_host": "Usa indirizzo pannello", + "settings.https_reconnecting": "WGTools passa al nuovo indirizzo HTTPS…", + "server.tab_nodes": "Nodi", + "common.type": "Tipo", + "common.status": "Stato", + "common.copy_failed": "Impossibile copiare", + "clients.vpn_address": "Indirizzo VPN", + "nodes.title": "Nodi WGTools", + "nodes.subtitle": "Collega più server WGTools in una rete protetta e pubblica solo le reti accessibili agli altri nodi.", + "nodes.enable_hub": "Attiva HUB", + "nodes.connect_hub": "Connetti a HUB", + "nodes.settings": "Impostazioni nodo", + "nodes.settings_action": "Impostazioni", + "nodes.sync_now": "Sincronizza", + "nodes.disable": "Disattiva nodi", + "nodes.disable_action": "Disconnetti", + "nodes.join_title": "Connetti nuovi nodi", + "nodes.join_help": "Genera un codice monouso e inseriscilo su un altro pannello WGTools insieme all’endpoint HUB, ad es. vpn.example.com:51950. Il codice vale 15 minuti e un solo utilizzo.", + "nodes.create_code": "Crea codice", + "nodes.connected_nodes": "Nodi connessi", + "nodes.connected_nodes_help": "Informazioni su altri pannelli, reti pubblicate e client. I client remoti sono in sola lettura.", + "nodes.enable_hub_help": "Questo pannello diventa il nodo centrale. La stessa porta accetta WireGuard su UDP e l’associazione iniziale protetta su TCP.", + "nodes.node_name": "Nome nodo", + "nodes.transport_network": "Rete di trasporto nodi", + "nodes.transport_help": "Rete privata separata usata solo per il trasporto tra WGTools. Non deve sovrapporsi alle reti VPN/LAN.", + "nodes.panel_url": "URL pannello", + "nodes.panel_url_help": "Facoltativo. Solo collegamento informativo per “Apri pannello” sugli altri nodi; non usato per la connessione Nodes.", + "nodes.extra_networks": "Reti nodo aggiuntive", + "nodes.extra_networks_help": "Una rete per riga. Reti VPN delle interfacce e reti remote Site-to-site sono pubblicate automaticamente. Aggiungi solo altre LAN/reti instradate, ad es. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools inserisce reti VPN, Site-to-site e LAN instradate rilevate. Mantieni solo le reti da pubblicare. Una per riga.", + "nodes.published_networks_settings_help": "Una rete per riga. Questo è l’elenco esplicito delle reti pubblicate dal nodo. Rimuovere una riga interrompe l’annuncio agli altri nodi.", + "nodes.available_networks_help": "Reti rilevate: {networks}. Le nuove reti non vengono pubblicate automaticamente; aggiungi quelle desiderate sopra.", + "nodes.available_networks_none": "Nessuna rete locale aggiuntiva rilevata.", + "nodes.connect_help": "Inserisci endpoint HUB e codice monouso. URL web, porta HTTPS, certificato e percorso privato non sono usati per associare i nodi.", + "nodes.join_code": "Codice connessione", + "nodes.connect_reachability_note": "L’associazione iniziale usa TCP protetto sulla porta indicata. Dopo la creazione di wgnode0, reti, stato, versioni e dati client in sola lettura si sincronizzano con HUB tramite indirizzo WireGuard interno.", + "nodes.connect": "Connetti", + "nodes.settings_help": "Nome nodo, collegamento facoltativo “Apri pannello” ed elenco reti pubblicate. L’URL non è usata per associazione o sincronizzazione.", + "nodes.details": "Dettagli", + "nodes.not_configured": "WGTools Nodes non configurato", + "nodes.not_configured_help": "Attiva HUB su questo pannello o collegalo a un HUB WGTools esistente.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Connesso a HUB", + "nodes.mode_none": "Non configurato", + "nodes.role": "Ruolo", + "nodes.tunnel": "Tunnel nodo", + "nodes.node_ip": "Indirizzo nodo", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Reti pubblicate", + "nodes.last_sync": "Ultima sincronizzazione", + "nodes.no_nodes_hub": "Nessun nodo connesso. Crea un codice e usalo su un altro pannello WGTools.", + "nodes.no_nodes_spoke": "Nessuna informazione ricevuta sui nodi remoti.", + "nodes.clients_short": "Client", + "nodes.open_panel": "Apri pannello", + "nodes.route_conflict": "Conflitto di route", + "nodes.no_published_networks": "Nessuna rete pubblicata", + "nodes.load_failed": "Impossibile caricare WGTools Nodes", + "nodes.enable_hub_confirm": "Attivare WGTools HUB e creare il tunnel WireGuard interno dei nodi?", + "nodes.applying": "Configurazione tunnel WGTools Nodes…", + "nodes.enable_failed": "Impossibile attivare HUB", + "nodes.hub_enabled": "WGTools HUB attivato", + "nodes.connecting": "Verifica codice HUB e creazione tunnel protetto…", + "nodes.connect_failed": "Impossibile connettersi a HUB", + "nodes.connected": "Connesso a WGTools HUB", + "nodes.settings_failed": "Impossibile salvare impostazioni nodo", + "nodes.settings_saved": "Impostazioni nodo salvate", + "nodes.code_failed": "Impossibile creare codice di connessione", + "nodes.code_expires": "Codice monouso. Valido fino alle {time}.", + "nodes.code_copied": "Codice connessione copiato", + "nodes.network_vpn": "Client VPN", + "nodes.network_site_to_site": "Rete Site-to-site", + "nodes.network_custom": "Rete aggiuntiva", + "nodes.conflict": "Conflitto", + "nodes.remote_clients": "Client (sola lettura)", + "nodes.no_clients": "Nessun client segnalato da questo nodo", + "nodes.details_failed": "Impossibile caricare dettagli nodo", + "nodes.remove_confirm": "Rimuovere il nodo “{name}” da HUB? L’accesso al tunnel interno sarà revocato.", + "nodes.remove_failed": "Impossibile rimuovere il nodo", + "nodes.removed": "Nodo rimosso", + "nodes.disable_hub_confirm": "Disattivare HUB e disconnettere tutti i nodi WGTools? Il tunnel interno sarà rimosso.", + "nodes.disconnect_confirm": "Disconnettere questo pannello WGTools da HUB e rimuovere il tunnel interno?", + "nodes.disable_failed": "Impossibile disattivare WGTools Nodes", + "nodes.disabled": "WGTools Nodes disattivato", + "nodes.sync_failed": "Sincronizzazione nodi non riuscita", + "nodes.synced": "Informazioni nodi sincronizzate", + "nodes.service_port": "Porta Nodes", + "nodes.service_port_help": "La stessa porta serve contemporaneamente WireGuard su UDP e l’associazione iniziale protetta su TCP.", + "nodes.hub_port_forward_note": "Se HUB è dietro NAT, inoltra la stessa porta UDP e TCP. Porta web WGTools, HTTPS e percorso privato del pannello non riguardano Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Dominio/IP e porta Nodes senza http:// o https://, ad es. vpn.example.com:51950.", + "settings.collapse_sidebar": "Comprimi barra laterale", + "settings.expand_sidebar": "Espandi barra laterale", + "settings.https_issue_fields_required": "Inserisci dominio/IP pubblico, email Let’s Encrypt e percorso pannello.", + "settings.https_issue_ok_saved": "Certificato pronto e impostazioni HTTPS salvate.", + "settings.https_enable_need_certificate": "Prima ottieni un certificato.", + "settings.https_enable_certificate_mismatch": "Prima ottieni un certificato per dominio o IP corrente.", + "settings.https_enable_certificate_expired": "Certificato scaduto. Rinnovalo prima di attivare HTTPS.", + "settings.https_enable_certificate_ready": "Certificato pronto: puoi attivare HTTPS integrato.", + "settings.https_enable_active_help": "Deseleziona e salva per tornare a HTTP.", + "settings.https_certificate_expired": "Scaduto", + "settings.https_certificate_wrong_target": "Per un altro indirizzo", + "nodes.network_conflict_error": "Le reti pubblicate sono in conflitto con un altro nodo o la rete di trasporto Nodes: {conflicts}. Rimuovi o modifica le reti.", + "nodes.networks_changed": "Le reti rilevate sono cambiate dall’ultimo salvataggio. Nuove: {added}. Non più rilevate: {removed}. Controlla e salva l’elenco pubblicato.", + "nodes.review_networks": "Controlla reti", + "nodes.vpn_pool_mismatch": "Pool VPN modificato: Nodes pubblica ancora {old}, mentre il pool attuale è {current}. Apri impostazioni nodo e aggiorna le reti pubblicate.", + "server.error_vpn_network_invalid": "La rete VPN deve essere una rete IPv4 valida, ad es. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Sono supportate solo reti VPN IPv4.", + "server.error_vpn_network_too_small": "La rete VPN deve contenere almeno due indirizzi utilizzabili.", + "server.error_vpn_network_no_hosts": "La rete VPN scelta non contiene indirizzi server utilizzabili.", + "server.error_server_address_prefix": "L’indirizzo VPN server deve includere un prefisso, ad es. 10.0.0.1/24.", + "server.error_server_address_network": "L’indirizzo VPN server deve appartenere al pool selezionato e usare lo stesso prefisso.", + "server.error_server_address_reserved": "L’indirizzo VPN server non può essere indirizzo di rete o broadcast.", + "server.error_listen_port_number": "La porta WireGuard deve essere un numero.", + "server.error_listen_port_range": "La porta WireGuard deve essere tra 1 e 65535.", + "server.error_mtu_number": "MTU deve essere un numero.", + "auth.mfa_title": "Autenticazione a due fattori", + "auth.mfa_login_help": "Inserisci il codice a 6 cifre di Google Authenticator o uno dei codici di recupero.", + "auth.mfa_code": "Codice di autenticazione", + "auth.mfa_verify": "Verifica e accedi", + "auth.mfa_back": "Torna alla password", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Autenticazione a due fattori (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Abilitato", + "settings.mfa_disabled": "Disabilitato", + "settings.mfa_google_help": "Proteggi l’account con Google Authenticator o un’altra app TOTP. Per iniziare serve la password corrente.", + "settings.current_password": "Password corrente", + "settings.mfa_start": "Configura Google Authenticator", + "settings.mfa_secret": "Chiave di configurazione manuale", + "settings.mfa_scan_help": "Scansiona il QR con Google Authenticator e inserisci il codice corrente a 6 cifre per abilitare MFA.", + "settings.mfa_code": "Codice a 6 cifre", + "settings.mfa_enable": "Attiva MFA", + "settings.mfa_manage_help": "Per modificare MFA, inserisci password corrente e codice Authenticator o di recupero.", + "settings.mfa_code_or_recovery": "Codice Authenticator o di recupero", + "settings.mfa_regenerate": "Nuovi codici di recupero", + "settings.mfa_disable": "Disattiva MFA", + "settings.mfa_recovery_title": "Codici di recupero", + "settings.mfa_recovery_help": "Salva questi codici ora. Ognuno può essere usato una volta se Google Authenticator non è disponibile. Non verranno mostrati di nuovo.", + "settings.mfa_recovery_remaining": "Codici di recupero rimanenti: {count}", + "settings.mfa_enabled_ok": "MFA attivata.", + "settings.mfa_disabled_ok": "MFA disattivata.", + "settings.mfa_disable_confirm": "Disattivare l’autenticazione a due fattori per questo account?", + "settings.mfa_regenerate_confirm": "Sostituire tutti i codici di recupero esistenti?", + "settings.mfa_recovery_regenerated": "Nuovi codici di recupero creati.", + "audit.action.auth.mfa_failed": "Verifica MFA non riuscita", + "audit.action.auth.mfa_recovery_used": "Codice di recupero MFA utilizzato", + "audit.action.user.mfa_setup_started": "Configurazione MFA avviata", + "audit.action.user.mfa_enabled": "MFA attivata", + "audit.action.user.mfa_disabled": "MFA disattivata", + "audit.action.user.mfa_disabled_cli": "MFA disattivata da CLI", + "audit.action.user.mfa_recovery_regenerated": "Codici di recupero MFA rigenerati", + "settings.mfa_error_password": "Password corrente non valida.", + "settings.mfa_error_code": "Codice di autenticazione non valido.", + "settings.mfa_error_already_enabled": "MFA è già attiva.", + "settings.mfa_error_not_enabled": "MFA non è attiva.", + "settings.mfa_error_not_started": "Riavvia la configurazione MFA.", + "trace.title": "Traceroute, ping e mappa del percorso", + "trace.subtitle": "Misura la latenza verso un VPS o altro server e individua i ritardi lungo il percorso.", + "trace.target": "IP o nome host del server", + "trace.show_map": "Mostra percorso sulla mappa", + "trace.run": "Avvia traceroute", + "trace.geo_note": "La geolocalizzazione è approssimativa. Con la mappa attiva, gli IP pubblici degli hop vengono inviati a ipwho.is; le mappe sono caricate da OpenStreetMap.", + "trace.latency_note": "Traceroute misura la latenza in millisecondi, non la velocità in Mbit/s.", + "trace.map": "Mappa del percorso", + "trace.map_hint": "Mappa interattiva: trascina per spostare, usa la rotella o +/− per lo zoom e clicca un hop per i dettagli.", + "trace.hop": "Hop / IP", + "trace.location": "Posizione", + "trace.avg_rtt": "RTT medio", + "trace.delta": "Δ RTT", + "trace.loss": "Perdita", + "trace.summary_target": "Destinazione", + "trace.summary_ping": "Ping medio", + "trace.summary_loss": "Perdita ping", + "trace.summary_hops": "Hop", + "trace.no_reply": "Nessuna risposta", + "trace.private": "Rete privata", + "trace.unknown": "Sconosciuto", + "trace.running": "Ping e traceroute in corso… L’operazione può durare un minuto.", + "trace.done": "Tracciamento di rete completato.", + "trace.failed": "Tracciamento di rete non riuscito", + "trace.partial_geo": "Impossibile geolocalizzare alcuni hop pubblici.", + "trace.not_reached": "Destinazione non raggiunta dal traceroute.", + "trace.reached": "Destinazione raggiunta", + "trace.ms": "ms", + "server.tab_trace": "Tracciamento", + "trace.map_controls": "Controlli mappa", + "trace.zoom_in": "Ingrandisci", + "trace.zoom_out": "Riduci", + "trace.fit_route": "Adatta al percorso", + "trace.fit": "Adatta", + "trace.map_click_hint": "Clicca un hop per visualizzare IP, posizione, ASN e RTT.", + "trace.route_path": "Percorso", + "trace.ping_ok_trace_filtered": "La destinazione risponde al ping, ma gli ultimi hop del traceroute non rispondono.", + "trace.latency_legend": "Aumento della latenza tra hop che rispondono", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normale", + "trace.latency_warn": "Δ RTT 5–20 ms — elevato", + "trace.latency_bad": "Δ RTT > 20 ms — forte aumento" +} diff --git a/app/static/locales/pl.json b/app/static/locales/pl.json new file mode 100644 index 0000000..ff5fd67 --- /dev/null +++ b/app/static/locales/pl.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Utwórz użytkownika", + "auth.login_subtitle": "Podaj nazwę użytkownika i hasło WGTools.", + "auth.login_title": "Zaloguj się do WGTools", + "auth.password": "Hasło", + "auth.password_repeat": "Powtórz hasło", + "auth.setup_help": "Pierwsze konto ma pełny dostęp do WGTools. Kolejnych użytkowników można dodać później w ustawieniach.", + "auth.setup_subtitle": "Przed zarządzaniem serwerem trzeba utworzyć konto WGTools.", + "auth.setup_title": "Utwórz pierwszego użytkownika", + "auth.sign_in": "Zaloguj", + "auth.sign_out": "Wyloguj", + "auth.username": "Nazwa użytkownika", + "clients.actions": "Akcje", + "clients.add": "+ Dodaj klienta", + "clients.address": "Adres VPN", + "clients.address_hint": "Pierwszy wolny adres jest proponowany automatycznie.", + "clients.allowed_ips_required": "Podaj przynajmniej jedną sieć AllowedIPs dla konfiguracji klienta.", + "clients.basic_connection": "Ustawienia połączenia", + "clients.basic_details": "Klient", + "clients.client": "Klient", + "clients.client_allowed_ips": "AllowedIPs w konfiguracji klienta", + "clients.config_private_warning": "Ta konfiguracja zawiera klucz prywatny klienta. Przechowuj ją bezpiecznie.", + "clients.config_title": "Konfiguracja klienta", + "clients.config_unavailable": "Konfiguracja niedostępna", + "clients.connection_direct": "Bezpośrednio do WGTools", + "clients.connection_path": "Ścieżka połączenia", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Połącz przez", + "clients.connection_via_hint": "Wybierz publiczny punkt wejścia dla klienta. Relay jest widoczny tylko po instalacji dla wybranego interfejsu WireGuard.", + "clients.copy_config": "Kopiuj", + "clients.copy_done": "Skopiowano konfigurację", + "clients.create_subtitle": "Utwórz peer WireGuard i wygeneruj jego konfigurację.", + "clients.create_title": "Utwórz klienta", + "clients.creating": "Generowanie kluczy i stosowanie konfiguracji klienta…", + "clients.day_fri": "Pt", + "clients.day_mon": "Pon", + "clients.day_sat": "Sob", + "clients.day_sun": "Niedz", + "clients.day_thu": "Czw", + "clients.day_tue": "Wt", + "clients.day_wed": "Śr", + "clients.delete_confirm": "Usunąć tego klienta z WireGuard? WGTools utworzy kopię i usunie powiązane reguły automatyczne.", + "clients.deleted": "Klient usunięty", + "clients.dns": "DNS (opcjonalnie)", + "clients.dns_hint": "Serwery DNS IPv4 rozdzielone przecinkami.", + "clients.download_config": "Pobierz .conf", + "clients.duplicate": "Duplikuj", + "clients.duplicate_address_error": "Ten adres VPN jest już używany przez innego peera.", + "clients.duplicate_name_error": "Peer o tej nazwie już istnieje.", + "clients.duplicate_ready": "Kopia gotowa. WGTools przydzielił nową nazwę i adres VPN. Sprawdź ustawienia przed zapisaniem.", + "clients.duplicate_site_hint": "Sieci zdalne wyczyszczono, aby uniknąć zduplikowanych tras. Podaj sieci dla nowego peera Site-to-site.", + "clients.duplicate_suffix": "kopia", + "clients.edit_subtitle": "Zaktualizuj peer na serwerze. Zmiany są stosowane bez restartu WireGuard.", + "clients.edit_title": "Edytuj klienta", + "clients.endpoint": "Endpoint serwera", + "clients.endpoint_hint": "Dla klientów zdalnych użyj publicznego IP lub domeny przekierowującej port WireGuard na ten serwer.", + "clients.existing": "Istniejący peer", + "clients.expiration": "Czas ważności dostępu", + "clients.expiration_action": "Po wygaśnięciu", + "clients.expiration_action_hint": "Jeśli opcja nie jest zaznaczona, klient zostanie w WGTools, ale utraci dostęp WireGuard. Ustaw nowy termin lub Bez terminu i zapisz, aby przywrócić dostęp.", + "clients.expiration_datetime": "Wygasa dnia", + "clients.expiration_datetime_hint": "Używa lokalnej daty i godziny przeglądarki.", + "clients.expiration_delete": "Usuń klienta", + "clients.expiration_future_required": "Wybierz przyszłą datę i godzinę.", + "clients.expiration_hint": "Po wygaśnięciu WGTools wykonuje wybraną akcję na początku następnej minuty. Najpierw tworzy kopię WireGuard.", + "clients.expire_1d": "1 dzień", + "clients.expire_1h": "1 godzina", + "clients.expire_3h": "3 godziny", + "clients.expire_6h": "6 godzin", + "clients.expire_custom": "Własna data i godzina", + "clients.expire_never": "Bez terminu wygaśnięcia", + "clients.expired": "Wygasło", + "clients.expired_disabled_hint": "Okres dostępu wygasł. Klient pozostał, ale dostęp WireGuard jest wyłączony. Ustaw nowy termin lub Bez terminu i zapisz.", + "clients.expired_disabled_short": "Wygasło · wyłączono", + "clients.expired_disabled_status": "Wygasło", + "clients.expires_days": "Wygasa za {n} dni", + "clients.expires_hours": "Wygasa za {n} godz.", + "clients.expires_minutes": "Wygasa za {n} min", + "clients.generated_config": "Wygenerowana konfiguracja klienta", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 sekund to dobry domyślny czas dla klientów za NAT.", + "clients.local_access_exceptions": "Dozwolone adresy lokalne", + "clients.local_access_exceptions_hint": "Opcjonalne adresy IP lub CIDR dostępne nawet wtedy, gdy ich sieć lokalna lub Site-to-site jest zablokowana. Oddziel przecinkami.", + "clients.managed": "Zarządzany przez WGTools", + "clients.name": "Nazwa", + "clients.no_peers": "Nie znaleziono peerów", + "clients.peers": "Peery", + "clients.peers_subtitle": "Zmiany są archiwizowane i stosowane przez wg syncconf bez restartu interfejsu WireGuard.", + "clients.protected_networks_reference": "Zablokowane sieci lokalne (informacja)", + "clients.protected_networks_reference_hint": "Te sieci nie są wpisywane do AllowedIPs. Dostęp blokują zasady serwera WGTools; poszczególne adresy można dopuścić powyżej.", + "clients.psk": "Klucz współdzielony (PSK)", + "clients.psk_enable": "Używaj dodatkowego klucza współdzielonego WireGuard", + "clients.psk_hint": "Zalecane. Dodaje dodatkowy sekret symetryczny do handshake WireGuard. Standardowe klienty go obsługują; WGTools dołącza PSK do konfiguracji i QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generowanie kodu QR…", + "clients.quick_search": "Szybkie wyszukiwanie", + "clients.quick_search_clear": "Wyczyść wyszukiwanie", + "clients.quick_search_empty": "Brak pasujących klientów", + "clients.relay_endpoint_note": "Wygenerowana konfiguracja klienta połączy się z {endpoint}. Serwer WireGuard pozostaje na tym hoście WGTools.", + "clients.relay_required": "Wybierz VPS Relay dla tego klienta.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "niedostępny", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "Endpoint klienta jest generowany automatycznie na podstawie Relay.", + "clients.remote_hint": "Sieci za tym peerem. Jedna w wierszu lub rozdzielone przecinkami.", + "clients.remote_networks": "Sieci zdalne", + "clients.remote_required": "Podaj co najmniej jedną sieć zdalną dla peera Site-to-site.", + "clients.required": "Nazwa i adres VPN są wymagane.", + "clients.route_custom": "Własne", + "clients.route_full": "Pełny tunel", + "clients.route_full_except_local": "Pełny tunel bez sieci lokalnych", + "clients.route_hint": "Tylko te sieci zostaną wpisane do AllowedIPs konfiguracji klienta.", + "clients.route_preset": "Ruch przez VPN", + "clients.route_vpn": "Tylko sieć VPN", + "clients.route_vpn_lan": "VPN + lokalny LAN", + "clients.saved": "Klient zapisany", + "clients.schedule_blocked_short": "Harmonogram · blokada", + "clients.schedule_blocked_status": "Zablokowano przez harmonogram", + "clients.schedule_days": "Dozwolone dni", + "clients.schedule_days_required": "Wybierz co najmniej jeden dzień harmonogramu.", + "clients.schedule_disabled_hint": "Ten klient jest obecnie blokowany harmonogramem. WGTools automatycznie przywróci peera w następnym dozwolonym okresie.", + "clients.schedule_enable": "Ogranicz dostęp harmonogramem", + "clients.schedule_from": "Dostęp od", + "clients.schedule_hint": "WGTools może automatycznie wyłączać i przywracać klienta w wybrane dni i godziny bez zmiany konfiguracji.", + "clients.schedule_short": "Harmonogram", + "clients.schedule_time_required": "Ustaw godzinę początku i końca harmonogramu.", + "clients.schedule_timezone_hint": "Harmonogram używa lokalnego czasu serwera WireGuard. Obsługuje przedziały przez północ, np. 22:00–06:00.", + "clients.schedule_title": "Harmonogram dostępu", + "clients.schedule_to": "Dostęp do", + "clients.security_access": "Bezpieczeństwo i czas dostępu", + "clients.server_host": "Adres / domena serwera", + "clients.server_host_hint": "Publiczny IP lub domena używane przez klienta. Wcześniejsze wartości są proponowane.", + "clients.server_host_required": "Adres / domena serwera są wymagane do wygenerowania konfiguracji.", + "clients.server_peer": "Peer serwera", + "clients.server_port": "Port WireGuard", + "clients.server_port_hint": "Pobierany automatycznie z konfiguracji serwera.", + "clients.site_to_site": "Sieć do sieci", + "clients.status": "Status", + "clients.subtitle": "Peery WireGuard, stan na żywo i zarządzanie konfiguracjami klientów.", + "clients.tab_basic": "Podstawowe", + "clients.tab_config": "Konfiguracja", + "clients.tab_policy": "Zasady", + "clients.tab_security": "Bezpieczeństwo", + "clients.title": "Klienci", + "clients.type": "Typ", + "clients.unmanaged_note": "Peer istniał przed WGTools. Nie da się odzyskać jego klucza prywatnego. WGTools może edytować peera na serwerze, ale nie wygeneruje jego konfiguracji ani QR.", + "clients.updating": "Aktualizacja klienta…", + "common.actions": "Akcje", + "common.ago": "temu", + "common.cancel": "Anuluj", + "common.checking": "Sprawdzanie…", + "common.close": "Zamknij", + "common.config": "Konfiguracja", + "common.delete": "Usuń", + "common.disabled": "Wyłączone", + "common.edit": "Edytuj", + "common.enabled": "Włączone", + "common.loading": "Ładowanie…", + "common.never": "Nigdy", + "common.no": "Nie", + "common.not_configured": "Nie skonfigurowano", + "common.not_installed": "Nie zainstalowano", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Odśwież", + "common.running": "Działa", + "common.save": "Zapisz", + "common.stopped": "Zatrzymano", + "common.total": "Łącznie", + "common.unknown": "Nieznany", + "common.updated": "Zaktualizowano", + "common.yes": "Tak", + "dashboard.active_peers": "Aktywne peery", + "dashboard.active_peers_subtitle": "Dane na żywo z wg show.", + "dashboard.activity": "Przegląd systemu", + "dashboard.activity_subtitle": "Kontrole działającego WireGuard bez wprowadzania zmian.", + "dashboard.cores": "rdzenie", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Ostatnie 24 godz.", + "dashboard.history_avg": "Śr.", + "dashboard.history_max": "Maks.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "teraz", + "dashboard.memory": "Pamięć", + "dashboard.network": "Sieć", + "dashboard.peers": "Peery", + "dashboard.quick_search": "Szybkie wyszukiwanie", + "dashboard.quick_search_clear": "Wyczyść wyszukiwanie", + "dashboard.quick_search_empty": "Brak peerów pasujących do wyszukiwania", + "dashboard.restart": "Uruchom ponownie", + "dashboard.restart_confirm": "Uruchomić WireGuard ponownie? Aktywni klienci VPN połączą się automatycznie.", + "dashboard.restart_ok": "WireGuard uruchomiono ponownie.", + "dashboard.routing": "Trasowanie", + "dashboard.site_to_site": "Sieć do sieci", + "dashboard.start": "Uruchom", + "dashboard.start_ok": "Uruchomiono WireGuard.", + "dashboard.stop": "Zatrzymaj", + "dashboard.stop_confirm": "Zatrzymać WireGuard? Aktywni klienci VPN zostaną rozłączeni.", + "dashboard.stop_ok": "Zatrzymano WireGuard.", + "dashboard.subtitle": "Stan serwera WireGuard, peery i ruch na żywo.", + "dashboard.title": "Pulpit", + "dashboard.traffic": "Ruch", + "dashboard.uptime": "Czas działania", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Zasady dostępu do serwera", + "groups.additional_allowed": "Dodatkowe dozwolone adresy", + "groups.additional_blocked": "Dodatkowe blokowane adresy", + "groups.allow": "Zezwól", + "groups.allowed": "Dozwolone", + "groups.allowed_addresses": "Dozwolone adresy / sieci", + "groups.apply_current_template": "Zastosuj bieżący szablon grupy", + "groups.apply_defaults": "Zastosuj bieżący szablon grupy", + "groups.apply_defaults_hint": "Kopiuje trasy, DNS i Keepalive z szablonu grupy do klienta. Zapisz klienta, a następnie wygeneruj nową konfigurację lub QR, jeśli urządzenie wymaga aktualizacji.", + "groups.basic": "Informacje podstawowe", + "groups.block": "Blokuj", + "groups.blocked": "Zablokowane", + "groups.blocked_addresses": "Zablokowane adresy / sieci", + "groups.client_config_source": "Źródło konfiguracji klienta", + "groups.client_defaults": "Domyślne ustawienia klienta", + "groups.client_group_hint": "Opcjonalna grupa do ponownego użycia zasad dostępu i ustawień klienta. Grupy dotyczą wybranego interfejsu WireGuard.", + "groups.config_differs": "Konfiguracja klienta różni się od bieżącego szablonu grupy. Zasady serwera są aktualne, ale urządzenie wymaga nowej konfiguracji lub kodu QR.", + "groups.config_differs_short": "Konfiguracja klienta różni się od grupy", + "groups.create": "Utwórz grupę", + "groups.create_title": "Utwórz grupę", + "groups.created": "Utworzono grupę", + "groups.creating": "Tworzenie grupy…", + "groups.defaults_applied": "Zastosowano szablon grupy. Zapisz klienta, aby zachować zmiany.", + "groups.defaults_hint": "Określa ruch wysyłany przez urządzenie przez WireGuard. Zasady serwera niezależnie decydują o dostępie. Zmiana szablonu nie zmienia automatycznie konfiguracji już zainstalowanych.", + "groups.delete_message": "Usunąć „{name}”? Konfiguracje klientów nie są usuwane wraz z grupą.", + "groups.delete_move": "Przenieś klientów do innej grupy", + "groups.delete_title": "Usuń grupę klientów", + "groups.delete_unassign": "Usuń przypisanie klientów do grupy", + "groups.deleted": "Usunięto grupę", + "groups.deleting": "Aktualizacja klientów i usuwanie grupy…", + "groups.description": "Opis", + "groups.edit_title": "Edytuj grupę", + "groups.editor_subtitle": "Grupa łączy aktywne zasady dostępu do serwera z szablonem konfiguracji klientów.", + "groups.effective_allow": "Dozwolone wyjątki", + "groups.effective_deny": "Zablokowane wyjątki", + "groups.effective_policy": "Obowiązujące zasady serwera", + "groups.empty": "Brak grup klientów. Utwórz grupę, aby ponownie wykorzystywać zasady dostępu i ustawienia.", + "groups.group": "Grupa", + "groups.inherit": "Dziedzicz", + "groups.internet_access": "Dostęp do Internetu", + "groups.internet_short": "Internet", + "groups.local_access": "Sieci lokalne", + "groups.local_short": "Lokalnie", + "groups.manage": "Grupy", + "groups.members_count": "Klienci: {count}", + "groups.name": "Nazwa", + "groups.name_required": "Nazwa grupy jest wymagana.", + "groups.new_client_defaults": "Szablon konfiguracji klienta", + "groups.new_clients_short": "Nowi klienci", + "groups.no_group": "Brak grupy", + "groups.none": "Brak", + "groups.override_client_config": "Nadpisz szablon grupy dla tego klienta", + "groups.override_client_config_hint": "Wyłączone: trasy, DNS i Keepalive pochodzą z grupy. Włączone: klient zachowuje własne wartości. Wyjątki zasad serwera działają niezależnie.", + "groups.policy_addresses_hint": "Adresy IPv4 lub CIDR rozdzielone przecinkami. Wyjątki klienta mają pierwszeństwo przed wyjątkami grupy.", + "groups.policy_custom": "Własne zasady", + "groups.policy_inherit": "Użyj zasad grupy", + "groups.policy_mode": "Źródło zasad", + "groups.policy_mode_hint": "Domyślnie dziedziczone są zasady grupy. Wyjątki klienta nigdy nie modyfikują grupy.", + "groups.routes_required": "Trasy klienta nie mogą być puste.", + "groups.subtitle": "Korzystaj ponownie z zasad dostępu i ustawień klientów na wybranym interfejsie WireGuard.", + "groups.title": "Grupy klientów", + "groups.traffic_through_vpn": "Ruch przez VPN", + "groups.updated": "Zaktualizowano grupę", + "groups.updating": "Aktualizacja zasad grupy…", + "help.example_note": "Wszystkie adresy, interfejsy, nazwy peerów i domeny w przykładach pomocy są fikcyjne. Zastąp je danymi swojej sieci.", + "help.navigation": "Nawigacja pomocy", + "help.open": "Otwórz pomoc", + "help.subtitle": "Przystępna pomoc dotycząca panelu, serwera, klientów i ustawień z krótkimi przykładami.", + "help.title": "Pomoc WGTools", + "interfaces.add": "+ Dodaj interfejs", + "interfaces.create": "Utwórz interfejs", + "interfaces.create_confirm": "Utworzyć i uruchomić interfejs {name}?", + "interfaces.create_failed": "Nie udało się utworzyć interfejsu", + "interfaces.create_hint": "Przed utworzeniem konfiguracji WGTools sprawdza, czy sieć VPN, port UDP i tablica routingu nie kolidują z innymi interfejsami WireGuard.", + "interfaces.create_subtitle": "Utwórz niezależny interfejs WireGuard z własną pulą adresów, portem UDP i ustawieniami routingu.", + "interfaces.create_title": "Dodaj interfejs WireGuard", + "interfaces.created": "Pomyślnie utworzono interfejs.", + "interfaces.creating": "Generowanie kluczy, zapisywanie konfiguracji i uruchamianie WireGuard…", + "interfaces.current": "Bieżący", + "interfaces.delete": "Usuń", + "interfaces.delete_confirm": "Usunąć interfejs {name}? Zostanie usunięta jego konfiguracja WireGuard oraz wszystkie peery. Najpierw powstanie kopia zapasowa.", + "interfaces.delete_failed": "Nie udało się usunąć interfejsu", + "interfaces.delete_last": "Nie można tutaj usunąć ostatniego skonfigurowanego interfejsu WireGuard.", + "interfaces.delete_tooltip": "Usuń ten interfejs WireGuard", + "interfaces.deleted": "Usunięto interfejs. Kopia: {backup}", + "interfaces.deleting": "Zatrzymywanie WireGuard i usuwanie interfejsu…", + "interfaces.display_name": "Nazwa wyświetlana", + "interfaces.display_name_edit_hint": "Tylko nazwa wyświetlana; nazwa interfejsu Linux nie zmieni się.", + "interfaces.display_name_hint": "Opcjonalna przyjazna nazwa, np. Praca lub Wykonawcy.", + "interfaces.identity": "Tożsamość interfejsu", + "interfaces.none": "Nie znaleziono interfejsów WireGuard", + "interfaces.none_configured": "Nie skonfigurowano jeszcze żadnego interfejsu WireGuard.", + "interfaces.peers_short": "peery", + "interfaces.rename_failed": "Nie udało się zapisać nazwy wyświetlanej interfejsu.", + "interfaces.select": "Wybierz", + "interfaces.subtitle": "Każdy interfejs ma własną sieć VPN, port, peery i reguły. Wybierz interfejs, aby zarządzać nim w WGTools.", + "interfaces.switch_title": "Interfejsy WireGuard", + "interfaces.system_name": "Nazwa systemowa", + "interfaces.system_name_hint": "Nazwa interfejsu Linux, np. wg1. Nie można jej zmienić po utworzeniu.", + "interfaces.title": "Interfejsy WireGuard", + "interfaces.unique_port_hint": "Każdy interfejs WireGuard na tym serwerze musi używać osobnego portu UDP.", + "interfaces.unique_table_hint": "WGTools zaleca osobną tablicę routingu dla każdego interfejsu. Pozostaw puste przy zwykłym routingu.", + "nav.clients": "Klienci", + "nav.dashboard": "Pulpit", + "nav.server": "Serwer", + "nav.settings": "Ustawienia", + "server.access_apply_confirm": "Zapisać i zastosować tę regułę zapory? WireGuard zostanie na krótko uruchomiony ponownie po wykonaniu kopii.", + "server.access_rule_deleted": "Usunięto regułę dostępu.", + "server.access_rule_help": "Utwórz regułę dostępu FORWARD bez ręcznej edycji poleceń iptables.", + "server.access_rule_order_hint": "WGTools wstawia reguły na początek łańcucha FORWARD, aby ograniczenia działały przed ogólnymi regułami VPN ACCEPT.", + "server.access_rule_saved": "Zapisano i zastosowano regułę dostępu.", + "server.action": "Akcja", + "server.action_hint": "REJECT informuje klienta o odmowie; DROP odrzuca bez odpowiedzi; ACCEPT jawnie zezwala.", + "server.add_access_rule": "Dodaj regułę dostępu", + "server.add_route": "Dodaj trasę", + "server.address": "Adres", + "server.any": "Dowolny", + "server.any_protocol": "Dowolny", + "server.apply_confirm": "Zapisać i zastosować ustawienia serwera? WireGuard zostanie na krótko uruchomiony ponownie. WGTools najpierw utworzy kopię i automatycznie przywróci konfigurację w razie błędu.", + "server.apply_settings": "Zapisz i zastosuj", + "server.applying_rule": "Tworzenie kopii i stosowanie zmian…", + "server.applying_settings": "Weryfikacja ustawień, tworzenie kopii i stosowanie zmian…", + "server.basic_settings": "Ustawienia podstawowe", + "server.config_tab_help": "Otwórz edytor źródłowej konfiguracji wybranego interfejsu WireGuard.", + "server.create_confirm": "Utworzyć i uruchomić serwer WireGuard z tymi ustawieniami?", + "server.create_server": "Utwórz serwer", + "server.create_step_conf": "Utwórz konfigurację wybranego interfejsu WireGuard z uprawnieniami 600.", + "server.create_step_forward": "Skonfiguruj forwarding, NAT i opcjonalny routing oparty na regułach.", + "server.create_step_key": "Wygeneruj nową parę kluczy serwera.", + "server.create_step_start": "Włącz i uruchom wybrany interfejs wg-quick.", + "server.create_subtitle": "WireGuard jest zainstalowany, ale wybrany interfejs nie jest skonfigurowany.", + "server.create_success": "Pomyślnie utworzono serwer WireGuard.", + "server.create_title": "Utwórz serwer WireGuard", + "server.creating": "Generowanie kluczy, zapisywanie konfiguracji i uruchamianie WireGuard…", + "server.custom_preserved": "Bloki peerów, trasy Site-to-site i niestandardowe reguły PostUp/PostDown poza tymi polami zostaną zachowane.", + "server.delete_access_confirm": "Usunąć tę regułę dostępu i zastosować zmianę?", + "server.delete_route_confirm": "Usunąć tę własną trasę i zastosować zmianę?", + "server.destination": "Cel", + "server.destination_hint": "Puste = dowolny. IP, CIDR lub zakres adresów. Oddziel wiele celów przecinkami.", + "server.destination_port": "Port docelowy", + "server.destination_port_hint": "Opcjonalnie. Port np. 443 lub zakres 10000:20000. Najpierw wybierz TCP lub UDP.", + "server.details": "Szczegóły", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostyka", + "server.diagnostics_done": "Diagnostyka zakończona", + "server.diagnostics_subtitle": "Bieżące kontrole systemu. Konfiguracja nie jest zmieniana.", + "server.direction": "Hook", + "server.edit_access_rule": "Edytuj regułę dostępu", + "server.edit_route": "Edytuj trasę", + "server.edit_server": "Edytuj serwer", + "server.edit_subtitle": "Edytuj podstawowe ustawienia WireGuard, routingu i NAT. Istniejące peery i własne reguły zostają zachowane.", + "server.edit_title": "Ustawienia serwera", + "server.edit_warning": "Zastosowanie ustawień interfejsu, routingu lub zapory na krótko restartuje WireGuard. Aktywne peery połączą się ponownie.", + "server.enable_forwarding": "Włącz przekazywanie IPv4", + "server.enable_nat": "Włącz NAT / Masquerade", + "server.firewall": "Zapora i NAT", + "server.firewall_subtitle": "Reguły wykryte w hookach WireGuard.", + "server.firewall_subtitle_v08": "Reguły forwarding/NAT i dostępu z konfiguracji interfejsu. Proste reguły edytujesz tutaj, zaawansowane w edytorze źródłowym.", + "server.forward_from_vpn": "Zezwól na przekazywanie z VPN", + "server.forward_to_vpn": "Zezwól na przekazywanie do VPN", + "server.forwarding_section": "Przekazywanie i NAT", + "server.gateway": "Brama", + "server.gateway_hint": "Wymagana tylko przy korzystaniu z tablicy routingu regułowego.", + "server.install_success": "Pomyślnie zainstalowano WireGuard.", + "server.install_wireguard": "Zainstaluj WireGuard", + "server.install_wireguard_help": "Uruchamia apt update i instaluje WireGuard oraz wymagane narzędzia sieciowe.", + "server.install_wireguard_title": "Zainstaluj WireGuard", + "server.installing": "Instalowanie WireGuard… Może potrwać minutę.", + "server.interface": "Interfejs", + "server.interface_hint": "WGTools zarządza obecnie tym interfejsem.", + "server.interface_name": "Interfejs", + "server.interface_section": "Interfejs WireGuard", + "server.ip_forwarding": "Przekazywanie IPv4", + "server.kind": "Rodzaj", + "server.listen_port": "Port nasłuchiwania", + "server.local_network": "Sieć lokalna", + "server.local_network_hint": "Opcjonalna trasa dodawana do tablicy reguł routingu.", + "server.managed_automatically": "Zarządzane automatycznie", + "server.nat": "NAT / Masquerade", + "server.network": "Sieć", + "server.network_settings": "Sieć i NAT", + "server.no_firewall": "Nie znaleziono reguł zapory", + "server.no_routes": "Nie znaleziono tras", + "server.not_configured": "Nie skonfigurowano", + "server.not_set": "Nie ustawiono", + "server.policy_disabled_hint": "Wyłącz dla zwykłego routingu systemowego. Włącz tylko jeśli ten VPN wymaga osobnej tablicy routingu według źródła.", + "server.policy_enabled": "Włącz routing regułowy", + "server.policy_table": "Tablica reguł", + "server.policy_table_hint": "Dla zwykłego routingu pozostaw puste; np. 200 dla routingu według źródła.", + "server.port_word": "port", + "server.private_hidden": "Skonfigurowano (ukryto)", + "server.private_key": "Klucz prywatny", + "server.protocol": "Protokół", + "server.route_apply_confirm": "Zapisać i zastosować tę trasę? WireGuard zostanie na krótko uruchomiony ponownie po utworzeniu kopii.", + "server.route_custom": "Własna", + "server.route_deleted": "Usunięto trasę.", + "server.route_device_hint": "Opcjonalny interfejs wyjściowy, np. wg0 lub enp6s18.", + "server.route_editor_help": "Dodaj trasę instalowaną przy uruchomieniu WireGuard i usuwaną po zatrzymaniu.", + "server.route_gateway_hint": "Opcjonalna brama następnego skoku. Wymagana jest brama lub interfejs.", + "server.route_managed_peer": "Peer Site-to-site", + "server.route_managed_server": "Ustawienie serwera", + "server.route_network_hint": "Sieć IPv4, np. 10.20.0.0/24, lub 'default'.", + "server.route_saved": "Zapisano i zastosowano trasę.", + "server.route_table_hint": "Użyj 'main' dla zwykłego routingu albo numerycznej tablicy np. 200.", + "server.route_type": "Typ", + "server.routes": "Wykryte trasy", + "server.routes_subtitle": "Trasy z PostUp/PostDown i aktualnego stanu routingu regułowego.", + "server.routes_subtitle_v08": "Trasy serwera, Site-to-site i własne z wybranego interfejsu. Własne trasy można tu dodawać, edytować i usuwać.", + "server.routing": "Trasowanie", + "server.routing_section": "Trasowanie", + "server.rule": "Reguła", + "server.rule_access": "Reguła dostępu", + "server.rule_advanced": "Zaawansowane", + "server.rule_apply_warning": "Zastosowanie trasy lub reguły zapory na krótko restartuje WireGuard. WGTools tworzy kopię i przywraca konfigurację automatycznie w razie błędu.", + "server.rule_client_exception": "Wyjątek klienta", + "server.rule_client_policy": "Zasada klienta", + "server.rule_managed_server": "Ustawienie serwera", + "server.rule_type": "Typ", + "server.run_diagnostics": "Uruchom diagnostykę", + "server.save_apply": "Zapisz i zastosuj", + "server.save_config": "SaveConfig", + "server.server_address": "Adres VPN serwera", + "server.server_address_hint": "Zwykle pierwszy użyteczny adres w sieci VPN.", + "server.settings_applied": "Pomyślnie zapisano i zastosowano ustawienia serwera.", + "server.settings_apply_failed": "Nie udało się zastosować ustawień serwera", + "server.setup_required": "Wymagana konfiguracja", + "server.source": "Źródło", + "server.source_hint": "Puste = dowolny. IP, CIDR lub zakres np. 10.0.0.100-10.0.0.120.", + "server.subtitle": "Instalacja, pierwsza konfiguracja i bieżące ustawienia serwera WireGuard.", + "server.tab_config": "Konfiguracja", + "server.tab_interface": "Interfejs", + "server.tab_routing": "Trasowanie", + "server.tab_vps": "VPS", + "server.table": "Tabela", + "server.tabs_aria": "Sekcje ustawień serwera", + "server.title": "Serwer", + "server.uplink": "Interfejs uplink", + "server.use_raw_editor": "Użyj edytora źródłowego", + "server.via": "Przez / urządzenie", + "server.via_word": "via", + "server.vpn_network": "Sieć VPN", + "server.vpn_network_hint": "Adresy klientów będą później przydzielane z tej sieci.", + "server.vpn_pool": "Pula adresów VPN", + "server.wg_not_installed": "WireGuard nie jest zainstalowany", + "server.wg_not_installed_subtitle": "WGTools może automatycznie zainstalować wymagane pakiety Debiana.", + "server.what_happens": "Co zrobi WGTools", + "settings.about": "O programie", + "settings.add_user": "Dodaj użytkownika", + "settings.advanced": "Zaawansowane", + "settings.advanced_subtitle": "Bezpośredni dostęp do zaawansowanych narzędzi konfiguracji WireGuard.", + "settings.appearance": "Wygląd", + "settings.applying_config": "Weryfikacja konfiguracji, tworzenie kopii i stosowanie zmian…", + "settings.backup_count": "Zapisane kopie", + "settings.backup_retention": "Liczba kopii", + "settings.backup_retention_help": "Stare automatyczne kopie są usuwane po utworzeniu nowej. Od 1 do 200 plików.", + "settings.backups": "Kopie konfiguracji", + "settings.backups_always_on": "Włączone", + "settings.backups_subtitle": "WGTools tworzy automatyczne kopie przed operacjami zmieniającymi konfigurację. Nie można ich wyłączyć.", + "settings.change_password": "Zmień hasło", + "settings.check_updates": "Sprawdź aktualizacje", + "settings.config_applied": "Pomyślnie zapisano i zastosowano konfigurację.", + "settings.config_applied_restarted": "Zastosowano konfigurację i uruchomiono ponownie WireGuard.", + "settings.config_applied_stopped": "Zapisano konfigurację. WireGuard był zatrzymany i pozostał zatrzymany.", + "settings.config_apply_failed": "Nie udało się zastosować konfiguracji", + "settings.config_load_failed": "Nie udało się wczytać konfiguracji", + "settings.current_user": "Bieżący użytkownik", + "settings.current_version": "Bieżąca wersja", + "settings.audit_action": "Akcja", + "settings.audit_empty": "Brak zdarzeń audytu", + "settings.audit_log": "Dziennik audytu", + "settings.audit_log_subtitle": "Działania w panelu, logowanie, Telegram i historia połączeń klientów WireGuard. Sekrety nie są zapisywane.", + "settings.audit_object": "Obiekt", + "settings.audit_result": "Wynik", + "settings.audit_retention_note": "Przechowywanie: 30 dni", + "settings.audit_search": "Szybkie wyszukiwanie", + "settings.audit_search_clear": "Wyczyść wyszukiwanie", + "settings.audit_search_empty": "Brak zdarzeń audytu pasujących do wyszukiwania", + "settings.audit_time": "Data / godzina", + "settings.audit_user": "Użytkownik", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Utworzono regułę dostępu", + "audit.action.access_rule.deleted": "Usunięto regułę dostępu", + "audit.action.access_rule.updated": "Zaktualizowano regułę dostępu", + "audit.action.auth.first_user_created": "Utworzono pierwszego użytkownika", + "audit.action.auth.login": "Zalogowano", + "audit.action.auth.login_failed": "Logowanie nie powiodło się", + "audit.action.auth.logout": "Wylogowano", + "audit.action.backup.full_created": "Utworzono pełną kopię zapasową", + "audit.action.backup.full_restored": "Przywrócono pełną kopię zapasową", + "audit.action.client.config_downloaded": "Pobrano konfigurację klienta", + "audit.action.client.config_viewed": "Wyświetlono konfigurację klienta", + "audit.action.client.created": "Utworzono klienta", + "audit.action.client.deleted": "Klient usunięty", + "audit.action.client.qr_viewed": "Wyświetlono kod QR klienta", + "audit.action.client.updated": "Zaktualizowano klienta", + "audit.action.client_group.created": "Utworzono grupę klientów", + "audit.action.client_group.deleted": "Usunięto grupę klientów", + "audit.action.client_group.updated": "Zaktualizowano grupę klientów", + "audit.action.interface.created": "Utworzono interfejs", + "audit.action.interface.deleted": "Usunięto interfejs", + "audit.action.interface.renamed": "Zmieniono nazwę interfejsu", + "audit.action.route.created": "Utworzono trasę", + "audit.action.route.deleted": "Usunięto trasę", + "audit.action.route.updated": "Zaktualizowano trasę", + "audit.action.server.created": "Utworzono serwer", + "audit.action.server.raw_config_applied": "Zastosowano konfigurację źródłową", + "audit.action.server.settings_applied": "Zastosowano ustawienia serwera", + "audit.action.settings.updated": "Zaktualizowano ustawienia panelu", + "audit.action.telegram.action_denied": "Odrzucono akcję Telegram", + "audit.action.telegram.action_failed": "Akcja Telegram nie powiodła się", + "audit.action.telegram.connection_test": "Test połączenia Telegram", + "audit.action.telegram.settings_updated": "Zaktualizowano ustawienia Telegram", + "audit.action.update.checked": "Sprawdzono aktualizację", + "audit.action.update.scheduled": "Zaplanowano aktualizację", + "audit.action.update.backup_created": "Kopia przed aktualizacją", + "audit.action.update.completed": "Zakończono aktualizację", + "audit.action.update.failed": "Aktualizacja nie powiodła się", + "audit.action.update.rollback_completed": "Przywrócono poprzednią wersję", + "audit.action.update.rollback_failed": "Nie udało się cofnąć aktualizacji", + "audit.action.user.created": "Utworzono użytkownika", + "audit.action.user.deleted": "Usunięto użytkownika", + "audit.action.user.password_changed": "Zmieniono hasło użytkownika", + "audit.action.vps.candidate_deleted": "Usunięto kandydata VPS", + "audit.action.vps.candidate_saved": "Zapisano kandydata VPS", + "audit.action.vps.detached": "Odłączono VPS Relay", + "audit.action.vps.relay_installed": "Zainstalowano VPS Relay", + "audit.action.wireguard.client_connected": "Połączono klienta WireGuard", + "audit.action.wireguard.installed": "Zainstalowano WireGuard", + "audit.action.wireguard.restarted": "Uruchomiono WireGuard ponownie", + "audit.action.wireguard.started": "Uruchomiono WireGuard", + "audit.action.wireguard.stopped": "Zatrzymano WireGuard", + "audit.result.applied": "zastosowano", + "audit.result.available": "dostępna", + "audit.result.changed": "zmieniono", + "audit.result.created": "utworzono", + "audit.result.current": "aktualna", + "audit.result.deleted": "usunięto", + "audit.result.detached": "odłączono", + "audit.result.denied": "odrzucono", + "audit.result.downloaded": "pobrano", + "audit.result.endpoint": "Punkt końcowy", + "audit.result.error": "Błąd", + "audit.result.installed": "zainstalowano", + "audit.result.invalid_credentials": "nieprawidłowe dane logowania", + "audit.result.ok": "OK", + "audit.result.queued": "w kolejce", + "audit.result.restarted": "uruchomiono ponownie", + "audit.result.restored": "przywrócono", + "audit.result.rotated": "odnowiono", + "audit.result.saved": "zapisano", + "audit.result.shown": "wyświetlono", + "audit.result.started": "uruchomiono", + "audit.result.stopped": "zatrzymano", + "audit.result.updated": "zaktualizowano", + "settings.delete_user": "Usuń", + "settings.delete_user_confirm": "Usunąć użytkownika {name}?", + "settings.edit_raw_config": "Edytuj konfigurację interfejsu", + "settings.expert_mode": "Ekspert", + "settings.full_backup_component_clients": "Metadane klientów WGTools, klucze prywatne, PSK, terminy ważności i grupy wymagane do odtworzenia konfiguracji oraz QR.", + "settings.full_backup_component_db": "Baza WGTools: użytkownicy, preferencje, poczta/SMTP, Telegram i zapisany stan VPS Relay.", + "settings.full_backup_component_relay": "Dane odzyskiwania VPS Relay: identyfikatory kontrolera i tenanta, token zarządzania oraz klucz transportowy Home. Po przywróceniu WGTools może odbudować lokalny transport i połączyć zachowany tenant.", + "settings.full_backup_component_system": "Plik sysctl przekazywania IPv4 WGTools, nazwy wyświetlane interfejsów oraz zasady i szablony grup, jeśli istnieją. Automatyczna historia konfiguracji interfejsów jest celowo pomijana.", + "settings.full_backup_component_wg": "Wszystkie wykryte konfiguracje interfejsów WireGuard z /etc/wireguard/ wraz ze stanem działania.", + "settings.full_backup_create_failed": "Nie udało się utworzyć pełnej kopii", + "settings.full_backup_creating": "Tworzenie pełnej kopii zapasowej…", + "settings.full_backup_download": "Utwórz", + "settings.full_backup_downloaded": "Kopia utworzona i pobrana. Przechowuj ją bezpiecznie.", + "settings.full_backup_downloaded_short": "Pobrano pełną kopię.", + "settings.full_backup_help": "Tworzy przenośną kopię WGTools do migracji lub odzyskiwania: konfiguracje WireGuard, użytkownicy, ustawienia, grupy, dane klientów i informacje potrzebne do ponownego połączenia tenantów VPS Relay.", + "settings.full_backup_no_file": "Nie wybrano kopii", + "settings.full_backup_restore": "Przywróć", + "settings.full_backup_restore_confirm": "Przywrócić pełną kopię WGTools? Użytkownicy, ustawienia, zarządzani klienci i konfiguracje WireGuard z kopii zostaną przywrócone. Interfejsy mogą zostać zrestartowane. WGTools najpierw utworzy kopię bezpieczeństwa i automatycznie cofnie zmiany w razie błędu.", + "settings.full_backup_restore_failed": "Przywracanie nie powiodło się", + "settings.full_backup_restored": "Pomyślnie przywrócono kopię. Zaloguj się kontem z przywróconej kopii.", + "settings.full_backup_restored_short": "Przywrócono kopię.", + "settings.full_backup_restoring": "Weryfikacja kopii, tworzenie zabezpieczenia i przywracanie…", + "settings.full_backup_secret_warning": "Plik zawiera dane poufne: klucze prywatne WireGuard i klientów, PSK, skróty haseł WGTools, token bota Telegram i zapisane hasło SMTP. Chroń go jak hasło i nigdy nie dołączaj do publicznych zgłoszeń ani czatów.", + "settings.full_backup_select": "Wybierz", + "settings.full_backup_title": "Pełna kopia i przywracanie", + "settings.full_mode": "Włączono zarządzanie serwerem i klientami", + "settings.interface_help": "Zarządzany interfejs WireGuard wybiera się podczas wdrożenia WGTools.", + "settings.language": "Język", + "settings.last_backup": "Ostatnia kopia", + "settings.latest_version": "Najnowsza wersja", + "settings.loading_config": "Wczytywanie konfiguracji…", + "settings.mode": "Tryb", + "settings.never_logged_in": "Nigdy", + "settings.new_password": "Nowe hasło", + "settings.no_backups": "Brak kopii zapasowych", + "settings.online_help": "Peer jest online, jeśli jego ostatni handshake jest młodszy niż ta wartość. 30–3600 sekund.", + "settings.online_threshold": "Próg online", + "settings.open_release": "Otwórz wydanie", + "settings.password_changed": "Zmieniono hasło.", + "settings.passwords_mismatch": "Hasła nie są zgodne.", + "settings.project_github": "Projekt / GitHub", + "settings.raw_config_confirm": "Zapisać i zastosować konfigurację WireGuard? Wybrany interfejs zostanie zrestartowany. Najpierw powstanie kopia; WGTools automatycznie przywróci poprzedni stan w razie błędu.", + "settings.raw_config_help": "Otwórz źródłową konfigurację wybranego interfejsu WireGuard.", + "settings.raw_config_title": "Źródłowa konfiguracja WireGuard", + "settings.raw_config_warning": "Tryb eksperta: to rzeczywista konfiguracja serwera WireGuard zawierająca klucz prywatny i PSK peerów. Zapisanie i zastosowanie restartuje interfejs. WGTools najpierw tworzy kopię i przywraca stan w razie błędu.", + "settings.readonly_mode": "Włączono zarządzanie klientami", + "settings.refresh_help": "Częstotliwość odświeżania stanu przez WGTools. Od 2 do 60 sekund.", + "settings.refresh_interval": "Interwał odświeżania", + "settings.release_notes": "Informacje o wydaniu", + "settings.reload_config": "Wczytaj ponownie z dysku", + "settings.save_apply": "Zapisz i zastosuj", + "settings.saved": "Zapisano ustawienia.", + "settings.saved_reload": "Zapisano ustawienia. Ponowne wczytywanie…", + "settings.saving": "Zapisywanie ustawień…", + "settings.status": "Odświeżanie statusu", + "settings.status_help": "Ustawienia odświeżania panelu i stanu peerów.", + "settings.subtitle": "Preferencje interfejsu i ustawienia stanu WGTools.", + "settings.syntax_hint": "Sekcje, klucze, wartości i komentarze WireGuard są podświetlane podczas edycji.", + "settings.tab_about": "O programie", + "settings.tab_backups": "Kopie zapasowe", + "settings.tab_general": "Ogólne", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Użytkownicy", + "settings.tabs_aria": "Sekcje ustawień", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "Dozwolone identyfikatory użytkowników Telegram", + "settings.telegram_allowed_ids_help": "Jeden liczbowy identyfikator na wiersz. Nieautoryzowane /start odpowie identyfikatorem Telegram nadawcy, aby dodać go tutaj.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Połączono", + "settings.telegram_disabled": "Wyłączone", + "settings.telegram_dns": "Domyślny DNS klienta", + "settings.telegram_dns_help": "Opcjonalne adresy DNS IPv4 rozdzielone przecinkami. Dla klientów utworzonych przez bota.", + "settings.telegram_enabled": "Włącz bota Telegram", + "settings.telegram_endpoint": "Domyślny adres / domena serwera", + "settings.telegram_endpoint_help": "Używany przy tworzeniu klienta przez bota. Podaj tylko IP lub domenę; port WireGuard jest pobierany z konfiguracji serwera.", + "settings.telegram_language": "Język bota", + "settings.telegram_language_auto": "Automatycznie (język Telegram)", + "settings.telegram_last_poll": "Ostatni kontakt z Telegram", + "settings.telegram_not_configured": "Nie skonfigurowano", + "settings.telegram_remove_token": "Usuń token", + "settings.telegram_remove_token_confirm": "Usunąć zapisany token bota Telegram i wyłączyć bota?", + "settings.telegram_save": "Zapisz ustawienia Telegram", + "settings.telegram_saved": "Zapisano ustawienia Telegram.", + "settings.telegram_setup_note": "Utwórz bota w @BotFather, zapisz token, włącz bota i wyślij /start. Jeśli identyfikator nie jest autoryzowany, WGTools go pokaże — dodaj go do listy dozwolonych ID.", + "settings.telegram_status": "Status bota", + "settings.telegram_subtitle": "Zdalne zarządzanie WireGuard przez Telegram: stan serwera, klienci, tworzenie/usuwanie i start/restart/stop.", + "settings.telegram_test": "Testuj połączenie", + "settings.telegram_test_ok": "Połączenie Telegram działa: @{username}", + "settings.telegram_test_recent_ok": "Bot Telegram działa. Test bezpośredni przekroczył limit czasu, ale bot kontaktował się z Telegram niedawno.", + "settings.telegram_token": "Token bota", + "settings.telegram_token_help": "Utwórz bota w @BotFather i wklej tutaj token Bot API. API ID i API Hash nie są potrzebne.", + "settings.telegram_token_keep": "Pozostaw puste, aby zachować zapisany token.", + "settings.telegram_waiting": "Skonfigurowano, oczekiwanie na usługę bota", + "settings.theme": "Motyw", + "settings.theme_dark": "Ciemny", + "settings.theme_light": "Jasny", + "settings.theme_system": "System", + "settings.title": "Ustawienia", + "settings.update_available": "Dostępna aktualizacja", + "settings.update_backup_queued": "Aktualizacja w kolejce. WGTools przed instalacją wykona automatycznie pełną kopię…", + "settings.update_backup_running": "Tworzenie pełnej kopii przed aktualizacją…", + "settings.update_check_failed": "Nie udało się sprawdzić aktualizacji", + "settings.update_checking": "Sprawdzanie najnowszego wydania GitHub…", + "settings.update_confirm": "Zaktualizować WGTools z v{current} do v{latest}? Najpierw powstaną pełna kopia i kopia do wycofania zmian. Panel na chwilę uruchomi się ponownie.", + "settings.update_current": "Aktualna wersja", + "settings.update_downloading": "Pobieranie i weryfikowanie wydania GitHub…", + "settings.update_failed": "Aktualizacja WGTools nie powiodła się.", + "settings.update_installing": "Instalowanie aktualizacji. Panel może być przez chwilę niedostępny…", + "settings.update_no_update": "WGTools ma już najnowszą wersję.", + "settings.update_not_checked": "Nie sprawdzono", + "settings.update_queued": "Aktualizacja w kolejce. Oczekiwanie na usługę aktualizacji…", + "settings.update_rollback_ok": "Automatycznie przywrócono poprzednią wersję WGTools.", + "settings.update_rolling_back": "Aktualizacja nie powiodła się. Przywracanie poprzedniej wersji WGTools…", + "settings.update_running": "Tworzenie kopii bezpieczeństwa…", + "settings.update_safety_hint": "Aktualizacje są uruchamiane na życzenie. WGTools najpierw tworzy pełną kopię i kopię do wycofania. W razie błędu przywraca poprzednią aplikację. Sam WireGuard nie jest restartowany, chyba że nowe wydanie wyraźnie zmienia jego konfigurację.", + "settings.update_sidebar": "Dostępna nowa wersja", + "settings.update_sidebar_hint": "Ustawienia → Informacje", + "settings.update_starting": "Uruchamianie aktualizacji…", + "settings.update_status_unknown": "Stan aktualizacji niedostępny. Ponawianie…", + "settings.update_subtitle": "Wgraj zaufany pakiet wydania WGTools-Extended w formacie .bin.", + "settings.update_success": "Pomyślnie zaktualizowano WGTools do v{version}. Ponowne wczytywanie…", + "settings.update_wgtools": "Zaktualizuj WGTools", + "settings.user_actions": "Akcje", + "settings.user_created": "Utworzono", + "settings.user_created_ok": "Utworzono użytkownika.", + "settings.user_deleted": "Usunięto użytkownika.", + "settings.user_equal_rights": "Uprawnienia sieciowe są przypisywane przez administratora.", + "settings.user_last_login": "Ostatnie logowanie", + "settings.user_name": "Nazwa użytkownika", + "settings.users": "Użytkownicy", + "settings.users_subtitle": "Lokalne konta WGTools. E-mail jest opcjonalny i służy jedynie do odzyskiwania hasła po włączeniu poczty.", + "vps.add": "Dodaj VPS", + "vps.add_help": "WGTools używa SSH do sprawdzania lub instalacji Relay. Hasła i prywatne klucze SSH nigdy nie są zapisywane.", + "vps.add_title": "Dodaj VPS", + "vps.agent": "Agent Relay", + "vps.agent_found": "Już zainstalowany", + "vps.agent_will_install": "Zostanie zainstalowany", + "vps.arch": "Architektura", + "vps.auth_method": "Uwierzytelnianie", + "vps.authentication": "Uwierzytelnianie SSH", + "vps.check": "Sprawdź VPS", + "vps.check_failed": "Sprawdzanie VPS nie powiodło się", + "vps.check_link": "Sprawdź połączenie", + "vps.check_ok": "VPS zgodny", + "vps.checking": "Sprawdzanie dostępu SSH i zgodności VPS…", + "vps.connections": "połączenia", + "vps.credentials_not_saved": "Używane tylko do tej kontroli, nie są zapisywane przez WGTools.", + "vps.delete_candidate": "Usuń", + "vps.delete_installed": "Usuń VPS", + "vps.delete_installed_confirm": "Usunąć „{name}” z WGTools? Lokalny transport Relay zostanie rozłączony, ale agent i tenant na VPS pozostaną. Po ponownym dodaniu VPS WGTools połączy się z istniejącym Relay, zamiast tworzyć nowy. Klienci nie połączą się przez Relay do czasu ponownego podłączenia.", + "vps.delete_installed_failed": "Nie udało się usunąć VPS z WGTools", + "vps.delete_installed_ok": "Usunięto VPS z WGTools. Zdalny Relay zachowano i można go ponownie połączyć.", + "vps.empty_help": "Dodaj VPS Debian lub Ubuntu, aby sprawdzić SSH, zgodność systemu i wymagane porty UDP.", + "vps.empty_title": "Brak skonfigurowanego VPS", + "vps.endpoint": "Publiczny endpoint", + "vps.endpoint_domain": "Domena (zalecana)", + "vps.endpoint_domain_hint": "Przy późniejszej zmianie głównego VPS zmiana DNS pozwoli zachować dotychczasowe konfiguracje klientów.", + "vps.health_failed": "Sprawdzanie połączenia Relay nie powiodło się", + "vps.host": "IP / nazwa hosta", + "vps.host_key": "Klucz hosta SSH", + "vps.identity": "Połączenie VPS", + "vps.install_failed": "Instalacja Relay nie powiodła się", + "vps.install_ok": "Zainstalowano Relay i zweryfikowano chronione połączenie zarządzania", + "vps.install_relay": "Zainstaluj Relay", + "vps.install_title": "Zainstaluj VPS Relay", + "vps.installed": "Zainstalowano", + "vps.installing": "Instalowanie agenta Relay i zestawianie chronionego tunelu…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Hasło klucza", + "vps.link_ok": "Połączenie Relay OK", + "vps.multi_tenant_note": "Na tym VPS działa już agent WGTools Relay. Nie zostanie zastąpiony: ten WGTools otrzyma odizolowane połączenie z własnymi kluczami i portami UDP.", + "vps.name": "Nazwa", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Zostanie zainstalowany", + "vps.os": "System operacyjny", + "vps.password": "Hasło", + "vps.phase_note": "Agent Relay obsługuje wiele niezależnych kontrolerów WGTools na jednym VPS. Każdy ma osobne połączenie, klucze i porty UDP; istniejące połączenia pozostają bez zmian.", + "vps.port_pair": "Porty UDP", + "vps.ports_adjusted": "wybrano wolne porty", + "vps.private_key": "Klucz prywatny", + "vps.privilege": "Uprawnienia", + "vps.public_endpoint": "Przyszły publiczny endpoint", + "vps.ready_help": "Dane SSH służą wyłącznie do sprawdzenia zgodności i natychmiastowej instalacji Relay; nie są zapisywane.", + "vps.reconnect_note": "Na VPS znaleziono istniejące połączenie Relay utworzone przez ten WGTools. Zostanie ponownie połączony ten sam tenant bez tworzenia nowego lub portów UDP.", + "vps.reconnect_ok": "Pomyślnie połączono z istniejącym Relay", + "vps.reconnect_relay": "Połącz Relay ponownie", + "vps.relay_port": "Port UDP Relay", + "vps.remove_confirm": "Usunąć tego kandydata VPS? Nie wprowadzono zmian na serwerze zdalnym.", + "vps.save_candidate": "Zapisz kandydata", + "vps.saved": "Zapisano kandydata VPS", + "vps.ssh": "SSH", + "vps.ssh_key": "Klucz SSH", + "vps.ssh_port": "Port SSH", + "vps.ssh_user": "Użytkownik SSH", + "vps.status_candidate": "Gotowy do instalacji", + "vps.status_installed": "Relay połączony", + "vps.subtitle": "Przygotuj publiczny VPS do zdalnego dostępu, gdy ten serwer WGTools nie ma publicznego IP.", + "vps.tenant": "Połączenie", + "vps.title": "VPS Relay", + "vps.transport_port": "Port UDP transportu", + "vps.transport_port_hint": "Osobny port UDP dla prywatnego tunelu transportowego Dom ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Zapisano", + "vps.active_short": "Aktywny", + "dashboard.traffic_reset": "Resetuj", + "dashboard.traffic_reset_confirm": "Zresetować liczniki ruchu WireGuard tego interfejsu? Liczniki klientów również zaczną od zera.", + "dashboard.traffic_reset_done": "Zresetowano liczniki ruchu", + "dashboard.traffic_reset_failed": "Nie udało się zresetować liczników ruchu", + "audit.action.traffic.reset": "Zresetowano liczniki ruchu", + "audit.result.reset": "zresetowano", + "server.mtu": "MTU", + "server.mtu_auto": "Automatycznie", + "server.mtu_hint": "Opcjonalnie. Pozostaw puste dla automatycznego MTU wg-quick. Ustaw np. 1380 lub 1420 tylko gdy wymaga tego LTE lub PPPoE.", + "clients.peer_isolation": "Izolacja klientów VPN", + "clients.peer_isolation_enable": "Izoluj od innych klientów VPN", + "clients.peer_isolation_hint": "Blokuje ruch między tym klientem a innymi adresami puli WireGuard. Dostęp do serwera, Internetu i sieci lokalnych lub Site-to-site nadal zależy od pozostałych zasad.", + "clients.credentials_rotate": "Klucze klienta", + "clients.credentials_rotate_button": "Odnów klucze", + "clients.credentials_rotate_confirm": "Wygenerować nowe klucze klienta? Jeśli jest połączony, jego sesja WireGuard zostanie natychmiast przerwana. Następnie wyślij nową konfigurację lub QR.", + "clients.credentials_rotate_confirm_psk": "Wygenerować nową parę kluczy i PSK? Aktywna sesja WireGuard klienta zostanie natychmiast przerwana. Następnie wyślij nową konfigurację lub QR.", + "clients.credentials_rotate_hint": "Odnawia PrivateKey/PublicKey, a przy włączonym PSK również PSK. Adres, trasy, grupa, harmonogram, izolacja i statystyki pozostają bez zmian.", + "clients.credentials_rotating": "Generowanie nowych kluczy i rozłączanie starej sesji…", + "clients.credentials_rotated": "Zmieniono klucze klienta. Aktywną sesję rozłączono. Stara konfiguracja już nie działa; przed ponownym połączeniem prześlij nową lub kod QR.", + "clients.credentials_rotated_short": "Klucze zmienione — wymagana nowa konfiguracja", + "audit.action.client.credentials_rotated": "Odnowiono klucze klienta", + "clients.credentials_connection_lost": "Przerwano połączenie z WGTools. Jeśli panel otwarto przez klienta, którego klucze odnowiono, to normalne: stara sesja WireGuard została od razu rozłączona. Połącz się inną drogą i wygeneruj nową konfigurację lub QR.", + "nav.navigation": "Nawigacja główna", + "nav.project_github": "WGTools na GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Na razie opcjonalny. Po skonfigurowaniu poczty może służyć do odzyskiwania hasła.", + "auth.forgot_password": "Nie pamiętasz hasła?", + "auth.reset_title": "Zresetuj hasło", + "auth.reset_subtitle": "Odbierz jednorazowy kod e-mailem i ustaw nowe hasło WGTools.", + "auth.reset_identifier": "Nazwa użytkownika lub e-mail", + "auth.reset_identifier_help": "Dla ochrony prywatności WGTools zawsze pokazuje tę samą odpowiedź niezależnie od istnienia konta.", + "auth.send_reset_code": "Wyślij kod", + "auth.reset_code_sent_generic": "Jeśli konto istnieje i ma adres e-mail, wysłano kod resetowania ważny przez 15 minut.", + "auth.reset_code": "Kod 6-cyfrowy", + "auth.set_new_password": "Ustaw nowe hasło", + "auth.request_another_code": "Poproś o nowy kod", + "auth.back_to_login": "Wróć do logowania", + "auth.reset_not_configured": "Odzyskiwanie hasła e-mailem nie jest skonfigurowane. Skontaktuj się z administratorem WGTools.", + "settings.tab_mail": "Poczta", + "settings.mail": "Poczta / SMTP", + "settings.mail_subtitle": "SMTP służy do odzyskiwania hasła.", + "settings.mail_not_configured": "Nie skonfigurowano", + "settings.mail_enabled": "Włącz pocztę i odzyskiwanie hasła", + "settings.mail_smtp_host": "Serwer SMTP", + "settings.mail_smtp_port": "Port SMTP", + "settings.mail_security": "Szyfrowanie", + "settings.mail_security_none": "Bez szyfrowania", + "settings.mail_username": "Użytkownik SMTP", + "settings.mail_username_help": "Używane do logowania SMTP i jako adres e-mail nadawcy.", + "settings.mail_password": "Hasło SMTP", + "settings.mail_password_keep": "Pozostaw puste, aby zachować zapisane hasło.", + "settings.mail_from_email": "E-mail nadawcy", + "settings.mail_from_name": "Nazwa nadawcy", + "settings.mail_test_recipient": "Odbiorca testowy", + "settings.mail_test_recipient_help": "Test używa aktualnie zapisanych ustawień SMTP.", + "settings.mail_remove_password": "Usuń hasło", + "settings.mail_test": "Wyślij test", + "settings.mail_save": "Zapisz ustawienia poczty", + "settings.mail_enabled_badge": "Włączone", + "settings.mail_disabled_badge": "Wyłączone", + "settings.mail_saved": "Zapisano ustawienia poczty.", + "settings.mail_remove_password_confirm": "Usunąć zapisane hasło SMTP i wyłączyć pocztę?", + "settings.mail_password_removed": "Usunięto hasło SMTP i wyłączono pocztę.", + "settings.mail_test_recipient_required": "Podaj adres e-mail odbiorcy testowego.", + "settings.mail_testing": "Wysyłanie testowego e-maila…", + "settings.mail_test_ok": "Pomyślnie wysłano testowy e-mail.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Opcjonalny. Wymagany tylko do samodzielnego odzyskiwania hasła.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "Zapisano e-mail.", + "settings.send_password_reset": "Wyślij reset", + "settings.user_reset_mail_not_configured": "Najpierw skonfiguruj i włącz pocztę.", + "settings.user_reset_email_missing": "Najpierw dodaj adres e-mail.", + "settings.user_reset_confirm": "Wysłać kod resetowania hasła do {name} na {email}?", + "settings.user_reset_sent": "Wysłano kod resetowania hasła na {email}.", + "audit.action.auth.password_reset_requested": "Zażądano resetowania hasła", + "audit.action.auth.password_reset_code_sent": "Wysłano kod resetowania hasła", + "audit.action.auth.password_reset_completed": "Zresetowano hasło", + "audit.action.auth.password_reset_failed": "Resetowanie hasła nie powiodło się", + "audit.action.mail.settings_updated": "Zaktualizowano ustawienia poczty", + "audit.action.mail.test_sent": "Wysłano testowy e-mail", + "audit.action.mail.test_failed": "Nie udało się wysłać testowego e-maila", + "audit.action.user.email_changed": "Zmieniono e-mail użytkownika", + "audit.action.user.password_reset_sent": "Wysłano resetowanie hasła użytkownika", + "audit.action.user.password_reset_failed": "Resetowanie hasła użytkownika nie powiodło się", + "audit.result.accepted": "zaakceptowano", + "audit.result.sent": "wysłano", + "audit.result.invalid_code": "nieprawidłowy kod", + "common.copy": "Kopiuj", + "common.copied": "Skopiowano", + "clients.use_panel_host": "Użyj adresu panelu", + "clients.use_panel_host_done": "Wstawiono adres panelu: {host}", + "clients.use_panel_host_failed": "Nie udało się ustalić adresu panelu z URL przeglądarki.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Wbudowany HTTPS Let’s Encrypt do bezpośredniego dostępu do WGTools bez reverse proxy.", + "settings.https_disabled": "Wyłączone", + "settings.https_enabled": "Włączone", + "settings.https_enable": "Włącz wbudowany HTTPS", + "settings.https_type": "Certyfikat dla", + "settings.https_domain": "Domena", + "settings.https_public_ip": "Publiczny IP", + "settings.https_target": "Domena lub publiczny IP", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "Port HTTPS", + "settings.https_port80_note": "Port TCP 80 musi być dostępny z Internetu do wydania i odnawiania certyfikatu. Otwórz też wybrany port HTTPS panelu.", + "settings.https_check_ports": "Sprawdź porty", + "settings.https_certificate": "Certyfikat", + "settings.https_certificate_ready": "Gotowy", + "settings.https_certificate_missing": "Nie wydano", + "settings.https_expires": "Ważny do", + "settings.https_renewal": "Automatyczne odnawianie", + "settings.https_renewal_enabled": "Włączone", + "settings.https_renewal_disabled": "Wyłączone", + "settings.https_certificate_path": "Certyfikat", + "settings.https_private_key_path": "Klucz prywatny", + "settings.https_issue": "Uzyskaj / odnów certyfikat", + "settings.https_port_free": "Wolny", + "settings.https_port_busy": "Zajęty", + "settings.https_ports_checked": "Zakończono sprawdzanie portów.", + "settings.https_target_email_required": "Podaj domenę/publiczny IP i e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Uzyskać lub odnowić certyfikat Let’s Encrypt dla {target}? Ustawienia HTTPS zostaną zapisane. Port TCP 80 musi być dostępny z Internetu.", + "settings.https_issuing": "Pobieranie certyfikatu z Let’s Encrypt…", + "settings.https_issue_ok": "Certyfikat gotowy.", + "settings.https_already_enabled": "Wbudowany HTTPS jest już włączony.", + "settings.https_already_disabled": "Wbudowany HTTPS jest już wyłączony.", + "settings.https_enable_confirm": "Włączyć wbudowany HTTPS na TCP {port} ze ścieżką {path}? WGTools uruchomi się ponownie, a strona połączy z nowym adresem.", + "settings.https_disable_confirm": "Wyłączyć wbudowany HTTPS i wrócić do HTTP?", + "settings.https_switching": "Włączanie HTTPS i ponowne uruchamianie WGTools…", + "settings.https_switching_http": "Wyłączanie HTTPS i ponowne uruchamianie WGTools…", + "audit.action.https.certificate_issued": "Wydano certyfikat HTTPS", + "audit.action.https.certificate_failed": "Nie udało się uzyskać certyfikatu HTTPS", + "audit.action.https.enabled": "Włączono HTTPS", + "audit.action.https.disabled": "Wyłączono HTTPS", + "audit.result.issued": "wydano", + "audit.result.enabled": "włączono", + "audit.result.disabled": "wyłączono", + "settings.https_access_path": "Ścieżka dostępu do panelu", + "settings.https_access_path_help": "Wybierz własną ścieżkę. Przy wbudowanym HTTPS żądania poza nią zwracają 404.", + "settings.https_enable_fields_required": "Podaj domenę/publiczny IP, e-mail Let’s Encrypt i ścieżkę panelu.", + "settings.https_use_panel_host": "Użyj adresu panelu", + "settings.https_reconnecting": "WGTools przełącza się na nowy adres HTTPS…", + "server.tab_nodes": "Węzły", + "common.type": "Typ", + "common.status": "Status", + "common.copy_failed": "Nie udało się skopiować", + "clients.vpn_address": "Adres VPN", + "nodes.title": "Węzły WGTools", + "nodes.subtitle": "Połącz serwery WGTools w jedną chronioną sieć i publikuj tylko sieci dostępne dla innych węzłów.", + "nodes.enable_hub": "Włącz HUB", + "nodes.connect_hub": "Połącz z HUB", + "nodes.settings": "Ustawienia węzła", + "nodes.settings_action": "Ustawienia", + "nodes.sync_now": "Synchronizuj", + "nodes.disable": "Wyłącz węzły", + "nodes.disable_action": "Rozłącz", + "nodes.join_title": "Połącz nowe węzły", + "nodes.join_help": "Utwórz jednorazowy kod i wpisz go w drugim panelu WGTools wraz z endpointem usługi HUB, np. vpn.example.com:51950. Kod jest ważny 15 minut i można go użyć tylko raz.", + "nodes.create_code": "Utwórz kod", + "nodes.connected_nodes": "Połączone węzły", + "nodes.connected_nodes_help": "Informacje o innych panelach, publikowanych sieciach i klientach. Klienci zdalni są tylko do odczytu.", + "nodes.enable_hub_help": "Ten panel stanie się węzłem centralnym. Na tym samym porcie HUB odbiera WireGuard przez UDP i chronione pierwsze parowanie przez TCP.", + "nodes.node_name": "Nazwa węzła", + "nodes.transport_network": "Sieć transportowa węzłów", + "nodes.transport_help": "Osobna sieć prywatna tylko do komunikacji WGTools ↔ WGTools. Nie może pokrywać się z sieciami VPN/LAN.", + "nodes.panel_url": "URL panelu", + "nodes.panel_url_help": "Opcjonalnie. To tylko link dla przycisku „Otwórz panel” na innych węzłach; nie służy do łączenia Nodes.", + "nodes.extra_networks": "Dodatkowe sieci węzła", + "nodes.extra_networks_help": "Jedna sieć w wierszu. Sieci VPN interfejsów i zdalne sieci Site-to-site są publikowane automatycznie. Dodaj tylko inne routowane sieci LAN, np. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools uzupełnia wykryte sieci VPN, Site-to-site i routowane LAN. Pozostaw tylko sieci przeznaczone do publikacji. Jedna na wiersz.", + "nodes.published_networks_settings_help": "Jedna sieć na wiersz. To jawna lista sieci publikowanych przez węzeł. Usunięcie wiersza zatrzymuje ogłaszanie sieci innym węzłom.", + "nodes.available_networks_help": "Wykryte sieci: {networks}. Nowe sieci nie są publikowane automatycznie; dodaj potrzebne powyżej.", + "nodes.available_networks_none": "Nie wykryto dodatkowych sieci lokalnych.", + "nodes.connect_help": "Podaj endpoint usługi HUB i kod jednorazowy. URL panelu, port HTTPS, certyfikat i prywatna ścieżka nie są używane do parowania Nodes.", + "nodes.join_code": "Kod połączenia", + "nodes.connect_reachability_note": "Pierwsze parowanie korzysta z chronionego TCP na podanym porcie. Po utworzeniu wgnode0 sieci, stan, wersje i dane klientów tylko do odczytu synchronizują się z HUB przez wewnętrzny adres WireGuard.", + "nodes.connect": "Połącz", + "nodes.settings_help": "Nazwa węzła, opcjonalny link „Otwórz panel” i lista publikowanych sieci. URL panelu nie służy do parowania ani synchronizacji.", + "nodes.details": "Szczegóły", + "nodes.not_configured": "WGTools Nodes nieskonfigurowane", + "nodes.not_configured_help": "Włącz HUB w tym panelu lub połącz go z istniejącym WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Połączono z HUB", + "nodes.mode_none": "Nie skonfigurowano", + "nodes.role": "Rola", + "nodes.tunnel": "Tunel węzła", + "nodes.node_ip": "Adres węzła", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Publikowane sieci", + "nodes.last_sync": "Ostatnia synchronizacja", + "nodes.no_nodes_hub": "Nie połączono jeszcze węzłów. Utwórz kod i użyj go w innym panelu WGTools.", + "nodes.no_nodes_spoke": "Nie otrzymano jeszcze informacji o zdalnych węzłach.", + "nodes.clients_short": "Klienci", + "nodes.open_panel": "Otwórz panel", + "nodes.route_conflict": "Konflikt tras", + "nodes.no_published_networks": "Brak publikowanych sieci", + "nodes.load_failed": "Nie udało się wczytać WGTools Nodes", + "nodes.enable_hub_confirm": "Włączyć WGTools HUB i utworzyć wewnętrzny tunel WireGuard Nodes?", + "nodes.applying": "Konfigurowanie tunelu WGTools Nodes…", + "nodes.enable_failed": "Nie udało się włączyć HUB", + "nodes.hub_enabled": "Włączono WGTools HUB", + "nodes.connecting": "Weryfikacja kodu HUB i tworzenie chronionego tunelu…", + "nodes.connect_failed": "Nie udało się połączyć z HUB", + "nodes.connected": "Połączono z WGTools HUB", + "nodes.settings_failed": "Nie udało się zapisać ustawień węzła", + "nodes.settings_saved": "Zapisano ustawienia węzła", + "nodes.code_failed": "Nie udało się utworzyć kodu połączenia", + "nodes.code_expires": "Kod jednorazowy. Ważny do {time}.", + "nodes.code_copied": "Skopiowano kod połączenia", + "nodes.network_vpn": "Klienci VPN", + "nodes.network_site_to_site": "Sieć Site-to-site", + "nodes.network_custom": "Dodatkowa sieć", + "nodes.conflict": "Konflikt", + "nodes.remote_clients": "Klienci (tylko odczyt)", + "nodes.no_clients": "Ten węzeł nie zgłasza klientów", + "nodes.details_failed": "Nie udało się pobrać szczegółów węzła", + "nodes.remove_confirm": "Usunąć węzeł „{name}” z HUB? Dostęp do wewnętrznego tunelu zostanie cofnięty.", + "nodes.remove_failed": "Nie udało się usunąć węzła", + "nodes.removed": "Usunięto węzeł", + "nodes.disable_hub_confirm": "Wyłączyć HUB i rozłączyć wszystkie węzły WGTools? Wewnętrzny tunel zostanie usunięty.", + "nodes.disconnect_confirm": "Odłączyć ten panel WGTools od HUB i usunąć wewnętrzny tunel węzła?", + "nodes.disable_failed": "Nie udało się wyłączyć WGTools Nodes", + "nodes.disabled": "Wyłączono WGTools Nodes", + "nodes.sync_failed": "Synchronizacja węzłów nie powiodła się", + "nodes.synced": "Zsynchronizowano informacje węzłów", + "nodes.service_port": "Port Nodes", + "nodes.service_port_help": "Ten sam numer portu służy równocześnie: UDP dla WireGuard i TCP do chronionego parowania.", + "nodes.hub_port_forward_note": "Jeśli HUB jest za NAT, przekieruj ten sam port UDP i TCP. Port web WGTools, HTTPS i prywatna ścieżka panelu nie są powiązane z Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Domena/IP i port Nodes bez http:// lub https://, np. vpn.example.com:51950.", + "settings.collapse_sidebar": "Zwiń pasek boczny", + "settings.expand_sidebar": "Rozwiń panel boczny", + "settings.https_issue_fields_required": "Podaj domenę/publiczny IP, e-mail Let’s Encrypt i ścieżkę panelu.", + "settings.https_issue_ok_saved": "Certyfikat gotowy i ustawienia HTTPS zapisane.", + "settings.https_enable_need_certificate": "Najpierw uzyskaj certyfikat.", + "settings.https_enable_certificate_mismatch": "Najpierw uzyskaj certyfikat dla bieżącej domeny lub IP.", + "settings.https_enable_certificate_expired": "Certyfikat wygasł. Odnów go przed włączeniem HTTPS.", + "settings.https_enable_certificate_ready": "Certyfikat gotowy — można włączyć wbudowany HTTPS.", + "settings.https_enable_active_help": "Odznacz i zapisz, aby wrócić do HTTP.", + "settings.https_certificate_expired": "Wygasł", + "settings.https_certificate_wrong_target": "Dla innego adresu", + "nodes.network_conflict_error": "Publikowane sieci kolidują z innym węzłem lub siecią transportową Nodes: {conflicts}. Usuń lub zmień kolidującą sieć.", + "nodes.networks_changed": "Wykryte sieci zmieniły się od ostatniego zapisu. Nowe: {added}. Niewykrywane: {removed}. Sprawdź listę publikowanych sieci i zapisz ustawienia.", + "nodes.review_networks": "Sprawdź sieci", + "nodes.vpn_pool_mismatch": "Pula VPN zmieniła się: Nodes nadal publikuje {old}, a aktualna pula to {current}. Otwórz ustawienia węzła i zaktualizuj publikowane sieci.", + "server.error_vpn_network_invalid": "Sieć VPN musi być prawidłową siecią IPv4, np. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Obsługiwane są tylko sieci VPN IPv4.", + "server.error_vpn_network_too_small": "Sieć VPN musi zawierać co najmniej dwa użyteczne adresy.", + "server.error_vpn_network_no_hosts": "Wybrana sieć VPN nie ma użytecznych adresów serwera.", + "server.error_server_address_prefix": "Adres VPN serwera musi zawierać prefiks, np. 10.0.0.1/24.", + "server.error_server_address_network": "Adres VPN serwera musi należeć do wybranej puli i mieć ten sam prefiks.", + "server.error_server_address_reserved": "Adres VPN serwera nie może być adresem sieci ani adresem rozgłoszeniowym.", + "server.error_listen_port_number": "Port WireGuard musi być liczbą.", + "server.error_listen_port_range": "Port WireGuard musi mieścić się w zakresie 1–65535.", + "server.error_mtu_number": "MTU musi być liczbą.", + "auth.mfa_title": "Uwierzytelnianie dwuskładnikowe", + "auth.mfa_login_help": "Wprowadź 6-cyfrowy kod z Google Authenticator lub jeden z kodów odzyskiwania.", + "auth.mfa_code": "Kod uwierzytelniania", + "auth.mfa_verify": "Zweryfikuj i zaloguj", + "auth.mfa_back": "Wróć do hasła", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Uwierzytelnianie dwuskładnikowe (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Włączone", + "settings.mfa_disabled": "Wyłączone", + "settings.mfa_google_help": "Chroń konto przez Google Authenticator lub inną aplikację TOTP. Aby zacząć, podaj bieżące hasło.", + "settings.current_password": "Bieżące hasło", + "settings.mfa_start": "Skonfiguruj Google Authenticator", + "settings.mfa_secret": "Ręczny klucz konfiguracji", + "settings.mfa_scan_help": "Zeskanuj QR w Google Authenticator i wpisz aktualny 6-cyfrowy kod, aby włączyć MFA.", + "settings.mfa_code": "Kod 6-cyfrowy", + "settings.mfa_enable": "Włącz MFA", + "settings.mfa_manage_help": "Aby zmienić MFA, podaj bieżące hasło oraz kod Authenticator lub kod odzyskiwania.", + "settings.mfa_code_or_recovery": "Kod Authenticator lub odzyskiwania", + "settings.mfa_regenerate": "Nowe kody odzyskiwania", + "settings.mfa_disable": "Wyłącz MFA", + "settings.mfa_recovery_title": "Kody odzyskiwania", + "settings.mfa_recovery_help": "Zapisz te kody teraz. Każdego można użyć raz, gdy Google Authenticator jest niedostępny. Nie zostaną ponownie pokazane.", + "settings.mfa_recovery_remaining": "Pozostałe kody odzyskiwania: {count}", + "settings.mfa_enabled_ok": "Włączono MFA.", + "settings.mfa_disabled_ok": "Wyłączono MFA.", + "settings.mfa_disable_confirm": "Wyłączyć uwierzytelnianie dwuskładnikowe dla tego konta?", + "settings.mfa_regenerate_confirm": "Zastąpić wszystkie istniejące kody odzyskiwania?", + "settings.mfa_recovery_regenerated": "Utworzono nowe kody odzyskiwania.", + "audit.action.auth.mfa_failed": "Weryfikacja MFA nie powiodła się", + "audit.action.auth.mfa_recovery_used": "Użyto kodu odzyskiwania MFA", + "audit.action.user.mfa_setup_started": "Rozpoczęto konfigurację MFA", + "audit.action.user.mfa_enabled": "Włączono MFA", + "audit.action.user.mfa_disabled": "Wyłączono MFA", + "audit.action.user.mfa_disabled_cli": "Wyłączono MFA przez CLI", + "audit.action.user.mfa_recovery_regenerated": "Wygenerowano ponownie kody odzyskiwania MFA", + "settings.mfa_error_password": "Nieprawidłowe bieżące hasło.", + "settings.mfa_error_code": "Nieprawidłowy kod uwierzytelniania.", + "settings.mfa_error_already_enabled": "MFA jest już włączone.", + "settings.mfa_error_not_enabled": "MFA nie jest włączone.", + "settings.mfa_error_not_started": "Rozpocznij konfigurację MFA ponownie.", + "trace.title": "Traceroute, ping i mapa trasy", + "trace.subtitle": "Zmierz opóźnienie do VPS lub innego serwera i sprawdź, gdzie rośnie na trasie.", + "trace.target": "IP lub nazwa hosta serwera", + "trace.show_map": "Pokaż trasę na mapie", + "trace.run": "Uruchom traceroute", + "trace.geo_note": "Geolokalizacja jest przybliżona. Po włączeniu mapy publiczne IP przeskoków są wysyłane do ipwho.is, a kafelki mapy pobierane z OpenStreetMap.", + "trace.latency_note": "Traceroute mierzy opóźnienia w milisekundach, a nie przepustowość w Mbit/s.", + "trace.map": "Mapa trasy", + "trace.map_hint": "Mapa interaktywna: przeciągnij, aby przesunąć; użyj kółka myszy lub +/− do powiększenia; kliknij przeskok po szczegóły.", + "trace.hop": "Przeskok / IP", + "trace.location": "Lokalizacja", + "trace.avg_rtt": "Śr. RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Straty", + "trace.summary_target": "Cel", + "trace.summary_ping": "Średni ping", + "trace.summary_loss": "Straty ping", + "trace.summary_hops": "Przeskoki", + "trace.no_reply": "Brak odpowiedzi", + "trace.private": "Sieć prywatna", + "trace.unknown": "Nieznany", + "trace.running": "Trwa ping i traceroute… Może to potrwać do minuty.", + "trace.done": "Zakończono śledzenie trasy.", + "trace.failed": "Śledzenie trasy nie powiodło się", + "trace.partial_geo": "Nie udało się ustalić lokalizacji części publicznych przeskoków.", + "trace.not_reached": "Traceroute nie dotarł do celu.", + "trace.reached": "Osiągnięto cel", + "trace.ms": "ms", + "server.tab_trace": "Śledzenie trasy", + "trace.map_controls": "Sterowanie mapą", + "trace.zoom_in": "Powiększ", + "trace.zoom_out": "Pomniejsz", + "trace.fit_route": "Dopasuj trasę", + "trace.fit": "Dopasuj", + "trace.map_click_hint": "Kliknij przeskok, aby zobaczyć IP, lokalizację, ASN i RTT.", + "trace.route_path": "Trasa", + "trace.ping_ok_trace_filtered": "Cel odpowiada na ping, ale ostatnie przeskoki traceroute nie odpowiadają.", + "trace.latency_legend": "Wzrost opóźnienia między odpowiadającymi przeskokami", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normalnie", + "trace.latency_warn": "Δ RTT 5–20 ms — podwyższone", + "trace.latency_bad": "Δ RTT > 20 ms — duży skok" +} diff --git a/app/static/locales/ru.json b/app/static/locales/ru.json new file mode 100644 index 0000000..015c465 --- /dev/null +++ b/app/static/locales/ru.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Создать пользователя", + "auth.login_subtitle": "Введите логин и пароль WGTools.", + "auth.login_title": "Вход в WGTools", + "auth.password": "Пароль", + "auth.password_repeat": "Повторите пароль", + "auth.setup_help": "Первый пользователь получает полный доступ к WGTools. Дополнительных пользователей можно будет создать в Настройках.", + "auth.setup_subtitle": "Перед управлением сервером WGTools нужно создать учетную запись.", + "auth.setup_title": "Создание первого пользователя", + "auth.sign_in": "Войти", + "auth.sign_out": "Выйти", + "auth.username": "Логин", + "clients.actions": "Действия", + "clients.add": "+ Добавить клиента", + "clients.address": "VPN адрес", + "clients.address_hint": "Первый свободный адрес предлагается автоматически.", + "clients.allowed_ips_required": "Укажите хотя бы одну сеть AllowedIPs для конфигурации клиента.", + "clients.basic_connection": "Основные настройки подключения", + "clients.basic_details": "Клиент", + "clients.client": "Клиент", + "clients.client_allowed_ips": "AllowedIPs в клиентском конфиге", + "clients.config_private_warning": "В конфигурации находится приватный ключ клиента. Храни её безопасно.", + "clients.config_title": "Конфигурация клиента", + "clients.config_unavailable": "Конфигурация недоступна", + "clients.connection_direct": "Напрямую к WGTools", + "clients.connection_path": "Точка подключения", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Подключение через", + "clients.connection_via_hint": "Выберите публичную точку входа для этого клиента. Relay показывается только если он установлен для выбранного интерфейса WireGuard.", + "clients.copy_config": "Копировать", + "clients.copy_done": "Конфигурация скопирована", + "clients.create_subtitle": "Создание пира WireGuard и готовой клиентской конфигурации.", + "clients.create_title": "Создать клиента", + "clients.creating": "Генерирую ключи и добавляю клиента…", + "clients.day_fri": "Пт", + "clients.day_mon": "Пн", + "clients.day_sat": "Сб", + "clients.day_sun": "Вс", + "clients.day_thu": "Чт", + "clients.day_tue": "Вт", + "clients.day_wed": "Ср", + "clients.delete_confirm": "Удалить этого клиента из WireGuard? WGTools создаст резервную копию и удалит связанные с этим клиентом автоматически созданные правила политики.", + "clients.deleted": "Клиент удалён", + "clients.dns": "DNS (необязательно)", + "clients.dns_hint": "IPv4-адреса DNS через запятую.", + "clients.download_config": "Скачать .conf", + "clients.duplicate": "Дублировать", + "clients.duplicate_address_error": "Этот VPN-адрес уже используется другим пиром.", + "clients.duplicate_name_error": "Пир с таким именем уже существует.", + "clients.duplicate_ready": "Копия подготовлена. WGTools назначил новое имя и VPN-адрес; проверьте параметры перед сохранением.", + "clients.duplicate_site_hint": "Удалённые сети очищены, чтобы не создать дублирующиеся маршруты. Укажите сети для нового Site-to-site пира.", + "clients.duplicate_suffix": "копия", + "clients.edit_subtitle": "Изменение серверной части пира. Настройки применяются без перезапуска WireGuard.", + "clients.edit_title": "Изменить клиента", + "clients.endpoint": "Адрес сервера для клиента", + "clients.endpoint_hint": "Для удалённых клиентов укажи внешний IP/домен, с которого порт WireGuard проброшен на этот сервер.", + "clients.existing": "Существующий пир", + "clients.expiration": "Срок доступа", + "clients.expiration_action": "После окончания срока", + "clients.expiration_action_hint": "Если выключено, клиент останется в WGTools, но доступ WireGuard будет отключён. Чтобы вернуть доступ, укажите новый срок или «Без ограничения» и сохраните клиента.", + "clients.expiration_datetime": "Доступ до", + "clients.expiration_datetime_hint": "Используется локальная дата и время этого браузера.", + "clients.expiration_delete": "Удалить клиента", + "clients.expiration_future_required": "Укажи дату и время в будущем.", + "clients.expiration_hint": "Когда срок закончится, WGTools выполнит выбранное действие на ближайшей минутной границе. Перед изменением создаётся резервная копия WireGuard-конфига.", + "clients.expire_1d": "1 день", + "clients.expire_1h": "1 час", + "clients.expire_3h": "3 часа", + "clients.expire_6h": "6 часов", + "clients.expire_custom": "Своя дата и время", + "clients.expire_never": "Без ограничения", + "clients.expired": "Срок истёк", + "clients.expired_disabled_hint": "Срок доступа истёк, клиент сохранён, но WireGuard-доступ отключён. Укажите новый срок или «Без ограничения» и сохраните, чтобы вернуть доступ.", + "clients.expired_disabled_short": "Срок истёк · отключён", + "clients.expired_disabled_status": "Срок истёк", + "clients.expires_days": "Осталось {n} дн", + "clients.expires_hours": "Осталось {n} ч", + "clients.expires_minutes": "Осталось {n} мин", + "clients.generated_config": "Клиентская конфигурация", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 секунд — хороший вариант для клиентов за NAT.", + "clients.local_access_exceptions": "Разрешённые локальные адреса", + "clients.local_access_exceptions_hint": "Необязательные IP или CIDR, которые останутся доступны, даже если их локальная или Site-to-site сеть заблокирована. Несколько значений — через запятую.", + "clients.managed": "Управляется WGTools", + "clients.name": "Имя", + "clients.no_peers": "Клиенты не найдены", + "clients.peers": "Клиенты", + "clients.peers_subtitle": "Перед изменениями создаётся резервная копия, затем конфигурация применяется через wg syncconf без перезапуска интерфейса WireGuard.", + "clients.protected_networks_reference": "Заблокированные локальные сети (справочно)", + "clients.protected_networks_reference_hint": "Эти сети не записываются в AllowedIPs. Доступ к ним блокируется серверной политикой WGTools; отдельные адреса можно разрешить полем выше.", + "clients.psk": "Preshared key (PSK)", + "clients.psk_enable": "Использовать дополнительный PSK WireGuard", + "clients.psk_hint": "Рекомендуется. Добавляет к рукопожатию WireGuard дополнительный симметричный секрет. Стандартные клиенты WireGuard его поддерживают; WGTools добавляет PSK в конфиг и QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Создаю QR…", + "clients.quick_search": "Быстрый поиск", + "clients.quick_search_clear": "Очистить поиск", + "clients.quick_search_empty": "По запросу клиентов нет", + "clients.relay_endpoint_note": "Готовый конфиг клиента будет подключаться к {endpoint}. Сам сервер WireGuard по-прежнему находится на этом WGTools.", + "clients.relay_required": "Выберите VPS Relay для этого клиента.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "недоступен", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "Endpoint клиента формируется автоматически из настроек выбранного Relay.", + "clients.remote_hint": "Сети, расположенные за этим пиром. По одной сети в строке или через запятую.", + "clients.remote_networks": "Удалённые сети", + "clients.remote_required": "Для Site-to-site пира укажите хотя бы одну удалённую сеть.", + "clients.required": "Нужно указать имя и VPN-адрес.", + "clients.route_custom": "Свои маршруты", + "clients.route_full": "Весь трафик через VPN", + "clients.route_full_except_local": "Весь трафик кроме локальных сетей", + "clients.route_hint": "Только эти сети записываются в AllowedIPs готового клиентского конфига.", + "clients.route_preset": "Трафик через VPN", + "clients.route_vpn": "Только VPN-сеть", + "clients.route_vpn_lan": "VPN + локальная сеть", + "clients.saved": "Клиент сохранён", + "clients.schedule_blocked_short": "Расписание · заблокирован", + "clients.schedule_blocked_status": "Заблокирован расписанием", + "clients.schedule_days": "Дни доступа", + "clients.schedule_days_required": "Выбери хотя бы один день для расписания доступа.", + "clients.schedule_disabled_hint": "Сейчас клиент заблокирован расписанием. В следующем разрешённом интервале WGTools автоматически вернёт доступ тому же peer — конфиг клиента менять не нужно.", + "clients.schedule_enable": "Ограничивать доступ по расписанию", + "clients.schedule_from": "Доступ с", + "clients.schedule_hint": "WGTools будет автоматически отключать и возвращать доступ этому клиенту в выбранные дни и часы без замены клиентского конфига.", + "clients.schedule_short": "Расписание", + "clients.schedule_time_required": "Укажи время начала и окончания доступа.", + "clients.schedule_timezone_hint": "Расписание работает по локальному времени WireGuard-сервера. Поддерживаются интервалы через полночь, например 22:00–06:00.", + "clients.schedule_title": "Расписание доступа", + "clients.schedule_to": "Доступ до", + "clients.security_access": "Безопасность и срок доступа", + "clients.server_host": "Адрес / домен сервера", + "clients.server_host_hint": "Внешний IP или домен для подключения этого клиента. Ранее введённые значения доступны в подсказках.", + "clients.server_host_required": "Для готовой конфигурации клиента обязательно укажите адрес или домен сервера.", + "clients.server_peer": "Пир на сервере", + "clients.server_port": "Порт WireGuard", + "clients.server_port_hint": "Берётся автоматически из конфигурации сервера.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Статус", + "clients.subtitle": "Пиры WireGuard, текущий статус и управление конфигурациями клиентов.", + "clients.tab_basic": "Основное", + "clients.tab_config": "Конфигурация", + "clients.tab_policy": "Политики", + "clients.tab_security": "Безопасность", + "clients.title": "Клиенты", + "clients.type": "Тип", + "clients.unmanaged_note": "Этот пир существовал до WGTools. Его приватный ключ восстановить невозможно, поэтому WGTools может менять серверную часть, но не сможет сгенерировать клиентский конфиг или QR-код.", + "clients.updating": "Обновляю клиента…", + "common.actions": "Действия", + "common.ago": "назад", + "common.cancel": "Отмена", + "common.checking": "Проверка…", + "common.close": "Закрыть", + "common.config": "Конфиг", + "common.delete": "Удалить", + "common.disabled": "Выключено", + "common.edit": "Изменить", + "common.enabled": "Включено", + "common.loading": "Загрузка…", + "common.never": "Никогда", + "common.no": "Нет", + "common.not_configured": "Не настроен", + "common.not_installed": "Не установлен", + "common.offline": "офлайн", + "common.online": "онлайн", + "common.refresh": "Обновить", + "common.running": "Работает", + "common.save": "Сохранить", + "common.stopped": "Остановлен", + "common.total": "Всего", + "common.unknown": "Неизвестно", + "common.updated": "Обновлено", + "common.yes": "Да", + "dashboard.active_peers": "Активные клиенты", + "dashboard.active_peers_subtitle": "Живые данные из wg show.", + "dashboard.activity": "Состояние системы", + "dashboard.activity_subtitle": "Проверки работающего WireGuard без изменения конфигурации.", + "dashboard.cores": "ядер", + "dashboard.cpu": "ЦП", + "dashboard.history_24h": "Последние 24 ч", + "dashboard.history_avg": "Сред", + "dashboard.history_max": "Макс", + "dashboard.history_min": "Мин", + "dashboard.history_now": "сейчас", + "dashboard.memory": "Память", + "dashboard.network": "Сеть", + "dashboard.peers": "Клиенты", + "dashboard.quick_search": "Быстрый поиск", + "dashboard.quick_search_clear": "Очистить поиск", + "dashboard.quick_search_empty": "По запросу ничего не найдено", + "dashboard.restart": "Перезапуск", + "dashboard.restart_confirm": "Перезапустить WireGuard? Активные VPN-клиенты автоматически переподключатся.", + "dashboard.restart_ok": "WireGuard перезапущен.", + "dashboard.routing": "Маршрутизация", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Пуск", + "dashboard.start_ok": "WireGuard запущен.", + "dashboard.stop": "Стоп", + "dashboard.stop_confirm": "Остановить WireGuard? Активные VPN-клиенты будут отключены.", + "dashboard.stop_ok": "WireGuard остановлен.", + "dashboard.subtitle": "Состояние WireGuard, клиенты и текущий трафик.", + "dashboard.title": "Главная", + "dashboard.traffic": "Трафик", + "dashboard.uptime": "Аптайм", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Политика доступа на сервере", + "groups.additional_allowed": "Дополнительно разрешить", + "groups.additional_blocked": "Дополнительно запретить", + "groups.allow": "Разрешить", + "groups.allowed": "Разрешён", + "groups.allowed_addresses": "Разрешённые адреса / сети", + "groups.apply_current_template": "Применить текущий шаблон группы", + "groups.apply_defaults": "Применить текущий шаблон группы", + "groups.apply_defaults_hint": "Копирует текущие маршруты, DNS и Keepalive группы в этого клиента. После сохранения выдай новый конфиг или QR, если нужно обновить уже установленное устройство.", + "groups.basic": "Основное", + "groups.block": "Запретить", + "groups.blocked": "Запрещён", + "groups.blocked_addresses": "Запрещённые адреса / сети", + "groups.client_config_source": "Источник конфигурации клиента", + "groups.client_defaults": "Настройки клиента", + "groups.client_group_hint": "Необязательная группа с общей политикой доступа и настройками новых клиентов. Группы относятся только к выбранному интерфейсу WireGuard.", + "groups.config_differs": "Конфигурация этого клиента отличается от текущих настроек группы. Серверная политика уже актуальна, но конфиг на телефоне/ПК изменится только после выдачи нового файла или QR.", + "groups.config_differs_short": "Конфиг клиента отличается от настроек группы", + "groups.create": "Создать группу", + "groups.create_title": "Создать группу", + "groups.created": "Группа создана", + "groups.creating": "Создаю группу…", + "groups.defaults_applied": "Текущий шаблон группы применён. Сохрани клиента, чтобы закрепить изменения.", + "groups.defaults_hint": "Определяет, какой трафик устройство отправляет через WireGuard. Политика сервера выше независимо определяет, куда этот трафик будет допущен. Изменение шаблона позже не меняет молча конфиги, уже установленные на устройствах.", + "groups.delete_message": "Удалить группу «{name}»? Клиентские конфигурации при удалении группы никогда не удаляются.", + "groups.delete_move": "Переместить её клиентов в другую группу", + "groups.delete_title": "Удалить группу клиентов", + "groups.delete_unassign": "Убрать принадлежность к группе у её клиентов", + "groups.deleted": "Группа удалена", + "groups.deleting": "Обновляю клиентов и удаляю группу…", + "groups.description": "Описание", + "groups.edit_title": "Изменить группу", + "groups.editor_subtitle": "Группа объединяет действующую серверную политику доступа и шаблон, который используется при создании клиентских конфигураций.", + "groups.effective_allow": "Разрешённые исключения", + "groups.effective_deny": "Запрещённые исключения", + "groups.effective_policy": "Итоговая политика сервера", + "groups.empty": "Групп клиентов пока нет. Создайте группу, чтобы переиспользовать правила доступа и настройки клиентов.", + "groups.group": "Группа", + "groups.inherit": "Наследовать", + "groups.internet_access": "Доступ в интернет", + "groups.internet_short": "Интернет", + "groups.local_access": "Локальные сети", + "groups.local_short": "Локальные сети", + "groups.manage": "Группы", + "groups.members_count": "Клиентов: {count}", + "groups.name": "Название", + "groups.name_required": "Укажите название группы.", + "groups.new_client_defaults": "Шаблон конфигурации клиента", + "groups.new_clients_short": "Новые клиенты", + "groups.no_group": "Без группы", + "groups.none": "Нет", + "groups.override_client_config": "Переопределить шаблон группы для этого клиента", + "groups.override_client_config_hint": "Выключено: маршруты, DNS и Keepalive берутся из шаблона группы. Включено: у клиента собственные значения. Индивидуальная серверная политика выше работает независимо.", + "groups.policy_addresses_hint": "IPv4-адреса или CIDR через запятую. Индивидуальные исключения клиента имеют приоритет над исключениями группы.", + "groups.policy_custom": "Своя политика", + "groups.policy_inherit": "Использовать политику группы", + "groups.policy_mode": "Источник политики", + "groups.policy_mode_hint": "По умолчанию политика наследуется от группы. Исключения клиента никогда не меняют саму группу.", + "groups.routes_required": "Маршруты клиента не могут быть пустыми.", + "groups.subtitle": "Общие политики доступа и настройки для обычных клиентов выбранного интерфейса WireGuard.", + "groups.title": "Группы клиентов", + "groups.traffic_through_vpn": "Трафик через VPN", + "groups.updated": "Группа обновлена", + "groups.updating": "Обновляю политику группы…", + "help.example_note": "Все IP-адреса, имена интерфейсов, peer и домены в примерах справки вымышлены и используются только для документации. Заменяйте их значениями своей сети.", + "help.navigation": "Навигация по справке", + "help.open": "Открыть справку", + "help.subtitle": "Понятная справка по Главной, Серверу, Клиентам и Настройкам с короткими примерами.", + "help.title": "Справка WGTools", + "interfaces.add": "+ Добавить интерфейс", + "interfaces.create": "Создать интерфейс", + "interfaces.create_confirm": "Создать и запустить интерфейс {name}?", + "interfaces.create_failed": "Не удалось создать интерфейс", + "interfaces.create_hint": "Перед созданием WGTools проверит, что VPN-сеть, UDP-порт и policy table не конфликтуют с другими интерфейсами WireGuard.", + "interfaces.create_subtitle": "Создать отдельный интерфейс WireGuard со своим пулом адресов, UDP-портом и настройками маршрутизации.", + "interfaces.create_title": "Добавить интерфейс WireGuard", + "interfaces.created": "Интерфейс успешно создан.", + "interfaces.creating": "Генерирую ключи, создаю новую конфигурацию и запускаю WireGuard…", + "interfaces.current": "Текущий", + "interfaces.delete": "Удалить", + "interfaces.delete_confirm": "Удалить интерфейс {name}? Будут удалены его конфигурация WireGuard и все пиры этого интерфейса. Перед удалением WGTools создаст резервную копию конфигурации.", + "interfaces.delete_failed": "Не удалось удалить интерфейс", + "interfaces.delete_last": "Последний настроенный интерфейс WireGuard нельзя удалить здесь.", + "interfaces.delete_tooltip": "Удалить этот интерфейс WireGuard", + "interfaces.deleted": "Интерфейс удалён. Резервная копия: {backup}", + "interfaces.deleting": "Останавливаю WireGuard и удаляю интерфейс…", + "interfaces.display_name": "Отображаемое имя", + "interfaces.display_name_edit_hint": "Меняется только понятное имя в WGTools; системное имя Linux остаётся прежним.", + "interfaces.display_name_hint": "Необязательное понятное имя, например Работа или Подрядчики.", + "interfaces.identity": "Идентификация интерфейса", + "interfaces.none": "Интерфейсы WireGuard не найдены", + "interfaces.none_configured": "Настроенных интерфейсов WireGuard пока нет.", + "interfaces.peers_short": "пиров", + "interfaces.rename_failed": "Не удалось сохранить понятное имя интерфейса.", + "interfaces.select": "Выбрать", + "interfaces.subtitle": "У каждого интерфейса своя VPN-сеть, порт, клиенты и правила. Выбранный интерфейс используется на всех страницах WGTools.", + "interfaces.switch_title": "Интерфейсы WireGuard", + "interfaces.system_name": "Системное имя", + "interfaces.system_name_hint": "Имя интерфейса Linux, например wg1. После создания его лучше не менять.", + "interfaces.title": "Интерфейсы WireGuard", + "interfaces.unique_port_hint": "Каждый интерфейс WireGuard на этом сервере должен использовать свой UDP-порт.", + "interfaces.unique_table_hint": "WGTools рекомендует отдельную policy table для каждого интерфейса. Оставь пустым для обычной системной маршрутизации.", + "nav.clients": "Клиенты", + "nav.dashboard": "Главная", + "nav.server": "Сервер", + "nav.settings": "Настройки", + "server.access_apply_confirm": "Сохранить правило firewall и применить его сейчас? WireGuard кратковременно перезапустится, перед этим будет создан backup.", + "server.access_rule_deleted": "Правило доступа удалено.", + "server.access_rule_help": "Создание обычного правила FORWARD без ручного редактирования команд iptables.", + "server.access_rule_order_hint": "WGTools вставляет правила доступа в начало цепочки FORWARD, чтобы ограничения срабатывали раньше общих разрешающих правил VPN.", + "server.access_rule_saved": "Правило доступа сохранено и применено.", + "server.action": "Действие", + "server.action_hint": "REJECT сообщает клиенту об отказе; DROP молча отбрасывает трафик; ACCEPT явно разрешает его.", + "server.add_access_rule": "Добавить правило доступа", + "server.add_route": "Добавить маршрут", + "server.address": "Адрес", + "server.any": "Любой", + "server.any_protocol": "Любой", + "server.apply_confirm": "Сохранить эти настройки сервера и применить их сейчас? WireGuard будет кратковременно перезапущен. Перед изменением создаётся резервная копия, а при ошибке WGTools автоматически вернёт предыдущую конфигурацию.", + "server.apply_settings": "Сохранить и применить", + "server.applying_rule": "Создаю backup и применяю…", + "server.applying_settings": "Проверяю настройки, создаю резервную копию и применяю…", + "server.basic_settings": "Основные настройки", + "server.config_tab_help": "Открывает редактор исходного конфига выбранного интерфейса WireGuard.", + "server.create_confirm": "Создать и запустить сервер WireGuard с этими настройками?", + "server.create_server": "Создать сервер", + "server.create_step_conf": "Создаст конфигурацию выбранного интерфейса WireGuard с правами 600.", + "server.create_step_forward": "Настроит forwarding, NAT и при необходимости policy routing.", + "server.create_step_key": "Сгенерирует новую пару ключей сервера.", + "server.create_step_start": "Включит и запустит выбранный интерфейс wg-quick.", + "server.create_subtitle": "WireGuard установлен, но выбранный интерфейс пока не настроен.", + "server.create_success": "Сервер WireGuard успешно создан.", + "server.create_title": "Создать сервер WireGuard", + "server.creating": "Генерирую ключи, записываю конфигурацию и запускаю WireGuard…", + "server.custom_preserved": "Блоки пиров, маршруты site-to-site и пользовательские PostUp/PostDown, которыми эти поля не управляют, сохраняются.", + "server.delete_access_confirm": "Удалить это правило доступа и применить изменение?", + "server.delete_route_confirm": "Удалить этот пользовательский маршрут и применить изменение?", + "server.destination": "Назначение", + "server.destination_hint": "Пусто = любое назначение. Можно указать IP, CIDR или диапазон IP. Несколько назначений разделяйте запятыми.", + "server.destination_port": "Порт назначения", + "server.destination_port_hint": "Необязательно. Например 443 или диапазон 10000:20000. Для порта сначала выбери TCP или UDP.", + "server.details": "Детали", + "server.dev_word": "dev", + "server.diagnostics": "Диагностика", + "server.diagnostics_done": "Диагностика завершена", + "server.diagnostics_subtitle": "Текущие проверки системы. Конфигурация не изменяется.", + "server.direction": "Хук", + "server.edit_access_rule": "Изменить правило доступа", + "server.edit_route": "Изменить маршрут", + "server.edit_server": "Изменить настройки", + "server.edit_subtitle": "Основные настройки WireGuard, маршрутизации и NAT. Существующие пиры и пользовательские правила сохраняются.", + "server.edit_title": "Настройки сервера", + "server.edit_warning": "При изменении настроек интерфейса, маршрутизации или firewall интерфейс WireGuard кратковременно перезапускается. Активные пиры подключатся снова автоматически.", + "server.enable_forwarding": "Включить IPv4 forwarding", + "server.enable_nat": "Включить NAT / Masquerade", + "server.firewall": "Firewall и NAT", + "server.firewall_subtitle": "Правила, обнаруженные в хуках WireGuard.", + "server.firewall_subtitle_v08": "Базовые правила forwarding/NAT и правила доступа из конфигурации выбранного интерфейса. Простые правила редактируются здесь, сложные остаются доступны через raw-редактор.", + "server.forward_from_vpn": "Разрешить forwarding из VPN", + "server.forward_to_vpn": "Разрешить forwarding в VPN", + "server.forwarding_section": "Forwarding и NAT", + "server.gateway": "Шлюз", + "server.gateway_hint": "Нужен только при использовании отдельной таблицы policy routing.", + "server.install_success": "WireGuard успешно установлен.", + "server.install_wireguard": "Установить WireGuard", + "server.install_wireguard_help": "Выполняет apt update и устанавливает WireGuard вместе с сетевыми инструментами, необходимыми WGTools.", + "server.install_wireguard_title": "Установить WireGuard", + "server.installing": "Устанавливаю WireGuard… Это может занять некоторое время.", + "server.interface": "Интерфейс", + "server.interface_hint": "Сейчас WGTools управляет этим интерфейсом.", + "server.interface_name": "Интерфейс", + "server.interface_section": "Интерфейс WireGuard", + "server.ip_forwarding": "IPv4 forwarding", + "server.kind": "Тип", + "server.listen_port": "Порт", + "server.local_network": "Локальная сеть", + "server.local_network_hint": "Необязательный маршрут, который будет добавлен в policy table.", + "server.managed_automatically": "Управляется автоматически", + "server.nat": "NAT / Masquerade", + "server.network": "Сеть", + "server.network_settings": "Сеть и NAT", + "server.no_firewall": "Правила firewall не обнаружены", + "server.no_routes": "Маршруты не обнаружены", + "server.not_configured": "Не настроен", + "server.not_set": "Не задан", + "server.policy_disabled_hint": "Для обычной системной маршрутизации выключи эту опцию. Включай её, если VPN нужна отдельная source policy routing table.", + "server.policy_enabled": "Включить policy routing", + "server.policy_table": "Таблица маршрутизации", + "server.policy_table_hint": "Оставь пустым для обычной системной маршрутизации; например 200 — для source policy routing.", + "server.port_word": "порт", + "server.private_hidden": "Настроен (скрыт)", + "server.private_key": "Приватный ключ", + "server.protocol": "Протокол", + "server.route_apply_confirm": "Сохранить маршрут и применить его сейчас? WireGuard кратковременно перезапустится, перед этим будет создан backup.", + "server.route_custom": "Пользовательский", + "server.route_deleted": "Маршрут удалён.", + "server.route_device_hint": "Необязательный выходной интерфейс, например wg0 или enp6s18.", + "server.route_editor_help": "Маршрут будет добавляться при запуске WireGuard и удаляться при его остановке.", + "server.route_gateway_hint": "Необязательный шлюз. Нужно указать хотя бы шлюз или интерфейс.", + "server.route_managed_peer": "Site-to-site пир", + "server.route_managed_server": "Настройка сервера", + "server.route_network_hint": "IPv4-сеть, например 10.20.0.0/24, либо 'default'.", + "server.route_saved": "Маршрут сохранён и применён.", + "server.route_table_hint": "'main' — обычная маршрутизация, либо номер таблицы, например 200.", + "server.route_type": "Тип", + "server.routes": "Обнаруженные маршруты", + "server.routes_subtitle": "Маршруты из PostUp/PostDown и текущего policy routing.", + "server.routes_subtitle_v08": "Системные, site-to-site и пользовательские маршруты выбранного интерфейса. Пользовательские маршруты можно добавлять, изменять и удалять здесь.", + "server.routing": "Маршрутизация", + "server.routing_section": "Маршрутизация", + "server.rule": "Правило", + "server.rule_access": "Правило доступа", + "server.rule_advanced": "Расширенное", + "server.rule_apply_warning": "При применении маршрута или правила firewall интерфейс WireGuard кратковременно перезапускается. WGTools создаёт backup и автоматически откатывается при ошибке запуска.", + "server.rule_client_exception": "Исключение клиента", + "server.rule_client_policy": "Политика клиента", + "server.rule_managed_server": "Настройка сервера", + "server.rule_type": "Тип", + "server.run_diagnostics": "Запустить диагностику", + "server.save_apply": "Сохранить и применить", + "server.save_config": "SaveConfig", + "server.server_address": "VPN-адрес сервера", + "server.server_address_hint": "Обычно используется первый доступный адрес VPN-сети.", + "server.settings_applied": "Настройки сервера сохранены и успешно применены.", + "server.settings_apply_failed": "Не удалось применить настройки сервера", + "server.setup_required": "Требуется настройка", + "server.source": "Источник", + "server.source_hint": "Пусто = любой. Можно указать IP, CIDR или диапазон, например 10.0.0.100-10.0.0.120.", + "server.subtitle": "Установка WireGuard, первичная настройка и текущая конфигурация сервера.", + "server.tab_config": "Конфиг", + "server.tab_interface": "Интерфейс", + "server.tab_routing": "Маршрутизация", + "server.tab_vps": "VPS", + "server.table": "Таблица", + "server.tabs_aria": "Разделы настроек сервера", + "server.title": "Сервер", + "server.uplink": "Внешний интерфейс", + "server.use_raw_editor": "Через raw-редактор", + "server.via": "Через / Интерфейс", + "server.via_word": "via", + "server.vpn_network": "VPN сеть", + "server.vpn_network_hint": "Адреса клиентов будут выдаваться из этой сети.", + "server.vpn_pool": "Пул VPN-адресов", + "server.wg_not_installed": "WireGuard не установлен", + "server.wg_not_installed_subtitle": "WGTools может автоматически установить необходимые пакеты Debian.", + "server.what_happens": "Что сделает WGTools", + "settings.about": "О программе", + "settings.add_user": "Добавить пользователя", + "settings.advanced": "Расширенные настройки", + "settings.advanced_subtitle": "Прямой доступ к профессиональным инструментам конфигурации WireGuard.", + "settings.appearance": "Оформление", + "settings.applying_config": "Проверяю конфигурацию, создаю резервную копию и применяю…", + "settings.backup_count": "Сохранено копий", + "settings.backup_retention": "Хранить копий", + "settings.backup_retention_help": "Старые автоматические копии удаляются после создания новой. От 1 до 200 файлов.", + "settings.backups": "Резервные копии конфигурации", + "settings.backups_always_on": "Включено", + "settings.backups_subtitle": "WGTools автоматически создаёт резервную копию перед операциями, меняющими конфигурацию. Автоматические копии отключить нельзя.", + "settings.change_password": "Изменить пароль", + "settings.check_updates": "Проверить обновления", + "settings.config_applied": "Конфигурация сохранена и успешно применена.", + "settings.config_applied_restarted": "Конфигурация применена, WireGuard перезагружен.", + "settings.config_applied_stopped": "Конфигурация сохранена. WireGuard уже был остановлен и оставлен остановленным.", + "settings.config_apply_failed": "Не удалось применить конфигурацию", + "settings.config_load_failed": "Не удалось загрузить конфигурацию", + "settings.current_user": "Текущий пользователь", + "settings.current_version": "Текущая версия", + "settings.audit_action": "Действие", + "settings.audit_empty": "Событий аудита пока нет", + "settings.audit_log": "Аудит", + "settings.audit_log_subtitle": "Действия в панели, вход/восстановление доступа и Telegram, а также история подключений WireGuard-клиентов. Секреты сюда не записываются.", + "settings.audit_object": "Объект", + "settings.audit_result": "Результат", + "settings.audit_retention_note": "Срок хранения: 30 дней", + "settings.audit_search": "Быстрый поиск", + "settings.audit_search_clear": "Очистить поиск", + "settings.audit_search_empty": "По запросу событий нет", + "settings.audit_time": "Дата / время", + "settings.audit_user": "Пользователь", + "audit.user.telegram_short": "ТГ", + "audit.action.access_rule.created": "Правило доступа создано", + "audit.action.access_rule.deleted": "Правило доступа удалено", + "audit.action.access_rule.updated": "Правило доступа изменено", + "audit.action.auth.first_user_created": "Первый пользователь создан", + "audit.action.auth.login": "Вход в панель", + "audit.action.auth.login_failed": "Неудачный вход", + "audit.action.auth.logout": "Выход из панели", + "audit.action.backup.full_created": "Полная копия создана", + "audit.action.backup.full_restored": "Полная копия восстановлена", + "audit.action.client.config_downloaded": "Конфиг клиента скачан", + "audit.action.client.config_viewed": "Конфиг клиента открыт", + "audit.action.client.created": "Клиент создан", + "audit.action.client.deleted": "Клиент удалён", + "audit.action.client.qr_viewed": "QR клиента открыт", + "audit.action.client.updated": "Клиент изменён", + "audit.action.client_group.created": "Группа клиентов создана", + "audit.action.client_group.deleted": "Группа клиентов удалена", + "audit.action.client_group.updated": "Группа клиентов изменена", + "audit.action.interface.created": "Интерфейс создан", + "audit.action.interface.deleted": "Интерфейс удалён", + "audit.action.interface.renamed": "Интерфейс переименован", + "audit.action.route.created": "Маршрут создан", + "audit.action.route.deleted": "Маршрут удалён", + "audit.action.route.updated": "Маршрут изменён", + "audit.action.server.created": "Сервер создан", + "audit.action.server.raw_config_applied": "Raw config применён", + "audit.action.server.settings_applied": "Настройки сервера применены", + "audit.action.settings.updated": "Настройки панели изменены", + "audit.action.telegram.action_denied": "Действие Telegram запрещено", + "audit.action.telegram.action_failed": "Ошибка действия Telegram", + "audit.action.telegram.connection_test": "Проверка подключения Telegram", + "audit.action.telegram.settings_updated": "Настройки Telegram изменены", + "audit.action.update.checked": "Проверка обновлений", + "audit.action.update.scheduled": "Обновление запланировано", + "audit.action.update.backup_created": "Резервная копия перед обновлением", + "audit.action.update.completed": "Обновление завершено", + "audit.action.update.failed": "Ошибка обновления", + "audit.action.update.rollback_completed": "Предыдущая версия восстановлена", + "audit.action.update.rollback_failed": "Ошибка отката обновления", + "audit.action.user.created": "Пользователь создан", + "audit.action.user.deleted": "Пользователь удалён", + "audit.action.user.password_changed": "Пароль пользователя изменён", + "audit.action.vps.candidate_deleted": "VPS удалён из списка", + "audit.action.vps.candidate_saved": "VPS сохранён", + "audit.action.vps.detached": "VPS Relay отключён", + "audit.action.vps.relay_installed": "VPS Relay установлен", + "audit.action.wireguard.client_connected": "Клиент WireGuard подключён", + "audit.action.wireguard.installed": "WireGuard установлен", + "audit.action.wireguard.restarted": "WireGuard перезапущен", + "audit.action.wireguard.started": "WireGuard запущен", + "audit.action.wireguard.stopped": "WireGuard остановлен", + "audit.result.applied": "применено", + "audit.result.available": "доступно", + "audit.result.changed": "изменено", + "audit.result.created": "создано", + "audit.result.current": "актуально", + "audit.result.deleted": "удалено", + "audit.result.detached": "отключено", + "audit.result.denied": "запрещено", + "audit.result.downloaded": "скачано", + "audit.result.endpoint": "IP", + "audit.result.error": "Ошибка", + "audit.result.installed": "установлено", + "audit.result.invalid_credentials": "неверные данные", + "audit.result.ok": "успешно", + "audit.result.queued": "в очереди", + "audit.result.restarted": "перезапущено", + "audit.result.restored": "восстановлено", + "audit.result.rotated": "обновлено", + "audit.result.saved": "сохранено", + "audit.result.shown": "показано", + "audit.result.started": "запущено", + "audit.result.stopped": "остановлено", + "audit.result.updated": "изменено", + "settings.delete_user": "Удалить", + "settings.delete_user_confirm": "Удалить пользователя {name}?", + "settings.edit_raw_config": "Редактировать конфиг интерфейса", + "settings.expert_mode": "Для профи", + "settings.full_backup_component_clients": "Данные и приватные ключи клиентов, PSK, сроки доступа и принадлежность к группам, необходимые для повторной выдачи конфигов и QR.", + "settings.full_backup_component_db": "База WGTools: пользователи, настройки программы, почта/SMTP, Telegram и сохранённое состояние VPS Relay.", + "settings.full_backup_component_relay": "Данные для восстановления VPS Relay: controller/tenant ID, management token и домашний transport-ключ. После restore WGTools может заново поднять локальный transport и подключиться к сохранённому tenant на VPS.", + "settings.full_backup_component_system": "Файл sysctl WGTools для IPv4 forwarding, метаданные понятных имён интерфейсов и определения групп клиентов с их политиками и шаблонами, если они существуют. История автоматических копий конфигураций интерфейсов намеренно не включается.", + "settings.full_backup_component_wg": "Все обнаруженные конфигурации интерфейсов WireGuard из /etc/wireguard/ вместе с их состоянием запущен/остановлен.", + "settings.full_backup_create_failed": "Не удалось создать полную резервную копию", + "settings.full_backup_creating": "Создаю полную резервную копию…", + "settings.full_backup_download": "Создать", + "settings.full_backup_downloaded": "Резервная копия создана и скачана. Храните её в безопасном месте.", + "settings.full_backup_downloaded_short": "Полная копия скачана.", + "settings.full_backup_help": "Создаёт переносимую резервную копию WGTools для переезда или аварийного восстановления. В архив входят конфигурации WireGuard, пользователи, настройки, группы, данные управляемых клиентов и состояние, необходимое для повторного подключения к сохранённым VPS Relay.", + "settings.full_backup_no_file": "Файл резервной копии не выбран", + "settings.full_backup_restore": "Восстановить", + "settings.full_backup_restore_confirm": "Восстановить эту полную копию WGTools? Будут восстановлены пользователи, настройки, данные управляемых клиентов и все конфигурации WireGuard, включённые в архив. Интерфейсы WireGuard могут быть перезапущены. Перед восстановлением WGTools создаст страховочную копию и автоматически откатит изменения, если применение восстановленного состояния завершится ошибкой.", + "settings.full_backup_restore_failed": "Ошибка восстановления", + "settings.full_backup_restored": "Резервная копия успешно восстановлена. Войдите под пользователем из восстановленной копии.", + "settings.full_backup_restored_short": "Резервная копия восстановлена.", + "settings.full_backup_restoring": "Проверяю архив, создаю страховочную копию и выполняю восстановление…", + "settings.full_backup_secret_warning": "Файл содержит секретные данные: приватные ключи WireGuard, приватные ключи клиентов, preshared keys (PSK), хэши паролей WGTools, токен Telegram-бота и сохранённый пароль SMTP. Храните его как пароль и никогда не прикладывайте к публичным issue, чатам или форумам.", + "settings.full_backup_select": "Выбрать", + "settings.full_backup_title": "Полная резервная копия и восстановление", + "settings.full_mode": "Управление сервером и клиентами включено", + "settings.interface_help": "Интерфейс WireGuard выбирается при установке WGTools.", + "settings.language": "Язык", + "settings.last_backup": "Последняя копия", + "settings.latest_version": "Последний релиз", + "settings.loading_config": "Загрузка конфигурации…", + "settings.mode": "Режим", + "settings.never_logged_in": "Никогда", + "settings.new_password": "Новый пароль", + "settings.no_backups": "Резервных копий пока нет", + "settings.online_help": "Клиент считается онлайн, пока последний handshake не старше этого значения. От 30 до 3600 секунд.", + "settings.online_threshold": "Порог Online", + "settings.open_release": "Открыть релиз", + "settings.password_changed": "Пароль изменен.", + "settings.passwords_mismatch": "Пароли не совпадают.", + "settings.project_github": "Проект / GitHub", + "settings.raw_config_confirm": "Сохранить эту конфигурацию WireGuard и применить её сейчас? Выбранный интерфейс будет перезапущен. Сначала создаётся резервная копия; если новая конфигурация не запустится, WGTools автоматически выполнит откат.", + "settings.raw_config_help": "Открыть исходную конфигурацию выбранного интерфейса WireGuard.", + "settings.raw_config_title": "Конфигурация WireGuard вручную", + "settings.raw_config_warning": "Режим для опытных пользователей: это реальный конфигурационный файл WireGuard, в нём находятся приватный ключ сервера и PSK пиров, если они используются. При сохранении и применении интерфейс WireGuard будет перезапущен. Перед изменением WGTools создаёт резервную копию и автоматически откатывается, если новая конфигурация не запускается.", + "settings.readonly_mode": "Управление клиентами включено", + "settings.refresh_help": "Как часто WGTools запрашивает свежие данные состояния. От 2 до 60 секунд.", + "settings.refresh_interval": "Интервал обновления", + "settings.release_notes": "Описание релиза", + "settings.reload_config": "Перечитать с диска", + "settings.save_apply": "Сохранить и применить", + "settings.saved": "Настройки сохранены.", + "settings.saved_reload": "Настройки сохранены. Перезагрузка…", + "settings.saving": "Сохраняю настройки…", + "settings.status": "Обновление статуса", + "settings.status_help": "Настройки обновления живых данных Главной и статусов клиентов.", + "settings.subtitle": "Настройки интерфейса WGTools и отображения статуса.", + "settings.syntax_hint": "Секции, параметры, значения и комментарии WireGuard подсвечиваются во время редактирования.", + "settings.tab_about": "О программе", + "settings.tab_backups": "Резервные копии", + "settings.tab_general": "Основные", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Пользователи", + "settings.tabs_aria": "Разделы настроек", + "settings.telegram": "Telegram Bot", + "settings.telegram_allowed_ids": "Разрешённые Telegram user ID", + "settings.telegram_allowed_ids_help": "По одному числовому user ID в строке. Если неразрешённый пользователь отправит /start, WGTools ответит его Telegram user ID — его можно добавить сюда.", + "settings.telegram_bot_name": "Бот", + "settings.telegram_connected": "Подключён", + "settings.telegram_disabled": "Отключён", + "settings.telegram_dns": "DNS клиентов по умолчанию", + "settings.telegram_dns_help": "Необязательные IPv4-адреса DNS через запятую. Используются для клиентов, созданных ботом.", + "settings.telegram_enabled": "Включить Telegram-бота", + "settings.telegram_endpoint": "Адрес / домен сервера по умолчанию", + "settings.telegram_endpoint_help": "Используется ботом при создании нового клиентского конфига. Укажите только IP или домен; порт WireGuard берётся из конфигурации сервера.", + "settings.telegram_language": "Язык бота", + "settings.telegram_language_auto": "Авто (язык Telegram)", + "settings.telegram_last_poll": "Последняя связь с Telegram", + "settings.telegram_not_configured": "Не настроен", + "settings.telegram_remove_token": "Удалить токен", + "settings.telegram_remove_token_confirm": "Удалить сохранённый токен Telegram-бота и отключить бота?", + "settings.telegram_save": "Сохранить настройки Telegram", + "settings.telegram_saved": "Настройки Telegram сохранены.", + "settings.telegram_setup_note": "Создайте бота в @BotFather, сохраните токен, включите бота и отправьте ему /start. Если ваш user ID ещё не разрешён, WGTools покажет его — добавьте этот ID в список разрешённых Telegram user ID.", + "settings.telegram_status": "Состояние бота", + "settings.telegram_subtitle": "Удалённое управление WireGuard из Telegram: состояние сервера, клиенты, создание/удаление клиентов и запуск/перезапуск/остановка WireGuard.", + "settings.telegram_test": "Проверить подключение", + "settings.telegram_test_ok": "Telegram подключён: @{username}", + "settings.telegram_test_recent_ok": "Telegram-бот работает. Прямая проверка получила timeout, но бот недавно успешно связывался с Telegram.", + "settings.telegram_token": "Токен бота", + "settings.telegram_token_help": "Создайте бота через @BotFather и вставьте сюда его Bot API token. API ID и API Hash для Telegram Bot API не нужны.", + "settings.telegram_token_keep": "Оставьте поле пустым, чтобы сохранить уже записанный токен.", + "settings.telegram_waiting": "Настроен, ожидается запуск бота", + "settings.theme": "Тема", + "settings.theme_dark": "Тёмная", + "settings.theme_light": "Светлая", + "settings.theme_system": "Системная", + "settings.title": "Настройки", + "settings.update_available": "Доступно обновление", + "settings.update_backup_queued": "Обновление поставлено в очередь. Перед установкой WGTools создаст автоматическую полную резервную копию…", + "settings.update_backup_running": "Создаю автоматическую полную резервную копию перед обновлением…", + "settings.update_check_failed": "Не удалось проверить обновления", + "settings.update_checking": "Проверяю последний опубликованный релиз на GitHub…", + "settings.update_confirm": "Обновить WGTools с v{current} до v{latest}? Сначала будет создана полная резервная копия и копия приложения для отката. Веб-интерфейс ненадолго перезапустится.", + "settings.update_current": "Актуальная версия", + "settings.update_downloading": "Скачиваю и проверяю релиз с GitHub…", + "settings.update_failed": "Не удалось обновить WGTools.", + "settings.update_installing": "Устанавливаю обновление. Веб-интерфейс может ненадолго стать недоступен…", + "settings.update_no_update": "Установлена последняя версия WGTools.", + "settings.update_not_checked": "Не проверялось", + "settings.update_queued": "Обновление поставлено в очередь. Жду запуска службы обновления…", + "settings.update_rollback_ok": "Предыдущая версия WGTools восстановлена автоматически.", + "settings.update_rolling_back": "Обновление завершилось ошибкой. Восстанавливаю предыдущую версию WGTools…", + "settings.update_running": "Создаю резервные копии перед обновлением…", + "settings.update_safety_hint": "Обновление запускается только вручную. Перед установкой WGTools создаёт полную резервную копию состояния и отдельную копию приложения для отката. При ошибке предыдущая версия приложения восстанавливается автоматически. Сам WireGuard обновлятор не перезапускает, если новый релиз явно не меняет его конфигурацию.", + "settings.update_sidebar": "Доступна новая версия", + "settings.update_sidebar_hint": "Открыть Настройки → О программе", + "settings.update_starting": "Запускаю обновление…", + "settings.update_status_unknown": "Статус обновления временно недоступен. Повторяю проверку…", + "settings.update_subtitle": "Информация о проекте, автоматическая проверка новых релизов и безопасное обновление из GitHub Releases.", + "settings.update_success": "WGTools успешно обновлён до v{version}. Перезагружаю страницу…", + "settings.update_wgtools": "Обновить WGTools", + "settings.user_actions": "Действия", + "settings.user_created": "Создан", + "settings.user_created_ok": "Пользователь создан.", + "settings.user_deleted": "Пользователь удален.", + "settings.user_equal_rights": "Все пользователи WGTools имеют одинаковые права.", + "settings.user_last_login": "Последний вход", + "settings.user_name": "Логин", + "settings.users": "Пользователи", + "settings.users_subtitle": "Локальные учётные записи WGTools. E-mail необязателен и используется только для восстановления пароля при включённой почте.", + "vps.add": "Добавить VPS", + "vps.add_help": "WGTools подключится по SSH для проверки или установки Relay. Пароль и приватный SSH-ключ не сохраняются.", + "vps.add_title": "Добавить VPS", + "vps.agent": "Relay Agent", + "vps.agent_found": "Уже установлен", + "vps.agent_will_install": "Будет установлен", + "vps.arch": "Архитектура", + "vps.auth_method": "Способ входа", + "vps.authentication": "Авторизация SSH", + "vps.check": "Проверить VPS", + "vps.check_failed": "Проверка VPS не пройдена", + "vps.check_link": "Проверить связь", + "vps.check_ok": "VPS совместим", + "vps.checking": "Проверяем SSH и совместимость VPS…", + "vps.connections": "подключений", + "vps.credentials_not_saved": "Используется только для этой проверки и не сохраняется WGTools.", + "vps.delete_candidate": "Убрать", + "vps.delete_installed": "Удалить VPS", + "vps.delete_installed_confirm": "Удалить «{name}» из WGTools? Локальный транспорт Relay будет отключён, но Relay Agent и tenant на самом VPS останутся без изменений. Этот VPS можно будет добавить снова и WGTools подключится к существующему Relay, не создавая новый. Клиенты, использующие Relay, не смогут подключаться через него, пока VPS не будет подключён повторно.", + "vps.delete_installed_failed": "Не удалось удалить VPS из WGTools", + "vps.delete_installed_ok": "VPS удалён из WGTools. Relay на удалённом VPS сохранён и может быть подключён повторно.", + "vps.empty_help": "Добавьте VPS на Debian или Ubuntu: WGTools проверит SSH-доступ, совместимость системы и свободные UDP-порты.", + "vps.empty_title": "VPS пока не настроен", + "vps.endpoint": "Публичная точка", + "vps.endpoint_domain": "Домен (рекомендуется)", + "vps.endpoint_domain_hint": "При замене основного VPS достаточно будет изменить DNS, не перевыпуская конфиги клиентов.", + "vps.health_failed": "Проверка Relay не пройдена", + "vps.host": "IP / имя хоста", + "vps.host_key": "Ключ хоста SSH", + "vps.identity": "Подключение к VPS", + "vps.install_failed": "Не удалось установить Relay", + "vps.install_ok": "Relay установлен, защищённый канал управления проверен", + "vps.install_relay": "Установить Relay", + "vps.install_title": "Установить VPS Relay", + "vps.installed": "Установлен", + "vps.installing": "Устанавливаем Relay Agent и поднимаем защищённый транспортный туннель…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Пароль ключа", + "vps.link_ok": "Связь с Relay работает", + "vps.multi_tenant_note": "На VPS уже работает WGTools Relay Agent. Он не будет переустановлен: для этого WGTools создаст отдельное изолированное подключение со своими ключами и UDP-портами.", + "vps.name": "Название", + "vps.no_domain": "Подключение по IP", + "vps.not_installed": "Будет установлен", + "vps.os": "Операционная система", + "vps.password": "Пароль", + "vps.phase_note": "Relay Agent поддерживает несколько независимых WGTools на одном VPS. Каждый контроллер получает отдельное изолированное подключение, ключи и UDP-порты; существующие подключения не изменяются.", + "vps.port_pair": "UDP-порты", + "vps.ports_adjusted": "выбраны свободные порты", + "vps.private_key": "Приватный ключ", + "vps.privilege": "Права", + "vps.public_endpoint": "Будущая публичная точка", + "vps.ready_help": "SSH-данные используются для проверки совместимости и сразу для установки Relay; WGTools их не сохраняет.", + "vps.reconnect_note": "На VPS найдено существующее подключение Relay, созданное этим WGTools. Будет восстановлено именно оно — новый tenant и новые UDP-порты создаваться не будут.", + "vps.reconnect_ok": "Существующий Relay успешно подключён повторно", + "vps.reconnect_relay": "Подключить Relay", + "vps.relay_port": "UDP-порт Relay", + "vps.remove_confirm": "Убрать этого кандидата VPS? На удалённом сервере ничего не менялось.", + "vps.save_candidate": "Сохранить кандидата", + "vps.saved": "Кандидат VPS сохранён", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH-ключ", + "vps.ssh_port": "SSH-порт", + "vps.ssh_user": "SSH-пользователь", + "vps.status_candidate": "Готов к установке", + "vps.status_installed": "Relay подключён", + "vps.subtitle": "Подготовка публичного VPS для удалённого доступа, когда у этого сервера WGTools нет белого IP.", + "vps.tenant": "Подключение", + "vps.title": "VPS Relay", + "vps.transport_port": "UDP-порт транспорта", + "vps.transport_port_hint": "Отдельный UDP-порт защищённого туннеля Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Сохранено", + "vps.active_short": "Активно", + "dashboard.traffic_reset": "Сбросить", + "dashboard.traffic_reset_confirm": "Сбросить накопленные счётчики трафика WireGuard для этого интерфейса? Счётчики клиентов также начнутся с нуля.", + "dashboard.traffic_reset_done": "Счётчики трафика сброшены", + "dashboard.traffic_reset_failed": "Не удалось сбросить счётчики трафика", + "audit.action.traffic.reset": "Счётчики трафика сброшены", + "audit.result.reset": "сброшено", + "server.mtu": "MTU", + "server.mtu_auto": "Авто", + "server.mtu_hint": "Необязательно. Пустое поле — автоматический MTU wg-quick. Укажите вручную, например 1380 или 1420, если этого требует сеть, LTE или PPPoE.", + "clients.peer_isolation": "Изоляция VPN-клиента", + "clients.peer_isolation_enable": "Изолировать от других VPN-клиентов", + "clients.peer_isolation_hint": "Блокирует обмен трафиком между этим клиентом и другими адресами из пула WireGuard. Доступ к самому серверу, Интернету, локальным и Site-to-site сетям определяется остальными правилами.", + "clients.credentials_rotate": "Ключи клиента", + "clients.credentials_rotate_button": "Сменить ключи", + "clients.credentials_rotate_confirm": "Сгенерировать новые ключи этого клиента? Если клиент сейчас подключён, его текущая WireGuard-сессия будет принудительно разорвана. После смены нужно выдать новый конфиг или QR.", + "clients.credentials_rotate_confirm_psk": "Сгенерировать новую ключевую пару и новый PSK этого клиента? Если клиент сейчас подключён, его текущая WireGuard-сессия будет принудительно разорвана. После смены нужно выдать новый конфиг или QR.", + "clients.credentials_rotate_hint": "Одной операцией меняет PrivateKey/PublicKey и, если PSK включён, также PSK. Адрес, маршруты, группа, расписание, изоляция и накопленная статистика сохраняются.", + "clients.credentials_rotating": "Генерируем новые ключи и отключаем старую сессию клиента…", + "clients.credentials_rotated": "Ключи клиента сменены. Если клиент был подключён, его старая сессия принудительно отключена. Старый конфиг больше не работает; перед подключением выдайте новый конфиг или QR.", + "clients.credentials_rotated_short": "Ключи клиента сменены — нужен новый конфиг", + "audit.action.client.credentials_rotated": "Ключи клиента обновлены", + "clients.credentials_connection_lost": "Соединение с WGTools прервалось. Если панель была открыта через клиента, которому только что сменили ключи, это ожидаемо: его старая WireGuard-сессия отключается сразу. Подключитесь к WGTools другим способом и выдайте новый конфиг или QR.", + "nav.navigation": "Основная навигация", + "nav.project_github": "WGTools на GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Пока необязательно. После настройки почты адрес можно использовать для восстановления пароля.", + "auth.forgot_password": "Забыли пароль?", + "auth.reset_title": "Сброс пароля", + "auth.reset_subtitle": "Получите одноразовый код по почте и задайте новый пароль WGTools.", + "auth.reset_identifier": "Логин или E-mail", + "auth.reset_identifier_help": "Для защиты данных WGTools всегда показывает одинаковый ответ независимо от существования учётной записи.", + "auth.send_reset_code": "Отправить код", + "auth.reset_code_sent_generic": "Если такая учётная запись существует и для неё указан E-mail, код сброса отправлен. Код действует 15 минут.", + "auth.reset_code": "6-значный код", + "auth.set_new_password": "Установить новый пароль", + "auth.request_another_code": "Запросить другой код", + "auth.back_to_login": "Вернуться ко входу", + "auth.reset_not_configured": "Восстановление пароля по почте не настроено. Обратитесь к администратору WGTools.", + "settings.tab_mail": "Почта", + "settings.mail": "Почта / SMTP", + "settings.mail_subtitle": "SMTP используется для восстановления пароля.", + "settings.mail_not_configured": "Не настроено", + "settings.mail_enabled": "Включить почту и восстановление пароля", + "settings.mail_smtp_host": "SMTP-сервер", + "settings.mail_smtp_port": "SMTP-порт", + "settings.mail_security": "Шифрование", + "settings.mail_security_none": "Без шифрования", + "settings.mail_username": "Логин SMTP", + "settings.mail_username_help": "Используется для авторизации SMTP и как E-mail отправителя.", + "settings.mail_password": "Пароль SMTP", + "settings.mail_password_keep": "Оставьте пустым, чтобы сохранить текущий пароль.", + "settings.mail_from_email": "E-mail отправителя", + "settings.mail_from_name": "Имя отправителя", + "settings.mail_test_recipient": "Получатель теста", + "settings.mail_test_recipient_help": "Тест использует уже сохранённые настройки SMTP.", + "settings.mail_remove_password": "Удалить пароль", + "settings.mail_test": "Отправить тест", + "settings.mail_save": "Сохранить настройки почты", + "settings.mail_enabled_badge": "Включено", + "settings.mail_disabled_badge": "Отключено", + "settings.mail_saved": "Настройки почты сохранены.", + "settings.mail_remove_password_confirm": "Удалить сохранённый пароль SMTP и отключить почту?", + "settings.mail_password_removed": "Пароль SMTP удалён, почта отключена.", + "settings.mail_test_recipient_required": "Укажите E-mail получателя тестового письма.", + "settings.mail_testing": "Отправляем тестовое письмо…", + "settings.mail_test_ok": "Тестовое письмо успешно отправлено.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Необязательно. Нужен только для самостоятельного восстановления пароля.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail сохранён.", + "settings.send_password_reset": "Отправить сброс", + "settings.user_reset_mail_not_configured": "Сначала настройте и включите почту.", + "settings.user_reset_email_missing": "Сначала укажите E-mail пользователя.", + "settings.user_reset_confirm": "Отправить код сброса пароля пользователю {name} на {email}?", + "settings.user_reset_sent": "Код сброса пароля отправлен на {email}.", + "audit.action.auth.password_reset_requested": "Запрошен сброс пароля", + "audit.action.auth.password_reset_code_sent": "Код сброса отправлен", + "audit.action.auth.password_reset_completed": "Пароль восстановлен", + "audit.action.auth.password_reset_failed": "Ошибка сброса пароля", + "audit.action.mail.settings_updated": "Настройки почты изменены", + "audit.action.mail.test_sent": "Тестовое письмо отправлено", + "audit.action.mail.test_failed": "Ошибка тестового письма", + "audit.action.user.email_changed": "E-mail пользователя изменён", + "audit.action.user.password_reset_sent": "Сброс пароля пользователю отправлен", + "audit.action.user.password_reset_failed": "Не удалось отправить сброс пароля", + "audit.result.accepted": "принято", + "audit.result.sent": "отправлено", + "audit.result.invalid_code": "неверный код", + "common.copy": "Копировать", + "common.copied": "Скопировано", + "clients.use_panel_host": "Подставить адрес панели", + "clients.use_panel_host_done": "Адрес панели подставлен: {host}", + "clients.use_panel_host_failed": "Не удалось определить адрес панели из строки браузера.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Встроенный HTTPS Let’s Encrypt для прямого доступа к WGTools без reverse proxy.", + "settings.https_disabled": "Отключено", + "settings.https_enabled": "Включено", + "settings.https_enable": "Включить встроенный HTTPS", + "settings.https_type": "Сертификат для", + "settings.https_domain": "Домен", + "settings.https_public_ip": "Публичный IP", + "settings.https_target": "Домен или публичный IP", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "HTTPS-порт", + "settings.https_port80_note": "TCP-порт 80 должен быть открыт из Интернета для выпуска и автоматического продления сертификата. Для самой панели откройте выбранный HTTPS-порт.", + "settings.https_check_ports": "Проверить порты", + "settings.https_certificate": "Сертификат", + "settings.https_certificate_ready": "Готов", + "settings.https_certificate_missing": "Не выпущен", + "settings.https_expires": "Действует до", + "settings.https_renewal": "Автопродление", + "settings.https_renewal_enabled": "Включено", + "settings.https_renewal_disabled": "Отключено", + "settings.https_certificate_path": "Сертификат", + "settings.https_private_key_path": "Приватный ключ", + "settings.https_issue": "Получить / обновить сертификат", + "settings.https_port_free": "Свободен", + "settings.https_port_busy": "Занят", + "settings.https_ports_checked": "Проверка портов завершена.", + "settings.https_target_email_required": "Укажите домен/публичный IP и e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Получить или обновить сертификат Let’s Encrypt для {target}? Введённые настройки HTTPS будут сохранены. TCP-порт 80 должен быть доступен из Интернета.", + "settings.https_issuing": "Получаем сертификат Let’s Encrypt…", + "settings.https_issue_ok": "Сертификат готов.", + "settings.https_already_enabled": "Встроенный HTTPS уже включён.", + "settings.https_already_disabled": "Встроенный HTTPS уже отключён.", + "settings.https_enable_confirm": "Включить встроенный HTTPS на TCP {port} с путём {path}? WGTools перезапустится, а эта страница переподключится по новому адресу.", + "settings.https_disable_confirm": "Отключить встроенный HTTPS и вернуть WGTools на HTTP?", + "settings.https_switching": "Включаем HTTPS и перезапускаем WGTools…", + "settings.https_switching_http": "Отключаем HTTPS и перезапускаем WGTools…", + "audit.action.https.certificate_issued": "HTTPS-сертификат выпущен", + "audit.action.https.certificate_failed": "Ошибка выпуска HTTPS-сертификата", + "audit.action.https.enabled": "HTTPS включён", + "audit.action.https.disabled": "HTTPS отключён", + "audit.result.issued": "выпущен", + "audit.result.enabled": "включено", + "audit.result.disabled": "отключено", + "settings.https_access_path": "Путь доступа к панели", + "settings.https_access_path_help": "Задайте свой путь. При включённом встроенном HTTPS запросы вне него получают 404.", + "settings.https_enable_fields_required": "Укажите домен/публичный IP, e-mail Let’s Encrypt и путь доступа к панели.", + "settings.https_use_panel_host": "Подставить адрес панели", + "settings.https_reconnecting": "WGTools переключается на новый HTTPS-адрес…", + "server.tab_nodes": "Узлы", + "common.type": "Тип", + "common.status": "Статус", + "common.copy_failed": "Не удалось скопировать", + "clients.vpn_address": "VPN адрес", + "nodes.title": "Узлы WGTools", + "nodes.subtitle": "Объединяйте несколько серверов WGTools в одну защищённую сеть и публикуйте только те сети, которые должны быть доступны другим узлам.", + "nodes.enable_hub": "Включить HUB", + "nodes.connect_hub": "Подключиться к HUB", + "nodes.settings": "Настройки узла", + "nodes.settings_action": "Настройки", + "nodes.sync_now": "Синхронизировать", + "nodes.disable": "Отключить узлы", + "nodes.disable_action": "Отключить", + "nodes.join_title": "Подключение новых узлов", + "nodes.join_help": "Создайте одноразовый код и введите его на другой панели WGTools вместе со служебным endpoint HUB, например vpn.example.com:51950. Код действует 15 минут и используется один раз.", + "nodes.create_code": "Создать код", + "nodes.connected_nodes": "Связанные узлы", + "nodes.connected_nodes_help": "Информация о других панелях, их опубликованных сетях и клиентах. Клиенты удалённых панелей доступны только для просмотра.", + "nodes.enable_hub_help": "Эта панель станет центральным узлом. На одном номере порта HUB принимает UDP WireGuard и защищённый TCP для первоначального pairing.", + "nodes.node_name": "Имя узла", + "nodes.transport_network": "Служебная сеть узлов", + "nodes.transport_help": "Отдельная приватная сеть только для связи WGTools ↔ WGTools. Не должна пересекаться с вашими VPN/LAN сетями.", + "nodes.panel_url": "Адрес панели", + "nodes.panel_url_help": "Необязательно. Это только информационная ссылка для кнопки «Открыть панель» на других узлах и она никак не участвует в работе Nodes.", + "nodes.extra_networks": "Дополнительные сети узла", + "nodes.extra_networks_help": "По одной сети в строке. VPN-сети интерфейсов и удалённые сети Site-to-site клиентов публикуются автоматически. Здесь добавляются только остальные маршрутизируемые LAN/сети, например 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools подставляет найденные VPN-сети, сети Site-to-Site и локальные маршрутизируемые LAN. Оставьте только те сети, которые этот узел должен публиковать в Nodes. По одной сети в строке.", + "nodes.published_networks_settings_help": "По одной сети в строке. Здесь хранится явный список сетей, которые узел публикует в Nodes. Удалённая строка перестаёт распространяться на другие узлы.", + "nodes.available_networks_help": "Сейчас обнаружены: {networks}. Новые сети не публикуются автоматически — добавьте нужные в список выше.", + "nodes.available_networks_none": "Дополнительных локальных сетей сейчас не обнаружено.", + "nodes.connect_help": "Введите служебный endpoint HUB и одноразовый код. Адрес веб-панели, её HTTPS-порт, сертификат и приватный путь для подключения Nodes не используются.", + "nodes.join_code": "Код подключения", + "nodes.connect_reachability_note": "Первоначальный pairing идёт по защищённому TCP на указанном порту. После создания wgnode0 списки сетей, статусы, версии и read-only данные клиентов синхронизируются с HUB по его служебному адресу внутри WireGuard-туннеля.", + "nodes.connect": "Подключить", + "nodes.settings_help": "Имя узла, необязательная ссылка «Открыть панель» и явный список публикуемых сетей. Адрес панели не используется для pairing или синхронизации Nodes.", + "nodes.details": "Подробнее", + "nodes.not_configured": "WGTools Nodes не настроены", + "nodes.not_configured_help": "Включите HUB на этой панели или подключите её к уже существующему WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Подключён к HUB", + "nodes.mode_none": "Не настроено", + "nodes.role": "Роль", + "nodes.tunnel": "Туннель узлов", + "nodes.node_ip": "Адрес узла", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Опубликованные сети", + "nodes.last_sync": "Последняя синхронизация", + "nodes.no_nodes_hub": "Пока нет подключённых узлов. Создайте код подключения и используйте его на другой панели WGTools.", + "nodes.no_nodes_spoke": "Информация об удалённых узлах ещё не получена.", + "nodes.clients_short": "Клиенты", + "nodes.open_panel": "Открыть панель", + "nodes.route_conflict": "Конфликт маршрутов", + "nodes.no_published_networks": "Нет опубликованных сетей", + "nodes.load_failed": "Не удалось загрузить WGTools Nodes", + "nodes.enable_hub_confirm": "Включить WGTools HUB и создать служебный WireGuard-туннель узлов?", + "nodes.applying": "Настраиваем служебный туннель WGTools Nodes…", + "nodes.enable_failed": "Не удалось включить HUB", + "nodes.hub_enabled": "WGTools HUB включён", + "nodes.connecting": "Проверяем код HUB и создаём защищённый туннель узлов…", + "nodes.connect_failed": "Не удалось подключиться к HUB", + "nodes.connected": "Подключено к WGTools HUB", + "nodes.settings_failed": "Не удалось сохранить настройки узла", + "nodes.settings_saved": "Настройки узла сохранены", + "nodes.code_failed": "Не удалось создать код подключения", + "nodes.code_expires": "Одноразовый код. Действует до {time}.", + "nodes.code_copied": "Код подключения скопирован", + "nodes.network_vpn": "VPN-клиенты", + "nodes.network_site_to_site": "Сеть Site-to-site", + "nodes.network_custom": "Дополнительная сеть", + "nodes.conflict": "Конфликт", + "nodes.remote_clients": "Клиенты (только чтение)", + "nodes.no_clients": "Узел не передал список клиентов", + "nodes.details_failed": "Не удалось загрузить информацию об узле", + "nodes.remove_confirm": "Удалить узел «{name}» из HUB? Его доступ через служебный туннель будет отозван.", + "nodes.remove_failed": "Не удалось удалить узел", + "nodes.removed": "Узел удалён", + "nodes.disable_hub_confirm": "Отключить HUB и отсоединить все WGTools Nodes? Служебный туннель будет удалён.", + "nodes.disconnect_confirm": "Отключить эту панель WGTools от HUB и удалить служебный туннель?", + "nodes.disable_failed": "Не удалось отключить WGTools Nodes", + "nodes.disabled": "WGTools Nodes отключены", + "nodes.sync_failed": "Не удалось синхронизировать узел", + "nodes.synced": "Информация об узлах синхронизирована", + "nodes.service_port": "Порт Nodes", + "nodes.service_port_help": "Один номер порта используется одновременно: UDP — WireGuard, TCP — защищённое первоначальное подключение.", + "nodes.hub_port_forward_note": "Если HUB находится за NAT, пробросьте на него один и тот же порт и по UDP, и по TCP. Веб-порт WGTools, HTTPS и приватный путь панели к Nodes не относятся.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Домен или IP и порт Nodes без http:// и https://, например vpn.example.com:51950.", + "settings.collapse_sidebar": "Свернуть панель", + "settings.expand_sidebar": "Развернуть панель", + "settings.https_issue_fields_required": "Укажите домен/публичный IP, e-mail Let’s Encrypt и путь доступа к панели.", + "settings.https_issue_ok_saved": "Сертификат готов, настройки HTTPS сохранены.", + "settings.https_enable_need_certificate": "Сначала получите сертификат.", + "settings.https_enable_certificate_mismatch": "Для текущего домена или публичного IP нужно получить сертификат.", + "settings.https_enable_certificate_expired": "Сертификат истёк. Обновите его перед включением HTTPS.", + "settings.https_enable_certificate_ready": "Сертификат готов — встроенный HTTPS можно включить.", + "settings.https_enable_active_help": "Снимите флажок и сохраните, чтобы вернуться на HTTP.", + "settings.https_certificate_expired": "Истёк", + "settings.https_certificate_wrong_target": "Для другого адреса", + "nodes.network_conflict_error": "Опубликованные сети конфликтуют с другим узлом или служебной сетью Nodes: {conflicts}. Удалите или измените конфликтующую сеть.", + "nodes.networks_changed": "Обнаруженные сети изменились после последнего сохранения. Новые: {added}. Больше не обнаруживаются: {removed}. Проверьте список опубликованных сетей и сохраните настройки после проверки.", + "nodes.review_networks": "Проверьте сети", + "nodes.vpn_pool_mismatch": "VPN-пул изменён: в Nodes всё ещё опубликовано {old}, а текущий VPN-пул WireGuard — {current}. Откройте настройки узла и обновите список опубликованных сетей.", + "server.error_vpn_network_invalid": "VPN-сеть должна быть корректной IPv4-сетью, например 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Поддерживаются только IPv4 VPN-сети.", + "server.error_vpn_network_too_small": "VPN-сеть должна содержать как минимум два доступных адреса.", + "server.error_vpn_network_no_hosts": "В выбранной VPN-сети нет доступных адресов для сервера.", + "server.error_server_address_prefix": "VPN-адрес сервера должен содержать префикс, например 10.0.0.1/24.", + "server.error_server_address_network": "VPN-адрес сервера должен принадлежать выбранному пулу VPN-адресов и использовать тот же префикс.", + "server.error_server_address_reserved": "VPN-адрес сервера не может быть адресом сети или широковещательным адресом.", + "server.error_listen_port_number": "Порт WireGuard должен быть числом.", + "server.error_listen_port_range": "Порт WireGuard должен быть в диапазоне от 1 до 65535.", + "server.error_mtu_number": "MTU должен быть числом.", + "auth.mfa_title": "Двухфакторная аутентификация", + "auth.mfa_login_help": "Введите 6-значный код из Google Authenticator или один из резервных кодов.", + "auth.mfa_code": "Код аутентификации", + "auth.mfa_verify": "Проверить и войти", + "auth.mfa_back": "Вернуться к паролю", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Двухфакторная аутентификация (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Включена", + "settings.mfa_disabled": "Отключена", + "settings.mfa_google_help": "Защитите эту учётную запись с помощью Google Authenticator или другого TOTP-приложения. Для начала настройки нужен текущий пароль.", + "settings.current_password": "Текущий пароль", + "settings.mfa_start": "Настроить Google Authenticator", + "settings.mfa_secret": "Ключ для ручной настройки", + "settings.mfa_scan_help": "Отсканируйте QR-код в Google Authenticator, затем введите текущий 6-значный код для включения MFA.", + "settings.mfa_code": "6-значный код", + "settings.mfa_enable": "Включить MFA", + "settings.mfa_manage_help": "Для изменения MFA введите текущий пароль и код Google Authenticator или резервный код.", + "settings.mfa_code_or_recovery": "Код Authenticator или резервный код", + "settings.mfa_regenerate": "Новые резервные коды", + "settings.mfa_disable": "Отключить MFA", + "settings.mfa_recovery_title": "Резервные коды", + "settings.mfa_recovery_help": "Сохраните эти коды сейчас. Каждый код можно использовать один раз, если Google Authenticator недоступен. Повторно они не показываются.", + "settings.mfa_recovery_remaining": "Осталось резервных кодов: {count}", + "settings.mfa_enabled_ok": "MFA включена.", + "settings.mfa_disabled_ok": "MFA отключена.", + "settings.mfa_disable_confirm": "Отключить двухфакторную аутентификацию для этой учётной записи?", + "settings.mfa_regenerate_confirm": "Заменить все существующие резервные коды?", + "settings.mfa_recovery_regenerated": "Созданы новые резервные коды.", + "audit.action.auth.mfa_failed": "Ошибка проверки MFA", + "audit.action.auth.mfa_recovery_used": "Использован резервный код MFA", + "audit.action.user.mfa_setup_started": "Начата настройка MFA", + "audit.action.user.mfa_enabled": "MFA включена", + "audit.action.user.mfa_disabled": "MFA отключена", + "audit.action.user.mfa_disabled_cli": "MFA отключена через CLI", + "audit.action.user.mfa_recovery_regenerated": "Резервные коды MFA обновлены", + "settings.mfa_error_password": "Неверный текущий пароль.", + "settings.mfa_error_code": "Неверный код аутентификации.", + "settings.mfa_error_already_enabled": "MFA уже включена.", + "settings.mfa_error_not_enabled": "MFA не включена.", + "settings.mfa_error_not_started": "Начните настройку MFA заново.", + "trace.title": "Traceroute, ping и карта маршрута", + "trace.subtitle": "Проверка задержки до VPS или другого сервера и поиск участка маршрута, где растёт ping.", + "trace.target": "IP или имя сервера", + "trace.show_map": "Показать маршрут на карте", + "trace.run": "Запустить", + "trace.geo_note": "Геолокация приблизительная. Если карта включена, публичные IP узлов отправляются в ipwho.is для определения координат; тайлы карты загружаются с OpenStreetMap.", + "trace.latency_note": "Traceroute измеряет задержку в миллисекундах, а не пропускную способность в Мбит/с.", + "trace.map": "Карта маршрута", + "trace.map_hint": "Интерактивная карта: перетаскивайте мышью, масштабируйте колесом или кнопками +/− и нажимайте на узлы для деталей.", + "trace.hop": "Узел / IP", + "trace.location": "Расположение", + "trace.avg_rtt": "Средний RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Потери", + "trace.summary_target": "Цель", + "trace.summary_ping": "Средний ping", + "trace.summary_loss": "Потери ping", + "trace.summary_hops": "Узлов", + "trace.no_reply": "Нет ответа", + "trace.private": "Локальная сеть", + "trace.unknown": "Неизвестно", + "trace.running": "Выполняются ping и traceroute… Это может занять до минуты.", + "trace.done": "Проверка маршрута завершена.", + "trace.failed": "Не удалось выполнить traceroute", + "trace.partial_geo": "Для части публичных узлов не удалось определить геолокацию.", + "trace.not_reached": "Traceroute не дошёл до конечного адреса.", + "trace.reached": "Цель достигнута", + "trace.ms": "мс", + "server.tab_trace": "Маршрут", + "trace.map_controls": "Управление картой", + "trace.zoom_in": "Приблизить", + "trace.zoom_out": "Отдалить", + "trace.fit_route": "Показать весь маршрут", + "trace.fit": "Весь маршрут", + "trace.map_click_hint": "Нажмите на узел, чтобы увидеть IP, расположение, ASN и RTT.", + "trace.route_path": "Маршрут", + "trace.ping_ok_trace_filtered": "Цель отвечает на ping; конечные узлы traceroute не отвечают.", + "trace.latency_legend": "Рост задержки между отвечающими узлами", + "trace.latency_ok": "Δ RTT ≤ 5 мс — нормально", + "trace.latency_warn": "Δ RTT 5–20 мс — рост", + "trace.latency_bad": "Δ RTT > 20 мс — резкий скачок" +} diff --git a/app/static/pl.json b/app/static/pl.json new file mode 100644 index 0000000..ff5fd67 --- /dev/null +++ b/app/static/pl.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Utwórz użytkownika", + "auth.login_subtitle": "Podaj nazwę użytkownika i hasło WGTools.", + "auth.login_title": "Zaloguj się do WGTools", + "auth.password": "Hasło", + "auth.password_repeat": "Powtórz hasło", + "auth.setup_help": "Pierwsze konto ma pełny dostęp do WGTools. Kolejnych użytkowników można dodać później w ustawieniach.", + "auth.setup_subtitle": "Przed zarządzaniem serwerem trzeba utworzyć konto WGTools.", + "auth.setup_title": "Utwórz pierwszego użytkownika", + "auth.sign_in": "Zaloguj", + "auth.sign_out": "Wyloguj", + "auth.username": "Nazwa użytkownika", + "clients.actions": "Akcje", + "clients.add": "+ Dodaj klienta", + "clients.address": "Adres VPN", + "clients.address_hint": "Pierwszy wolny adres jest proponowany automatycznie.", + "clients.allowed_ips_required": "Podaj przynajmniej jedną sieć AllowedIPs dla konfiguracji klienta.", + "clients.basic_connection": "Ustawienia połączenia", + "clients.basic_details": "Klient", + "clients.client": "Klient", + "clients.client_allowed_ips": "AllowedIPs w konfiguracji klienta", + "clients.config_private_warning": "Ta konfiguracja zawiera klucz prywatny klienta. Przechowuj ją bezpiecznie.", + "clients.config_title": "Konfiguracja klienta", + "clients.config_unavailable": "Konfiguracja niedostępna", + "clients.connection_direct": "Bezpośrednio do WGTools", + "clients.connection_path": "Ścieżka połączenia", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Połącz przez", + "clients.connection_via_hint": "Wybierz publiczny punkt wejścia dla klienta. Relay jest widoczny tylko po instalacji dla wybranego interfejsu WireGuard.", + "clients.copy_config": "Kopiuj", + "clients.copy_done": "Skopiowano konfigurację", + "clients.create_subtitle": "Utwórz peer WireGuard i wygeneruj jego konfigurację.", + "clients.create_title": "Utwórz klienta", + "clients.creating": "Generowanie kluczy i stosowanie konfiguracji klienta…", + "clients.day_fri": "Pt", + "clients.day_mon": "Pon", + "clients.day_sat": "Sob", + "clients.day_sun": "Niedz", + "clients.day_thu": "Czw", + "clients.day_tue": "Wt", + "clients.day_wed": "Śr", + "clients.delete_confirm": "Usunąć tego klienta z WireGuard? WGTools utworzy kopię i usunie powiązane reguły automatyczne.", + "clients.deleted": "Klient usunięty", + "clients.dns": "DNS (opcjonalnie)", + "clients.dns_hint": "Serwery DNS IPv4 rozdzielone przecinkami.", + "clients.download_config": "Pobierz .conf", + "clients.duplicate": "Duplikuj", + "clients.duplicate_address_error": "Ten adres VPN jest już używany przez innego peera.", + "clients.duplicate_name_error": "Peer o tej nazwie już istnieje.", + "clients.duplicate_ready": "Kopia gotowa. WGTools przydzielił nową nazwę i adres VPN. Sprawdź ustawienia przed zapisaniem.", + "clients.duplicate_site_hint": "Sieci zdalne wyczyszczono, aby uniknąć zduplikowanych tras. Podaj sieci dla nowego peera Site-to-site.", + "clients.duplicate_suffix": "kopia", + "clients.edit_subtitle": "Zaktualizuj peer na serwerze. Zmiany są stosowane bez restartu WireGuard.", + "clients.edit_title": "Edytuj klienta", + "clients.endpoint": "Endpoint serwera", + "clients.endpoint_hint": "Dla klientów zdalnych użyj publicznego IP lub domeny przekierowującej port WireGuard na ten serwer.", + "clients.existing": "Istniejący peer", + "clients.expiration": "Czas ważności dostępu", + "clients.expiration_action": "Po wygaśnięciu", + "clients.expiration_action_hint": "Jeśli opcja nie jest zaznaczona, klient zostanie w WGTools, ale utraci dostęp WireGuard. Ustaw nowy termin lub Bez terminu i zapisz, aby przywrócić dostęp.", + "clients.expiration_datetime": "Wygasa dnia", + "clients.expiration_datetime_hint": "Używa lokalnej daty i godziny przeglądarki.", + "clients.expiration_delete": "Usuń klienta", + "clients.expiration_future_required": "Wybierz przyszłą datę i godzinę.", + "clients.expiration_hint": "Po wygaśnięciu WGTools wykonuje wybraną akcję na początku następnej minuty. Najpierw tworzy kopię WireGuard.", + "clients.expire_1d": "1 dzień", + "clients.expire_1h": "1 godzina", + "clients.expire_3h": "3 godziny", + "clients.expire_6h": "6 godzin", + "clients.expire_custom": "Własna data i godzina", + "clients.expire_never": "Bez terminu wygaśnięcia", + "clients.expired": "Wygasło", + "clients.expired_disabled_hint": "Okres dostępu wygasł. Klient pozostał, ale dostęp WireGuard jest wyłączony. Ustaw nowy termin lub Bez terminu i zapisz.", + "clients.expired_disabled_short": "Wygasło · wyłączono", + "clients.expired_disabled_status": "Wygasło", + "clients.expires_days": "Wygasa za {n} dni", + "clients.expires_hours": "Wygasa za {n} godz.", + "clients.expires_minutes": "Wygasa za {n} min", + "clients.generated_config": "Wygenerowana konfiguracja klienta", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 sekund to dobry domyślny czas dla klientów za NAT.", + "clients.local_access_exceptions": "Dozwolone adresy lokalne", + "clients.local_access_exceptions_hint": "Opcjonalne adresy IP lub CIDR dostępne nawet wtedy, gdy ich sieć lokalna lub Site-to-site jest zablokowana. Oddziel przecinkami.", + "clients.managed": "Zarządzany przez WGTools", + "clients.name": "Nazwa", + "clients.no_peers": "Nie znaleziono peerów", + "clients.peers": "Peery", + "clients.peers_subtitle": "Zmiany są archiwizowane i stosowane przez wg syncconf bez restartu interfejsu WireGuard.", + "clients.protected_networks_reference": "Zablokowane sieci lokalne (informacja)", + "clients.protected_networks_reference_hint": "Te sieci nie są wpisywane do AllowedIPs. Dostęp blokują zasady serwera WGTools; poszczególne adresy można dopuścić powyżej.", + "clients.psk": "Klucz współdzielony (PSK)", + "clients.psk_enable": "Używaj dodatkowego klucza współdzielonego WireGuard", + "clients.psk_hint": "Zalecane. Dodaje dodatkowy sekret symetryczny do handshake WireGuard. Standardowe klienty go obsługują; WGTools dołącza PSK do konfiguracji i QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Generowanie kodu QR…", + "clients.quick_search": "Szybkie wyszukiwanie", + "clients.quick_search_clear": "Wyczyść wyszukiwanie", + "clients.quick_search_empty": "Brak pasujących klientów", + "clients.relay_endpoint_note": "Wygenerowana konfiguracja klienta połączy się z {endpoint}. Serwer WireGuard pozostaje na tym hoście WGTools.", + "clients.relay_required": "Wybierz VPS Relay dla tego klienta.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "niedostępny", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "Endpoint klienta jest generowany automatycznie na podstawie Relay.", + "clients.remote_hint": "Sieci za tym peerem. Jedna w wierszu lub rozdzielone przecinkami.", + "clients.remote_networks": "Sieci zdalne", + "clients.remote_required": "Podaj co najmniej jedną sieć zdalną dla peera Site-to-site.", + "clients.required": "Nazwa i adres VPN są wymagane.", + "clients.route_custom": "Własne", + "clients.route_full": "Pełny tunel", + "clients.route_full_except_local": "Pełny tunel bez sieci lokalnych", + "clients.route_hint": "Tylko te sieci zostaną wpisane do AllowedIPs konfiguracji klienta.", + "clients.route_preset": "Ruch przez VPN", + "clients.route_vpn": "Tylko sieć VPN", + "clients.route_vpn_lan": "VPN + lokalny LAN", + "clients.saved": "Klient zapisany", + "clients.schedule_blocked_short": "Harmonogram · blokada", + "clients.schedule_blocked_status": "Zablokowano przez harmonogram", + "clients.schedule_days": "Dozwolone dni", + "clients.schedule_days_required": "Wybierz co najmniej jeden dzień harmonogramu.", + "clients.schedule_disabled_hint": "Ten klient jest obecnie blokowany harmonogramem. WGTools automatycznie przywróci peera w następnym dozwolonym okresie.", + "clients.schedule_enable": "Ogranicz dostęp harmonogramem", + "clients.schedule_from": "Dostęp od", + "clients.schedule_hint": "WGTools może automatycznie wyłączać i przywracać klienta w wybrane dni i godziny bez zmiany konfiguracji.", + "clients.schedule_short": "Harmonogram", + "clients.schedule_time_required": "Ustaw godzinę początku i końca harmonogramu.", + "clients.schedule_timezone_hint": "Harmonogram używa lokalnego czasu serwera WireGuard. Obsługuje przedziały przez północ, np. 22:00–06:00.", + "clients.schedule_title": "Harmonogram dostępu", + "clients.schedule_to": "Dostęp do", + "clients.security_access": "Bezpieczeństwo i czas dostępu", + "clients.server_host": "Adres / domena serwera", + "clients.server_host_hint": "Publiczny IP lub domena używane przez klienta. Wcześniejsze wartości są proponowane.", + "clients.server_host_required": "Adres / domena serwera są wymagane do wygenerowania konfiguracji.", + "clients.server_peer": "Peer serwera", + "clients.server_port": "Port WireGuard", + "clients.server_port_hint": "Pobierany automatycznie z konfiguracji serwera.", + "clients.site_to_site": "Sieć do sieci", + "clients.status": "Status", + "clients.subtitle": "Peery WireGuard, stan na żywo i zarządzanie konfiguracjami klientów.", + "clients.tab_basic": "Podstawowe", + "clients.tab_config": "Konfiguracja", + "clients.tab_policy": "Zasady", + "clients.tab_security": "Bezpieczeństwo", + "clients.title": "Klienci", + "clients.type": "Typ", + "clients.unmanaged_note": "Peer istniał przed WGTools. Nie da się odzyskać jego klucza prywatnego. WGTools może edytować peera na serwerze, ale nie wygeneruje jego konfiguracji ani QR.", + "clients.updating": "Aktualizacja klienta…", + "common.actions": "Akcje", + "common.ago": "temu", + "common.cancel": "Anuluj", + "common.checking": "Sprawdzanie…", + "common.close": "Zamknij", + "common.config": "Konfiguracja", + "common.delete": "Usuń", + "common.disabled": "Wyłączone", + "common.edit": "Edytuj", + "common.enabled": "Włączone", + "common.loading": "Ładowanie…", + "common.never": "Nigdy", + "common.no": "Nie", + "common.not_configured": "Nie skonfigurowano", + "common.not_installed": "Nie zainstalowano", + "common.offline": "offline", + "common.online": "online", + "common.refresh": "Odśwież", + "common.running": "Działa", + "common.save": "Zapisz", + "common.stopped": "Zatrzymano", + "common.total": "Łącznie", + "common.unknown": "Nieznany", + "common.updated": "Zaktualizowano", + "common.yes": "Tak", + "dashboard.active_peers": "Aktywne peery", + "dashboard.active_peers_subtitle": "Dane na żywo z wg show.", + "dashboard.activity": "Przegląd systemu", + "dashboard.activity_subtitle": "Kontrole działającego WireGuard bez wprowadzania zmian.", + "dashboard.cores": "rdzenie", + "dashboard.cpu": "CPU", + "dashboard.history_24h": "Ostatnie 24 godz.", + "dashboard.history_avg": "Śr.", + "dashboard.history_max": "Maks.", + "dashboard.history_min": "Min.", + "dashboard.history_now": "teraz", + "dashboard.memory": "Pamięć", + "dashboard.network": "Sieć", + "dashboard.peers": "Peery", + "dashboard.quick_search": "Szybkie wyszukiwanie", + "dashboard.quick_search_clear": "Wyczyść wyszukiwanie", + "dashboard.quick_search_empty": "Brak peerów pasujących do wyszukiwania", + "dashboard.restart": "Uruchom ponownie", + "dashboard.restart_confirm": "Uruchomić WireGuard ponownie? Aktywni klienci VPN połączą się automatycznie.", + "dashboard.restart_ok": "WireGuard uruchomiono ponownie.", + "dashboard.routing": "Trasowanie", + "dashboard.site_to_site": "Sieć do sieci", + "dashboard.start": "Uruchom", + "dashboard.start_ok": "Uruchomiono WireGuard.", + "dashboard.stop": "Zatrzymaj", + "dashboard.stop_confirm": "Zatrzymać WireGuard? Aktywni klienci VPN zostaną rozłączeni.", + "dashboard.stop_ok": "Zatrzymano WireGuard.", + "dashboard.subtitle": "Stan serwera WireGuard, peery i ruch na żywo.", + "dashboard.title": "Pulpit", + "dashboard.traffic": "Ruch", + "dashboard.uptime": "Czas działania", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Zasady dostępu do serwera", + "groups.additional_allowed": "Dodatkowe dozwolone adresy", + "groups.additional_blocked": "Dodatkowe blokowane adresy", + "groups.allow": "Zezwól", + "groups.allowed": "Dozwolone", + "groups.allowed_addresses": "Dozwolone adresy / sieci", + "groups.apply_current_template": "Zastosuj bieżący szablon grupy", + "groups.apply_defaults": "Zastosuj bieżący szablon grupy", + "groups.apply_defaults_hint": "Kopiuje trasy, DNS i Keepalive z szablonu grupy do klienta. Zapisz klienta, a następnie wygeneruj nową konfigurację lub QR, jeśli urządzenie wymaga aktualizacji.", + "groups.basic": "Informacje podstawowe", + "groups.block": "Blokuj", + "groups.blocked": "Zablokowane", + "groups.blocked_addresses": "Zablokowane adresy / sieci", + "groups.client_config_source": "Źródło konfiguracji klienta", + "groups.client_defaults": "Domyślne ustawienia klienta", + "groups.client_group_hint": "Opcjonalna grupa do ponownego użycia zasad dostępu i ustawień klienta. Grupy dotyczą wybranego interfejsu WireGuard.", + "groups.config_differs": "Konfiguracja klienta różni się od bieżącego szablonu grupy. Zasady serwera są aktualne, ale urządzenie wymaga nowej konfiguracji lub kodu QR.", + "groups.config_differs_short": "Konfiguracja klienta różni się od grupy", + "groups.create": "Utwórz grupę", + "groups.create_title": "Utwórz grupę", + "groups.created": "Utworzono grupę", + "groups.creating": "Tworzenie grupy…", + "groups.defaults_applied": "Zastosowano szablon grupy. Zapisz klienta, aby zachować zmiany.", + "groups.defaults_hint": "Określa ruch wysyłany przez urządzenie przez WireGuard. Zasady serwera niezależnie decydują o dostępie. Zmiana szablonu nie zmienia automatycznie konfiguracji już zainstalowanych.", + "groups.delete_message": "Usunąć „{name}”? Konfiguracje klientów nie są usuwane wraz z grupą.", + "groups.delete_move": "Przenieś klientów do innej grupy", + "groups.delete_title": "Usuń grupę klientów", + "groups.delete_unassign": "Usuń przypisanie klientów do grupy", + "groups.deleted": "Usunięto grupę", + "groups.deleting": "Aktualizacja klientów i usuwanie grupy…", + "groups.description": "Opis", + "groups.edit_title": "Edytuj grupę", + "groups.editor_subtitle": "Grupa łączy aktywne zasady dostępu do serwera z szablonem konfiguracji klientów.", + "groups.effective_allow": "Dozwolone wyjątki", + "groups.effective_deny": "Zablokowane wyjątki", + "groups.effective_policy": "Obowiązujące zasady serwera", + "groups.empty": "Brak grup klientów. Utwórz grupę, aby ponownie wykorzystywać zasady dostępu i ustawienia.", + "groups.group": "Grupa", + "groups.inherit": "Dziedzicz", + "groups.internet_access": "Dostęp do Internetu", + "groups.internet_short": "Internet", + "groups.local_access": "Sieci lokalne", + "groups.local_short": "Lokalnie", + "groups.manage": "Grupy", + "groups.members_count": "Klienci: {count}", + "groups.name": "Nazwa", + "groups.name_required": "Nazwa grupy jest wymagana.", + "groups.new_client_defaults": "Szablon konfiguracji klienta", + "groups.new_clients_short": "Nowi klienci", + "groups.no_group": "Brak grupy", + "groups.none": "Brak", + "groups.override_client_config": "Nadpisz szablon grupy dla tego klienta", + "groups.override_client_config_hint": "Wyłączone: trasy, DNS i Keepalive pochodzą z grupy. Włączone: klient zachowuje własne wartości. Wyjątki zasad serwera działają niezależnie.", + "groups.policy_addresses_hint": "Adresy IPv4 lub CIDR rozdzielone przecinkami. Wyjątki klienta mają pierwszeństwo przed wyjątkami grupy.", + "groups.policy_custom": "Własne zasady", + "groups.policy_inherit": "Użyj zasad grupy", + "groups.policy_mode": "Źródło zasad", + "groups.policy_mode_hint": "Domyślnie dziedziczone są zasady grupy. Wyjątki klienta nigdy nie modyfikują grupy.", + "groups.routes_required": "Trasy klienta nie mogą być puste.", + "groups.subtitle": "Korzystaj ponownie z zasad dostępu i ustawień klientów na wybranym interfejsie WireGuard.", + "groups.title": "Grupy klientów", + "groups.traffic_through_vpn": "Ruch przez VPN", + "groups.updated": "Zaktualizowano grupę", + "groups.updating": "Aktualizacja zasad grupy…", + "help.example_note": "Wszystkie adresy, interfejsy, nazwy peerów i domeny w przykładach pomocy są fikcyjne. Zastąp je danymi swojej sieci.", + "help.navigation": "Nawigacja pomocy", + "help.open": "Otwórz pomoc", + "help.subtitle": "Przystępna pomoc dotycząca panelu, serwera, klientów i ustawień z krótkimi przykładami.", + "help.title": "Pomoc WGTools", + "interfaces.add": "+ Dodaj interfejs", + "interfaces.create": "Utwórz interfejs", + "interfaces.create_confirm": "Utworzyć i uruchomić interfejs {name}?", + "interfaces.create_failed": "Nie udało się utworzyć interfejsu", + "interfaces.create_hint": "Przed utworzeniem konfiguracji WGTools sprawdza, czy sieć VPN, port UDP i tablica routingu nie kolidują z innymi interfejsami WireGuard.", + "interfaces.create_subtitle": "Utwórz niezależny interfejs WireGuard z własną pulą adresów, portem UDP i ustawieniami routingu.", + "interfaces.create_title": "Dodaj interfejs WireGuard", + "interfaces.created": "Pomyślnie utworzono interfejs.", + "interfaces.creating": "Generowanie kluczy, zapisywanie konfiguracji i uruchamianie WireGuard…", + "interfaces.current": "Bieżący", + "interfaces.delete": "Usuń", + "interfaces.delete_confirm": "Usunąć interfejs {name}? Zostanie usunięta jego konfiguracja WireGuard oraz wszystkie peery. Najpierw powstanie kopia zapasowa.", + "interfaces.delete_failed": "Nie udało się usunąć interfejsu", + "interfaces.delete_last": "Nie można tutaj usunąć ostatniego skonfigurowanego interfejsu WireGuard.", + "interfaces.delete_tooltip": "Usuń ten interfejs WireGuard", + "interfaces.deleted": "Usunięto interfejs. Kopia: {backup}", + "interfaces.deleting": "Zatrzymywanie WireGuard i usuwanie interfejsu…", + "interfaces.display_name": "Nazwa wyświetlana", + "interfaces.display_name_edit_hint": "Tylko nazwa wyświetlana; nazwa interfejsu Linux nie zmieni się.", + "interfaces.display_name_hint": "Opcjonalna przyjazna nazwa, np. Praca lub Wykonawcy.", + "interfaces.identity": "Tożsamość interfejsu", + "interfaces.none": "Nie znaleziono interfejsów WireGuard", + "interfaces.none_configured": "Nie skonfigurowano jeszcze żadnego interfejsu WireGuard.", + "interfaces.peers_short": "peery", + "interfaces.rename_failed": "Nie udało się zapisać nazwy wyświetlanej interfejsu.", + "interfaces.select": "Wybierz", + "interfaces.subtitle": "Każdy interfejs ma własną sieć VPN, port, peery i reguły. Wybierz interfejs, aby zarządzać nim w WGTools.", + "interfaces.switch_title": "Interfejsy WireGuard", + "interfaces.system_name": "Nazwa systemowa", + "interfaces.system_name_hint": "Nazwa interfejsu Linux, np. wg1. Nie można jej zmienić po utworzeniu.", + "interfaces.title": "Interfejsy WireGuard", + "interfaces.unique_port_hint": "Każdy interfejs WireGuard na tym serwerze musi używać osobnego portu UDP.", + "interfaces.unique_table_hint": "WGTools zaleca osobną tablicę routingu dla każdego interfejsu. Pozostaw puste przy zwykłym routingu.", + "nav.clients": "Klienci", + "nav.dashboard": "Pulpit", + "nav.server": "Serwer", + "nav.settings": "Ustawienia", + "server.access_apply_confirm": "Zapisać i zastosować tę regułę zapory? WireGuard zostanie na krótko uruchomiony ponownie po wykonaniu kopii.", + "server.access_rule_deleted": "Usunięto regułę dostępu.", + "server.access_rule_help": "Utwórz regułę dostępu FORWARD bez ręcznej edycji poleceń iptables.", + "server.access_rule_order_hint": "WGTools wstawia reguły na początek łańcucha FORWARD, aby ograniczenia działały przed ogólnymi regułami VPN ACCEPT.", + "server.access_rule_saved": "Zapisano i zastosowano regułę dostępu.", + "server.action": "Akcja", + "server.action_hint": "REJECT informuje klienta o odmowie; DROP odrzuca bez odpowiedzi; ACCEPT jawnie zezwala.", + "server.add_access_rule": "Dodaj regułę dostępu", + "server.add_route": "Dodaj trasę", + "server.address": "Adres", + "server.any": "Dowolny", + "server.any_protocol": "Dowolny", + "server.apply_confirm": "Zapisać i zastosować ustawienia serwera? WireGuard zostanie na krótko uruchomiony ponownie. WGTools najpierw utworzy kopię i automatycznie przywróci konfigurację w razie błędu.", + "server.apply_settings": "Zapisz i zastosuj", + "server.applying_rule": "Tworzenie kopii i stosowanie zmian…", + "server.applying_settings": "Weryfikacja ustawień, tworzenie kopii i stosowanie zmian…", + "server.basic_settings": "Ustawienia podstawowe", + "server.config_tab_help": "Otwórz edytor źródłowej konfiguracji wybranego interfejsu WireGuard.", + "server.create_confirm": "Utworzyć i uruchomić serwer WireGuard z tymi ustawieniami?", + "server.create_server": "Utwórz serwer", + "server.create_step_conf": "Utwórz konfigurację wybranego interfejsu WireGuard z uprawnieniami 600.", + "server.create_step_forward": "Skonfiguruj forwarding, NAT i opcjonalny routing oparty na regułach.", + "server.create_step_key": "Wygeneruj nową parę kluczy serwera.", + "server.create_step_start": "Włącz i uruchom wybrany interfejs wg-quick.", + "server.create_subtitle": "WireGuard jest zainstalowany, ale wybrany interfejs nie jest skonfigurowany.", + "server.create_success": "Pomyślnie utworzono serwer WireGuard.", + "server.create_title": "Utwórz serwer WireGuard", + "server.creating": "Generowanie kluczy, zapisywanie konfiguracji i uruchamianie WireGuard…", + "server.custom_preserved": "Bloki peerów, trasy Site-to-site i niestandardowe reguły PostUp/PostDown poza tymi polami zostaną zachowane.", + "server.delete_access_confirm": "Usunąć tę regułę dostępu i zastosować zmianę?", + "server.delete_route_confirm": "Usunąć tę własną trasę i zastosować zmianę?", + "server.destination": "Cel", + "server.destination_hint": "Puste = dowolny. IP, CIDR lub zakres adresów. Oddziel wiele celów przecinkami.", + "server.destination_port": "Port docelowy", + "server.destination_port_hint": "Opcjonalnie. Port np. 443 lub zakres 10000:20000. Najpierw wybierz TCP lub UDP.", + "server.details": "Szczegóły", + "server.dev_word": "dev", + "server.diagnostics": "Diagnostyka", + "server.diagnostics_done": "Diagnostyka zakończona", + "server.diagnostics_subtitle": "Bieżące kontrole systemu. Konfiguracja nie jest zmieniana.", + "server.direction": "Hook", + "server.edit_access_rule": "Edytuj regułę dostępu", + "server.edit_route": "Edytuj trasę", + "server.edit_server": "Edytuj serwer", + "server.edit_subtitle": "Edytuj podstawowe ustawienia WireGuard, routingu i NAT. Istniejące peery i własne reguły zostają zachowane.", + "server.edit_title": "Ustawienia serwera", + "server.edit_warning": "Zastosowanie ustawień interfejsu, routingu lub zapory na krótko restartuje WireGuard. Aktywne peery połączą się ponownie.", + "server.enable_forwarding": "Włącz przekazywanie IPv4", + "server.enable_nat": "Włącz NAT / Masquerade", + "server.firewall": "Zapora i NAT", + "server.firewall_subtitle": "Reguły wykryte w hookach WireGuard.", + "server.firewall_subtitle_v08": "Reguły forwarding/NAT i dostępu z konfiguracji interfejsu. Proste reguły edytujesz tutaj, zaawansowane w edytorze źródłowym.", + "server.forward_from_vpn": "Zezwól na przekazywanie z VPN", + "server.forward_to_vpn": "Zezwól na przekazywanie do VPN", + "server.forwarding_section": "Przekazywanie i NAT", + "server.gateway": "Brama", + "server.gateway_hint": "Wymagana tylko przy korzystaniu z tablicy routingu regułowego.", + "server.install_success": "Pomyślnie zainstalowano WireGuard.", + "server.install_wireguard": "Zainstaluj WireGuard", + "server.install_wireguard_help": "Uruchamia apt update i instaluje WireGuard oraz wymagane narzędzia sieciowe.", + "server.install_wireguard_title": "Zainstaluj WireGuard", + "server.installing": "Instalowanie WireGuard… Może potrwać minutę.", + "server.interface": "Interfejs", + "server.interface_hint": "WGTools zarządza obecnie tym interfejsem.", + "server.interface_name": "Interfejs", + "server.interface_section": "Interfejs WireGuard", + "server.ip_forwarding": "Przekazywanie IPv4", + "server.kind": "Rodzaj", + "server.listen_port": "Port nasłuchiwania", + "server.local_network": "Sieć lokalna", + "server.local_network_hint": "Opcjonalna trasa dodawana do tablicy reguł routingu.", + "server.managed_automatically": "Zarządzane automatycznie", + "server.nat": "NAT / Masquerade", + "server.network": "Sieć", + "server.network_settings": "Sieć i NAT", + "server.no_firewall": "Nie znaleziono reguł zapory", + "server.no_routes": "Nie znaleziono tras", + "server.not_configured": "Nie skonfigurowano", + "server.not_set": "Nie ustawiono", + "server.policy_disabled_hint": "Wyłącz dla zwykłego routingu systemowego. Włącz tylko jeśli ten VPN wymaga osobnej tablicy routingu według źródła.", + "server.policy_enabled": "Włącz routing regułowy", + "server.policy_table": "Tablica reguł", + "server.policy_table_hint": "Dla zwykłego routingu pozostaw puste; np. 200 dla routingu według źródła.", + "server.port_word": "port", + "server.private_hidden": "Skonfigurowano (ukryto)", + "server.private_key": "Klucz prywatny", + "server.protocol": "Protokół", + "server.route_apply_confirm": "Zapisać i zastosować tę trasę? WireGuard zostanie na krótko uruchomiony ponownie po utworzeniu kopii.", + "server.route_custom": "Własna", + "server.route_deleted": "Usunięto trasę.", + "server.route_device_hint": "Opcjonalny interfejs wyjściowy, np. wg0 lub enp6s18.", + "server.route_editor_help": "Dodaj trasę instalowaną przy uruchomieniu WireGuard i usuwaną po zatrzymaniu.", + "server.route_gateway_hint": "Opcjonalna brama następnego skoku. Wymagana jest brama lub interfejs.", + "server.route_managed_peer": "Peer Site-to-site", + "server.route_managed_server": "Ustawienie serwera", + "server.route_network_hint": "Sieć IPv4, np. 10.20.0.0/24, lub 'default'.", + "server.route_saved": "Zapisano i zastosowano trasę.", + "server.route_table_hint": "Użyj 'main' dla zwykłego routingu albo numerycznej tablicy np. 200.", + "server.route_type": "Typ", + "server.routes": "Wykryte trasy", + "server.routes_subtitle": "Trasy z PostUp/PostDown i aktualnego stanu routingu regułowego.", + "server.routes_subtitle_v08": "Trasy serwera, Site-to-site i własne z wybranego interfejsu. Własne trasy można tu dodawać, edytować i usuwać.", + "server.routing": "Trasowanie", + "server.routing_section": "Trasowanie", + "server.rule": "Reguła", + "server.rule_access": "Reguła dostępu", + "server.rule_advanced": "Zaawansowane", + "server.rule_apply_warning": "Zastosowanie trasy lub reguły zapory na krótko restartuje WireGuard. WGTools tworzy kopię i przywraca konfigurację automatycznie w razie błędu.", + "server.rule_client_exception": "Wyjątek klienta", + "server.rule_client_policy": "Zasada klienta", + "server.rule_managed_server": "Ustawienie serwera", + "server.rule_type": "Typ", + "server.run_diagnostics": "Uruchom diagnostykę", + "server.save_apply": "Zapisz i zastosuj", + "server.save_config": "SaveConfig", + "server.server_address": "Adres VPN serwera", + "server.server_address_hint": "Zwykle pierwszy użyteczny adres w sieci VPN.", + "server.settings_applied": "Pomyślnie zapisano i zastosowano ustawienia serwera.", + "server.settings_apply_failed": "Nie udało się zastosować ustawień serwera", + "server.setup_required": "Wymagana konfiguracja", + "server.source": "Źródło", + "server.source_hint": "Puste = dowolny. IP, CIDR lub zakres np. 10.0.0.100-10.0.0.120.", + "server.subtitle": "Instalacja, pierwsza konfiguracja i bieżące ustawienia serwera WireGuard.", + "server.tab_config": "Konfiguracja", + "server.tab_interface": "Interfejs", + "server.tab_routing": "Trasowanie", + "server.tab_vps": "VPS", + "server.table": "Tabela", + "server.tabs_aria": "Sekcje ustawień serwera", + "server.title": "Serwer", + "server.uplink": "Interfejs uplink", + "server.use_raw_editor": "Użyj edytora źródłowego", + "server.via": "Przez / urządzenie", + "server.via_word": "via", + "server.vpn_network": "Sieć VPN", + "server.vpn_network_hint": "Adresy klientów będą później przydzielane z tej sieci.", + "server.vpn_pool": "Pula adresów VPN", + "server.wg_not_installed": "WireGuard nie jest zainstalowany", + "server.wg_not_installed_subtitle": "WGTools może automatycznie zainstalować wymagane pakiety Debiana.", + "server.what_happens": "Co zrobi WGTools", + "settings.about": "O programie", + "settings.add_user": "Dodaj użytkownika", + "settings.advanced": "Zaawansowane", + "settings.advanced_subtitle": "Bezpośredni dostęp do zaawansowanych narzędzi konfiguracji WireGuard.", + "settings.appearance": "Wygląd", + "settings.applying_config": "Weryfikacja konfiguracji, tworzenie kopii i stosowanie zmian…", + "settings.backup_count": "Zapisane kopie", + "settings.backup_retention": "Liczba kopii", + "settings.backup_retention_help": "Stare automatyczne kopie są usuwane po utworzeniu nowej. Od 1 do 200 plików.", + "settings.backups": "Kopie konfiguracji", + "settings.backups_always_on": "Włączone", + "settings.backups_subtitle": "WGTools tworzy automatyczne kopie przed operacjami zmieniającymi konfigurację. Nie można ich wyłączyć.", + "settings.change_password": "Zmień hasło", + "settings.check_updates": "Sprawdź aktualizacje", + "settings.config_applied": "Pomyślnie zapisano i zastosowano konfigurację.", + "settings.config_applied_restarted": "Zastosowano konfigurację i uruchomiono ponownie WireGuard.", + "settings.config_applied_stopped": "Zapisano konfigurację. WireGuard był zatrzymany i pozostał zatrzymany.", + "settings.config_apply_failed": "Nie udało się zastosować konfiguracji", + "settings.config_load_failed": "Nie udało się wczytać konfiguracji", + "settings.current_user": "Bieżący użytkownik", + "settings.current_version": "Bieżąca wersja", + "settings.audit_action": "Akcja", + "settings.audit_empty": "Brak zdarzeń audytu", + "settings.audit_log": "Dziennik audytu", + "settings.audit_log_subtitle": "Działania w panelu, logowanie, Telegram i historia połączeń klientów WireGuard. Sekrety nie są zapisywane.", + "settings.audit_object": "Obiekt", + "settings.audit_result": "Wynik", + "settings.audit_retention_note": "Przechowywanie: 30 dni", + "settings.audit_search": "Szybkie wyszukiwanie", + "settings.audit_search_clear": "Wyczyść wyszukiwanie", + "settings.audit_search_empty": "Brak zdarzeń audytu pasujących do wyszukiwania", + "settings.audit_time": "Data / godzina", + "settings.audit_user": "Użytkownik", + "audit.user.telegram_short": "TG", + "audit.action.access_rule.created": "Utworzono regułę dostępu", + "audit.action.access_rule.deleted": "Usunięto regułę dostępu", + "audit.action.access_rule.updated": "Zaktualizowano regułę dostępu", + "audit.action.auth.first_user_created": "Utworzono pierwszego użytkownika", + "audit.action.auth.login": "Zalogowano", + "audit.action.auth.login_failed": "Logowanie nie powiodło się", + "audit.action.auth.logout": "Wylogowano", + "audit.action.backup.full_created": "Utworzono pełną kopię zapasową", + "audit.action.backup.full_restored": "Przywrócono pełną kopię zapasową", + "audit.action.client.config_downloaded": "Pobrano konfigurację klienta", + "audit.action.client.config_viewed": "Wyświetlono konfigurację klienta", + "audit.action.client.created": "Utworzono klienta", + "audit.action.client.deleted": "Klient usunięty", + "audit.action.client.qr_viewed": "Wyświetlono kod QR klienta", + "audit.action.client.updated": "Zaktualizowano klienta", + "audit.action.client_group.created": "Utworzono grupę klientów", + "audit.action.client_group.deleted": "Usunięto grupę klientów", + "audit.action.client_group.updated": "Zaktualizowano grupę klientów", + "audit.action.interface.created": "Utworzono interfejs", + "audit.action.interface.deleted": "Usunięto interfejs", + "audit.action.interface.renamed": "Zmieniono nazwę interfejsu", + "audit.action.route.created": "Utworzono trasę", + "audit.action.route.deleted": "Usunięto trasę", + "audit.action.route.updated": "Zaktualizowano trasę", + "audit.action.server.created": "Utworzono serwer", + "audit.action.server.raw_config_applied": "Zastosowano konfigurację źródłową", + "audit.action.server.settings_applied": "Zastosowano ustawienia serwera", + "audit.action.settings.updated": "Zaktualizowano ustawienia panelu", + "audit.action.telegram.action_denied": "Odrzucono akcję Telegram", + "audit.action.telegram.action_failed": "Akcja Telegram nie powiodła się", + "audit.action.telegram.connection_test": "Test połączenia Telegram", + "audit.action.telegram.settings_updated": "Zaktualizowano ustawienia Telegram", + "audit.action.update.checked": "Sprawdzono aktualizację", + "audit.action.update.scheduled": "Zaplanowano aktualizację", + "audit.action.update.backup_created": "Kopia przed aktualizacją", + "audit.action.update.completed": "Zakończono aktualizację", + "audit.action.update.failed": "Aktualizacja nie powiodła się", + "audit.action.update.rollback_completed": "Przywrócono poprzednią wersję", + "audit.action.update.rollback_failed": "Nie udało się cofnąć aktualizacji", + "audit.action.user.created": "Utworzono użytkownika", + "audit.action.user.deleted": "Usunięto użytkownika", + "audit.action.user.password_changed": "Zmieniono hasło użytkownika", + "audit.action.vps.candidate_deleted": "Usunięto kandydata VPS", + "audit.action.vps.candidate_saved": "Zapisano kandydata VPS", + "audit.action.vps.detached": "Odłączono VPS Relay", + "audit.action.vps.relay_installed": "Zainstalowano VPS Relay", + "audit.action.wireguard.client_connected": "Połączono klienta WireGuard", + "audit.action.wireguard.installed": "Zainstalowano WireGuard", + "audit.action.wireguard.restarted": "Uruchomiono WireGuard ponownie", + "audit.action.wireguard.started": "Uruchomiono WireGuard", + "audit.action.wireguard.stopped": "Zatrzymano WireGuard", + "audit.result.applied": "zastosowano", + "audit.result.available": "dostępna", + "audit.result.changed": "zmieniono", + "audit.result.created": "utworzono", + "audit.result.current": "aktualna", + "audit.result.deleted": "usunięto", + "audit.result.detached": "odłączono", + "audit.result.denied": "odrzucono", + "audit.result.downloaded": "pobrano", + "audit.result.endpoint": "Punkt końcowy", + "audit.result.error": "Błąd", + "audit.result.installed": "zainstalowano", + "audit.result.invalid_credentials": "nieprawidłowe dane logowania", + "audit.result.ok": "OK", + "audit.result.queued": "w kolejce", + "audit.result.restarted": "uruchomiono ponownie", + "audit.result.restored": "przywrócono", + "audit.result.rotated": "odnowiono", + "audit.result.saved": "zapisano", + "audit.result.shown": "wyświetlono", + "audit.result.started": "uruchomiono", + "audit.result.stopped": "zatrzymano", + "audit.result.updated": "zaktualizowano", + "settings.delete_user": "Usuń", + "settings.delete_user_confirm": "Usunąć użytkownika {name}?", + "settings.edit_raw_config": "Edytuj konfigurację interfejsu", + "settings.expert_mode": "Ekspert", + "settings.full_backup_component_clients": "Metadane klientów WGTools, klucze prywatne, PSK, terminy ważności i grupy wymagane do odtworzenia konfiguracji oraz QR.", + "settings.full_backup_component_db": "Baza WGTools: użytkownicy, preferencje, poczta/SMTP, Telegram i zapisany stan VPS Relay.", + "settings.full_backup_component_relay": "Dane odzyskiwania VPS Relay: identyfikatory kontrolera i tenanta, token zarządzania oraz klucz transportowy Home. Po przywróceniu WGTools może odbudować lokalny transport i połączyć zachowany tenant.", + "settings.full_backup_component_system": "Plik sysctl przekazywania IPv4 WGTools, nazwy wyświetlane interfejsów oraz zasady i szablony grup, jeśli istnieją. Automatyczna historia konfiguracji interfejsów jest celowo pomijana.", + "settings.full_backup_component_wg": "Wszystkie wykryte konfiguracje interfejsów WireGuard z /etc/wireguard/ wraz ze stanem działania.", + "settings.full_backup_create_failed": "Nie udało się utworzyć pełnej kopii", + "settings.full_backup_creating": "Tworzenie pełnej kopii zapasowej…", + "settings.full_backup_download": "Utwórz", + "settings.full_backup_downloaded": "Kopia utworzona i pobrana. Przechowuj ją bezpiecznie.", + "settings.full_backup_downloaded_short": "Pobrano pełną kopię.", + "settings.full_backup_help": "Tworzy przenośną kopię WGTools do migracji lub odzyskiwania: konfiguracje WireGuard, użytkownicy, ustawienia, grupy, dane klientów i informacje potrzebne do ponownego połączenia tenantów VPS Relay.", + "settings.full_backup_no_file": "Nie wybrano kopii", + "settings.full_backup_restore": "Przywróć", + "settings.full_backup_restore_confirm": "Przywrócić pełną kopię WGTools? Użytkownicy, ustawienia, zarządzani klienci i konfiguracje WireGuard z kopii zostaną przywrócone. Interfejsy mogą zostać zrestartowane. WGTools najpierw utworzy kopię bezpieczeństwa i automatycznie cofnie zmiany w razie błędu.", + "settings.full_backup_restore_failed": "Przywracanie nie powiodło się", + "settings.full_backup_restored": "Pomyślnie przywrócono kopię. Zaloguj się kontem z przywróconej kopii.", + "settings.full_backup_restored_short": "Przywrócono kopię.", + "settings.full_backup_restoring": "Weryfikacja kopii, tworzenie zabezpieczenia i przywracanie…", + "settings.full_backup_secret_warning": "Plik zawiera dane poufne: klucze prywatne WireGuard i klientów, PSK, skróty haseł WGTools, token bota Telegram i zapisane hasło SMTP. Chroń go jak hasło i nigdy nie dołączaj do publicznych zgłoszeń ani czatów.", + "settings.full_backup_select": "Wybierz", + "settings.full_backup_title": "Pełna kopia i przywracanie", + "settings.full_mode": "Włączono zarządzanie serwerem i klientami", + "settings.interface_help": "Zarządzany interfejs WireGuard wybiera się podczas wdrożenia WGTools.", + "settings.language": "Język", + "settings.last_backup": "Ostatnia kopia", + "settings.latest_version": "Najnowsza wersja", + "settings.loading_config": "Wczytywanie konfiguracji…", + "settings.mode": "Tryb", + "settings.never_logged_in": "Nigdy", + "settings.new_password": "Nowe hasło", + "settings.no_backups": "Brak kopii zapasowych", + "settings.online_help": "Peer jest online, jeśli jego ostatni handshake jest młodszy niż ta wartość. 30–3600 sekund.", + "settings.online_threshold": "Próg online", + "settings.open_release": "Otwórz wydanie", + "settings.password_changed": "Zmieniono hasło.", + "settings.passwords_mismatch": "Hasła nie są zgodne.", + "settings.project_github": "Projekt / GitHub", + "settings.raw_config_confirm": "Zapisać i zastosować konfigurację WireGuard? Wybrany interfejs zostanie zrestartowany. Najpierw powstanie kopia; WGTools automatycznie przywróci poprzedni stan w razie błędu.", + "settings.raw_config_help": "Otwórz źródłową konfigurację wybranego interfejsu WireGuard.", + "settings.raw_config_title": "Źródłowa konfiguracja WireGuard", + "settings.raw_config_warning": "Tryb eksperta: to rzeczywista konfiguracja serwera WireGuard zawierająca klucz prywatny i PSK peerów. Zapisanie i zastosowanie restartuje interfejs. WGTools najpierw tworzy kopię i przywraca stan w razie błędu.", + "settings.readonly_mode": "Włączono zarządzanie klientami", + "settings.refresh_help": "Częstotliwość odświeżania stanu przez WGTools. Od 2 do 60 sekund.", + "settings.refresh_interval": "Interwał odświeżania", + "settings.release_notes": "Informacje o wydaniu", + "settings.reload_config": "Wczytaj ponownie z dysku", + "settings.save_apply": "Zapisz i zastosuj", + "settings.saved": "Zapisano ustawienia.", + "settings.saved_reload": "Zapisano ustawienia. Ponowne wczytywanie…", + "settings.saving": "Zapisywanie ustawień…", + "settings.status": "Odświeżanie statusu", + "settings.status_help": "Ustawienia odświeżania panelu i stanu peerów.", + "settings.subtitle": "Preferencje interfejsu i ustawienia stanu WGTools.", + "settings.syntax_hint": "Sekcje, klucze, wartości i komentarze WireGuard są podświetlane podczas edycji.", + "settings.tab_about": "O programie", + "settings.tab_backups": "Kopie zapasowe", + "settings.tab_general": "Ogólne", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Użytkownicy", + "settings.tabs_aria": "Sekcje ustawień", + "settings.telegram": "Bot Telegram", + "settings.telegram_allowed_ids": "Dozwolone identyfikatory użytkowników Telegram", + "settings.telegram_allowed_ids_help": "Jeden liczbowy identyfikator na wiersz. Nieautoryzowane /start odpowie identyfikatorem Telegram nadawcy, aby dodać go tutaj.", + "settings.telegram_bot_name": "Bot", + "settings.telegram_connected": "Połączono", + "settings.telegram_disabled": "Wyłączone", + "settings.telegram_dns": "Domyślny DNS klienta", + "settings.telegram_dns_help": "Opcjonalne adresy DNS IPv4 rozdzielone przecinkami. Dla klientów utworzonych przez bota.", + "settings.telegram_enabled": "Włącz bota Telegram", + "settings.telegram_endpoint": "Domyślny adres / domena serwera", + "settings.telegram_endpoint_help": "Używany przy tworzeniu klienta przez bota. Podaj tylko IP lub domenę; port WireGuard jest pobierany z konfiguracji serwera.", + "settings.telegram_language": "Język bota", + "settings.telegram_language_auto": "Automatycznie (język Telegram)", + "settings.telegram_last_poll": "Ostatni kontakt z Telegram", + "settings.telegram_not_configured": "Nie skonfigurowano", + "settings.telegram_remove_token": "Usuń token", + "settings.telegram_remove_token_confirm": "Usunąć zapisany token bota Telegram i wyłączyć bota?", + "settings.telegram_save": "Zapisz ustawienia Telegram", + "settings.telegram_saved": "Zapisano ustawienia Telegram.", + "settings.telegram_setup_note": "Utwórz bota w @BotFather, zapisz token, włącz bota i wyślij /start. Jeśli identyfikator nie jest autoryzowany, WGTools go pokaże — dodaj go do listy dozwolonych ID.", + "settings.telegram_status": "Status bota", + "settings.telegram_subtitle": "Zdalne zarządzanie WireGuard przez Telegram: stan serwera, klienci, tworzenie/usuwanie i start/restart/stop.", + "settings.telegram_test": "Testuj połączenie", + "settings.telegram_test_ok": "Połączenie Telegram działa: @{username}", + "settings.telegram_test_recent_ok": "Bot Telegram działa. Test bezpośredni przekroczył limit czasu, ale bot kontaktował się z Telegram niedawno.", + "settings.telegram_token": "Token bota", + "settings.telegram_token_help": "Utwórz bota w @BotFather i wklej tutaj token Bot API. API ID i API Hash nie są potrzebne.", + "settings.telegram_token_keep": "Pozostaw puste, aby zachować zapisany token.", + "settings.telegram_waiting": "Skonfigurowano, oczekiwanie na usługę bota", + "settings.theme": "Motyw", + "settings.theme_dark": "Ciemny", + "settings.theme_light": "Jasny", + "settings.theme_system": "System", + "settings.title": "Ustawienia", + "settings.update_available": "Dostępna aktualizacja", + "settings.update_backup_queued": "Aktualizacja w kolejce. WGTools przed instalacją wykona automatycznie pełną kopię…", + "settings.update_backup_running": "Tworzenie pełnej kopii przed aktualizacją…", + "settings.update_check_failed": "Nie udało się sprawdzić aktualizacji", + "settings.update_checking": "Sprawdzanie najnowszego wydania GitHub…", + "settings.update_confirm": "Zaktualizować WGTools z v{current} do v{latest}? Najpierw powstaną pełna kopia i kopia do wycofania zmian. Panel na chwilę uruchomi się ponownie.", + "settings.update_current": "Aktualna wersja", + "settings.update_downloading": "Pobieranie i weryfikowanie wydania GitHub…", + "settings.update_failed": "Aktualizacja WGTools nie powiodła się.", + "settings.update_installing": "Instalowanie aktualizacji. Panel może być przez chwilę niedostępny…", + "settings.update_no_update": "WGTools ma już najnowszą wersję.", + "settings.update_not_checked": "Nie sprawdzono", + "settings.update_queued": "Aktualizacja w kolejce. Oczekiwanie na usługę aktualizacji…", + "settings.update_rollback_ok": "Automatycznie przywrócono poprzednią wersję WGTools.", + "settings.update_rolling_back": "Aktualizacja nie powiodła się. Przywracanie poprzedniej wersji WGTools…", + "settings.update_running": "Tworzenie kopii bezpieczeństwa…", + "settings.update_safety_hint": "Aktualizacje są uruchamiane na życzenie. WGTools najpierw tworzy pełną kopię i kopię do wycofania. W razie błędu przywraca poprzednią aplikację. Sam WireGuard nie jest restartowany, chyba że nowe wydanie wyraźnie zmienia jego konfigurację.", + "settings.update_sidebar": "Dostępna nowa wersja", + "settings.update_sidebar_hint": "Ustawienia → Informacje", + "settings.update_starting": "Uruchamianie aktualizacji…", + "settings.update_status_unknown": "Stan aktualizacji niedostępny. Ponawianie…", + "settings.update_subtitle": "Wgraj zaufany pakiet wydania WGTools-Extended w formacie .bin.", + "settings.update_success": "Pomyślnie zaktualizowano WGTools do v{version}. Ponowne wczytywanie…", + "settings.update_wgtools": "Zaktualizuj WGTools", + "settings.user_actions": "Akcje", + "settings.user_created": "Utworzono", + "settings.user_created_ok": "Utworzono użytkownika.", + "settings.user_deleted": "Usunięto użytkownika.", + "settings.user_equal_rights": "Uprawnienia sieciowe są przypisywane przez administratora.", + "settings.user_last_login": "Ostatnie logowanie", + "settings.user_name": "Nazwa użytkownika", + "settings.users": "Użytkownicy", + "settings.users_subtitle": "Lokalne konta WGTools. E-mail jest opcjonalny i służy jedynie do odzyskiwania hasła po włączeniu poczty.", + "vps.add": "Dodaj VPS", + "vps.add_help": "WGTools używa SSH do sprawdzania lub instalacji Relay. Hasła i prywatne klucze SSH nigdy nie są zapisywane.", + "vps.add_title": "Dodaj VPS", + "vps.agent": "Agent Relay", + "vps.agent_found": "Już zainstalowany", + "vps.agent_will_install": "Zostanie zainstalowany", + "vps.arch": "Architektura", + "vps.auth_method": "Uwierzytelnianie", + "vps.authentication": "Uwierzytelnianie SSH", + "vps.check": "Sprawdź VPS", + "vps.check_failed": "Sprawdzanie VPS nie powiodło się", + "vps.check_link": "Sprawdź połączenie", + "vps.check_ok": "VPS zgodny", + "vps.checking": "Sprawdzanie dostępu SSH i zgodności VPS…", + "vps.connections": "połączenia", + "vps.credentials_not_saved": "Używane tylko do tej kontroli, nie są zapisywane przez WGTools.", + "vps.delete_candidate": "Usuń", + "vps.delete_installed": "Usuń VPS", + "vps.delete_installed_confirm": "Usunąć „{name}” z WGTools? Lokalny transport Relay zostanie rozłączony, ale agent i tenant na VPS pozostaną. Po ponownym dodaniu VPS WGTools połączy się z istniejącym Relay, zamiast tworzyć nowy. Klienci nie połączą się przez Relay do czasu ponownego podłączenia.", + "vps.delete_installed_failed": "Nie udało się usunąć VPS z WGTools", + "vps.delete_installed_ok": "Usunięto VPS z WGTools. Zdalny Relay zachowano i można go ponownie połączyć.", + "vps.empty_help": "Dodaj VPS Debian lub Ubuntu, aby sprawdzić SSH, zgodność systemu i wymagane porty UDP.", + "vps.empty_title": "Brak skonfigurowanego VPS", + "vps.endpoint": "Publiczny endpoint", + "vps.endpoint_domain": "Domena (zalecana)", + "vps.endpoint_domain_hint": "Przy późniejszej zmianie głównego VPS zmiana DNS pozwoli zachować dotychczasowe konfiguracje klientów.", + "vps.health_failed": "Sprawdzanie połączenia Relay nie powiodło się", + "vps.host": "IP / nazwa hosta", + "vps.host_key": "Klucz hosta SSH", + "vps.identity": "Połączenie VPS", + "vps.install_failed": "Instalacja Relay nie powiodła się", + "vps.install_ok": "Zainstalowano Relay i zweryfikowano chronione połączenie zarządzania", + "vps.install_relay": "Zainstaluj Relay", + "vps.install_title": "Zainstaluj VPS Relay", + "vps.installed": "Zainstalowano", + "vps.installing": "Instalowanie agenta Relay i zestawianie chronionego tunelu…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Hasło klucza", + "vps.link_ok": "Połączenie Relay OK", + "vps.multi_tenant_note": "Na tym VPS działa już agent WGTools Relay. Nie zostanie zastąpiony: ten WGTools otrzyma odizolowane połączenie z własnymi kluczami i portami UDP.", + "vps.name": "Nazwa", + "vps.no_domain": "Endpoint IP", + "vps.not_installed": "Zostanie zainstalowany", + "vps.os": "System operacyjny", + "vps.password": "Hasło", + "vps.phase_note": "Agent Relay obsługuje wiele niezależnych kontrolerów WGTools na jednym VPS. Każdy ma osobne połączenie, klucze i porty UDP; istniejące połączenia pozostają bez zmian.", + "vps.port_pair": "Porty UDP", + "vps.ports_adjusted": "wybrano wolne porty", + "vps.private_key": "Klucz prywatny", + "vps.privilege": "Uprawnienia", + "vps.public_endpoint": "Przyszły publiczny endpoint", + "vps.ready_help": "Dane SSH służą wyłącznie do sprawdzenia zgodności i natychmiastowej instalacji Relay; nie są zapisywane.", + "vps.reconnect_note": "Na VPS znaleziono istniejące połączenie Relay utworzone przez ten WGTools. Zostanie ponownie połączony ten sam tenant bez tworzenia nowego lub portów UDP.", + "vps.reconnect_ok": "Pomyślnie połączono z istniejącym Relay", + "vps.reconnect_relay": "Połącz Relay ponownie", + "vps.relay_port": "Port UDP Relay", + "vps.remove_confirm": "Usunąć tego kandydata VPS? Nie wprowadzono zmian na serwerze zdalnym.", + "vps.save_candidate": "Zapisz kandydata", + "vps.saved": "Zapisano kandydata VPS", + "vps.ssh": "SSH", + "vps.ssh_key": "Klucz SSH", + "vps.ssh_port": "Port SSH", + "vps.ssh_user": "Użytkownik SSH", + "vps.status_candidate": "Gotowy do instalacji", + "vps.status_installed": "Relay połączony", + "vps.subtitle": "Przygotuj publiczny VPS do zdalnego dostępu, gdy ten serwer WGTools nie ma publicznego IP.", + "vps.tenant": "Połączenie", + "vps.title": "VPS Relay", + "vps.transport_port": "Port UDP transportu", + "vps.transport_port_hint": "Osobny port UDP dla prywatnego tunelu transportowego Dom ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Zapisano", + "vps.active_short": "Aktywny", + "dashboard.traffic_reset": "Resetuj", + "dashboard.traffic_reset_confirm": "Zresetować liczniki ruchu WireGuard tego interfejsu? Liczniki klientów również zaczną od zera.", + "dashboard.traffic_reset_done": "Zresetowano liczniki ruchu", + "dashboard.traffic_reset_failed": "Nie udało się zresetować liczników ruchu", + "audit.action.traffic.reset": "Zresetowano liczniki ruchu", + "audit.result.reset": "zresetowano", + "server.mtu": "MTU", + "server.mtu_auto": "Automatycznie", + "server.mtu_hint": "Opcjonalnie. Pozostaw puste dla automatycznego MTU wg-quick. Ustaw np. 1380 lub 1420 tylko gdy wymaga tego LTE lub PPPoE.", + "clients.peer_isolation": "Izolacja klientów VPN", + "clients.peer_isolation_enable": "Izoluj od innych klientów VPN", + "clients.peer_isolation_hint": "Blokuje ruch między tym klientem a innymi adresami puli WireGuard. Dostęp do serwera, Internetu i sieci lokalnych lub Site-to-site nadal zależy od pozostałych zasad.", + "clients.credentials_rotate": "Klucze klienta", + "clients.credentials_rotate_button": "Odnów klucze", + "clients.credentials_rotate_confirm": "Wygenerować nowe klucze klienta? Jeśli jest połączony, jego sesja WireGuard zostanie natychmiast przerwana. Następnie wyślij nową konfigurację lub QR.", + "clients.credentials_rotate_confirm_psk": "Wygenerować nową parę kluczy i PSK? Aktywna sesja WireGuard klienta zostanie natychmiast przerwana. Następnie wyślij nową konfigurację lub QR.", + "clients.credentials_rotate_hint": "Odnawia PrivateKey/PublicKey, a przy włączonym PSK również PSK. Adres, trasy, grupa, harmonogram, izolacja i statystyki pozostają bez zmian.", + "clients.credentials_rotating": "Generowanie nowych kluczy i rozłączanie starej sesji…", + "clients.credentials_rotated": "Zmieniono klucze klienta. Aktywną sesję rozłączono. Stara konfiguracja już nie działa; przed ponownym połączeniem prześlij nową lub kod QR.", + "clients.credentials_rotated_short": "Klucze zmienione — wymagana nowa konfiguracja", + "audit.action.client.credentials_rotated": "Odnowiono klucze klienta", + "clients.credentials_connection_lost": "Przerwano połączenie z WGTools. Jeśli panel otwarto przez klienta, którego klucze odnowiono, to normalne: stara sesja WireGuard została od razu rozłączona. Połącz się inną drogą i wygeneruj nową konfigurację lub QR.", + "nav.navigation": "Nawigacja główna", + "nav.project_github": "WGTools na GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Na razie opcjonalny. Po skonfigurowaniu poczty może służyć do odzyskiwania hasła.", + "auth.forgot_password": "Nie pamiętasz hasła?", + "auth.reset_title": "Zresetuj hasło", + "auth.reset_subtitle": "Odbierz jednorazowy kod e-mailem i ustaw nowe hasło WGTools.", + "auth.reset_identifier": "Nazwa użytkownika lub e-mail", + "auth.reset_identifier_help": "Dla ochrony prywatności WGTools zawsze pokazuje tę samą odpowiedź niezależnie od istnienia konta.", + "auth.send_reset_code": "Wyślij kod", + "auth.reset_code_sent_generic": "Jeśli konto istnieje i ma adres e-mail, wysłano kod resetowania ważny przez 15 minut.", + "auth.reset_code": "Kod 6-cyfrowy", + "auth.set_new_password": "Ustaw nowe hasło", + "auth.request_another_code": "Poproś o nowy kod", + "auth.back_to_login": "Wróć do logowania", + "auth.reset_not_configured": "Odzyskiwanie hasła e-mailem nie jest skonfigurowane. Skontaktuj się z administratorem WGTools.", + "settings.tab_mail": "Poczta", + "settings.mail": "Poczta / SMTP", + "settings.mail_subtitle": "SMTP służy do odzyskiwania hasła.", + "settings.mail_not_configured": "Nie skonfigurowano", + "settings.mail_enabled": "Włącz pocztę i odzyskiwanie hasła", + "settings.mail_smtp_host": "Serwer SMTP", + "settings.mail_smtp_port": "Port SMTP", + "settings.mail_security": "Szyfrowanie", + "settings.mail_security_none": "Bez szyfrowania", + "settings.mail_username": "Użytkownik SMTP", + "settings.mail_username_help": "Używane do logowania SMTP i jako adres e-mail nadawcy.", + "settings.mail_password": "Hasło SMTP", + "settings.mail_password_keep": "Pozostaw puste, aby zachować zapisane hasło.", + "settings.mail_from_email": "E-mail nadawcy", + "settings.mail_from_name": "Nazwa nadawcy", + "settings.mail_test_recipient": "Odbiorca testowy", + "settings.mail_test_recipient_help": "Test używa aktualnie zapisanych ustawień SMTP.", + "settings.mail_remove_password": "Usuń hasło", + "settings.mail_test": "Wyślij test", + "settings.mail_save": "Zapisz ustawienia poczty", + "settings.mail_enabled_badge": "Włączone", + "settings.mail_disabled_badge": "Wyłączone", + "settings.mail_saved": "Zapisano ustawienia poczty.", + "settings.mail_remove_password_confirm": "Usunąć zapisane hasło SMTP i wyłączyć pocztę?", + "settings.mail_password_removed": "Usunięto hasło SMTP i wyłączono pocztę.", + "settings.mail_test_recipient_required": "Podaj adres e-mail odbiorcy testowego.", + "settings.mail_testing": "Wysyłanie testowego e-maila…", + "settings.mail_test_ok": "Pomyślnie wysłano testowy e-mail.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Opcjonalny. Wymagany tylko do samodzielnego odzyskiwania hasła.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "Zapisano e-mail.", + "settings.send_password_reset": "Wyślij reset", + "settings.user_reset_mail_not_configured": "Najpierw skonfiguruj i włącz pocztę.", + "settings.user_reset_email_missing": "Najpierw dodaj adres e-mail.", + "settings.user_reset_confirm": "Wysłać kod resetowania hasła do {name} na {email}?", + "settings.user_reset_sent": "Wysłano kod resetowania hasła na {email}.", + "audit.action.auth.password_reset_requested": "Zażądano resetowania hasła", + "audit.action.auth.password_reset_code_sent": "Wysłano kod resetowania hasła", + "audit.action.auth.password_reset_completed": "Zresetowano hasło", + "audit.action.auth.password_reset_failed": "Resetowanie hasła nie powiodło się", + "audit.action.mail.settings_updated": "Zaktualizowano ustawienia poczty", + "audit.action.mail.test_sent": "Wysłano testowy e-mail", + "audit.action.mail.test_failed": "Nie udało się wysłać testowego e-maila", + "audit.action.user.email_changed": "Zmieniono e-mail użytkownika", + "audit.action.user.password_reset_sent": "Wysłano resetowanie hasła użytkownika", + "audit.action.user.password_reset_failed": "Resetowanie hasła użytkownika nie powiodło się", + "audit.result.accepted": "zaakceptowano", + "audit.result.sent": "wysłano", + "audit.result.invalid_code": "nieprawidłowy kod", + "common.copy": "Kopiuj", + "common.copied": "Skopiowano", + "clients.use_panel_host": "Użyj adresu panelu", + "clients.use_panel_host_done": "Wstawiono adres panelu: {host}", + "clients.use_panel_host_failed": "Nie udało się ustalić adresu panelu z URL przeglądarki.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Wbudowany HTTPS Let’s Encrypt do bezpośredniego dostępu do WGTools bez reverse proxy.", + "settings.https_disabled": "Wyłączone", + "settings.https_enabled": "Włączone", + "settings.https_enable": "Włącz wbudowany HTTPS", + "settings.https_type": "Certyfikat dla", + "settings.https_domain": "Domena", + "settings.https_public_ip": "Publiczny IP", + "settings.https_target": "Domena lub publiczny IP", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "Port HTTPS", + "settings.https_port80_note": "Port TCP 80 musi być dostępny z Internetu do wydania i odnawiania certyfikatu. Otwórz też wybrany port HTTPS panelu.", + "settings.https_check_ports": "Sprawdź porty", + "settings.https_certificate": "Certyfikat", + "settings.https_certificate_ready": "Gotowy", + "settings.https_certificate_missing": "Nie wydano", + "settings.https_expires": "Ważny do", + "settings.https_renewal": "Automatyczne odnawianie", + "settings.https_renewal_enabled": "Włączone", + "settings.https_renewal_disabled": "Wyłączone", + "settings.https_certificate_path": "Certyfikat", + "settings.https_private_key_path": "Klucz prywatny", + "settings.https_issue": "Uzyskaj / odnów certyfikat", + "settings.https_port_free": "Wolny", + "settings.https_port_busy": "Zajęty", + "settings.https_ports_checked": "Zakończono sprawdzanie portów.", + "settings.https_target_email_required": "Podaj domenę/publiczny IP i e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Uzyskać lub odnowić certyfikat Let’s Encrypt dla {target}? Ustawienia HTTPS zostaną zapisane. Port TCP 80 musi być dostępny z Internetu.", + "settings.https_issuing": "Pobieranie certyfikatu z Let’s Encrypt…", + "settings.https_issue_ok": "Certyfikat gotowy.", + "settings.https_already_enabled": "Wbudowany HTTPS jest już włączony.", + "settings.https_already_disabled": "Wbudowany HTTPS jest już wyłączony.", + "settings.https_enable_confirm": "Włączyć wbudowany HTTPS na TCP {port} ze ścieżką {path}? WGTools uruchomi się ponownie, a strona połączy z nowym adresem.", + "settings.https_disable_confirm": "Wyłączyć wbudowany HTTPS i wrócić do HTTP?", + "settings.https_switching": "Włączanie HTTPS i ponowne uruchamianie WGTools…", + "settings.https_switching_http": "Wyłączanie HTTPS i ponowne uruchamianie WGTools…", + "audit.action.https.certificate_issued": "Wydano certyfikat HTTPS", + "audit.action.https.certificate_failed": "Nie udało się uzyskać certyfikatu HTTPS", + "audit.action.https.enabled": "Włączono HTTPS", + "audit.action.https.disabled": "Wyłączono HTTPS", + "audit.result.issued": "wydano", + "audit.result.enabled": "włączono", + "audit.result.disabled": "wyłączono", + "settings.https_access_path": "Ścieżka dostępu do panelu", + "settings.https_access_path_help": "Wybierz własną ścieżkę. Przy wbudowanym HTTPS żądania poza nią zwracają 404.", + "settings.https_enable_fields_required": "Podaj domenę/publiczny IP, e-mail Let’s Encrypt i ścieżkę panelu.", + "settings.https_use_panel_host": "Użyj adresu panelu", + "settings.https_reconnecting": "WGTools przełącza się na nowy adres HTTPS…", + "server.tab_nodes": "Węzły", + "common.type": "Typ", + "common.status": "Status", + "common.copy_failed": "Nie udało się skopiować", + "clients.vpn_address": "Adres VPN", + "nodes.title": "Węzły WGTools", + "nodes.subtitle": "Połącz serwery WGTools w jedną chronioną sieć i publikuj tylko sieci dostępne dla innych węzłów.", + "nodes.enable_hub": "Włącz HUB", + "nodes.connect_hub": "Połącz z HUB", + "nodes.settings": "Ustawienia węzła", + "nodes.settings_action": "Ustawienia", + "nodes.sync_now": "Synchronizuj", + "nodes.disable": "Wyłącz węzły", + "nodes.disable_action": "Rozłącz", + "nodes.join_title": "Połącz nowe węzły", + "nodes.join_help": "Utwórz jednorazowy kod i wpisz go w drugim panelu WGTools wraz z endpointem usługi HUB, np. vpn.example.com:51950. Kod jest ważny 15 minut i można go użyć tylko raz.", + "nodes.create_code": "Utwórz kod", + "nodes.connected_nodes": "Połączone węzły", + "nodes.connected_nodes_help": "Informacje o innych panelach, publikowanych sieciach i klientach. Klienci zdalni są tylko do odczytu.", + "nodes.enable_hub_help": "Ten panel stanie się węzłem centralnym. Na tym samym porcie HUB odbiera WireGuard przez UDP i chronione pierwsze parowanie przez TCP.", + "nodes.node_name": "Nazwa węzła", + "nodes.transport_network": "Sieć transportowa węzłów", + "nodes.transport_help": "Osobna sieć prywatna tylko do komunikacji WGTools ↔ WGTools. Nie może pokrywać się z sieciami VPN/LAN.", + "nodes.panel_url": "URL panelu", + "nodes.panel_url_help": "Opcjonalnie. To tylko link dla przycisku „Otwórz panel” na innych węzłach; nie służy do łączenia Nodes.", + "nodes.extra_networks": "Dodatkowe sieci węzła", + "nodes.extra_networks_help": "Jedna sieć w wierszu. Sieci VPN interfejsów i zdalne sieci Site-to-site są publikowane automatycznie. Dodaj tylko inne routowane sieci LAN, np. 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools uzupełnia wykryte sieci VPN, Site-to-site i routowane LAN. Pozostaw tylko sieci przeznaczone do publikacji. Jedna na wiersz.", + "nodes.published_networks_settings_help": "Jedna sieć na wiersz. To jawna lista sieci publikowanych przez węzeł. Usunięcie wiersza zatrzymuje ogłaszanie sieci innym węzłom.", + "nodes.available_networks_help": "Wykryte sieci: {networks}. Nowe sieci nie są publikowane automatycznie; dodaj potrzebne powyżej.", + "nodes.available_networks_none": "Nie wykryto dodatkowych sieci lokalnych.", + "nodes.connect_help": "Podaj endpoint usługi HUB i kod jednorazowy. URL panelu, port HTTPS, certyfikat i prywatna ścieżka nie są używane do parowania Nodes.", + "nodes.join_code": "Kod połączenia", + "nodes.connect_reachability_note": "Pierwsze parowanie korzysta z chronionego TCP na podanym porcie. Po utworzeniu wgnode0 sieci, stan, wersje i dane klientów tylko do odczytu synchronizują się z HUB przez wewnętrzny adres WireGuard.", + "nodes.connect": "Połącz", + "nodes.settings_help": "Nazwa węzła, opcjonalny link „Otwórz panel” i lista publikowanych sieci. URL panelu nie służy do parowania ani synchronizacji.", + "nodes.details": "Szczegóły", + "nodes.not_configured": "WGTools Nodes nieskonfigurowane", + "nodes.not_configured_help": "Włącz HUB w tym panelu lub połącz go z istniejącym WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Połączono z HUB", + "nodes.mode_none": "Nie skonfigurowano", + "nodes.role": "Rola", + "nodes.tunnel": "Tunel węzła", + "nodes.node_ip": "Adres węzła", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Publikowane sieci", + "nodes.last_sync": "Ostatnia synchronizacja", + "nodes.no_nodes_hub": "Nie połączono jeszcze węzłów. Utwórz kod i użyj go w innym panelu WGTools.", + "nodes.no_nodes_spoke": "Nie otrzymano jeszcze informacji o zdalnych węzłach.", + "nodes.clients_short": "Klienci", + "nodes.open_panel": "Otwórz panel", + "nodes.route_conflict": "Konflikt tras", + "nodes.no_published_networks": "Brak publikowanych sieci", + "nodes.load_failed": "Nie udało się wczytać WGTools Nodes", + "nodes.enable_hub_confirm": "Włączyć WGTools HUB i utworzyć wewnętrzny tunel WireGuard Nodes?", + "nodes.applying": "Konfigurowanie tunelu WGTools Nodes…", + "nodes.enable_failed": "Nie udało się włączyć HUB", + "nodes.hub_enabled": "Włączono WGTools HUB", + "nodes.connecting": "Weryfikacja kodu HUB i tworzenie chronionego tunelu…", + "nodes.connect_failed": "Nie udało się połączyć z HUB", + "nodes.connected": "Połączono z WGTools HUB", + "nodes.settings_failed": "Nie udało się zapisać ustawień węzła", + "nodes.settings_saved": "Zapisano ustawienia węzła", + "nodes.code_failed": "Nie udało się utworzyć kodu połączenia", + "nodes.code_expires": "Kod jednorazowy. Ważny do {time}.", + "nodes.code_copied": "Skopiowano kod połączenia", + "nodes.network_vpn": "Klienci VPN", + "nodes.network_site_to_site": "Sieć Site-to-site", + "nodes.network_custom": "Dodatkowa sieć", + "nodes.conflict": "Konflikt", + "nodes.remote_clients": "Klienci (tylko odczyt)", + "nodes.no_clients": "Ten węzeł nie zgłasza klientów", + "nodes.details_failed": "Nie udało się pobrać szczegółów węzła", + "nodes.remove_confirm": "Usunąć węzeł „{name}” z HUB? Dostęp do wewnętrznego tunelu zostanie cofnięty.", + "nodes.remove_failed": "Nie udało się usunąć węzła", + "nodes.removed": "Usunięto węzeł", + "nodes.disable_hub_confirm": "Wyłączyć HUB i rozłączyć wszystkie węzły WGTools? Wewnętrzny tunel zostanie usunięty.", + "nodes.disconnect_confirm": "Odłączyć ten panel WGTools od HUB i usunąć wewnętrzny tunel węzła?", + "nodes.disable_failed": "Nie udało się wyłączyć WGTools Nodes", + "nodes.disabled": "Wyłączono WGTools Nodes", + "nodes.sync_failed": "Synchronizacja węzłów nie powiodła się", + "nodes.synced": "Zsynchronizowano informacje węzłów", + "nodes.service_port": "Port Nodes", + "nodes.service_port_help": "Ten sam numer portu służy równocześnie: UDP dla WireGuard i TCP do chronionego parowania.", + "nodes.hub_port_forward_note": "Jeśli HUB jest za NAT, przekieruj ten sam port UDP i TCP. Port web WGTools, HTTPS i prywatna ścieżka panelu nie są powiązane z Nodes.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Domena/IP i port Nodes bez http:// lub https://, np. vpn.example.com:51950.", + "settings.collapse_sidebar": "Zwiń pasek boczny", + "settings.expand_sidebar": "Rozwiń panel boczny", + "settings.https_issue_fields_required": "Podaj domenę/publiczny IP, e-mail Let’s Encrypt i ścieżkę panelu.", + "settings.https_issue_ok_saved": "Certyfikat gotowy i ustawienia HTTPS zapisane.", + "settings.https_enable_need_certificate": "Najpierw uzyskaj certyfikat.", + "settings.https_enable_certificate_mismatch": "Najpierw uzyskaj certyfikat dla bieżącej domeny lub IP.", + "settings.https_enable_certificate_expired": "Certyfikat wygasł. Odnów go przed włączeniem HTTPS.", + "settings.https_enable_certificate_ready": "Certyfikat gotowy — można włączyć wbudowany HTTPS.", + "settings.https_enable_active_help": "Odznacz i zapisz, aby wrócić do HTTP.", + "settings.https_certificate_expired": "Wygasł", + "settings.https_certificate_wrong_target": "Dla innego adresu", + "nodes.network_conflict_error": "Publikowane sieci kolidują z innym węzłem lub siecią transportową Nodes: {conflicts}. Usuń lub zmień kolidującą sieć.", + "nodes.networks_changed": "Wykryte sieci zmieniły się od ostatniego zapisu. Nowe: {added}. Niewykrywane: {removed}. Sprawdź listę publikowanych sieci i zapisz ustawienia.", + "nodes.review_networks": "Sprawdź sieci", + "nodes.vpn_pool_mismatch": "Pula VPN zmieniła się: Nodes nadal publikuje {old}, a aktualna pula to {current}. Otwórz ustawienia węzła i zaktualizuj publikowane sieci.", + "server.error_vpn_network_invalid": "Sieć VPN musi być prawidłową siecią IPv4, np. 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Obsługiwane są tylko sieci VPN IPv4.", + "server.error_vpn_network_too_small": "Sieć VPN musi zawierać co najmniej dwa użyteczne adresy.", + "server.error_vpn_network_no_hosts": "Wybrana sieć VPN nie ma użytecznych adresów serwera.", + "server.error_server_address_prefix": "Adres VPN serwera musi zawierać prefiks, np. 10.0.0.1/24.", + "server.error_server_address_network": "Adres VPN serwera musi należeć do wybranej puli i mieć ten sam prefiks.", + "server.error_server_address_reserved": "Adres VPN serwera nie może być adresem sieci ani adresem rozgłoszeniowym.", + "server.error_listen_port_number": "Port WireGuard musi być liczbą.", + "server.error_listen_port_range": "Port WireGuard musi mieścić się w zakresie 1–65535.", + "server.error_mtu_number": "MTU musi być liczbą.", + "auth.mfa_title": "Uwierzytelnianie dwuskładnikowe", + "auth.mfa_login_help": "Wprowadź 6-cyfrowy kod z Google Authenticator lub jeden z kodów odzyskiwania.", + "auth.mfa_code": "Kod uwierzytelniania", + "auth.mfa_verify": "Zweryfikuj i zaloguj", + "auth.mfa_back": "Wróć do hasła", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Uwierzytelnianie dwuskładnikowe (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Włączone", + "settings.mfa_disabled": "Wyłączone", + "settings.mfa_google_help": "Chroń konto przez Google Authenticator lub inną aplikację TOTP. Aby zacząć, podaj bieżące hasło.", + "settings.current_password": "Bieżące hasło", + "settings.mfa_start": "Skonfiguruj Google Authenticator", + "settings.mfa_secret": "Ręczny klucz konfiguracji", + "settings.mfa_scan_help": "Zeskanuj QR w Google Authenticator i wpisz aktualny 6-cyfrowy kod, aby włączyć MFA.", + "settings.mfa_code": "Kod 6-cyfrowy", + "settings.mfa_enable": "Włącz MFA", + "settings.mfa_manage_help": "Aby zmienić MFA, podaj bieżące hasło oraz kod Authenticator lub kod odzyskiwania.", + "settings.mfa_code_or_recovery": "Kod Authenticator lub odzyskiwania", + "settings.mfa_regenerate": "Nowe kody odzyskiwania", + "settings.mfa_disable": "Wyłącz MFA", + "settings.mfa_recovery_title": "Kody odzyskiwania", + "settings.mfa_recovery_help": "Zapisz te kody teraz. Każdego można użyć raz, gdy Google Authenticator jest niedostępny. Nie zostaną ponownie pokazane.", + "settings.mfa_recovery_remaining": "Pozostałe kody odzyskiwania: {count}", + "settings.mfa_enabled_ok": "Włączono MFA.", + "settings.mfa_disabled_ok": "Wyłączono MFA.", + "settings.mfa_disable_confirm": "Wyłączyć uwierzytelnianie dwuskładnikowe dla tego konta?", + "settings.mfa_regenerate_confirm": "Zastąpić wszystkie istniejące kody odzyskiwania?", + "settings.mfa_recovery_regenerated": "Utworzono nowe kody odzyskiwania.", + "audit.action.auth.mfa_failed": "Weryfikacja MFA nie powiodła się", + "audit.action.auth.mfa_recovery_used": "Użyto kodu odzyskiwania MFA", + "audit.action.user.mfa_setup_started": "Rozpoczęto konfigurację MFA", + "audit.action.user.mfa_enabled": "Włączono MFA", + "audit.action.user.mfa_disabled": "Wyłączono MFA", + "audit.action.user.mfa_disabled_cli": "Wyłączono MFA przez CLI", + "audit.action.user.mfa_recovery_regenerated": "Wygenerowano ponownie kody odzyskiwania MFA", + "settings.mfa_error_password": "Nieprawidłowe bieżące hasło.", + "settings.mfa_error_code": "Nieprawidłowy kod uwierzytelniania.", + "settings.mfa_error_already_enabled": "MFA jest już włączone.", + "settings.mfa_error_not_enabled": "MFA nie jest włączone.", + "settings.mfa_error_not_started": "Rozpocznij konfigurację MFA ponownie.", + "trace.title": "Traceroute, ping i mapa trasy", + "trace.subtitle": "Zmierz opóźnienie do VPS lub innego serwera i sprawdź, gdzie rośnie na trasie.", + "trace.target": "IP lub nazwa hosta serwera", + "trace.show_map": "Pokaż trasę na mapie", + "trace.run": "Uruchom traceroute", + "trace.geo_note": "Geolokalizacja jest przybliżona. Po włączeniu mapy publiczne IP przeskoków są wysyłane do ipwho.is, a kafelki mapy pobierane z OpenStreetMap.", + "trace.latency_note": "Traceroute mierzy opóźnienia w milisekundach, a nie przepustowość w Mbit/s.", + "trace.map": "Mapa trasy", + "trace.map_hint": "Mapa interaktywna: przeciągnij, aby przesunąć; użyj kółka myszy lub +/− do powiększenia; kliknij przeskok po szczegóły.", + "trace.hop": "Przeskok / IP", + "trace.location": "Lokalizacja", + "trace.avg_rtt": "Śr. RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Straty", + "trace.summary_target": "Cel", + "trace.summary_ping": "Średni ping", + "trace.summary_loss": "Straty ping", + "trace.summary_hops": "Przeskoki", + "trace.no_reply": "Brak odpowiedzi", + "trace.private": "Sieć prywatna", + "trace.unknown": "Nieznany", + "trace.running": "Trwa ping i traceroute… Może to potrwać do minuty.", + "trace.done": "Zakończono śledzenie trasy.", + "trace.failed": "Śledzenie trasy nie powiodło się", + "trace.partial_geo": "Nie udało się ustalić lokalizacji części publicznych przeskoków.", + "trace.not_reached": "Traceroute nie dotarł do celu.", + "trace.reached": "Osiągnięto cel", + "trace.ms": "ms", + "server.tab_trace": "Śledzenie trasy", + "trace.map_controls": "Sterowanie mapą", + "trace.zoom_in": "Powiększ", + "trace.zoom_out": "Pomniejsz", + "trace.fit_route": "Dopasuj trasę", + "trace.fit": "Dopasuj", + "trace.map_click_hint": "Kliknij przeskok, aby zobaczyć IP, lokalizację, ASN i RTT.", + "trace.route_path": "Trasa", + "trace.ping_ok_trace_filtered": "Cel odpowiada na ping, ale ostatnie przeskoki traceroute nie odpowiadają.", + "trace.latency_legend": "Wzrost opóźnienia między odpowiadającymi przeskokami", + "trace.latency_ok": "Δ RTT ≤ 5 ms — normalnie", + "trace.latency_warn": "Δ RTT 5–20 ms — podwyższone", + "trace.latency_bad": "Δ RTT > 20 ms — duży skok" +} diff --git a/app/static/ru.json b/app/static/ru.json new file mode 100644 index 0000000..015c465 --- /dev/null +++ b/app/static/ru.json @@ -0,0 +1,1101 @@ +{ + "auth.create_user": "Создать пользователя", + "auth.login_subtitle": "Введите логин и пароль WGTools.", + "auth.login_title": "Вход в WGTools", + "auth.password": "Пароль", + "auth.password_repeat": "Повторите пароль", + "auth.setup_help": "Первый пользователь получает полный доступ к WGTools. Дополнительных пользователей можно будет создать в Настройках.", + "auth.setup_subtitle": "Перед управлением сервером WGTools нужно создать учетную запись.", + "auth.setup_title": "Создание первого пользователя", + "auth.sign_in": "Войти", + "auth.sign_out": "Выйти", + "auth.username": "Логин", + "clients.actions": "Действия", + "clients.add": "+ Добавить клиента", + "clients.address": "VPN адрес", + "clients.address_hint": "Первый свободный адрес предлагается автоматически.", + "clients.allowed_ips_required": "Укажите хотя бы одну сеть AllowedIPs для конфигурации клиента.", + "clients.basic_connection": "Основные настройки подключения", + "clients.basic_details": "Клиент", + "clients.client": "Клиент", + "clients.client_allowed_ips": "AllowedIPs в клиентском конфиге", + "clients.config_private_warning": "В конфигурации находится приватный ключ клиента. Храни её безопасно.", + "clients.config_title": "Конфигурация клиента", + "clients.config_unavailable": "Конфигурация недоступна", + "clients.connection_direct": "Напрямую к WGTools", + "clients.connection_path": "Точка подключения", + "clients.connection_relay": "VPS Relay", + "clients.connection_via": "Подключение через", + "clients.connection_via_hint": "Выберите публичную точку входа для этого клиента. Relay показывается только если он установлен для выбранного интерфейса WireGuard.", + "clients.copy_config": "Копировать", + "clients.copy_done": "Конфигурация скопирована", + "clients.create_subtitle": "Создание пира WireGuard и готовой клиентской конфигурации.", + "clients.create_title": "Создать клиента", + "clients.creating": "Генерирую ключи и добавляю клиента…", + "clients.day_fri": "Пт", + "clients.day_mon": "Пн", + "clients.day_sat": "Сб", + "clients.day_sun": "Вс", + "clients.day_thu": "Чт", + "clients.day_tue": "Вт", + "clients.day_wed": "Ср", + "clients.delete_confirm": "Удалить этого клиента из WireGuard? WGTools создаст резервную копию и удалит связанные с этим клиентом автоматически созданные правила политики.", + "clients.deleted": "Клиент удалён", + "clients.dns": "DNS (необязательно)", + "clients.dns_hint": "IPv4-адреса DNS через запятую.", + "clients.download_config": "Скачать .conf", + "clients.duplicate": "Дублировать", + "clients.duplicate_address_error": "Этот VPN-адрес уже используется другим пиром.", + "clients.duplicate_name_error": "Пир с таким именем уже существует.", + "clients.duplicate_ready": "Копия подготовлена. WGTools назначил новое имя и VPN-адрес; проверьте параметры перед сохранением.", + "clients.duplicate_site_hint": "Удалённые сети очищены, чтобы не создать дублирующиеся маршруты. Укажите сети для нового Site-to-site пира.", + "clients.duplicate_suffix": "копия", + "clients.edit_subtitle": "Изменение серверной части пира. Настройки применяются без перезапуска WireGuard.", + "clients.edit_title": "Изменить клиента", + "clients.endpoint": "Адрес сервера для клиента", + "clients.endpoint_hint": "Для удалённых клиентов укажи внешний IP/домен, с которого порт WireGuard проброшен на этот сервер.", + "clients.existing": "Существующий пир", + "clients.expiration": "Срок доступа", + "clients.expiration_action": "После окончания срока", + "clients.expiration_action_hint": "Если выключено, клиент останется в WGTools, но доступ WireGuard будет отключён. Чтобы вернуть доступ, укажите новый срок или «Без ограничения» и сохраните клиента.", + "clients.expiration_datetime": "Доступ до", + "clients.expiration_datetime_hint": "Используется локальная дата и время этого браузера.", + "clients.expiration_delete": "Удалить клиента", + "clients.expiration_future_required": "Укажи дату и время в будущем.", + "clients.expiration_hint": "Когда срок закончится, WGTools выполнит выбранное действие на ближайшей минутной границе. Перед изменением создаётся резервная копия WireGuard-конфига.", + "clients.expire_1d": "1 день", + "clients.expire_1h": "1 час", + "clients.expire_3h": "3 часа", + "clients.expire_6h": "6 часов", + "clients.expire_custom": "Своя дата и время", + "clients.expire_never": "Без ограничения", + "clients.expired": "Срок истёк", + "clients.expired_disabled_hint": "Срок доступа истёк, клиент сохранён, но WireGuard-доступ отключён. Укажите новый срок или «Без ограничения» и сохраните, чтобы вернуть доступ.", + "clients.expired_disabled_short": "Срок истёк · отключён", + "clients.expired_disabled_status": "Срок истёк", + "clients.expires_days": "Осталось {n} дн", + "clients.expires_hours": "Осталось {n} ч", + "clients.expires_minutes": "Осталось {n} мин", + "clients.generated_config": "Клиентская конфигурация", + "clients.handshake": "Handshake", + "clients.keepalive": "Keepalive", + "clients.keepalive_hint": "25 секунд — хороший вариант для клиентов за NAT.", + "clients.local_access_exceptions": "Разрешённые локальные адреса", + "clients.local_access_exceptions_hint": "Необязательные IP или CIDR, которые останутся доступны, даже если их локальная или Site-to-site сеть заблокирована. Несколько значений — через запятую.", + "clients.managed": "Управляется WGTools", + "clients.name": "Имя", + "clients.no_peers": "Клиенты не найдены", + "clients.peers": "Клиенты", + "clients.peers_subtitle": "Перед изменениями создаётся резервная копия, затем конфигурация применяется через wg syncconf без перезапуска интерфейса WireGuard.", + "clients.protected_networks_reference": "Заблокированные локальные сети (справочно)", + "clients.protected_networks_reference_hint": "Эти сети не записываются в AllowedIPs. Доступ к ним блокируется серверной политикой WGTools; отдельные адреса можно разрешить полем выше.", + "clients.psk": "Preshared key (PSK)", + "clients.psk_enable": "Использовать дополнительный PSK WireGuard", + "clients.psk_hint": "Рекомендуется. Добавляет к рукопожатию WireGuard дополнительный симметричный секрет. Стандартные клиенты WireGuard его поддерживают; WGTools добавляет PSK в конфиг и QR.", + "clients.psk_short": "PSK", + "clients.qr_loading": "Создаю QR…", + "clients.quick_search": "Быстрый поиск", + "clients.quick_search_clear": "Очистить поиск", + "clients.quick_search_empty": "По запросу клиентов нет", + "clients.relay_endpoint_note": "Готовый конфиг клиента будет подключаться к {endpoint}. Сам сервер WireGuard по-прежнему находится на этом WGTools.", + "clients.relay_required": "Выберите VPS Relay для этого клиента.", + "clients.relay_short": "Relay", + "clients.relay_unknown": "недоступен", + "clients.relay_vps": "VPS Relay", + "clients.relay_vps_hint": "Endpoint клиента формируется автоматически из настроек выбранного Relay.", + "clients.remote_hint": "Сети, расположенные за этим пиром. По одной сети в строке или через запятую.", + "clients.remote_networks": "Удалённые сети", + "clients.remote_required": "Для Site-to-site пира укажите хотя бы одну удалённую сеть.", + "clients.required": "Нужно указать имя и VPN-адрес.", + "clients.route_custom": "Свои маршруты", + "clients.route_full": "Весь трафик через VPN", + "clients.route_full_except_local": "Весь трафик кроме локальных сетей", + "clients.route_hint": "Только эти сети записываются в AllowedIPs готового клиентского конфига.", + "clients.route_preset": "Трафик через VPN", + "clients.route_vpn": "Только VPN-сеть", + "clients.route_vpn_lan": "VPN + локальная сеть", + "clients.saved": "Клиент сохранён", + "clients.schedule_blocked_short": "Расписание · заблокирован", + "clients.schedule_blocked_status": "Заблокирован расписанием", + "clients.schedule_days": "Дни доступа", + "clients.schedule_days_required": "Выбери хотя бы один день для расписания доступа.", + "clients.schedule_disabled_hint": "Сейчас клиент заблокирован расписанием. В следующем разрешённом интервале WGTools автоматически вернёт доступ тому же peer — конфиг клиента менять не нужно.", + "clients.schedule_enable": "Ограничивать доступ по расписанию", + "clients.schedule_from": "Доступ с", + "clients.schedule_hint": "WGTools будет автоматически отключать и возвращать доступ этому клиенту в выбранные дни и часы без замены клиентского конфига.", + "clients.schedule_short": "Расписание", + "clients.schedule_time_required": "Укажи время начала и окончания доступа.", + "clients.schedule_timezone_hint": "Расписание работает по локальному времени WireGuard-сервера. Поддерживаются интервалы через полночь, например 22:00–06:00.", + "clients.schedule_title": "Расписание доступа", + "clients.schedule_to": "Доступ до", + "clients.security_access": "Безопасность и срок доступа", + "clients.server_host": "Адрес / домен сервера", + "clients.server_host_hint": "Внешний IP или домен для подключения этого клиента. Ранее введённые значения доступны в подсказках.", + "clients.server_host_required": "Для готовой конфигурации клиента обязательно укажите адрес или домен сервера.", + "clients.server_peer": "Пир на сервере", + "clients.server_port": "Порт WireGuard", + "clients.server_port_hint": "Берётся автоматически из конфигурации сервера.", + "clients.site_to_site": "Site-to-site", + "clients.status": "Статус", + "clients.subtitle": "Пиры WireGuard, текущий статус и управление конфигурациями клиентов.", + "clients.tab_basic": "Основное", + "clients.tab_config": "Конфигурация", + "clients.tab_policy": "Политики", + "clients.tab_security": "Безопасность", + "clients.title": "Клиенты", + "clients.type": "Тип", + "clients.unmanaged_note": "Этот пир существовал до WGTools. Его приватный ключ восстановить невозможно, поэтому WGTools может менять серверную часть, но не сможет сгенерировать клиентский конфиг или QR-код.", + "clients.updating": "Обновляю клиента…", + "common.actions": "Действия", + "common.ago": "назад", + "common.cancel": "Отмена", + "common.checking": "Проверка…", + "common.close": "Закрыть", + "common.config": "Конфиг", + "common.delete": "Удалить", + "common.disabled": "Выключено", + "common.edit": "Изменить", + "common.enabled": "Включено", + "common.loading": "Загрузка…", + "common.never": "Никогда", + "common.no": "Нет", + "common.not_configured": "Не настроен", + "common.not_installed": "Не установлен", + "common.offline": "офлайн", + "common.online": "онлайн", + "common.refresh": "Обновить", + "common.running": "Работает", + "common.save": "Сохранить", + "common.stopped": "Остановлен", + "common.total": "Всего", + "common.unknown": "Неизвестно", + "common.updated": "Обновлено", + "common.yes": "Да", + "dashboard.active_peers": "Активные клиенты", + "dashboard.active_peers_subtitle": "Живые данные из wg show.", + "dashboard.activity": "Состояние системы", + "dashboard.activity_subtitle": "Проверки работающего WireGuard без изменения конфигурации.", + "dashboard.cores": "ядер", + "dashboard.cpu": "ЦП", + "dashboard.history_24h": "Последние 24 ч", + "dashboard.history_avg": "Сред", + "dashboard.history_max": "Макс", + "dashboard.history_min": "Мин", + "dashboard.history_now": "сейчас", + "dashboard.memory": "Память", + "dashboard.network": "Сеть", + "dashboard.peers": "Клиенты", + "dashboard.quick_search": "Быстрый поиск", + "dashboard.quick_search_clear": "Очистить поиск", + "dashboard.quick_search_empty": "По запросу ничего не найдено", + "dashboard.restart": "Перезапуск", + "dashboard.restart_confirm": "Перезапустить WireGuard? Активные VPN-клиенты автоматически переподключатся.", + "dashboard.restart_ok": "WireGuard перезапущен.", + "dashboard.routing": "Маршрутизация", + "dashboard.site_to_site": "Site-to-site", + "dashboard.start": "Пуск", + "dashboard.start_ok": "WireGuard запущен.", + "dashboard.stop": "Стоп", + "dashboard.stop_confirm": "Остановить WireGuard? Активные VPN-клиенты будут отключены.", + "dashboard.stop_ok": "WireGuard остановлен.", + "dashboard.subtitle": "Состояние WireGuard, клиенты и текущий трафик.", + "dashboard.title": "Главная", + "dashboard.traffic": "Трафик", + "dashboard.uptime": "Аптайм", + "dashboard.wireguard": "WireGuard", + "groups.access_policy": "Политика доступа на сервере", + "groups.additional_allowed": "Дополнительно разрешить", + "groups.additional_blocked": "Дополнительно запретить", + "groups.allow": "Разрешить", + "groups.allowed": "Разрешён", + "groups.allowed_addresses": "Разрешённые адреса / сети", + "groups.apply_current_template": "Применить текущий шаблон группы", + "groups.apply_defaults": "Применить текущий шаблон группы", + "groups.apply_defaults_hint": "Копирует текущие маршруты, DNS и Keepalive группы в этого клиента. После сохранения выдай новый конфиг или QR, если нужно обновить уже установленное устройство.", + "groups.basic": "Основное", + "groups.block": "Запретить", + "groups.blocked": "Запрещён", + "groups.blocked_addresses": "Запрещённые адреса / сети", + "groups.client_config_source": "Источник конфигурации клиента", + "groups.client_defaults": "Настройки клиента", + "groups.client_group_hint": "Необязательная группа с общей политикой доступа и настройками новых клиентов. Группы относятся только к выбранному интерфейсу WireGuard.", + "groups.config_differs": "Конфигурация этого клиента отличается от текущих настроек группы. Серверная политика уже актуальна, но конфиг на телефоне/ПК изменится только после выдачи нового файла или QR.", + "groups.config_differs_short": "Конфиг клиента отличается от настроек группы", + "groups.create": "Создать группу", + "groups.create_title": "Создать группу", + "groups.created": "Группа создана", + "groups.creating": "Создаю группу…", + "groups.defaults_applied": "Текущий шаблон группы применён. Сохрани клиента, чтобы закрепить изменения.", + "groups.defaults_hint": "Определяет, какой трафик устройство отправляет через WireGuard. Политика сервера выше независимо определяет, куда этот трафик будет допущен. Изменение шаблона позже не меняет молча конфиги, уже установленные на устройствах.", + "groups.delete_message": "Удалить группу «{name}»? Клиентские конфигурации при удалении группы никогда не удаляются.", + "groups.delete_move": "Переместить её клиентов в другую группу", + "groups.delete_title": "Удалить группу клиентов", + "groups.delete_unassign": "Убрать принадлежность к группе у её клиентов", + "groups.deleted": "Группа удалена", + "groups.deleting": "Обновляю клиентов и удаляю группу…", + "groups.description": "Описание", + "groups.edit_title": "Изменить группу", + "groups.editor_subtitle": "Группа объединяет действующую серверную политику доступа и шаблон, который используется при создании клиентских конфигураций.", + "groups.effective_allow": "Разрешённые исключения", + "groups.effective_deny": "Запрещённые исключения", + "groups.effective_policy": "Итоговая политика сервера", + "groups.empty": "Групп клиентов пока нет. Создайте группу, чтобы переиспользовать правила доступа и настройки клиентов.", + "groups.group": "Группа", + "groups.inherit": "Наследовать", + "groups.internet_access": "Доступ в интернет", + "groups.internet_short": "Интернет", + "groups.local_access": "Локальные сети", + "groups.local_short": "Локальные сети", + "groups.manage": "Группы", + "groups.members_count": "Клиентов: {count}", + "groups.name": "Название", + "groups.name_required": "Укажите название группы.", + "groups.new_client_defaults": "Шаблон конфигурации клиента", + "groups.new_clients_short": "Новые клиенты", + "groups.no_group": "Без группы", + "groups.none": "Нет", + "groups.override_client_config": "Переопределить шаблон группы для этого клиента", + "groups.override_client_config_hint": "Выключено: маршруты, DNS и Keepalive берутся из шаблона группы. Включено: у клиента собственные значения. Индивидуальная серверная политика выше работает независимо.", + "groups.policy_addresses_hint": "IPv4-адреса или CIDR через запятую. Индивидуальные исключения клиента имеют приоритет над исключениями группы.", + "groups.policy_custom": "Своя политика", + "groups.policy_inherit": "Использовать политику группы", + "groups.policy_mode": "Источник политики", + "groups.policy_mode_hint": "По умолчанию политика наследуется от группы. Исключения клиента никогда не меняют саму группу.", + "groups.routes_required": "Маршруты клиента не могут быть пустыми.", + "groups.subtitle": "Общие политики доступа и настройки для обычных клиентов выбранного интерфейса WireGuard.", + "groups.title": "Группы клиентов", + "groups.traffic_through_vpn": "Трафик через VPN", + "groups.updated": "Группа обновлена", + "groups.updating": "Обновляю политику группы…", + "help.example_note": "Все IP-адреса, имена интерфейсов, peer и домены в примерах справки вымышлены и используются только для документации. Заменяйте их значениями своей сети.", + "help.navigation": "Навигация по справке", + "help.open": "Открыть справку", + "help.subtitle": "Понятная справка по Главной, Серверу, Клиентам и Настройкам с короткими примерами.", + "help.title": "Справка WGTools", + "interfaces.add": "+ Добавить интерфейс", + "interfaces.create": "Создать интерфейс", + "interfaces.create_confirm": "Создать и запустить интерфейс {name}?", + "interfaces.create_failed": "Не удалось создать интерфейс", + "interfaces.create_hint": "Перед созданием WGTools проверит, что VPN-сеть, UDP-порт и policy table не конфликтуют с другими интерфейсами WireGuard.", + "interfaces.create_subtitle": "Создать отдельный интерфейс WireGuard со своим пулом адресов, UDP-портом и настройками маршрутизации.", + "interfaces.create_title": "Добавить интерфейс WireGuard", + "interfaces.created": "Интерфейс успешно создан.", + "interfaces.creating": "Генерирую ключи, создаю новую конфигурацию и запускаю WireGuard…", + "interfaces.current": "Текущий", + "interfaces.delete": "Удалить", + "interfaces.delete_confirm": "Удалить интерфейс {name}? Будут удалены его конфигурация WireGuard и все пиры этого интерфейса. Перед удалением WGTools создаст резервную копию конфигурации.", + "interfaces.delete_failed": "Не удалось удалить интерфейс", + "interfaces.delete_last": "Последний настроенный интерфейс WireGuard нельзя удалить здесь.", + "interfaces.delete_tooltip": "Удалить этот интерфейс WireGuard", + "interfaces.deleted": "Интерфейс удалён. Резервная копия: {backup}", + "interfaces.deleting": "Останавливаю WireGuard и удаляю интерфейс…", + "interfaces.display_name": "Отображаемое имя", + "interfaces.display_name_edit_hint": "Меняется только понятное имя в WGTools; системное имя Linux остаётся прежним.", + "interfaces.display_name_hint": "Необязательное понятное имя, например Работа или Подрядчики.", + "interfaces.identity": "Идентификация интерфейса", + "interfaces.none": "Интерфейсы WireGuard не найдены", + "interfaces.none_configured": "Настроенных интерфейсов WireGuard пока нет.", + "interfaces.peers_short": "пиров", + "interfaces.rename_failed": "Не удалось сохранить понятное имя интерфейса.", + "interfaces.select": "Выбрать", + "interfaces.subtitle": "У каждого интерфейса своя VPN-сеть, порт, клиенты и правила. Выбранный интерфейс используется на всех страницах WGTools.", + "interfaces.switch_title": "Интерфейсы WireGuard", + "interfaces.system_name": "Системное имя", + "interfaces.system_name_hint": "Имя интерфейса Linux, например wg1. После создания его лучше не менять.", + "interfaces.title": "Интерфейсы WireGuard", + "interfaces.unique_port_hint": "Каждый интерфейс WireGuard на этом сервере должен использовать свой UDP-порт.", + "interfaces.unique_table_hint": "WGTools рекомендует отдельную policy table для каждого интерфейса. Оставь пустым для обычной системной маршрутизации.", + "nav.clients": "Клиенты", + "nav.dashboard": "Главная", + "nav.server": "Сервер", + "nav.settings": "Настройки", + "server.access_apply_confirm": "Сохранить правило firewall и применить его сейчас? WireGuard кратковременно перезапустится, перед этим будет создан backup.", + "server.access_rule_deleted": "Правило доступа удалено.", + "server.access_rule_help": "Создание обычного правила FORWARD без ручного редактирования команд iptables.", + "server.access_rule_order_hint": "WGTools вставляет правила доступа в начало цепочки FORWARD, чтобы ограничения срабатывали раньше общих разрешающих правил VPN.", + "server.access_rule_saved": "Правило доступа сохранено и применено.", + "server.action": "Действие", + "server.action_hint": "REJECT сообщает клиенту об отказе; DROP молча отбрасывает трафик; ACCEPT явно разрешает его.", + "server.add_access_rule": "Добавить правило доступа", + "server.add_route": "Добавить маршрут", + "server.address": "Адрес", + "server.any": "Любой", + "server.any_protocol": "Любой", + "server.apply_confirm": "Сохранить эти настройки сервера и применить их сейчас? WireGuard будет кратковременно перезапущен. Перед изменением создаётся резервная копия, а при ошибке WGTools автоматически вернёт предыдущую конфигурацию.", + "server.apply_settings": "Сохранить и применить", + "server.applying_rule": "Создаю backup и применяю…", + "server.applying_settings": "Проверяю настройки, создаю резервную копию и применяю…", + "server.basic_settings": "Основные настройки", + "server.config_tab_help": "Открывает редактор исходного конфига выбранного интерфейса WireGuard.", + "server.create_confirm": "Создать и запустить сервер WireGuard с этими настройками?", + "server.create_server": "Создать сервер", + "server.create_step_conf": "Создаст конфигурацию выбранного интерфейса WireGuard с правами 600.", + "server.create_step_forward": "Настроит forwarding, NAT и при необходимости policy routing.", + "server.create_step_key": "Сгенерирует новую пару ключей сервера.", + "server.create_step_start": "Включит и запустит выбранный интерфейс wg-quick.", + "server.create_subtitle": "WireGuard установлен, но выбранный интерфейс пока не настроен.", + "server.create_success": "Сервер WireGuard успешно создан.", + "server.create_title": "Создать сервер WireGuard", + "server.creating": "Генерирую ключи, записываю конфигурацию и запускаю WireGuard…", + "server.custom_preserved": "Блоки пиров, маршруты site-to-site и пользовательские PostUp/PostDown, которыми эти поля не управляют, сохраняются.", + "server.delete_access_confirm": "Удалить это правило доступа и применить изменение?", + "server.delete_route_confirm": "Удалить этот пользовательский маршрут и применить изменение?", + "server.destination": "Назначение", + "server.destination_hint": "Пусто = любое назначение. Можно указать IP, CIDR или диапазон IP. Несколько назначений разделяйте запятыми.", + "server.destination_port": "Порт назначения", + "server.destination_port_hint": "Необязательно. Например 443 или диапазон 10000:20000. Для порта сначала выбери TCP или UDP.", + "server.details": "Детали", + "server.dev_word": "dev", + "server.diagnostics": "Диагностика", + "server.diagnostics_done": "Диагностика завершена", + "server.diagnostics_subtitle": "Текущие проверки системы. Конфигурация не изменяется.", + "server.direction": "Хук", + "server.edit_access_rule": "Изменить правило доступа", + "server.edit_route": "Изменить маршрут", + "server.edit_server": "Изменить настройки", + "server.edit_subtitle": "Основные настройки WireGuard, маршрутизации и NAT. Существующие пиры и пользовательские правила сохраняются.", + "server.edit_title": "Настройки сервера", + "server.edit_warning": "При изменении настроек интерфейса, маршрутизации или firewall интерфейс WireGuard кратковременно перезапускается. Активные пиры подключатся снова автоматически.", + "server.enable_forwarding": "Включить IPv4 forwarding", + "server.enable_nat": "Включить NAT / Masquerade", + "server.firewall": "Firewall и NAT", + "server.firewall_subtitle": "Правила, обнаруженные в хуках WireGuard.", + "server.firewall_subtitle_v08": "Базовые правила forwarding/NAT и правила доступа из конфигурации выбранного интерфейса. Простые правила редактируются здесь, сложные остаются доступны через raw-редактор.", + "server.forward_from_vpn": "Разрешить forwarding из VPN", + "server.forward_to_vpn": "Разрешить forwarding в VPN", + "server.forwarding_section": "Forwarding и NAT", + "server.gateway": "Шлюз", + "server.gateway_hint": "Нужен только при использовании отдельной таблицы policy routing.", + "server.install_success": "WireGuard успешно установлен.", + "server.install_wireguard": "Установить WireGuard", + "server.install_wireguard_help": "Выполняет apt update и устанавливает WireGuard вместе с сетевыми инструментами, необходимыми WGTools.", + "server.install_wireguard_title": "Установить WireGuard", + "server.installing": "Устанавливаю WireGuard… Это может занять некоторое время.", + "server.interface": "Интерфейс", + "server.interface_hint": "Сейчас WGTools управляет этим интерфейсом.", + "server.interface_name": "Интерфейс", + "server.interface_section": "Интерфейс WireGuard", + "server.ip_forwarding": "IPv4 forwarding", + "server.kind": "Тип", + "server.listen_port": "Порт", + "server.local_network": "Локальная сеть", + "server.local_network_hint": "Необязательный маршрут, который будет добавлен в policy table.", + "server.managed_automatically": "Управляется автоматически", + "server.nat": "NAT / Masquerade", + "server.network": "Сеть", + "server.network_settings": "Сеть и NAT", + "server.no_firewall": "Правила firewall не обнаружены", + "server.no_routes": "Маршруты не обнаружены", + "server.not_configured": "Не настроен", + "server.not_set": "Не задан", + "server.policy_disabled_hint": "Для обычной системной маршрутизации выключи эту опцию. Включай её, если VPN нужна отдельная source policy routing table.", + "server.policy_enabled": "Включить policy routing", + "server.policy_table": "Таблица маршрутизации", + "server.policy_table_hint": "Оставь пустым для обычной системной маршрутизации; например 200 — для source policy routing.", + "server.port_word": "порт", + "server.private_hidden": "Настроен (скрыт)", + "server.private_key": "Приватный ключ", + "server.protocol": "Протокол", + "server.route_apply_confirm": "Сохранить маршрут и применить его сейчас? WireGuard кратковременно перезапустится, перед этим будет создан backup.", + "server.route_custom": "Пользовательский", + "server.route_deleted": "Маршрут удалён.", + "server.route_device_hint": "Необязательный выходной интерфейс, например wg0 или enp6s18.", + "server.route_editor_help": "Маршрут будет добавляться при запуске WireGuard и удаляться при его остановке.", + "server.route_gateway_hint": "Необязательный шлюз. Нужно указать хотя бы шлюз или интерфейс.", + "server.route_managed_peer": "Site-to-site пир", + "server.route_managed_server": "Настройка сервера", + "server.route_network_hint": "IPv4-сеть, например 10.20.0.0/24, либо 'default'.", + "server.route_saved": "Маршрут сохранён и применён.", + "server.route_table_hint": "'main' — обычная маршрутизация, либо номер таблицы, например 200.", + "server.route_type": "Тип", + "server.routes": "Обнаруженные маршруты", + "server.routes_subtitle": "Маршруты из PostUp/PostDown и текущего policy routing.", + "server.routes_subtitle_v08": "Системные, site-to-site и пользовательские маршруты выбранного интерфейса. Пользовательские маршруты можно добавлять, изменять и удалять здесь.", + "server.routing": "Маршрутизация", + "server.routing_section": "Маршрутизация", + "server.rule": "Правило", + "server.rule_access": "Правило доступа", + "server.rule_advanced": "Расширенное", + "server.rule_apply_warning": "При применении маршрута или правила firewall интерфейс WireGuard кратковременно перезапускается. WGTools создаёт backup и автоматически откатывается при ошибке запуска.", + "server.rule_client_exception": "Исключение клиента", + "server.rule_client_policy": "Политика клиента", + "server.rule_managed_server": "Настройка сервера", + "server.rule_type": "Тип", + "server.run_diagnostics": "Запустить диагностику", + "server.save_apply": "Сохранить и применить", + "server.save_config": "SaveConfig", + "server.server_address": "VPN-адрес сервера", + "server.server_address_hint": "Обычно используется первый доступный адрес VPN-сети.", + "server.settings_applied": "Настройки сервера сохранены и успешно применены.", + "server.settings_apply_failed": "Не удалось применить настройки сервера", + "server.setup_required": "Требуется настройка", + "server.source": "Источник", + "server.source_hint": "Пусто = любой. Можно указать IP, CIDR или диапазон, например 10.0.0.100-10.0.0.120.", + "server.subtitle": "Установка WireGuard, первичная настройка и текущая конфигурация сервера.", + "server.tab_config": "Конфиг", + "server.tab_interface": "Интерфейс", + "server.tab_routing": "Маршрутизация", + "server.tab_vps": "VPS", + "server.table": "Таблица", + "server.tabs_aria": "Разделы настроек сервера", + "server.title": "Сервер", + "server.uplink": "Внешний интерфейс", + "server.use_raw_editor": "Через raw-редактор", + "server.via": "Через / Интерфейс", + "server.via_word": "via", + "server.vpn_network": "VPN сеть", + "server.vpn_network_hint": "Адреса клиентов будут выдаваться из этой сети.", + "server.vpn_pool": "Пул VPN-адресов", + "server.wg_not_installed": "WireGuard не установлен", + "server.wg_not_installed_subtitle": "WGTools может автоматически установить необходимые пакеты Debian.", + "server.what_happens": "Что сделает WGTools", + "settings.about": "О программе", + "settings.add_user": "Добавить пользователя", + "settings.advanced": "Расширенные настройки", + "settings.advanced_subtitle": "Прямой доступ к профессиональным инструментам конфигурации WireGuard.", + "settings.appearance": "Оформление", + "settings.applying_config": "Проверяю конфигурацию, создаю резервную копию и применяю…", + "settings.backup_count": "Сохранено копий", + "settings.backup_retention": "Хранить копий", + "settings.backup_retention_help": "Старые автоматические копии удаляются после создания новой. От 1 до 200 файлов.", + "settings.backups": "Резервные копии конфигурации", + "settings.backups_always_on": "Включено", + "settings.backups_subtitle": "WGTools автоматически создаёт резервную копию перед операциями, меняющими конфигурацию. Автоматические копии отключить нельзя.", + "settings.change_password": "Изменить пароль", + "settings.check_updates": "Проверить обновления", + "settings.config_applied": "Конфигурация сохранена и успешно применена.", + "settings.config_applied_restarted": "Конфигурация применена, WireGuard перезагружен.", + "settings.config_applied_stopped": "Конфигурация сохранена. WireGuard уже был остановлен и оставлен остановленным.", + "settings.config_apply_failed": "Не удалось применить конфигурацию", + "settings.config_load_failed": "Не удалось загрузить конфигурацию", + "settings.current_user": "Текущий пользователь", + "settings.current_version": "Текущая версия", + "settings.audit_action": "Действие", + "settings.audit_empty": "Событий аудита пока нет", + "settings.audit_log": "Аудит", + "settings.audit_log_subtitle": "Действия в панели, вход/восстановление доступа и Telegram, а также история подключений WireGuard-клиентов. Секреты сюда не записываются.", + "settings.audit_object": "Объект", + "settings.audit_result": "Результат", + "settings.audit_retention_note": "Срок хранения: 30 дней", + "settings.audit_search": "Быстрый поиск", + "settings.audit_search_clear": "Очистить поиск", + "settings.audit_search_empty": "По запросу событий нет", + "settings.audit_time": "Дата / время", + "settings.audit_user": "Пользователь", + "audit.user.telegram_short": "ТГ", + "audit.action.access_rule.created": "Правило доступа создано", + "audit.action.access_rule.deleted": "Правило доступа удалено", + "audit.action.access_rule.updated": "Правило доступа изменено", + "audit.action.auth.first_user_created": "Первый пользователь создан", + "audit.action.auth.login": "Вход в панель", + "audit.action.auth.login_failed": "Неудачный вход", + "audit.action.auth.logout": "Выход из панели", + "audit.action.backup.full_created": "Полная копия создана", + "audit.action.backup.full_restored": "Полная копия восстановлена", + "audit.action.client.config_downloaded": "Конфиг клиента скачан", + "audit.action.client.config_viewed": "Конфиг клиента открыт", + "audit.action.client.created": "Клиент создан", + "audit.action.client.deleted": "Клиент удалён", + "audit.action.client.qr_viewed": "QR клиента открыт", + "audit.action.client.updated": "Клиент изменён", + "audit.action.client_group.created": "Группа клиентов создана", + "audit.action.client_group.deleted": "Группа клиентов удалена", + "audit.action.client_group.updated": "Группа клиентов изменена", + "audit.action.interface.created": "Интерфейс создан", + "audit.action.interface.deleted": "Интерфейс удалён", + "audit.action.interface.renamed": "Интерфейс переименован", + "audit.action.route.created": "Маршрут создан", + "audit.action.route.deleted": "Маршрут удалён", + "audit.action.route.updated": "Маршрут изменён", + "audit.action.server.created": "Сервер создан", + "audit.action.server.raw_config_applied": "Raw config применён", + "audit.action.server.settings_applied": "Настройки сервера применены", + "audit.action.settings.updated": "Настройки панели изменены", + "audit.action.telegram.action_denied": "Действие Telegram запрещено", + "audit.action.telegram.action_failed": "Ошибка действия Telegram", + "audit.action.telegram.connection_test": "Проверка подключения Telegram", + "audit.action.telegram.settings_updated": "Настройки Telegram изменены", + "audit.action.update.checked": "Проверка обновлений", + "audit.action.update.scheduled": "Обновление запланировано", + "audit.action.update.backup_created": "Резервная копия перед обновлением", + "audit.action.update.completed": "Обновление завершено", + "audit.action.update.failed": "Ошибка обновления", + "audit.action.update.rollback_completed": "Предыдущая версия восстановлена", + "audit.action.update.rollback_failed": "Ошибка отката обновления", + "audit.action.user.created": "Пользователь создан", + "audit.action.user.deleted": "Пользователь удалён", + "audit.action.user.password_changed": "Пароль пользователя изменён", + "audit.action.vps.candidate_deleted": "VPS удалён из списка", + "audit.action.vps.candidate_saved": "VPS сохранён", + "audit.action.vps.detached": "VPS Relay отключён", + "audit.action.vps.relay_installed": "VPS Relay установлен", + "audit.action.wireguard.client_connected": "Клиент WireGuard подключён", + "audit.action.wireguard.installed": "WireGuard установлен", + "audit.action.wireguard.restarted": "WireGuard перезапущен", + "audit.action.wireguard.started": "WireGuard запущен", + "audit.action.wireguard.stopped": "WireGuard остановлен", + "audit.result.applied": "применено", + "audit.result.available": "доступно", + "audit.result.changed": "изменено", + "audit.result.created": "создано", + "audit.result.current": "актуально", + "audit.result.deleted": "удалено", + "audit.result.detached": "отключено", + "audit.result.denied": "запрещено", + "audit.result.downloaded": "скачано", + "audit.result.endpoint": "IP", + "audit.result.error": "Ошибка", + "audit.result.installed": "установлено", + "audit.result.invalid_credentials": "неверные данные", + "audit.result.ok": "успешно", + "audit.result.queued": "в очереди", + "audit.result.restarted": "перезапущено", + "audit.result.restored": "восстановлено", + "audit.result.rotated": "обновлено", + "audit.result.saved": "сохранено", + "audit.result.shown": "показано", + "audit.result.started": "запущено", + "audit.result.stopped": "остановлено", + "audit.result.updated": "изменено", + "settings.delete_user": "Удалить", + "settings.delete_user_confirm": "Удалить пользователя {name}?", + "settings.edit_raw_config": "Редактировать конфиг интерфейса", + "settings.expert_mode": "Для профи", + "settings.full_backup_component_clients": "Данные и приватные ключи клиентов, PSK, сроки доступа и принадлежность к группам, необходимые для повторной выдачи конфигов и QR.", + "settings.full_backup_component_db": "База WGTools: пользователи, настройки программы, почта/SMTP, Telegram и сохранённое состояние VPS Relay.", + "settings.full_backup_component_relay": "Данные для восстановления VPS Relay: controller/tenant ID, management token и домашний transport-ключ. После restore WGTools может заново поднять локальный transport и подключиться к сохранённому tenant на VPS.", + "settings.full_backup_component_system": "Файл sysctl WGTools для IPv4 forwarding, метаданные понятных имён интерфейсов и определения групп клиентов с их политиками и шаблонами, если они существуют. История автоматических копий конфигураций интерфейсов намеренно не включается.", + "settings.full_backup_component_wg": "Все обнаруженные конфигурации интерфейсов WireGuard из /etc/wireguard/ вместе с их состоянием запущен/остановлен.", + "settings.full_backup_create_failed": "Не удалось создать полную резервную копию", + "settings.full_backup_creating": "Создаю полную резервную копию…", + "settings.full_backup_download": "Создать", + "settings.full_backup_downloaded": "Резервная копия создана и скачана. Храните её в безопасном месте.", + "settings.full_backup_downloaded_short": "Полная копия скачана.", + "settings.full_backup_help": "Создаёт переносимую резервную копию WGTools для переезда или аварийного восстановления. В архив входят конфигурации WireGuard, пользователи, настройки, группы, данные управляемых клиентов и состояние, необходимое для повторного подключения к сохранённым VPS Relay.", + "settings.full_backup_no_file": "Файл резервной копии не выбран", + "settings.full_backup_restore": "Восстановить", + "settings.full_backup_restore_confirm": "Восстановить эту полную копию WGTools? Будут восстановлены пользователи, настройки, данные управляемых клиентов и все конфигурации WireGuard, включённые в архив. Интерфейсы WireGuard могут быть перезапущены. Перед восстановлением WGTools создаст страховочную копию и автоматически откатит изменения, если применение восстановленного состояния завершится ошибкой.", + "settings.full_backup_restore_failed": "Ошибка восстановления", + "settings.full_backup_restored": "Резервная копия успешно восстановлена. Войдите под пользователем из восстановленной копии.", + "settings.full_backup_restored_short": "Резервная копия восстановлена.", + "settings.full_backup_restoring": "Проверяю архив, создаю страховочную копию и выполняю восстановление…", + "settings.full_backup_secret_warning": "Файл содержит секретные данные: приватные ключи WireGuard, приватные ключи клиентов, preshared keys (PSK), хэши паролей WGTools, токен Telegram-бота и сохранённый пароль SMTP. Храните его как пароль и никогда не прикладывайте к публичным issue, чатам или форумам.", + "settings.full_backup_select": "Выбрать", + "settings.full_backup_title": "Полная резервная копия и восстановление", + "settings.full_mode": "Управление сервером и клиентами включено", + "settings.interface_help": "Интерфейс WireGuard выбирается при установке WGTools.", + "settings.language": "Язык", + "settings.last_backup": "Последняя копия", + "settings.latest_version": "Последний релиз", + "settings.loading_config": "Загрузка конфигурации…", + "settings.mode": "Режим", + "settings.never_logged_in": "Никогда", + "settings.new_password": "Новый пароль", + "settings.no_backups": "Резервных копий пока нет", + "settings.online_help": "Клиент считается онлайн, пока последний handshake не старше этого значения. От 30 до 3600 секунд.", + "settings.online_threshold": "Порог Online", + "settings.open_release": "Открыть релиз", + "settings.password_changed": "Пароль изменен.", + "settings.passwords_mismatch": "Пароли не совпадают.", + "settings.project_github": "Проект / GitHub", + "settings.raw_config_confirm": "Сохранить эту конфигурацию WireGuard и применить её сейчас? Выбранный интерфейс будет перезапущен. Сначала создаётся резервная копия; если новая конфигурация не запустится, WGTools автоматически выполнит откат.", + "settings.raw_config_help": "Открыть исходную конфигурацию выбранного интерфейса WireGuard.", + "settings.raw_config_title": "Конфигурация WireGuard вручную", + "settings.raw_config_warning": "Режим для опытных пользователей: это реальный конфигурационный файл WireGuard, в нём находятся приватный ключ сервера и PSK пиров, если они используются. При сохранении и применении интерфейс WireGuard будет перезапущен. Перед изменением WGTools создаёт резервную копию и автоматически откатывается, если новая конфигурация не запускается.", + "settings.readonly_mode": "Управление клиентами включено", + "settings.refresh_help": "Как часто WGTools запрашивает свежие данные состояния. От 2 до 60 секунд.", + "settings.refresh_interval": "Интервал обновления", + "settings.release_notes": "Описание релиза", + "settings.reload_config": "Перечитать с диска", + "settings.save_apply": "Сохранить и применить", + "settings.saved": "Настройки сохранены.", + "settings.saved_reload": "Настройки сохранены. Перезагрузка…", + "settings.saving": "Сохраняю настройки…", + "settings.status": "Обновление статуса", + "settings.status_help": "Настройки обновления живых данных Главной и статусов клиентов.", + "settings.subtitle": "Настройки интерфейса WGTools и отображения статуса.", + "settings.syntax_hint": "Секции, параметры, значения и комментарии WireGuard подсвечиваются во время редактирования.", + "settings.tab_about": "О программе", + "settings.tab_backups": "Резервные копии", + "settings.tab_general": "Основные", + "settings.tab_telegram": "Telegram", + "settings.tab_users": "Пользователи", + "settings.tabs_aria": "Разделы настроек", + "settings.telegram": "Telegram Bot", + "settings.telegram_allowed_ids": "Разрешённые Telegram user ID", + "settings.telegram_allowed_ids_help": "По одному числовому user ID в строке. Если неразрешённый пользователь отправит /start, WGTools ответит его Telegram user ID — его можно добавить сюда.", + "settings.telegram_bot_name": "Бот", + "settings.telegram_connected": "Подключён", + "settings.telegram_disabled": "Отключён", + "settings.telegram_dns": "DNS клиентов по умолчанию", + "settings.telegram_dns_help": "Необязательные IPv4-адреса DNS через запятую. Используются для клиентов, созданных ботом.", + "settings.telegram_enabled": "Включить Telegram-бота", + "settings.telegram_endpoint": "Адрес / домен сервера по умолчанию", + "settings.telegram_endpoint_help": "Используется ботом при создании нового клиентского конфига. Укажите только IP или домен; порт WireGuard берётся из конфигурации сервера.", + "settings.telegram_language": "Язык бота", + "settings.telegram_language_auto": "Авто (язык Telegram)", + "settings.telegram_last_poll": "Последняя связь с Telegram", + "settings.telegram_not_configured": "Не настроен", + "settings.telegram_remove_token": "Удалить токен", + "settings.telegram_remove_token_confirm": "Удалить сохранённый токен Telegram-бота и отключить бота?", + "settings.telegram_save": "Сохранить настройки Telegram", + "settings.telegram_saved": "Настройки Telegram сохранены.", + "settings.telegram_setup_note": "Создайте бота в @BotFather, сохраните токен, включите бота и отправьте ему /start. Если ваш user ID ещё не разрешён, WGTools покажет его — добавьте этот ID в список разрешённых Telegram user ID.", + "settings.telegram_status": "Состояние бота", + "settings.telegram_subtitle": "Удалённое управление WireGuard из Telegram: состояние сервера, клиенты, создание/удаление клиентов и запуск/перезапуск/остановка WireGuard.", + "settings.telegram_test": "Проверить подключение", + "settings.telegram_test_ok": "Telegram подключён: @{username}", + "settings.telegram_test_recent_ok": "Telegram-бот работает. Прямая проверка получила timeout, но бот недавно успешно связывался с Telegram.", + "settings.telegram_token": "Токен бота", + "settings.telegram_token_help": "Создайте бота через @BotFather и вставьте сюда его Bot API token. API ID и API Hash для Telegram Bot API не нужны.", + "settings.telegram_token_keep": "Оставьте поле пустым, чтобы сохранить уже записанный токен.", + "settings.telegram_waiting": "Настроен, ожидается запуск бота", + "settings.theme": "Тема", + "settings.theme_dark": "Тёмная", + "settings.theme_light": "Светлая", + "settings.theme_system": "Системная", + "settings.title": "Настройки", + "settings.update_available": "Доступно обновление", + "settings.update_backup_queued": "Обновление поставлено в очередь. Перед установкой WGTools создаст автоматическую полную резервную копию…", + "settings.update_backup_running": "Создаю автоматическую полную резервную копию перед обновлением…", + "settings.update_check_failed": "Не удалось проверить обновления", + "settings.update_checking": "Проверяю последний опубликованный релиз на GitHub…", + "settings.update_confirm": "Обновить WGTools с v{current} до v{latest}? Сначала будет создана полная резервная копия и копия приложения для отката. Веб-интерфейс ненадолго перезапустится.", + "settings.update_current": "Актуальная версия", + "settings.update_downloading": "Скачиваю и проверяю релиз с GitHub…", + "settings.update_failed": "Не удалось обновить WGTools.", + "settings.update_installing": "Устанавливаю обновление. Веб-интерфейс может ненадолго стать недоступен…", + "settings.update_no_update": "Установлена последняя версия WGTools.", + "settings.update_not_checked": "Не проверялось", + "settings.update_queued": "Обновление поставлено в очередь. Жду запуска службы обновления…", + "settings.update_rollback_ok": "Предыдущая версия WGTools восстановлена автоматически.", + "settings.update_rolling_back": "Обновление завершилось ошибкой. Восстанавливаю предыдущую версию WGTools…", + "settings.update_running": "Создаю резервные копии перед обновлением…", + "settings.update_safety_hint": "Обновление запускается только вручную. Перед установкой WGTools создаёт полную резервную копию состояния и отдельную копию приложения для отката. При ошибке предыдущая версия приложения восстанавливается автоматически. Сам WireGuard обновлятор не перезапускает, если новый релиз явно не меняет его конфигурацию.", + "settings.update_sidebar": "Доступна новая версия", + "settings.update_sidebar_hint": "Открыть Настройки → О программе", + "settings.update_starting": "Запускаю обновление…", + "settings.update_status_unknown": "Статус обновления временно недоступен. Повторяю проверку…", + "settings.update_subtitle": "Информация о проекте, автоматическая проверка новых релизов и безопасное обновление из GitHub Releases.", + "settings.update_success": "WGTools успешно обновлён до v{version}. Перезагружаю страницу…", + "settings.update_wgtools": "Обновить WGTools", + "settings.user_actions": "Действия", + "settings.user_created": "Создан", + "settings.user_created_ok": "Пользователь создан.", + "settings.user_deleted": "Пользователь удален.", + "settings.user_equal_rights": "Все пользователи WGTools имеют одинаковые права.", + "settings.user_last_login": "Последний вход", + "settings.user_name": "Логин", + "settings.users": "Пользователи", + "settings.users_subtitle": "Локальные учётные записи WGTools. E-mail необязателен и используется только для восстановления пароля при включённой почте.", + "vps.add": "Добавить VPS", + "vps.add_help": "WGTools подключится по SSH для проверки или установки Relay. Пароль и приватный SSH-ключ не сохраняются.", + "vps.add_title": "Добавить VPS", + "vps.agent": "Relay Agent", + "vps.agent_found": "Уже установлен", + "vps.agent_will_install": "Будет установлен", + "vps.arch": "Архитектура", + "vps.auth_method": "Способ входа", + "vps.authentication": "Авторизация SSH", + "vps.check": "Проверить VPS", + "vps.check_failed": "Проверка VPS не пройдена", + "vps.check_link": "Проверить связь", + "vps.check_ok": "VPS совместим", + "vps.checking": "Проверяем SSH и совместимость VPS…", + "vps.connections": "подключений", + "vps.credentials_not_saved": "Используется только для этой проверки и не сохраняется WGTools.", + "vps.delete_candidate": "Убрать", + "vps.delete_installed": "Удалить VPS", + "vps.delete_installed_confirm": "Удалить «{name}» из WGTools? Локальный транспорт Relay будет отключён, но Relay Agent и tenant на самом VPS останутся без изменений. Этот VPS можно будет добавить снова и WGTools подключится к существующему Relay, не создавая новый. Клиенты, использующие Relay, не смогут подключаться через него, пока VPS не будет подключён повторно.", + "vps.delete_installed_failed": "Не удалось удалить VPS из WGTools", + "vps.delete_installed_ok": "VPS удалён из WGTools. Relay на удалённом VPS сохранён и может быть подключён повторно.", + "vps.empty_help": "Добавьте VPS на Debian или Ubuntu: WGTools проверит SSH-доступ, совместимость системы и свободные UDP-порты.", + "vps.empty_title": "VPS пока не настроен", + "vps.endpoint": "Публичная точка", + "vps.endpoint_domain": "Домен (рекомендуется)", + "vps.endpoint_domain_hint": "При замене основного VPS достаточно будет изменить DNS, не перевыпуская конфиги клиентов.", + "vps.health_failed": "Проверка Relay не пройдена", + "vps.host": "IP / имя хоста", + "vps.host_key": "Ключ хоста SSH", + "vps.identity": "Подключение к VPS", + "vps.install_failed": "Не удалось установить Relay", + "vps.install_ok": "Relay установлен, защищённый канал управления проверен", + "vps.install_relay": "Установить Relay", + "vps.install_title": "Установить VPS Relay", + "vps.installed": "Установлен", + "vps.installing": "Устанавливаем Relay Agent и поднимаем защищённый транспортный туннель…", + "vps.iptables": "iptables", + "vps.key_passphrase": "Пароль ключа", + "vps.link_ok": "Связь с Relay работает", + "vps.multi_tenant_note": "На VPS уже работает WGTools Relay Agent. Он не будет переустановлен: для этого WGTools создаст отдельное изолированное подключение со своими ключами и UDP-портами.", + "vps.name": "Название", + "vps.no_domain": "Подключение по IP", + "vps.not_installed": "Будет установлен", + "vps.os": "Операционная система", + "vps.password": "Пароль", + "vps.phase_note": "Relay Agent поддерживает несколько независимых WGTools на одном VPS. Каждый контроллер получает отдельное изолированное подключение, ключи и UDP-порты; существующие подключения не изменяются.", + "vps.port_pair": "UDP-порты", + "vps.ports_adjusted": "выбраны свободные порты", + "vps.private_key": "Приватный ключ", + "vps.privilege": "Права", + "vps.public_endpoint": "Будущая публичная точка", + "vps.ready_help": "SSH-данные используются для проверки совместимости и сразу для установки Relay; WGTools их не сохраняет.", + "vps.reconnect_note": "На VPS найдено существующее подключение Relay, созданное этим WGTools. Будет восстановлено именно оно — новый tenant и новые UDP-порты создаваться не будут.", + "vps.reconnect_ok": "Существующий Relay успешно подключён повторно", + "vps.reconnect_relay": "Подключить Relay", + "vps.relay_port": "UDP-порт Relay", + "vps.remove_confirm": "Убрать этого кандидата VPS? На удалённом сервере ничего не менялось.", + "vps.save_candidate": "Сохранить кандидата", + "vps.saved": "Кандидат VPS сохранён", + "vps.ssh": "SSH", + "vps.ssh_key": "SSH-ключ", + "vps.ssh_port": "SSH-порт", + "vps.ssh_user": "SSH-пользователь", + "vps.status_candidate": "Готов к установке", + "vps.status_installed": "Relay подключён", + "vps.subtitle": "Подготовка публичного VPS для удалённого доступа, когда у этого сервера WGTools нет белого IP.", + "vps.tenant": "Подключение", + "vps.title": "VPS Relay", + "vps.transport_port": "UDP-порт транспорта", + "vps.transport_port_hint": "Отдельный UDP-порт защищённого туннеля Home ↔ VPS.", + "vps.wireguard": "WireGuard", + "vps.saved_short": "Сохранено", + "vps.active_short": "Активно", + "dashboard.traffic_reset": "Сбросить", + "dashboard.traffic_reset_confirm": "Сбросить накопленные счётчики трафика WireGuard для этого интерфейса? Счётчики клиентов также начнутся с нуля.", + "dashboard.traffic_reset_done": "Счётчики трафика сброшены", + "dashboard.traffic_reset_failed": "Не удалось сбросить счётчики трафика", + "audit.action.traffic.reset": "Счётчики трафика сброшены", + "audit.result.reset": "сброшено", + "server.mtu": "MTU", + "server.mtu_auto": "Авто", + "server.mtu_hint": "Необязательно. Пустое поле — автоматический MTU wg-quick. Укажите вручную, например 1380 или 1420, если этого требует сеть, LTE или PPPoE.", + "clients.peer_isolation": "Изоляция VPN-клиента", + "clients.peer_isolation_enable": "Изолировать от других VPN-клиентов", + "clients.peer_isolation_hint": "Блокирует обмен трафиком между этим клиентом и другими адресами из пула WireGuard. Доступ к самому серверу, Интернету, локальным и Site-to-site сетям определяется остальными правилами.", + "clients.credentials_rotate": "Ключи клиента", + "clients.credentials_rotate_button": "Сменить ключи", + "clients.credentials_rotate_confirm": "Сгенерировать новые ключи этого клиента? Если клиент сейчас подключён, его текущая WireGuard-сессия будет принудительно разорвана. После смены нужно выдать новый конфиг или QR.", + "clients.credentials_rotate_confirm_psk": "Сгенерировать новую ключевую пару и новый PSK этого клиента? Если клиент сейчас подключён, его текущая WireGuard-сессия будет принудительно разорвана. После смены нужно выдать новый конфиг или QR.", + "clients.credentials_rotate_hint": "Одной операцией меняет PrivateKey/PublicKey и, если PSK включён, также PSK. Адрес, маршруты, группа, расписание, изоляция и накопленная статистика сохраняются.", + "clients.credentials_rotating": "Генерируем новые ключи и отключаем старую сессию клиента…", + "clients.credentials_rotated": "Ключи клиента сменены. Если клиент был подключён, его старая сессия принудительно отключена. Старый конфиг больше не работает; перед подключением выдайте новый конфиг или QR.", + "clients.credentials_rotated_short": "Ключи клиента сменены — нужен новый конфиг", + "audit.action.client.credentials_rotated": "Ключи клиента обновлены", + "clients.credentials_connection_lost": "Соединение с WGTools прервалось. Если панель была открыта через клиента, которому только что сменили ключи, это ожидаемо: его старая WireGuard-сессия отключается сразу. Подключитесь к WGTools другим способом и выдайте новый конфиг или QR.", + "nav.navigation": "Основная навигация", + "nav.project_github": "WGTools на GitHub", + "auth.email": "E-mail", + "auth.email_optional_help": "Пока необязательно. После настройки почты адрес можно использовать для восстановления пароля.", + "auth.forgot_password": "Забыли пароль?", + "auth.reset_title": "Сброс пароля", + "auth.reset_subtitle": "Получите одноразовый код по почте и задайте новый пароль WGTools.", + "auth.reset_identifier": "Логин или E-mail", + "auth.reset_identifier_help": "Для защиты данных WGTools всегда показывает одинаковый ответ независимо от существования учётной записи.", + "auth.send_reset_code": "Отправить код", + "auth.reset_code_sent_generic": "Если такая учётная запись существует и для неё указан E-mail, код сброса отправлен. Код действует 15 минут.", + "auth.reset_code": "6-значный код", + "auth.set_new_password": "Установить новый пароль", + "auth.request_another_code": "Запросить другой код", + "auth.back_to_login": "Вернуться ко входу", + "auth.reset_not_configured": "Восстановление пароля по почте не настроено. Обратитесь к администратору WGTools.", + "settings.tab_mail": "Почта", + "settings.mail": "Почта / SMTP", + "settings.mail_subtitle": "SMTP используется для восстановления пароля.", + "settings.mail_not_configured": "Не настроено", + "settings.mail_enabled": "Включить почту и восстановление пароля", + "settings.mail_smtp_host": "SMTP-сервер", + "settings.mail_smtp_port": "SMTP-порт", + "settings.mail_security": "Шифрование", + "settings.mail_security_none": "Без шифрования", + "settings.mail_username": "Логин SMTP", + "settings.mail_username_help": "Используется для авторизации SMTP и как E-mail отправителя.", + "settings.mail_password": "Пароль SMTP", + "settings.mail_password_keep": "Оставьте пустым, чтобы сохранить текущий пароль.", + "settings.mail_from_email": "E-mail отправителя", + "settings.mail_from_name": "Имя отправителя", + "settings.mail_test_recipient": "Получатель теста", + "settings.mail_test_recipient_help": "Тест использует уже сохранённые настройки SMTP.", + "settings.mail_remove_password": "Удалить пароль", + "settings.mail_test": "Отправить тест", + "settings.mail_save": "Сохранить настройки почты", + "settings.mail_enabled_badge": "Включено", + "settings.mail_disabled_badge": "Отключено", + "settings.mail_saved": "Настройки почты сохранены.", + "settings.mail_remove_password_confirm": "Удалить сохранённый пароль SMTP и отключить почту?", + "settings.mail_password_removed": "Пароль SMTP удалён, почта отключена.", + "settings.mail_test_recipient_required": "Укажите E-mail получателя тестового письма.", + "settings.mail_testing": "Отправляем тестовое письмо…", + "settings.mail_test_ok": "Тестовое письмо успешно отправлено.", + "settings.user_email": "E-mail", + "settings.user_email_help": "Необязательно. Нужен только для самостоятельного восстановления пароля.", + "settings.change_email": "E-mail", + "settings.user_email_saved": "E-mail сохранён.", + "settings.send_password_reset": "Отправить сброс", + "settings.user_reset_mail_not_configured": "Сначала настройте и включите почту.", + "settings.user_reset_email_missing": "Сначала укажите E-mail пользователя.", + "settings.user_reset_confirm": "Отправить код сброса пароля пользователю {name} на {email}?", + "settings.user_reset_sent": "Код сброса пароля отправлен на {email}.", + "audit.action.auth.password_reset_requested": "Запрошен сброс пароля", + "audit.action.auth.password_reset_code_sent": "Код сброса отправлен", + "audit.action.auth.password_reset_completed": "Пароль восстановлен", + "audit.action.auth.password_reset_failed": "Ошибка сброса пароля", + "audit.action.mail.settings_updated": "Настройки почты изменены", + "audit.action.mail.test_sent": "Тестовое письмо отправлено", + "audit.action.mail.test_failed": "Ошибка тестового письма", + "audit.action.user.email_changed": "E-mail пользователя изменён", + "audit.action.user.password_reset_sent": "Сброс пароля пользователю отправлен", + "audit.action.user.password_reset_failed": "Не удалось отправить сброс пароля", + "audit.result.accepted": "принято", + "audit.result.sent": "отправлено", + "audit.result.invalid_code": "неверный код", + "common.copy": "Копировать", + "common.copied": "Скопировано", + "clients.use_panel_host": "Подставить адрес панели", + "clients.use_panel_host_done": "Адрес панели подставлен: {host}", + "clients.use_panel_host_failed": "Не удалось определить адрес панели из строки браузера.", + "settings.tab_https": "HTTPS", + "settings.https_title": "HTTPS", + "settings.https_subtitle": "Встроенный HTTPS Let’s Encrypt для прямого доступа к WGTools без reverse proxy.", + "settings.https_disabled": "Отключено", + "settings.https_enabled": "Включено", + "settings.https_enable": "Включить встроенный HTTPS", + "settings.https_type": "Сертификат для", + "settings.https_domain": "Домен", + "settings.https_public_ip": "Публичный IP", + "settings.https_target": "Домен или публичный IP", + "settings.https_email": "E-mail Let’s Encrypt", + "settings.https_port": "HTTPS-порт", + "settings.https_port80_note": "TCP-порт 80 должен быть открыт из Интернета для выпуска и автоматического продления сертификата. Для самой панели откройте выбранный HTTPS-порт.", + "settings.https_check_ports": "Проверить порты", + "settings.https_certificate": "Сертификат", + "settings.https_certificate_ready": "Готов", + "settings.https_certificate_missing": "Не выпущен", + "settings.https_expires": "Действует до", + "settings.https_renewal": "Автопродление", + "settings.https_renewal_enabled": "Включено", + "settings.https_renewal_disabled": "Отключено", + "settings.https_certificate_path": "Сертификат", + "settings.https_private_key_path": "Приватный ключ", + "settings.https_issue": "Получить / обновить сертификат", + "settings.https_port_free": "Свободен", + "settings.https_port_busy": "Занят", + "settings.https_ports_checked": "Проверка портов завершена.", + "settings.https_target_email_required": "Укажите домен/публичный IP и e-mail Let’s Encrypt.", + "settings.https_issue_confirm": "Получить или обновить сертификат Let’s Encrypt для {target}? Введённые настройки HTTPS будут сохранены. TCP-порт 80 должен быть доступен из Интернета.", + "settings.https_issuing": "Получаем сертификат Let’s Encrypt…", + "settings.https_issue_ok": "Сертификат готов.", + "settings.https_already_enabled": "Встроенный HTTPS уже включён.", + "settings.https_already_disabled": "Встроенный HTTPS уже отключён.", + "settings.https_enable_confirm": "Включить встроенный HTTPS на TCP {port} с путём {path}? WGTools перезапустится, а эта страница переподключится по новому адресу.", + "settings.https_disable_confirm": "Отключить встроенный HTTPS и вернуть WGTools на HTTP?", + "settings.https_switching": "Включаем HTTPS и перезапускаем WGTools…", + "settings.https_switching_http": "Отключаем HTTPS и перезапускаем WGTools…", + "audit.action.https.certificate_issued": "HTTPS-сертификат выпущен", + "audit.action.https.certificate_failed": "Ошибка выпуска HTTPS-сертификата", + "audit.action.https.enabled": "HTTPS включён", + "audit.action.https.disabled": "HTTPS отключён", + "audit.result.issued": "выпущен", + "audit.result.enabled": "включено", + "audit.result.disabled": "отключено", + "settings.https_access_path": "Путь доступа к панели", + "settings.https_access_path_help": "Задайте свой путь. При включённом встроенном HTTPS запросы вне него получают 404.", + "settings.https_enable_fields_required": "Укажите домен/публичный IP, e-mail Let’s Encrypt и путь доступа к панели.", + "settings.https_use_panel_host": "Подставить адрес панели", + "settings.https_reconnecting": "WGTools переключается на новый HTTPS-адрес…", + "server.tab_nodes": "Узлы", + "common.type": "Тип", + "common.status": "Статус", + "common.copy_failed": "Не удалось скопировать", + "clients.vpn_address": "VPN адрес", + "nodes.title": "Узлы WGTools", + "nodes.subtitle": "Объединяйте несколько серверов WGTools в одну защищённую сеть и публикуйте только те сети, которые должны быть доступны другим узлам.", + "nodes.enable_hub": "Включить HUB", + "nodes.connect_hub": "Подключиться к HUB", + "nodes.settings": "Настройки узла", + "nodes.settings_action": "Настройки", + "nodes.sync_now": "Синхронизировать", + "nodes.disable": "Отключить узлы", + "nodes.disable_action": "Отключить", + "nodes.join_title": "Подключение новых узлов", + "nodes.join_help": "Создайте одноразовый код и введите его на другой панели WGTools вместе со служебным endpoint HUB, например vpn.example.com:51950. Код действует 15 минут и используется один раз.", + "nodes.create_code": "Создать код", + "nodes.connected_nodes": "Связанные узлы", + "nodes.connected_nodes_help": "Информация о других панелях, их опубликованных сетях и клиентах. Клиенты удалённых панелей доступны только для просмотра.", + "nodes.enable_hub_help": "Эта панель станет центральным узлом. На одном номере порта HUB принимает UDP WireGuard и защищённый TCP для первоначального pairing.", + "nodes.node_name": "Имя узла", + "nodes.transport_network": "Служебная сеть узлов", + "nodes.transport_help": "Отдельная приватная сеть только для связи WGTools ↔ WGTools. Не должна пересекаться с вашими VPN/LAN сетями.", + "nodes.panel_url": "Адрес панели", + "nodes.panel_url_help": "Необязательно. Это только информационная ссылка для кнопки «Открыть панель» на других узлах и она никак не участвует в работе Nodes.", + "nodes.extra_networks": "Дополнительные сети узла", + "nodes.extra_networks_help": "По одной сети в строке. VPN-сети интерфейсов и удалённые сети Site-to-site клиентов публикуются автоматически. Здесь добавляются только остальные маршрутизируемые LAN/сети, например 192.168.50.0/24.", + "nodes.published_networks_select_help": "WGTools подставляет найденные VPN-сети, сети Site-to-Site и локальные маршрутизируемые LAN. Оставьте только те сети, которые этот узел должен публиковать в Nodes. По одной сети в строке.", + "nodes.published_networks_settings_help": "По одной сети в строке. Здесь хранится явный список сетей, которые узел публикует в Nodes. Удалённая строка перестаёт распространяться на другие узлы.", + "nodes.available_networks_help": "Сейчас обнаружены: {networks}. Новые сети не публикуются автоматически — добавьте нужные в список выше.", + "nodes.available_networks_none": "Дополнительных локальных сетей сейчас не обнаружено.", + "nodes.connect_help": "Введите служебный endpoint HUB и одноразовый код. Адрес веб-панели, её HTTPS-порт, сертификат и приватный путь для подключения Nodes не используются.", + "nodes.join_code": "Код подключения", + "nodes.connect_reachability_note": "Первоначальный pairing идёт по защищённому TCP на указанном порту. После создания wgnode0 списки сетей, статусы, версии и read-only данные клиентов синхронизируются с HUB по его служебному адресу внутри WireGuard-туннеля.", + "nodes.connect": "Подключить", + "nodes.settings_help": "Имя узла, необязательная ссылка «Открыть панель» и явный список публикуемых сетей. Адрес панели не используется для pairing или синхронизации Nodes.", + "nodes.details": "Подробнее", + "nodes.not_configured": "WGTools Nodes не настроены", + "nodes.not_configured_help": "Включите HUB на этой панели или подключите её к уже существующему WGTools HUB.", + "nodes.mode_hub": "HUB", + "nodes.mode_spoke": "Подключён к HUB", + "nodes.mode_none": "Не настроено", + "nodes.role": "Роль", + "nodes.tunnel": "Туннель узлов", + "nodes.node_ip": "Адрес узла", + "nodes.endpoint": "Endpoint HUB", + "nodes.published_networks": "Опубликованные сети", + "nodes.last_sync": "Последняя синхронизация", + "nodes.no_nodes_hub": "Пока нет подключённых узлов. Создайте код подключения и используйте его на другой панели WGTools.", + "nodes.no_nodes_spoke": "Информация об удалённых узлах ещё не получена.", + "nodes.clients_short": "Клиенты", + "nodes.open_panel": "Открыть панель", + "nodes.route_conflict": "Конфликт маршрутов", + "nodes.no_published_networks": "Нет опубликованных сетей", + "nodes.load_failed": "Не удалось загрузить WGTools Nodes", + "nodes.enable_hub_confirm": "Включить WGTools HUB и создать служебный WireGuard-туннель узлов?", + "nodes.applying": "Настраиваем служебный туннель WGTools Nodes…", + "nodes.enable_failed": "Не удалось включить HUB", + "nodes.hub_enabled": "WGTools HUB включён", + "nodes.connecting": "Проверяем код HUB и создаём защищённый туннель узлов…", + "nodes.connect_failed": "Не удалось подключиться к HUB", + "nodes.connected": "Подключено к WGTools HUB", + "nodes.settings_failed": "Не удалось сохранить настройки узла", + "nodes.settings_saved": "Настройки узла сохранены", + "nodes.code_failed": "Не удалось создать код подключения", + "nodes.code_expires": "Одноразовый код. Действует до {time}.", + "nodes.code_copied": "Код подключения скопирован", + "nodes.network_vpn": "VPN-клиенты", + "nodes.network_site_to_site": "Сеть Site-to-site", + "nodes.network_custom": "Дополнительная сеть", + "nodes.conflict": "Конфликт", + "nodes.remote_clients": "Клиенты (только чтение)", + "nodes.no_clients": "Узел не передал список клиентов", + "nodes.details_failed": "Не удалось загрузить информацию об узле", + "nodes.remove_confirm": "Удалить узел «{name}» из HUB? Его доступ через служебный туннель будет отозван.", + "nodes.remove_failed": "Не удалось удалить узел", + "nodes.removed": "Узел удалён", + "nodes.disable_hub_confirm": "Отключить HUB и отсоединить все WGTools Nodes? Служебный туннель будет удалён.", + "nodes.disconnect_confirm": "Отключить эту панель WGTools от HUB и удалить служебный туннель?", + "nodes.disable_failed": "Не удалось отключить WGTools Nodes", + "nodes.disabled": "WGTools Nodes отключены", + "nodes.sync_failed": "Не удалось синхронизировать узел", + "nodes.synced": "Информация об узлах синхронизирована", + "nodes.service_port": "Порт Nodes", + "nodes.service_port_help": "Один номер порта используется одновременно: UDP — WireGuard, TCP — защищённое первоначальное подключение.", + "nodes.hub_port_forward_note": "Если HUB находится за NAT, пробросьте на него один и тот же порт и по UDP, и по TCP. Веб-порт WGTools, HTTPS и приватный путь панели к Nodes не относятся.", + "nodes.hub_endpoint": "HUB", + "nodes.hub_endpoint_help": "Домен или IP и порт Nodes без http:// и https://, например vpn.example.com:51950.", + "settings.collapse_sidebar": "Свернуть панель", + "settings.expand_sidebar": "Развернуть панель", + "settings.https_issue_fields_required": "Укажите домен/публичный IP, e-mail Let’s Encrypt и путь доступа к панели.", + "settings.https_issue_ok_saved": "Сертификат готов, настройки HTTPS сохранены.", + "settings.https_enable_need_certificate": "Сначала получите сертификат.", + "settings.https_enable_certificate_mismatch": "Для текущего домена или публичного IP нужно получить сертификат.", + "settings.https_enable_certificate_expired": "Сертификат истёк. Обновите его перед включением HTTPS.", + "settings.https_enable_certificate_ready": "Сертификат готов — встроенный HTTPS можно включить.", + "settings.https_enable_active_help": "Снимите флажок и сохраните, чтобы вернуться на HTTP.", + "settings.https_certificate_expired": "Истёк", + "settings.https_certificate_wrong_target": "Для другого адреса", + "nodes.network_conflict_error": "Опубликованные сети конфликтуют с другим узлом или служебной сетью Nodes: {conflicts}. Удалите или измените конфликтующую сеть.", + "nodes.networks_changed": "Обнаруженные сети изменились после последнего сохранения. Новые: {added}. Больше не обнаруживаются: {removed}. Проверьте список опубликованных сетей и сохраните настройки после проверки.", + "nodes.review_networks": "Проверьте сети", + "nodes.vpn_pool_mismatch": "VPN-пул изменён: в Nodes всё ещё опубликовано {old}, а текущий VPN-пул WireGuard — {current}. Откройте настройки узла и обновите список опубликованных сетей.", + "server.error_vpn_network_invalid": "VPN-сеть должна быть корректной IPv4-сетью, например 10.0.0.0/24.", + "server.error_vpn_ipv4_only": "Поддерживаются только IPv4 VPN-сети.", + "server.error_vpn_network_too_small": "VPN-сеть должна содержать как минимум два доступных адреса.", + "server.error_vpn_network_no_hosts": "В выбранной VPN-сети нет доступных адресов для сервера.", + "server.error_server_address_prefix": "VPN-адрес сервера должен содержать префикс, например 10.0.0.1/24.", + "server.error_server_address_network": "VPN-адрес сервера должен принадлежать выбранному пулу VPN-адресов и использовать тот же префикс.", + "server.error_server_address_reserved": "VPN-адрес сервера не может быть адресом сети или широковещательным адресом.", + "server.error_listen_port_number": "Порт WireGuard должен быть числом.", + "server.error_listen_port_range": "Порт WireGuard должен быть в диапазоне от 1 до 65535.", + "server.error_mtu_number": "MTU должен быть числом.", + "auth.mfa_title": "Двухфакторная аутентификация", + "auth.mfa_login_help": "Введите 6-значный код из Google Authenticator или один из резервных кодов.", + "auth.mfa_code": "Код аутентификации", + "auth.mfa_verify": "Проверить и войти", + "auth.mfa_back": "Вернуться к паролю", + "settings.user_mfa": "MFA", + "settings.mfa_title": "Двухфакторная аутентификация (MFA)", + "settings.mfa_button": "MFA", + "settings.mfa_enabled": "Включена", + "settings.mfa_disabled": "Отключена", + "settings.mfa_google_help": "Защитите эту учётную запись с помощью Google Authenticator или другого TOTP-приложения. Для начала настройки нужен текущий пароль.", + "settings.current_password": "Текущий пароль", + "settings.mfa_start": "Настроить Google Authenticator", + "settings.mfa_secret": "Ключ для ручной настройки", + "settings.mfa_scan_help": "Отсканируйте QR-код в Google Authenticator, затем введите текущий 6-значный код для включения MFA.", + "settings.mfa_code": "6-значный код", + "settings.mfa_enable": "Включить MFA", + "settings.mfa_manage_help": "Для изменения MFA введите текущий пароль и код Google Authenticator или резервный код.", + "settings.mfa_code_or_recovery": "Код Authenticator или резервный код", + "settings.mfa_regenerate": "Новые резервные коды", + "settings.mfa_disable": "Отключить MFA", + "settings.mfa_recovery_title": "Резервные коды", + "settings.mfa_recovery_help": "Сохраните эти коды сейчас. Каждый код можно использовать один раз, если Google Authenticator недоступен. Повторно они не показываются.", + "settings.mfa_recovery_remaining": "Осталось резервных кодов: {count}", + "settings.mfa_enabled_ok": "MFA включена.", + "settings.mfa_disabled_ok": "MFA отключена.", + "settings.mfa_disable_confirm": "Отключить двухфакторную аутентификацию для этой учётной записи?", + "settings.mfa_regenerate_confirm": "Заменить все существующие резервные коды?", + "settings.mfa_recovery_regenerated": "Созданы новые резервные коды.", + "audit.action.auth.mfa_failed": "Ошибка проверки MFA", + "audit.action.auth.mfa_recovery_used": "Использован резервный код MFA", + "audit.action.user.mfa_setup_started": "Начата настройка MFA", + "audit.action.user.mfa_enabled": "MFA включена", + "audit.action.user.mfa_disabled": "MFA отключена", + "audit.action.user.mfa_disabled_cli": "MFA отключена через CLI", + "audit.action.user.mfa_recovery_regenerated": "Резервные коды MFA обновлены", + "settings.mfa_error_password": "Неверный текущий пароль.", + "settings.mfa_error_code": "Неверный код аутентификации.", + "settings.mfa_error_already_enabled": "MFA уже включена.", + "settings.mfa_error_not_enabled": "MFA не включена.", + "settings.mfa_error_not_started": "Начните настройку MFA заново.", + "trace.title": "Traceroute, ping и карта маршрута", + "trace.subtitle": "Проверка задержки до VPS или другого сервера и поиск участка маршрута, где растёт ping.", + "trace.target": "IP или имя сервера", + "trace.show_map": "Показать маршрут на карте", + "trace.run": "Запустить", + "trace.geo_note": "Геолокация приблизительная. Если карта включена, публичные IP узлов отправляются в ipwho.is для определения координат; тайлы карты загружаются с OpenStreetMap.", + "trace.latency_note": "Traceroute измеряет задержку в миллисекундах, а не пропускную способность в Мбит/с.", + "trace.map": "Карта маршрута", + "trace.map_hint": "Интерактивная карта: перетаскивайте мышью, масштабируйте колесом или кнопками +/− и нажимайте на узлы для деталей.", + "trace.hop": "Узел / IP", + "trace.location": "Расположение", + "trace.avg_rtt": "Средний RTT", + "trace.delta": "Δ RTT", + "trace.loss": "Потери", + "trace.summary_target": "Цель", + "trace.summary_ping": "Средний ping", + "trace.summary_loss": "Потери ping", + "trace.summary_hops": "Узлов", + "trace.no_reply": "Нет ответа", + "trace.private": "Локальная сеть", + "trace.unknown": "Неизвестно", + "trace.running": "Выполняются ping и traceroute… Это может занять до минуты.", + "trace.done": "Проверка маршрута завершена.", + "trace.failed": "Не удалось выполнить traceroute", + "trace.partial_geo": "Для части публичных узлов не удалось определить геолокацию.", + "trace.not_reached": "Traceroute не дошёл до конечного адреса.", + "trace.reached": "Цель достигнута", + "trace.ms": "мс", + "server.tab_trace": "Маршрут", + "trace.map_controls": "Управление картой", + "trace.zoom_in": "Приблизить", + "trace.zoom_out": "Отдалить", + "trace.fit_route": "Показать весь маршрут", + "trace.fit": "Весь маршрут", + "trace.map_click_hint": "Нажмите на узел, чтобы увидеть IP, расположение, ASN и RTT.", + "trace.route_path": "Маршрут", + "trace.ping_ok_trace_filtered": "Цель отвечает на ping; конечные узлы traceroute не отвечают.", + "trace.latency_legend": "Рост задержки между отвечающими узлами", + "trace.latency_ok": "Δ RTT ≤ 5 мс — нормально", + "trace.latency_warn": "Δ RTT 5–20 мс — рост", + "trace.latency_bad": "Δ RTT > 20 мс — резкий скачок" +} diff --git a/app/telegram_bot.py b/app/telegram_bot.py new file mode 100644 index 0000000..e273274 --- /dev/null +++ b/app/telegram_bot.py @@ -0,0 +1,1383 @@ +from __future__ import annotations + +import html +import io +import json +import mimetypes +import os +import re +import sys +import time +import urllib.error +import urllib.request +import uuid +from typing import Any + +import qrcode + +from app.core.audit import list_audit_page, write_audit +from app.core.helper import HelperError, run_helper +from app.core.settings import WG_INTERFACE +from app.core.preferences import get_preferences +from app.core.telegram_config import ( + get_telegram_settings, + init_telegram_settings, + set_default_endpoint, + set_update_offset, + telegram_api_call, + update_telegram_runtime, +) + +PENDING: dict[int, dict[str, Any]] = {} +SELECTED_INTERFACES: dict[int, str] = {} + +BOT_TEXT = { + "en": { + "audit": "🧾 Audit", + "audit_title": "🧾 Audit history", + "audit_empty": "No audit entries yet.", + "audit_older": "➡️", + "audit_newer": "⬅️", + "audit_footer": "Records are kept for 30 days.", + "audit_bad_cursor": "Audit page is unavailable. Open the latest records.", + "interface": "🧩 Interface", + "server": "⚙ Server", + "server_controls": "WireGuard server · {interface}\nChoose an action:", + "choose_interface": "Choose the WireGuard interface to manage:", + "interface_selected": "Interface selected: {name}", + "welcome": "WGTools Telegram control is ready. Choose an action:", + "private_only": "For security, WGTools works only in a private chat with the bot.", + "denied": "Access denied. Your Telegram user ID is: {user_id}\nAdd this ID in WGTools → Settings → Telegram Bot.", + "menu": "Main menu", + "status": "📊 Server status", + "clients": "👥 Clients", + "create": "➕ Create client", + "delete": "➖ Delete client", + "configs": "📄 Configs", + "choose_config": "Choose a client. 📄 = configuration available, 🔒 = an older peer whose private key is not stored by WGTools.", + "no_configs": "No clients configured.", + "legacy_config_unavailable": "🔒 WGTools cannot recreate this older client configuration because the server does not have the client's private key. Only clients created by WGTools can be reissued as .conf/QR.", + "sending_config": "Preparing configuration for {name}…", + "config_sent": "✅ Configuration sent: {name}", + "start": "Start", + "restart": "Restart", + "stop": "Stop", + "cancel": "Cancel", + "back": "⬅️ Menu", + "running": "Running", + "stopped": "Stopped", + "online": "online", + "offline": "offline", + "blocked_schedule": "blocked by schedule", + "blocked_expired": "expired / blocked", + "never": "never", + "status_body": "🛡 WireGuard: {state}\nInterface: {interface}\nVPN address: {address}\nPort: {port}\nPeers: {online}/{total} online\nCPU: {cpu}%\nRAM: {memory}%\nNetwork: ↓ {rx}/s · ↑ {tx}/s\nUptime: {uptime}", + "clients_title": "👥 Clients ({total})", + "no_clients": "No clients configured.", + "choose_create_group": "Choose a group for the new client, or continue without a group:", + "create_no_group": "Without group", + "create_name": "Send a name for the new peer. Send /cancel to stop.", + "create_endpoint": "The public server address/domain is not configured. Send it now (for example vpn.example.com). It will be saved as the default. Send /cancel to stop.", + "creating": "Creating client…", + "created": "✅ Client created\nName: {name}{group_line}\nVPN address: {address}\nRoutes: {routes}\nEndpoint: {endpoint}", + "config_unavailable": "The peer was created, but a client configuration could not be generated: {error}", + "choose_delete": "Choose the client to delete:", + "confirm_delete": "Delete peer “{name}” ({address})? A backup of the selected WireGuard interface configuration will be created first.", + "deleted": "✅ Client deleted: {name}", + "deleting": "Deleting client…", + "already_deleted": "ℹ️ Client is already deleted.", + "working": "Working…", + "confirm_stop": "Stop WireGuard? Active VPN clients will be disconnected.", + "confirm_restart": "Restart WireGuard? Active clients will reconnect automatically.", + "started": "✅ WireGuard started.", + "stopped_ok": "✅ WireGuard stopped.", + "restarted": "✅ WireGuard restarted.", + "yes": "Yes", + "no": "No", + "cancelled": "Cancelled.", + "error": "⚠️ {error}", + "unknown": "Use the buttons or /menu.", + "endpoint_saved": "Server address saved: {endpoint}", + "managed_conf": "Client configuration", + }, + "ru": { + "audit": "🧾 Аудит", + "audit_title": "🧾 История аудита", + "audit_empty": "Записей аудита пока нет.", + "audit_older": "➡️", + "audit_newer": "⬅️", + "audit_footer": "Срок хранения записей — 30 дней.", + "audit_bad_cursor": "Страница аудита недоступна. Откройте последние записи.", + "interface": "🧩 Интерфейс", + "server": "⚙ Сервер", + "server_controls": "Сервер WireGuard · {interface}\nВыберите действие:", + "choose_interface": "Выберите интерфейс WireGuard для управления:", + "interface_selected": "Выбран интерфейс: {name}", + "welcome": "WGTools Telegram готов к работе. Выберите действие:", + "private_only": "Для безопасности WGTools работает только в личном чате с ботом.", + "denied": "Доступ запрещён. Ваш Telegram user ID: {user_id}\nДобавьте этот ID в WGTools → Настройки → Telegram Bot.", + "menu": "Главное меню", + "status": "📊 Состояние сервера", + "clients": "👥 Клиенты", + "create": "➕ Создать клиента", + "delete": "➖ Удалить клиента", + "configs": "📄 Конфиги", + "choose_config": "Выберите клиента. 📄 — конфиг доступен, 🔒 — старый peer, приватный ключ которого не хранится в WGTools.", + "no_configs": "Клиенты не настроены.", + "legacy_config_unavailable": "🔒 WGTools не может заново собрать конфигурацию этого старого клиента: на сервере нет его приватного ключа. Повторно выдавать .conf/QR можно только для клиентов, созданных WGTools.", + "sending_config": "Готовлю конфигурацию для {name}…", + "config_sent": "✅ Конфигурация отправлена: {name}", + "start": "Пуск", + "restart": "Перезапуск", + "stop": "Стоп", + "cancel": "Отмена", + "back": "⬅️ Меню", + "running": "Работает", + "stopped": "Остановлен", + "online": "онлайн", + "offline": "офлайн", + "blocked_schedule": "заблокирован расписанием", + "blocked_expired": "срок истёк / заблокирован", + "never": "никогда", + "status_body": "🛡 WireGuard: {state}\nИнтерфейс: {interface}\nVPN-адрес: {address}\nПорт: {port}\nКлиенты: {online}/{total} онлайн\nCPU: {cpu}%\nRAM: {memory}%\nСеть: ↓ {rx}/с · ↑ {tx}/с\nUptime: {uptime}", + "clients_title": "👥 Клиенты ({total})", + "no_clients": "Клиенты не настроены.", + "choose_create_group": "Выберите группу для нового клиента или продолжите без группы:", + "create_no_group": "Без группы", + "create_name": "Отправьте имя нового peer. Для отмены отправьте /cancel.", + "create_endpoint": "Публичный адрес/домен сервера не настроен. Отправьте его сейчас (например vpn.example.com). Он будет сохранён как адрес по умолчанию. Для отмены отправьте /cancel.", + "creating": "Создаю клиента…", + "created": "✅ Клиент создан\nИмя: {name}{group_line}\nVPN-адрес: {address}\nМаршруты: {routes}\nEndpoint: {endpoint}", + "config_unavailable": "Peer создан, но готовый клиентский конфиг получить не удалось: {error}", + "choose_delete": "Выберите клиента для удаления:", + "confirm_delete": "Удалить peer «{name}» ({address})? Перед изменением будет создана резервная копия конфигурации выбранного WireGuard-интерфейса.", + "deleted": "✅ Клиент удалён: {name}", + "deleting": "Удаляю клиента…", + "already_deleted": "ℹ️ Клиент уже удалён.", + "working": "Выполняю…", + "confirm_stop": "Остановить WireGuard? Активные VPN-клиенты будут отключены.", + "confirm_restart": "Перезапустить WireGuard? Активные клиенты подключатся снова автоматически.", + "started": "✅ WireGuard запущен.", + "stopped_ok": "✅ WireGuard остановлен.", + "restarted": "✅ WireGuard перезапущен.", + "yes": "Да", + "no": "Нет", + "cancelled": "Отменено.", + "error": "⚠️ {error}", + "unknown": "Используйте кнопки или команду /menu.", + "endpoint_saved": "Адрес сервера сохранён: {endpoint}", + "managed_conf": "Конфигурация клиента", + }, +} + + +def lang_for(user: dict[str, Any] | None, settings: dict[str, Any]) -> str: + configured = str(settings.get("language") or "auto") + if configured in {"en", "ru"}: + return configured + code = str((user or {}).get("language_code") or "").lower() + return "ru" if code.startswith("ru") else "en" + + +def tr(lang: str, key: str, **kwargs: Any) -> str: + text = BOT_TEXT.get(lang, BOT_TEXT["en"]).get(key, BOT_TEXT["en"].get(key, key)) + try: + return text.format(**kwargs) + except Exception: + return text + + +def fmt_bytes(value: Any) -> str: + try: + n = float(value or 0) + except (TypeError, ValueError): + n = 0 + units = ["B", "KB", "MB", "GB", "TB"] + i = 0 + while n >= 1024 and i < len(units) - 1: + n /= 1024.0 + i += 1 + return f"{n:.1f} {units[i]}" if i else f"{int(n)} B" + + +def fmt_uptime(value: Any) -> str: + try: + seconds = max(0, int(value or 0)) + except (TypeError, ValueError): + seconds = 0 + days, seconds = divmod(seconds, 86400) + hours, seconds = divmod(seconds, 3600) + minutes = seconds // 60 + if days: + return f"{days}d {hours}h" + if hours: + return f"{hours}h {minutes}m" + return f"{minutes}m" + + +def selected_interface(user_id: int) -> str: + value = str(SELECTED_INTERFACES.get(int(user_id)) or WG_INTERFACE).strip() + return value or WG_INTERFACE + + +def interface_keyboard(lang: str, user_id: int) -> dict[str, Any]: + current = selected_interface(user_id) + try: + data = run_helper("interfaces_list", interface=current) + items = [item for item in data.get("interfaces") or [] if item.get("configured")] + except Exception: + items = [] + rows: list[list[dict[str, str]]] = [] + for item in items[:30]: + name = str(item.get("name") or "") + if not name: + continue + alias = str(item.get("display_name") or "").strip() + label = f"{name} · {alias}" if alias and alias != name else name + state = "🟢" if item.get("running") else "🔴" + current_mark = "✓ " if name == current else "" + rows.append([{"text": f"{current_mark}{state} {label}"[:60], "callback_data": f"iface:{name}"}]) + rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}]) + return {"inline_keyboard": rows} + + +def main_keyboard(lang: str, user_id: int = 0) -> dict[str, Any]: + return { + "inline_keyboard": [ + [ + {"text": f"{tr(lang, 'interface')}: {selected_interface(user_id)}", "callback_data": "interfaces"}, + {"text": tr(lang, "server"), "callback_data": "server"}, + ], + [{"text": tr(lang, "status"), "callback_data": "status"}, {"text": tr(lang, "clients"), "callback_data": "clients"}], + [{"text": tr(lang, "create"), "callback_data": "create"}, {"text": tr(lang, "delete"), "callback_data": "delete"}], + [{"text": tr(lang, "configs"), "callback_data": "configs"}, {"text": tr(lang, "audit"), "callback_data": "audit:latest"}], + ] + } + + +def server_controls_text(lang: str, user_id: int) -> str: + return tr(lang, "server_controls", interface=selected_interface(user_id)) + + +def server_keyboard(lang: str) -> dict[str, Any]: + return { + "inline_keyboard": [ + [ + {"text": tr(lang, "start"), "callback_data": "start", "style": "success"}, + {"text": tr(lang, "restart"), "callback_data": "restart", "style": "primary"}, + {"text": tr(lang, "stop"), "callback_data": "stop", "style": "danger"}, + ], + [{"text": tr(lang, "back"), "callback_data": "menu"}], + ] + } + + +def server_controls_screen(lang: str, user_id: int, prefix: str = "") -> tuple[str, dict[str, Any]]: + return picker_text(prefix, server_controls_text(lang, user_id)), server_keyboard(lang) + + +def back_keyboard(lang: str) -> dict[str, Any]: + return {"inline_keyboard": [[{"text": tr(lang, "back"), "callback_data": "menu"}]]} + + +def send_message(token: str, chat_id: int, text: str, reply_markup: dict[str, Any] | None = None, *, parse_mode: str | None = None) -> Any: + payload: dict[str, Any] = {"chat_id": chat_id, "text": text, "disable_web_page_preview": True} + if parse_mode: + payload["parse_mode"] = parse_mode + if reply_markup is not None: + payload["reply_markup"] = reply_markup + return telegram_api_call(token, "sendMessage", payload, timeout=15) + + +def edit_message(token: str, chat_id: int, message_id: int, text: str, reply_markup: dict[str, Any] | None = None) -> Any: + payload: dict[str, Any] = {"chat_id": chat_id, "message_id": message_id, "text": text, "disable_web_page_preview": True} + if reply_markup is not None: + payload["reply_markup"] = reply_markup + try: + return telegram_api_call(token, "editMessageText", payload, timeout=15) + except Exception as exc: + if "message is not modified" not in str(exc).lower(): + raise + return None + + +def answer_callback(token: str, callback_id: str, text: str = "") -> None: + payload: dict[str, Any] = {"callback_query_id": callback_id} + if text: + payload["text"] = text[:180] + try: + telegram_api_call(token, "answerCallbackQuery", payload, timeout=10) + except Exception: + pass + + +def clear_inline_keyboard(token: str, chat_id: int, message_id: int) -> None: + """Best-effort removal of stale inline buttons before a long/destructive action.""" + if chat_id <= 0 or message_id <= 0: + return + try: + telegram_api_call( + token, + "editMessageReplyMarkup", + {"chat_id": chat_id, "message_id": message_id, "reply_markup": {"inline_keyboard": []}}, + timeout=10, + ) + except Exception: + pass + + +def edit_or_send( + token: str, + chat_id: int, + message_id: int, + text: str, + reply_markup: dict[str, Any] | None = None, +) -> Any: + """Append bot screens to chat history instead of replacing the previous screen. + + Keeps the earlier status, clients and action results readable and reusable. + Only pending confirmation buttons are invalidated after use. + """ + result = send_message(token, chat_id, text, reply_markup) + if isinstance(result, dict): + for state in PENDING.values(): + if int(state.get("chat_id") or 0) == chat_id and int(state.get("message_id") or 0) == message_id: + state["message_id"] = int(result.get("message_id") or 0) + break + return result + + +def pending_prompt(state: dict[str, Any]) -> tuple[int, int]: + return int(state.get("chat_id") or 0), int(state.get("message_id") or 0) + + +def update_pending_prompt( + token: str, + state: dict[str, Any], + fallback_chat_id: int, + text: str, + reply_markup: dict[str, Any] | None = None, +) -> Any: + prompt_chat, prompt_message = pending_prompt(state) + return edit_or_send(token, prompt_chat or fallback_chat_id, prompt_message, text, reply_markup) + + +def send_next_pending_prompt( + token: str, + state: dict[str, Any], + chat_id: int, + text: str, + reply_markup: dict[str, Any] | None = None, +) -> Any: + """After a user text reply, send the next bot prompt below it and retire the previous inline keyboard.""" + prompt_chat, prompt_message = pending_prompt(state) + clear_inline_keyboard(token, prompt_chat or chat_id, prompt_message) + result = send_message(token, chat_id, text, reply_markup) + if isinstance(result, dict): + new_message_id = int(result.get("message_id") or 0) + if new_message_id > 0: + state["chat_id"] = chat_id + state["message_id"] = new_message_id + return result + + +def multipart_call(token: str, method: str, fields: dict[str, Any], file_field: str, filename: str, content: bytes, content_type: str) -> Any: + boundary = f"----WGTools{uuid.uuid4().hex}" + body = io.BytesIO() + for key, value in fields.items(): + body.write(f"--{boundary}\r\n".encode()) + body.write(f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode()) + if isinstance(value, (dict, list)): + value = json.dumps(value, ensure_ascii=False) + body.write(str(value).encode("utf-8")) + body.write(b"\r\n") + body.write(f"--{boundary}\r\n".encode()) + body.write(f'Content-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n'.encode("utf-8")) + body.write(f"Content-Type: {content_type}\r\n\r\n".encode()) + body.write(content) + body.write(b"\r\n") + body.write(f"--{boundary}--\r\n".encode()) + data = body.getvalue() + req = urllib.request.Request( + f"https://api.telegram.org/bot{token}/{method}", + data=data, + headers={"Content-Type": f"multipart/form-data; boundary={boundary}", "Content-Length": str(len(data)), "User-Agent": "WGTools/Telegram"}, + ) + try: + with urllib.request.urlopen(req, timeout=30) as resp: + result = json.loads(resp.read().decode("utf-8", "replace")) + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace") + raise RuntimeError(f"Telegram HTTP {exc.code}: {detail[:500]}") from exc + except urllib.error.URLError as exc: + raise RuntimeError(f"Telegram connection failed: {exc.reason}") from exc + if not result.get("ok"): + raise RuntimeError(str(result.get("description") or "Telegram upload failed")) + return result.get("result") + + +def send_client_files(token: str, chat_id: int, config_data: dict[str, Any], lang: str) -> None: + config_text = str(config_data.get("config") or "") + filename = str(config_data.get("filename") or "wireguard-client.conf") + multipart_call(token, "sendDocument", {"chat_id": chat_id, "caption": tr(lang, "managed_conf")}, "document", filename, config_text.encode("utf-8"), "text/plain") + qr = qrcode.make(config_text) + stream = io.BytesIO() + qr.save(stream, format="PNG") + multipart_call(token, "sendPhoto", {"chat_id": chat_id}, "photo", "wireguard-qr.png", stream.getvalue(), "image/png") + + +def is_private(update: dict[str, Any]) -> bool: + message = update.get("message") or (update.get("callback_query") or {}).get("message") or {} + chat = message.get("chat") or {} + return chat.get("type") == "private" + + +def actor(update: dict[str, Any]) -> dict[str, Any]: + return (update.get("callback_query") or {}).get("from") or (update.get("message") or {}).get("from") or {} + + +def chat_id_from(update: dict[str, Any]) -> int: + message = update.get("message") or (update.get("callback_query") or {}).get("message") or {} + return int((message.get("chat") or {}).get("id") or 0) + + +def allowed(update: dict[str, Any], settings: dict[str, Any]) -> bool: + user_id = int(actor(update).get("id") or 0) + return user_id > 0 and user_id in set(settings.get("allowed_user_ids") or []) + + +def telegram_audit_actor(user: dict[str, Any] | None) -> str: + data = user or {} + user_id = int(data.get("id") or 0) + username = str(data.get("username") or "").strip().lstrip("@") + if username: + return f"Telegram · @{username} · ID {user_id}" + return f"Telegram · ID {user_id}" + + +def telegram_audit( + user: dict[str, Any] | None, + action: str, + *, + object: str = "", + result: str = "ok", + details: dict[str, Any] | None = None, +) -> None: + data = user or {} + user_id = int(data.get("id") or 0) + username = str(data.get("username") or "").strip().lstrip("@") + payload: dict[str, Any] = dict(details or {}) + payload["source"] = "telegram" + payload["telegram_user_id"] = user_id + if username: + payload["telegram_username"] = username + try: + write_audit( + telegram_audit_actor(data), + action, + object=object, + result=result, + details=payload, + ) + except Exception: + # Audit logging must never break an administrative Telegram action. + pass + + +def telegram_audit_failure( + user: dict[str, Any] | None, + operation: str, + exc: Exception, + *, + interface: str = "", + object: str = "", +) -> None: + target = object or operation + if interface: + target = f"{interface} · {target}" + telegram_audit( + user, + "telegram.action_failed", + object=target, + result=f"error: {exc}", + details={"operation": operation, "interface": interface}, + ) + + +def telegram_state_change_attempt(update: dict[str, Any]) -> str: + callback = update.get("callback_query") or {} + data = str(callback.get("data") or "") + if data == "start": + return "WireGuard start" + if data == "stop_yes": + return "WireGuard stop" + if data == "restart_yes": + return "WireGuard restart" + if data.startswith("delyes:"): + return "Delete client" + user_id = int(actor(update).get("id") or 0) + pending = PENDING.get(user_id) or {} + if update.get("message") and str(pending.get("step") or "") in {"name", "endpoint"}: + return "Create client" + return "" + + +def audit_denied_telegram_action(update: dict[str, Any]) -> None: + operation = telegram_state_change_attempt(update) + if not operation: + return + user = actor(update) + user_id = int(user.get("id") or 0) + iface = selected_interface(user_id) if user_id else WG_INTERFACE + telegram_audit( + user, + "telegram.action_denied", + object=f"{iface} · {operation}", + result="denied", + details={"operation": operation, "interface": iface}, + ) + + +def server_status_text(lang: str, user_id: int) -> str: + iface = selected_interface(user_id) + d = run_helper("snapshot", interface=iface) + prefs = get_preferences() + now = time.time() + threshold = int(prefs.get("online_threshold_seconds") or 180) + peers = d.get("peers") or [] + online_count = sum( + 1 + for p in peers + if not bool(p.get("schedule_disabled")) + and not bool(p.get("expired_disabled")) + and int(p.get("latest_handshake") or 0) > 0 + and now - int(p.get("latest_handshake") or 0) <= threshold + ) + metrics = d.get("metrics") or {} + cpu = metrics.get("cpu") or {} + mem = metrics.get("memory") or {} + net = metrics.get("network") or {} + interface_cfg = (d.get("config") or {}).get("interface") or {} + return tr( + lang, + "status_body", + state=tr(lang, "running" if d.get("running") else "stopped"), + interface=d.get("interface") or "wg0", + address=interface_cfg.get("address") or "—", + port=d.get("listen_port") or interface_cfg.get("listen_port") or "—", + online=online_count, + total=len(peers), + cpu=f"{float(cpu.get('percent') or 0):.1f}", + memory=f"{float(mem.get('percent') or 0):.1f}", + rx=fmt_bytes(net.get("rx_bytes_per_second")), + tx=fmt_bytes(net.get("tx_bytes_per_second")), + uptime=fmt_uptime(metrics.get("uptime_seconds")), + ) + + +def clients_text(lang: str, user_id: int) -> str: + iface = selected_interface(user_id) + d = run_helper("snapshot", interface=iface) + prefs = get_preferences() + now = time.time() + threshold = int(prefs.get("online_threshold_seconds") or 180) + peers = d.get("peers") or [] + if not peers: + return tr(lang, "no_clients") + lines = [tr(lang, "clients_title", total=len(peers)), ""] + for p in peers[:50]: + hs = int(p.get("latest_handshake") or 0) + schedule_blocked = bool(p.get("schedule_disabled")) + expired_blocked = bool(p.get("expired_disabled")) + is_on = not schedule_blocked and not expired_blocked and hs > 0 and now - hs <= threshold + icon = "🟢" if is_on else ("⛔" if schedule_blocked or expired_blocked else "🔴") + line = f"{icon} {p.get('name') or 'Peer'} · {p.get('vpn_address') or '—'}" + if p.get("group_name"): + line += f" · [{p.get('group_name')}]" + if schedule_blocked: + line += f" · {tr(lang, 'blocked_schedule')}" + elif expired_blocked: + line += f" · {tr(lang, 'blocked_expired')}" + if is_on and p.get("endpoint"): + line += f"\n ↳ {p.get('endpoint')}" + lines.append(line) + if len(peers) > 50: + lines.append(f"… +{len(peers)-50}") + return "\n".join(lines) + + +# Human-friendly event labels; unknown event types remain readable as identifiers. +AUDIT_ACTIONS = { + "client.created": ("Client created", "Клиент создан"), + "client.deleted": ("Client deleted", "Клиент удалён"), + "client.updated": ("Client updated", "Клиент изменён"), + "client.config_viewed": ("Client configuration opened", "Конфигурация открыта"), + "wireguard.client_connected": ("Client connected", "Клиент подключился"), + "wireguard.started": ("WireGuard started", "WireGuard запущен"), + "wireguard.stopped": ("WireGuard stopped", "WireGuard остановлен"), + "wireguard.restarted": ("WireGuard restarted", "WireGuard перезапущен"), + "auth.login": ("User signed in", "Вход пользователя"), + "auth.login_failed": ("Login failed", "Ошибка входа"), + "telegram.action_failed": ("Telegram action failed", "Ошибка команды Telegram"), + "telegram.action_denied": ("Telegram action denied", "Действие Telegram запрещено"), +} + + +AUDIT_ICONS = { + "client.created": "➕", + "client.deleted": "🗑️", + "client.updated": "✏️", + "client.config_viewed": "📄", + "wireguard.client_connected": "🟢", + "wireguard.started": "🟢", + "wireguard.stopped": "🔴", + "wireguard.restarted": "🔄", + "auth.login": "🔓", + "auth.login_failed": "⚠️", + "telegram.action_failed": "⚠️", + "telegram.action_denied": "⛔", +} + + +def _audit_html(value: Any, max_length: int) -> str: + """Escape untrusted audit values before inserting them into Telegram HTML.""" + clean = " ".join(str(value or "").split())[:max_length] + return html.escape(clean, quote=True) + + +def audit_screen(lang: str, page: dict[str, Any]) -> tuple[str, dict[str, Any]]: + """Readable, safely escaped Telegram HTML for a read-only audit page.""" + items = list(page.get("items") or [])[:20] + title = tr(lang, "audit_title").removeprefix("🧾 ").strip() + heading = f"🧾 {_audit_html(title, 65)}" + footer = f"{_audit_html(tr(lang, 'audit_footer'), 120)}" + variants = [] + for item in items: + date = time.strftime("%d.%m %H:%M", time.localtime(int(item.get("created_at") or 0))) + event = str(item.get("action") or "event") + label = AUDIT_ACTIONS.get(event, (event.replace(".", " / "), event.replace(".", " / ")))[0 if lang == "en" else 1] + actor = _audit_html(item.get("username") or "system", 40) + target = _audit_html(item.get("object"), 56) + outcome_raw = " ".join(str(item.get("result") or "").split()) + routine = {"ok", "created", "deleted", "started", "stopped", "restarted", "shown", "success", "connected", "updated"} + outcome = "" if outcome_raw.casefold() in routine else _audit_html(outcome_raw, 36) + icon = AUDIT_ICONS.get(event, "▫️") + stamp = f"{date}" + action = f"{icon} {_audit_html(label, 50)}" + detail = (f" · {target}" if target else "") + (f" · {outcome}" if outcome else "") + full = f"{stamp} · {actor}\n{action}{detail}" + compact = f"{stamp} · {_audit_html(item.get('username') or 'system', 22)}\n{action}" + minimal = f"{stamp}\n{icon} {_audit_html(label, 30)}" + variants.append((full, compact, minimal)) + + if not items: + body = _audit_html(tr(lang, "audit_empty"), 140) + else: + selected = [variants[i][0] for i in range(len(variants))] + def render() -> str: + return "\n\n".join([heading, *selected, footer]) + # Keep all 20 records, reducing optional metadata as needed. Never slice HTML tags. + for level in (1, 2): + for i in range(len(selected) - 1, -1, -1): + if len(render()) <= 3900: + break + selected[i] = variants[i][level] + body = "\n\n".join(selected) + text = "\n\n".join([heading, body, footer]) + + buttons = [] + if items: + if page.get("has_newer"): + buttons.append({"text": tr(lang, "audit_newer"), "callback_data": f"audit:after:{items[0]['id']}"}) + if page.get("has_older"): + buttons.append({"text": tr(lang, "audit_older"), "callback_data": f"audit:before:{items[-1]['id']}"}) + rows = [buttons] if buttons else [] + rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}]) + return text, {"inline_keyboard": rows} + + +def delete_keyboard(lang: str, peers: list[dict[str, Any]]) -> dict[str, Any]: + rows: list[list[dict[str, str]]] = [] + for p in peers[:40]: + name = str(p.get("name") or "Peer")[:32] + addr = str(p.get("vpn_address") or "")[:20] + key = str(p.get("public_key") or "") + if key: + rows.append([{"text": f"🗑 {name} · {addr}", "callback_data": f"delpick:{key}"}]) + rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}]) + return {"inline_keyboard": rows} + + +def config_keyboard(lang: str, peers: list[dict[str, Any]]) -> dict[str, Any]: + rows: list[list[dict[str, str]]] = [] + for p in peers[:40]: + name = str(p.get("name") or "Peer")[:30] + addr = str(p.get("vpn_address") or "")[:20] + key = str(p.get("public_key") or "") + if key: + icon = "📄" if p.get("managed") else "🔒" + rows.append([{"text": f"{icon} {name} · {addr}", "callback_data": f"cfgpick:{key}"}]) + rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}]) + return {"inline_keyboard": rows} + + + + +def picker_text(prefix: str, body: str) -> str: + prefix = str(prefix or "").strip() + return f"{prefix}\n\n{body}" if prefix else body + + +def config_picker(lang: str, peers: list[dict[str, Any]], prefix: str = "") -> tuple[str, dict[str, Any]]: + if not peers: + return picker_text(prefix, tr(lang, "no_configs")), back_keyboard(lang) + return picker_text(prefix, tr(lang, "choose_config")), config_keyboard(lang, peers) + + +def delete_picker(lang: str, peers: list[dict[str, Any]], prefix: str = "") -> tuple[str, dict[str, Any]]: + if not peers: + return picker_text(prefix, tr(lang, "no_clients")), back_keyboard(lang) + return picker_text(prefix, tr(lang, "choose_delete")), delete_keyboard(lang, peers) + + +def current_peers(interface: str) -> list[dict[str, Any]]: + snap = run_helper("snapshot", interface=interface) + return list(snap.get("peers") or []) + + +def create_group_keyboard(lang: str, groups: list[dict[str, Any]]) -> dict[str, Any]: + rows: list[list[dict[str, str]]] = [[{"text": f"— {tr(lang, 'create_no_group')}", "callback_data": "creategroup:none"}]] + for group in groups[:40]: + group_id = str(group.get("id") or "") + if not group_id: + continue + name = str(group.get("name") or group_id)[:48] + rows.append([{"text": f"👥 {name}", "callback_data": f"creategroup:{group_id}"}]) + rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}]) + return {"inline_keyboard": rows} + + +def handle_message(update: dict[str, Any], settings: dict[str, Any], token: str, lang: str) -> None: + message = update.get("message") or {} + chat_id = int((message.get("chat") or {}).get("id") or 0) + user_id = int((message.get("from") or {}).get("id") or 0) + text = str(message.get("text") or "").strip() + + if text in {"/start", "/menu"}: + state = PENDING.pop(user_id, None) + if state: + prompt_chat, prompt_message = pending_prompt(state) + clear_inline_keyboard(token, prompt_chat or chat_id, prompt_message) + send_message(token, chat_id, tr(lang, "welcome"), main_keyboard(lang, user_id)) + return + + if text == "/audit": + state = PENDING.pop(user_id, None) + if state: + prompt_chat, prompt_message = pending_prompt(state) + clear_inline_keyboard(token, prompt_chat or chat_id, prompt_message) + screen, keyboard = audit_screen(lang, list_audit_page(limit=20)) + send_message(token, chat_id, screen, keyboard, parse_mode="HTML") + return + + if text == "/cancel": + state = PENDING.pop(user_id, None) + if state: + prompt_chat, prompt_message = pending_prompt(state) + clear_inline_keyboard(token, prompt_chat or chat_id, prompt_message) + send_message(token, chat_id, tr(lang, "cancelled"), main_keyboard(lang, user_id)) + return + + pending = PENDING.get(user_id) + if not pending: + send_message(token, chat_id, tr(lang, "unknown"), main_keyboard(lang, user_id)) + return + + if pending.get("step") == "name": + name = text.strip() + if not name or len(name) > 64 or any(ord(ch) < 32 for ch in name): + send_next_pending_prompt( + token, + pending, + chat_id, + f"{tr(lang, 'error', error='Peer name must be 1–64 characters.')}\n\n{tr(lang, 'create_name')}", + back_keyboard(lang), + ) + return + endpoint = str(settings.get("default_endpoint") or "").strip() + pending["name"] = name + if not endpoint: + pending["step"] = "endpoint" + send_next_pending_prompt(token, pending, chat_id, tr(lang, "create_endpoint"), back_keyboard(lang)) + return + finish_create( + user_id, + chat_id, + token, + lang, + settings, + name, + endpoint, + str(pending.get("interface") or selected_interface(user_id)), + str(pending.get("group_id") or ""), + pending, + message.get("from") or {}, + ) + return + + if pending.get("step") == "endpoint": + endpoint = text.strip() + try: + set_default_endpoint(endpoint) + telegram_audit( + message.get("from") or {}, + "telegram.settings_updated", + object="Default client endpoint", + result="saved", + details={"setting": "default_endpoint"}, + ) + except Exception as exc: + telegram_audit_failure(message.get("from") or {}, "Update default client endpoint", exc) + send_next_pending_prompt( + token, + pending, + chat_id, + f"{tr(lang, 'error', error=str(exc))}\n\n{tr(lang, 'create_endpoint')}", + back_keyboard(lang), + ) + return + name = str(pending.get("name") or "Peer") + settings = get_telegram_settings(include_token=True) + finish_create( + user_id, + chat_id, + token, + lang, + settings, + name, + endpoint, + str(pending.get("interface") or selected_interface(user_id)), + str(pending.get("group_id") or ""), + pending, + message.get("from") or {}, + ) + return + + PENDING.pop(user_id, None) + update_pending_prompt(token, pending, chat_id, tr(lang, "unknown"), main_keyboard(lang, user_id)) + + +def finish_create( + user_id: int, + chat_id: int, + token: str, + lang: str, + settings: dict[str, Any], + name: str, + endpoint_host: str, + iface: str, + group_id: str = "", + state: dict[str, Any] | None = None, + actor_user: dict[str, Any] | None = None, +) -> None: + state = dict(state or {}) + PENDING.pop(user_id, None) + send_next_pending_prompt(token, state, chat_id, tr(lang, "creating"), {"inline_keyboard": []}) + + try: + snapshot = run_helper("snapshot", interface=iface) + port = int(snapshot.get("listen_port") or ((snapshot.get("config") or {}).get("interface") or {}).get("listen_port") or 51820) + endpoint = f"{endpoint_host}:{port}" + group = next((g for g in snapshot.get("client_groups") or [] if str(g.get("id") or "") == group_id), None) if group_id else None + defaults = (group or {}).get("resolved_defaults") or (group or {}).get("defaults") or {} + routes = list(defaults.get("client_allowed_ips") or ["0.0.0.0/0"]) + dns = list(defaults.get("dns") or []) if group else list(settings.get("default_dns") or []) + keepalive = int(defaults.get("persistent_keepalive", 25) or 0) + route_preset = str(defaults.get("route_preset") or "full") + result = run_helper( + "create_client", + { + "name": name, + "type": "client", + "vpn_address": "", + "remote_networks": [], + "persistent_keepalive": keepalive, + "endpoint": endpoint, + "client_allowed_ips": routes, + "route_preset": route_preset, + "dns": dns, + "group_id": str((group or {}).get("id") or ""), + "policy_mode": "inherit" if group else "", + "internet_access": "inherit" if group else "", + "local_access": "inherit" if group else "", + "policy_allow": [], + "policy_deny": [], + # Keep Telegram-created clients aligned with the web UI default. + "use_preshared_key": True, + }, + interface=iface, + ) + except Exception as exc: + telegram_audit_failure(actor_user, "Create client", exc, interface=iface, object=name) + update_pending_prompt(token, state, chat_id, tr(lang, "error", error=str(exc)), main_keyboard(lang, user_id)) + return + + telegram_audit( + actor_user, + "client.created", + object=f"{iface} · {name}", + result="created", + details={ + "interface": iface, + "client_name": name, + "vpn_address": result.get("vpn_address") or "", + "group_id": str((group or {}).get("id") or ""), + }, + ) + public_key = str(result.get("public_key") or "") + group_line = f"\nGroup: {group.get('name')}" if group and lang == "en" else (f"\nГруппа: {group.get('name')}" if group else "") + created_text = tr( + lang, + "created", + name=name, + group_line=group_line, + address=result.get("vpn_address") or "—", + routes=", ".join(routes), + endpoint=endpoint, + ) + update_pending_prompt(token, state, chat_id, created_text, {"inline_keyboard": []}) + + try: + config = run_helper("client_config", {"public_key": public_key}, interface=iface) + send_client_files(token, chat_id, config, lang) + except Exception as exc: + send_message(token, chat_id, tr(lang, "config_unavailable", error=str(exc))) + + # Always end a completed create flow on a fresh main-menu screen below the files. + send_message(token, chat_id, tr(lang, "welcome"), main_keyboard(lang, user_id)) + + +def handle_callback(update: dict[str, Any], settings: dict[str, Any], token: str, lang: str) -> None: + callback = update.get("callback_query") or {} + callback_id = str(callback.get("id") or "") + data = str(callback.get("data") or "") + message = callback.get("message") or {} + chat_id = int((message.get("chat") or {}).get("id") or 0) + message_id = int(message.get("message_id") or 0) + actor_user = callback.get("from") or {} + user_id = int(actor_user.get("id") or 0) + iface = selected_interface(user_id) + answer_callback(token, callback_id) + + if data.startswith("audit:"): + PENDING.pop(user_id, None) + parts = data.split(":") + try: + if data == "audit:latest": + page_data = list_audit_page(limit=20) + elif len(parts) == 3 and parts[1] in {"before", "after"} and parts[2].isdigit() and int(parts[2]) > 0: + anchor = int(parts[2]) + page_data = list_audit_page(**{("before_id" if parts[1] == "before" else "after_id"): anchor}, limit=20) + else: + raise ValueError("Invalid audit cursor") + except (ValueError, OverflowError): + send_message(token, chat_id, tr(lang, "audit_bad_cursor"), main_keyboard(lang, user_id)) + return + text, keyboard = audit_screen(lang, page_data) + send_message(token, chat_id, text, keyboard, parse_mode="HTML") + return + + if data == "menu": + PENDING.pop(user_id, None) + edit_or_send(token, chat_id, message_id, tr(lang, "welcome"), main_keyboard(lang, user_id)) + return + + if data == "interfaces": + PENDING.pop(user_id, None) + edit_or_send(token, chat_id, message_id, tr(lang, "choose_interface"), interface_keyboard(lang, user_id)) + return + + if data == "server": + PENDING.pop(user_id, None) + text, keyboard = server_controls_screen(lang, user_id) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + + if data.startswith("iface:"): + candidate = data.split(":", 1)[1] + listing = run_helper("interfaces_list", interface=iface) + valid = {str(item.get("name") or "") for item in listing.get("interfaces") or [] if item.get("configured")} + if candidate not in valid: + text = picker_text(tr(lang, "error", error="WireGuard interface is no longer available"), tr(lang, "choose_interface")) + edit_or_send(token, chat_id, message_id, text, interface_keyboard(lang, user_id)) + return + SELECTED_INTERFACES[user_id] = candidate + PENDING.pop(user_id, None) + edit_or_send(token, chat_id, message_id, tr(lang, "interface_selected", name=candidate), main_keyboard(lang, user_id)) + return + + if data == "status": + PENDING.pop(user_id, None) + edit_or_send(token, chat_id, message_id, server_status_text(lang, user_id), back_keyboard(lang)) + return + + if data == "clients": + PENDING.pop(user_id, None) + edit_or_send(token, chat_id, message_id, clients_text(lang, user_id), back_keyboard(lang)) + return + + if data == "create": + snap = run_helper("snapshot", interface=iface) + groups = snap.get("client_groups") or [] + PENDING[user_id] = { + "step": "group" if groups else "name", + "created_at": int(time.time()), + "interface": iface, + "group_id": "", + "chat_id": chat_id, + "message_id": message_id, + } + if groups: + edit_or_send(token, chat_id, message_id, tr(lang, "choose_create_group"), create_group_keyboard(lang, groups)) + else: + edit_or_send(token, chat_id, message_id, tr(lang, "create_name"), back_keyboard(lang)) + return + + if data.startswith("creategroup:"): + state = PENDING.get(user_id) or {} + if state.get("step") != "group" or int(state.get("message_id") or 0) != message_id: + PENDING.pop(user_id, None) + edit_or_send(token, chat_id, message_id, tr(lang, "cancelled"), main_keyboard(lang, user_id)) + return + requested = data.split(":", 1)[1] + snap = run_helper("snapshot", interface=str(state.get("interface") or iface)) + groups = snap.get("client_groups") or [] + valid = {str(g.get("id") or "") for g in groups} + group_id = "" if requested == "none" else requested + if group_id and group_id not in valid: + state["step"] = "group" + text = picker_text(tr(lang, "error", error="Client group is no longer available"), tr(lang, "choose_create_group")) + edit_or_send(token, chat_id, message_id, text, create_group_keyboard(lang, groups)) + return + state["group_id"] = group_id + state["step"] = "name" + state["chat_id"] = chat_id + state["message_id"] = message_id + edit_or_send(token, chat_id, message_id, tr(lang, "create_name"), back_keyboard(lang)) + return + + if data == "configs": + PENDING.pop(user_id, None) + peers = current_peers(iface) + text, keyboard = config_picker(lang, peers) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + + if data.startswith("cfgpick:"): + public_key = data.split(":", 1)[1] + peers = current_peers(iface) + peer = next((p for p in peers if p.get("public_key") == public_key), None) + if not peer: + text, keyboard = config_picker(lang, peers, tr(lang, "error", error="Peer not found")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + if not peer.get("managed"): + text, keyboard = config_picker(lang, peers, tr(lang, "legacy_config_unavailable")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + + name = str(peer.get("name") or "Peer") + clear_inline_keyboard(token, chat_id, message_id) + edit_or_send(token, chat_id, message_id, tr(lang, "sending_config", name=name), {"inline_keyboard": []}) + try: + config = run_helper("client_config", {"public_key": public_key}, interface=iface) + send_client_files(token, chat_id, config, lang) + except Exception as exc: + # A document may already have been sent before a QR/upload error. Keep the + # next actionable screen below any emitted files and stay inside Configs. + telegram_audit_failure(actor_user, "Open client config", exc, interface=iface, object=name) + edit_or_send(token, chat_id, message_id, tr(lang, "error", error=str(exc)), {"inline_keyboard": []}) + peers = current_peers(iface) + text, keyboard = config_picker(lang, peers) + send_message(token, chat_id, text, keyboard) + return + + # Config text and QR are one logical disclosure in WGTools, just like the + # combined web modal. Record one audit event after both Telegram files were sent. + telegram_audit( + actor_user, + "client.config_viewed", + object=str(config.get("filename") or name or "client config"), + result="shown", + details={"interface": iface, "client_name": name}, + ) + + # The selected .conf and QR are separate Telegram messages. Do not leave the + # actionable menu above them: retire the old picker, then send a fresh Configs + # picker below the files so the conversation continues in visual order. + edit_or_send(token, chat_id, message_id, tr(lang, "config_sent", name=name), {"inline_keyboard": []}) + peers = current_peers(iface) + text, keyboard = config_picker(lang, peers) + send_message(token, chat_id, text, keyboard) + return + + if data == "delete": + PENDING.pop(user_id, None) + peers = current_peers(iface) + text, keyboard = delete_picker(lang, peers) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + + if data.startswith("delpick:"): + public_key = data.split(":", 1)[1] + peers = current_peers(iface) + peer = next((p for p in peers if p.get("public_key") == public_key), None) + if not peer: + text, keyboard = delete_picker(lang, peers, tr(lang, "error", error="Peer not found")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + keyboard = { + "inline_keyboard": [[ + {"text": tr(lang, "yes"), "callback_data": f"delyes:{public_key}"}, + {"text": tr(lang, "no"), "callback_data": "delete"}, + ]] + } + PENDING[user_id] = { + "step": "confirm_delete", + "created_at": int(time.time()), + "interface": iface, + "public_key": public_key, + "chat_id": chat_id, + "message_id": message_id, + } + edit_or_send( + token, + chat_id, + message_id, + tr(lang, "confirm_delete", name=peer.get("name") or "Peer", address=peer.get("vpn_address") or "—"), + keyboard, + ) + return + + if data.startswith("delyes:"): + public_key = data.split(":", 1)[1] + state = PENDING.get(user_id) or {} + peers = current_peers(iface) + peer = next((p for p in peers if p.get("public_key") == public_key), None) + if state.get("step") != "confirm_delete" or str(state.get("public_key") or "") != public_key or int(state.get("message_id") or 0) != message_id: + # A queued second tap after a successful delete is harmless. A stale confirmation + # after navigation is never allowed to delete a still-existing peer. Return to + # the parent delete picker instead of unexpectedly jumping to the main menu. + prefix = tr(lang, "already_deleted") if not peer else tr(lang, "cancelled") + text, keyboard = delete_picker(lang, peers, prefix) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + PENDING.pop(user_id, None) + if not peer: + text, keyboard = delete_picker(lang, peers, tr(lang, "already_deleted")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + name = str(peer.get("name") or "Peer") + clear_inline_keyboard(token, chat_id, message_id) + edit_or_send(token, chat_id, message_id, tr(lang, "deleting"), {"inline_keyboard": []}) + try: + run_helper("delete_client", {"public_key": public_key}, interface=iface) + except Exception as exc: + telegram_audit_failure(actor_user, "Delete client", exc, interface=iface, object=name) + peers = current_peers(iface) + text, keyboard = delete_picker(lang, peers, tr(lang, "error", error=str(exc))) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + telegram_audit( + actor_user, + "client.deleted", + object=f"{iface} · {name}", + result="deleted", + details={"interface": iface, "client_name": name}, + ) + peers = current_peers(iface) + text, keyboard = delete_picker(lang, peers, tr(lang, "deleted", name=name)) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + + if data == "start": + PENDING.pop(user_id, None) + clear_inline_keyboard(token, chat_id, message_id) + edit_or_send(token, chat_id, message_id, tr(lang, "working"), {"inline_keyboard": []}) + try: + run_helper("wireguard_start", interface=iface) + except Exception as exc: + telegram_audit_failure(actor_user, "Start WireGuard", exc, interface=iface) + text, keyboard = server_controls_screen(lang, user_id, tr(lang, "error", error=str(exc))) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + telegram_audit(actor_user, "wireguard.started", object=iface, result="started", details={"interface": iface}) + text, keyboard = server_controls_screen(lang, user_id, tr(lang, "started")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + + if data == "stop": + PENDING[user_id] = {"step": "confirm_stop", "created_at": int(time.time()), "interface": iface, "chat_id": chat_id, "message_id": message_id} + keyboard = { + "inline_keyboard": [[ + {"text": tr(lang, "yes"), "callback_data": "stop_yes"}, + {"text": tr(lang, "no"), "callback_data": "server"}, + ]] + } + edit_or_send(token, chat_id, message_id, tr(lang, "confirm_stop"), keyboard) + return + + if data == "restart": + PENDING[user_id] = {"step": "confirm_restart", "created_at": int(time.time()), "interface": iface, "chat_id": chat_id, "message_id": message_id} + keyboard = { + "inline_keyboard": [[ + {"text": tr(lang, "yes"), "callback_data": "restart_yes"}, + {"text": tr(lang, "no"), "callback_data": "server"}, + ]] + } + edit_or_send(token, chat_id, message_id, tr(lang, "confirm_restart"), keyboard) + return + + if data == "stop_yes": + state = PENDING.get(user_id) or {} + if state.get("step") != "confirm_stop" or int(state.get("message_id") or 0) != message_id: + text, keyboard = server_controls_screen(lang, user_id, tr(lang, "cancelled")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + PENDING.pop(user_id, None) + clear_inline_keyboard(token, chat_id, message_id) + edit_or_send(token, chat_id, message_id, tr(lang, "working"), {"inline_keyboard": []}) + target_iface = str(state.get("interface") or iface) + try: + run_helper("wireguard_stop", interface=target_iface) + except Exception as exc: + telegram_audit_failure(actor_user, "Stop WireGuard", exc, interface=target_iface) + text, keyboard = server_controls_screen(lang, user_id, tr(lang, "error", error=str(exc))) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + telegram_audit(actor_user, "wireguard.stopped", object=target_iface, result="stopped", details={"interface": target_iface}) + text, keyboard = server_controls_screen(lang, user_id, tr(lang, "stopped_ok")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + + if data == "restart_yes": + state = PENDING.get(user_id) or {} + if state.get("step") != "confirm_restart" or int(state.get("message_id") or 0) != message_id: + text, keyboard = server_controls_screen(lang, user_id, tr(lang, "cancelled")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + PENDING.pop(user_id, None) + clear_inline_keyboard(token, chat_id, message_id) + edit_or_send(token, chat_id, message_id, tr(lang, "working"), {"inline_keyboard": []}) + target_iface = str(state.get("interface") or iface) + try: + run_helper("wireguard_restart", interface=target_iface) + except Exception as exc: + telegram_audit_failure(actor_user, "Restart WireGuard", exc, interface=target_iface) + text, keyboard = server_controls_screen(lang, user_id, tr(lang, "error", error=str(exc))) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + telegram_audit(actor_user, "wireguard.restarted", object=target_iface, result="restarted", details={"interface": target_iface}) + text, keyboard = server_controls_screen(lang, user_id, tr(lang, "restarted")) + edit_or_send(token, chat_id, message_id, text, keyboard) + return + + PENDING.pop(user_id, None) + edit_or_send(token, chat_id, message_id, tr(lang, "unknown"), main_keyboard(lang, user_id)) + +def handle_update(update: dict[str, Any], settings: dict[str, Any], token: str) -> None: + user = actor(update) + lang = lang_for(user, settings) + chat_id = chat_id_from(update) + if chat_id <= 0: + return + if not is_private(update): + audit_denied_telegram_action(update) + try: + send_message(token, chat_id, tr(lang, "private_only")) + except Exception: + pass + return + if not allowed(update, settings): + audit_denied_telegram_action(update) + try: + send_message(token, chat_id, tr(lang, "denied", user_id=int(user.get("id") or 0))) + except Exception: + pass + return + try: + if update.get("callback_query"): + handle_callback(update, settings, token, lang) + elif update.get("message"): + handle_message(update, settings, token, lang) + except Exception as exc: + user_id = int(user.get("id") or 0) + callback = update.get("callback_query") or {} + if callback: + message = callback.get("message") or {} + message_id = int(message.get("message_id") or 0) + PENDING.pop(user_id, None) + clear_inline_keyboard(token, chat_id, message_id) + edit_or_send(token, chat_id, message_id, tr(lang, "error", error=str(exc)), main_keyboard(lang, user_id)) + else: + send_message(token, chat_id, tr(lang, "error", error=str(exc)), main_keyboard(lang, user_id)) + + +def cleanup_pending() -> None: + cutoff = time.time() - 1800 + stale = [uid for uid, state in PENDING.items() if int(state.get("created_at") or 0) < cutoff] + for uid in stale: + PENDING.pop(uid, None) + + +def main() -> int: + init_telegram_settings() + last_token = "" + while True: + try: + settings = get_telegram_settings(include_token=True) + token = str(settings.get("bot_token") or "") + if not settings.get("enabled") or not token: + last_token = "" + time.sleep(3) + continue + if token != last_token: + try: + me = telegram_api_call(token, "getMe", {}, timeout=12) or {} + username = str(me.get("username") or "") + telegram_api_call(token, "deleteWebhook", {"drop_pending_updates": False}, timeout=12) + update_telegram_runtime(bot_username=username, last_error="") + last_token = token + except Exception as exc: + update_telegram_runtime(last_error=str(exc)) + time.sleep(5) + continue + offset = int(settings.get("update_offset") or 0) + updates = telegram_api_call( + token, + "getUpdates", + {"offset": offset, "timeout": 25, "allowed_updates": ["message", "callback_query"]}, + timeout=35, + ) or [] + update_telegram_runtime(last_error="", last_poll_at=int(time.time())) + for update in updates: + update_id = int(update.get("update_id") or 0) + if update_id: + # Persist first so destructive button presses are not replayed after a daemon restart. + set_update_offset(update_id + 1) + settings = get_telegram_settings(include_token=True) + handle_update(update, settings, token) + cleanup_pending() + except KeyboardInterrupt: + return 0 + except Exception as exc: + try: + update_telegram_runtime(last_error=str(exc)) + except Exception: + pass + time.sleep(3) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/app/templates/auth_base.html b/app/templates/auth_base.html new file mode 100644 index 0000000..a3274a1 --- /dev/null +++ b/app/templates/auth_base.html @@ -0,0 +1,30 @@ + + + + + + + + {{ branding.name or 'Panel' }} + + + + + + +
+
+ +
+
{{ branding.name }}
+
+
+
+
+ {% block auth_content %}{% endblock %} +
+ + + diff --git a/app/templates/base.html b/app/templates/base.html new file mode 100644 index 0000000..6b2532c --- /dev/null +++ b/app/templates/base.html @@ -0,0 +1,195 @@ + + + + + + + + {{ branding.name or 'Panel' }} + + + + + + +
+
+ +
+
{{ branding.name }}
+
+
+
+
+ + +
+ {% if current_user %} + + + {% if not current_user or request.state.access.role == 'admin' %}{% endif %} + {% if request.state.access.role == 'admin' %}{% endif %} +
{{ current_user.username }}
+ {% endif %} +
+
+ + + +
+ {% block content %}{% endblock %} +
+ {% if current_user %} + + + + + {% endif %} + + + + {% if current_user %} + + {% endif %} + +
+ + + + + diff --git a/app/templates/clients.html b/app/templates/clients.html new file mode 100644 index 0000000..bd8da70 --- /dev/null +++ b/app/templates/clients.html @@ -0,0 +1,506 @@ +{% extends "base.html" %} +{% block content %} +
+
+

{{ tr('clients.title') }}

+

{{ tr('clients.subtitle') }}

+
+
+ {% if request.state.access.role == 'admin' %}{% endif %} + +
+
+ +
+

Przekierowania portów

Wybierz dostępny adres publiczny i adres klienta tej sieci.

+
+
+ + + + + +
+ + +
+
+
+ +
+
+
+

{{ tr('clients.peers') }}

+

{{ tr('clients.peers_subtitle') }}

+
+
+
+ + +
+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
{{ tr('clients.name') }}{{ tr('groups.group') }}{{ tr('clients.address') }}{{ tr('clients.remote_networks') }}{{ tr('clients.keepalive') }}{{ tr('clients.status') }}{{ tr('clients.handshake') }}RX / TX{{ tr('clients.actions') }}
{{ tr('common.loading') }}
+
+
+ + + + + + + + + + +{% endblock %} diff --git a/app/templates/dashboard.html b/app/templates/dashboard.html new file mode 100644 index 0000000..f40c418 --- /dev/null +++ b/app/templates/dashboard.html @@ -0,0 +1,94 @@ +{% extends "base.html" %} +{% block content %} +
+
+

{{ tr('dashboard.title') }}

+

{{ tr('dashboard.subtitle') }}

+
+
+ + + +
+
+ +
+
+
{{ tr('dashboard.wireguard') }}
+
{{ tr('common.checking') }}
+
wg0——
+
+
+
{{ tr('dashboard.peers') }}
+
0 {{ tr('common.online') }}
+
{{ tr('common.total') }}: 0{{ tr('dashboard.site_to_site') }}: 0
+
+
+
+
{{ tr('dashboard.traffic') }}
+ +
+
↓0 BRX
↑0 BTX
+
+
+
{{ tr('dashboard.routing') }}
+
○{{ tr('server.ip_forwarding') }}
○{{ tr('server.nat') }}
○{{ tr('server.policy_table') }} —
+
+
+ +
+
+
◉{{ tr('dashboard.cpu') }}
+
—%
+
—
+
+
+
+ {{ tr('dashboard.history_min') }}— + {{ tr('dashboard.history_avg') }}— + {{ tr('dashboard.history_max') }}— +
+ +
{{ tr('dashboard.history_24h') }}{{ tr('dashboard.history_now') }}
+
+
+
+
▣{{ tr('dashboard.memory') }}
+
—%
+
—
+
+
+
+ {{ tr('dashboard.history_min') }}— + {{ tr('dashboard.history_avg') }}— + {{ tr('dashboard.history_max') }}— +
+ +
{{ tr('dashboard.history_24h') }}{{ tr('dashboard.history_now') }}
+
+
+
+
⇄{{ tr('dashboard.network') }}
+
↓ RX—
↑ TX—
+
— · —
+
+
+
RX{{ tr('dashboard.history_min') }}—{{ tr('dashboard.history_avg') }}—{{ tr('dashboard.history_max') }}—
+
TX{{ tr('dashboard.history_min') }}—{{ tr('dashboard.history_avg') }}—{{ tr('dashboard.history_max') }}—
+
+ +
{{ tr('dashboard.history_24h') }} · RX / TX{{ tr('dashboard.history_now') }}
+
+
+
+ +
+

{{ tr('dashboard.active_peers') }}

{{ tr('dashboard.active_peers_subtitle') }}

+
{{ tr('clients.name') }}{{ tr('clients.address') }}{{ tr('clients.type') }}{{ tr('clients.status') }}{{ tr('clients.handshake') }}RXTX
{{ tr('common.loading') }}
+
+ +
+

{{ tr('dashboard.activity') }}

{{ tr('dashboard.activity_subtitle') }}

—
+
+
+{% endblock %} diff --git a/app/templates/forgot_password.html b/app/templates/forgot_password.html new file mode 100644 index 0000000..cd4a283 --- /dev/null +++ b/app/templates/forgot_password.html @@ -0,0 +1,36 @@ +{% extends "auth_base.html" %} +{% block auth_content %} +
+
+ +
+

{{ tr('auth.reset_title') }}

+

{{ tr('auth.reset_subtitle') }}

+
+
+ {% if password_recovery_available %} +
+ + + + +
+ + {% else %} +
+
{{ tr('auth.reset_not_configured') }}
+ +
+ {% endif %} +
+{% endblock %} diff --git a/app/templates/login.html b/app/templates/login.html new file mode 100644 index 0000000..df65a7d --- /dev/null +++ b/app/templates/login.html @@ -0,0 +1,31 @@ +{% extends "auth_base.html" %} +{% block auth_content %} +
+
+ +
+

{{ tr('auth.login_title') }}

+

{{ tr('auth.login_subtitle') }}

+
+
+
+ + + {% if password_recovery_available %} + + {% endif %} + + +
+ +
+{% endblock %} diff --git a/app/templates/server.html b/app/templates/server.html new file mode 100644 index 0000000..30a1fc2 --- /dev/null +++ b/app/templates/server.html @@ -0,0 +1,750 @@ +{% extends "base.html" %} +{% block content %} +
+
+

{{ tr('server.title') }}

+

{{ tr('server.subtitle') }}

+
+
+ + +
+
+ +
+

Główny adres IPv4 dla ruchu wychodzącego

Adres musi być przypisany do interfejsu wyjściowego serwera. Puste pole wyłącza regułę SNAT.

+
+
+ + +
+ + +
+
+ +
+

Ograniczenie nasłuchiwania WireGuard

Wybierz adres IPv4, interfejs wejściowy lub oba. Dla tego ograniczenia IPv6 zostanie zablokowane. Puste pola wyłączają ograniczenie.

+
+
+ + +
+ + +
+
+ +
+

Grupy publicznych adresów IPv4

Grupy przydzielają adresy do sieci. Ten sam adres może należeć do wielu grup.

+
+
+ + + +
+ + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +{% endblock %} diff --git a/app/templates/settings.html b/app/templates/settings.html new file mode 100644 index 0000000..aea2309 --- /dev/null +++ b/app/templates/settings.html @@ -0,0 +1,387 @@ +{% extends "base.html" %} +{% block content %} +
+

{{ tr('settings.title') }}

{{ tr('settings.subtitle') }}

+ +
+
+ + + + + + + + +
+ + + +
+
+
+

{{ tr('settings.appearance') }}

+
+ + + +
+
+
+

{{ tr('settings.status') }}

{{ tr('settings.status_help') }}

+
+
+ + + +
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + +{% endblock %} diff --git a/app/templates/setup.html b/app/templates/setup.html new file mode 100644 index 0000000..1999b13 --- /dev/null +++ b/app/templates/setup.html @@ -0,0 +1,21 @@ +{% extends "auth_base.html" %} +{% block auth_content %} +
+
+ +
+

{{ tr('auth.setup_title') }}

+

{{ tr('auth.setup_subtitle') }}

+
+
+
+ + + + +

{{ tr('auth.setup_help') }}

+ + +
+
+{% endblock %} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..814142f --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,83 @@ +# WGTools Architecture + +## Components + +### Web application + +`app/main.py` runs a FastAPI application under Uvicorn. It provides: + +- server-rendered HTML pages; +- authenticated JSON API endpoints; +- local user/session handling; +- orchestration of privileged operations through the helper. + +### Privileged helper + +`scripts/wgtools-helper` contains the privileged operating-system integration. + +It reads and changes WireGuard state, routes, firewall/NAT, backups and server provisioning. Keeping this code in a separate readable file makes privileged behavior easier to audit. + +### Telegram service + +`app/telegram_bot.py` runs as a separate systemd service. It reads Telegram configuration from the same local WGTools state and uses the Telegram Bot API only when enabled. + +### Built-in HTTPS + +The normal `wgtools.service` starts `scripts/wgtools-web`. By default it launches Uvicorn over HTTP on the configured WGTools port. When built-in HTTPS is enabled, the same launcher serves TLS directly on TCP `443` with the Let’s Encrypt `fullchain.pem` and `privkey.pem`; no reverse proxy is bundled. + +Certificate issuance uses the Certbot client from the WGTools virtual environment with standalone HTTP-01 validation on TCP `80`. A dedicated `wgtools-certbot-renew.timer` checks renewal automatically while built-in HTTPS is active, and its deploy hook restarts the WGTools web service after a successful renewal so Uvicorn reloads the certificate. `/etc/letsencrypt` remains host-level state and is deliberately not removed by the normal WGTools uninstaller. + +### WGTools Nodes + +Nodes use a dedicated hidden `wgnode0` WireGuard transport and do not depend on the WGTools web listener. + +- The HUB listens on one numeric Nodes port over **UDP** for WireGuard and independently over **TCP** for the Node control socket. +- Initial pairing uses pinned TLS on the TCP socket. A one-time join code contains a random secret plus the SHA-256 fingerprint of the HUB Node-control certificate, so the Spoke verifies the HUB identity before sending the secret. +- The Spoke supplies the public HUB `host:port`; that same endpoint becomes the WireGuard endpoint. The HUB does not need to know its own public web or panel URL. +- After `wgnode0` is up, sync/leave control requests are sent to the HUB transport address (normally `10.254.240.1`) through the WireGuard tunnel. The HUB accepts steady-state requests only from the transport IP assigned to that Node. +- The optional panel URL is metadata only for the **Open panel** button and is never used for pairing, routing or synchronization. +- Each Node automatically exports its configured interface VPN pools plus configured Site-to-Site peer remote networks. Export membership is configuration-driven rather than handshake-driven. +- For traffic originating from a remote Node's ordinary VPN client pool and terminating in a locally published network, the receiving Node provides destination-scoped return-path MASQUERADE. Site-to-Site/custom LAN sources remain routed without this NAT. +- The HUB control certificate/private key are mirrored into the SQLite Node state so a full `.wgtbackup` restore preserves the identity pinned by existing Spokes. + +### Update job + +The administrator uploads a trusted `.bin` release archive from **Settings → About**. The helper validates the archive, version and required files, then schedules a one-shot systemd job outside the web-service cgroup. No upstream release server is queried. + +Before replacement, the updater creates a full state backup and a separate rollback archive containing the current `/opt/wgtools` application, helper, environment file and systemd units. On installation failure it attempts to restore the previous application. Packages are not cryptographically signed; their origin must be verified by the administrator. + +### Storage + +- `/var/lib/wgtools/wgtools.db` — users, preferences, Telegram settings and WGTools-managed metadata. +- `/var/lib/wgtools/session.key` — session-signing secret. +- `/var/lib/wgtools/backups/` — automatic WireGuard configuration backups. +- `/var/lib/wgtools/migration-backups/` — pre-restore safety backups. +- `/var/lib/wgtools/update-backups/` — pre-update state backups and application rollback archives (last few copies retained). +- `/var/lib/wgtools/update-status.json` — local progress/result of the latest update job. +- `/etc/wireguard/*.conf` — actual WireGuard interface configurations. +- `/etc/wgtools/https.env` and `/etc/wgtools/https.json` — built-in HTTPS runtime/state when configured. +- `/etc/letsencrypt/live/wgtools/` — host-level Let’s Encrypt certificate/key lineage for built-in HTTPS. + +## Configuration ownership + +WGTools distinguishes between: + +- **server-owned rules** — generated from the main Server settings; +- **site-to-site routes** — owned by a specific peer and edited through Clients; +- **WGTools-generated client policy** — for modes such as Full Tunnel except local networks; +- **custom user rules** — explicitly created in the Server firewall/routes UI; +- **advanced/raw configuration** — preserved for direct `wg0.conf` editing. + +This ownership model prevents a row from being edited in one screen while a different screen silently believes it owns the same configuration. + +## Apply strategy + +Peer-only operations can use live WireGuard synchronization where possible. + +Changes involving interface addresses, routing, PostUp/PostDown or other `wg-quick` behavior can require a WireGuard restart. WGTools creates backups before risky operations and attempts rollback when apply fails. + +## Trust boundary + +The browser is not trusted with filesystem/root access. Requests are authenticated by the web application, which then invokes a constrained helper action. The helper validates action arguments before running system changes. + +Because the services currently run as root, a vulnerability in the application can have high impact. Deploy WGTools only on trusted management networks and keep dependencies and WGTools updated. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..b1bca86 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,48 @@ +# Maintainer Release Checklist + +1. Update `VERSION`. +2. Update `CHANGELOG.md`. +3. Confirm the top-level `install.sh` still resolves the latest stable published GitHub Release by default (do not hard-code the new tag). +4. Run local validation: + +```bash +python3 -m compileall -q app scripts/wgtools-helper +python3 -m json.tool app/locales/en.json >/dev/null +python3 -m json.tool app/locales/ru.json >/dev/null +bash -n install.sh scripts/install.sh scripts/uninstall.sh +python3 -m unittest discover -s tests -v +``` + +5. Search the repository for secrets/personal infrastructure before publishing. +6. Before tagging: deploy the exact candidate archive to a disposable Debian/Ubuntu VM. Confirm the installer reaches and completes `[8/8]`, including helper snapshot and migration backup smoke tests, without disrupting WireGuard. This is required in addition to the mocked public-bootstrap unit test. +7. Commit and push to `main`. +8. Create an annotated tag, for example: + +```bash +git tag -a v0.40.4 -m "WGTools v0.40.4" +git push origin v0.40.4 +``` + +9. Create a GitHub Release from that tag and paste the relevant changelog section. +10. After publishing, test the public one-line installer on clean Debian and Ubuntu VMs, and confirm it reaches `[8/8]`. +11. Test backup/restore and a real client connection before marking the release stable. +12. From an installed release that already contains the updater, test **Settings → About → Check for updates / Update WGTools** against the new published release. Verify the pre-update backups, temporary web restart and final version. +13. For the first updater-capable release, a full end-to-end update test can be performed on a disposable VM by installing the release code, temporarily lowering only `/opt/wgtools/VERSION`, then updating back to the real published release. Never use this trick on production. + +## Public project discovery / SEO + +The WGTools admin panel is private software and must not be indexed. The HTML templates carry `noindex,nofollow,noarchive,nosnippet`, rendered HTML adds `X-Robots-Tag`, and `/robots.txt` disallows crawling. Verify this before a public release. + +For the public GitHub repository, use a concise natural-language description rather than keyword stuffing: + +> Self-hosted WireGuard web UI and server management panel for Debian/Ubuntu — clients, Site-to-Site, routing/NAT, Nodes, VPS Relay, monitoring, backups, HTTPS and Telegram. + +Recommended GitHub topics: + +`wireguard`, `wireguard-ui`, `wireguard-manager`, `vpn`, `self-hosted`, `debian`, `ubuntu`, `network-management`, `site-to-site-vpn`, `homelab`, `fastapi`, `systemd` + +Recommended release title: + +`WGTools v0.40.4 — WireGuard Web UI and Server Manager` + +Before publishing, search the repository and screenshots for personal domains/IPs, passwords, tokens, private keys, QR codes and environment-specific hostnames. Keep screenshot filenames and alt text descriptive so GitHub/readme previews remain understandable to both users and search engines. diff --git a/docs/TRANSLATIONS_STATUS.md b/docs/TRANSLATIONS_STATUS.md new file mode 100644 index 0000000..f33a5df --- /dev/null +++ b/docs/TRANSLATIONS_STATUS.md @@ -0,0 +1,38 @@ +# WGTools localization status (v0.40.4) + +WGTools supports seven interface languages, now with full **key parity**: + +| Language | Present keys | Total source keys | Missing keys | +| --- | ---: | ---: | ---: | +| English (en) | 1098 | 1098 | 0 | +| Русский (ru) | 1098 | 1098 | 0 | +| Deutsch (de) | 1098 | 1098 | 0 | +| Français (fr) | 1098 | 1098 | 0 | +| Italiano (it) | 1098 | 1098 | 0 | +| Español (es) | 1098 | 1098 | 0 | +| Polski (pl) | 1098 | 1098 | 0 | + +Each key has a non-empty translation, and `{variables}` are validated against English. +The three distributed copies of each locale JSON file must remain byte-for-byte identical. +Fallback to English remains active for any new key added in future versions. + +**Important:** machine-assisted translations need in-app layout checks and ideally +review by native speakers before declaring linguistic QA complete. Key parity is +not a substitute for human proofreading. Confirm widths, wrapping and safety prompts +in Settings (HTTPS, backup/restore, MFA, Telegram), Server, Clients, Nodes and VPS. + +## Help articles + +Help articles are **not part of the 1098 interface-string keys**. They use +`app/core/help_content.py` (reference RU/EN texts) and additional dedicated +`app/core/help_locales/{de,fr,it,es,pl}.json` files. + +All seven languages have the same four Help sections and 40 topics. The +five new language editions use locally written, concise explanations of the +same features and retain technical examples and security warnings. +`tests/test_help_localization.py` verifies every language is loaded and +matches the reference section/topic structure, so missing files cannot +silently ship as English Help again. + +Linguistic QA and line-breaking on actual mobile/desktop browsers remain +recommended before publishing as stable. diff --git a/docs/screenshots/clients-list.png b/docs/screenshots/clients-list.png new file mode 100644 index 0000000..6a3f21c Binary files /dev/null and b/docs/screenshots/clients-list.png differ diff --git a/docs/screenshots/create-client.png b/docs/screenshots/create-client.png new file mode 100644 index 0000000..4f61f28 Binary files /dev/null and b/docs/screenshots/create-client.png differ diff --git a/docs/screenshots/create-site-to-site.png b/docs/screenshots/create-site-to-site.png new file mode 100644 index 0000000..49d5fff Binary files /dev/null and b/docs/screenshots/create-site-to-site.png differ diff --git a/docs/screenshots/dashboard-interface-selector.png b/docs/screenshots/dashboard-interface-selector.png new file mode 100644 index 0000000..1afee84 Binary files /dev/null and b/docs/screenshots/dashboard-interface-selector.png differ diff --git a/docs/screenshots/first-user-setup.png b/docs/screenshots/first-user-setup.png new file mode 100644 index 0000000..d7d0beb Binary files /dev/null and b/docs/screenshots/first-user-setup.png differ diff --git a/docs/screenshots/server-multi-interface.png b/docs/screenshots/server-multi-interface.png new file mode 100644 index 0000000..28613b6 Binary files /dev/null and b/docs/screenshots/server-multi-interface.png differ diff --git a/docs/screenshots/settings-general.png b/docs/screenshots/settings-general.png new file mode 100644 index 0000000..a2257d8 Binary files /dev/null and b/docs/screenshots/settings-general.png differ diff --git a/docs/screenshots/wgtools-cli.png b/docs/screenshots/wgtools-cli.png new file mode 100644 index 0000000..a9c2e94 Binary files /dev/null and b/docs/screenshots/wgtools-cli.png differ diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..b65f58e --- /dev/null +++ b/install.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +# Instalacja z lokalnego katalogu źródłowego WGTools-Extended. +SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec bash "$SOURCE_DIR/scripts/install.sh" "$@" diff --git a/relay/wgtools-relay-agent.py b/relay/wgtools-relay-agent.py new file mode 100644 index 0000000..ebb780c --- /dev/null +++ b/relay/wgtools-relay-agent.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import asyncio +import json +import os +import socket +import subprocess +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +AGENT_VERSION = "0.1" +STATE_DIR = Path(os.environ.get("WGTOOLS_RELAY_STATE", "/var/lib/wgtools-relay")) +TENANTS_DIR = STATE_DIR / "tenants" +AGENT_FILE = STATE_DIR / "agent.json" +DEFAULT_CONTROL_PORT = 8787 +RELOAD_SECONDS = 2 +MAPPING_IDLE_SECONDS = 300 + + +def load_json(path: Path) -> dict[str, Any]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + return data if isinstance(data, dict) else {} + except Exception: + return {} + + +def write_log(message: str) -> None: + print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {message}", flush=True) + + +def wg_handshake_age(interface: str) -> int | None: + if not interface: + return None + try: + proc = subprocess.run( + ["wg", "show", interface, "latest-handshakes"], + text=True, + capture_output=True, + timeout=2, + check=False, + ) + if proc.returncode != 0: + return None + latest = 0 + for line in proc.stdout.splitlines(): + parts = line.split() + if len(parts) >= 2: + try: + latest = max(latest, int(parts[1])) + except ValueError: + pass + if latest <= 0: + return None + return max(0, int(time.time()) - latest) + except Exception: + return None + + +class UpstreamProtocol(asyncio.DatagramProtocol): + def __init__(self, runtime: "TenantRuntime", client_addr: tuple[str, int]): + self.runtime = runtime + self.client_addr = client_addr + self.transport: asyncio.DatagramTransport | None = None + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.transport = transport # type: ignore[assignment] + + def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None: + self.runtime.last_activity = time.time() + mapping = self.runtime.mappings.get(self.client_addr) + if mapping: + mapping[1] = time.time() + if self.runtime.public_transport is not None: + self.runtime.public_transport.sendto(data, self.client_addr) + + def error_received(self, exc: Exception) -> None: + write_log(f"tenant={self.runtime.tenant_id} upstream error for {self.client_addr}: {exc}") + + +class PublicProtocol(asyncio.DatagramProtocol): + def __init__(self, runtime: "TenantRuntime"): + self.runtime = runtime + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.runtime.public_transport = transport # type: ignore[assignment] + write_log( + f"tenant={self.runtime.tenant_id} UDP relay listening on :{self.runtime.relay_port} " + f"-> {self.runtime.home_transport_ip}:{self.runtime.home_wg_port}" + ) + + def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None: + self.runtime.last_activity = time.time() + asyncio.create_task(self.runtime.forward_from_client(data, addr)) + + def error_received(self, exc: Exception) -> None: + write_log(f"tenant={self.runtime.tenant_id} public UDP error: {exc}") + + +@dataclass +class TenantRuntime: + config_path: Path + config: dict[str, Any] + public_transport: asyncio.DatagramTransport | None = None + control_server: asyncio.AbstractServer | None = None + mappings: dict[tuple[str, int], list[Any]] = field(default_factory=dict) + cleanup_task: asyncio.Task[Any] | None = None + last_activity: float = field(default_factory=time.time) + + @property + def tenant_id(self) -> str: + return str(self.config.get("tenant_id") or self.config_path.parent.name) + + @property + def relay_port(self) -> int: + return int(self.config.get("relay_port") or 0) + + @property + def transport_interface(self) -> str: + return str(self.config.get("transport_interface") or "") + + @property + def relay_transport_ip(self) -> str: + return str(self.config.get("relay_transport_ip") or "") + + @property + def home_transport_ip(self) -> str: + return str(self.config.get("home_transport_ip") or "") + + @property + def home_wg_port(self) -> int: + return int(self.config.get("home_wg_port") or 0) + + @property + def control_token(self) -> str: + return str(self.config.get("control_token") or "") + + @property + def control_port(self) -> int: + return int(self.config.get("control_port") or DEFAULT_CONTROL_PORT) + + def validate(self) -> None: + if not self.tenant_id or not self.relay_port or not self.home_wg_port: + raise ValueError("missing tenant id or UDP ports") + for value in (self.relay_transport_ip, self.home_transport_ip): + socket.inet_aton(value) + if not self.control_token: + raise ValueError("missing control token") + + async def start(self) -> None: + self.validate() + loop = asyncio.get_running_loop() + transport, _ = await loop.create_datagram_endpoint( + lambda: PublicProtocol(self), + local_addr=("0.0.0.0", self.relay_port), + family=socket.AF_INET, + reuse_port=False, + ) + self.public_transport = transport # type: ignore[assignment] + self.control_server = await asyncio.start_server( + self.handle_control, + host=self.relay_transport_ip, + port=self.control_port, + family=socket.AF_INET, + ) + self.cleanup_task = asyncio.create_task(self.cleanup_loop()) + write_log( + f"tenant={self.tenant_id} control API http://{self.relay_transport_ip}:{self.control_port}" + ) + + async def stop(self) -> None: + if self.cleanup_task: + self.cleanup_task.cancel() + if self.control_server: + self.control_server.close() + await self.control_server.wait_closed() + self.control_server = None + for transport, _last_seen in list(self.mappings.values()): + try: + transport.close() + except Exception: + pass + self.mappings.clear() + if self.public_transport: + self.public_transport.close() + self.public_transport = None + write_log(f"tenant={self.tenant_id} stopped") + + async def forward_from_client(self, data: bytes, client_addr: tuple[str, int]) -> None: + now = time.time() + item = self.mappings.get(client_addr) + if item is None: + loop = asyncio.get_running_loop() + try: + transport, _ = await loop.create_datagram_endpoint( + lambda: UpstreamProtocol(self, client_addr), + local_addr=(self.relay_transport_ip, 0), + remote_addr=(self.home_transport_ip, self.home_wg_port), + family=socket.AF_INET, + ) + except Exception as exc: + write_log(f"tenant={self.tenant_id} cannot create upstream for {client_addr}: {exc}") + return + item = [transport, now] + self.mappings[client_addr] = item + else: + item[1] = now + try: + item[0].sendto(data) + except Exception as exc: + write_log(f"tenant={self.tenant_id} forward failed for {client_addr}: {exc}") + + async def cleanup_loop(self) -> None: + while True: + await asyncio.sleep(30) + cutoff = time.time() - MAPPING_IDLE_SECONDS + stale = [addr for addr, (_transport, last_seen) in self.mappings.items() if last_seen < cutoff] + for addr in stale: + transport, _ = self.mappings.pop(addr) + try: + transport.close() + except Exception: + pass + + async def handle_control(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + status = 500 + body: dict[str, Any] = {"ok": False, "error": "invalid request"} + try: + raw = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=3) + if len(raw) > 16384: + raise ValueError("request too large") + text = raw.decode("iso-8859-1", errors="replace") + lines = text.split("\r\n") + request_line = lines[0].split() + if len(request_line) != 3: + raise ValueError("bad request") + method, path, _version = request_line + headers: dict[str, str] = {} + for line in lines[1:]: + if ":" in line: + key, value = line.split(":", 1) + headers[key.strip().lower()] = value.strip() + if headers.get("authorization") != f"Bearer {self.control_token}": + status = 401 + body = {"ok": False, "error": "unauthorized"} + elif method != "GET": + status = 405 + body = {"ok": False, "error": "method not allowed"} + elif path.rstrip("/") == "/v1/health": + agent = load_json(AGENT_FILE) + status = 200 + body = { + "ok": True, + "agent_id": str(agent.get("agent_id") or ""), + "agent_version": str(agent.get("version") or AGENT_VERSION), + "tenant_id": self.tenant_id, + "relay_port": self.relay_port, + "transport_interface": self.transport_interface, + "transport_handshake_age": wg_handshake_age(self.transport_interface), + "active_udp_mappings": len(self.mappings), + "uptime": int(time.monotonic()), + "time": int(time.time()), + } + else: + status = 404 + body = {"ok": False, "error": "not found"} + except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, TimeoutError): + status = 400 + body = {"ok": False, "error": "bad request"} + except Exception as exc: + status = 500 + body = {"ok": False, "error": str(exc)} + payload = json.dumps(body, separators=(",", ":")).encode("utf-8") + reason = {200: "OK", 400: "Bad Request", 401: "Unauthorized", 404: "Not Found", 405: "Method Not Allowed", 500: "Internal Server Error"}.get(status, "Error") + writer.write( + f"HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {len(payload)}\r\nConnection: close\r\n\r\n".encode("ascii") + + payload + ) + try: + await writer.drain() + finally: + writer.close() + try: + await writer.wait_closed() + except Exception: + pass + + +class RelayAgent: + def __init__(self) -> None: + self.runtimes: dict[str, TenantRuntime] = {} + self.signatures: dict[str, tuple[int, int]] = {} + + def tenant_files(self) -> list[Path]: + if not TENANTS_DIR.exists(): + return [] + return sorted(TENANTS_DIR.glob("*/config.json")) + + async def reconcile(self) -> None: + files = self.tenant_files() + wanted = {path.parent.name: path for path in files} + for tenant_id in list(self.runtimes): + if tenant_id not in wanted: + await self.runtimes.pop(tenant_id).stop() + self.signatures.pop(tenant_id, None) + for tenant_id, path in wanted.items(): + try: + stat = path.stat() + sig = (stat.st_mtime_ns, stat.st_size) + except OSError: + continue + if tenant_id in self.runtimes and self.signatures.get(tenant_id) == sig: + continue + if tenant_id in self.runtimes: + await self.runtimes.pop(tenant_id).stop() + config = load_json(path) + if not config.get("enabled", True): + self.signatures[tenant_id] = sig + continue + runtime = TenantRuntime(path, config) + try: + await runtime.start() + except Exception as exc: + write_log(f"tenant={tenant_id} failed to start: {exc}") + continue + self.runtimes[tenant_id] = runtime + self.signatures[tenant_id] = sig + + async def run(self) -> None: + STATE_DIR.mkdir(parents=True, exist_ok=True) + TENANTS_DIR.mkdir(parents=True, exist_ok=True) + write_log("WGTools Relay Agent starting") + while True: + try: + await self.reconcile() + except Exception as exc: + write_log(f"reconcile error: {exc}") + await asyncio.sleep(RELOAD_SECONDS) + + +if __name__ == "__main__": + try: + asyncio.run(RelayAgent().run()) + except KeyboardInterrupt: + pass diff --git a/relay/wgtools-relay-agent.service b/relay/wgtools-relay-agent.service new file mode 100644 index 0000000..494263d --- /dev/null +++ b/relay/wgtools-relay-agent.service @@ -0,0 +1,18 @@ +[Unit] +Description=WGTools Relay Agent +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=root +Group=root +ExecStart=/opt/wgtools-relay/wgtools-relay-agent.py +Restart=always +RestartSec=2 +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true + +[Install] +WantedBy=multi-user.target diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..9b9f7aa --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +fastapi==0.116.1 +uvicorn[standard]==0.35.0 +jinja2==3.1.6 +qrcode[pil]==8.2 + +itsdangerous==2.2.0 +certbot==5.7.0 diff --git a/scripts/full-clean.sh b/scripts/full-clean.sh new file mode 100644 index 0000000..ec4027b --- /dev/null +++ b/scripts/full-clean.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ ${EUID:-$(id -u)} -ne 0 ]]; then + echo "Run as root: sudo bash $0" >&2 + exit 1 +fi + +if [[ "${WGTOOLS_FULL_CLEAN_CONFIRMED:-0}" != "1" ]]; then + cat <<'TXT' +WARNING: FULL CLEANUP removes WGTools, all WireGuard interfaces/configs, +local WGTools Relay state and the WGTools Let's Encrypt certificate from THIS host. +Remote Relay Agents on other VPS hosts are not contacted. +TXT + printf '\nType DELETE ALL to continue: ' + read -r answer + [[ "$answer" == "DELETE ALL" ]] || { echo "Cancelled."; exit 0; } +fi + +echo "[1/7] Stopping WGTools and Relay services..." +for unit in \ + wgtools.service wgtools-telegram.service \ + wgtools-expiry.timer wgtools-expiry.service \ + wgtools-certbot-renew.timer wgtools-certbot-renew.service \ + wg-quick@wgnode0.service +do + systemctl disable --now "$unit" >/dev/null 2>&1 || true +done + +mapfile -t relay_units < <( + systemctl list-unit-files --type=service --no-legend 2>/dev/null \ + | awk '$1 ~ /^wgtools-relay-(agent|transport-|home-)/ {print $1}' \ + | sort -u +) +for unit in "${relay_units[@]}"; do + systemctl disable --now "$unit" >/dev/null 2>&1 || true +done + +echo "[2/7] Bringing down WireGuard interfaces..." +if [[ -d /etc/wireguard ]]; then + shopt -s nullglob + for conf in /etc/wireguard/*.conf; do + iface="$(basename "$conf" .conf)" + systemctl disable --now "wg-quick@${iface}.service" >/dev/null 2>&1 || true + if command -v wg-quick >/dev/null 2>&1; then + wg-quick down "$iface" >/dev/null 2>&1 || true + fi + done + shopt -u nullglob +fi + +# Also stop enabled wg-quick units whose config may already be missing. +while read -r unit _; do + [[ "$unit" == wg-quick@*.service ]] || continue + systemctl disable --now "$unit" >/dev/null 2>&1 || true +done < <(systemctl list-unit-files 'wg-quick@*.service' --no-legend 2>/dev/null || true) + +if command -v wg >/dev/null 2>&1; then + for iface in $(wg show interfaces 2>/dev/null || true); do + ip link delete "$iface" >/dev/null 2>&1 || true + done +fi + +echo "[3/7] Removing WGTools firewall/NAT leftovers..." +if command -v iptables >/dev/null 2>&1; then + # Known direct Nodes rules. + while iptables -C FORWARD -i wgnode0 -j ACCEPT >/dev/null 2>&1; do iptables -D FORWARD -i wgnode0 -j ACCEPT || true; done + while iptables -C FORWARD -o wgnode0 -j ACCEPT >/dev/null 2>&1; do iptables -D FORWARD -o wgnode0 -j ACCEPT || true; done + + # Remove every rule that jumps to a WGTOOLS-* custom chain (including + # source/comment-qualified jumps), then remove the chains themselves. + for table in filter nat mangle; do + mapfile -t chains < <(iptables -t "$table" -S 2>/dev/null | awk '$1=="-N" && $2 ~ /^WGTOOLS-/ {print $2}') + for chain in "${chains[@]}"; do + mapfile -t jump_rules < <(iptables -t "$table" -S 2>/dev/null | grep -E "^-A .* -j ${chain}($| )" || true) + for rule in "${jump_rules[@]}"; do + eval "iptables -t '$table' ${rule/-A /-D }" >/dev/null 2>&1 || true + done + iptables -t "$table" -F "$chain" >/dev/null 2>&1 || true + iptables -t "$table" -X "$chain" >/dev/null 2>&1 || true + done + done + + # Protection rules are direct FORWARD entries carrying a WGTools comment. + mapfile -t protect_rules < <(iptables -S FORWARD 2>/dev/null | grep -- '--comment wgtools-' || true) + for rule in "${protect_rules[@]}"; do + # iptables -S output is generated by the local kernel/iptables, not user input. + eval "iptables ${rule/-A FORWARD/-D FORWARD}" >/dev/null 2>&1 || true + done +fi + +echo "[4/7] Removing WGTools files and systemd units..." +rm -f \ + /etc/systemd/system/wgtools.service \ + /etc/systemd/system/wgtools-telegram.service \ + /etc/systemd/system/wgtools-expiry.service \ + /etc/systemd/system/wgtools-expiry.timer \ + /etc/systemd/system/wgtools-certbot-renew.service \ + /etc/systemd/system/wgtools-certbot-renew.timer \ + /etc/systemd/system/wgtools-relay-agent.service \ + /etc/systemd/system/wgtools-relay-transport-*.service \ + /etc/systemd/system/wgtools-relay-home-*.service \ + /etc/sudoers.d/wgtools \ + /usr/local/libexec/wgtools-helper \ + /usr/local/libexec/wgtools-certbot-reload \ + /usr/local/bin/wgtools \ + /etc/sysctl.d/99-wgtools-wireguard.conf \ + /var/lib/systemd/timers/stamp-wgtools-* + +rm -rf \ + /opt/wgtools \ + /etc/wgtools \ + /var/lib/wgtools \ + /opt/wgtools-relay \ + /var/lib/wgtools-relay \ + /etc/wireguard \ + /tmp/wgtools-install \ + /tmp/wgtools-update* \ + /tmp/wgtools-cli-* \ + /tmp/wgtools-* + +echo "[5/7] Removing WGTools Let's Encrypt certificate..." +if command -v certbot >/dev/null 2>&1; then + certbot delete --cert-name wgtools --non-interactive >/dev/null 2>&1 || true +fi +rm -rf /etc/letsencrypt/live/wgtools /etc/letsencrypt/archive/wgtools +rm -f /etc/letsencrypt/renewal/wgtools.conf + +echo "[6/7] Removing WireGuard packages..." +export DEBIAN_FRONTEND=noninteractive +if command -v apt-get >/dev/null 2>&1; then + apt-get purge -y wireguard wireguard-tools || true + apt-get autoremove -y --purge || true +fi + +echo "[7/7] Reloading system state..." +systemctl daemon-reload +systemctl reset-failed >/dev/null 2>&1 || true +sysctl --system >/dev/null 2>&1 || true + +echo +echo "Done: WGTools, local Relay state, all WireGuard configs/interfaces and WGTools-specific files were removed from this host." +echo "Remote Relay Agents on other VPS hosts were not changed." +echo "Shared OS tools (Python, iproute2, iptables, certbot, OpenSSH) were intentionally preserved." diff --git a/scripts/gitea_release.py b/scripts/gitea_release.py new file mode 100644 index 0000000..65b3842 --- /dev/null +++ b/scripts/gitea_release.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Create a Gitea release from a version tag; the .bin is a gzip tar archive.""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +from urllib.parse import quote +from urllib.request import Request, urlopen +import uuid + + +def main() -> None: + tag = os.environ['GITHUB_REF_NAME'] + if not re.fullmatch(r'v\d+\.\d+\.\d+', tag): + raise ValueError('Tag wydania musi mieć postać v1.2.3') + if Path('VERSION').read_text(encoding='utf-8').strip() != tag[1:]: + raise ValueError('VERSION musi odpowiadać tagowi wydania') + server = os.environ['GITHUB_SERVER_URL'].rstrip('/') + repo = os.environ['GITHUB_REPOSITORY'] + if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', repo): + raise ValueError('Nieprawidłowa nazwa repozytorium') + token = os.environ['GITEA_RELEASE_TOKEN'] + if not token: + raise ValueError('Brakuje sekretu GITEA_RELEASE_TOKEN') + api = f'{server}/api/v1/repos/{repo}/releases' + + def request(url: str, method: str, data: bytes, content_type: str) -> dict: + req = Request(url, data=data, method=method, headers={'Authorization': f'token {token}', 'Content-Type': content_type}) + with urlopen(req, timeout=120) as response: + return json.load(response) + + with tempfile.TemporaryDirectory() as tmp: + package = Path(tmp) / f'WGTools-Extended-{tag[1:]}.bin' + for required in ('VERSION', 'app/main.py', 'scripts/wgtools-helper', 'scripts/install.sh'): + subprocess.run(['git', 'cat-file', '-e', f'HEAD:{required}'], check=True) + subprocess.run(['git', 'archive', '--format=tar.gz', f'--output={package}', 'HEAD'], check=True) + title = f'WGTools-Extended wersja {tag[1:]}' + release = request(api, 'POST', json.dumps({'tag_name': tag, 'name': title, 'body': title, 'draft': True}).encode(), 'application/json') + boundary = 'wgtools' + uuid.uuid4().hex + body = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{package.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + + package.read_bytes() + f'\r\n--{boundary}--\r\n'.encode()) + request(f'{api}/{int(release["id"])}/assets?name={quote(package.name)}', 'POST', body, f'multipart/form-data; boundary={boundary}') + request(f'{api}/{int(release["id"])}', 'PATCH', b'{"draft":false}', 'application/json') + + +if __name__ == '__main__': + main() diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100644 index 0000000..fdcc196 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,238 @@ +#!/usr/bin/env bash +set -euo pipefail + +APP_DIR=/opt/wgtools +# Keep custom settings when upgrading an existing native installation. +# Avoid overriding environment explicitly supplied for a fresh install. +if [[ -r /etc/wgtools/wgtools.env ]]; then + # shellcheck disable=SC1091 + source /etc/wgtools/wgtools.env +fi +WG_INTERFACE="${WG_INTERFACE:-${WGTOOLS_INTERFACE:-wg0}}" +WEB_PORT="${WGTOOLS_PORT:-8341}" +SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +if [[ ${EUID} -ne 0 ]]; then + echo "Run this installer as root." >&2 + exit 1 +fi + +if [[ ! "$WG_INTERFACE" =~ ^[A-Za-z0-9_.-]{1,15}$ ]]; then + echo "Invalid WireGuard interface: $WG_INTERFACE" >&2 + exit 1 +fi + +echo "[1/8] Installing WGTools runtime packages..." +apt-get update +DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-venv python3-pip iproute2 iputils-ping traceroute curl openssh-client sshpass openssl + +echo "[2/8] Preparing directories..." +install -d -o root -g root -m 0755 /var/lib/wgtools /etc/wgtools /usr/local/libexec /usr/local/bin +if [[ ! -s /var/lib/wgtools/session.key ]]; then + python3 - <<'PYSECRET' +from pathlib import Path +import secrets +p=Path('/var/lib/wgtools/session.key') +p.write_text(secrets.token_hex(32), encoding='utf-8') +p.chmod(0o600) +PYSECRET +fi +touch /var/lib/wgtools/wgtools.db +chmod 0600 /var/lib/wgtools/session.key /var/lib/wgtools/wgtools.db + +echo "[3/8] Installing application..." +# Stop only the WGTools web service while replacing its files. WireGuard itself is not touched. +if systemctl is-active --quiet wgtools-telegram.service 2>/dev/null; then + systemctl stop wgtools-telegram.service +fi +if systemctl is-active --quiet wgtools-expiry.timer 2>/dev/null; then + systemctl stop wgtools-expiry.timer +fi +if systemctl is-active --quiet wgtools-certbot-renew.timer 2>/dev/null; then + systemctl stop wgtools-certbot-renew.timer +fi +if systemctl is-active --quiet wgtools.service 2>/dev/null; then + systemctl stop wgtools.service +fi +rm -rf "$APP_DIR" +mkdir -p "$APP_DIR" +cp -a "$SOURCE_DIR"/. "$APP_DIR"/ +rm -rf "$APP_DIR/.git" "$APP_DIR/.github" "$APP_DIR/.venv" "$APP_DIR/.test-deps" "$APP_DIR/tests" +find "$APP_DIR" -type d -name __pycache__ -prune -exec rm -rf {} + 2>/dev/null || true +chown -R root:root "$APP_DIR" + +# Normalize executable bits after archive extraction or Windows/Git workflows. +chmod 0755 "$APP_DIR/scripts/install.sh" "$APP_DIR/scripts/uninstall.sh" "$APP_DIR/scripts/full-clean.sh" "$APP_DIR/scripts/wgtools-web" "$APP_DIR/scripts/wgtools-cli" "$APP_DIR/scripts/wgtools-certbot-reload" "$APP_DIR/scripts/wgtools-helper" + +python3 -m venv "$APP_DIR/.venv" +"$APP_DIR/.venv/bin/pip" install --upgrade pip >/dev/null +"$APP_DIR/.venv/bin/pip" install -r "$APP_DIR/requirements.txt" + +echo "[4/8] Installing root helper..." +install -o root -g root -m 0755 "$APP_DIR/scripts/wgtools-helper" /usr/local/libexec/wgtools-helper +install -o root -g root -m 0755 "$APP_DIR/scripts/wgtools-certbot-reload" /usr/local/libexec/wgtools-certbot-reload +install -o root -g root -m 0755 "$APP_DIR/scripts/wgtools-cli" /usr/local/bin/wgtools + +if [[ ! -f /etc/wgtools/wgtools.env ]]; then + cat > /etc/wgtools/wgtools.env </dev/null +systemctl enable wgtools-telegram.service >/dev/null +systemctl enable wgtools-expiry.timer >/dev/null +if [[ -r /etc/wgtools/https.env ]] && grep -q '^WGTOOLS_HTTPS_ENABLED=1$' /etc/wgtools/https.env; then + systemctl enable wgtools-certbot-renew.timer >/dev/null + systemctl restart wgtools-certbot-renew.timer +fi +systemctl restart wgtools.service +systemctl restart wgtools-expiry.timer + +echo "[6/8] Waiting for web service..." +READY=0 +HTTPS_ENABLED=0 +HTTPS_PORT=443 +WGTOOLS_ACCESS_PATH="" +if [[ -r /etc/wgtools/https.env ]]; then + # shellcheck disable=SC1091 + source /etc/wgtools/https.env + HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}" + HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}" + WGTOOLS_ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-}" +fi +for _ in $(seq 1 25); do + if [[ "$HTTPS_ENABLED" == "1" ]]; then + if curl -kfsS "https://127.0.0.1:${HTTPS_PORT}${WGTOOLS_ACCESS_PATH%/}/healthz" >/dev/null 2>&1; then + READY=1 + break + fi + elif curl -fsS "http://127.0.0.1:${WEB_PORT}/healthz" >/dev/null 2>&1; then + READY=1 + break + fi + sleep 1 +done +if [[ "$READY" -ne 1 ]]; then + echo "WGTools did not become ready. Recent log:" >&2 + journalctl -u wgtools.service -n 60 --no-pager >&2 || true + exit 1 +fi + +echo "[7/8] Starting integrated Telegram bot service..." +systemctl restart wgtools-telegram.service +sleep 1 +if ! systemctl is-active --quiet wgtools-telegram.service; then + echo "WGTools Telegram service did not start. Recent log:" >&2 + journalctl -u wgtools-telegram.service -n 40 --no-pager >&2 || true + exit 1 +fi +echo "Telegram service OK (it stays idle until a BotFather token is enabled in Settings)." + +echo "[8/8] Running helper self-test..." +printf '%s\n' '{"view":"server"}' | timeout --foreground 20s /usr/local/libexec/wgtools-helper snapshot "$WG_INTERFACE" >/tmp/wgtools-selftest.json +python3 - <<'PY' +import json +with open('/tmp/wgtools-selftest.json', encoding='utf-8') as f: + data=json.load(f) +assert data.get('ok') is True, data +wg=data.get('wireguard', {}) +assert isinstance(data.get('route_items', []), list), data +assert isinstance(data.get('firewall_items', []), list), data +assert isinstance(data.get('client_groups', []), list), data +print(f"Helper OK: state={wg.get('state')} interface={data.get('interface')} routes={len(data.get('route_items', []))} firewall={len(data.get('firewall_items', []))}") +PY +rm -f /tmp/wgtools-selftest.json + +# Create and immediately remove a full migration backup as a non-destructive smoke test. +timeout --foreground 60s /usr/local/libexec/wgtools-helper migration_backup_create "$WG_INTERFACE" /tmp/wgtools-migration-selftest.json +python3 - <<'PY' +import json +from pathlib import Path +with open('/tmp/wgtools-migration-selftest.json', encoding='utf-8') as f: + data=json.load(f) +assert data.get('ok') is True, data +p=Path(data.get('path','')) +assert p.is_file() and p.stat().st_size > 0, data +print(f"Migration backup helper OK: {p.name} ({p.stat().st_size} bytes)") +p.unlink() +PY +rm -f /tmp/wgtools-migration-selftest.json + +# Smoke-test the raw configuration helper when a WireGuard config already exists. +# The HTTP API is intentionally protected by authentication from v0.6 onward. +if [[ -f "/etc/wireguard/${WG_INTERFACE}.conf" ]]; then + timeout --foreground 20s /usr/local/libexec/wgtools-helper raw_config_get "$WG_INTERFACE" /tmp/wgtools-raw-config-selftest.json + python3 - <<'PY' +import json +with open('/tmp/wgtools-raw-config-selftest.json', encoding='utf-8') as f: + data=json.load(f) +assert data.get('ok') is True, data +assert isinstance(data.get('content'), str) and '[Interface]' in data.get('content', ''), data +print('Raw config helper OK') +PY + rm -f /tmp/wgtools-raw-config-selftest.json +fi + +echo +echo "WGTools v$(cat "$APP_DIR/VERSION") is installed." +echo "Service account: root (no additional Linux user is created)." +echo "WireGuard is NOT installed by the WGTools deploy script on a clean VM." +echo "If it is missing, install it later from Server -> Install WireGuard." +if [[ "$HTTPS_ENABLED" == "1" ]]; then + HTTPS_OPEN_HOST="" + if [[ -r /etc/wgtools/https.json ]]; then + HTTPS_OPEN_HOST="$(python3 - <<'PYHTTPSHOST' +import json +from pathlib import Path +try: + data=json.loads(Path('/etc/wgtools/https.json').read_text(encoding='utf-8')) + print(str(data.get('target') or '').strip()) +except Exception: + pass +PYHTTPSHOST +)" + fi + if [[ -z "$HTTPS_OPEN_HOST" ]]; then + HTTPS_OPEN_HOST="$(hostname -I | awk '{print $1}')" + fi + if [[ "$HTTPS_OPEN_HOST" == *:* && "$HTTPS_OPEN_HOST" != \[*\] ]]; then + HTTPS_OPEN_HOST="[$HTTPS_OPEN_HOST]" + fi + HTTPS_OPEN_PATH="${WGTOOLS_ACCESS_PATH:-}" + if [[ -n "$HTTPS_OPEN_PATH" && "$HTTPS_OPEN_PATH" != */ ]]; then + HTTPS_OPEN_PATH="${HTTPS_OPEN_PATH}/" + fi + if [[ "$HTTPS_PORT" == "443" ]]; then + echo "Open: https://${HTTPS_OPEN_HOST}${HTTPS_OPEN_PATH}" + else + echo "Open: https://${HTTPS_OPEN_HOST}:${HTTPS_PORT}${HTTPS_OPEN_PATH}" + fi +else + echo "Open: http://$(hostname -I | awk '{print $1}'):${WEB_PORT}" +fi +echo "Web: systemctl status wgtools --no-pager" +echo "Telegram: systemctl status wgtools-telegram --no-pager" +echo "Access: systemctl status wgtools-expiry.timer --no-pager" +echo "Web logs: journalctl -u wgtools -f" +echo "Bot logs: journalctl -u wgtools-telegram -f" +echo "Console: wgtools" diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh new file mode 100644 index 0000000..471f999 --- /dev/null +++ b/scripts/uninstall.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ ${EUID} -ne 0 ]]; then echo "Run as root" >&2; exit 1; fi + +systemctl disable --now wgtools-certbot-renew.timer 2>/dev/null || true +systemctl disable --now wgtools-certbot-renew.service 2>/dev/null || true +systemctl disable --now wgtools-expiry.timer 2>/dev/null || true +systemctl disable --now wgtools-expiry.service 2>/dev/null || true +systemctl disable --now wgtools-telegram.service 2>/dev/null || true +systemctl disable --now wgtools.service 2>/dev/null || true + +# The Nodes tunnel is an internal WGTools transport, not a user WireGuard server. +systemctl disable --now wg-quick@wgnode0.service 2>/dev/null || true +ip link delete wgnode0 2>/dev/null || true +rm -f /etc/wireguard/wgnode0.conf + +# Detach local home-side Relay transports, but preserve /var/lib/wgtools so a +# later reinstall/restore can reconnect to the same remote Relay tenants. +for service in /etc/systemd/system/wgtools-relay-home-*.service; do + [[ -e "$service" ]] || continue + unit="$(basename "$service")" + systemctl disable --now "$unit" 2>/dev/null || true + rm -f "$service" +done + +rm -f \ + /etc/systemd/system/wgtools.service \ + /etc/systemd/system/wgtools-telegram.service \ + /etc/systemd/system/wgtools-expiry.service \ + /etc/systemd/system/wgtools-expiry.timer \ + /etc/systemd/system/wgtools-certbot-renew.service \ + /etc/systemd/system/wgtools-certbot-renew.timer \ + /etc/sudoers.d/wgtools \ + /usr/local/libexec/wgtools-helper \ + /usr/local/libexec/wgtools-certbot-reload \ + /usr/local/bin/wgtools +rm -rf /opt/wgtools /etc/wgtools +systemctl daemon-reload +systemctl reset-failed >/dev/null 2>&1 || true +cat <<'TXT' +WGTools removed. + +Preserved intentionally: + /var/lib/wgtools WGTools users, settings, keys/metadata and backups + /etc/wireguard Normal WireGuard configuration (internal wgnode0 removed) + /etc/letsencrypt Let's Encrypt certificates + WireGuard packages and normal wg-quick services + Remote VPS Relay Agent/tenants + +Reinstalling WGTools can reuse the preserved state. +For a destructive wipe of this host, use the "FULL CLEANUP" action from the +wgtools menu before uninstalling, or run /opt/wgtools/scripts/full-clean.sh +while WGTools is still installed. +TXT diff --git a/scripts/wgtools-certbot-reload b/scripts/wgtools-certbot-reload new file mode 100644 index 0000000..eb7972e --- /dev/null +++ b/scripts/wgtools-certbot-reload @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +/bin/systemctl try-restart wgtools.service diff --git a/scripts/wgtools-cli b/scripts/wgtools-cli new file mode 100644 index 0000000..e81576a --- /dev/null +++ b/scripts/wgtools-cli @@ -0,0 +1,783 @@ +#!/usr/bin/env bash +set -u + +APP_DIR=/opt/wgtools +WG_ENV=/etc/wgtools/wgtools.env +HTTPS_ENV=/etc/wgtools/https.env +HTTPS_STATE=/etc/wgtools/https.json +VERSION_FILE="$APP_DIR/VERSION" +DATABASE_PATH="${WGTOOLS_DB:-/var/lib/wgtools/wgtools.db}" + +if [[ ${EUID:-$(id -u)} -ne 0 ]]; then + echo "Run wgtools as root (or with sudo)." >&2 + exit 1 +fi + +# shellcheck disable=SC1090 +[[ -r "$WG_ENV" ]] && source "$WG_ENV" +# shellcheck disable=SC1090 +[[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV" + +WG_INTERFACE="${WGTOOLS_INTERFACE:-wg0}" +NODE_INTERFACE="wgnode0" +HTTP_PORT="${WGTOOLS_PORT:-8341}" +HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}" +HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}" +ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-}" +VERSION="$(cat "$VERSION_FILE" 2>/dev/null || echo unknown)" + +if [[ -t 1 ]]; then + BOLD='\033[1m'; DIM='\033[2m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; CYAN='\033[36m'; HEADER_RED='\033[38;5;124m'; RESET='\033[0m' +else + BOLD=''; DIM=''; GREEN=''; YELLOW=''; RED=''; CYAN=''; HEADER_RED=''; RESET='' +fi + +service_state_raw() { + local unit="$1" + if systemctl is-active --quiet "$unit" 2>/dev/null; then + printf 'Running' + elif systemctl is-failed --quiet "$unit" 2>/dev/null; then + printf 'Failed' + else + printf 'Stopped' + fi +} + +timer_state_raw() { + local unit="$1" + if systemctl is-active --quiet "$unit" 2>/dev/null; then + printf 'Active' + else + printf 'Inactive' + fi +} + +state_color() { + case "$1" in + Running|Active|Enabled*) printf '%b' "$GREEN" ;; + Failed) printf '%b' "$RED" ;; + Stopped|Inactive|Disabled|"Not configured"|"Not installed") printf '%b' "$YELLOW" ;; + *) printf '%b' "$RESET" ;; + esac +} + +https_target() { + python3 - "$HTTPS_STATE" <<'PY' 2>/dev/null || true +import json,sys +from pathlib import Path +p=Path(sys.argv[1]) +try: + data=json.loads(p.read_text(encoding='utf-8')) + print(str(data.get('target') or '').strip()) +except Exception: + pass +PY +} + +primary_ip() { + hostname -I 2>/dev/null | awk '{print $1}' +} + +panel_url() { + local host path + if [[ "$HTTPS_ENABLED" == "1" ]]; then + host="$(https_target)" + [[ -z "$host" ]] && host="$(primary_ip)" + [[ "$host" == *:* && "$host" != \[*\] ]] && host="[$host]" + path="$ACCESS_PATH" + [[ -n "$path" && "$path" != /* ]] && path="/$path" + [[ -n "$path" && "$path" != */ ]] && path="$path/" + if [[ "$HTTPS_PORT" == "443" ]]; then + printf 'https://%s%s' "$host" "$path" + else + printf 'https://%s:%s%s' "$host" "$HTTPS_PORT" "$path" + fi + else + host="$(primary_ip)" + [[ "$host" == *:* && "$host" != \[*\] ]] && host="[$host]" + printf 'http://%s:%s/' "$host" "$HTTP_PORT" + fi +} + +wireguard_interfaces() { + { + if [[ -d /etc/wireguard ]]; then + for path in /etc/wireguard/*.conf; do + [[ -e "$path" ]] || continue + basename "$path" .conf + done + fi + wg show interfaces 2>/dev/null | tr ' ' '\n' || true + } | awk 'NF && $0 !~ /^wgrly/ && $0 !~ /^wgnode/ {print}' | sort -u +} + +wg_state_for_raw() { + local iface="$1" + if wg show "$iface" >/dev/null 2>&1; then + printf 'Running' + elif [[ -f "/etc/wireguard/${iface}.conf" ]]; then + printf 'Stopped' + else + printf 'Not configured' + fi +} + +node_state_raw() { + if wg show "$NODE_INTERFACE" >/dev/null 2>&1; then + printf 'Running' + elif [[ -f "/etc/wireguard/${NODE_INTERFACE}.conf" ]]; then + printf 'Stopped' + else + printf 'Not configured' + fi +} + +relay_agent_state_raw() { + if systemctl is-active --quiet wgtools-relay-agent.service 2>/dev/null; then + printf 'Running' + elif [[ -e /etc/systemd/system/wgtools-relay-agent.service || -d /opt/wgtools-relay || -d /var/lib/wgtools-relay ]]; then + printf 'Stopped' + else + printf 'Not installed' + fi +} + +cert_expiry() { + local cert=/etc/letsencrypt/live/wgtools/fullchain.pem + [[ -r "$cert" ]] || { printf '—'; return; } + openssl x509 -in "$cert" -noout -enddate 2>/dev/null | sed 's/^notAfter=//' || printf '—' +} + +print_row() { + local label="$1" value="$2" color="${3:-$RESET}" + printf '│ %-22s │ %b%-38s%b │\n' "$label" "$color" "$value" "$RESET" +} + +print_status() { + HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-$HTTPS_ENABLED}" + HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-$HTTPS_PORT}" + ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-$ACCESS_PATH}" + [[ -t 1 ]] && printf '\033c' 2>/dev/null || true + + printf '┌─────────────────────────────────────────────────────────────────┐\n' + printf '│ %bWGTools Management%b - v%-41s │\n' "$BOLD" "$RESET" "$VERSION" + printf '├────────────────────────┬────────────────────────────────────────┤\n' + + local value color iface + value="$(service_state_raw wgtools.service)"; color="$(state_color "$value")"; print_row 'Panel service' "$value" "$color" + + mapfile -t wg_ifaces < <(wireguard_interfaces) + if [[ ${#wg_ifaces[@]} -eq 0 ]]; then + value='Not configured'; color="$(state_color "$value")"; print_row 'WireGuard' "$value" "$color" + else + for iface in "${wg_ifaces[@]}"; do + value="$(wg_state_for_raw "$iface")"; color="$(state_color "$value")"; print_row "WireGuard $iface" "$value" "$color" + done + fi + + value="$(node_state_raw)"; color="$(state_color "$value")"; print_row 'Nodes tunnel' "$value" "$color" + value="$(service_state_raw wgtools-telegram.service)"; color="$(state_color "$value")"; print_row 'Telegram service' "$value" "$color" + value="$(timer_state_raw wgtools-expiry.timer)"; color="$(state_color "$value")"; print_row 'Expiry timer' "$value" "$color" + + if [[ "$HTTPS_ENABLED" == "1" ]]; then + value="Enabled - TCP $HTTPS_PORT"; print_row 'HTTPS' "$value" "$GREEN" + value="$(timer_state_raw wgtools-certbot-renew.timer)"; color="$(state_color "$value")"; print_row 'Renewal timer' "$value" "$color" + print_row 'Panel path' "${ACCESS_PATH:-—}" "$CYAN" + print_row 'Certificate until' "$(cert_expiry)" "$RESET" + else + print_row 'HTTPS' 'Disabled' "$YELLOW" + fi + + if [[ -e /etc/systemd/system/wgtools-relay-agent.service || -d /opt/wgtools-relay || -d /var/lib/wgtools-relay ]]; then + value="$(relay_agent_state_raw)"; color="$(state_color "$value")"; print_row 'Relay agent (local)' "$value" "$color" + fi + + printf '└────────────────────────┴────────────────────────────────────────┘\n' + printf '%bPanel URL:%b %b%s%b\n' "$BOLD" "$RESET" "$CYAN" "$(panel_url)" "$RESET" +} + +format_age() { + local epoch="${1:-0}" now delta + [[ "$epoch" =~ ^[0-9]+$ ]] || { printf 'never'; return; } + (( epoch > 0 )) || { printf 'never'; return; } + now="$(date +%s)" + delta=$(( now - epoch )) + (( delta < 0 )) && delta=0 + if (( delta < 60 )); then + printf '%ss ago' "$delta" + elif (( delta < 3600 )); then + printf '%sm ago' "$((delta / 60))" + elif (( delta < 86400 )); then + printf '%sh ago' "$((delta / 3600))" + else + printf '%sd ago' "$((delta / 86400))" + fi +} + +online_threshold_seconds() { + python3 - "$DATABASE_PATH" "${WGTOOLS_ONLINE_THRESHOLD_SECONDS:-180}" <<'PYTHRESH' 2>/dev/null || printf '180' +import sqlite3, sys +path, default = sys.argv[1], sys.argv[2] +try: + fallback = max(30, min(int(default), 3600)) +except Exception: + fallback = 180 +try: + conn = sqlite3.connect(path) + row = conn.execute("SELECT value FROM app_settings WHERE key='online_threshold_seconds'").fetchone() + conn.close() + value = int(row[0]) if row else fallback + print(max(30, min(value, 3600))) +except Exception: + print(fallback) +PYTHRESH +} + +show_wireguard_status() { + local requested="${1:-}" iface snapshot threshold + mapfile -t interfaces < <(wireguard_interfaces) + if [[ -n "$requested" ]]; then + interfaces=("$requested") + fi + if [[ ${#interfaces[@]} -eq 0 ]]; then + echo "No WireGuard interfaces are configured." + return 1 + fi + + threshold="$(online_threshold_seconds)" + [[ "$threshold" =~ ^[0-9]+$ ]] || threshold=180 + + echo + printf '%bWireGuard status%b\n' "$BOLD" "$RESET" + + for iface in "${interfaces[@]}"; do + if [[ ! -f "/etc/wireguard/${iface}.conf" ]] && ! wg show "$iface" >/dev/null 2>&1; then + printf '\n%s: Not found\n' "$iface" + continue + fi + + snapshot='' + if [[ -x /usr/local/libexec/wgtools-helper ]]; then + snapshot="$(printf '%s\n' '{"view":"clients"}' | /usr/local/libexec/wgtools-helper snapshot "$iface" 2>/dev/null || true)" + fi + + if [[ -n "$snapshot" ]]; then + python3 - "$iface" "$threshold" "$DATABASE_PATH" 3<<<"$snapshot" <<'PYSTATUS' +import json, sqlite3, sys, time + +iface = sys.argv[1] +database_path = sys.argv[3] +try: + threshold = max(30, min(int(sys.argv[2]), 3600)) +except Exception: + threshold = 180 + +try: + data = json.loads(open('/dev/fd/3', encoding='utf-8').read()) +except Exception: + data = {} + +if not isinstance(data, dict) or not data.get('ok'): + raise SystemExit(2) + +now = int(time.time()) +peers = list(data.get('peers') or []) +running = bool(data.get('running')) +config = data.get('config') or {} +interface = config.get('interface') or {} +address = str(interface.get('address') or '—') +port = data.get('listen_port') or interface.get('listen_port') or '—' + +audit = {} +try: + conn = sqlite3.connect(database_path) + rows = conn.execute( + 'SELECT public_key,latest_handshake,endpoint FROM audit_wg_connection_state WHERE interface=?', + (iface,), + ).fetchall() + conn.close() + audit = {str(row[0]): {'latest_handshake': int(row[1] or 0), 'endpoint': str(row[2] or '')} for row in rows} +except Exception: + audit = {} + + +def handshake_epoch(peer): + try: + live = int(peer.get('latest_handshake') or 0) + except Exception: + live = 0 + saved = audit.get(str(peer.get('public_key') or ''), {}) + try: + historical = int(saved.get('latest_handshake') or 0) + except Exception: + historical = 0 + return max(live, historical) + + +def peer_endpoint(peer): + value = str(peer.get('endpoint') or '').strip() + if value: + return value + return str(audit.get(str(peer.get('public_key') or ''), {}).get('endpoint') or '—') + + +def age(epoch): + try: + epoch = int(epoch or 0) + except Exception: + epoch = 0 + if epoch <= 0: + return 'Never' + delta = max(0, now - epoch) + if delta < 60: + return f'{delta}s ago' + if delta < 3600: + return f'{delta // 60}m ago' + if delta < 86400: + return f'{delta // 3600}h ago' + return f'{delta // 86400}d ago' + + +def online(peer): + hs = handshake_epoch(peer) + return bool(running and hs > 0 and now - hs <= threshold) + + +def human_bytes(value): + try: + n = float(int(value or 0)) + except Exception: + n = 0.0 + units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'] + idx = 0 + while n >= 1024 and idx < len(units) - 1: + n /= 1024.0 + idx += 1 + if idx == 0: + return f'{int(n)} {units[idx]}' + if n >= 100: + return f'{n:.0f} {units[idx]}' + if n >= 10: + return f'{n:.1f} {units[idx]}' + return f'{n:.2f} {units[idx]}' + + +def short_key(value): + value = str(value or '') + if len(value) <= 16: + return value or 'Unnamed peer' + return value[:8] + '…' + value[-6:] + +def compact_bytes(value): + try: + n = float(int(value or 0)) + except Exception: + n = 0.0 + units = ['B', 'K', 'M', 'G', 'T'] + idx = 0 + while n >= 1024 and idx < len(units) - 1: + n /= 1024.0 + idx += 1 + if idx == 0: + return f'{int(n)}B' + if n >= 100: + return f'{n:.0f}{units[idx]}' + if n >= 10: + return f'{n:.1f}{units[idx]}' + return f'{n:.2f}{units[idx]}' + + +def fit(value, width, middle=False): + value = str(value or '-') + if len(value) <= width: + return value + if width <= 3: + return value[:width] + if middle: + right = min(6, max(2, width // 2)) + left = width - right - 1 + return value[:left] + '~' + value[-right:] + return value[:width - 1] + '~' + + +online_count = sum(1 for p in peers if online(p)) +state = 'Running' if running else 'Stopped' +print() +print(f'{iface} {state} {address} UDP {port} Peers {len(peers)} ({online_count} online)') + +if not peers: + print('Clients / peers: none configured') + raise SystemExit(0) + +# Keep one peer per line, but do not shorten Endpoint: the terminal usually has +# more horizontal room than the boxed menu. Column widths adapt to current data. +rows = [] +for peer in peers: + name = str(peer.get('name') or '').strip() + if not name or name.lower() == 'unnamed peer': + name = short_key(peer.get('public_key')) + allowed = list(peer.get('allowed_ips') or peer.get('allowed_ips_runtime') or []) + vpn_ip = str(peer.get('vpn_address') or (allowed[0] if allowed else '-')) + peer_state = 'Online' if online(peer) else 'Offline' + handshake = age(handshake_epoch(peer)) + endpoint = peer_endpoint(peer) + if endpoint in {'—', '(none)', 'None', ''}: + endpoint = '-' + traffic = f"{compact_bytes(peer.get('rx_bytes'))}/{compact_bytes(peer.get('tx_bytes'))}" + rows.append((name, vpn_ip, peer_state, handshake, endpoint, traffic)) + +name_width = min(20, max([len('Name')] + [len(r[0]) for r in rows])) +vpn_width = max([len('VPN IP')] + [len(r[1]) for r in rows]) +state_width = max([len('State')] + [len(r[2]) for r in rows]) +handshake_width = max([len('Handshake')] + [len(r[3]) for r in rows]) +endpoint_width = max([len('Endpoint')] + [len(r[4]) for r in rows]) +traffic_width = max([len('RX/TX')] + [len(r[5]) for r in rows]) + +print() +print('Clients / peers') +header = ( + f"{'Name':<{name_width}} " + f"{'VPN IP':<{vpn_width}} " + f"{'State':<{state_width}} " + f"{'Handshake':<{handshake_width}} " + f"{'Endpoint':<{endpoint_width}} " + f"{'RX/TX':<{traffic_width}}" +) +print(header) +print('-' * len(header)) +for name, vpn_ip, peer_state, handshake, endpoint, traffic in rows: + print( + f"{fit(name, name_width):<{name_width}} " + f"{vpn_ip:<{vpn_width}} " + f"{peer_state:<{state_width}} " + f"{handshake:<{handshake_width}} " + f"{endpoint:<{endpoint_width}} " + f"{traffic:<{traffic_width}}" + ) +PYSTATUS + rc=$? + [[ $rc -eq 0 ]] && continue + fi + + # Fallback for a damaged/missing helper: still show live WireGuard data. + local state address port peers latest latest_text + state="$(wg_state_for_raw "$iface")" + address="$(ip -o -4 addr show dev "$iface" 2>/dev/null | awk '{print $4}' | paste -sd, -)" + [[ -n "$address" ]] || address='—' + if wg show "$iface" >/dev/null 2>&1; then + port="$(wg show "$iface" listen-port 2>/dev/null || true)" + [[ "$port" =~ ^[0-9]+$ ]] || port='—' + peers="$(wg show "$iface" peers 2>/dev/null | awk 'NF{n++} END{print n+0}')" + latest="$(wg show "$iface" latest-handshakes 2>/dev/null | awk '$2>m{m=$2} END{print m+0}')" + latest_text="$(format_age "$latest")" + else + port='—'; peers='0'; latest_text='—' + fi + printf '\nInterface: %s\n State: %s\n Address: %s\n Port: %s\n Peers: %s\n Latest handshake: %s\n' \ + "$iface" "$state" "$address" "$port" "$peers" "$latest_text" + done +} + +control_wireguard() { + local action="$1" requested="${2:-}" iface + mapfile -t interfaces < <(wireguard_interfaces) + if [[ -n "$requested" ]]; then + iface="$requested" + if [[ ! -f "/etc/wireguard/${iface}.conf" ]]; then + echo "WireGuard interface $iface is not configured." + return 1 + fi + else + if [[ ${#interfaces[@]} -eq 0 ]]; then + echo "No WireGuard interfaces are configured." + return 1 + elif [[ ${#interfaces[@]} -eq 1 ]]; then + iface="${interfaces[0]}" + elif [[ -f "/etc/wireguard/${WG_INTERFACE}.conf" ]]; then + iface="$WG_INTERFACE" + else + echo "Multiple WireGuard interfaces are configured: ${interfaces[*]}" + echo "Use: wgtools ${action}-wg " + return 1 + fi + fi + + case "$action" in + start|stop|restart) systemctl "$action" "wg-quick@${iface}.service" ;; + *) echo "Unsupported WireGuard action: $action" >&2; return 1 ;; + esac +} + +menu_wireguard_action() { + local action="$1" selected + mapfile -t _wg_menu_ifaces < <(wireguard_interfaces) + if [[ ${#_wg_menu_ifaces[@]} -eq 0 ]]; then + echo "No WireGuard interfaces are configured." + return 1 + fi + if [[ ${#_wg_menu_ifaces[@]} -eq 1 ]]; then + control_wireguard "$action" "${_wg_menu_ifaces[0]}" + return + fi + printf 'Interface [%s]: ' "${_wg_menu_ifaces[*]}" + read -r selected + [[ -n "$selected" ]] || { echo "Cancelled."; return 0; } + control_wireguard "$action" "$selected" +} + +disable_https_rescue() { + if [[ "$HTTPS_ENABLED" != "1" ]]; then + echo "Built-in HTTPS is already disabled." + return 0 + fi + printf 'Disable built-in HTTPS and restore HTTP on TCP %s? [y/N] ' "$HTTP_PORT" + read -r answer + [[ "$answer" =~ ^[Yy]$ ]] || return 0 + if [[ -x /usr/local/libexec/wgtools-helper ]]; then + /usr/local/libexec/wgtools-helper https_disable "$WG_INTERFACE" >/tmp/wgtools-cli-https.json 2>/tmp/wgtools-cli-https.err || { + cat /tmp/wgtools-cli-https.err >&2 || true + rm -f /tmp/wgtools-cli-https.json /tmp/wgtools-cli-https.err + return 1 + } + rm -f /tmp/wgtools-cli-https.json /tmp/wgtools-cli-https.err + sleep 6 + # shellcheck disable=SC1090 + [[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV" + HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}" + echo "HTTP restored: $(panel_url)" + else + echo "WGTools helper is not installed." >&2 + return 1 + fi +} + +mfa_enabled_users() { + python3 - "$DATABASE_PATH" <<'PYMFAUSERS' 2>/dev/null || true +import sqlite3, sys +path=sys.argv[1] +try: + conn=sqlite3.connect(path) + cols={row[1] for row in conn.execute("PRAGMA table_info(users)")} + if "mfa_enabled" not in cols: + raise SystemExit(0) + for row in conn.execute("SELECT username FROM users WHERE mfa_enabled=1 ORDER BY username COLLATE NOCASE"): + print(str(row[0])) +except Exception: + pass +PYMFAUSERS +} + +disable_mfa_cli() { + local requested="${1:-}" selected answer i + mapfile -t _mfa_users < <(mfa_enabled_users) + if [[ ${#_mfa_users[@]} -eq 0 ]]; then + echo "MFA is not enabled for any WGTools user." + return 0 + fi + + if [[ -n "$requested" ]]; then + selected='' + for i in "${_mfa_users[@]}"; do + if [[ "${i,,}" == "${requested,,}" ]]; then selected="$i"; break; fi + done + if [[ -z "$selected" ]]; then + echo "MFA-enabled user not found: $requested" >&2 + return 1 + fi + elif [[ ${#_mfa_users[@]} -eq 1 ]]; then + selected="${_mfa_users[0]}" + else + echo "MFA-enabled users:" + for i in "${!_mfa_users[@]}"; do printf ' %d. %s\n' "$((i+1))" "${_mfa_users[$i]}"; done + printf 'Select user [1-%d]: ' "${#_mfa_users[@]}" + read -r answer + [[ "$answer" =~ ^[0-9]+$ ]] || { echo "Cancelled."; return 0; } + (( answer >= 1 && answer <= ${#_mfa_users[@]} )) || { echo "Cancelled."; return 0; } + selected="${_mfa_users[$((answer-1))]}" + fi + + printf 'Disable MFA for %b%s%b? This invalidates existing sessions. [y/N] ' "$BOLD" "$selected" "$RESET" + read -r answer + [[ "$answer" =~ ^[Yy]$ ]] || { echo "Cancelled."; return 0; } + + python3 - "$DATABASE_PATH" "$selected" <<'PYMFADISABLE' +import json, sqlite3, sys, time +path, username = sys.argv[1], sys.argv[2] +conn=sqlite3.connect(path) +try: + cols={row[1] for row in conn.execute("PRAGMA table_info(users)")} + required={"mfa_enabled","mfa_secret","mfa_recovery_codes","mfa_confirmed_at","session_version"} + if not required.issubset(cols): + raise SystemExit("This WGTools database does not support MFA.") + row=conn.execute("SELECT id,mfa_enabled FROM users WHERE username=? COLLATE NOCASE",(username,)).fetchone() + if not row: + raise SystemExit("User not found.") + if not int(row[1] or 0): + print("MFA is already disabled.") + raise SystemExit(0) + conn.execute( + "UPDATE users SET mfa_enabled=0,mfa_secret='',mfa_recovery_codes='[]',mfa_confirmed_at=0,session_version=session_version+1 WHERE id=?", + (int(row[0]),), + ) + audit_exists=conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='audit_log'").fetchone() + if audit_exists: + conn.execute( + "INSERT INTO audit_log(created_at,username,action,object,result,details) VALUES(?,?,?,?,?,?)", + (int(time.time()),"root-cli","user.mfa_disabled_cli",username,"disabled",json.dumps({"reason":"root CLI rescue"},separators=(",",":"))), + ) + conn.commit() + print(f"MFA disabled for {username}. Existing web sessions were invalidated.") +finally: + conn.close() +PYMFADISABLE +} + +show_logs() { + echo "Press Ctrl+C to return." + journalctl -u wgtools.service -f --no-pager +} + +show_bot_logs() { + echo "Press Ctrl+C to return." + journalctl -u wgtools-telegram.service -f --no-pager +} + +uninstall_wgtools() { + echo + printf '%bUninstall WGTools from this host?%b\n' "$YELLOW" "$RESET" + cat <<'TXT' +This removes the WGTools application, web/Telegram/timer services, CLI, +internal Nodes tunnel and local Relay-home transport services. + +Preserved intentionally: + • normal WireGuard interfaces/configs and packages + • /var/lib/wgtools (database, backups and reusable state) + • Let's Encrypt certificates + • Relay Agents/tenants on other VPS hosts +TXT + printf '\nType %bUNINSTALL%b to continue: ' "$BOLD" "$RESET" + read -r answer + [[ "$answer" == "UNINSTALL" ]] || { echo "Cancelled."; return 0; } + if [[ -x "$APP_DIR/scripts/uninstall.sh" ]]; then + bash "$APP_DIR/scripts/uninstall.sh" + else + echo "Uninstall script was not found: $APP_DIR/scripts/uninstall.sh" >&2 + return 1 + fi + exit 0 +} + +full_cleanup() { + echo + printf '%bFULL CLEANUP — destructive operation%b\n' "$RED$BOLD" "$RESET" + cat <<'TXT' +This wipes this host's WGTools installation completely: + • WGTools application, services, database, backups and CLI + • Nodes and local Relay Agent/tenant state on THIS host + • all WireGuard interfaces and /etc/wireguard configs on THIS host + • WGTools Let's Encrypt certificate + • Debian wireguard / wireguard-tools packages + +Remote Relay Agents on OTHER VPS hosts are not contacted or deleted. +Generic shared OS tools such as iproute2, iptables, Python and certbot are kept. +TXT + printf '\nType %bDELETE ALL%b to continue: ' "$RED$BOLD" "$RESET" + read -r answer + [[ "$answer" == "DELETE ALL" ]] || { echo "Cancelled."; return 0; } + if [[ -x "$APP_DIR/scripts/full-clean.sh" ]]; then + WGTOOLS_FULL_CLEAN_CONFIRMED=1 bash "$APP_DIR/scripts/full-clean.sh" + else + echo "Full cleanup script was not found: $APP_DIR/scripts/full-clean.sh" >&2 + return 1 + fi + exit 0 +} + +run_action() { + case "${1:-}" in + status) print_status ;; + start) systemctl start wgtools.service ;; + stop) systemctl stop wgtools.service ;; + restart) systemctl restart wgtools.service ;; + status-wg) show_wireguard_status "${2:-}" ;; + start-wg) control_wireguard start "${2:-}" ;; + stop-wg) control_wireguard stop "${2:-}" ;; + restart-wg) control_wireguard restart "${2:-}" ;; + logs) journalctl -u wgtools.service -n 80 --no-pager ;; + bot-logs) journalctl -u wgtools-telegram.service -n 80 --no-pager ;; + http-rescue) disable_https_rescue ;; + disable-mfa) disable_mfa_cli "${2:-}" ;; + uninstall) uninstall_wgtools ;; + full-clean) full_cleanup ;; + *) return 2 ;; + esac +} + +if [[ $# -gt 0 ]]; then + run_action "$@" || { + rc=$? + if [[ $rc -eq 2 ]]; then + echo "Usage: wgtools [status|start|stop|restart|status-wg [interface]|start-wg [interface]|stop-wg [interface]|restart-wg [interface]|logs|bot-logs|http-rescue|disable-mfa [username]|uninstall|full-clean]" >&2 + fi + exit "$rc" + } + exit 0 +fi + +while true; do + # Reload mutable HTTPS settings on each pass. + unset WGTOOLS_HTTPS_ENABLED WGTOOLS_HTTPS_PORT WGTOOLS_ACCESS_PATH 2>/dev/null || true + # shellcheck disable=SC1090 + [[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV" + HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}" + HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}" + ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-}" + print_status + printf '\n┌─────────────────────────────────────────────────────────────────┐\n' + printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Panel' "$RESET" + printf '│ %-63s │\n' ' 1. Refresh status' + printf '│ %-63s │\n' ' 2. Start' + printf '│ %-63s │\n' ' 3. Stop' + printf '│ %-63s │\n' ' 4. Restart' + printf '├─────────────────────────────────────────────────────────────────┤\n' + printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'WireGuard' "$RESET" + printf '│ %-63s │\n' ' 5. Status' + printf '│ %-63s │\n' ' 6. Start' + printf '│ %-63s │\n' ' 7. Stop' + printf '│ %-63s │\n' ' 8. Restart' + printf '├─────────────────────────────────────────────────────────────────┤\n' + printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Logs & recovery' "$RESET" + printf '│ %-63s │\n' ' 9. WGTools logs' + printf '│ %-63s │\n' '10. Telegram logs' + printf '│ %-63s │\n' '11. Restore HTTP access (disable built-in HTTPS)' + printf '├─────────────────────────────────────────────────────────────────┤\n' + printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Security' "$RESET" + printf '│ %-63s │\n' '12. Disable user MFA (emergency rescue)' + printf '├─────────────────────────────────────────────────────────────────┤\n' + printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Removal' "$RESET" + printf '│ %-63s │\n' '13. Uninstall WGTools (keep WireGuard + reusable data)' + printf '│ %-63s │\n' '14. FULL CLEANUP (WGTools + WireGuard + Relay + all data)' + printf '├─────────────────────────────────────────────────────────────────┤\n' + printf '│ %-63s │\n' ' 0. Exit' + printf '└─────────────────────────────────────────────────────────────────┘\n' + printf '\nSelect [0-14]: ' + read -r choice || exit 0 + case "$choice" in + 1) ;; + 2) systemctl start wgtools.service; sleep 1 ;; + 3) systemctl stop wgtools.service; sleep 1 ;; + 4) systemctl restart wgtools.service; sleep 1 ;; + 5) show_wireguard_status || true; printf '\nPress Enter to continue...'; read -r _ ;; + 6) menu_wireguard_action start || true; sleep 1 ;; + 7) menu_wireguard_action stop || true; sleep 1 ;; + 8) menu_wireguard_action restart || true; sleep 1 ;; + 9) show_logs || true ;; + 10) show_bot_logs || true ;; + 11) disable_https_rescue || true; printf '\nPress Enter to continue...'; read -r _ ;; + 12) disable_mfa_cli || true; printf '\nPress Enter to continue...'; read -r _ ;; + 13) uninstall_wgtools || true; printf '\nPress Enter to continue...'; read -r _ ;; + 14) full_cleanup || true; printf '\nPress Enter to continue...'; read -r _ ;; + 0) exit 0 ;; + *) printf 'Unknown selection.\n'; sleep 1 ;; + esac +done diff --git a/scripts/wgtools-helper b/scripts/wgtools-helper new file mode 100644 index 0000000..cdbcd56 --- /dev/null +++ b/scripts/wgtools-helper @@ -0,0 +1,6735 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import fcntl +import hashlib +import ipaddress +import json +import os +import re +import secrets +import shutil +import shlex +import socket +import sqlite3 +import subprocess +import sys +import tarfile +import tempfile +import time +import urllib.error +import urllib.parse +import urllib.request +import unicodedata +from concurrent.futures import ThreadPoolExecutor, as_completed +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +ALLOWED_ACTIONS = {"snapshot", "interfaces_list", "interface_meta_set", "interface_delete", "metrics_sample", "metrics_history", "diagnostics", "network_trace", "wireguard_start", "wireguard_stop", "wireguard_restart", "install_wireguard", "create_server", "create_client", "update_client", "delete_client", "rotate_client_credentials", "expire_clients", "client_config", "group_create", "group_update", "group_delete", "raw_config_get", "raw_config_apply", "server_settings_apply", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete", "migration_backup_create", "migration_restore", "update_check", "update_notice", "update_status", "update_schedule", "update_apply", "traffic_reset", "https_status", "https_ports", "https_issue", "https_enable", "https_disable", "https_switch_commit"} +ALLOWED_ACTIONS.update({"extended_snat_get", "extended_snat_apply"}) +ALLOWED_ACTIONS.update({"extended_listen_get", "extended_listen_apply"}) +ALLOWED_ACTIONS.update({"extended_ip_groups_get", "extended_ip_groups_set", "extended_forward_get", "extended_forward_add", "extended_forward_delete"}) +ALLOWED_ACTIONS.update({"update_file_schedule", "update_file_apply"}) +ALLOWED_IFACE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,15}$") +INTERNAL_INTERFACE_PREFIXES = ("wgrly", "wgnode") +LOCK_PATH = Path("/run/wgtools.lock") +WG_DIR = Path("/etc/wireguard") +DATA_DIR = Path("/var/lib/wgtools") +CLIENT_DIR = DATA_DIR / "clients" +GROUPS_PATH = DATA_DIR / "groups.json" +BACKUP_DIR = DATA_DIR / "backups" +DATABASE_PATH = DATA_DIR / "wgtools.db" +METRICS_CACHE = Path("/run/wgtools-metrics.json") +METRICS_HISTORY_PATH = DATA_DIR / "metrics-history.json" +METRICS_HISTORY_STAMP = Path("/run/wgtools-metrics-history.stamp") +METRICS_HISTORY_LOCK = Path("/run/wgtools-metrics-history.lock") +METRICS_HISTORY_SECONDS = 24 * 60 * 60 +METRICS_HISTORY_SAMPLE_SECONDS = 60 +TRACE_GEO_CACHE_PATH = Path("/run/wgtools-trace-geo.json") +TRACE_GEO_CACHE_TTL = 24 * 60 * 60 +EXPORT_DIR = DATA_DIR / "exports" +MIGRATION_SAFETY_DIR = DATA_DIR / "migration-backups" +SYSCTL_FILE = Path("/etc/sysctl.d/99-wgtools-wireguard.conf") +MIGRATION_FORMAT_VERSION = 4 +MIGRATION_MAX_BYTES = 64 * 1024 * 1024 +APP_DIR = Path("/opt/wgtools") +ENV_FILE = Path("/etc/wgtools/wgtools.env") +HELPER_INSTALL_PATH = Path("/usr/local/libexec/wgtools-helper") +SYSTEMD_DIR = Path("/etc/systemd/system") +UPDATE_STATUS_PATH = DATA_DIR / "update-status.json" +UPDATE_NOTICE_PATH = DATA_DIR / "update-notice.json" +UPDATE_NOTICE_MAX_AGE = 15 * 60 +UPDATE_LOCK_PATH = Path("/run/wgtools-update.lock") +UPDATE_BACKUP_DIR = DATA_DIR / "update-backups" +INTERFACES_META_PATH = DATA_DIR / "interfaces.json" +EXT_IP_GROUPS_PATH = DATA_DIR / "extended-ip-groups.json" +HTTPS_ENV_FILE = Path("/etc/wgtools/https.env") +HTTPS_STATE_FILE = Path("/etc/wgtools/https.json") +HTTPS_CERT_NAME = "wgtools" +HTTPS_CERT_DIR = Path("/etc/letsencrypt/live") / HTTPS_CERT_NAME +HTTPS_CERT_FILE = HTTPS_CERT_DIR / "fullchain.pem" +HTTPS_KEY_FILE = HTTPS_CERT_DIR / "privkey.pem" +HTTPS_RENEW_TIMER = "wgtools-certbot-renew.timer" +CERTBOT_PATH = APP_DIR / ".venv" / "bin" / "certbot" + + +def run(cmd: list[str], timeout: int = 8, input_text: str | None = None) -> tuple[int, str, str]: + try: + p = subprocess.run( + cmd, + input=input_text, + capture_output=True, + text=True, + timeout=timeout, + check=False, + env={**os.environ, "LC_ALL": "C"}, + ) + return p.returncode, p.stdout.strip(), p.stderr.strip() + except FileNotFoundError as exc: + return 127, "", str(exc) + except subprocess.TimeoutExpired: + return 124, "", f"Command timed out after {timeout}s: {' '.join(cmd)}" + except Exception as exc: + return 127, "", str(exc) + + +def read_app_setting(key: str, default: int) -> int: + try: + if not DATABASE_PATH.exists(): + return default + conn = sqlite3.connect(DATABASE_PATH) + try: + row = conn.execute("SELECT value FROM app_settings WHERE key=?", (key,)).fetchone() + finally: + conn.close() + return int(row[0]) if row else default + except Exception: + return default + + +def backup_retention() -> int: + return max(1, min(read_app_setting("backup_retention", 20), 200)) + + +def _audit_safe_text(value: Any, limit: int = 1200) -> str: + text = str(value or "") + text = re.sub(r"\b\d{6,12}:[A-Za-z0-9_-]{20,}\b", "[redacted]", text) + text = re.sub(r"(? None: + """Best-effort audit writer for privileged/background helper jobs. + + Update installation continues while the web service restarts, so lifecycle + events cannot depend on the FastAPI process being alive. + """ + try: + DATA_DIR.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH, timeout=10) + try: + with conn: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS audit_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at INTEGER NOT NULL, + username TEXT NOT NULL, + action TEXT NOT NULL, + object TEXT NOT NULL DEFAULT '', + result TEXT NOT NULL DEFAULT '', + details TEXT NOT NULL DEFAULT '' + ) + """ + ) + payload = "" + if details: + cleaned = {str(k): _audit_safe_text(v, 1000) for k, v in details.items()} + payload = json.dumps(cleaned, ensure_ascii=False, sort_keys=True)[:4000] + conn.execute( + "INSERT INTO audit_log(created_at,username,action,object,result,details) VALUES(?,?,?,?,?,?)", + ( + int(time.time()), + "system", + _audit_safe_text(action, 160), + _audit_safe_text(object, 240), + _audit_safe_text(result, 1200), + payload, + ), + ) + finally: + conn.close() + except Exception: + # Audit must never make an update fail. + pass + + +def _traffic_connect() -> sqlite3.Connection: + DATA_DIR.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DATABASE_PATH, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute( + """ + CREATE TABLE IF NOT EXISTS wg_traffic_counters ( + interface TEXT NOT NULL, + public_key TEXT NOT NULL, + runtime_rx INTEGER NOT NULL DEFAULT 0, + runtime_tx INTEGER NOT NULL DEFAULT 0, + total_rx INTEGER NOT NULL DEFAULT 0, + total_tx INTEGER NOT NULL DEFAULT 0, + updated_at INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(interface, public_key) + ) + """ + ) + return conn + + +def _traffic_runtime_peers(iface: str) -> list[dict[str, Any]]: + dump = wg_dump(iface) + if not dump.get("running"): + return [] + return list((dump.get("peers") or {}).values()) + + +def persist_wireguard_traffic(iface: str, peers: list[dict[str, Any]]) -> dict[str, int]: + """Merge WireGuard's resettable runtime counters into durable totals. + + WireGuard transfer counters return to zero after an interface/peer reset. + We retain the previous runtime sample and only add the positive delta. If + the runtime value goes backwards, the counter was reset and the new value + is the first delta of the new runtime session. + """ + now = int(time.time()) + conn = _traffic_connect() + try: + # Snapshot requests can arrive from the UI and background sampler at + # the same time. Take the write lock before reading baselines so an + # older concurrent sample can never overwrite a newer lifetime total. + conn.execute("BEGIN IMMEDIATE") + try: + for peer in peers: + public_key = str(peer.get("public_key") or "").strip() + # Config-only peers do not contain runtime counters. Treating + # that as zero would double count the next time wg comes up. + if not public_key or "rx_bytes" not in peer or "tx_bytes" not in peer: + continue + runtime_rx = max(0, int(peer.get("rx_bytes") or 0)) + runtime_tx = max(0, int(peer.get("tx_bytes") or 0)) + row = conn.execute( + "SELECT runtime_rx,runtime_tx,total_rx,total_tx FROM wg_traffic_counters WHERE interface=? AND public_key=?", + (iface, public_key), + ).fetchone() + if row is None: + total_rx, total_tx = runtime_rx, runtime_tx + else: + old_rx = max(0, int(row["runtime_rx"] or 0)) + old_tx = max(0, int(row["runtime_tx"] or 0)) + total_rx = max(0, int(row["total_rx"] or 0)) + (runtime_rx - old_rx if runtime_rx >= old_rx else runtime_rx) + total_tx = max(0, int(row["total_tx"] or 0)) + (runtime_tx - old_tx if runtime_tx >= old_tx else runtime_tx) + conn.execute( + """ + INSERT INTO wg_traffic_counters(interface,public_key,runtime_rx,runtime_tx,total_rx,total_tx,updated_at) + VALUES(?,?,?,?,?,?,?) + ON CONFLICT(interface,public_key) DO UPDATE SET + runtime_rx=excluded.runtime_rx, + runtime_tx=excluded.runtime_tx, + total_rx=excluded.total_rx, + total_tx=excluded.total_tx, + updated_at=excluded.updated_at + """, + (iface, public_key, runtime_rx, runtime_tx, total_rx, total_tx, now), + ) + totals = conn.execute( + "SELECT COALESCE(SUM(total_rx),0) AS rx, COALESCE(SUM(total_tx),0) AS tx FROM wg_traffic_counters WHERE interface=?", + (iface,), + ).fetchone() + conn.commit() + return {"rx_bytes": int(totals["rx"] or 0), "tx_bytes": int(totals["tx"] or 0)} + except Exception: + conn.rollback() + raise + finally: + conn.close() + + +def merge_wireguard_traffic(iface: str, peers: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, int]]: + totals = persist_wireguard_traffic(iface, peers) + conn = _traffic_connect() + try: + rows = { + str(row["public_key"]): row + for row in conn.execute( + "SELECT public_key,total_rx,total_tx FROM wg_traffic_counters WHERE interface=?", + (iface,), + ).fetchall() + } + finally: + conn.close() + merged: list[dict[str, Any]] = [] + for peer in peers: + item = dict(peer) + row = rows.get(str(item.get("public_key") or "")) + if row is not None: + item["rx_bytes"] = int(row["total_rx"] or 0) + item["tx_bytes"] = int(row["total_tx"] or 0) + else: + item["rx_bytes"] = int(item.get("rx_bytes") or 0) + item["tx_bytes"] = int(item.get("tx_bytes") or 0) + merged.append(item) + return merged, totals + + +def capture_wireguard_traffic(iface: str) -> dict[str, int]: + return persist_wireguard_traffic(iface, _traffic_runtime_peers(iface)) + + +def reset_wireguard_traffic(iface: str) -> dict[str, Any]: + require_valid_iface(iface) + runtime_peers = _traffic_runtime_peers(iface) + now = int(time.time()) + conn = _traffic_connect() + try: + conn.execute("BEGIN IMMEDIATE") + try: + # This intentionally removes rows for deleted clients too: the + # Dashboard counter represents all traffic since the last reset. + conn.execute("DELETE FROM wg_traffic_counters WHERE interface=?", (iface,)) + for peer in runtime_peers: + public_key = str(peer.get("public_key") or "").strip() + if not public_key: + continue + runtime_rx = max(0, int(peer.get("rx_bytes") or 0)) + runtime_tx = max(0, int(peer.get("tx_bytes") or 0)) + conn.execute( + "INSERT INTO wg_traffic_counters(interface,public_key,runtime_rx,runtime_tx,total_rx,total_tx,updated_at) VALUES(?,?,?,?,0,0,?)", + (iface, public_key, runtime_rx, runtime_tx, now), + ) + conn.commit() + except Exception: + conn.rollback() + raise + finally: + conn.close() + return {"ok": True, "interface": iface, "rx_bytes": 0, "tx_bytes": 0} + + +def delete_wireguard_traffic(iface: str) -> None: + try: + conn = _traffic_connect() + try: + with conn: + conn.execute("DELETE FROM wg_traffic_counters WHERE interface=?", (iface,)) + finally: + conn.close() + except Exception: + pass + + +def installed_relay_for_interface(vps_id: str, iface: str) -> dict[str, Any] | None: + wanted = str(vps_id or "").strip() + if not wanted or not DATABASE_PATH.exists(): + return None + try: + conn = sqlite3.connect(DATABASE_PATH) + conn.row_factory = sqlite3.Row + try: + row = conn.execute( + """SELECT id,name,host,endpoint_domain,relay_port,status,published_interface + FROM vps_relays WHERE id=?""", + (wanted,), + ).fetchone() + finally: + conn.close() + except sqlite3.Error: + return None + if not row: + return None + item = dict(row) + if str(item.get("status") or "") != "installed": + return None + if str(item.get("published_interface") or "") != iface: + return None + return item + + +def relay_client_endpoint(item: dict[str, Any]) -> str: + host = str(item.get("endpoint_domain") or item.get("host") or "").strip() + try: + port = int(item.get("relay_port") or 0) + except (TypeError, ValueError): + port = 0 + if not host or not (1 <= port <= 65535): + raise ValueError("Selected VPS Relay does not have a valid public endpoint") + return f"{host}:{port}" + + +def _read_proc_cpu() -> tuple[int, int]: + line = Path("/proc/stat").read_text(encoding="utf-8", errors="replace").splitlines()[0] + parts = line.split()[1:] + values = [int(x) for x in parts if x.isdigit()] + total = sum(values) + idle = (values[3] if len(values) > 3 else 0) + (values[4] if len(values) > 4 else 0) + return total, idle + + +def _read_meminfo() -> dict[str, int]: + result: dict[str, int] = {} + for line in Path("/proc/meminfo").read_text(encoding="utf-8", errors="replace").splitlines(): + if ":" not in line: + continue + key, value = line.split(":", 1) + token = value.strip().split()[0] if value.strip() else "0" + if token.isdigit(): + result[key] = int(token) * 1024 + return result + + +def _read_net_bytes(interface: str | None) -> tuple[int, int]: + if not interface: + return 0, 0 + base = Path("/sys/class/net") / interface / "statistics" + try: + return int((base / "rx_bytes").read_text().strip()), int((base / "tx_bytes").read_text().strip()) + except Exception: + return 0, 0 + + +def system_metrics(uplink: str | None) -> dict[str, Any]: + now = time.time() + cpu_total, cpu_idle = _read_proc_cpu() + rx_bytes, tx_bytes = _read_net_bytes(uplink) + previous: dict[str, Any] = {} + try: + previous = json.loads(METRICS_CACHE.read_text(encoding="utf-8")) if METRICS_CACHE.exists() else {} + except Exception: + previous = {} + + cpu_percent = previous.get("cpu_percent") + rx_rate = float(previous.get("rx_rate") or 0.0) + tx_rate = float(previous.get("tx_rate") or 0.0) + dt = now - float(previous.get("timestamp") or 0.0) + if not previous: + time.sleep(0.08) + total2, idle2 = _read_proc_cpu() + delta_total = total2 - cpu_total + delta_idle = idle2 - cpu_idle + if delta_total > 0: + cpu_percent = max(0.0, min(100.0, 100.0 * (1.0 - delta_idle / delta_total))) + cpu_total, cpu_idle = total2, idle2 + now = time.time() + elif dt >= 0.5: + delta_total = cpu_total - int(previous.get("cpu_total") or cpu_total) + delta_idle = cpu_idle - int(previous.get("cpu_idle") or cpu_idle) + if delta_total > 0: + cpu_percent = max(0.0, min(100.0, 100.0 * (1.0 - delta_idle / delta_total))) + if str(previous.get("uplink") or "") == str(uplink or ""): + rx_rate = max(0.0, (rx_bytes - int(previous.get("rx_bytes") or rx_bytes)) / dt) + tx_rate = max(0.0, (tx_bytes - int(previous.get("tx_bytes") or tx_bytes)) / dt) + + cache = { + "timestamp": now, + "cpu_total": cpu_total, + "cpu_idle": cpu_idle, + "cpu_percent": cpu_percent, + "uplink": uplink or "", + "rx_bytes": rx_bytes, + "tx_bytes": tx_bytes, + "rx_rate": rx_rate, + "tx_rate": tx_rate, + } + try: + METRICS_CACHE.write_text(json.dumps(cache), encoding="utf-8") + os.chmod(METRICS_CACHE, 0o600) + except Exception: + pass + + mem = _read_meminfo() + total_mem = int(mem.get("MemTotal") or 0) + available_mem = int(mem.get("MemAvailable") or mem.get("MemFree") or 0) + used_mem = max(0, total_mem - available_mem) + mem_percent = (100.0 * used_mem / total_mem) if total_mem else 0.0 + load1, load5, load15 = os.getloadavg() if hasattr(os, "getloadavg") else (0.0, 0.0, 0.0) + try: + uptime_seconds = int(float(Path("/proc/uptime").read_text().split()[0])) + except Exception: + uptime_seconds = 0 + disk = shutil.disk_usage("/") + return { + "cpu": { + "percent": round(float(cpu_percent), 1) if cpu_percent is not None else None, + "cores": int(os.cpu_count() or 1), + "load1": round(load1, 2), + "load5": round(load5, 2), + "load15": round(load15, 2), + }, + "memory": { + "total_bytes": total_mem, + "used_bytes": used_mem, + "available_bytes": available_mem, + "percent": round(mem_percent, 1), + }, + "network": { + "interface": uplink, + "rx_bytes": rx_bytes, + "tx_bytes": tx_bytes, + "rx_bytes_per_second": round(rx_rate, 1), + "tx_bytes_per_second": round(tx_rate, 1), + }, + "disk": { + "total_bytes": disk.total, + "used_bytes": disk.used, + "free_bytes": disk.free, + "percent": round(100.0 * disk.used / disk.total, 1) if disk.total else 0.0, + }, + "uptime_seconds": uptime_seconds, + } + + +def _load_metrics_history() -> list[dict[str, Any]]: + try: + raw = json.loads(METRICS_HISTORY_PATH.read_text(encoding="utf-8")) if METRICS_HISTORY_PATH.exists() else [] + except Exception: + raw = [] + if not isinstance(raw, list): + return [] + now = int(time.time()) + cutoff = now - METRICS_HISTORY_SECONDS + result: list[dict[str, Any]] = [] + for item in raw: + if not isinstance(item, dict): + continue + try: + ts = int(item.get("timestamp") or 0) + except (TypeError, ValueError): + continue + if ts < cutoff or ts > now + 300: + continue + try: + result.append({ + "timestamp": ts, + "cpu": round(float(item.get("cpu") or 0.0), 1), + "memory": round(float(item.get("memory") or 0.0), 1), + "rx": round(max(0.0, float(item.get("rx") or 0.0)), 1), + "tx": round(max(0.0, float(item.get("tx") or 0.0)), 1), + }) + except (TypeError, ValueError): + continue + result.sort(key=lambda item: item["timestamp"]) + return result[-1600:] + + +def _record_metrics_history(metrics: dict[str, Any], *, force: bool = False) -> None: + METRICS_HISTORY_LOCK.parent.mkdir(parents=True, exist_ok=True) + with METRICS_HISTORY_LOCK.open("w") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + now = int(time.time()) + if not force: + try: + last = int(METRICS_HISTORY_STAMP.read_text(encoding="utf-8").strip() or 0) + except Exception: + last = 0 + if now - last < METRICS_HISTORY_SAMPLE_SECONDS: + return + + cpu = metrics.get("cpu") or {} + memory = metrics.get("memory") or {} + network = metrics.get("network") or {} + point = { + "timestamp": now, + "cpu": round(float(cpu.get("percent") or 0.0), 1), + "memory": round(float(memory.get("percent") or 0.0), 1), + "rx": round(max(0.0, float(network.get("rx_bytes_per_second") or 0.0)), 1), + "tx": round(max(0.0, float(network.get("tx_bytes_per_second") or 0.0)), 1), + } + history = _load_metrics_history() + if history and now - int(history[-1].get("timestamp") or 0) < METRICS_HISTORY_SAMPLE_SECONDS: + return + history.append(point) + cutoff = now - METRICS_HISTORY_SECONDS + history = [item for item in history if int(item.get("timestamp") or 0) >= cutoff][-1600:] + tmp: Path | None = None + try: + DATA_DIR.mkdir(parents=True, exist_ok=True) + tmp = METRICS_HISTORY_PATH.with_name(f".{METRICS_HISTORY_PATH.name}.{os.getpid()}.tmp") + tmp.write_text(json.dumps(history, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + os.chmod(tmp, 0o600) + os.replace(tmp, METRICS_HISTORY_PATH) + os.chmod(METRICS_HISTORY_PATH, 0o600) + METRICS_HISTORY_STAMP.write_text(str(now), encoding="utf-8") + os.chmod(METRICS_HISTORY_STAMP, 0o600) + except Exception: + if tmp is not None: + try: + tmp.unlink() + except Exception: + pass + + +def metrics_sample(iface: str) -> dict[str, Any]: + require_valid_iface(iface) + # CPU, memory and Network on Dashboard are host metrics, not metrics of the + # selected WireGuard interface. Always sample the host default uplink so + # switching wg0/wg1 cannot mix different NICs in the same 24-hour graph. + route_info = default_route_info() + metrics = system_metrics(route_info.get("default_uplink")) + _record_metrics_history(metrics) + return {"ok": True, "timestamp": int(time.time()), "metrics": metrics} + + +def metrics_history() -> dict[str, Any]: + return {"ok": True, "window_seconds": METRICS_HISTORY_SECONDS, "sample_seconds": METRICS_HISTORY_SAMPLE_SECONDS, "history": _load_metrics_history()} + + + +def _load_interface_meta() -> dict[str, dict[str, Any]]: + try: + raw = json.loads(INTERFACES_META_PATH.read_text(encoding="utf-8")) if INTERFACES_META_PATH.exists() else {} + except Exception: + raw = {} + if not isinstance(raw, dict): + return {} + result: dict[str, dict[str, Any]] = {} + for name, value in raw.items(): + if ALLOWED_IFACE_RE.fullmatch(str(name)) and isinstance(value, dict): + result[str(name)] = dict(value) + return result + + +def _save_interface_meta(data: dict[str, dict[str, Any]]) -> None: + DATA_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(DATA_DIR, 0o755) + temp = INTERFACES_META_PATH.with_suffix(".tmp") + temp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + os.chmod(temp, 0o600) + os.replace(temp, INTERFACES_META_PATH) + os.chmod(INTERFACES_META_PATH, 0o600) + + +def interface_meta_set(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + require_valid_iface(iface) + display_name = str(payload.get("display_name") or "").strip() + if len(display_name) > 64: + raise ValueError("Interface display name must be 64 characters or fewer") + if any(ord(ch) < 32 for ch in display_name): + raise ValueError("Interface display name contains unsupported control characters") + data = _load_interface_meta() + current = dict(data.get(iface) or {}) + current["display_name"] = display_name or iface + current["updated_at"] = int(time.time()) + data[iface] = current + _save_interface_meta(data) + return {"ok": True, "interface": iface, "display_name": current["display_name"]} + + +def interface_delete(iface: str) -> dict[str, Any]: + require_valid_iface(iface) + if any(iface in group.get("interfaces", []) for group in _extended_groups().values()): + raise ValueError("Najpierw usuń tę sieć z grup adresów IP") + # Preserve every byte reported by the live interface before it disappears. + capture_wireguard_traffic(iface) + config_path = WG_DIR / f"{iface}.conf" + if not config_path.exists(): + raise ValueError(f"WireGuard interface configuration {iface}.conf was not found") + + configured = sorted( + path.stem for path in WG_DIR.glob("*.conf") + if path.is_file() and ALLOWED_IFACE_RE.fullmatch(path.stem) + ) + if len(configured) <= 1: + raise ValueError("The last configured WireGuard interface cannot be deleted") + + # Keep the exact server configuration before any destructive action. + backup = make_backup(iface, config_path) + + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + rc, out, err = run([systemctl, "disable", "--now", f"wg-quick@{iface}.service"], timeout=30) + if rc != 0: + raise RuntimeError(f"Could not stop WireGuard interface {iface}: {(err or out)[-1200:]}") + + # A manually-created/runtime-only interface can survive a service stop. + # Try wg-quick down using the still-present config before deleting the file. + if wg_dump(iface).get("running"): + wg_quick = shutil.which("wg-quick") or "/usr/bin/wg-quick" + run([wg_quick, "down", str(config_path)], timeout=20) + if wg_dump(iface).get("running"): + raise RuntimeError(f"WireGuard interface {iface} is still running; configuration was not deleted") + + # Remove WGTools-managed private metadata belonging only to this interface. + removed_clients = 0 + for meta in iter_client_metas(): + if str(meta.get("interface") or "").strip() != iface: + continue + public_key = str(meta.get("public_key") or "").strip() + if public_key: + delete_client_meta(public_key) + removed_clients += 1 + + groups_doc = _load_groups_document() + groups_doc["groups"] = [ + item for item in groups_doc.get("groups", []) + if str(item.get("interface") or "") != iface + ] + _save_groups_document(groups_doc) + + config_path.unlink() + + meta = _load_interface_meta() + if iface in meta: + meta.pop(iface, None) + _save_interface_meta(meta) + + remaining = [name for name in configured if name != iface] + def _sort_key(name: str) -> tuple[int, int | str]: + match = re.fullmatch(r"wg(\d+)", name) + return (0, int(match.group(1))) if match else (1, name) + remaining.sort(key=_sort_key) + next_interface = remaining[0] if remaining else "" + delete_wireguard_traffic(iface) + + return { + "ok": True, + "message": f"WireGuard interface {iface} deleted", + "interface": iface, + "next_interface": next_interface, + "removed_managed_clients": removed_clients, + "backup": str(backup), + } + + +def _configured_interface_names() -> set[str]: + result: set[str] = set() + if WG_DIR.exists(): + for path in WG_DIR.glob("*.conf"): + if path.is_file() and ALLOWED_IFACE_RE.fullmatch(path.stem) and not is_internal_interface(path.stem): + result.add(path.stem) + wg = shutil.which("wg") + if wg: + rc, out, _ = run([wg, "show", "interfaces"]) + if rc == 0: + for token in out.split(): + if ALLOWED_IFACE_RE.fullmatch(token) and not is_internal_interface(token): + result.add(token) + return result + + +def _suggest_next_interface_name(used: set[str]) -> str: + for idx in range(0, 1000): + candidate = f"wg{idx}" + if candidate not in used: + return candidate + return "wg-new" + + +def _suggest_next_port(used_ports: set[int]) -> int: + for port in range(51820, 65536): + if port not in used_ports: + return port + for port in range(1024, 51820): + if port not in used_ports: + return port + raise RuntimeError("No free UDP listen port could be suggested") + + +def _suggest_next_policy_table(used_tables: set[int]) -> int: + for table in range(200, 32766): + if table not in used_tables: + return table + raise RuntimeError("No free policy routing table number could be suggested") + + +def _suggest_next_vpn_network(networks: list[ipaddress.IPv4Network]) -> ipaddress.IPv4Network: + # Prefer continuing the first configured private /24. This keeps the + # common wg0=10.0.0.0/24, wg1=10.0.1.0/24 layout predictable. + seeds = [net for net in networks if net.version == 4 and net.is_private and net.prefixlen <= 30] + if seeds: + seed = seeds[0] + step = seed.num_addresses + value = int(seed.network_address) + step + limit = (1 << 32) - step + while value <= limit: + try: + candidate = ipaddress.ip_network((value, seed.prefixlen), strict=True) + except ValueError: + break + if candidate.is_private and not any(candidate.overlaps(existing) for existing in networks): + return candidate + value += step + for raw in ("10.0.0.0/24", "10.1.0.0/24", "10.2.0.0/24", "172.31.0.0/24", "192.168.177.0/24"): + candidate = ipaddress.ip_network(raw) + if not any(candidate.overlaps(existing) for existing in networks): + return candidate + raise RuntimeError("No non-overlapping private IPv4 network could be suggested") + + +def interfaces_list(active_iface: str) -> dict[str, Any]: + require_valid_iface(active_iface) + names = _configured_interface_names() + # Keep the configured default visible during first-run provisioning even + # before its .conf exists. + if not names: + names.add(active_iface) + meta = _load_interface_meta() + items: list[dict[str, Any]] = [] + used_ports: set[int] = set() + used_tables: set[int] = set() + networks: list[ipaddress.IPv4Network] = [] + preferred_uplink = "" + preferred_gateway = "" + preferred_local = "" + + def sort_key(name: str) -> tuple[int, int | str]: + match = re.fullmatch(r"wg(\d+)", name) + return (0, int(match.group(1))) if match else (1, name) + + for name in sorted(names, key=sort_key): + config_path = WG_DIR / f"{name}.conf" + cfg = None + parse_error = "" + if config_path.exists(): + try: + cfg = parse_config(read_config_text(name), name) + except Exception as exc: + parse_error = str(exc) + dump = wg_dump(name) if wg_installed() else {"running": False, "listen_port": None, "peers": {}} + interface_cfg = (cfg or {}).get("interface") or {} + detected = (cfg or {}).get("detected") or {} + address = interface_cfg.get("address") + port_raw = dump.get("listen_port") or interface_cfg.get("listen_port") + try: + port = int(port_raw) if port_raw not in (None, "") else None + except (TypeError, ValueError): + port = None + if port: + used_ports.add(port) + table_raw = detected.get("policy_table") + try: + table_num = int(table_raw) if table_raw not in (None, "") else None + except (TypeError, ValueError): + table_num = None + if table_num: + used_tables.add(table_num) + vpn_network = str(detected.get("vpn_network") or "") + if vpn_network: + try: + networks.append(ipaddress.ip_network(vpn_network, strict=False)) + except ValueError: + pass + preferred_uplink = preferred_uplink or str(detected.get("uplink_interface") or "") + preferred_gateway = preferred_gateway or str(detected.get("gateway") or "") + preferred_local = preferred_local or str(detected.get("local_network") or "") + peer_count = len((cfg or {}).get("peers") or dump.get("peers") or {}) + remote_networks: list[str] = [] + for peer in (cfg or {}).get("peers") or []: + for raw in peer.get("remote_networks") or []: + text = str(raw or "").strip() + if text and text not in remote_networks: + remote_networks.append(text) + display_name = str((meta.get(name) or {}).get("display_name") or name) + items.append({ + "name": name, + "display_name": display_name, + "configured": config_path.exists(), + "running": bool(dump.get("running")), + "address": address, + "listen_port": port, + "vpn_network": vpn_network or None, + "remote_networks": remote_networks, + "policy_table": table_num, + "uplink_interface": detected.get("uplink_interface"), + "peer_count": peer_count, + "config_error": parse_error or None, + "active": name == active_iface, + }) + + route = default_route_info() + suggestion_network = _suggest_next_vpn_network(networks) + first_host = next(suggestion_network.hosts()) + suggested_name = _suggest_next_interface_name(names) + suggestion = { + "interface": suggested_name, + "display_name": "", + "vpn_network": str(suggestion_network), + "server_address": str(ipaddress.ip_interface(f"{first_host}/{suggestion_network.prefixlen}")), + "listen_port": _suggest_next_port(used_ports), + "uplink_interface": preferred_uplink or route.get("default_uplink") or "", + "gateway": preferred_gateway or route.get("default_gateway") or "", + "local_network": preferred_local or route.get("local_network") or "", + "policy_table": str(_suggest_next_policy_table(used_tables)) if used_tables else "", + "nat_enabled": True, + "ip_forwarding": True, + } + return {"ok": True, "active_interface": active_iface, "interfaces": items, "suggested": suggestion} + + +def _validate_cross_interface_server_settings(iface: str, network: ipaddress.IPv4Network, listen_port: int, policy_table: int | None) -> None: + for path in WG_DIR.glob("*.conf") if WG_DIR.exists() else []: + other = path.stem + if other == iface or not ALLOWED_IFACE_RE.fullmatch(other): + continue + try: + cfg = parse_config(path.read_text(encoding="utf-8", errors="replace"), other) + except Exception: + continue + detected = cfg.get("detected") or {} + other_network_raw = str(detected.get("vpn_network") or "").strip() + if other_network_raw: + try: + other_network = ipaddress.ip_network(other_network_raw, strict=False) + if network.overlaps(other_network): + raise ValueError(f"VPN network {network} overlaps with {other} ({other_network})") + except ValueError as exc: + if "overlaps with" in str(exc): + raise + other_port = (cfg.get("interface") or {}).get("listen_port") + try: + if other_port not in (None, "") and int(other_port) == listen_port: + raise ValueError(f"UDP listen port {listen_port} is already used by {other}") + except (TypeError, ValueError) as exc: + if isinstance(exc, ValueError) and "already used" in str(exc): + raise + other_table = detected.get("policy_table") + try: + if policy_table is not None and other_table not in (None, "") and int(other_table) == policy_table: + raise ValueError(f"Policy routing table {policy_table} is already used by {other}; use a separate table for each WGTools interface") + except (TypeError, ValueError) as exc: + if isinstance(exc, ValueError) and "already used" in str(exc): + raise + + +def backup_info(iface: str) -> dict[str, Any]: + files = sorted(BACKUP_DIR.glob(f"{iface}-*.conf"), key=lambda x: x.stat().st_mtime, reverse=True) if BACKUP_DIR.exists() else [] + latest = files[0] if files else None + return { + "count": len(files), + "retention": backup_retention(), + "latest_name": latest.name if latest else None, + "latest_modified_at": int(latest.stat().st_mtime) if latest else None, + } + + +def wireguard_service_action(iface: str, action: str) -> dict[str, Any]: + require_valid_iface(iface) + if action not in {"start", "stop", "restart"}: + raise ValueError("Unsupported WireGuard service action") + if not wg_installed(): + raise RuntimeError("WireGuard is not installed") + config_path = WG_DIR / f"{iface}.conf" + if not config_path.exists(): + raise RuntimeError(f"{config_path} does not exist") + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + service = f"wg-quick@{iface}.service" + if action in {"stop", "restart"}: + capture_wireguard_traffic(iface) + rc, out, err = run([systemctl, action, service], timeout=40) + if rc != 0: + raise RuntimeError(f"Could not {action} {service}: {err or out}") + running = bool(wg_dump(iface).get("running")) + expected = action != "stop" + if running != expected: + raise RuntimeError(f"systemd completed {action}, but {iface} is {'running' if running else 'stopped'} unexpectedly") + return {"ok": True, "action": action, "running": running, "message": f"WireGuard {action} completed"} + + +def read_json_stdin() -> dict[str, Any]: + raw = sys.stdin.read() + if not raw.strip(): + return {} + data = json.loads(raw) + if not isinstance(data, dict): + raise ValueError("JSON payload must be an object") + return data + + +def read_config_text(iface: str) -> str: + path = WG_DIR / f"{iface}.conf" + if not path.exists(): + raise FileNotFoundError(str(path)) + return path.read_text(encoding="utf-8", errors="replace") + + +def parse_comment_name(line: str) -> str | None: + s = line.strip() + if not s.startswith("#"): + return None + s = s.lstrip("#").strip() + m = re.fullmatch(r"-+\s*(.*?)\s*-+", s) + if m and m.group(1).strip(): + return m.group(1).strip().replace("\\_", "_") + return None + + +def parse_config(text: str, iface_hint: str | None = None) -> dict[str, Any]: + interface: dict[str, Any] = { + "address": None, + "listen_port": None, + "mtu": None, + "private_key_set": False, + "save_config": None, + "post_up": [], + "post_down": [], + } + peers: list[dict[str, Any]] = [] + current_section: str | None = None + current_peer: dict[str, Any] | None = None + pending_name: str | None = None + + for raw in text.splitlines(): + line = raw.strip() + if not line: + continue + name = parse_comment_name(line) + if name: + pending_name = name + continue + if line.startswith("#") or line.startswith(";"): + continue + if line.startswith("[") and line.endswith("]"): + current_section = line[1:-1].strip().lower() + if current_section == "peer": + current_peer = { + "name": pending_name or "Unnamed peer", + "public_key": None, + "allowed_ips": [], + "persistent_keepalive": None, + "preshared_key_set": False, + } + peers.append(current_peer) + pending_name = None + continue + if "=" not in line: + continue + key, value = [x.strip() for x in line.split("=", 1)] + lk = key.lower() + if current_section == "interface": + if lk == "address": + interface["address"] = value + elif lk == "listenport": + interface["listen_port"] = int(value) if value.isdigit() else value + elif lk == "mtu": + interface["mtu"] = int(value) if value.isdigit() else value + elif lk == "privatekey": + interface["private_key_set"] = bool(value) + elif lk == "saveconfig": + interface["save_config"] = value + elif lk == "postup": + interface["post_up"].append(value) + elif lk == "postdown": + interface["post_down"].append(value) + elif current_section == "peer" and current_peer is not None: + if lk == "publickey": + current_peer["public_key"] = value + elif lk == "allowedips": + current_peer["allowed_ips"] = [v.strip() for v in value.split(",") if v.strip()] + elif lk == "persistentkeepalive": + current_peer["persistent_keepalive"] = int(value) if value.isdigit() else value + elif lk == "presharedkey": + current_peer["preshared_key_set"] = bool(value) + + vpn_network = None + if interface["address"]: + first_address = str(interface["address"]).split(",")[0].strip() + try: + vpn_network = str(ipaddress.ip_interface(first_address).network) + except ValueError: + pass + + routes: list[dict[str, Any]] = [] + firewall: list[dict[str, Any]] = [] + policy_table = None + gateway = None + uplink_interface = None + local_network = None + nat_enabled = False + forward_from_vpn = False + forward_to_vpn = False + + def parse_hook(hook: str, commands: list[str]) -> None: + nonlocal policy_table, gateway, uplink_interface, local_network, nat_enabled, forward_from_vpn, forward_to_vpn + for cmd in commands: + if re.search(r"\biptables\b", cmd): + kind = "Firewall" + if "-t nat" in cmd or "MASQUERADE" in cmd: + kind = "NAT" + nat_enabled = True + elif "REJECT" in cmd or "DROP" in cmd: + kind = "Access rule" + if hook == "PostUp" and iface_hint: + if re.search(r"(?:^|\s)-(?:A|I)\s+FORWARD\b.*\s-i\s+" + re.escape(iface_hint) + r"(?:\s|$)", cmd): + forward_from_vpn = True + if re.search(r"(?:^|\s)-(?:A|I)\s+FORWARD\b.*\s-o\s+" + re.escape(iface_hint) + r"(?:\s|$)", cmd): + forward_to_vpn = True + firewall.append({"hook": hook, "kind": kind, "command": cmd}) + continue + + if re.search(r"\bip\s+rule\s+(add|del)\b", cmd): + m = re.search(r"\btable\s+(\d+)\b", cmd) + if m and hook == "PostUp": + policy_table = m.group(1) + continue + + if re.search(r"\bip\s+route\s+(add|replace|del)\b", cmd): + network = None + mnet = re.search(r"\broute\s+(?:add|replace|del)\s+([^\s]+)", cmd) + if mnet: + network = mnet.group(1) + mtable = re.search(r"\btable\s+(\d+)\b", cmd) + mvia = re.search(r"\bvia\s+([^\s]+)", cmd) + mdev = re.search(r"\bdev\s+([^\s]+)", cmd) + if hook == "PostUp": + routes.append({ + "hook": hook, + "network": network, + "table": mtable.group(1) if mtable else "main", + "via": mvia.group(1) if mvia else None, + "device": mdev.group(1) if mdev else None, + "command": cmd, + }) + if network == "default" and mvia: + gateway = mvia.group(1) + if mdev: + uplink_interface = mdev.group(1) + + parse_hook("PostUp", interface["post_up"]) + parse_hook("PostDown", interface["post_down"]) + + if uplink_interface: + for route in routes: + if route.get("device") == uplink_interface and route.get("network") != "default": + local_network = route.get("network") + break + + vpn_network_obj = None + if vpn_network: + try: + vpn_network_obj = ipaddress.ip_network(vpn_network, strict=False) + except ValueError: + vpn_network_obj = None + + for peer in peers: + vpn_address = None + remote_networks: list[str] = [] + for allowed in peer["allowed_ips"]: + try: + net = ipaddress.ip_network(allowed, strict=False) + # A valid WireGuard peer may contain both IPv4 and IPv6 AllowedIPs + # (for example 0.0.0.0/0, ::/0). Never compare networks of + # different IP versions: ipaddress raises TypeError and that used + # to break the entire WGTools snapshot/provisioning page. + is_peer_vpn_address = ( + vpn_network_obj is not None + and net.version == vpn_network_obj.version + and net.subnet_of(vpn_network_obj) + and net.prefixlen == vpn_network_obj.max_prefixlen + and vpn_address is None + ) + if is_peer_vpn_address: + vpn_address = allowed + else: + remote_networks.append(allowed) + except (ValueError, TypeError): + remote_networks.append(allowed) + peer["vpn_address"] = vpn_address + peer["remote_networks"] = remote_networks + + return { + "interface": interface, + "peers": peers, + "routes": routes, + "firewall": firewall, + "detected": { + "vpn_network": vpn_network, + "policy_table": policy_table, + "gateway": gateway, + "uplink_interface": uplink_interface, + "local_network": local_network, + "nat_enabled": nat_enabled, + "forward_from_vpn": forward_from_vpn, + "forward_to_vpn": forward_to_vpn, + }, + } + + +def wg_installed() -> bool: + return shutil.which("wg") is not None and shutil.which("wg-quick") is not None + + +def wg_dump(iface: str) -> dict[str, Any]: + wg = shutil.which("wg") + if not wg: + return {"running": False, "listen_port": None, "public_key": None, "peers": {}, "error": "WireGuard tools are not installed"} + rc, out, err = run([wg, "show", iface, "dump"]) + if rc != 0: + return {"running": False, "listen_port": None, "public_key": None, "peers": {}, "error": err or out or "Interface is not running"} + lines = out.splitlines() + if not lines: + return {"running": False, "listen_port": None, "public_key": None, "peers": {}} + first = lines[0].split("\t") + public_key = first[1] if len(first) > 1 else None + listen_port = int(first[2]) if len(first) > 2 and first[2].isdigit() else (first[2] if len(first) > 2 else None) + peers: dict[str, Any] = {} + for line in lines[1:]: + cols = line.split("\t") + if len(cols) < 8: + continue + pub = cols[0] + peers[pub] = { + "public_key": pub, + "preshared_key_set": bool(cols[1] and set(cols[1]) != {"0", "="}), + "endpoint": cols[2] or None, + "allowed_ips_runtime": [x.strip() for x in cols[3].split(",") if x.strip()], + "latest_handshake": int(cols[4] or 0), + "rx_bytes": int(cols[5] or 0), + "tx_bytes": int(cols[6] or 0), + "persistent_keepalive_runtime": int(cols[7]) if cols[7].isdigit() else 0, + } + return {"running": True, "listen_port": listen_port, "public_key": public_key, "peers": peers} + + +def default_route_info() -> dict[str, Any]: + ip = shutil.which("ip") or "/usr/sbin/ip" + rc, out, _ = run([ip, "-4", "route", "show", "default"]) + gateway = None + uplink = None + if rc == 0 and out: + line = out.splitlines()[0] + mgw = re.search(r"\bvia\s+(\S+)", line) + mdev = re.search(r"\bdev\s+(\S+)", line) + gateway = mgw.group(1) if mgw else None + uplink = mdev.group(1) if mdev else None + + local_network = None + if uplink: + rc, out, _ = run([ip, "-4", "route", "show", "dev", uplink, "scope", "link"]) + if rc == 0: + for line in out.splitlines(): + first = line.split()[0] if line.split() else "" + try: + net = ipaddress.ip_network(first, strict=False) + if not net.is_loopback and not net.is_link_local: + local_network = str(net) + break + except ValueError: + continue + return {"default_gateway": gateway, "default_uplink": uplink, "local_network": local_network} + + +def diagnostics(iface: str, cfg: dict[str, Any] | None = None, dump: dict[str, Any] | None = None) -> list[dict[str, Any]]: + installed = wg_installed() + config_exists = (WG_DIR / f"{iface}.conf").exists() + checks: list[dict[str, Any]] = [ + {"label": "WireGuard installed", "ok": installed, "detail": "wg and wg-quick are available" if installed else "WireGuard tools are not installed"}, + {"label": f"Configuration {iface}.conf", "ok": config_exists, "detail": str(WG_DIR / f"{iface}.conf") if config_exists else "Server has not been configured yet"}, + ] + + if not installed or not config_exists: + return checks + + if cfg is None: + cfg = parse_config(read_config_text(iface), iface) + if dump is None: + dump = wg_dump(iface) + + checks.append({ + "label": f"WireGuard interface {iface}", + "ok": bool(dump.get("running")), + "detail": "Interface is available via wg show" if dump.get("running") else dump.get("error", "Interface is not running"), + }) + + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + rc, out, err = run([systemctl, "is-active", f"wg-quick@{iface}.service"]) + checks.append({"label": f"wg-quick@{iface}", "ok": rc == 0 and out == "active", "detail": out or err or "unknown"}) + + sysctl = shutil.which("sysctl") or "/usr/sbin/sysctl" + rc, out, err = run([sysctl, "-n", "net.ipv4.ip_forward"]) + ipf = rc == 0 and out.strip() == "1" + checks.append({"label": "IPv4 forwarding", "ok": ipf, "detail": f"net.ipv4.ip_forward={out.strip() if out else '?'}"}) + + listen_port = dump.get("listen_port") or cfg.get("interface", {}).get("listen_port") + if listen_port: + ss = shutil.which("ss") or "/usr/bin/ss" + rc, out, err = run([ss, "-lun"]) + present = rc == 0 and re.search(rf":{re.escape(str(listen_port))}\b", out) is not None + checks.append({"label": f"UDP {listen_port} listening", "ok": present, "detail": "UDP socket found" if present else "UDP socket not found in ss -lun"}) + + table = cfg.get("detected", {}).get("policy_table") + if table: + ip = shutil.which("ip") or "/usr/sbin/ip" + rc, out, err = run([ip, "route", "show", "table", str(table)]) + checks.append({"label": f"Routing table {table}", "ok": rc == 0 and bool(out.strip()), "detail": out.splitlines()[0] if out else (err or "Table is empty")}) + + nat_expected = bool(cfg.get("detected", {}).get("nat_enabled")) + if nat_expected: + iptables = shutil.which("iptables") + if not iptables: + checks.append({"label": "NAT / Masquerade", "ok": False, "detail": "iptables is not installed"}) + else: + rc, out, err = run([iptables, "-t", "nat", "-S", "POSTROUTING"]) + vpn_net = cfg.get("detected", {}).get("vpn_network") or "" + uplink = cfg.get("detected", {}).get("uplink_interface") or "" + found = rc == 0 and "MASQUERADE" in out and (not vpn_net or vpn_net in out) and (not uplink or uplink in out) + checks.append({"label": "NAT / Masquerade", "ok": found, "detail": "Matching POSTROUTING rule found" if found else (err or "Expected MASQUERADE rule was not found")}) + + ip = shutil.which("ip") or "/usr/sbin/ip" + rc, out, err = run([ip, "address", "show", "dev", iface]) + address = cfg.get("interface", {}).get("address") + addr_ip = str(address).split("/")[0] if address else "" + has_addr = rc == 0 and (not addr_ip or addr_ip in out) + checks.append({"label": f"{iface} address", "ok": has_addr, "detail": address or (err or "No configured address")}) + return checks + + + +def _route_remote_networks(cfg: dict[str, Any]) -> set[str]: + return { + str(net).strip() + for peer in cfg.get("peers", []) + for net in (peer.get("remote_networks") or []) + if str(net).strip() + } + + +def _route_category(route: dict[str, Any], cfg: dict[str, Any], iface: str) -> tuple[str, bool]: + target = str(route.get("network") or "") + table = str(route.get("table") or "main") + device = str(route.get("device") or "") + via = str(route.get("via") or "") + detected = cfg.get("detected", {}) + vpn_network = str(detected.get("vpn_network") or "") + local_network = str(detected.get("local_network") or "") + policy_table = str(detected.get("policy_table") or "") + uplink = str(detected.get("uplink_interface") or "") + gateway = str(detected.get("gateway") or "") + remotes = _route_remote_networks(cfg) + + if target in remotes and device == iface: + return "site_to_site", False + if policy_table and table == policy_table: + if target == "default" and (not gateway or via == gateway): + return "server", False + if target == vpn_network and device == iface: + return "server", False + if local_network and target == local_network and (not uplink or device == uplink): + return "server", False + return "custom", True + + +def _parse_access_rule(command: str) -> dict[str, Any] | None: + compact = " ".join(str(command).split()) + if not re.search(r"\biptables\b", compact) or not re.search(r"\bFORWARD\b", compact): + return None + action_match = re.search(r"\s-j\s+(ACCEPT|REJECT|DROP)(?:\s|$)", compact) + if not action_match: + return None + # The simple editor intentionally supports only the common FORWARD rule shape. + # Interface-specific, stateful, multiport, mark and other advanced rules stay read-only + # and are still editable from the raw wg0.conf editor. + if re.search(r"\s(?:-i|-o|--sport|--sports|--dports|--sports|-m\s+(?!iprange\b|comment\b)|--state|--ctstate|--mark|--uid-owner)\b", compact): + return None + + def grab(pattern: str) -> str: + m = re.search(pattern, compact) + return m.group(1) if m else "" + + src_range = grab(r"--src-range\s+([^\s]+)") + dst_range = grab(r"--dst-range\s+([^\s]+)") + source = src_range or grab(r"(?:^|\s)-s\s+([^\s]+)") + destination = dst_range or grab(r"(?:^|\s)-d\s+([^\s]+)") + protocol = grab(r"(?:^|\s)-p\s+(tcp|udp)(?:\s|$)") + dport = grab(r"--dport\s+(\d+(?::\d+)?)") + managed_tag = grab(r"--comment\s+(wgtools-protect-[A-Za-z0-9_-]+)") + + # Reject any tokens we do not know how to recreate faithfully. + test = compact + test = re.sub(r"^.*?iptables\s+(?:-[AI])\s+FORWARD\b", "", test).strip() + patterns = [ + r"(?:^|\s)-m\s+iprange(?=\s|$)", + r"(?:^|\s)-m\s+comment(?=\s|$)", + r"(?:^|\s)--comment\s+wgtools-protect-[A-Za-z0-9_-]+", + r"(?:^|\s)--src-range\s+[^\s]+", + r"(?:^|\s)--dst-range\s+[^\s]+", + r"(?:^|\s)-s\s+[^\s]+", + r"(?:^|\s)-d\s+[^\s]+", + r"(?:^|\s)-p\s+(?:tcp|udp)(?=\s|$)", + r"(?:^|\s)--dport\s+\d+(?::\d+)?", + r"(?:^|\s)-j\s+(?:ACCEPT|REJECT|DROP)(?=\s|$)", + ] + for pattern in patterns: + test = re.sub(pattern, " ", test) + if test.strip(): + return None + + return { + "source": source, + "destination": destination, + "action": action_match.group(1), + "protocol": protocol or "any", + "destination_port": dport, + "managed_tag": managed_tag, + } + + +def _is_peer_isolation_access_rule(access: dict[str, Any], meta: dict[str, Any] | None, cfg: dict[str, Any]) -> bool: + if not meta or not bool(meta.get("peer_isolation")) or str(access.get("action") or "") != "REJECT": + return False + try: + source = str(ipaddress.ip_network(str(access.get("source") or ""), strict=False)) + destination = str(ipaddress.ip_network(str(access.get("destination") or ""), strict=False)) + client = str(ipaddress.ip_network(str(meta.get("vpn_address") or ""), strict=False)) + vpn_network = str(ipaddress.ip_network(str(cfg.get("detected", {}).get("vpn_network") or ""), strict=False)) + except ValueError: + return False + return (source == client and destination == vpn_network) or (source == vpn_network and destination == client) + + +def describe_server_items(cfg: dict[str, Any], iface: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + route_items: list[dict[str, Any]] = [] + for route in cfg.get("routes", []): + item = dict(route) + category, editable = _route_category(item, cfg, iface) + item["category"] = category + item["editable"] = editable + item["id"] = hashlib.sha256(str(item.get("command") or "").encode("utf-8")).hexdigest()[:16] + route_items.append(item) + + firewall_items: list[dict[str, Any]] = [] + old_cfg = cfg + remote_set = _route_remote_networks(cfg) + # Resolve WGTools-managed policy tags once. Looking up every firewall row + # by rescanning all client metadata becomes noticeably expensive on large + # group deployments. + policy_meta_by_tag = { + client_policy_tag(str(meta.get("public_key") or "")): meta + for meta in iter_client_metas() + if meta.get("public_key") + } + seen_up: set[str] = set() + for row in cfg.get("firewall", []): + if row.get("hook") != "PostUp": + continue + cmd = str(row.get("command") or "") + if not cmd or cmd in seen_up: + continue + seen_up.add(cmd) + managed_kind = _managed_hook_kind(cmd, iface, old_cfg, remote_set) + access = _parse_access_rule(cmd) + if managed_kind in {"forward_from", "forward_to", "nat"}: + category = "server" + editable = False + elif access is not None: + category = "access" + # Managed ACCEPT rows are client-local exceptions. They are edited + # from the client form so their ordering relative to the broader + # managed REJECT policy stays deterministic. + managed_meta = policy_meta_by_tag.get(str(access.get("managed_tag") or "")) if access.get("managed_tag") else None + managed_group = bool(managed_meta and managed_meta.get("group_id")) + managed_isolation = _is_peer_isolation_access_rule(access, managed_meta, cfg) + editable = not managed_group and not managed_isolation and not (access.get("managed_tag") and access.get("action") == "ACCEPT") + else: + category = "advanced" + editable = False + item = { + "id": hashlib.sha256(cmd.encode("utf-8")).hexdigest()[:16], + "hook": "PostUp", + "kind": row.get("kind") or "Firewall", + "command": cmd, + "category": category, + "editable": editable, + "access": access, + } + firewall_items.append(item) + return route_items, firewall_items + +def _proc_default_uplink() -> str | None: + """Return the host default IPv4 interface without spawning `ip`. + + Dashboard snapshots run every few seconds. Reading /proc avoids paying for + route helper subprocesses merely to select the NIC used for host metrics. + """ + try: + lines = Path("/proc/net/route").read_text(encoding="utf-8", errors="replace").splitlines()[1:] + for line in lines: + cols = line.split() + if len(cols) >= 4 and cols[1] == "00000000" and int(cols[3], 16) & 0x2: + return cols[0] + except Exception: + pass + return None + + +def _ip_forwarding_enabled() -> bool: + try: + return Path("/proc/sys/net/ipv4/ip_forward").read_text(encoding="utf-8", errors="replace").strip() == "1" + except Exception: + return False + + +def build_snapshot(iface: str, view: str = "full") -> dict[str, Any]: + """Build a UI snapshot, doing only the work required by the current page. + + `full` preserves the server/settings payload. `clients` skips host metrics, + diagnostics, firewall/route descriptions and backup scans. `dashboard` + skips client-editor/group expansion and server-management data; diagnostics + are fetched independently so they never block first paint. + """ + view = str(view or "full").strip().lower() + if view not in {"full", "clients", "dashboard", "peers", "server"}: + view = "full" + full_view = view == "full" + clients_view = view == "clients" + dashboard_view = view == "dashboard" + peers_view = view == "peers" + server_view = view == "server" + detailed_clients = full_view or clients_view + + installed = wg_installed() + config_path = WG_DIR / f"{iface}.conf" + config_exists = config_path.exists() + + cfg: dict[str, Any] = { + "interface": {"address": None, "listen_port": None, "mtu": None, "private_key_set": False, "save_config": None, "post_up": [], "post_down": []}, + "peers": [], + "routes": [], + "firewall": [], + "detected": {"vpn_network": None, "policy_table": None, "gateway": None, "uplink_interface": None, "local_network": None, "nat_enabled": False, "forward_from_vpn": False, "forward_to_vpn": False}, + } + config_parse_error = None + if config_exists: + try: + cfg = parse_config(read_config_text(iface), iface) + except Exception as exc: + config_parse_error = str(exc) + + dump = wg_dump(iface) if installed else {"running": False, "listen_port": None, "public_key": None, "peers": {}} + runtime = dump.get("peers", {}) + + # Read client metadata once. The old path opened the same files repeatedly + # per peer and again for group counts, which became very visible when merely + # switching to Clients/Dashboard. + all_client_metas = [] if (peers_view or server_view) else iter_client_metas() + meta_by_public_key = { + str(meta.get("public_key") or ""): meta + for meta in all_client_metas + if str(meta.get("public_key") or "") and (not meta.get("interface") or str(meta.get("interface")) == iface) + } + groups = iter_groups(iface) if detailed_clients else [] + groups_by_id = {str(group.get("id") or ""): group for group in groups if group.get("id")} + + peers: list[dict[str, Any]] = [] + for peer in cfg.get("peers", []): + if server_view: + continue + merged = dict(peer) + live = runtime.get(peer.get("public_key"), {}) + merged.update(live) + pub = str(peer.get("public_key") or "") + meta = meta_by_public_key.get(pub) + + if dashboard_view or peers_view: + # Dashboard only needs policy state that affects the status badge; + # background peer summaries need no client metadata at all. + if dashboard_view and meta: + merged["expired_disabled"] = bool(meta.get("expired_disabled")) + merged["schedule_disabled"] = bool(meta.get("schedule_disabled")) + peers.append(merged) + continue + + merged["managed"] = bool(meta and meta.get("private_key")) + if meta: + merged["client_endpoint"] = meta.get("endpoint") + merged["client_allowed_ips"] = meta.get("client_allowed_ips", []) + merged["client_route_preset"] = meta.get("client_route_preset") or _infer_route_preset(cfg, list(meta.get("client_allowed_ips") or []), bool(meta.get("protect_local_networks"))) + merged["protect_local_networks"] = bool(meta.get("protect_local_networks")) + merged["local_access_exceptions"] = meta.get("local_access_exceptions", []) + merged["client_dns"] = meta.get("dns", []) + merged["group_id"] = str(meta.get("group_id") or "") + merged["policy_mode"] = str(meta.get("policy_mode") or "inherit") if meta.get("group_id") else "" + merged["internet_access"] = str(meta.get("internet_access") or "inherit") if meta.get("group_id") else "" + merged["local_access"] = str(meta.get("local_access") or "inherit") if meta.get("group_id") else "" + merged["policy_allow"] = meta.get("policy_allow", []) + merged["policy_deny"] = meta.get("policy_deny", []) + merged["config_mode"] = str(meta.get("config_mode") or "") if meta.get("group_id") else "" + merged["preshared_key_enabled"] = bool(meta.get("preshared_key")) + merged["peer_isolation"] = bool(meta.get("peer_isolation")) + merged["expires_at"] = int(meta.get("expires_at") or 0) + merged["expiration_action"] = str(meta.get("expiration_action") or "delete") + merged["expired_disabled"] = bool(meta.get("expired_disabled")) + merged["expired_at"] = int(meta.get("expired_at") or 0) + merged["access_schedule_enabled"] = bool(meta.get("access_schedule_enabled")) + merged["access_schedule_days"] = list(meta.get("access_schedule_days") or []) + merged["access_schedule_start"] = str(meta.get("access_schedule_start") or "08:00") + merged["access_schedule_end"] = str(meta.get("access_schedule_end") or "19:00") + merged["schedule_disabled"] = bool(meta.get("schedule_disabled")) + merged["connection_mode"] = str(meta.get("connection_mode") or "direct") + merged["relay_vps_id"] = str(meta.get("relay_vps_id") or "") + try: + merged["schedule_allowed_now"] = client_schedule_allows(meta) if meta.get("access_schedule_enabled") else True + except Exception: + merged["schedule_allowed_now"] = False + merged.update(_client_group_snapshot(meta, cfg, iface, groups_by_id)) + peers.append(merged) + + # Dashboard and Clients both display lifetime peer counters; keep this one + # durable merge, but avoid all unrelated management work around it. + if peers_view or server_view: + traffic_totals = {"rx_bytes": 0, "tx_bytes": 0} + else: + peers, traffic_totals = merge_wireguard_traffic(iface, peers) + + next_free = next_free_address(cfg) if config_exists and detailed_clients else None + detected = cfg.get("detected") or {} + + if full_view or server_view: + route_info = default_route_info() + system = {"ip_forwarding": _ip_forwarding_enabled(), **route_info} + if full_view: + metrics = system_metrics(route_info.get("default_uplink")) + _record_metrics_history(metrics) + else: + metrics = None + elif dashboard_view: + uplink = str(detected.get("uplink_interface") or "").strip() or _proc_default_uplink() + system = { + "ip_forwarding": _ip_forwarding_enabled(), + "default_gateway": detected.get("gateway"), + "default_uplink": uplink, + "local_network": detected.get("local_network"), + } + metrics = system_metrics(uplink) + else: + system = { + "ip_forwarding": None, + "default_gateway": detected.get("gateway"), + "default_uplink": detected.get("uplink_interface"), + "local_network": detected.get("local_network"), + } + metrics = None + + if not installed: + server_state = "not_installed" + elif not config_exists: + server_state = "not_configured" + elif dump.get("running"): + server_state = "running" + else: + server_state = "stopped" + + route_items, firewall_items = describe_server_items(cfg, iface) if (full_view or server_view) and config_exists and not config_parse_error else ([], []) + diagnostic_items = diagnostics(iface, cfg if config_exists else None, dump if installed else None) if full_view else None + if config_parse_error and diagnostic_items is not None: + diagnostic_items.insert(2, { + "label": "Configuration parse", + "ok": False, + "detail": config_parse_error, + }) + + group_rows: list[dict[str, Any]] = [] + if detailed_clients: + member_counts: dict[str, int] = {} + for meta in all_client_metas: + if str(meta.get("interface") or "") != iface: + continue + group_id = str(meta.get("group_id") or "") + if group_id: + member_counts[group_id] = member_counts.get(group_id, 0) + 1 + for group in groups: + row = dict(group) + row["member_count"] = member_counts.get(str(group.get("id") or ""), 0) + row["resolved_defaults"] = _group_defaults_for_config(group, cfg) if config_exists and not config_parse_error else group.get("defaults", {}) + group_rows.append(row) + + result: dict[str, Any] = { + "ok": True, + "timestamp": int(time.time()), + "interface": iface, + "running": bool(dump.get("running")), + "listen_port": dump.get("listen_port"), + "public_key": dump.get("public_key"), + "config": cfg, + "peers": peers, + "traffic_totals": traffic_totals, + "system": system, + "wireguard": { + "installed": installed, + "config_exists": config_exists, + "config_path": str(config_path), + "config_error": config_parse_error, + "state": server_state, + }, + } + if detailed_clients: + result["client_groups"] = group_rows + result["next_free_address"] = next_free + if metrics is not None: + result["metrics"] = metrics + if full_view: + result.update({ + "route_items": route_items, + "firewall_items": firewall_items, + "backups": backup_info(iface), + "diagnostics": diagnostic_items or [], + }) + elif server_view: + result.update({ + "route_items": route_items, + "firewall_items": firewall_items, + }) + return result + + +def build_diagnostics(iface: str) -> dict[str, Any]: + """Run only diagnostics, without constructing a full UI snapshot first.""" + installed = wg_installed() + config_path = WG_DIR / f"{iface}.conf" + cfg: dict[str, Any] | None = None + parse_error = "" + if config_path.exists(): + try: + cfg = parse_config(read_config_text(iface), iface) + except Exception as exc: + parse_error = str(exc) + dump = wg_dump(iface) if installed else {"running": False, "listen_port": None, "public_key": None, "peers": {}} + items = diagnostics(iface, cfg if cfg is not None else None, dump if installed else None) + if parse_error: + items.insert(2, {"label": "Configuration parse", "ok": False, "detail": parse_error}) + return {"ok": True, "interface": iface, "diagnostics": items} + +def _trace_target_host(raw: Any) -> str: + value = str(raw or "").strip() + if not value or len(value) > 320: + raise ValueError("Enter an IPv4 address or hostname") + # Accept a pasted URL as a convenience, but trace only its host. + try: + parsed = urllib.parse.urlsplit(value if "://" in value else f"//{value}") + host = (parsed.hostname or "").strip().rstrip(".") + except Exception: + host = "" + if not host: + host = value.strip("[]").rstrip(".") + if len(host) > 253 or any(ch.isspace() for ch in host): + raise ValueError("Invalid trace target") + return host + + +def _resolve_trace_ipv4(host: str) -> str: + try: + literal = ipaddress.ip_address(host) + if literal.version != 4: + raise ValueError("IPv6 traceroute is not enabled yet") + return str(literal) + except ValueError as exc: + if "IPv6 traceroute" in str(exc): + raise + try: + infos = socket.getaddrinfo(host, None, socket.AF_INET, socket.SOCK_STREAM) + except socket.gaierror as exc: + raise ValueError(f"Could not resolve {host}") from exc + addresses = [] + for info in infos: + address = str(info[4][0]) + if address not in addresses: + addresses.append(address) + if not addresses: + raise ValueError(f"No IPv4 address found for {host}") + return addresses[0] + + +def _parse_ping_output(text: str) -> dict[str, Any]: + result: dict[str, Any] = {"sent": 0, "received": 0, "loss_percent": 100.0, "min_ms": None, "avg_ms": None, "max_ms": None} + summary = re.search(r"(\d+) packets transmitted, (\d+) received,.*?([0-9.]+)% packet loss", text) + if summary: + result["sent"] = int(summary.group(1)) + result["received"] = int(summary.group(2)) + result["loss_percent"] = float(summary.group(3)) + rtt = re.search(r"(?:rtt|round-trip) min/avg/max/(?:mdev|stddev) = ([0-9.]+)/([0-9.]+)/([0-9.]+)/", text) + if rtt: + result["min_ms"] = round(float(rtt.group(1)), 2) + result["avg_ms"] = round(float(rtt.group(2)), 2) + result["max_ms"] = round(float(rtt.group(3)), 2) + return result + + +def _parse_traceroute_output(text: str, target_ip: str) -> list[dict[str, Any]]: + hops: list[dict[str, Any]] = [] + previous_avg: float | None = None + ip_re = re.compile(r"(? dict[str, Any]: + try: + data = json.loads(TRACE_GEO_CACHE_PATH.read_text(encoding="utf-8")) + return data if isinstance(data, dict) else {} + except Exception: + return {} + + +def _save_trace_geo_cache(cache: dict[str, Any]) -> None: + try: + now = int(time.time()) + cleaned = { + ip: item for ip, item in cache.items() + if isinstance(item, dict) and now - int(item.get("cached_at") or 0) <= TRACE_GEO_CACHE_TTL + } + if len(cleaned) > 500: + cleaned = dict(sorted(cleaned.items(), key=lambda pair: int(pair[1].get("cached_at") or 0), reverse=True)[:500]) + TRACE_GEO_CACHE_PATH.write_text(json.dumps(cleaned, ensure_ascii=False), encoding="utf-8") + TRACE_GEO_CACHE_PATH.chmod(0o600) + except Exception: + pass + + +def _trace_geo_lookup(ip: str, language: str = "en") -> dict[str, Any] | None: + try: + address = ipaddress.ip_address(ip) + if not address.is_global: + return None + except ValueError: + return None + lang = "ru" if str(language).lower() == "ru" else "en" + fields = "success,ip,continent,country,country_code,region,city,latitude,longitude,connection" + url = f"https://ipwho.is/{urllib.parse.quote(ip, safe='')}?fields={urllib.parse.quote(fields)}&lang={lang}" + req = urllib.request.Request(url, headers={"User-Agent": "WGTools/0.40.0 network-trace"}) + try: + with urllib.request.urlopen(req, timeout=3.5) as response: + payload = json.loads(response.read().decode("utf-8", errors="replace")) + except Exception: + return None + if not isinstance(payload, dict) or not payload.get("success", False): + return None + try: + latitude = float(payload.get("latitude")) + longitude = float(payload.get("longitude")) + except (TypeError, ValueError): + return None + connection = payload.get("connection") if isinstance(payload.get("connection"), dict) else {} + return { + "latitude": latitude, + "longitude": longitude, + "city": str(payload.get("city") or ""), + "region": str(payload.get("region") or ""), + "country": str(payload.get("country") or ""), + "country_code": str(payload.get("country_code") or ""), + "asn": str(connection.get("asn") or ""), + "org": str(connection.get("org") or connection.get("isp") or ""), + } + + +def _trace_geolocate(hops: list[dict[str, Any]], language: str, extra_ips: list[str] | None = None) -> tuple[dict[str, dict[str, Any]], bool]: + ips = [] + for hop in hops: + ip = str(hop.get("ip") or "") + try: + if ip and ipaddress.ip_address(ip).is_global and ip not in ips: + ips.append(ip) + except ValueError: + pass + for candidate in extra_ips or []: + try: + if ipaddress.ip_address(candidate).is_global and candidate not in ips: + ips.append(candidate) + except ValueError: + pass + if not ips: + return {}, False + cache = _load_trace_geo_cache() + now = int(time.time()) + result: dict[str, dict[str, Any]] = {} + missing = [] + for ip in ips: + cached = cache.get(ip) + if isinstance(cached, dict) and now - int(cached.get("cached_at") or 0) <= TRACE_GEO_CACHE_TTL: + result[ip] = {k: v for k, v in cached.items() if k != "cached_at"} + else: + missing.append(ip) + lookup_failed = False + if missing: + with ThreadPoolExecutor(max_workers=min(6, len(missing))) as pool: + futures = {pool.submit(_trace_geo_lookup, ip, language): ip for ip in missing} + for future in as_completed(futures): + ip = futures[future] + try: + geo = future.result() + except Exception: + geo = None + if geo: + result[ip] = geo + cache[ip] = {**geo, "cached_at": now} + else: + lookup_failed = True + _save_trace_geo_cache(cache) + return result, lookup_failed + + +def network_trace(payload: dict[str, Any]) -> dict[str, Any]: + host = _trace_target_host(payload.get("target")) + target_ip = _resolve_trace_ipv4(host) + ping_path = shutil.which("ping") + trace_path = shutil.which("traceroute") + if not ping_path: + raise RuntimeError("ping is not installed (install iputils-ping)") + if not trace_path: + raise RuntimeError("traceroute is not installed") + + ping_rc, ping_out, ping_err = run([ping_path, "-n", "-c", "4", "-W", "2", target_ip], timeout=12) + ping = _parse_ping_output("\n".join(part for part in (ping_out, ping_err) if part)) + ping["reachable"] = bool(ping.get("received", 0)) + ping["return_code"] = ping_rc + + started = time.monotonic() + trace_rc, trace_out, trace_err = run([trace_path, "-n", "-q", "2", "-w", "1", "-m", "30", target_ip], timeout=68) + trace_seconds = round(time.monotonic() - started, 2) + hops = _parse_traceroute_output("\n".join(part for part in (trace_out, trace_err) if part), target_ip) + if not hops and trace_rc not in (0, 1): + raise RuntimeError(trace_err or trace_out or "Traceroute failed") + + geo: dict[str, dict[str, Any]] = {} + geo_partial = False + if bool(payload.get("geolocate", True)): + geo, geo_partial = _trace_geolocate(hops, str(payload.get("language") or "en"), [target_ip]) + for hop in hops: + ip = str(hop.get("ip") or "") + hop["geo"] = geo.get(ip) + + reached = any(bool(hop.get("reached")) for hop in hops) + return { + "ok": True, + "target": host, + "target_ip": target_ip, + "ping": ping, + "hops": hops, + "hop_count": len(hops), + "reached": reached, + "trace_seconds": trace_seconds, + "geolocate": bool(payload.get("geolocate", True)), + "geo_partial": geo_partial, + "target_geo": geo.get(target_ip), + } + + +def is_internal_interface(iface: str) -> bool: + value = str(iface or "").strip().lower() + return any(value.startswith(prefix) for prefix in INTERNAL_INTERFACE_PREFIXES) + + +def require_valid_iface(iface: str) -> None: + if not ALLOWED_IFACE_RE.fullmatch(iface): + raise ValueError("Invalid WireGuard interface name") + if is_internal_interface(iface): + raise ValueError("This WireGuard interface name is reserved for WGTools internal transport") + + +def install_wireguard() -> dict[str, Any]: + if wg_installed(): + return {"ok": True, "changed": False, "message": "WireGuard is already installed"} + + apt = shutil.which("apt-get") + if not apt: + raise RuntimeError("apt-get was not found; automatic installation is supported on Debian/Ubuntu systems") + + rc, out, err = run([apt, "update"], timeout=180) + if rc != 0: + raise RuntimeError(f"apt-get update failed: {(err or out)[-1600:]}") + + rc, out, err = run([apt, "install", "-y", "wireguard", "iptables", "iproute2"], timeout=240) + if rc != 0: + raise RuntimeError(f"WireGuard installation failed: {(err or out)[-2000:]}") + if not wg_installed(): + raise RuntimeError("Package installation completed, but wg/wg-quick are still unavailable") + return {"ok": True, "changed": True, "message": "WireGuard installed successfully"} + + +def validate_server_payload(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + require_valid_iface(iface) + + network_raw = str(payload.get("vpn_network", "")).strip() + try: + network = ipaddress.ip_network(network_raw, strict=True) + except ValueError as exc: + raise ValueError("VPN network must be a valid IPv4 network such as 10.77.0.0/24") from exc + if network.version != 4: + raise ValueError("Only IPv4 VPN networks are supported in this version") + if network.prefixlen > 30: + raise ValueError("VPN network must contain at least two usable addresses") + + address_raw = str(payload.get("server_address", "")).strip() + if not address_raw: + try: + first_host = next(network.hosts()) + except StopIteration as exc: + raise ValueError("VPN network has no usable host addresses") from exc + server_iface = ipaddress.ip_interface(f"{first_host}/{network.prefixlen}") + else: + try: + server_iface = ipaddress.ip_interface(address_raw) + except ValueError as exc: + raise ValueError("Server address must include a prefix, for example 10.77.0.1/24") from exc + if server_iface.version != 4 or server_iface.ip not in network or server_iface.network != network: + raise ValueError("Server address must belong to the selected VPN network and use the same prefix") + if server_iface.ip == network.network_address or server_iface.ip == network.broadcast_address: + raise ValueError("Server address cannot be the network or broadcast address") + + try: + listen_port = int(payload.get("listen_port", 51820)) + except (TypeError, ValueError) as exc: + raise ValueError("Listen port must be a number") from exc + if not 1 <= listen_port <= 65535: + raise ValueError("Listen port must be between 1 and 65535") + + try: + mtu = int(payload.get("mtu") or 0) + except (TypeError, ValueError) as exc: + raise ValueError("MTU must be a number") from exc + if mtu and not 576 <= mtu <= 65535: + raise ValueError("MTU must be empty/0 for automatic mode or between 576 and 65535") + + uplink = str(payload.get("uplink_interface", "")).strip() + if not uplink or not ALLOWED_IFACE_RE.fullmatch(uplink): + raise ValueError("A valid uplink interface is required") + if not (Path("/sys/class/net") / uplink).exists(): + raise ValueError(f"Network interface {uplink} does not exist") + + nat_enabled = bool(payload.get("nat_enabled", True)) + ip_forwarding = bool(payload.get("ip_forwarding", True)) + + table_raw = str(payload.get("policy_table", "")).strip() + policy_table: int | None = None + if table_raw: + try: + policy_table = int(table_raw) + except ValueError as exc: + raise ValueError("Policy routing table must be a number") from exc + if not 1 <= policy_table <= 32765: + raise ValueError("Policy routing table must be between 1 and 32765") + + gateway_raw = str(payload.get("gateway", "")).strip() + gateway = None + if gateway_raw: + try: + gateway = str(ipaddress.ip_address(gateway_raw)) + except ValueError as exc: + raise ValueError("Gateway must be a valid IPv4 address") from exc + if policy_table is not None and not gateway: + raise ValueError("Gateway is required when policy routing is enabled") + + local_raw = str(payload.get("local_network", "")).strip() + local_network = None + if local_raw: + try: + local = ipaddress.ip_network(local_raw, strict=True) + except ValueError as exc: + raise ValueError("Local network must be a valid IPv4 network") from exc + if local.version != 4: + raise ValueError("Only IPv4 local networks are supported") + local_network = str(local) + + _validate_cross_interface_server_settings(iface, network, listen_port, policy_table) + + return { + "network": str(network), + "server_address": str(server_iface), + "listen_port": listen_port, + "mtu": mtu, + "uplink_interface": uplink, + "nat_enabled": nat_enabled, + "ip_forwarding": ip_forwarding, + "policy_table": policy_table, + "gateway": gateway, + "local_network": local_network, + } + + +def generate_private_key() -> str: + wg = shutil.which("wg") + if not wg: + raise RuntimeError("WireGuard is not installed") + rc, out, err = run([wg, "genkey"]) + if rc != 0 or not out: + raise RuntimeError(err or "Failed to generate WireGuard private key") + return out.strip() + + +def private_to_public(private_key: str) -> str | None: + wg = shutil.which("wg") + if not wg: + return None + rc, out, _ = run([wg, "pubkey"], input_text=private_key + "\n") + return out.strip() if rc == 0 and out else None + + +def generate_preshared_key() -> str: + wg = shutil.which("wg") + if not wg: + raise RuntimeError("WireGuard is not installed") + rc, out, err = run([wg, "genpsk"]) + if rc != 0 or not out: + raise RuntimeError(err or "Failed to generate WireGuard preshared key") + return out.strip() + + +def create_server(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + if not wg_installed(): + raise RuntimeError("WireGuard is not installed") + + config_path = WG_DIR / f"{iface}.conf" + if config_path.exists(): + raise RuntimeError(f"{config_path} already exists; WGTools will not overwrite an existing server configuration") + + settings = validate_server_payload(iface, payload) + private_key = generate_private_key() + public_key = private_to_public(private_key) + network = settings["network"] + uplink = settings["uplink_interface"] + table = settings["policy_table"] + gateway = settings["gateway"] + local_network = settings["local_network"] + + post_up: list[str] = [] + post_down: list[str] = [] + + if settings["ip_forwarding"]: + post_up.append("sysctl -w net.ipv4.ip_forward=1") + + if table is not None: + post_up.append(f"ip rule add from {network} table {table}") + post_down.append(f"ip rule del from {network} table {table} 2>/dev/null || true") + post_up.append(f"ip route add default via {gateway} dev {uplink} table {table}") + post_down.append(f"ip route del default via {gateway} dev {uplink} table {table} 2>/dev/null || true") + if local_network: + post_up.append(f"ip route add {local_network} dev {uplink} table {table}") + post_down.append(f"ip route del {local_network} dev {uplink} table {table} 2>/dev/null || true") + post_up.append(f"ip route replace {network} dev {iface} table {table}") + post_down.append(f"ip route del {network} dev {iface} table {table} 2>/dev/null || true") + + post_up.append(f"iptables -A FORWARD -i {iface} -j ACCEPT") + post_down.append(f"iptables -D FORWARD -i {iface} -j ACCEPT 2>/dev/null || true") + post_up.append(f"iptables -A FORWARD -o {iface} -j ACCEPT") + post_down.append(f"iptables -D FORWARD -o {iface} -j ACCEPT 2>/dev/null || true") + + if settings["nat_enabled"]: + post_up.append(f"iptables -t nat -A POSTROUTING -s {network} -o {uplink} -j MASQUERADE") + post_down.append(f"iptables -t nat -D POSTROUTING -s {network} -o {uplink} -j MASQUERADE 2>/dev/null || true") + + lines = [ + "[Interface]", + f"Address = {settings['server_address']}", + f"ListenPort = {settings['listen_port']}", + ] + if settings.get("mtu"): + lines.append(f"MTU = {settings['mtu']}") + lines.extend([ + f"PrivateKey = {private_key}", + "SaveConfig = false", + "", + ]) + lines.extend(f"PostUp = {cmd}" for cmd in post_up) + if post_down: + lines.append("") + lines.extend(f"PostDown = {cmd}" for cmd in post_down) + lines.append("") + config_text = "\n".join(lines) + + WG_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(WG_DIR, 0o700) + tmp = WG_DIR / f".{iface}.conf.tmp" + tmp.write_text(config_text, encoding="utf-8") + os.chmod(tmp, 0o600) + os.replace(tmp, config_path) + os.chmod(config_path, 0o600) + + if settings["ip_forwarding"]: + sysctl_file = Path("/etc/sysctl.d/99-wgtools-wireguard.conf") + sysctl_file.write_text("net.ipv4.ip_forward=1\n", encoding="utf-8") + os.chmod(sysctl_file, 0o644) + sysctl = shutil.which("sysctl") or "/usr/sbin/sysctl" + run([sysctl, "-w", "net.ipv4.ip_forward=1"]) + + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + rc, out, err = run([systemctl, "enable", "--now", f"wg-quick@{iface}.service"], timeout=30) + if rc != 0: + run([systemctl, "disable", "--now", f"wg-quick@{iface}.service"], timeout=15) + failed_path = WG_DIR / f"{iface}.failed-{time.strftime('%Y%m%d-%H%M%S')}.conf" + try: + os.replace(config_path, failed_path) + except OSError: + failed_path = config_path + raise RuntimeError(f"wg-quick failed to start. Generated configuration was preserved as {failed_path}. Detail: {(err or out)[-1200:]}") + + dump = wg_dump(iface) + if not dump.get("running"): + raise RuntimeError("wg-quick started without an error, but the WireGuard interface is not visible in wg show") + + interface_meta_set(iface, {"display_name": str(payload.get("display_name") or iface)}) + + return { + "ok": True, + "message": "WireGuard server created and started", + "interface": iface, + "config_path": str(config_path), + "public_key": public_key, + "server": settings, + } + + + +def client_meta_path(public_key: str) -> Path: + digest = hashlib.sha256(public_key.encode("utf-8")).hexdigest() + return CLIENT_DIR / f"{digest}.json" + + +def load_client_meta(public_key: str) -> dict[str, Any] | None: + if not public_key: + return None + path = client_meta_path(public_key) + if not path.exists(): + return None + try: + data = json.loads(path.read_text(encoding="utf-8")) + return data if isinstance(data, dict) and data.get("public_key") == public_key else None + except Exception: + return None + + +def save_client_meta(meta: dict[str, Any]) -> None: + CLIENT_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(CLIENT_DIR, 0o700) + path = client_meta_path(str(meta["public_key"])) + tmp = path.with_suffix(".tmp") + tmp.write_text(json.dumps(meta, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + os.chmod(tmp, 0o600) + os.replace(tmp, path) + os.chmod(path, 0o600) + + +def delete_client_meta(public_key: str) -> None: + path = client_meta_path(public_key) + try: + path.unlink() + except FileNotFoundError: + pass + + +def iter_client_metas() -> list[dict[str, Any]]: + result: list[dict[str, Any]] = [] + if not CLIENT_DIR.exists(): + return result + for path in sorted(CLIENT_DIR.glob("*.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + if isinstance(data, dict) and data.get("public_key"): + result.append(data) + except Exception: + continue + return result + + +def _load_groups_document() -> dict[str, Any]: + if not GROUPS_PATH.exists(): + return {"version": 1, "groups": []} + try: + data = json.loads(GROUPS_PATH.read_text(encoding="utf-8")) + except Exception: + return {"version": 1, "groups": []} + if not isinstance(data, dict): + return {"version": 1, "groups": []} + raw_groups = data.get("groups") if isinstance(data.get("groups"), list) else [] + groups = [item for item in raw_groups if isinstance(item, dict) and item.get("id") and item.get("interface")] + return {"version": 1, "groups": groups} + + +def _save_groups_document(data: dict[str, Any]) -> None: + DATA_DIR.mkdir(parents=True, exist_ok=True) + GROUPS_PATH.parent.mkdir(parents=True, exist_ok=True) + tmp = GROUPS_PATH.with_suffix(".tmp") + payload = {"version": 1, "groups": list(data.get("groups") or [])} + tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + os.chmod(tmp, 0o600) + os.replace(tmp, GROUPS_PATH) + os.chmod(GROUPS_PATH, 0o600) + + +def iter_groups(interface: str | None = None) -> list[dict[str, Any]]: + groups = [dict(item) for item in _load_groups_document().get("groups", [])] + if interface is not None: + groups = [item for item in groups if str(item.get("interface") or "") == interface] + groups.sort(key=lambda item: (str(item.get("name") or "").casefold(), str(item.get("id") or ""))) + return groups + + +def load_group(group_id: str, interface: str | None = None) -> dict[str, Any] | None: + wanted = str(group_id or "").strip() + if not wanted: + return None + for item in iter_groups(interface): + if str(item.get("id") or "") == wanted: + return item + return None + + +def _group_member_metas(group_id: str, interface: str) -> list[dict[str, Any]]: + return [ + meta for meta in iter_client_metas() + if str(meta.get("interface") or "") == interface and str(meta.get("group_id") or "") == group_id + ] + + +def _validate_policy_access(value: Any, label: str, *, allow_inherit: bool) -> str: + text = str(value or ("inherit" if allow_inherit else "allow")).strip().lower() + allowed = {"allow", "block"} | ({"inherit"} if allow_inherit else set()) + if text not in allowed: + options = ", ".join(sorted(allowed)) + raise ValueError(f"{label} must be one of: {options}") + return text + + +def _validate_policy_lists(allow_values: Any, deny_values: Any) -> tuple[list[str], list[str]]: + allow = normalize_networks(allow_values, "Allowed policy addresses", allow_empty=True) + deny = normalize_networks(deny_values, "Blocked policy addresses", allow_empty=True) + for left in allow: + a = ipaddress.ip_network(left, strict=False) + for right in deny: + b = ipaddress.ip_network(right, strict=False) + if a.overlaps(b): + raise ValueError(f"Allowed policy network {a} overlaps blocked policy network {b}") + return allow, deny + + +def _route_preset_values(cfg: dict[str, Any], preset: str, custom_routes: list[str] | None = None) -> list[str]: + preset = str(preset or "full").strip().lower() + if preset not in {"full", "full_except_local", "vpn_lan", "vpn", "custom"}: + raise ValueError("Client route preset is invalid") + vpn = str(cfg.get("detected", {}).get("vpn_network") or "").strip() + local = str(cfg.get("detected", {}).get("local_network") or "").strip() + sites = sorted(_route_remote_networks(cfg)) + if preset in {"full", "full_except_local"}: + return ["0.0.0.0/0"] + if preset == "vpn": + return [vpn] if vpn else [] + if preset == "vpn_lan": + out: list[str] = [] + for raw in [vpn, local, *sites]: + if raw and raw not in out: + out.append(raw) + return out + return list(custom_routes or []) + + +def _infer_route_preset(cfg: dict[str, Any], routes: list[str], protect_local: bool = False) -> str: + if protect_local and "0.0.0.0/0" in routes: + return "full_except_local" + if routes == ["0.0.0.0/0"]: + return "full" + vpn = str(cfg.get("detected", {}).get("vpn_network") or "").strip() + if vpn and routes == [vpn]: + return "vpn" + expected = _route_preset_values(cfg, "vpn_lan") + if sorted(routes) == sorted(expected) and routes: + return "vpn_lan" + return "custom" + + +def validate_group_payload(iface: str, payload: dict[str, Any], existing_id: str | None = None) -> dict[str, Any]: + require_valid_iface(iface) + cfg = parse_config(read_config_text(iface), iface) + name = str(payload.get("name") or "").strip() + if not name or len(name) > 64 or any(ord(ch) < 32 for ch in name): + raise ValueError("Group name must be between 1 and 64 printable characters") + description = str(payload.get("description") or "").strip() + if len(description) > 240: + raise ValueError("Group description cannot exceed 240 characters") + for group in iter_groups(iface): + if existing_id and str(group.get("id") or "") == existing_id: + continue + if str(group.get("name") or "").casefold() == name.casefold(): + raise ValueError(f"A group named {name!r} already exists on {iface}") + + internet_access = _validate_policy_access(payload.get("internet_access", "allow"), "Internet access", allow_inherit=False) + local_access = _validate_policy_access(payload.get("local_access", "allow"), "Local network access", allow_inherit=False) + policy_allow, policy_deny = _validate_policy_lists(payload.get("policy_allow", []), payload.get("policy_deny", [])) + + route_preset = str(payload.get("route_preset") or "full").strip().lower() + custom_routes = normalize_networks(payload.get("client_allowed_ips", []), "Group client routes", allow_empty=route_preset != "custom") + routes = _route_preset_values(cfg, route_preset, custom_routes) + if not routes: + raise ValueError("Group client routes cannot be empty") + dns = normalize_dns(payload.get("dns", [])) + try: + keepalive = int(payload.get("persistent_keepalive", 25)) + except (TypeError, ValueError) as exc: + raise ValueError("Persistent keepalive must be a number") from exc + if not 0 <= keepalive <= 65535: + raise ValueError("Persistent keepalive must be between 0 and 65535") + + return { + "name": name, + "description": description, + "policy": { + "internet_access": internet_access, + "local_access": local_access, + "allow": policy_allow, + "deny": policy_deny, + }, + "defaults": { + "route_preset": route_preset, + "client_allowed_ips": routes, + "dns": dns, + "persistent_keepalive": keepalive, + }, + } + + +def _save_group_record(group: dict[str, Any]) -> None: + data = _load_groups_document() + groups = list(data.get("groups") or []) + replaced = False + for idx, current in enumerate(groups): + if str(current.get("id") or "") == str(group.get("id") or ""): + groups[idx] = group + replaced = True + break + if not replaced: + groups.append(group) + data["groups"] = groups + _save_groups_document(data) + + +def _sync_group_policy_transaction(iface: str) -> Path: + old_text = read_config_text(iface) + cfg = parse_config(old_text, iface) + new_text = sync_managed_client_policies(old_text, iface) + return write_config_transaction(iface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) + + +def group_create(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + values = validate_group_payload(iface, payload) + now = int(time.time()) + group = { + "id": "g_" + secrets.token_hex(8), + "interface": iface, + **values, + "created_at": now, + "updated_at": now, + } + _save_group_record(group) + return {"ok": True, "message": f"Group {group['name']} created", "group": group} + + +def group_update(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + group_id = str(payload.get("group_id") or "").strip() + old_group = load_group(group_id, iface) + if not old_group: + raise ValueError("Client group was not found") + values = validate_group_payload(iface, payload, existing_id=group_id) + new_group = {**old_group, **values, "updated_at": int(time.time())} + old_doc = _load_groups_document() + _save_group_record(new_group) + backup = None + policy_changed = old_group.get("policy") != new_group.get("policy") + try: + # Name/description/default-template edits do not alter live firewall + # policy and therefore must not rewrite the WireGuard config. + if policy_changed and _group_member_metas(group_id, iface): + backup = _sync_group_policy_transaction(iface) + except Exception: + _save_groups_document(old_doc) + raise + return {"ok": True, "message": f"Group {new_group['name']} updated", "group": new_group, "backup": str(backup) if backup else ""} + + +def group_delete(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + group_id = str(payload.get("group_id") or "").strip() + group = load_group(group_id, iface) + if not group: + raise ValueError("Client group was not found") + move_to = str(payload.get("move_to_group_id") or "").strip() + if move_to == group_id: + raise ValueError("Clients cannot be moved to the group being deleted") + target = load_group(move_to, iface) if move_to else None + if move_to and not target: + raise ValueError("Destination client group was not found") + + old_doc = _load_groups_document() + members = _group_member_metas(group_id, iface) + old_metas = {str(meta.get("public_key") or ""): dict(meta) for meta in members} + try: + for meta in members: + meta["group_id"] = move_to + meta["policy_mode"] = "inherit" if move_to else "" + meta["config_mode"] = "inherit" if move_to else "" + meta["internet_access"] = "inherit" + meta["local_access"] = "inherit" + meta["policy_allow"] = [] + meta["policy_deny"] = [] + meta["updated_at"] = int(time.time()) + save_client_meta(meta) + data = _load_groups_document() + data["groups"] = [item for item in data.get("groups", []) if str(item.get("id") or "") != group_id] + _save_groups_document(data) + backup = _sync_group_policy_transaction(iface) if members else None + except Exception: + _save_groups_document(old_doc) + for old_meta in old_metas.values(): + save_client_meta(old_meta) + raise + return { + "ok": True, + "message": f"Group {group.get('name') or group_id} deleted", + "moved_clients": len(members), + "backup": str(backup) if backup else "", + } + + +def _client_group_policy(meta: dict[str, Any], iface: str, group: dict[str, Any] | None = None) -> dict[str, Any] | None: + group_id = str(meta.get("group_id") or "").strip() + if not group_id: + return None + if group is None: + group = load_group(group_id, iface) + if not group: + return None + mode = str(meta.get("policy_mode") or "inherit").strip().lower() + if mode not in {"inherit", "custom"}: + mode = "inherit" + group_policy = group.get("policy") if isinstance(group.get("policy"), dict) else {} + base_internet = str(group_policy.get("internet_access") or "allow") + base_local = str(group_policy.get("local_access") or "allow") + group_allow = normalize_networks(group_policy.get("allow", []), "Group allowed addresses", allow_empty=True) + group_deny = normalize_networks(group_policy.get("deny", []), "Group blocked addresses", allow_empty=True) + client_allow = normalize_networks(meta.get("policy_allow", []), "Client allowed addresses", allow_empty=True) + client_deny = normalize_networks(meta.get("policy_deny", []), "Client blocked addresses", allow_empty=True) + + if mode == "custom": + internet = _validate_policy_access(meta.get("internet_access", "allow"), "Internet access", allow_inherit=False) + local = _validate_policy_access(meta.get("local_access", "allow"), "Local network access", allow_inherit=False) + group_allow = [] + group_deny = [] + else: + internet_override = _validate_policy_access(meta.get("internet_access", "inherit"), "Internet access", allow_inherit=True) + local_override = _validate_policy_access(meta.get("local_access", "inherit"), "Local network access", allow_inherit=True) + internet = base_internet if internet_override == "inherit" else internet_override + local = base_local if local_override == "inherit" else local_override + + return { + "group": group, + "mode": mode, + "internet_access": internet, + "local_access": local, + "group_allow": group_allow, + "group_deny": group_deny, + "client_allow": client_allow, + "client_deny": client_deny, + } + + +def _policy_logical_rules(meta: dict[str, Any], cfg: dict[str, Any], iface: str) -> list[tuple[str, str]]: + group_policy = _client_group_policy(meta, iface) + if not group_policy: + if not meta.get("protect_local_networks"): + return [] + exclusions = _policy_exclusions(meta) + effective_networks = [network for network in protected_networks(cfg) if network not in exclusions] + effective_objs = [ipaddress.ip_network(network, strict=False) for network in effective_networks] + allow_exceptions = [] + for raw in _local_access_exceptions(meta): + exc = ipaddress.ip_network(raw, strict=False) + if any(exc.subnet_of(parent) for parent in effective_objs): + allow_exceptions.append(str(exc)) + return [(dest, "ACCEPT") for dest in allow_exceptions] + [(dest, "REJECT") for dest in effective_networks] + + rules: list[tuple[str, str]] = [] + # Client-specific exceptions intentionally outrank group exceptions. + rules.extend((dest, "REJECT") for dest in group_policy["client_deny"]) + rules.extend((dest, "ACCEPT") for dest in group_policy["client_allow"]) + rules.extend((dest, "REJECT") for dest in group_policy["group_deny"]) + rules.extend((dest, "ACCEPT") for dest in group_policy["group_allow"]) + + local_networks = protected_networks(cfg) + vpn_network = str(cfg.get("detected", {}).get("vpn_network") or "").strip() + if group_policy["internet_access"] == "block": + # Internet policy must stay independent from future peer-isolation + # controls, so the VPN pool itself remains reachable. + if vpn_network: + rules.append((vpn_network, "ACCEPT")) + if group_policy["local_access"] == "allow": + rules.extend((dest, "ACCEPT") for dest in local_networks) + rules.append(("0.0.0.0/0", "REJECT")) + elif group_policy["local_access"] == "block": + rules.extend((dest, "REJECT") for dest in local_networks) + + # Remove exact duplicate rules while preserving priority/order. + out: list[tuple[str, str]] = [] + seen: set[tuple[str, str]] = set() + for destination, action in rules: + item = (destination, action) + if item not in seen: + seen.add(item) + out.append(item) + return out + + +def _group_defaults_for_config(group: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any]: + defaults = group.get("defaults") if isinstance(group.get("defaults"), dict) else {} + preset = str(defaults.get("route_preset") or "full").strip().lower() + stored_routes = normalize_networks(defaults.get("client_allowed_ips", []), "Group client routes", allow_empty=True) + routes = _route_preset_values(cfg, preset, stored_routes) + return { + "route_preset": preset, + "client_allowed_ips": routes, + "dns": normalize_dns(defaults.get("dns", [])), + "persistent_keepalive": int(defaults.get("persistent_keepalive", 25) or 0), + } + + +def _client_group_snapshot( + meta: dict[str, Any], + cfg: dict[str, Any], + iface: str, + groups_by_id: dict[str, dict[str, Any]] | None = None, +) -> dict[str, Any]: + group_id = str(meta.get("group_id") or "").strip() + group = (groups_by_id or {}).get(group_id) if groups_by_id is not None else (load_group(group_id, iface) if group_id else None) + if not group: + return { + "group_id": "", + "group_name": "", + "group_policy_mode": "", + "group_config_differs": False, + "effective_policy": None, + } + policy = _client_group_policy(meta, iface, group) + defaults = _group_defaults_for_config(group, cfg) + current_routes = normalize_networks(meta.get("client_allowed_ips", []), "Client routes", allow_empty=True) + current_preset = str(meta.get("client_route_preset") or "").strip().lower() + if not current_preset: + current_preset = _infer_route_preset(cfg, current_routes, bool(meta.get("protect_local_networks"))) + config_mode = str(meta.get("config_mode") or "inherit").strip().lower() + if config_mode not in {"inherit", "custom"}: + config_mode = "inherit" + differs = config_mode == "inherit" and ( + current_preset != defaults["route_preset"] + or sorted(current_routes) != sorted(defaults["client_allowed_ips"]) + or normalize_dns(meta.get("dns", [])) != defaults["dns"] + or int(meta.get("persistent_keepalive", 25) or 0) != defaults["persistent_keepalive"] + ) + return { + "group_id": group_id, + "group_name": str(group.get("name") or ""), + "group_policy_mode": str(meta.get("policy_mode") or "inherit"), + "group_config_mode": config_mode, + "group_config_differs": differs, + "effective_policy": { + "internet_access": policy.get("internet_access") if policy else "allow", + "local_access": policy.get("local_access") if policy else "allow", + "allow": [*(policy.get("group_allow") or []), *(policy.get("client_allow") or [])] if policy else [], + "deny": [*(policy.get("group_deny") or []), *(policy.get("client_deny") or [])] if policy else [], + }, + } + + +def client_policy_tag(public_key: str) -> str: + return "wgtools-protect-" + hashlib.sha256(public_key.encode("utf-8")).hexdigest()[:12] + + +def protected_networks(cfg: dict[str, Any]) -> list[str]: + values: list[str] = [] + local = str(cfg.get("detected", {}).get("local_network") or default_route_info().get("local_network") or "").strip() + if local: + values.append(local) + values.extend(sorted(_route_remote_networks(cfg))) + result: list[str] = [] + seen: set[str] = set() + for raw in values: + try: + net = ipaddress.ip_network(raw, strict=False) + except ValueError: + continue + if net.version != 4: + continue + value = str(net) + if value not in seen: + seen.add(value) + result.append(value) + return result + + +def _policy_exclusions(meta: dict[str, Any]) -> set[str]: + result: set[str] = set() + for raw in meta.get("protect_local_exclusions") or []: + try: + net = ipaddress.ip_network(str(raw).strip(), strict=False) + except ValueError: + continue + if net.version == 4: + result.add(str(net)) + return result + + +def _local_access_exceptions(meta: dict[str, Any]) -> list[str]: + result: list[str] = [] + for raw in meta.get("local_access_exceptions") or []: + try: + net = ipaddress.ip_network(str(raw).strip(), strict=False) + except ValueError: + continue + if net.version != 4: + continue + value = str(net) + if value not in result: + result.append(value) + return result + + +def _set_policy_exclusion_by_tag(tag: str, destination: str) -> dict[str, Any] | None: + meta = find_policy_meta_by_tag(tag) + if not meta: + return None + old_meta = dict(meta) + try: + network = ipaddress.ip_network(str(destination).strip(), strict=False) + except ValueError as exc: + raise ValueError("Managed policy destination is not a valid IPv4 network") from exc + exclusions = _policy_exclusions(meta) + exclusions.add(str(network)) + meta["protect_local_exclusions"] = sorted(exclusions) + meta["updated_at"] = int(time.time()) + save_client_meta(meta) + return old_meta + + +def managed_policy_commands( + public_key: str, + vpn_address: str, + logical_rules: list[tuple[str, str]], +) -> tuple[list[str], list[str]]: + tag = client_policy_tag(public_key) + source = vpn_address + up: list[str] = [] + down: list[str] = [] + # logical_rules is highest priority first. PostUp uses iptables -I, so write + # the commands in reverse order to reproduce that priority after boot. + for destination, action in reversed(logical_rules): + cmd = f"iptables -I FORWARD -s {source} -d {destination} -m comment --comment {tag} -j {action}" + up.append(cmd) + down.append(cmd.replace("iptables -I FORWARD", "iptables -D FORWARD", 1) + " 2>/dev/null || true") + return up, down + + +def _managed_policy_hook_commands(text: str) -> tuple[list[str], list[str]]: + up: list[str] = [] + down: list[str] = [] + for raw in text.replace("\r\n", "\n").replace("\r", "\n").splitlines(): + if "=" not in raw: + continue + key, value = [x.strip() for x in raw.split("=", 1)] + if "--comment wgtools-protect-" not in value: + continue + if key.lower() == "postup": + up.append(value) + elif key.lower() == "postdown": + down.append(value) + return up, down + + +def _peer_isolation_commands(public_key: str, vpn_address: str, vpn_network: str) -> tuple[list[str], list[str]]: + """Build symmetric FORWARD rules that isolate one VPN client from peers. + + The rules intentionally target only the WireGuard address pool. They do + not affect INPUT traffic to the WGTools server itself and do not block + Internet, local-LAN or Site-to-site destinations controlled by the other + client/group policy settings. + """ + if not vpn_network: + return [], [] + tag = client_policy_tag(public_key) + source = str(ipaddress.ip_network(vpn_address, strict=False)) + destination = source + specs = [ + (source, vpn_network, "REJECT"), + (vpn_network, destination, "REJECT"), + ] + up: list[str] = [] + down: list[str] = [] + for src, dst, action in specs: + cmd = f"iptables -I FORWARD -s {src} -d {dst} -m comment --comment {tag} -j {action}" + up.append(cmd) + down.append(cmd.replace("iptables -I FORWARD", "iptables -D FORWARD", 1) + " 2>/dev/null || true") + return up, down + + +def sync_managed_client_policies(text: str, iface: str) -> str: + old_up, old_down = _managed_policy_hook_commands(text) + if old_up or old_down: + text = _edit_interface_hooks(text, old_up, old_down, [], []) + cfg = parse_config(text, iface) + peers = {str(p.get("public_key") or ""): p for p in cfg.get("peers", [])} + add_up: list[str] = [] + add_down: list[str] = [] + isolation_up: list[str] = [] + isolation_down: list[str] = [] + vpn_network = str(cfg.get("detected", {}).get("vpn_network") or "").strip() + for meta in iter_client_metas(): + if meta.get("interface") and str(meta.get("interface")) != iface: + continue + public_key = str(meta.get("public_key") or "") + peer = peers.get(public_key) + if not peer: + continue + vpn_address = str(peer.get("vpn_address") or meta.get("vpn_address") or "").strip() + if not vpn_address: + continue + logical_rules = _policy_logical_rules(meta, cfg, iface) + if logical_rules: + up, down = managed_policy_commands(public_key, vpn_address, logical_rules) + add_up.extend(up) + add_down.extend(down) + if bool(meta.get("peer_isolation")) and not list(peer.get("remote_networks") or []): + up, down = _peer_isolation_commands(public_key, vpn_address, vpn_network) + isolation_up.extend(up) + isolation_down.extend(down) + # Isolation commands are emitted after normal policy commands because all + # of them use iptables -I. Executing them last places isolation at the top + # of FORWARD, so a group/client ACCEPT rule cannot accidentally bypass it. + add_up.extend(isolation_up) + add_down.extend(isolation_down) + if add_up or add_down: + text = _edit_interface_hooks(text, [], [], add_up, add_down) + return text + + +def detach_managed_policy(text: str, tag: str) -> str: + if not tag: + return text + lines = [] + marker = f"--comment {tag}" + for raw in text.splitlines(): + if marker in raw: + raw = raw.replace(f" -m comment --comment {tag}", "") + lines.append(raw) + return "\n".join(lines).rstrip() + "\n" + + +def find_policy_meta_by_tag(tag: str) -> dict[str, Any] | None: + if not tag: + return None + for meta in iter_client_metas(): + if client_policy_tag(str(meta.get("public_key") or "")) == tag: + return meta + return None + + +def disable_policy_by_tag(tag: str) -> dict[str, Any] | None: + meta = find_policy_meta_by_tag(tag) + if not meta: + return None + old_meta = dict(meta) + meta["protect_local_networks"] = False + meta["updated_at"] = int(time.time()) + save_client_meta(meta) + return old_meta + + +def next_free_address(cfg: dict[str, Any]) -> str | None: + vpn_network = cfg.get("detected", {}).get("vpn_network") + if not vpn_network: + return None + try: + network = ipaddress.ip_network(vpn_network, strict=True) + except ValueError: + return None + if network.version != 4: + return None + used: set[ipaddress.IPv4Address] = set() + address = cfg.get("interface", {}).get("address") + if address: + for raw in str(address).split(","): + try: + used.add(ipaddress.ip_interface(raw.strip()).ip) + except ValueError: + pass + for peer in cfg.get("peers", []): + raw = peer.get("vpn_address") + if raw: + try: + used.add(ipaddress.ip_interface(raw).ip) + except ValueError: + pass + # Keep this bounded even if somebody configured a very large VPN network. + for idx, host in enumerate(network.hosts()): + if idx > 65535: + break + if host not in used: + return f"{host}/32" + return None + + +def normalize_name(value: Any) -> str: + name = str(value or "").strip() + if not name or len(name) > 64: + raise ValueError("Client name must be between 1 and 64 characters") + if any(ord(ch) < 32 for ch in name) or "\n" in name or "\r" in name: + raise ValueError("Client name contains unsupported control characters") + return name + + +def normalize_networks(value: Any, label: str, allow_empty: bool = True) -> list[str]: + if value is None: + items: list[Any] = [] + elif isinstance(value, str): + items = [x.strip() for x in re.split(r"[,\n]+", value) if x.strip()] + elif isinstance(value, list): + items = value + else: + raise ValueError(f"{label} must be a list of networks") + result: list[str] = [] + for raw in items: + try: + net = ipaddress.ip_network(str(raw).strip(), strict=False) + except ValueError as exc: + raise ValueError(f"Invalid network in {label}: {raw}") from exc + if net.version != 4: + raise ValueError(f"Only IPv4 networks are supported in {label}") + canonical = str(net) + if canonical not in result: + result.append(canonical) + if not allow_empty and not result: + raise ValueError(f"{label} cannot be empty") + return result + + +def normalize_dns(value: Any) -> list[str]: + if value is None: + return [] + if isinstance(value, str): + items = [x.strip() for x in value.split(",") if x.strip()] + elif isinstance(value, list): + items = [str(x).strip() for x in value if str(x).strip()] + else: + raise ValueError("DNS must be a comma-separated list of IP addresses") + result: list[str] = [] + for raw in items: + try: + ip = ipaddress.ip_address(raw) + except ValueError as exc: + raise ValueError(f"Invalid DNS address: {raw}") from exc + if ip.version != 4: + raise ValueError("Only IPv4 DNS addresses are supported in this version") + text = str(ip) + if text not in result: + result.append(text) + return result + + +def _normalize_schedule_time(value: Any, label: str) -> str: + text = str(value or "").strip() + if not re.fullmatch(r"(?:[01]\d|2[0-3]):[0-5]\d", text): + raise ValueError(f"{label} must use HH:MM in 24-hour format") + return text + + +def _normalize_schedule_days(value: Any) -> list[int]: + if value is None: + return [] + if not isinstance(value, list): + raise ValueError("Access schedule days must be a list") + result: list[int] = [] + for raw in value: + try: + day = int(raw) + except (TypeError, ValueError) as exc: + raise ValueError("Access schedule days must be integers from 0 to 6") from exc + if day < 0 or day > 6: + raise ValueError("Access schedule days must be integers from 0 to 6") + if day not in result: + result.append(day) + return sorted(result) + + +def _schedule_minutes(value: str) -> int: + hour, minute = value.split(":", 1) + return int(hour) * 60 + int(minute) + + +def client_schedule_allows(meta: dict[str, Any], now: int | None = None) -> bool: + if not bool(meta.get("access_schedule_enabled")): + return True + days = _normalize_schedule_days(meta.get("access_schedule_days") or []) + if not days: + return False + start = _normalize_schedule_time(meta.get("access_schedule_start") or "08:00", "Access schedule start") + end = _normalize_schedule_time(meta.get("access_schedule_end") or "19:00", "Access schedule end") + current = datetime.fromtimestamp(int(now if now is not None else time.time())).astimezone() + current_minute = current.hour * 60 + current.minute + start_minute = _schedule_minutes(start) + end_minute = _schedule_minutes(end) + weekday = current.weekday() + if start_minute == end_minute: + return weekday in days + if start_minute < end_minute: + return weekday in days and start_minute <= current_minute < end_minute + previous_weekday = (weekday - 1) % 7 + return (weekday in days and current_minute >= start_minute) or (previous_weekday in days and current_minute < end_minute) + + + +def schedule_settings_disabled(settings: dict[str, Any], now: int | None = None) -> bool: + if not bool(settings.get("access_schedule_enabled")): + return False + meta = { + "access_schedule_enabled": True, + "access_schedule_days": list(settings.get("access_schedule_days") or []), + "access_schedule_start": str(settings.get("access_schedule_start") or "08:00"), + "access_schedule_end": str(settings.get("access_schedule_end") or "19:00"), + } + return not client_schedule_allows(meta, now) + +def validate_client_payload(iface: str, payload: dict[str, Any], existing_public_key: str | None = None) -> dict[str, Any]: + require_valid_iface(iface) + config_path = WG_DIR / f"{iface}.conf" + if not config_path.exists(): + raise RuntimeError("WireGuard server is not configured") + cfg = parse_config(read_config_text(iface), iface) + vpn_raw = cfg.get("detected", {}).get("vpn_network") + if not vpn_raw: + raise RuntimeError("WGTools could not determine the VPN network from the server configuration") + vpn_network = ipaddress.ip_network(vpn_raw, strict=True) + + name = normalize_name(payload.get("name")) + client_type = str(payload.get("type", "client")).strip().lower() + if client_type not in {"client", "site_to_site"}: + raise ValueError("Client type must be client or site_to_site") + + group_id = str(payload.get("group_id") or "").strip() + group = load_group(group_id, iface) if group_id else None + if group_id and not group: + raise ValueError("Selected client group does not exist on this WireGuard interface") + if group_id and client_type != "client": + raise ValueError("Client groups are available only for normal clients, not Site-to-site peers") + + address_raw = str(payload.get("vpn_address", "")).strip() + if not address_raw: + address_raw = next_free_address(cfg) or "" + try: + addr_iface = ipaddress.ip_interface(address_raw) + except ValueError as exc: + raise ValueError("VPN address must be a valid IPv4 address such as 10.77.0.10/32") from exc + if addr_iface.version != 4 or addr_iface.ip not in vpn_network: + raise ValueError("VPN address must belong to the configured VPN network") + if addr_iface.ip in {vpn_network.network_address, vpn_network.broadcast_address}: + raise ValueError("VPN address cannot be the network or broadcast address") + vpn_address = f"{addr_iface.ip}/32" + + server_address = cfg.get("interface", {}).get("address") + if server_address: + try: + server_ip = ipaddress.ip_interface(str(server_address).split(",")[0].strip()).ip + if addr_iface.ip == server_ip: + raise ValueError("VPN address is already used by the WireGuard server") + except ValueError as exc: + if str(exc).startswith("VPN address"): + raise + + remote_networks = normalize_networks(payload.get("remote_networks", []), "Remote networks", allow_empty=True) + if client_type == "client" and remote_networks: + client_type = "site_to_site" + if client_type == "site_to_site" and not remote_networks: + raise ValueError("At least one remote network is required for a Site-to-site peer") + + try: + keepalive = int(payload.get("persistent_keepalive", 25)) + except (TypeError, ValueError) as exc: + raise ValueError("Persistent keepalive must be a number") from exc + if not 0 <= keepalive <= 65535: + raise ValueError("Persistent keepalive must be between 0 and 65535") + + connection_mode = str(payload.get("connection_mode") or "direct").strip().lower() + if connection_mode not in {"direct", "relay"}: + raise ValueError("Client connection mode must be direct or relay") + relay_vps_id = str(payload.get("relay_vps_id") or "").strip() + if connection_mode == "relay": + relay = installed_relay_for_interface(relay_vps_id, iface) + if not relay: + raise ValueError("Selected VPS Relay is not installed for this WireGuard interface") + endpoint = relay_client_endpoint(relay) + else: + relay_vps_id = "" + endpoint = str(payload.get("endpoint", "")).strip() + if endpoint and (len(endpoint) > 255 or any(ch.isspace() for ch in endpoint)): + raise ValueError("Endpoint must be a host or IP with optional port and no spaces") + if endpoint and ":" not in endpoint: + port = cfg.get("interface", {}).get("listen_port") or 51820 + endpoint = f"{endpoint}:{port}" + + client_allowed_ips = normalize_networks(payload.get("client_allowed_ips", []), "Client routes", allow_empty=existing_public_key is not None) + if client_allowed_ips and not endpoint: + raise ValueError("Server address/domain is required for a generated client configuration") + route_preset = str(payload.get("route_preset") or "").strip().lower() + if route_preset and route_preset not in {"full", "full_except_local", "vpn_lan", "vpn", "custom"}: + raise ValueError("Client route preset is invalid") + if not route_preset: + route_preset = _infer_route_preset(cfg, client_allowed_ips, bool(payload.get("protect_local_networks"))) + + protect_local_networks = bool(payload.get("protect_local_networks")) and client_type == "client" and not group_id + local_access_exceptions = normalize_networks(payload.get("local_access_exceptions", []), "Local access exceptions", allow_empty=True) + if protect_local_networks: + # The client remains a plain full tunnel. Local/Site-to-site blocking is + # a server-side WGTools policy and must not clutter AllowedIPs. + client_allowed_ips = ["0.0.0.0/0"] + protected_objs = [ipaddress.ip_network(raw, strict=False) for raw in protected_networks(cfg)] + validated_exceptions: list[str] = [] + for raw in local_access_exceptions: + exc = ipaddress.ip_network(raw, strict=False) + parents = [parent for parent in protected_objs if exc.subnet_of(parent)] + if not parents: + raise ValueError(f"Local access exception {exc} is outside the protected local/Site-to-site networks") + if any(exc == parent for parent in parents): + raise ValueError(f"Local access exception {exc} opens an entire protected network; remove that network restriction instead") + value = str(exc) + if value not in validated_exceptions: + validated_exceptions.append(value) + local_access_exceptions = validated_exceptions + else: + local_access_exceptions = [] + dns = normalize_dns(payload.get("dns", [])) + + config_mode = "" + if group_id: + config_mode = str(payload.get("config_mode") or "inherit").strip().lower() + if config_mode not in {"inherit", "custom"}: + raise ValueError("Group client configuration mode must be inherit or custom") + if config_mode == "inherit" and existing_public_key is None: + defaults = _group_defaults_for_config(group, cfg) + route_preset = defaults["route_preset"] + client_allowed_ips = list(defaults["client_allowed_ips"]) + dns = list(defaults["dns"]) + keepalive = int(defaults["persistent_keepalive"] or 0) + + use_preshared_key = bool(payload.get("use_preshared_key", True)) + peer_isolation = bool(payload.get("peer_isolation")) and client_type == "client" + try: + expires_at = int(payload.get("expires_at") or 0) + except (TypeError, ValueError) as exc: + raise ValueError("Expiration time must be a Unix timestamp") from exc + if expires_at < 0 or expires_at > 4102444800: + raise ValueError("Expiration time is outside the supported range") + if expires_at and expires_at <= int(time.time()): + raise ValueError("Expiration time must be in the future") + expiration_action = str(payload.get("expiration_action") or "delete").strip().lower() + if expiration_action not in {"delete", "disable"}: + raise ValueError("Expiration action must be delete or disable") + if not expires_at: + expiration_action = "delete" + if client_type == "site_to_site": + expiration_action = "delete" + + access_schedule_enabled = bool(payload.get("access_schedule_enabled")) and client_type != "site_to_site" + access_schedule_days = _normalize_schedule_days(payload.get("access_schedule_days") or []) if access_schedule_enabled else [] + access_schedule_start = _normalize_schedule_time(payload.get("access_schedule_start") or "08:00", "Access schedule start") + access_schedule_end = _normalize_schedule_time(payload.get("access_schedule_end") or "19:00", "Access schedule end") + if access_schedule_enabled and not access_schedule_days: + raise ValueError("Choose at least one day for the access schedule") + + policy_mode = "" + internet_access = "" + local_access = "" + policy_allow: list[str] = [] + policy_deny: list[str] = [] + if group_id: + policy_mode = str(payload.get("policy_mode") or "inherit").strip().lower() + if policy_mode not in {"inherit", "custom"}: + raise ValueError("Group policy mode must be inherit or custom") + internet_access = _validate_policy_access( + payload.get("internet_access", "inherit" if policy_mode == "inherit" else "allow"), + "Internet access", + allow_inherit=policy_mode == "inherit", + ) + local_access = _validate_policy_access( + payload.get("local_access", "inherit" if policy_mode == "inherit" else "allow"), + "Local network access", + allow_inherit=policy_mode == "inherit", + ) + policy_allow, policy_deny = _validate_policy_lists(payload.get("policy_allow", []), payload.get("policy_deny", [])) + + candidate_server_allowed = [vpn_address] + remote_networks + for peer in cfg.get("peers", []): + pub = peer.get("public_key") + if existing_public_key and pub == existing_public_key: + continue + peer_name = str(peer.get("name") or "").strip() + if peer_name and peer_name.casefold() == name.casefold(): + raise ValueError(f"A peer named {name!r} already exists") + for used_raw in peer.get("allowed_ips", []): + try: + used = ipaddress.ip_network(used_raw, strict=False) + except ValueError: + continue + for candidate_raw in candidate_server_allowed: + candidate = ipaddress.ip_network(candidate_raw, strict=False) + if candidate.overlaps(used): + raise ValueError(f"Address/network {candidate} overlaps with peer {peer.get('name') or pub}") + + return { + "name": name, + "type": client_type, + "vpn_address": vpn_address, + "remote_networks": remote_networks, + "persistent_keepalive": keepalive, + "endpoint": endpoint, + "client_allowed_ips": client_allowed_ips, + "client_route_preset": route_preset, + "protect_local_networks": protect_local_networks, + "local_access_exceptions": local_access_exceptions, + "dns": dns, + "group_id": group_id, + "policy_mode": policy_mode, + "internet_access": internet_access, + "local_access": local_access, + "policy_allow": policy_allow, + "policy_deny": policy_deny, + "config_mode": config_mode, + "use_preshared_key": use_preshared_key, + "peer_isolation": peer_isolation, + "expires_at": expires_at, + "expiration_action": expiration_action, + "access_schedule_enabled": access_schedule_enabled, + "access_schedule_days": access_schedule_days, + "access_schedule_start": access_schedule_start, + "access_schedule_end": access_schedule_end, + "connection_mode": connection_mode, + "relay_vps_id": relay_vps_id, + "cfg": cfg, + } + + +def peer_block(name: str, public_key: str, allowed_ips: list[str], keepalive: int, preshared_key: str = "") -> str: + lines = [ + f"# ---{name}---", + "", + "[Peer]", + f"PublicKey = {public_key}", + ] + if preshared_key: + lines.append(f"PresharedKey = {preshared_key}") + lines.append(f"AllowedIPs = {','.join(allowed_ips)}") + if keepalive: + lines.append(f"PersistentKeepalive = {keepalive}") + return "\n".join(lines) + + +def peer_block_spans(text: str) -> list[dict[str, Any]]: + lines = text.splitlines() + section_starts = [i for i, line in enumerate(lines) if line.strip().lower() == "[peer]"] + block_starts: list[int] = [] + for section_start in section_starts: + block_start = section_start + j = section_start - 1 + while j >= 0 and not lines[j].strip(): + j -= 1 + if j >= 0 and parse_comment_name(lines[j]) is not None: + block_start = j + block_starts.append(block_start) + + spans: list[dict[str, Any]] = [] + for pos, section_start in enumerate(section_starts): + block_start = block_starts[pos] + block_end = block_starts[pos + 1] if pos + 1 < len(block_starts) else len(lines) + public_key = None + for line in lines[section_start + 1:block_end]: + if "=" not in line: + continue + key, value = [x.strip() for x in line.split("=", 1)] + if key.lower() == "publickey": + public_key = value + break + spans.append({"start": block_start, "end": block_end, "section_start": section_start, "public_key": public_key}) + return spans + + +def find_peer_span(text: str, public_key: str) -> tuple[int, int] | None: + for span in peer_block_spans(text): + if span.get("public_key") == public_key: + return int(span["start"]), int(span["end"]) + return None + + +def peer_preshared_key(text: str, public_key: str) -> str: + span = find_peer_span(text, public_key) + if not span: + return "" + start, end = span + lines = text.splitlines() + for raw in lines[start:end]: + if "=" not in raw: + continue + key, value = [part.strip() for part in raw.split("=", 1)] + if key.lower() == "presharedkey": + return value + return "" + + +def replace_peer_block(text: str, public_key: str, replacement: str | None) -> str: + span = find_peer_span(text, public_key) + if span is None: + raise ValueError("Peer was not found in the server configuration") + lines = text.splitlines() + start, end = span + new_lines = lines[:start] + if replacement: + if new_lines and new_lines[-1].strip(): + new_lines.append("") + new_lines.extend(replacement.splitlines()) + new_lines.append("") + new_lines.extend(lines[end:]) + result = "\n".join(new_lines).strip() + "\n" + result = re.sub(r"\n{3,}", "\n\n", result) + return result + + +def append_peer_block(text: str, block: str) -> str: + return text.rstrip() + "\n\n" + block.strip() + "\n" + + +def update_route_hooks(text: str, iface: str, remove_networks: list[str], add_networks: list[str], policy_table: str | int | None) -> str: + remove = set(remove_networks) + lines = text.splitlines() + spans = peer_block_spans(text) + first_peer = int(spans[0]["start"]) if spans else len(lines) + interface_lines = lines[:first_peer] + peer_lines = lines[first_peer:] + + def route_network_from_hook(line: str) -> str | None: + if "=" not in line: + return None + key, cmd = [x.strip() for x in line.split("=", 1)] + if key.lower() not in {"postup", "postdown"}: + return None + m = re.search(r"\bip\s+route\s+(?:add|replace|del)\s+(\S+)\s+dev\s+" + re.escape(iface) + r"(?:\s+table\s+\d+)?\b", cmd) + return m.group(1) if m else None + + cleaned: list[str] = [] + for line in interface_lines: + net = route_network_from_hook(line) + if net and net in remove: + continue + cleaned.append(line) + + existing = set() + for line in cleaned: + net = route_network_from_hook(line) + if net: + existing.add((line.split("=", 1)[0].strip().lower(), net, "table" in line)) + + additions: list[str] = [] + for net in add_networks: + if policy_table: + if ("postup", net, True) not in existing: + additions.append(f"PostUp = ip route add {net} dev {iface} table {policy_table}") + if ("postdown", net, True) not in existing: + additions.append(f"PostDown = ip route del {net} dev {iface} table {policy_table} 2>/dev/null || true") + if ("postup", net, False) not in existing: + additions.append(f"PostUp = ip route replace {net} dev {iface}") + if ("postdown", net, False) not in existing: + additions.append(f"PostDown = ip route del {net} dev {iface} 2>/dev/null || true") + + while cleaned and not cleaned[-1].strip(): + cleaned.pop() + if additions: + cleaned.append("") + cleaned.extend(additions) + if peer_lines: + cleaned.append("") + cleaned.extend(peer_lines) + return re.sub(r"\n{3,}", "\n\n", "\n".join(cleaned).strip() + "\n") + + +def make_backup(iface: str, config_path: Path) -> Path: + BACKUP_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(BACKUP_DIR, 0o700) + stamp = time.strftime("%Y%m%d-%H%M%S") + path = BACKUP_DIR / f"{iface}-{stamp}-{time.time_ns() % 1000000:06d}.conf" + shutil.copy2(config_path, path) + os.chmod(path, 0o600) + files = sorted(BACKUP_DIR.glob(f"{iface}-*.conf"), key=lambda x: x.stat().st_mtime, reverse=True) + for stale in files[backup_retention():]: + try: + stale.unlink() + except OSError: + pass + return path + + +def validate_config_file(path: Path) -> str: + wg_quick = shutil.which("wg-quick") + if not wg_quick: + raise RuntimeError("wg-quick is not installed") + rc, out, err = run([wg_quick, "strip", str(path)], timeout=12) + if rc != 0 or not out.strip(): + raise RuntimeError(f"WireGuard configuration validation failed: {err or out}") + return out + "\n" + + +def sync_runtime(iface: str, config_path: Path) -> None: + dump = wg_dump(iface) + if not dump.get("running"): + return + stripped = validate_config_file(config_path) + sync_path = Path(f"/run/wgtools-{iface}.sync.conf") + sync_path.write_text(stripped, encoding="utf-8") + os.chmod(sync_path, 0o600) + wg = shutil.which("wg") + if not wg: + raise RuntimeError("wg is not installed") + rc, out, err = run([wg, "syncconf", iface, str(sync_path)], timeout=12) + try: + sync_path.unlink() + except FileNotFoundError: + pass + if rc != 0: + raise RuntimeError(f"wg syncconf failed: {err or out}") + + +def apply_remote_routes(iface: str, remove_networks: list[str], add_networks: list[str], policy_table: str | int | None) -> None: + if not wg_dump(iface).get("running"): + return + ip = shutil.which("ip") or "/usr/sbin/ip" + for net in remove_networks: + run([ip, "route", "del", net, "dev", iface], timeout=5) + if policy_table: + run([ip, "route", "del", net, "dev", iface, "table", str(policy_table)], timeout=5) + for net in add_networks: + rc, out, err = run([ip, "route", "replace", net, "dev", iface], timeout=5) + if rc != 0: + raise RuntimeError(f"Failed to install route {net}: {err or out}") + if policy_table: + rc, out, err = run([ip, "route", "replace", net, "dev", iface, "table", str(policy_table)], timeout=5) + if rc != 0: + raise RuntimeError(f"Failed to install route {net} in table {policy_table}: {err or out}") + + +def _managed_runtime_rule(command: str) -> tuple[str, str, str, str] | None: + compact = " ".join(str(command).split()) + match = re.fullmatch( + r"iptables -I FORWARD -s ([^\s]+) -d ([^\s]+) -m comment --comment (wgtools-protect-[A-Za-z0-9_-]+) -j (REJECT|DROP|ACCEPT)", + compact, + ) + if not match: + return None + return match.group(1), match.group(2), match.group(3), match.group(4) + + +def _parse_live_managed_policy_rule(raw: str) -> tuple[tuple[str, str, str, str], list[str]]: + """Parse one ``iptables -S FORWARD`` rule owned by WGTools. + + iptables normalises rules when printing them. In particular, an explicit + ``-d 0.0.0.0/0`` is omitted and ``-j REJECT`` is printed with its default + ``--reject-with icmp-port-unreachable`` option. Treat those canonical + forms as equivalent to the commands stored in wg0.conf, while still + rejecting any unexpected WGTools-tagged rule shape. + """ + tokens = shlex.split(raw) + if len(tokens) < 4 or tokens[0:2] != ["-A", "FORWARD"]: + raise ValueError("not a FORWARD rule") + + source = "" + destination = "0.0.0.0/0" + tag = "" + action = "" + reject_with = "" + seen_comment_match = False + i = 2 + while i < len(tokens): + token = tokens[i] + if token == "-s" and i + 1 < len(tokens): + source = tokens[i + 1] + i += 2 + elif token == "-d" and i + 1 < len(tokens): + destination = tokens[i + 1] + i += 2 + elif token == "-m" and i + 1 < len(tokens) and tokens[i + 1] == "comment": + seen_comment_match = True + i += 2 + elif token == "--comment" and i + 1 < len(tokens): + tag = tokens[i + 1] + i += 2 + elif token == "-j" and i + 1 < len(tokens): + action = tokens[i + 1] + i += 2 + elif token == "--reject-with" and i + 1 < len(tokens): + reject_with = tokens[i + 1] + i += 2 + else: + raise ValueError(f"unexpected token {token}") + + if not source or not seen_comment_match or not tag.startswith("wgtools-protect-"): + raise ValueError("unexpected WGTools rule shape") + if action not in {"REJECT", "DROP", "ACCEPT"}: + raise ValueError("unexpected WGTools rule action") + if reject_with and action != "REJECT": + raise ValueError("reject option on a non-REJECT rule") + + return (source, destination, tag, action), tokens + + +def _apply_managed_policy_runtime_diff(old_text: str, new_text: str) -> None: + # Rebuild every WGTools-tagged rule in a deterministic order. This heals + # stale/duplicate rules left by older releases and, importantly, preserves + # the precedence of client overrides over group rules and broad defaults. + new_up, _ = _managed_policy_hook_commands(new_text) + desired_specs: list[tuple[str, str, str, str]] = [] + for command in new_up: + parsed = _managed_runtime_rule(command) + if not parsed: + raise RuntimeError(f"Unsupported WGTools-managed firewall rule: {command}") + desired_specs.append(parsed) + + iptables = shutil.which("iptables") or "/usr/sbin/iptables" + + def args_for_spec(spec: tuple[str, str, str, str], operation: str) -> list[str]: + source, destination, tag, action = spec + return [iptables, operation, "FORWARD", "-s", source, "-d", destination, "-m", "comment", "--comment", tag, "-j", action] + + rc, out, err = run([iptables, "-S", "FORWARD"], timeout=8) + if rc != 0: + raise RuntimeError(f"Failed to inspect live firewall rules: {err or out}") + + current_rules: list[tuple[tuple[str, str, str, str], list[str], str]] = [] + for raw in out.splitlines(): + if "wgtools-protect-" not in raw: + continue + try: + spec, tokens = _parse_live_managed_policy_rule(raw) + current_rules.append((spec, tokens, raw)) + except (ValueError, IndexError) as exc: + raise RuntimeError(f"Unsupported live WGTools firewall rule: {' '.join(raw.split())}") from exc + + # Only reconcile tags that belong to the interface/configuration being + # changed. WGTools can manage multiple WireGuard interfaces at once; + # removing every wgtools-protect-* rule globally would otherwise erase + # policy rules belonging to the other interfaces. + managed_tags = {spec[2] for spec in desired_specs} + for command in [*_managed_policy_hook_commands(old_text)[0], *_managed_policy_hook_commands(new_text)[0]]: + parsed = _managed_runtime_rule(command) + if parsed: + managed_tags.add(parsed[2]) + + # Delete the exact canonical rules returned by ``iptables -S``. Using the + # printed token shape is important for REJECT rules because iptables adds + # ``--reject-with`` automatically and may omit ``-d 0.0.0.0/0``. + for spec, tokens, raw in current_rules: + if spec[2] not in managed_tags: + continue + delete_args = [iptables, "-D", "FORWARD", *tokens[2:]] + rc, out, err = run(delete_args, timeout=8) + if rc != 0: + raise RuntimeError(f"Failed to remove stale WGTools client firewall policy: {err or out or raw}") + + added: list[tuple[str, str, str, str]] = [] + try: + # new_up is deliberately stored in reverse logical priority because + # wg-quick executes PostUp commands with iptables -I. Replaying in that + # same order yields the exact same final chain as a clean boot. + for spec in desired_specs: + rc, out, err = run(args_for_spec(spec, "-I"), timeout=8) + if rc != 0: + raise RuntimeError(f"Failed to apply WGTools client firewall policy: {err or out}") + added.append(spec) + except Exception: + for spec in reversed(added): + run(args_for_spec(spec, "-D"), timeout=8) + raise + + +def write_config_transaction(iface: str, new_text: str, remove_routes: list[str], add_routes: list[str], policy_table: str | int | None) -> Path: + # syncconf may remove/recreate peers. Snapshot the runtime counters first + # so no accumulated traffic disappears during a managed configuration edit. + capture_wireguard_traffic(iface) + config_path = WG_DIR / f"{iface}.conf" + old_text = config_path.read_text(encoding="utf-8", errors="strict") + backup = make_backup(iface, config_path) + validate_dir = Path("/run/wgtools-validate") + validate_dir.mkdir(parents=True, exist_ok=True) + validate_path = validate_dir / f"{iface}.conf" + validate_path.write_text(new_text, encoding="utf-8") + os.chmod(validate_path, 0o600) + try: + validate_config_file(validate_path) + tmp = WG_DIR / f".{iface}.conf.wgtools.tmp" + tmp.write_text(new_text, encoding="utf-8") + os.chmod(tmp, 0o600) + os.replace(tmp, config_path) + os.chmod(config_path, 0o600) + try: + sync_runtime(iface, config_path) + apply_remote_routes(iface, remove_routes, add_routes, policy_table) + _apply_managed_policy_runtime_diff(old_text, new_text) + except Exception: + shutil.copy2(backup, config_path) + os.chmod(config_path, 0o600) + try: + sync_runtime(iface, config_path) + apply_remote_routes(iface, add_routes, remove_routes, policy_table) + _apply_managed_policy_runtime_diff(new_text, old_text) + except Exception: + pass + raise + finally: + try: + validate_path.unlink() + except FileNotFoundError: + pass + return backup + + +def server_public_key_from_config(iface: str) -> str: + text = read_config_text(iface) + current = None + private = None + for raw in text.splitlines(): + line = raw.strip() + if line.startswith("[") and line.endswith("]"): + current = line[1:-1].strip().lower() + continue + if current == "interface" and "=" in line: + key, value = [x.strip() for x in line.split("=", 1)] + if key.lower() == "privatekey": + private = value + break + if not private: + raise RuntimeError("Server private key is missing from the WireGuard configuration") + public = private_to_public(private) + if not public: + raise RuntimeError("Failed to derive the server public key") + return public + + +def create_client(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + if not wg_installed(): + raise RuntimeError("WireGuard is not installed") + settings = validate_client_payload(iface, payload) + new_ip = str(ipaddress.ip_interface(settings["vpn_address"]).ip) + if any(row["target_ip"] == new_ip for row in _extended_forwards(iface)): + raise ValueError("Adres klienta jest używany przez istniejące przekierowanie") + cfg = settings.pop("cfg") + private_key = generate_private_key() + public_key = private_to_public(private_key) + if not public_key: + raise RuntimeError("Failed to generate the client public key") + preshared_key = generate_preshared_key() if settings["use_preshared_key"] else "" + schedule_disabled = schedule_settings_disabled(settings) + server_preshared_key = generate_preshared_key() if schedule_disabled else preshared_key + allowed = [settings["vpn_address"]] + settings["remote_networks"] + block = peer_block(settings["name"], public_key, allowed, settings["persistent_keepalive"], server_preshared_key) + text = read_config_text(iface) + new_text = append_peer_block(text, block) + policy_table = cfg.get("detected", {}).get("policy_table") + new_text = update_route_hooks(new_text, iface, [], settings["remote_networks"], policy_table) + meta = { + "public_key": public_key, + "interface": iface, + "private_key": private_key, + "name": settings["name"], + "vpn_address": settings["vpn_address"], + "endpoint": settings["endpoint"], + "client_allowed_ips": settings["client_allowed_ips"], + "client_route_preset": settings["client_route_preset"], + "protect_local_networks": settings["protect_local_networks"], + "protect_local_exclusions": [], + "local_access_exceptions": settings["local_access_exceptions"], + "dns": settings["dns"], + "persistent_keepalive": settings["persistent_keepalive"], + "group_id": settings["group_id"], + "policy_mode": settings["policy_mode"], + "internet_access": settings["internet_access"], + "local_access": settings["local_access"], + "policy_allow": settings["policy_allow"], + "policy_deny": settings["policy_deny"], + "config_mode": settings["config_mode"], + "preshared_key": preshared_key, + "peer_isolation": settings["peer_isolation"], + "expires_at": settings["expires_at"], + "expiration_action": settings["expiration_action"], + "expired_disabled": False, + "expired_at": 0, + "access_schedule_enabled": settings["access_schedule_enabled"], + "access_schedule_days": settings["access_schedule_days"], + "access_schedule_start": settings["access_schedule_start"], + "access_schedule_end": settings["access_schedule_end"], + "schedule_disabled": schedule_disabled, + "schedule_changed_at": int(time.time()) if schedule_disabled else 0, + "connection_mode": settings["connection_mode"], + "relay_vps_id": settings["relay_vps_id"], + "created_at": int(time.time()), + } + save_client_meta(meta) + try: + new_text = sync_managed_client_policies(new_text, iface) + backup = write_config_transaction(iface, new_text, [], settings["remote_networks"], policy_table) + except Exception: + delete_client_meta(public_key) + raise + return { + "ok": True, + "message": "Client created and applied without restarting WireGuard", + "public_key": public_key, + "vpn_address": settings["vpn_address"], + "backup": str(backup), + "managed": True, + } + + +def update_client(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + public_key = str(payload.get("public_key", "")).strip() + if not public_key: + raise ValueError("Public key is required") + settings = validate_client_payload(iface, payload, existing_public_key=public_key) + cfg = settings.pop("cfg") + peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) + if not peer: + raise ValueError("Peer was not found") + old_ip = str(ipaddress.ip_interface(peer["vpn_address"]).ip) if peer.get("vpn_address") else "" + new_ip = str(ipaddress.ip_interface(settings["vpn_address"]).ip) + if old_ip != new_ip and any(row["target_ip"] in {old_ip, new_ip} for row in _extended_forwards(iface)): + raise ValueError("Najpierw usuń przekierowania powiązane z adresem klienta") + old_remote = list(peer.get("remote_networks", [])) + meta = load_client_meta(public_key) + old_meta = dict(meta) if meta else None + text = read_config_text(iface) + if meta: + preshared_key = str(meta.get("preshared_key") or "").strip() if settings["use_preshared_key"] else "" + if settings["use_preshared_key"] and not preshared_key: + preshared_key = generate_preshared_key() + else: + # Existing/unmanaged peers may already use a PSK. The visual editor + # cannot regenerate their client configuration, so preserve that secret + # instead of silently removing it when other peer fields are edited. + preshared_key = peer_preshared_key(text, public_key) + schedule_disabled = schedule_settings_disabled(settings) if meta else False + server_preshared_key = generate_preshared_key() if schedule_disabled else preshared_key + allowed = [settings["vpn_address"]] + settings["remote_networks"] + block = peer_block(settings["name"], public_key, allowed, settings["persistent_keepalive"], server_preshared_key) + new_text = replace_peer_block(text, public_key, block) + policy_table = cfg.get("detected", {}).get("policy_table") + new_text = update_route_hooks(new_text, iface, old_remote, settings["remote_networks"], policy_table) + if meta: + old_protect_local = bool(meta.get("protect_local_networks")) + if not settings["protect_local_networks"] or not old_protect_local: + meta["protect_local_exclusions"] = [] + else: + meta["protect_local_exclusions"] = sorted(_policy_exclusions(meta)) + if not settings["protect_local_networks"]: + meta["local_access_exceptions"] = [] + meta.update({ + "interface": iface, + "name": settings["name"], + "vpn_address": settings["vpn_address"], + "endpoint": settings["endpoint"], + "client_allowed_ips": settings["client_allowed_ips"], + "client_route_preset": settings["client_route_preset"], + "protect_local_networks": settings["protect_local_networks"], + "local_access_exceptions": settings["local_access_exceptions"], + "dns": settings["dns"], + "persistent_keepalive": settings["persistent_keepalive"], + "group_id": settings["group_id"], + "policy_mode": settings["policy_mode"], + "internet_access": settings["internet_access"], + "local_access": settings["local_access"], + "policy_allow": settings["policy_allow"], + "policy_deny": settings["policy_deny"], + "config_mode": settings["config_mode"], + "preshared_key": preshared_key, + "peer_isolation": settings["peer_isolation"], + "expires_at": settings["expires_at"], + "expiration_action": settings["expiration_action"], + "expired_disabled": False, + "expired_at": 0, + "access_schedule_enabled": settings["access_schedule_enabled"], + "access_schedule_days": settings["access_schedule_days"], + "access_schedule_start": settings["access_schedule_start"], + "access_schedule_end": settings["access_schedule_end"], + "schedule_disabled": schedule_disabled, + "schedule_changed_at": int(time.time()) if bool(old_meta and old_meta.get("schedule_disabled")) != schedule_disabled else int((old_meta or {}).get("schedule_changed_at") or 0), + "connection_mode": settings["connection_mode"], + "relay_vps_id": settings["relay_vps_id"], + "updated_at": int(time.time()), + }) + save_client_meta(meta) + try: + new_text = sync_managed_client_policies(new_text, iface) + backup = write_config_transaction(iface, new_text, old_remote, settings["remote_networks"], policy_table) + except Exception: + if old_meta: + save_client_meta(old_meta) + raise + return {"ok": True, "message": "Client updated", "backup": str(backup), "managed": bool(meta)} + + +def delete_client(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + public_key = str(payload.get("public_key", "")).strip() + if not public_key: + raise ValueError("Public key is required") + cfg = parse_config(read_config_text(iface), iface) + peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) + if not peer: + raise ValueError("Peer was not found") + peer_ip = str(ipaddress.ip_interface(peer["vpn_address"]).ip) if peer.get("vpn_address") else "" + forwards = _extended_forwards(iface) + remaining_forwards = [row for row in forwards if row["target_ip"] != peer_ip] + if len(remaining_forwards) != len(forwards): + _extended_write_forwards(iface, remaining_forwards) + old_remote = list(peer.get("remote_networks", [])) + text = read_config_text(iface) + new_text = replace_peer_block(text, public_key, None) + policy_table = cfg.get("detected", {}).get("policy_table") + new_text = update_route_hooks(new_text, iface, old_remote, [], policy_table) + old_meta = load_client_meta(public_key) + delete_client_meta(public_key) + try: + new_text = sync_managed_client_policies(new_text, iface) + backup = write_config_transaction(iface, new_text, old_remote, [], policy_table) + except Exception: + if old_meta: + save_client_meta(old_meta) + raise + return {"ok": True, "message": f"Client {peer.get('name') or public_key} deleted", "name": str(peer.get("name") or public_key[:16]), "backup": str(backup)} + + +def _migrate_client_public_key_state(iface: str, old_public_key: str, new_public_key: str) -> None: + """Move durable traffic/last-seen state to a rotated client public key.""" + try: + conn = _traffic_connect() + try: + with conn: + # A freshly generated key cannot normally collide, but keep the + # operation deterministic if stale state somehow exists. + conn.execute( + "DELETE FROM wg_traffic_counters WHERE interface=? AND public_key=?", + (iface, new_public_key), + ) + conn.execute( + "UPDATE wg_traffic_counters SET public_key=? WHERE interface=? AND public_key=?", + (new_public_key, iface, old_public_key), + ) + state_table = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='audit_wg_connection_state'" + ).fetchone() + if state_table: + conn.execute( + "DELETE FROM audit_wg_connection_state WHERE interface=? AND public_key=?", + (iface, new_public_key), + ) + conn.execute( + "UPDATE audit_wg_connection_state SET public_key=? WHERE interface=? AND public_key=?", + (new_public_key, iface, old_public_key), + ) + finally: + conn.close() + except Exception: + # The key rotation itself must not be made unsafe by auxiliary history + # migration. The interface lifetime total still retains old-key bytes. + pass + + +def rotate_client_credentials(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + old_public_key = str(payload.get("public_key", "")).strip() + if not old_public_key: + raise ValueError("Public key is required") + meta = load_client_meta(old_public_key) + if not meta or str(meta.get("interface") or "") != iface or not meta.get("private_key"): + raise ValueError("Key rotation is available only for WGTools-managed clients") + if bool(meta.get("expired_disabled")): + raise ValueError("Restore this client's access before rotating its keys") + + cfg = parse_config(read_config_text(iface), iface) + peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == old_public_key), None) + if not peer: + raise ValueError("Peer was not found") + + # Capture resettable counters while the old public key still exists. + capture_wireguard_traffic(iface) + new_private_key = generate_private_key() + new_public_key = private_to_public(new_private_key) + if not new_public_key: + raise RuntimeError("Failed to derive the new client public key") + + old_meta = dict(meta) + new_meta = dict(meta) + new_meta["public_key"] = new_public_key + new_meta["private_key"] = new_private_key + + # One user action rotates every active client secret. Respect the PSK + # checkbox: an enabled PSK is regenerated, while a deliberately disabled + # PSK stays disabled. + psk_enabled = bool(str(meta.get("preshared_key") or "").strip()) + new_client_psk = generate_preshared_key() if psk_enabled else "" + new_meta["preshared_key"] = new_client_psk + new_meta["credentials_rotated_at"] = int(time.time()) + new_meta["updated_at"] = int(time.time()) + + schedule_disabled = bool(meta.get("access_schedule_enabled")) and not client_schedule_allows(meta) + server_psk = generate_preshared_key() if schedule_disabled else new_client_psk + block = peer_block( + str(peer.get("name") or meta.get("name") or "Client"), + new_public_key, + list(peer.get("allowed_ips") or []), + int(peer.get("persistent_keepalive") or meta.get("persistent_keepalive") or 0), + server_psk, + ) + old_text = read_config_text(iface) + new_text = replace_peer_block(old_text, old_public_key, block) + new_meta["schedule_disabled"] = schedule_disabled + new_meta["schedule_changed_at"] = int(time.time()) if bool(old_meta.get("schedule_disabled")) != schedule_disabled else int(old_meta.get("schedule_changed_at") or 0) + + save_client_meta(new_meta) + delete_client_meta(old_public_key) + try: + new_text = sync_managed_client_policies(new_text, iface) + backup = write_config_transaction(iface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) + except Exception: + delete_client_meta(new_public_key) + save_client_meta(old_meta) + raise + + _migrate_client_public_key_state(iface, old_public_key, new_public_key) + return { + "ok": True, + "message": "Client keys rotated. Issue a new client config or QR before reconnecting.", + "name": str(peer.get("name") or meta.get("name") or "Client"), + "public_key": new_public_key, + "psk_enabled": psk_enabled, + "psk_rotated": psk_enabled, + "backup": str(backup), + "requires_client_config_update": True, + } + +def _apply_schedule_state(meta: dict[str, Any], *, disable: bool, now: int) -> dict[str, Any] | None: + public_key = str(meta.get("public_key") or "").strip() + interface = str(meta.get("interface") or "").strip() + name = str(meta.get("name") or public_key) + if not public_key or not ALLOWED_IFACE_RE.fullmatch(interface): + raise ValueError("Invalid client metadata for access schedule") + if bool(meta.get("expired_disabled")): + return None + currently_disabled = bool(meta.get("schedule_disabled")) + if currently_disabled == disable: + return None + cfg = parse_config(read_config_text(interface), interface) + peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) + if not peer: + raise ValueError("Peer was not found while applying access schedule") + old_meta = dict(meta) + old_text = read_config_text(interface) + target_psk = generate_preshared_key() if disable else str(meta.get("preshared_key") or "").strip() + block = peer_block( + str(peer.get("name") or name), + public_key, + list(peer.get("allowed_ips") or []), + int(peer.get("persistent_keepalive") or meta.get("persistent_keepalive") or 0), + target_psk, + ) + new_text = replace_peer_block(old_text, public_key, block) + meta["schedule_disabled"] = disable + meta["schedule_changed_at"] = now + meta["updated_at"] = now + save_client_meta(meta) + try: + new_text = sync_managed_client_policies(new_text, interface) + backup = write_config_transaction(interface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) + except Exception: + save_client_meta(old_meta) + raise + return { + "name": name, + "interface": interface, + "disabled": disable, + "backup": str(backup), + } + + +def enforce_client_schedule(public_key: str, now: int | None = None) -> dict[str, Any] | None: + meta = load_client_meta(public_key) + if not meta: + return None + current = int(now if now is not None else time.time()) + if bool(meta.get("expired_disabled")): + return None + try: + expires_at = int(meta.get("expires_at") or 0) + except (TypeError, ValueError): + expires_at = 0 + if expires_at and expires_at <= current: + return None + enabled = bool(meta.get("access_schedule_enabled")) + if not enabled: + if bool(meta.get("schedule_disabled")): + return _apply_schedule_state(meta, disable=False, now=current) + return None + allowed = client_schedule_allows(meta, current) + return _apply_schedule_state(meta, disable=not allowed, now=current) + + +def expire_clients() -> dict[str, Any]: + now = int(time.time()) + due = [] + for meta in iter_client_metas(): + try: + expires_at = int(meta.get("expires_at") or 0) + except (TypeError, ValueError): + expires_at = 0 + if expires_at and expires_at <= now and not bool(meta.get("expired_disabled")): + due.append(meta) + due.sort(key=lambda item: (int(item.get("expires_at") or 0), str(item.get("interface") or ""), str(item.get("name") or ""))) + deleted: list[dict[str, Any]] = [] + disabled: list[dict[str, Any]] = [] + errors: list[dict[str, str]] = [] + for meta in due: + public_key = str(meta.get("public_key") or "").strip() + interface = str(meta.get("interface") or "").strip() + name = str(meta.get("name") or public_key) + if not public_key or not ALLOWED_IFACE_RE.fullmatch(interface): + errors.append({"name": name, "error": "invalid client metadata"}) + continue + config_path = WG_DIR / f"{interface}.conf" + if not config_path.exists(): + errors.append({"name": name, "error": f"WireGuard interface config {interface}.conf is missing"}) + continue + try: + cfg = parse_config(read_config_text(interface), interface) + peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) + if not peer: + if str(meta.get("expiration_action") or "delete").lower() == "disable": + errors.append({"name": name, "interface": interface, "error": "peer is already absent; cannot preserve it as disabled"}) + else: + delete_client_meta(public_key) + deleted.append({"name": name, "interface": interface, "already_absent": True}) + continue + action = str(meta.get("expiration_action") or "delete").strip().lower() + if action == "disable": + old_meta = dict(meta) + old_text = read_config_text(interface) + disabled_psk = generate_preshared_key() + block = peer_block( + str(peer.get("name") or name), + public_key, + list(peer.get("allowed_ips") or []), + int(peer.get("persistent_keepalive") or 0), + disabled_psk, + ) + new_text = replace_peer_block(old_text, public_key, block) + meta["expired_disabled"] = True + meta["expired_at"] = now + meta["schedule_disabled"] = False + meta["updated_at"] = now + save_client_meta(meta) + try: + new_text = sync_managed_client_policies(new_text, interface) + backup = write_config_transaction(interface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) + except Exception: + save_client_meta(old_meta) + raise + disabled.append({"name": name, "interface": interface, "backup": str(backup)}) + else: + result = delete_client(interface, {"public_key": public_key}) + deleted.append({"name": name, "interface": interface, "backup": str(result.get("backup") or "")}) + except Exception as exc: + errors.append({"name": name, "interface": interface, "error": str(exc)}) + + schedule_disabled: list[dict[str, Any]] = [] + schedule_restored: list[dict[str, Any]] = [] + for meta in list(iter_client_metas()): + public_key = str(meta.get("public_key") or "").strip() + if not public_key: + continue + try: + change = enforce_client_schedule(public_key, now) + if not change: + continue + if change.get("disabled"): + schedule_disabled.append(change) + else: + schedule_restored.append(change) + except Exception as exc: + errors.append({ + "name": str(meta.get("name") or public_key), + "interface": str(meta.get("interface") or ""), + "error": f"schedule: {exc}", + }) + return { + "ok": True, + "checked_at": now, + "expired": len(due), + "deleted": deleted, + "disabled": disabled, + "schedule_disabled": schedule_disabled, + "schedule_restored": schedule_restored, + "errors": errors, + } + + +CYRILLIC_FILENAME_TRANSLIT = str.maketrans({ + "А": "A", "Б": "B", "В": "V", "Г": "G", "Д": "D", "Е": "E", "Ё": "Yo", + "Ж": "Zh", "З": "Z", "И": "I", "Й": "Y", "К": "K", "Л": "L", "М": "M", + "Н": "N", "О": "O", "П": "P", "Р": "R", "С": "S", "Т": "T", "У": "U", + "Ф": "F", "Х": "Kh", "Ц": "Ts", "Ч": "Ch", "Ш": "Sh", "Щ": "Sch", "Ъ": "", + "Ы": "Y", "Ь": "", "Э": "E", "Ю": "Yu", "Я": "Ya", + "а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "yo", + "ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m", + "н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u", + "ф": "f", "х": "kh", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "sch", "ъ": "", + "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya", +}) + + +def safe_client_filename_stem(value: Any) -> str: + """Return a portable ASCII filename stem while keeping Cyrillic client names recognizable.""" + raw = str(value or "").strip() + if not raw: + return "wireguard-client" + transliterated = raw.translate(CYRILLIC_FILENAME_TRANSLIT) + ascii_text = unicodedata.normalize("NFKD", transliterated).encode("ascii", "ignore").decode("ascii") + stem = re.sub(r"[^A-Za-z0-9._-]+", "_", ascii_text).strip("._-") + return stem[:96] or "wireguard-client" + + +def build_client_config(iface: str, public_key: str) -> dict[str, Any]: + meta = load_client_meta(public_key) + if meta and meta.get("interface") and meta.get("interface") != iface: + meta = None + if not meta or not meta.get("private_key"): + raise RuntimeError("Client configuration is unavailable for this existing peer because WGTools does not have its private key") + cfg = parse_config(read_config_text(iface), iface) + peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) + if not peer: + raise RuntimeError("Peer no longer exists in the WireGuard configuration") + connection_mode = str(meta.get("connection_mode") or "direct") + if connection_mode == "relay": + relay = installed_relay_for_interface(str(meta.get("relay_vps_id") or ""), iface) + if not relay: + raise RuntimeError("The VPS Relay selected for this client is no longer available") + endpoint = relay_client_endpoint(relay) + else: + endpoint = str(meta.get("endpoint") or "").strip() + if not endpoint: + raise RuntimeError("Client endpoint is not configured. Edit the client and set the server IP/domain used by this client") + server_public = server_public_key_from_config(iface) + lines = [ + "[Interface]", + f"PrivateKey = {meta['private_key']}", + f"Address = {peer.get('vpn_address') or meta.get('vpn_address')}", + ] + dns = meta.get("dns") or [] + if dns: + lines.append(f"DNS = {', '.join(dns)}") + lines.extend([ + "", + "[Peer]", + f"PublicKey = {server_public}", + ]) + preshared_key = str(meta.get("preshared_key") or "").strip() + if preshared_key: + lines.append(f"PresharedKey = {preshared_key}") + lines.extend([ + f"Endpoint = {endpoint}", + f"AllowedIPs = {', '.join(meta.get('client_allowed_ips') or [])}", + ]) + keepalive = peer.get("persistent_keepalive") or meta.get("persistent_keepalive") or 0 + if keepalive: + lines.append(f"PersistentKeepalive = {keepalive}") + config = "\n".join(lines) + "\n" + filename = safe_client_filename_stem(peer.get("name")) + return {"ok": True, "config": config, "filename": f"{filename}.conf", "name": peer.get("name")} + + + +def _interface_section_parts(text: str) -> tuple[list[str], list[str], list[str]]: + lines = text.replace("\r\n", "\n").replace("\r", "\n").splitlines() + start = None + end = len(lines) + for idx, line in enumerate(lines): + if re.fullmatch(r"\s*\[Interface\]\s*", line, flags=re.IGNORECASE): + start = idx + break + if start is None: + raise ValueError("WireGuard configuration does not contain an [Interface] section") + for idx in range(start + 1, len(lines)): + if re.fullmatch(r"\s*\[[^\]]+\]\s*", lines[idx]): + end = idx + break + # Peer labels are commonly written as comments immediately before [Peer]. + # Keep those comments with the peer section instead of absorbing them into [Interface]. + suffix_start = end + if end < len(lines): + while suffix_start > start + 1: + prev = lines[suffix_start - 1].strip() + if not prev or prev.startswith("#") or prev.startswith(";"): + suffix_start -= 1 + continue + break + return lines[:start], lines[start:suffix_start], lines[suffix_start:] + + +def _extract_interface_values(section: list[str]) -> tuple[str, str, list[str], list[str], list[str]]: + private_key = "" + save_config = "false" + preserved: list[str] = [] + post_up: list[str] = [] + post_down: list[str] = [] + for idx, raw in enumerate(section): + if idx == 0: + continue + stripped = raw.strip() + if not stripped or stripped.startswith("#") or stripped.startswith(";"): + preserved.append(raw) + continue + if "=" not in raw: + preserved.append(raw) + continue + key, value = [x.strip() for x in raw.split("=", 1)] + lk = key.lower() + if lk == "privatekey": + private_key = value + elif lk == "saveconfig": + save_config = value or "false" + elif lk == "postup": + post_up.append(value) + elif lk == "postdown": + post_down.append(value) + elif lk in {"address", "listenport", "mtu"}: + continue + else: + preserved.append(raw) + if not private_key: + raise ValueError("The existing [Interface] section does not contain PrivateKey") + return private_key, save_config, preserved, post_up, post_down + + +def _managed_hook_kind(cmd: str, iface: str, old_cfg: dict[str, Any], remote_networks: set[str]) -> str | None: + # Extended rules own their entire compound hook and must not be rewritten + # by the original server-settings classifier. + if f"--comment wgext-forward-{iface}-" in cmd or f"--comment wgext-listen-{iface}-" in cmd or f"--comment wgext-snat-{iface}" in cmd: + return None + old = old_cfg.get("detected", {}) + old_network = str(old.get("vpn_network") or "") + old_table = str(old.get("policy_table") or "") + old_uplink = str(old.get("uplink_interface") or "") + old_gateway = str(old.get("gateway") or "") + old_local = str(old.get("local_network") or "") + compact = " ".join(cmd.split()) + + if re.search(r"\bsysctl\s+-w\s+net\.ipv4\.ip_forward=1\b", compact): + return "forwarding" + if re.search(rf"\biptables\b.*\bFORWARD\b.*\s-i\s+{re.escape(iface)}(?:\s|$)", compact) and "-j ACCEPT" in compact: + return "forward_from" + if re.search(rf"\biptables\b.*\bFORWARD\b.*\s-o\s+{re.escape(iface)}(?:\s|$)", compact) and "-j ACCEPT" in compact: + return "forward_to" + if "iptables" in compact and "POSTROUTING" in compact and "MASQUERADE" in compact: + if (not old_network or old_network in compact) and (not old_uplink or old_uplink in compact): + return "nat" + if old_table and re.search(r"\bip\s+rule\s+(?:add|del)\b", compact) and f"table {old_table}" in compact: + if not old_network or old_network in compact: + return "policy_rule" + if old_table and re.search(r"\bip\s+route\s+(?:add|replace|del)\b", compact) and f"table {old_table}" in compact: + m = re.search(r"\broute\s+(?:add|replace|del)\s+([^\s]+)", compact) + target = m.group(1) if m else "" + if target in {"default", old_network, old_local}: + return "policy_base_route" + if target in remote_networks and re.search(rf"\bdev\s+{re.escape(iface)}\b", compact): + return "policy_remote_route" + if target == "default" and old_gateway and old_gateway in compact: + return "policy_base_route" + return None + + +def _canonical_hook_lines(iface: str, settings: dict[str, Any], remote_networks: list[str]) -> tuple[list[str], list[str]]: + network = settings["network"] + uplink = settings["uplink_interface"] + table = settings["policy_table"] + gateway = settings["gateway"] + local_network = settings["local_network"] + up: list[str] = [] + down: list[str] = [] + + if settings["ip_forwarding"]: + up.append("sysctl -w net.ipv4.ip_forward=1") + + if table is not None: + up.append(f"ip rule add from {network} table {table}") + down.append(f"ip rule del from {network} table {table} 2>/dev/null || true") + up.append(f"ip route add default via {gateway} dev {uplink} table {table}") + down.append(f"ip route del default via {gateway} dev {uplink} table {table} 2>/dev/null || true") + if local_network: + up.append(f"ip route add {local_network} dev {uplink} table {table}") + down.append(f"ip route del {local_network} dev {uplink} table {table} 2>/dev/null || true") + up.append(f"ip route replace {network} dev {iface} table {table}") + down.append(f"ip route del {network} dev {iface} table {table} 2>/dev/null || true") + for remote in remote_networks: + up.append(f"ip route add {remote} dev {iface} table {table}") + down.append(f"ip route del {remote} dev {iface} table {table} 2>/dev/null || true") + + if settings.get("forward_from_vpn", True): + up.append(f"iptables -A FORWARD -i {iface} -j ACCEPT") + down.append(f"iptables -D FORWARD -i {iface} -j ACCEPT 2>/dev/null || true") + if settings.get("forward_to_vpn", True): + up.append(f"iptables -A FORWARD -o {iface} -j ACCEPT") + down.append(f"iptables -D FORWARD -o {iface} -j ACCEPT 2>/dev/null || true") + if settings["nat_enabled"]: + up.append(f"iptables -t nat -A POSTROUTING -s {network} -o {uplink} -j MASQUERADE") + down.append(f"iptables -t nat -D POSTROUTING -s {network} -o {uplink} -j MASQUERADE 2>/dev/null || true") + return up, down + + +def _extended_groups() -> dict[str, dict[str, Any]]: + if not EXT_IP_GROUPS_PATH.exists(): + return {} + data = json.loads(EXT_IP_GROUPS_PATH.read_text(encoding="utf-8")) + if not isinstance(data, dict): + raise ValueError("Nieprawidłowa konfiguracja grup adresów") + return data + + +def _extended_configured() -> set[str]: + return {iface for iface in _configured_interface_names() if (WG_DIR / f"{iface}.conf").is_file()} + + +def _extended_allowed(groups: dict[str, Any], iface: str) -> set[str]: + return {addr for group in groups.values() if iface in group.get("interfaces", []) for addr in group.get("addresses", [])} + + +def _extended_host_ips() -> dict[str, str]: + rc, out, err = run(["ip", "-j", "-4", "addr", "show"]) + if rc: + raise ValueError(f"Nie można odczytać adresów serwera: {err}") + result: dict[str, str] = {} + for dev in json.loads(out): + name = str(dev.get("ifname") or "") + if not ALLOWED_IFACE_RE.fullmatch(name) or name.startswith('-'): + continue + for item in dev.get("addr_info", []): + if item.get("family") == "inet" and item.get("local"): + result[str(item["local"])] = name + return result + + +def _extended_listener_conflict(public_ip: str, port: int, protocols: set[str]) -> bool: + rc, out, err = run(["ss", "-H", "-lntu"]) + if rc: + raise ValueError(f"Nie można sprawdzić zajętych portów: {err}") + for line in out.splitlines(): + parts = line.split() + if len(parts) < 5 or parts[0].lower() not in protocols: + continue + local = parts[4] + host, separator, raw_port = local.rpartition(':') + if separator and raw_port.isdigit() and int(raw_port) == port: + host = host.strip('[]') + if host in {'*', '0.0.0.0', '::', public_ip}: + return True + return False + + +def _extended_forwards(iface: str) -> list[dict[str, Any]]: + _, section, _ = _interface_section_parts(read_config_text(iface)) + result = [] + for line in section: + if line.strip().startswith("# WGEXT-FORWARD "): + try: + row = json.loads(line.strip()[len("# WGEXT-FORWARD "):]) + if not re.fullmatch(r"[0-9a-f]{16}", str(row["id"])): + raise ValueError() + row["public_ip"] = str(ipaddress.IPv4Address(row["public_ip"])) + row["target_ip"] = str(ipaddress.IPv4Address(row["target_ip"])) + row["public_port"] = int(row["public_port"]) + row["target_port"] = int(row["target_port"]) + if not (1 <= row["public_port"] <= 65535 and 1 <= row["target_port"] <= 65535): + raise ValueError() + if row["protocol"] not in {"tcp", "udp", "both"} or not ALLOWED_IFACE_RE.fullmatch(row["device"]) or row["device"].startswith('-'): + raise ValueError() + except (KeyError, ValueError, TypeError) as exc: + raise ValueError(f"Nieprawidłowy wpis przekierowania w {iface}") from exc + result.append(row) + return result + + +def extended_ip_groups_get() -> dict[str, Any]: + return {"ok": True, "groups": _extended_groups(), "forwards": [{**row, "interface": iface} for iface in sorted(_extended_configured()) for row in _extended_forwards(iface)]} + + +def extended_ip_groups_set(payload: dict[str, Any]) -> dict[str, Any]: + name = str(payload.get("name") or "").strip() + if not re.fullmatch(r"[A-Za-z0-9_. -]{1,64}", name): + raise ValueError("Nieprawidłowa nazwa grupy") + groups = _extended_groups() + if payload.get("delete"): + if name not in groups: + raise ValueError("Nie znaleziono grupy") + del groups[name] + else: + addresses = payload.get("addresses") or [] + interfaces = payload.get("interfaces") or [] + if not isinstance(addresses, list) or not isinstance(interfaces, list) or len(addresses) > 256 or len(interfaces) > 100: + raise ValueError("Nieprawidłowa lista adresów lub sieci") + try: + addresses = sorted({str(ipaddress.IPv4Address(addr)) for addr in addresses}) + except (ValueError, TypeError) as exc: + raise ValueError("Nieprawidłowy adres IPv4") from exc + configured = _extended_configured() + if any(not isinstance(item, str) or item not in configured for item in interfaces): + raise ValueError("Grupa zawiera nieistniejącą sieć WireGuard") + host_ips = _extended_host_ips() + if any(addr not in host_ips for addr in addresses): + raise ValueError("Adres grupy nie jest przypisany do serwera") + groups[name] = {"addresses": addresses, "interfaces": sorted(set(interfaces))} + for iface in _extended_configured(): + for row in _extended_forwards(iface): + if row["public_ip"] not in _extended_allowed(groups, iface): + raise ValueError(f"Zmiana odebrałaby adres używany przez przekierowanie w {iface}; usuń najpierw przekierowanie") + EXT_IP_GROUPS_PATH.parent.mkdir(parents=True, exist_ok=True) + temp = EXT_IP_GROUPS_PATH.with_name(f".{EXT_IP_GROUPS_PATH.name}.{os.getpid()}.tmp") + try: + temp.write_text(json.dumps(groups, ensure_ascii=False), encoding="utf-8") + os.chmod(temp, 0o600) + os.replace(temp, EXT_IP_GROUPS_PATH) + finally: + temp.unlink(missing_ok=True) + return {"ok": True, "groups": groups} + + +def extended_forward_get(iface: str) -> dict[str, Any]: + require_valid_iface(iface) + return {"ok": True, "addresses": sorted(_extended_allowed(_extended_groups(), iface)), "forwards": _extended_forwards(iface)} + + +def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str, Any]: + prefix, section, suffix = _interface_section_parts(read_config_text(iface)) + marker = f"wgext-forward-{iface}" + section = [line for line in section if not (line.strip().startswith("# WGEXT-FORWARD ") or (re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I) and f"--comment {marker}-" in line))] + up: list[str] = [] + down: list[str] = [] + for row in rows: + section.append('# WGEXT-FORWARD ' + json.dumps(row, separators=(',', ':'), sort_keys=True)) + for proto in (["tcp", "udp"] if row["protocol"] == "both" else [row["protocol"]]): + tag = f"{marker}-{row['id']}-{proto}" + nat = f"-i {row['device']} -d {row['public_ip']} -p {proto} --dport {row['public_port']} -m comment --comment {tag}-nat -j DNAT --to-destination {row['target_ip']}:{row['target_port']}" + forward = f"-i {row['device']} -o {iface} -d {row['target_ip']} -p {proto} --dport {row['target_port']} -m comment --comment {tag}-in -j ACCEPT" + reply = f"-i {iface} -o {row['device']} -s {row['target_ip']} -p {proto} --sport {row['target_port']} -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment {tag}-out -j ACCEPT" + for table, chain, rule in [(' -t nat', 'PREROUTING', nat), ('', 'FORWARD', forward), ('', 'FORWARD', reply)]: + up.append(f"iptables -w{table} -I {chain} 1 {rule}") + down.append(f"iptables -w{table} -D {chain} {rule} 2>/dev/null || true") + if up: + cleanup = '; '.join(down) + section.extend([f"PostUp = {' && '.join(up)} || {{ {cleanup}; false; }}", f"PostDown = {cleanup}"]) + return raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"}) + + +def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + require_valid_iface(iface) + try: + public_ip = str(ipaddress.IPv4Address(payload.get("public_ip"))) + target_ip = str(ipaddress.IPv4Address(payload.get("target_ip"))) + public_port, target_port = int(payload.get("public_port")), int(payload.get("target_port")) + except (ValueError, TypeError) as exc: + raise ValueError("Nieprawidłowy adres lub port") from exc + protocol = str(payload.get("protocol") or "") + if protocol not in {"tcp", "udp", "both"} or not (1 <= public_port <= 65535 and 1 <= target_port <= 65535): + raise ValueError("Nieprawidłowy protokół lub port") + if public_ip not in _extended_allowed(_extended_groups(), iface): + raise ValueError("Ten publiczny adres IPv4 nie jest przypisany do tej sieci") + device = _extended_host_ips().get(public_ip) + if not device: + raise ValueError("Adres IPv4 nie jest obecnie przypisany do serwera") + cfg = parse_config(read_config_text(iface), iface) + peers = {str(ipaddress.ip_interface(p['vpn_address']).ip) for p in cfg.get('peers', []) if p.get('vpn_address')} + if target_ip not in peers: + raise ValueError("Adres docelowy nie należy do klienta tej sieci") + protocols = {"tcp", "udp"} if protocol == "both" else {protocol} + if _extended_listener_conflict(public_ip, public_port, protocols): + raise ValueError("Ten port jest już używany przez usługę na serwerze") + for other in _extended_configured(): + other_cfg = parse_config(read_config_text(other), other) + if "udp" in protocols and (other_cfg.get("interface") or {}).get("listen_port") == public_port: + raise ValueError("Ten port UDP jest używany przez WireGuard") + for row in _extended_forwards(other): + existing = {"tcp", "udp"} if row["protocol"] == "both" else {row["protocol"]} + if row["public_ip"] == public_ip and row["public_port"] == public_port and protocols & existing: + raise ValueError("Ten adres, port i protokół są już używane przez inne przekierowanie") + rows = _extended_forwards(iface) + if len(rows) >= 20: + raise ValueError("Osiągnięto limit przekierowań w tej sieci") + row = {"id": secrets.token_hex(8), "public_ip": public_ip, "public_port": public_port, "target_ip": target_ip, "target_port": target_port, "protocol": protocol, "device": device} + result = _extended_write_forwards(iface, [*rows, row]) + return {**result, "forward": row} + + +def extended_forward_delete(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + require_valid_iface(iface) + identifier = str(payload.get("id") or "") + rows = _extended_forwards(iface) + remaining = [row for row in rows if row['id'] != identifier] + if len(remaining) == len(rows): + raise ValueError("Nie znaleziono przekierowania") + return _extended_write_forwards(iface, remaining) + + +def extended_snat_get(iface: str) -> dict[str, Any]: + require_valid_iface(iface) + text = read_config_text(iface) + marker = f"wgext-snat-{iface}" + prefix, section, suffix = _interface_section_parts(text) + found = [line for line in section if marker in line and re.match(r"\s*PostUp\s*=", line, re.I)] + if len(found) > 1: + raise ValueError("Wykryto więcej niż jedną regułę SNAT; sprawdź konfigurację") + if not found: + return {"ok": True, "address": "", "uplink": ""} + match = re.search(r"\s-o\s+([A-Za-z0-9_.-]{1,15})\s+.*?--to-source\s+(\d+\.\d+\.\d+\.\d+)", found[0]) + if not match: + raise ValueError("Nie można odczytać zapisanej reguły SNAT") + return {"ok": True, "address": match.group(2), "uplink": match.group(1)} + + +def extended_listen_get(iface: str) -> dict[str, Any]: + require_valid_iface(iface) + _, section, _ = _interface_section_parts(read_config_text(iface)) + marker = f"# WGEXT-LISTEN-{iface} " + entries = [line.strip()[len(marker):] for line in section if line.strip().startswith(marker)] + if not entries: + return {"ok": True, "address": "", "interface": ""} + if len(entries) != 1: + raise ValueError("Nieprawidłowa konfiguracja ograniczenia nasłuchiwania") + match = re.fullmatch(r"address=([0-9.]*) interface=([A-Za-z0-9_.-]*)", entries[0]) + if not match: + raise ValueError("Nieprawidłowa konfiguracja ograniczenia nasłuchiwania") + return {"ok": True, "address": match.group(1), "interface": match.group(2)} + + +def extended_listen_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + require_valid_iface(iface) + text = read_config_text(iface) + cfg = parse_config(text, iface) + address = str(payload.get("address") or "").strip() + device = str(payload.get("interface") or "").strip() + marker = f"wgext-listen-{iface}" + metadata = f"# WGEXT-LISTEN-{iface} " + prefix, section, suffix = _interface_section_parts(text) + section = [line for line in section if not (line.strip().startswith(metadata) or (re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I) and f"--comment {marker}-" in line))] + if address or device: + port = (cfg.get("interface") or {}).get("listen_port") + if not isinstance(port, int) or not 1 <= port <= 65535: + raise ValueError("Nie można ustalić portu WireGuard") + if device: + if not ALLOWED_IFACE_RE.fullmatch(device) or device.startswith('-'): + raise ValueError("Nieprawidłowy interfejs") + rc, _, _ = run(["ip", "link", "show", "dev", device]) + if rc: + raise ValueError("Interfejs nie istnieje") + if address: + try: + address = str(ipaddress.IPv4Address(address)) + except ValueError as exc: + raise ValueError("Podaj poprawny adres IPv4") from exc + cmd = ["ip", "-j", "-4", "addr", "show"] + (["dev", device] if device else []) + rc, out, _ = run(cmd) + try: + assigned = {item.get("local") for dev in json.loads(out) for item in dev.get("addr_info", []) if item.get("family") == "inet"} if not rc else set() + except (ValueError, TypeError) as exc: + raise ValueError("Nie można odczytać adresów interfejsu") from exc + if address not in assigned: + raise ValueError("Adres IPv4 nie jest przypisany do wskazanego interfejsu") + common = f"-p udp --dport {port}" + selected = (f" -i {device}" if device else "") + (f" -d {address}" if address else "") + drop4 = f"{common} -m comment --comment {marker}-drop -j DROP" + allow4 = f"{common}{selected} -m comment --comment {marker}-allow -j ACCEPT" + drop6 = f"{common} -m comment --comment {marker}-v6 -j DROP" + cleanup = f"iptables -w -D INPUT {allow4} 2>/dev/null || true; iptables -w -D INPUT {drop4} 2>/dev/null || true; ip6tables -w -D INPUT {drop6} 2>/dev/null || true" + section.extend([metadata + f"address={address} interface={device}", + f"PostUp = iptables -w -I INPUT 1 {drop4} && ip6tables -w -I INPUT 1 {drop6} && iptables -w -I INPUT 1 {allow4} || {{ {cleanup}; false; }}", + f"PostDown = {cleanup}"]) + result = raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"}) + result.update({"address": address, "interface": device}) + return result + + +def extended_snat_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + require_valid_iface(iface) + text = read_config_text(iface) + cfg = parse_config(text, iface) + address = str(payload.get("address") or "").strip() + uplink = str(payload.get("uplink") or "").strip() + marker = f"wgext-snat-{iface}" + prefix, section, suffix = _interface_section_parts(text) + section = [line for line in section if not (marker in line and re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I))] + if address: + try: + address = str(ipaddress.IPv4Address(address)) + except ValueError as exc: + raise ValueError("Podaj poprawny adres IPv4") from exc + if not ALLOWED_IFACE_RE.fullmatch(uplink) or uplink.startswith('-'): + raise ValueError("Nieprawidłowy interfejs wyjściowy") + rc, out, err = run(["ip", "-j", "-4", "addr", "show", "dev", uplink]) + if rc: + raise ValueError(f"Nie można odczytać adresów interfejsu {uplink}: {err}") + try: + assigned = {item.get("local") for dev in json.loads(out) for item in dev.get("addr_info", []) if item.get("family") == "inet"} + except (ValueError, TypeError) as exc: + raise ValueError("Nie można odczytać adresów interfejsu") from exc + if address not in assigned: + raise ValueError("Adres IPv4 nie jest przypisany do wskazanego interfejsu") + detected = cfg.get("detected") or {} + try: + network = str(ipaddress.IPv4Network(str(detected.get("vpn_network") or ""), strict=False)) + except ValueError as exc: + raise ValueError("Nie można ustalić sieci IPv4 WireGuard") from exc + if detected.get("uplink_interface") and uplink != str(detected["uplink_interface"]): + raise ValueError("Interfejs wyjściowy musi odpowiadać ustawieniom sieci") + rule = f"-s {network} -o {uplink} -m comment --comment {marker} -j SNAT --to-source {address}" + section.extend([f"PostUp = iptables -t nat -I POSTROUTING 1 {rule}", f"PostDown = iptables -t nat -D POSTROUTING {rule}"]) + new_text = "\n".join([*prefix, *section, *suffix]).rstrip() + "\n" + result = raw_config_apply(iface, {"content": new_text}) + result.update({"address": address, "uplink": uplink if address else ""}) + return result + + +def server_settings_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + require_valid_iface(iface) + if not wg_installed(): + raise RuntimeError("WireGuard is not installed") + config_path = WG_DIR / f"{iface}.conf" + if not config_path.exists(): + raise RuntimeError(f"{config_path} does not exist") + + old_text = read_config_text(iface) + old_cfg = parse_config(old_text, iface) + normalized = dict(payload) + normalized["forward_from_vpn"] = bool(payload.get("forward_from_vpn", True)) + normalized["forward_to_vpn"] = bool(payload.get("forward_to_vpn", True)) + settings = validate_server_payload(iface, normalized) + listen = extended_listen_get(iface) + if (listen["address"] or listen["interface"]) and settings["listen_port"] != (old_cfg.get("interface") or {}).get("listen_port"): + raise ValueError("Przed zmianą portu wyłącz ograniczenie nasłuchiwania i ustaw je ponownie") + snat = extended_snat_get(iface) + if snat["address"] and (settings["network"] != str((old_cfg.get("detected") or {}).get("vpn_network") or "") or settings["uplink_interface"] != snat["uplink"]): + raise ValueError("Przed zmianą sieci VPN lub interfejsu wyjściowego usuń podstawowy adres SNAT i ustaw go ponownie po zapisaniu zmian") + settings["forward_from_vpn"] = normalized["forward_from_vpn"] + settings["forward_to_vpn"] = normalized["forward_to_vpn"] + + network = ipaddress.ip_network(settings["network"], strict=True) + for peer in old_cfg.get("peers", []): + vpn_address = peer.get("vpn_address") + if not vpn_address: + continue + try: + peer_ip = ipaddress.ip_interface(vpn_address).ip + except ValueError: + continue + if peer_ip not in network: + raise ValueError( + f"VPN pool {network} does not contain existing peer {peer.get('name') or 'Unnamed peer'} ({vpn_address}). " + "Move or remove that peer before changing the VPN pool." + ) + + remote_networks = sorted({ + str(net) + for peer in old_cfg.get("peers", []) + for net in (peer.get("remote_networks") or []) + if str(net).strip() + }) + remote_set = set(remote_networks) + + prefix, section, suffix = _interface_section_parts(old_text) + private_key, save_config, preserved_lines, old_up, old_down = _extract_interface_values(section) + extra_up = [cmd for cmd in old_up if _managed_hook_kind(cmd, iface, old_cfg, remote_set) is None] + extra_down = [cmd for cmd in old_down if _managed_hook_kind(cmd, iface, old_cfg, remote_set) is None] + managed_up, managed_down = _canonical_hook_lines(iface, settings, remote_networks) + + # Preserve unknown interface directives and comments, but normalize the common WGTools-managed fields. + new_section = [ + "[Interface]", + f"Address = {settings['server_address']}", + f"ListenPort = {settings['listen_port']}", + ] + if settings.get("mtu"): + new_section.append(f"MTU = {settings['mtu']}") + new_section.extend([ + f"PrivateKey = {private_key}", + f"SaveConfig = {save_config}", + ]) + nonempty_preserved = [line for line in preserved_lines if line.strip()] + if nonempty_preserved: + new_section.append("") + new_section.extend(nonempty_preserved) + if managed_up or extra_up: + new_section.append("") + new_section.extend(f"PostUp = {cmd}" for cmd in [*managed_up, *extra_up]) + if managed_down or extra_down: + new_section.append("") + new_section.extend(f"PostDown = {cmd}" for cmd in [*managed_down, *extra_down]) + new_section.append("") + + new_lines = [*prefix, *new_section, *suffix] + new_text = "\n".join(new_lines).rstrip() + "\n" + new_text = sync_managed_client_policies(new_text, iface) + result = raw_config_apply(iface, {"content": new_text}) + + sysctl_file = Path("/etc/sysctl.d/99-wgtools-wireguard.conf") + sysctl_value = "1" if settings["ip_forwarding"] else "0" + sysctl_file.write_text(f"net.ipv4.ip_forward={sysctl_value}\n", encoding="utf-8") + os.chmod(sysctl_file, 0o644) + sysctl = shutil.which("sysctl") or "/usr/sbin/sysctl" + rc, out, err = run([sysctl, "-w", f"net.ipv4.ip_forward={sysctl_value}"]) + if rc != 0: + result["warning"] = f"Configuration was applied, but sysctl could not set net.ipv4.ip_forward={sysctl_value}: {err or out}" + + result["server"] = settings + result["message"] = "Server settings saved and applied" + return result + + + +def _normalize_route_target(value: Any) -> str: + text = str(value or "").strip() + if text.lower() == "default": + return "default" + try: + return str(ipaddress.ip_network(text, strict=False)) + except ValueError as exc: + raise ValueError("Route network must be a valid IPv4 network or 'default'") from exc + + +def _normalize_ipv4(value: Any, label: str, allow_empty: bool = True) -> str: + text = str(value or "").strip() + if not text and allow_empty: + return "" + try: + return str(ipaddress.ip_address(text)) + except ValueError as exc: + raise ValueError(f"{label} must be a valid IP address") from exc + + +def _normalize_route_table(value: Any) -> str: + text = str(value or "").strip().lower() + if not text or text == "main": + return "main" + if not text.isdigit() or not (1 <= int(text) <= 4294967295): + raise ValueError("Routing table must be 'main' or a positive numeric table ID") + return str(int(text)) + + +def _build_route_commands(payload: dict[str, Any]) -> tuple[str, str, dict[str, str]]: + network = _normalize_route_target(payload.get("network")) + gateway = _normalize_ipv4(payload.get("gateway"), "Gateway") + device = str(payload.get("device") or "").strip() + if device and not ALLOWED_IFACE_RE.fullmatch(device): + raise ValueError("Invalid route interface name") + if not gateway and not device: + raise ValueError("Specify at least a gateway or an interface for the route") + table = _normalize_route_table(payload.get("table")) + + parts = ["ip", "route", "add", network] + if gateway: + parts += ["via", gateway] + if device: + parts += ["dev", device] + if table != "main": + parts += ["table", table] + up = " ".join(parts) + + down_parts = ["ip", "route", "del", network] + if gateway: + down_parts += ["via", gateway] + if device: + down_parts += ["dev", device] + if table != "main": + down_parts += ["table", table] + down = " ".join(down_parts) + " 2>/dev/null || true" + return up, down, {"network": network, "gateway": gateway, "device": device, "table": table} + + +def _normalize_rule_endpoint(value: Any, label: str) -> tuple[str, str]: + text = str(value or "").strip() + if not text or text.lower() in {"any", "all", "*"}: + return "", "any" + if "-" in text: + left, right = [x.strip() for x in text.split("-", 1)] + try: + a = ipaddress.ip_address(left) + b = ipaddress.ip_address(right) + except ValueError as exc: + raise ValueError(f"{label} range must contain valid IP addresses") from exc + if a.version != 4 or b.version != 4 or int(a) > int(b): + raise ValueError(f"{label} range is invalid") + return f"{a}-{b}", "range" + try: + if "/" in text: + return str(ipaddress.ip_network(text, strict=False)), "cidr" + return str(ipaddress.ip_address(text)), "ip" + except ValueError as exc: + raise ValueError(f"{label} must be an IP, CIDR, IP range, or empty") from exc + + +def _normalize_port(value: Any) -> str: + text = str(value or "").strip() + if not text: + return "" + if ":" in text: + a, b = text.split(":", 1) + if not a.isdigit() or not b.isdigit() or not (1 <= int(a) <= int(b) <= 65535): + raise ValueError("Destination port range must be in the form 1000:2000") + return f"{int(a)}:{int(b)}" + if not text.isdigit() or not (1 <= int(text) <= 65535): + raise ValueError("Destination port must be between 1 and 65535") + return str(int(text)) + + +def _normalize_rule_destinations(value: Any) -> list[tuple[str, str]]: + text = str(value or "").strip() + if not text or text.lower() in {"any", "all", "*"}: + return [("", "any")] + raw_items = [x.strip() for x in re.split(r"[,\n]+", text) if x.strip()] + if not raw_items: + return [("", "any")] + if len(raw_items) > 32: + raise ValueError("Destination may contain at most 32 IPs/networks") + result: list[tuple[str, str]] = [] + seen: set[str] = set() + for raw in raw_items: + endpoint = _normalize_rule_endpoint(raw, "Destination") + if endpoint[0] not in seen: + seen.add(endpoint[0]) + result.append(endpoint) + return result + + +def _build_access_rule_commands(payload: dict[str, Any]) -> tuple[list[str], list[str], dict[str, str]]: + source, source_kind = _normalize_rule_endpoint(payload.get("source"), "Source") + destinations = _normalize_rule_destinations(payload.get("destination")) + action = str(payload.get("action") or "REJECT").strip().upper() + if action not in {"ACCEPT", "REJECT", "DROP"}: + raise ValueError("Action must be ACCEPT, REJECT or DROP") + protocol = str(payload.get("protocol") or "any").strip().lower() + if protocol not in {"any", "tcp", "udp"}: + raise ValueError("Protocol must be any, tcp or udp") + dport = _normalize_port(payload.get("destination_port")) + if dport and protocol == "any": + raise ValueError("Select TCP or UDP when a destination port is specified") + + ups: list[str] = [] + downs: list[str] = [] + for destination, destination_kind in destinations: + tokens = ["iptables", "-I", "FORWARD"] + if source_kind == "range" or destination_kind == "range": + tokens += ["-m", "iprange"] + if source: + if source_kind == "range": + tokens += ["--src-range", source] + else: + tokens += ["-s", source] + if destination: + if destination_kind == "range": + tokens += ["--dst-range", destination] + else: + tokens += ["-d", destination] + if protocol != "any": + tokens += ["-p", protocol] + if dport: + tokens += ["--dport", dport] + tokens += ["-j", action] + up = " ".join(tokens) + ups.append(up) + downs.append(up.replace("iptables -I FORWARD", "iptables -D FORWARD", 1) + " 2>/dev/null || true") + + return ups, downs, { + "source": source, + "destination": ", ".join(destination for destination, _ in destinations if destination), + "action": action, + "protocol": protocol, + "destination_port": dport, + } + + +def _edit_interface_hooks(text: str, remove_up: list[str], remove_down: list[str], add_up: list[str], add_down: list[str]) -> str: + lines = text.splitlines() + start = None + end = len(lines) + for i, raw in enumerate(lines): + stripped = raw.strip().lower() + if stripped == "[interface]": + start = i + continue + if start is not None and i > start and stripped.startswith("[") and stripped.endswith("]"): + end = i + break + if start is None: + raise ValueError("[Interface] section was not found") + + # Keep comments/blank lines immediately preceding the first peer together + # with that peer. Otherwise adding a route/firewall hook can separate a + # human-readable peer label from its [Peer] section. + suffix_start = end + if end < len(lines): + while suffix_start > start + 1: + prev = lines[suffix_start - 1].strip() + if not prev or prev.startswith("#") or prev.startswith(";"): + suffix_start -= 1 + continue + break + end = suffix_start + + def hook_compare(value: str) -> str: + compact = " ".join(value.split()) + compact = re.sub(r"\s+2>/dev/null\s+\|\|\s+true$", "", compact) + return compact + + remove_up_set = {hook_compare(x) for x in remove_up if x} + remove_down_set = {hook_compare(x) for x in remove_down if x} + new_section: list[str] = [] + for raw in lines[start:end]: + stripped = raw.strip() + if "=" in raw: + key, value = [x.strip() for x in raw.split("=", 1)] + compact = hook_compare(value) + if key.lower() == "postup" and compact in remove_up_set: + continue + if key.lower() == "postdown" and compact in remove_down_set: + continue + new_section.append(raw) + + while len(new_section) > 1 and not new_section[-1].strip(): + new_section.pop() + if add_up or add_down: + new_section.append("") + new_section.extend(f"PostUp = {cmd}" for cmd in add_up) + new_section.extend(f"PostDown = {cmd}" for cmd in add_down) + new_section.append("") + return "\n".join([*lines[:start], *new_section, *lines[end:]]).rstrip() + "\n" + + +def _find_route_item(cfg: dict[str, Any], iface: str, command: str) -> dict[str, Any]: + for item in describe_server_items(cfg, iface)[0]: + if " ".join(str(item.get("command") or "").split()) == " ".join(command.split()): + if not item.get("editable"): + raise ValueError("This route is managed automatically by WGTools and cannot be edited here") + return item + raise ValueError("The route no longer exists in the selected WireGuard configuration; refresh the page and try again") + + +def _find_access_item(cfg: dict[str, Any], iface: str, command: str) -> dict[str, Any]: + for item in describe_server_items(cfg, iface)[1]: + if " ".join(str(item.get("command") or "").split()) == " ".join(command.split()): + if not item.get("editable") or item.get("category") != "access": + raise ValueError("This firewall rule is not supported by the simple editor; use the raw configuration editor") + return item + raise ValueError("The firewall rule no longer exists in the selected WireGuard configuration; refresh the page and try again") + + +def _expected_route_down(command: str) -> str: + compact = " ".join(command.split()) + return re.sub(r"\bip\s+route\s+(?:add|replace)\b", "ip route del", compact, count=1) + " 2>/dev/null || true" + + +def _expected_access_down(command: str) -> str: + compact = " ".join(command.split()) + compact = re.sub(r"\biptables\s+(?:-I|-A)\s+FORWARD\b", "iptables -D FORWARD", compact, count=1) + return compact + " 2>/dev/null || true" + + +def route_create(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + old_text = read_config_text(iface) + cfg = parse_config(old_text, iface) + up, down, values = _build_route_commands(payload) + if any(" ".join(str(r.get("command") or "").split()) == up for r in cfg.get("routes", [])): + raise ValueError("An identical route already exists") + new_text = _edit_interface_hooks(old_text, [], [], [up], [down]) + result = raw_config_apply(iface, {"content": new_text}) + result.update({"route": values, "message": "Route added and applied"}) + return result + + +def route_update(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + old_command = " ".join(str(payload.get("original_command") or "").split()) + if not old_command: + raise ValueError("original_command is required") + old_text = read_config_text(iface) + cfg = parse_config(old_text, iface) + _find_route_item(cfg, iface, old_command) + up, down, values = _build_route_commands(payload) + old_down = _expected_route_down(old_command) + new_text = _edit_interface_hooks(old_text, [old_command], [old_down], [up], [down]) + result = raw_config_apply(iface, {"content": new_text}) + result.update({"route": values, "message": "Route updated and applied"}) + return result + + +def route_delete(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + old_command = " ".join(str(payload.get("original_command") or "").split()) + if not old_command: + raise ValueError("original_command is required") + old_text = read_config_text(iface) + cfg = parse_config(old_text, iface) + _find_route_item(cfg, iface, old_command) + old_down = _expected_route_down(old_command) + new_text = _edit_interface_hooks(old_text, [old_command], [old_down], [], []) + result = raw_config_apply(iface, {"content": new_text}) + result["message"] = "Route removed and applied" + return result + + +def access_rule_create(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + old_text = read_config_text(iface) + cfg = parse_config(old_text, iface) + ups, downs, values = _build_access_rule_commands(payload) + existing = {" ".join(str(r.get("command") or "").split()) for r in cfg.get("firewall", [])} + duplicates = [up for up in ups if " ".join(up.split()) in existing] + if duplicates: + raise ValueError("One or more identical firewall rules already exist") + new_text = _edit_interface_hooks(old_text, [], [], ups, downs) + result = raw_config_apply(iface, {"content": new_text}) + result.update({"access_rule": values, "message": "Access rule added and applied"}) + return result + + +def access_rule_update(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + old_command = " ".join(str(payload.get("original_command") or "").split()) + if not old_command: + raise ValueError("original_command is required") + old_text = read_config_text(iface) + cfg = parse_config(old_text, iface) + item = _find_access_item(cfg, iface, old_command) + ups, downs, values = _build_access_rule_commands(payload) + managed_tag = str((item.get("access") or {}).get("managed_tag") or "") + old_meta = None + + if managed_tag: + # Editing one automatically generated restriction turns only that + # destination into an explicit exception. The client's remaining + # local-network restrictions keep following Site-to-site changes. + old_destination = str((item.get("access") or {}).get("destination") or "").strip() + if not old_destination: + raise ValueError("Managed client policy destination is missing") + old_meta = _set_policy_exclusion_by_tag(managed_tag, old_destination) + if not old_meta: + raise ValueError("The managed client policy metadata no longer exists") + working_text = sync_managed_client_policies(old_text, iface) + try: + new_text = _edit_interface_hooks(working_text, [], [], ups, downs) + result = raw_config_apply(iface, {"content": new_text}) + except Exception: + save_client_meta(old_meta) + raise + else: + old_down = _expected_access_down(old_command) + new_text = _edit_interface_hooks(old_text, [old_command], [old_down], ups, downs) + result = raw_config_apply(iface, {"content": new_text}) + + result.update({"access_rule": values, "message": "Access rule updated and applied"}) + return result + + +def access_rule_delete(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + old_command = " ".join(str(payload.get("original_command") or "").split()) + if not old_command: + raise ValueError("original_command is required") + old_text = read_config_text(iface) + cfg = parse_config(old_text, iface) + item = _find_access_item(cfg, iface, old_command) + managed_tag = str((item.get("access") or {}).get("managed_tag") or "") + + if managed_tag: + destination = str((item.get("access") or {}).get("destination") or "").strip() + if not destination: + raise ValueError("Managed client policy destination is missing") + old_meta = _set_policy_exclusion_by_tag(managed_tag, destination) + if not old_meta: + raise ValueError("The managed client policy metadata no longer exists") + try: + new_text = sync_managed_client_policies(old_text, iface) + backup = write_config_transaction(iface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) + except Exception: + save_client_meta(old_meta) + raise + return { + "ok": True, + "message": "Managed client restriction removed; the destination is now an explicit exception for this client", + "backup": str(backup), + "restarted": False, + } + + command_to_remove = old_command + old_down = _expected_access_down(command_to_remove) + new_text = _edit_interface_hooks(old_text, [command_to_remove], [old_down], [], []) + result = raw_config_apply(iface, {"content": new_text}) + result["message"] = "Access rule removed and applied" + return result + + +def raw_config_get(iface: str) -> dict[str, Any]: + require_valid_iface(iface) + config_path = WG_DIR / f"{iface}.conf" + if not config_path.exists(): + raise RuntimeError(f"{config_path} does not exist") + text = config_path.read_text(encoding="utf-8", errors="strict") + stat = config_path.stat() + return { + "ok": True, + "interface": iface, + "path": str(config_path), + "content": text, + "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), + "modified_at": int(stat.st_mtime), + "running": bool(wg_dump(iface).get("running")), + } + + +def normalize_raw_config_text(value: Any) -> str: + if not isinstance(value, str): + raise ValueError("Configuration content must be text") + if not value.strip(): + raise ValueError("Configuration cannot be empty") + if len(value.encode("utf-8")) > 1024 * 1024: + raise ValueError("Configuration is too large") + if "\x00" in value: + raise ValueError("Configuration contains a NUL byte") + text = value.replace("\r\n", "\n").replace("\r", "\n") + if not text.endswith("\n"): + text += "\n" + if not re.search(r"(?mi)^\s*\[Interface\]\s*$", text): + raise ValueError("WireGuard configuration must contain an [Interface] section") + return text + + +def raw_config_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + require_valid_iface(iface) + if not wg_installed(): + raise RuntimeError("WireGuard is not installed") + + config_path = WG_DIR / f"{iface}.conf" + if not config_path.exists(): + raise RuntimeError(f"{config_path} does not exist") + + new_text = normalize_raw_config_text(payload.get("content")) + new_cfg = parse_config(new_text, iface) + if ('# WGEXT-FORWARD ' in new_text or f'# WGEXT-LISTEN-{iface} ' in new_text) and str((new_cfg.get('interface') or {}).get('save_config') or '').lower() == 'true': + raise ValueError("Przekierowania i ograniczenie nasłuchiwania wymagają SaveConfig = false") + validate_dir = Path("/run/wgtools-validate") + validate_dir.mkdir(parents=True, exist_ok=True) + validate_path = validate_dir / f"{iface}.conf" + validate_path.write_text(new_text, encoding="utf-8") + os.chmod(validate_path, 0o600) + try: + # wg-quick strip parses the file without executing PostUp/PostDown commands. + validate_config_file(validate_path) + finally: + try: + validate_path.unlink() + except FileNotFoundError: + pass + + backup = make_backup(iface, config_path) + was_running = bool(wg_dump(iface).get("running")) + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + service = f"wg-quick@{iface}.service" + + if was_running: + rc, out, err = run([systemctl, "stop", service], timeout=30) + if rc != 0: + raise RuntimeError(f"Could not stop {service} before applying the raw configuration: {err or out}") + if wg_dump(iface).get("running"): + raise RuntimeError(f"{iface} is still running after systemd reported that it was stopped; configuration was not changed") + + tmp = WG_DIR / f".{iface}.conf.wgtools-raw.tmp" + try: + tmp.write_text(new_text, encoding="utf-8") + os.chmod(tmp, 0o600) + os.replace(tmp, config_path) + os.chmod(config_path, 0o600) + + if was_running: + rc, out, err = run([systemctl, "start", service], timeout=35) + if rc != 0 or not wg_dump(iface).get("running"): + failure = (err or out or f"{iface} did not return to the running state")[-1800:] + shutil.copy2(backup, config_path) + os.chmod(config_path, 0o600) + rollback_rc, rollback_out, rollback_err = run([systemctl, "start", service], timeout=35) + rollback_ok = rollback_rc == 0 and bool(wg_dump(iface).get("running")) + if rollback_ok: + raise RuntimeError(f"New configuration failed to start and was rolled back automatically. Detail: {failure}") + raise RuntimeError( + "New configuration failed and automatic rollback could not restore the WireGuard interface. " + f"New config error: {failure}. Rollback error: {(rollback_err or rollback_out)[-1200:]}" + ) + # A restart executes PostDown/PostUp once, but older releases could + # have left duplicate/stale tagged rules in RAM. Reconcile against + # the config that is now active so one restart cannot preserve them. + _apply_managed_policy_runtime_diff("", new_text) + except Exception: + try: + tmp.unlink() + except FileNotFoundError: + pass + raise + + return { + "ok": True, + "message": "Configuration saved and applied" if was_running else "Configuration saved. The WireGuard interface was already stopped, so it was left stopped.", + "backup": str(backup), + "running": bool(wg_dump(iface).get("running")), + "restarted": was_running, + } + + +def _wgtools_version() -> str: + for candidate in (Path("/opt/wgtools/VERSION"), Path(__file__).resolve().parents[1] / "VERSION"): + try: + value = candidate.read_text(encoding="utf-8").strip() + if value: + return value + except Exception: + pass + return "unknown" + + +def _copy_sqlite_database(source: Path, destination: Path) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + src = sqlite3.connect(source, timeout=10) + dst = sqlite3.connect(destination, timeout=10) + try: + src.backup(dst) + finally: + dst.close() + src.close() + os.chmod(destination, 0o600) + + +def _migration_manifest(iface: str, *, interfaces: list[dict[str, Any]], has_database: bool, managed_clients: int, vps_relays: int, has_sysctl: bool, has_interface_meta: bool, has_groups: bool) -> dict[str, Any]: + return { + "product": "WGTools", + "format_version": MIGRATION_FORMAT_VERSION, + "created_at": int(time.time()), + "wgtools_version": _wgtools_version(), + # Kept for compatibility and as the preferred/default interface. + "interface": iface, + "interfaces": interfaces, + "source_hostname": os.uname().nodename, + "components": { + "wireguard_config": bool(interfaces), + "wireguard_configs": len(interfaces), + "database": has_database, + "managed_clients": managed_clients, + "vps_relay_records": vps_relays, + "client_groups": has_groups, + "interface_metadata": has_interface_meta, + "sysctl_forwarding": has_sysctl, + "automatic_config_history": False, + }, + "contains_secrets": True, + } + + +def _build_migration_archive(iface: str, destination_dir: Path, *, prefix: str = "WGTools-backup") -> Path: + require_valid_iface(iface) + destination_dir.mkdir(parents=True, exist_ok=True) + os.chmod(destination_dir, 0o700) + staging = Path(tempfile.mkdtemp(prefix="wgtools-export-", dir="/run")) + try: + has_database = DATABASE_PATH.exists() + managed_clients = 0 + vps_relays = 0 + has_sysctl = SYSCTL_FILE.exists() + has_interface_meta = INTERFACES_META_PATH.exists() + has_groups = GROUPS_PATH.exists() + interface_entries: list[dict[str, Any]] = [] + + (staging / "data" / "clients").mkdir(parents=True, exist_ok=True) + if has_database: + _copy_sqlite_database(DATABASE_PATH, staging / "data" / "wgtools.db") + try: + conn = sqlite3.connect(DATABASE_PATH, timeout=10) + try: + row = conn.execute("SELECT COUNT(*) FROM vps_relays WHERE status IN ('installed','detached')").fetchone() + vps_relays = int(row[0] or 0) if row else 0 + finally: + conn.close() + except sqlite3.Error: + vps_relays = 0 + + if CLIENT_DIR.exists(): + for source in sorted(CLIENT_DIR.glob("*.json")): + if not source.is_file(): + continue + target = staging / "data" / "clients" / source.name + shutil.copy2(source, target) + os.chmod(target, 0o600) + managed_clients += 1 + + if has_interface_meta: + target = staging / "data" / "interfaces.json" + shutil.copy2(INTERFACES_META_PATH, target) + os.chmod(target, 0o600) + + if has_groups: + target = staging / "data" / "groups.json" + shutil.copy2(GROUPS_PATH, target) + os.chmod(target, 0o600) + + if EXT_IP_GROUPS_PATH.exists(): + target = staging / "data" / "extended-ip-groups.json" + shutil.copy2(EXT_IP_GROUPS_PATH, target) + os.chmod(target, 0o600) + + names = sorted({p.stem for p in WG_DIR.glob("*.conf") if p.is_file() and ALLOWED_IFACE_RE.fullmatch(p.stem)}) if WG_DIR.exists() else [] + for name in names: + config_path = WG_DIR / f"{name}.conf" + target = staging / "wireguard" / f"{name}.conf" + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(config_path, target) + os.chmod(target, 0o600) + interface_entries.append({"name": name, "running": bool(wg_dump(name).get("running")) if wg_installed() else False}) + + if has_sysctl: + target = staging / "system" / SYSCTL_FILE.name + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(SYSCTL_FILE, target) + + manifest = _migration_manifest( + iface, + interfaces=interface_entries, + has_database=has_database, + managed_clients=managed_clients, + vps_relays=vps_relays, + has_sysctl=has_sysctl, + has_interface_meta=has_interface_meta, + has_groups=has_groups, + ) + (staging / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + stamp = time.strftime("%Y%m%d-%H%M%S") + filename = f"{prefix}-{stamp}.wgtbackup" + archive = destination_dir / filename + counter = 1 + while archive.exists(): + archive = destination_dir / f"{prefix}-{stamp}-{counter}.wgtbackup" + counter += 1 + with tarfile.open(archive, "w:gz", compresslevel=6) as tf: + for rel in ("manifest.json", "wireguard", "data", "system"): + item = staging / rel + if item.exists(): + tf.add(item, arcname=rel, recursive=True) + os.chmod(archive, 0o600) + return archive + finally: + shutil.rmtree(staging, ignore_errors=True) + + +def migration_backup_create(iface: str) -> dict[str, Any]: + archive = _build_migration_archive(iface, EXPORT_DIR) + return { + "ok": True, + "path": str(archive), + "filename": archive.name, + "size": archive.stat().st_size, + "message": "Full migration backup created", + } + + +def _safe_extract_migration_archive(archive: Path, destination: Path) -> dict[str, Any]: + if not archive.exists() or not archive.is_file(): + raise RuntimeError("Backup file does not exist") + if archive.stat().st_size <= 0 or archive.stat().st_size > MIGRATION_MAX_BYTES: + raise RuntimeError("Backup file is empty or exceeds the 64 MB safety limit") + total = 0 + allowed_roots = {"manifest.json", "wireguard", "data", "system"} + try: + tf = tarfile.open(archive, "r:gz") + except (tarfile.TarError, OSError) as exc: + raise RuntimeError("The selected file is not a valid WGTools backup archive") from exc + with tf: + for member in tf.getmembers(): + name = member.name.replace("\\", "/") + while name.startswith("./"): + name = name[2:] + parts = [part for part in name.split("/") if part not in ("", ".")] + if name.startswith("/") or not parts or ".." in parts or parts[0] not in allowed_roots: + raise RuntimeError(f"Unsafe or unsupported path in backup: {member.name}") + if member.issym() or member.islnk() or not (member.isdir() or member.isfile()): + raise RuntimeError(f"Unsupported archive entry: {member.name}") + if member.isfile(): + total += max(0, int(member.size)) + if total > MIGRATION_MAX_BYTES: + raise RuntimeError("Unpacked backup exceeds the 64 MB safety limit") + target = destination.joinpath(*parts) + target.parent.mkdir(parents=True, exist_ok=True) + source = tf.extractfile(member) + if source is None: + raise RuntimeError(f"Could not read backup entry: {member.name}") + with target.open("wb") as out: + shutil.copyfileobj(source, out) + else: + destination.joinpath(*parts).mkdir(parents=True, exist_ok=True) + + manifest_path = destination / "manifest.json" + if not manifest_path.exists(): + raise RuntimeError("Backup manifest is missing") + try: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + except Exception as exc: + raise RuntimeError("Backup manifest is invalid") from exc + version = int(manifest.get("format_version", 0)) + if manifest.get("product") != "WGTools" or version not in {1, 2, 3, MIGRATION_FORMAT_VERSION}: + raise RuntimeError("Unsupported WGTools backup format") + return manifest + + +def _validate_restored_database(path: Path) -> None: + if not path.exists(): + raise RuntimeError("WGTools database is missing from the backup") + conn = sqlite3.connect(path, timeout=10) + try: + row = conn.execute("PRAGMA integrity_check").fetchone() + if not row or str(row[0]).lower() != "ok": + raise RuntimeError("WGTools database failed SQLite integrity_check") + tables = {str(row[0]) for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()} + if "users" not in tables: + raise RuntimeError("WGTools database does not contain the users table") + finally: + conn.close() + + +def _replace_file(source: Path | None, target: Path, mode: int) -> None: + target.parent.mkdir(parents=True, exist_ok=True) + if source is None or not source.exists(): + try: + target.unlink() + except FileNotFoundError: + pass + return + temp = target.parent / f".{target.name}.wgtools-restore-{os.getpid()}" + shutil.copy2(source, temp) + os.chmod(temp, mode) + os.replace(temp, target) + os.chmod(target, mode) + + +def _replace_clients(source_dir: Path | None) -> None: + CLIENT_DIR.parent.mkdir(parents=True, exist_ok=True) + temp = DATA_DIR / f".clients-restore-{os.getpid()}" + shutil.rmtree(temp, ignore_errors=True) + temp.mkdir(parents=True, exist_ok=True) + os.chmod(temp, 0o700) + if source_dir is not None and source_dir.exists(): + for source in source_dir.glob("*.json"): + if source.is_file(): + target = temp / source.name + shutil.copy2(source, target) + os.chmod(target, 0o600) + old = DATA_DIR / f".clients-old-{os.getpid()}" + shutil.rmtree(old, ignore_errors=True) + if CLIENT_DIR.exists(): + os.replace(CLIENT_DIR, old) + os.replace(temp, CLIENT_DIR) + shutil.rmtree(old, ignore_errors=True) + + +def _manifest_interfaces(iface: str, tree: Path, manifest: dict[str, Any]) -> list[dict[str, Any]]: + version = int(manifest.get("format_version", 0)) + if version == 1: + backup_iface = str(manifest.get("interface") or "") + if backup_iface != iface: + raise RuntimeError(f"Backup belongs to interface {backup_iface or 'unknown'}, but this WGTools instance manages {iface}") + config = tree / "wireguard" / f"{iface}.conf" + return [{"name": iface, "running": True}] if config.exists() else [] + result: list[dict[str, Any]] = [] + raw = manifest.get("interfaces") if isinstance(manifest.get("interfaces"), list) else [] + for item in raw: + if not isinstance(item, dict): + continue + name = str(item.get("name") or "").strip() + if ALLOWED_IFACE_RE.fullmatch(name) and (tree / "wireguard" / f"{name}.conf").exists(): + result.append({"name": name, "running": bool(item.get("running"))}) + if not result: + for path in sorted((tree / "wireguard").glob("*.conf")) if (tree / "wireguard").exists() else []: + if ALLOWED_IFACE_RE.fullmatch(path.stem): + result.append({"name": path.stem, "running": True}) + return result + + +def _apply_migration_tree(iface: str, tree: Path, manifest: dict[str, Any], *, start_configured_wireguard: bool) -> None: + components = manifest.get("components") if isinstance(manifest.get("components"), dict) else {} + interface_entries = _manifest_interfaces(iface, tree, manifest) + + db_source = tree / "data" / "wgtools.db" + _validate_restored_database(db_source) + + if interface_entries and not wg_installed(): + install_wireguard() + for entry in interface_entries: + validate_config_file(tree / "wireguard" / f"{entry['name']}.conf") + + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + run([systemctl, "stop", "wgtools-telegram.service"], timeout=20) + if wg_installed(): + for entry in interface_entries: + run([systemctl, "stop", f"wg-quick@{entry['name']}.service"], timeout=40) + + db_temp = DATA_DIR / f".wgtools.db.restore-{os.getpid()}" + shutil.copy2(db_source, db_temp) + os.chmod(db_temp, 0o600) + os.replace(db_temp, DATABASE_PATH) + os.chmod(DATABASE_PATH, 0o600) + for suffix in ("-wal", "-shm"): + try: + Path(str(DATABASE_PATH) + suffix).unlink() + except FileNotFoundError: + pass + + _replace_clients(tree / "data" / "clients") + meta_source = tree / "data" / "interfaces.json" + if int(manifest.get("format_version", 0)) >= 2: + _replace_file(meta_source if meta_source.exists() else None, INTERFACES_META_PATH, 0o600) + groups_source = tree / "data" / "groups.json" + if int(manifest.get("format_version", 0)) >= 3: + _replace_file(groups_source if groups_source.exists() else None, GROUPS_PATH, 0o600) + else: + _replace_file(None, GROUPS_PATH, 0o600) + extended_groups_source = tree / "data" / "extended-ip-groups.json" + _replace_file(extended_groups_source if int(manifest.get("format_version", 0)) >= 4 and extended_groups_source.exists() else None, EXT_IP_GROUPS_PATH, 0o600) + + for entry in interface_entries: + name = entry["name"] + _replace_file(tree / "wireguard" / f"{name}.conf", WG_DIR / f"{name}.conf", 0o600) + + sysctl_source = tree / "system" / SYSCTL_FILE.name + _replace_file(sysctl_source if bool(components.get("sysctl_forwarding")) and sysctl_source.exists() else None, SYSCTL_FILE, 0o644) + + for entry in interface_entries: + name = entry["name"] + run([systemctl, "enable", f"wg-quick@{name}.service"], timeout=20) + should_run = bool(entry.get("running")) if int(manifest.get("format_version", 0)) >= 2 else start_configured_wireguard + if start_configured_wireguard and should_run: + rc, out, err = run([systemctl, "restart", f"wg-quick@{name}.service"], timeout=45) + if rc != 0 or not wg_dump(name).get("running"): + raise RuntimeError(f"Restored WireGuard configuration {name} could not be started: {(err or out)[-1600:]}") + else: + run([systemctl, "stop", f"wg-quick@{name}.service"], timeout=30) + + run([systemctl, "restart", "wgtools-telegram.service"], timeout=20) + + +def _prune_migration_safety_backups() -> None: + if not MIGRATION_SAFETY_DIR.exists(): + return + files = sorted(MIGRATION_SAFETY_DIR.glob("*.wgtbackup"), key=lambda p: p.stat().st_mtime, reverse=True) + for stale in files[5:]: + try: + stale.unlink() + except OSError: + pass + + +def migration_restore(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + raw_path = str(payload.get("path") or "").strip() + if not raw_path: + raise ValueError("Backup path is required") + archive = Path(raw_path) + import_root = DATA_DIR / "imports" + try: + archive.resolve().relative_to(import_root.resolve()) + except Exception as exc: + raise RuntimeError("Restore file is outside the WGTools import directory") from exc + + restore_tree = Path(tempfile.mkdtemp(prefix="wgtools-restore-", dir="/run")) + rollback_tree = Path(tempfile.mkdtemp(prefix="wgtools-rollback-", dir="/run")) + safety_archive: Path | None = None + try: + manifest = _safe_extract_migration_archive(archive, restore_tree) + _validate_restored_database(restore_tree / "data" / "wgtools.db") + restore_entries = _manifest_interfaces(iface, restore_tree, manifest) + if restore_entries and not wg_installed(): + install_wireguard() + for entry in restore_entries: + validate_config_file(restore_tree / "wireguard" / f"{entry['name']}.conf") + + safety_archive = _build_migration_archive(iface, MIGRATION_SAFETY_DIR, prefix="WGTools-pre-restore") + _prune_migration_safety_backups() + rollback_manifest = _safe_extract_migration_archive(safety_archive, rollback_tree) + + try: + _apply_migration_tree(iface, restore_tree, manifest, start_configured_wireguard=True) + except Exception as exc: + try: + _apply_migration_tree(iface, rollback_tree, rollback_manifest, start_configured_wireguard=True) + except Exception as rollback_exc: + raise RuntimeError(f"Restore failed: {exc}. Automatic rollback also failed: {rollback_exc}") from exc + raise RuntimeError(f"Restore failed and the previous WGTools state was restored automatically: {exc}") from exc + + return { + "ok": True, + "message": "Full WGTools backup restored successfully", + "backup_version": str(manifest.get("wgtools_version") or "unknown"), + "created_at": int(manifest.get("created_at") or 0), + "interfaces_restored": [entry["name"] for entry in restore_entries], + "safety_backup": str(safety_archive) if safety_archive else None, + "running": bool(wg_dump(iface).get("running")) if wg_installed() else False, + "relogin_required": True, + } + finally: + shutil.rmtree(restore_tree, ignore_errors=True) + shutil.rmtree(rollback_tree, ignore_errors=True) + + +def _current_wgtools_version() -> str: + try: + value = (APP_DIR / "VERSION").read_text(encoding="utf-8").strip() + return value or "unknown" + except Exception: + return "unknown" + + +def _version_tuple(value: str) -> tuple[int, int, int] | None: + text = str(value or "").strip() + if text.startswith("v"): + text = text[1:] + match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", text) + if not match: + return None + return tuple(int(match.group(i)) for i in range(1, 4)) + + +def update_check() -> dict[str, Any]: + raise RuntimeError("Aktualizacje online są wyłączone. Wgraj pakiet .bin w ustawieniach.") + + +def update_notice() -> dict[str, Any]: + return {"ok": True, "update_available": False, "latest_version": ""} + + +def _write_update_status(data: dict[str, Any]) -> None: + DATA_DIR.mkdir(parents=True, exist_ok=True) + try: + DATA_DIR.chmod(0o700) + except OSError: + pass + payload = dict(data) + payload["updated_at"] = int(time.time()) + temp = UPDATE_STATUS_PATH.with_name(f".{UPDATE_STATUS_PATH.name}.{os.getpid()}.tmp") + temp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") + temp.chmod(0o600) + os.replace(temp, UPDATE_STATUS_PATH) + + +def update_status() -> dict[str, Any]: + if not UPDATE_STATUS_PATH.exists(): + return {"ok": True, "state": "idle", "current_version": _current_wgtools_version()} + try: + data = json.loads(UPDATE_STATUS_PATH.read_text(encoding="utf-8")) + if not isinstance(data, dict): + raise ValueError("invalid status") + except Exception: + return {"ok": True, "state": "idle", "current_version": _current_wgtools_version()} + data["ok"] = True + data["current_version"] = _current_wgtools_version() + return data + + +def _current_web_port() -> int: + service = SYSTEMD_DIR / "wgtools.service" + try: + text = service.read_text(encoding="utf-8", errors="replace") + match = re.search(r"--port\s+(\d{1,5})", text) + if match: + port = int(match.group(1)) + if 1 <= port <= 65535: + return port + except Exception: + pass + return 8341 + + +def _validate_update_source(source_root: Path, expected_version: str) -> None: + required = [ + "VERSION", + "app/main.py", + "app/locales/en.json", + "app/locales/ru.json", + "scripts/install.sh", + "scripts/uninstall.sh", + "scripts/wgtools-helper", + "systemd/wgtools.service", + "systemd/wgtools-telegram.service", + "systemd/wgtools-certbot-renew.service", + "systemd/wgtools-certbot-renew.timer", + "scripts/wgtools-web", + "scripts/wgtools-certbot-reload", + "scripts/wgtools-cli", + "requirements.txt", + ] + for relative in required: + if not (source_root / relative).is_file(): + raise RuntimeError(f"Update archive is missing required file: {relative}") + actual_version = (source_root / "VERSION").read_text(encoding="utf-8").strip() + if actual_version != expected_version: + raise RuntimeError(f"Update archive version mismatch: expected {expected_version}, got {actual_version or 'empty'}") + for locale in (source_root / "app/locales/en.json", source_root / "app/locales/ru.json"): + json.loads(locale.read_text(encoding="utf-8")) + for script_name in ("scripts/install.sh", "scripts/wgtools-cli"): + rc, out, err = run(["bash", "-n", str(source_root / script_name)], timeout=15) + if rc != 0: + raise RuntimeError(f"Update script syntax check failed ({script_name}): {err or out}") + rc, out, err = run(["python3", "-m", "py_compile", str(source_root / "app/main.py"), str(source_root / "scripts/wgtools-helper")], timeout=30) + if rc != 0: + raise RuntimeError(f"Update Python syntax check failed: {err or out}") + + +def _create_app_rollback_archive(current_version: str) -> Path: + UPDATE_BACKUP_DIR.mkdir(parents=True, exist_ok=True) + UPDATE_BACKUP_DIR.chmod(0o700) + stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime()) + path = UPDATE_BACKUP_DIR / f"WGTools-app-pre-update-v{current_version}-{stamp}.tar.gz" + with tarfile.open(path, "w:gz") as tar: + if APP_DIR.exists(): + tar.add(APP_DIR, arcname="opt/wgtools", recursive=True) + files = [ + (ENV_FILE, "etc/wgtools/wgtools.env"), + (HTTPS_ENV_FILE, "etc/wgtools/https.env"), + (HTTPS_STATE_FILE, "etc/wgtools/https.json"), + (HELPER_INSTALL_PATH, "usr/local/libexec/wgtools-helper"), + (Path("/usr/local/libexec/wgtools-certbot-reload"), "usr/local/libexec/wgtools-certbot-reload"), + (Path("/usr/local/bin/wgtools"), "usr/local/bin/wgtools"), + (SYSTEMD_DIR / "wgtools.service", "etc/systemd/system/wgtools.service"), + (SYSTEMD_DIR / "wgtools-telegram.service", "etc/systemd/system/wgtools-telegram.service"), + (SYSTEMD_DIR / "wgtools-certbot-renew.service", "etc/systemd/system/wgtools-certbot-renew.service"), + (SYSTEMD_DIR / "wgtools-certbot-renew.timer", "etc/systemd/system/wgtools-certbot-renew.timer"), + ] + for source, arcname in files: + if source.exists(): + tar.add(source, arcname=arcname, recursive=False) + path.chmod(0o600) + return path + + +def _restore_app_rollback_archive(archive: Path) -> None: + restore_root = Path(tempfile.mkdtemp(prefix="wgtools-update-rollback-", dir="/run")) + try: + with tarfile.open(archive, "r:gz") as tar: + root = restore_root.resolve() + for member in tar.getmembers(): + target = (restore_root / member.name).resolve() + try: + target.relative_to(root) + except Exception as exc: + raise RuntimeError("Rollback archive contains an unsafe path") from exc + tar.extractall(restore_root) + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + run([systemctl, "stop", "wgtools.service"], timeout=30) + run([systemctl, "stop", "wgtools-telegram.service"], timeout=30) + restored_app = restore_root / "opt/wgtools" + if not restored_app.is_dir(): + raise RuntimeError("Rollback archive does not contain the previous application") + shutil.rmtree(APP_DIR, ignore_errors=True) + shutil.copytree(restored_app, APP_DIR, symlinks=True) + cli_backup = restore_root / "usr/local/bin/wgtools" + if not cli_backup.exists(): + try: + Path("/usr/local/bin/wgtools").unlink() + except FileNotFoundError: + pass + replacements = [ + (restore_root / "etc/wgtools/wgtools.env", ENV_FILE, 0o644), + (restore_root / "etc/wgtools/https.env", HTTPS_ENV_FILE, 0o600), + (restore_root / "etc/wgtools/https.json", HTTPS_STATE_FILE, 0o600), + (restore_root / "usr/local/libexec/wgtools-helper", HELPER_INSTALL_PATH, 0o755), + (restore_root / "usr/local/libexec/wgtools-certbot-reload", Path("/usr/local/libexec/wgtools-certbot-reload"), 0o755), + (restore_root / "usr/local/bin/wgtools", Path("/usr/local/bin/wgtools"), 0o755), + (restore_root / "etc/systemd/system/wgtools.service", SYSTEMD_DIR / "wgtools.service", 0o644), + (restore_root / "etc/systemd/system/wgtools-telegram.service", SYSTEMD_DIR / "wgtools-telegram.service", 0o644), + (restore_root / "etc/systemd/system/wgtools-certbot-renew.service", SYSTEMD_DIR / "wgtools-certbot-renew.service", 0o644), + (restore_root / "etc/systemd/system/wgtools-certbot-renew.timer", SYSTEMD_DIR / "wgtools-certbot-renew.timer", 0o644), + ] + for source, destination, mode in replacements: + if source.exists(): + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + destination.chmod(mode) + run([systemctl, "daemon-reload"], timeout=30) + if _https_enabled_from_env() and (SYSTEMD_DIR / "wgtools-certbot-renew.timer").exists(): + run([systemctl, "enable", "--now", HTTPS_RENEW_TIMER], timeout=20) + rc, out, err = run([systemctl, "restart", "wgtools.service"], timeout=45) + if rc != 0: + raise RuntimeError(f"Could not restart the previous WGTools web service: {err or out}") + run([systemctl, "restart", "wgtools-telegram.service"], timeout=30) + finally: + shutil.rmtree(restore_root, ignore_errors=True) + + +def _prune_update_backups() -> None: + if not UPDATE_BACKUP_DIR.exists(): + return + groups = ["WGTools-app-pre-update-*.tar.gz", "WGTools-pre-update-*.wgtbackup"] + for pattern in groups: + files = sorted(UPDATE_BACKUP_DIR.glob(pattern), key=lambda p: p.stat().st_mtime, reverse=True) + for stale in files[3:]: + try: + stale.unlink() + except OSError: + pass + + +def _uploaded_update_path(value: str) -> Path: + root = (DATA_DIR / "imports").resolve() + path = Path(value) + if not re.fullmatch(r"upload-[0-9a-f]{24}\.bin", path.name) or path.resolve().parent != root or not path.is_file() or path.is_symlink(): + raise ValueError("Nieprawidłowa ścieżka pakietu aktualizacji") + if not 0 < path.stat().st_size <= 64 * 1024 * 1024: + raise ValueError("Pakiet aktualizacji musi mieć rozmiar do 64 MB") + return path + + +def _extract_uploaded_update(archive: Path, destination: Path) -> Path: + destination.mkdir(parents=True, exist_ok=True) + root = destination.resolve() + total = 0 + seen: set[str] = set() + with tarfile.open(archive, "r:gz") as tar: + for count, member in enumerate(tar, 1): + if count > 10000: + raise ValueError("Pakiet zawiera za dużo plików") + name = member.name.replace('\\', '/') + parts = [part for part in name.split('/') if part not in ('', '.')] + if name.startswith('/') or not parts or '..' in parts or not (member.isfile() or member.isdir()): + raise ValueError("Pakiet zawiera niedozwolony wpis") + normalized = '/'.join(parts) + if normalized in seen: + raise ValueError("Pakiet zawiera powtórzoną ścieżkę") + seen.add(normalized) + target = destination.joinpath(*parts) + target.resolve().relative_to(root) + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + else: + total += member.size + if total > 256 * 1024 * 1024: + raise ValueError("Rozpakowany pakiet jest za duży") + target.parent.mkdir(parents=True, exist_ok=True) + source = tar.extractfile(member) + if source is None: + raise ValueError("Nie można odczytać pakietu") + with target.open('wb') as out: + shutil.copyfileobj(source, out) + os.chmod(target, member.mode & 0o755) + return destination + + +def _uploaded_update_validate(path: Path, work: Path) -> tuple[Path, str]: + source = _extract_uploaded_update(path, work) + version_file = source / 'VERSION' + if not version_file.is_file(): + raise ValueError("Pakiet nie zawiera pliku VERSION") + version = version_file.read_text(encoding='utf-8').strip() + if not re.fullmatch(r'\d+\.\d+\.\d+', version): + raise ValueError("Nieprawidłowa wersja pakietu") + _validate_update_source(source, version) + current = _current_wgtools_version() + if not _version_tuple(current) or _version_tuple(version) <= _version_tuple(current): + raise ValueError("Wersja pakietu musi być nowsza od zainstalowanej") + return source, version + + +def update_file_schedule(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + if str(update_status().get('state') or '') in {'queued', 'running', 'rolling_back'}: + raise ValueError("Aktualizacja jest już uruchomiona") + path = _uploaded_update_path(str(payload.get('path') or '')) + with tempfile.TemporaryDirectory(prefix='wgext-update-check-', dir=DATA_DIR) as work: + _, version = _uploaded_update_validate(path, Path(work) / 'source') + digest = hashlib.sha256(path.read_bytes()).hexdigest() + unit = f"wgtools-update-{int(time.time())}-{os.getpid()}" + _write_update_status({'state':'queued', 'target_version':version, 'current_version':_current_wgtools_version(), 'message':'Aktualizacja oczekuje na uruchomienie', 'unit':unit}) + rc, out, err = run([shutil.which('systemd-run') or '/usr/bin/systemd-run', '--quiet', '--collect', '--no-block', f'--unit={unit}', '--property=Type=oneshot', f'--setenv=WGEXT_UPDATE_PATH={path}', f'--setenv=WGEXT_UPDATE_SHA256={digest}', str(HELPER_INSTALL_PATH), 'update_file_apply', iface], timeout=20) + if rc: + _write_update_status({'state':'error', 'message':'Nie udało się uruchomić aktualizacji', 'error':err or out}) + raise RuntimeError(f"Nie udało się uruchomić aktualizacji: {err or out}") + return {'ok':True, 'scheduled':True, 'target_version':version, 'unit':unit} + + +def update_file_apply(iface: str) -> dict[str, Any]: + path = _uploaded_update_path(str(os.environ.get('WGEXT_UPDATE_PATH') or '')) + expected = str(os.environ.get('WGEXT_UPDATE_SHA256') or '') + rollback = None + backup = None + current = _current_wgtools_version() + try: + if not re.fullmatch(r'[0-9a-f]{64}', expected) or not secrets.compare_digest(hashlib.sha256(path.read_bytes()).hexdigest(), expected): + raise ValueError("Pakiet zmienił się po zatwierdzeniu") + with tempfile.TemporaryDirectory(prefix='wgext-update-', dir=DATA_DIR) as work: + source, version = _uploaded_update_validate(path, Path(work) / 'source') + _write_update_status({'state':'running', 'phase':'backup', 'target_version':version, 'current_version':current, 'message':'Tworzenie kopii zapasowej'}) + backup = locked_call(lambda: _build_migration_archive(iface, UPDATE_BACKUP_DIR, prefix='WGTools-pre-update')) + rollback = _create_app_rollback_archive(current) + _prune_update_backups() + _write_update_status({'state':'running', 'phase':'install', 'target_version':version, 'current_version':current, 'message':'Instalowanie aktualizacji', 'state_backup':backup.name, 'app_backup':rollback.name}) + proc = subprocess.run(['bash', str(source / 'scripts/install.sh')], cwd=str(source), capture_output=True, text=True, timeout=900, check=False, env={**os.environ, 'WG_INTERFACE':iface, 'WGTOOLS_PORT':str(_current_web_port())}) + if proc.returncode: + raise RuntimeError(f"Instalator zakończył się błędem: {(proc.stderr or proc.stdout)[-5000:]}") + rc, out, err = run([shutil.which('systemctl') or '/usr/bin/systemctl', 'is-active', 'wgtools.service'], timeout=15) + if _current_wgtools_version() != version or rc or out.strip() != 'active': + raise RuntimeError(f"Nie udało się uruchomić zaktualizowanego programu: {err or out}") + _write_update_status({'state':'success', 'phase':'done', 'target_version':version, 'current_version':version, 'message':f'Zainstalowano WGTools-Extended {version}', 'state_backup':backup.name, 'app_backup':rollback.name}) + _write_system_audit('update.completed', object=version, result='updated') + return {'ok':True, 'version':version} + except Exception as exc: + rollback_ok = False + rollback_error = '' + if rollback and rollback.exists(): + _write_update_status({'state':'rolling_back', 'message':'Przywracanie poprzedniej wersji', 'error':str(exc)}) + try: + _restore_app_rollback_archive(rollback) + rollback_ok = True + except Exception as rollback_exc: + rollback_error = str(rollback_exc) + _write_update_status({'state':'error', 'message':'Aktualizacja nie powiodła się', 'error':str(exc), 'rollback_ok':rollback_ok, 'rollback_error':rollback_error, 'state_backup':backup.name if backup else None}) + _write_system_audit('update.failed', object='upload', result=f'error: {_audit_safe_text(exc)}') + raise + finally: + path.unlink(missing_ok=True) + + +def update_schedule(iface: str, payload: dict[str, Any]) -> dict[str, Any]: + raise RuntimeError("Aktualizacje online są wyłączone. Wgraj pakiet .bin w ustawieniach.") + + +def update_apply(iface: str) -> dict[str, Any]: + raise RuntimeError("Aktualizacje online są wyłączone. Wgraj pakiet .bin w ustawieniach.") + + +def _https_read_state() -> dict[str, Any]: + try: + data = json.loads(HTTPS_STATE_FILE.read_text(encoding="utf-8")) + return data if isinstance(data, dict) else {} + except Exception: + return {} + + +def _https_write_state(data: dict[str, Any]) -> None: + HTTPS_STATE_FILE.parent.mkdir(parents=True, exist_ok=True) + temp = HTTPS_STATE_FILE.parent / f".{HTTPS_STATE_FILE.name}.tmp-{os.getpid()}" + temp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + os.chmod(temp, 0o600) + os.replace(temp, HTTPS_STATE_FILE) + os.chmod(HTTPS_STATE_FILE, 0o600) + + +def _https_env_settings() -> dict[str, Any]: + result: dict[str, Any] = { + "enabled": False, + "port": 443, + "access_path": "", + } + try: + for raw in HTTPS_ENV_FILE.read_text(encoding="utf-8").splitlines(): + line = raw.strip() + if not line or "=" not in line: + continue + key, value = line.split("=", 1) + value = value.strip().strip('"').strip("'") + if key == "WGTOOLS_HTTPS_ENABLED": + result["enabled"] = value == "1" + elif key == "WGTOOLS_HTTPS_PORT": + try: + result["port"] = int(value) + except Exception: + pass + elif key == "WGTOOLS_ACCESS_PATH": + result["access_path"] = value + except Exception: + pass + return result + + +def _https_enabled_from_env() -> bool: + return bool(_https_env_settings().get("enabled")) + + +def _https_normalize_port(value: Any) -> int: + try: + port = int(value or 443) + except Exception as exc: + raise ValueError("HTTPS port must be a number") from exc + if port < 1 or port > 65535: + raise ValueError("HTTPS port must be between 1 and 65535") + if port == 80: + raise ValueError("TCP port 80 is reserved for Let's Encrypt HTTP-01 validation") + return port + + +def _https_normalize_access_path(value: Any, *, required: bool = False) -> str: + raw = str(value or "").strip() + if not raw: + if required: + raise ValueError("Panel access path is required when built-in HTTPS is enabled") + return "" + raw = raw.strip("/") + if not re.fullmatch(r"[A-Za-z0-9_-]{8,96}", raw): + raise ValueError("Panel access path must contain 8-96 letters, digits, '_' or '-' characters") + return f"/{raw}/" + + +def _https_write_env( + enabled: bool, + *, + https_port: int | None = None, + access_path: str | None = None, +) -> None: + current = _https_env_settings() + port = _https_normalize_port(https_port if https_port is not None else current.get("port") or 443) + path = _https_normalize_access_path(access_path if access_path is not None else current.get("access_path") or "", required=False) + HTTPS_ENV_FILE.parent.mkdir(parents=True, exist_ok=True) + content = "\n".join([ + f"WGTOOLS_HTTPS_ENABLED={'1' if enabled else '0'}", + f"WGTOOLS_HTTPS_PORT={port}", + f"WGTOOLS_ACCESS_PATH={path}", + f"WGTOOLS_SSL_CERTFILE={HTTPS_CERT_FILE}", + f"WGTOOLS_SSL_KEYFILE={HTTPS_KEY_FILE}", + "", + ]) + temp = HTTPS_ENV_FILE.parent / f".{HTTPS_ENV_FILE.name}.tmp-{os.getpid()}" + temp.write_text(content, encoding="utf-8") + os.chmod(temp, 0o600) + os.replace(temp, HTTPS_ENV_FILE) + os.chmod(HTTPS_ENV_FILE, 0o600) + +def _https_normalize_target(target_type: str, target: str) -> tuple[str, str]: + kind = str(target_type or "").strip().lower() + value = str(target or "").strip() + if kind not in {"domain", "ip"}: + raise ValueError("Certificate type must be domain or ip") + if not value: + raise ValueError("Domain or public IP is required") + if any(part in value for part in ("://", "/", "?", "#")): + raise ValueError("Enter only a domain name or IP address, without URL or port") + if kind == "ip": + try: + addr = ipaddress.ip_address(value.strip("[]")) + except ValueError as exc: + raise ValueError("Public IP address is invalid") from exc + if not addr.is_global: + raise ValueError("Let's Encrypt IP certificates require a public IP address") + return kind, str(addr) + try: + ascii_name = value.rstrip(".").encode("idna").decode("ascii").lower() + except Exception as exc: + raise ValueError("Domain name is invalid") from exc + if len(ascii_name) > 253 or not re.fullmatch(r"(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", ascii_name): + raise ValueError("Enter a fully qualified domain name, for example wg.example.com") + return kind, ascii_name + + +def _https_validate_email(value: str) -> str: + email = str(value or "").strip() + if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email) or len(email) > 254: + raise ValueError("A valid Let's Encrypt account email is required") + return email + + +def _https_container_port_listener(port: int) -> dict[str, Any] | None: + """Detect container-published TCP ports that may not have a host LISTEN socket. + + Docker with userland-proxy disabled publishes ports using netfilter DNAT, so + ``ss -ltnp`` can report the host port as free even though inbound traffic is + already claimed by a container (a common Nginx Proxy Manager setup). + """ + wanted = int(port) + for runtime in ("docker", "podman"): + binary = shutil.which(runtime) + if not binary: + continue + rc, out, _ = run([binary, "ps", "--format", "{{.ID}}\t{{.Names}}\t{{.Ports}}"], timeout=8) + if rc != 0: + continue + for raw in out.splitlines(): + parts = raw.split("\t", 2) + if len(parts) < 3: + continue + container_id, name, ports = (part.strip() for part in parts) + # Examples: 0.0.0.0:443->443/tcp, [::]:443->443/tcp, + # 127.0.0.1:8443->443/tcp. We care about the published host port. + if not re.search(rf"(?:^|[,\s])(?:[^,\s]*:)?{wanted}->\d+/tcp(?:$|[,\s])", ports, re.I): + continue + owner = name or container_id[:12] or runtime + return { + "port": wanted, + "free": False, + "owner": owner, + "detail": f"{runtime}: {raw}"[:700], + "source": runtime, + } + return None + + +def _https_nat_port_listener(port: int) -> dict[str, Any] | None: + """Best-effort fallback for TCP DNAT/redirect rules outside container metadata.""" + wanted = int(port) + + # Native nftables ruleset. + nft = shutil.which("nft") + if nft: + rc, out, _ = run([nft, "-a", "list", "ruleset"], timeout=8) + if rc == 0: + for raw in out.splitlines(): + line = raw.strip() + if not re.search(rf"\btcp\s+dport\s+(?:\{{[^}}]*\b{wanted}\b[^}}]*\}}|{wanted})\b", line): + continue + if not re.search(r"\b(?:dnat|redirect)\b", line): + continue + return { + "port": wanted, + "free": False, + "owner": "NAT", + "detail": line[:700], + "source": "nft", + } + + # Docker/NPM installations may still expose their NAT through the legacy + # iptables compatibility layer even when no process owns a LISTEN socket. + for tool_name in ("iptables-save", "ip6tables-save"): + tool = shutil.which(tool_name) + if not tool: + continue + rc, out, _ = run([tool, "-t", "nat"], timeout=8) + if rc != 0: + continue + for raw in out.splitlines(): + line = raw.strip() + if not re.search(rf"(?:--dport|--dports)\s+(?:[^\s]*,)?{wanted}(?:,|\s|$)", line): + continue + if not re.search(r"\s-j\s+(?:DNAT|REDIRECT)\b", line, re.I): + continue + return { + "port": wanted, + "free": False, + "owner": "NAT", + "detail": line[:700], + "source": "iptables", + } + return None + + +def _https_connectable_port_listener(port: int) -> dict[str, Any] | None: + """Last-resort local reachability test for NAT-published services. + + A container/NAT service can accept traffic on a host address while neither + ``ss`` nor container metadata exposes a local listener to WGTools. Probe + loopback plus the host's own addresses; a successful TCP handshake means + the port is not safe for WGTools to claim. + """ + wanted = int(port) + targets: list[str] = ["127.0.0.1"] + ip_cmd = shutil.which("ip") or "/usr/sbin/ip" + rc, out, _ = run([ip_cmd, "-j", "addr", "show"], timeout=8) + if rc == 0: + try: + for iface in json.loads(out or "[]"): + for info in iface.get("addr_info") or []: + local = str(info.get("local") or "").strip() + family = str(info.get("family") or "") + if local and family in {"inet", "inet6"} and local not in targets: + targets.append(local) + except Exception: + pass + for host in targets: + try: + with socket.create_connection((host, wanted), timeout=0.35): + return { + "port": wanted, + "free": False, + "owner": "service", + "detail": f"TCP connection accepted on {host}:{wanted}", + "source": "connect", + } + except OSError: + continue + return None + + +def _https_listener(port: int) -> dict[str, Any]: + wanted = int(port) + rc, out, err = run(["ss", "-ltnp"], timeout=8) + if rc == 0: + lines = [] + for line in out.splitlines(): + if not line.startswith("LISTEN"): + continue + if re.search(rf":{wanted}(?:\s|$)", line): + lines.append(line.strip()) + if lines: + detail = lines[0][:700] + owner_match = re.search(r'users:\(\(\"([^\"]+)', detail) + owner = owner_match.group(1) if owner_match else "process" + return {"port": wanted, "free": False, "owner": owner, "detail": detail, "source": "socket"} + else: + # Never call a port free when the primary socket inspection itself failed. + fallback_error = err or out or "ss failed" + + container = _https_container_port_listener(wanted) + if container: + return container + nat = _https_nat_port_listener(wanted) + if nat: + return nat + connectable = _https_connectable_port_listener(wanted) + if connectable: + return connectable + if rc != 0: + return {"port": wanted, "free": False, "owner": "unknown", "detail": fallback_error, "source": "unknown"} + return {"port": wanted, "free": True, "owner": "", "detail": "", "source": "none"} + +def _https_cert_info() -> dict[str, Any]: + result: dict[str, Any] = { + "exists": HTTPS_CERT_FILE.is_file() and HTTPS_KEY_FILE.is_file(), + "certificate_path": str(HTTPS_CERT_FILE), + "private_key_path": str(HTTPS_KEY_FILE), + "expires_at": 0, + "subject": "", + "sans": [], + } + if not result["exists"]: + return result + rc, out, err = run(["openssl", "x509", "-in", str(HTTPS_CERT_FILE), "-noout", "-enddate", "-subject", "-ext", "subjectAltName"], timeout=10) + if rc != 0: + result["error"] = err or out or "Could not read certificate" + return result + for line in out.splitlines(): + line = line.strip() + if line.startswith("notAfter="): + raw = line.split("=", 1)[1].strip() + try: + dt = datetime.strptime(raw, "%b %d %H:%M:%S %Y %Z").replace(tzinfo=timezone.utc) + result["expires_at"] = int(dt.timestamp()) + except Exception: + pass + elif line.startswith("subject="): + result["subject"] = line.split("=", 1)[1].strip() + elif "DNS:" in line or "IP Address:" in line: + for part in line.split(","): + item = part.strip() + if item.startswith("DNS:"): + result["sans"].append(item[4:]) + elif item.startswith("IP Address:"): + result["sans"].append(item[len("IP Address:"):]) + return result + + +def _https_cert_contains_target(cert: dict[str, Any], kind: str, target: str) -> bool: + for raw in cert.get("sans") or []: + item = str(raw).strip() + if kind == "ip": + try: + if ipaddress.ip_address(item) == ipaddress.ip_address(target): + return True + except ValueError: + continue + elif item.rstrip(".").lower() == target.rstrip(".").lower(): + return True + return False + + +def _https_certbot_version() -> str: + if not CERTBOT_PATH.exists(): + return "" + rc, out, _ = run([str(CERTBOT_PATH), "--version"], timeout=10) + if rc != 0: + return "" + match = re.search(r"certbot\s+([^\s]+)", out, re.I) + return match.group(1) if match else out.strip() + + +def _https_timer_state() -> tuple[bool, bool]: + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + rc_enabled, out_enabled, _ = run([systemctl, "is-enabled", HTTPS_RENEW_TIMER], timeout=10) + rc_active, out_active, _ = run([systemctl, "is-active", HTTPS_RENEW_TIMER], timeout=10) + return rc_enabled == 0 and out_enabled.strip() == "enabled", rc_active == 0 and out_active.strip() == "active" + + +def https_ports(payload: dict[str, Any] | None = None) -> dict[str, Any]: + payload = payload or {} + env = _https_env_settings() + requested_port = _https_normalize_port(payload.get("https_port") or env.get("port") or 443) + p80 = _https_listener(80) + panel = _https_listener(requested_port) + panel["wgtools"] = bool( + env.get("enabled") + and requested_port == int(env.get("port") or 443) + and not panel.get("free") + and panel.get("source") == "socket" + and str(panel.get("owner") or "").lower() in {"python", "python3", "uvicorn", "wgtools-web"} + ) + return {"ok": True, "https_port": requested_port, "ports": {"80": p80, str(requested_port): panel}} + + +def https_status() -> dict[str, Any]: + state = _https_read_state() + env = _https_env_settings() + cert = _https_cert_info() + timer_enabled, timer_active = _https_timer_state() + https_port = _https_normalize_port(state.get("https_port") or env.get("port") or 443) + access_path = _https_normalize_access_path(state.get("access_path") or env.get("access_path") or "", required=False) + ports = https_ports({"https_port": https_port})["ports"] + return { + "ok": True, + "enabled": bool(env.get("enabled")), + "target_type": str(state.get("target_type") or "domain"), + "target": str(state.get("target") or ""), + "email": str(state.get("email") or ""), + "https_port": https_port, + "access_path": access_path, + "issued_at": int(state.get("issued_at") or 0), + "certbot_version": _https_certbot_version(), + "certificate": cert, + "renewal_timer_enabled": timer_enabled, + "renewal_timer_active": timer_active, + "ports": ports, + } + +def https_issue(payload: dict[str, Any]) -> dict[str, Any]: + kind, target = _https_normalize_target(str(payload.get("target_type") or "domain"), str(payload.get("target") or "")) + email = _https_validate_email(str(payload.get("email") or "")) + old_state = _https_read_state() + desired_state = { + "target_type": kind, + "target": target, + "email": email, + "https_port": _https_normalize_port(payload.get("https_port") or old_state.get("https_port") or _https_env_settings().get("port") or 443), + "access_path": _https_normalize_access_path(payload.get("access_path") or old_state.get("access_path") or _https_env_settings().get("access_path") or "", required=False), + "issued_at": int(old_state.get("issued_at") or 0), + } + # When HTTPS is still disabled, the certificate button is also the Save step: + # keep the entered settings even if Certbot later fails (for example because + # TCP 80 is not reachable yet). Never replace the live HTTPS state before a + # successful certificate change on an already enabled panel. + if not _https_enabled_from_env(): + _https_write_state(desired_state) + if not CERTBOT_PATH.exists(): + raise RuntimeError("Certbot is not installed in the WGTools environment. Reinstall or update WGTools and try again.") + p80 = _https_listener(80) + if not p80.get("free"): + raise RuntimeError(f"TCP port 80 is already in use by {p80.get('owner') or 'another process'}. Free port 80 before requesting or renewing the certificate.") + version = _https_certbot_version() + if kind == "ip": + match = re.match(r"(\d+)\.(\d+)", version) + if not match or (int(match.group(1)), int(match.group(2))) < (5, 3): + raise RuntimeError("IP certificates require Certbot 5.3 or newer") + cmd = [ + str(CERTBOT_PATH), "certonly", "--standalone", "--non-interactive", "--agree-tos", + "--email", email, "--cert-name", HTTPS_CERT_NAME, "--keep-until-expiring", + ] + old_target = str(old_state.get("target") or "") + old_kind = str(old_state.get("target_type") or "") + if HTTPS_CERT_FILE.exists() and (old_target != target or old_kind != kind): + cmd.append("--renew-with-new-domains") + if kind == "ip": + cmd += ["--preferred-profile", "shortlived", "--ip-address", target] + else: + cmd += ["-d", target] + rc, out, err = run(cmd, timeout=240) + if rc != 0: + detail = (err or out or "Certbot failed").strip() + raise RuntimeError(detail[-2500:]) + cert = _https_cert_info() + if not cert.get("exists"): + raise RuntimeError("Certbot finished without creating the WGTools certificate files") + if not _https_cert_contains_target(cert, kind, target): + raise RuntimeError("The issued certificate does not contain the requested domain/IP") + if int(cert.get("expires_at") or 0) <= int(time.time()) + 300: + raise RuntimeError("The issued certificate is already expired or too close to expiry") + state = dict(desired_state) + state["issued_at"] = int(time.time()) + _https_write_state(state) + restart_warning = "" + if _https_enabled_from_env(): + try: + _https_schedule_restart() + except Exception as exc: + restart_warning = str(exc) + return {"ok": True, "message": "Certificate is ready", "certificate": cert, "state": state, "certbot_output": out[-1200:], "restart_warning": restart_warning} + + +def _https_health_url(settings: dict[str, Any]) -> str: + enabled = bool(settings.get("enabled")) + if enabled: + port = _https_normalize_port(settings.get("port") or 443) + path = _https_normalize_access_path(settings.get("access_path") or "", required=False).rstrip("/") + return f"https://127.0.0.1:{port}{path}/healthz" + http_port = 8341 + try: + for raw in ENV_FILE.read_text(encoding="utf-8").splitlines(): + if raw.strip().startswith("WGTOOLS_PORT="): + http_port = int(raw.split("=", 1)[1].strip()) + break + except Exception: + pass + return f"http://127.0.0.1:{http_port}/healthz" + + +def _https_wait_healthy(settings: dict[str, Any], timeout_seconds: int = 22) -> bool: + url = _https_health_url(settings) + curl = shutil.which("curl") or "/usr/bin/curl" + deadline = time.time() + max(3, timeout_seconds) + while time.time() < deadline: + cmd = [curl, "-fsS", "--max-time", "2"] + if url.startswith("https://"): + cmd.insert(1, "-k") + rc, _, _ = run(cmd + [url], timeout=4) + if rc == 0: + return True + time.sleep(1) + return False + + +def https_switch_commit() -> dict[str, Any]: + old_enabled = os.environ.get("WGTOOLS_HTTPS_ROLLBACK_ENABLED", "0") == "1" + old_port = _https_normalize_port(os.environ.get("WGTOOLS_HTTPS_ROLLBACK_PORT") or 443) + old_path = _https_normalize_access_path(os.environ.get("WGTOOLS_HTTPS_ROLLBACK_PATH") or "", required=False) + old_settings = {"enabled": old_enabled, "port": old_port, "access_path": old_path} + new_settings = _https_env_settings() + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + + rc, out, err = run([systemctl, "restart", "wgtools.service"], timeout=30) + if rc == 0 and _https_wait_healthy(new_settings): + return {"ok": True, "healthy": True, "url": _https_health_url(new_settings)} + + _https_write_env(old_enabled, https_port=old_port, access_path=old_path) + run([systemctl, "restart", "wgtools.service"], timeout=30) + rollback_ok = _https_wait_healthy(old_settings, timeout_seconds=15) + raise RuntimeError( + "WGTools did not become healthy after the HTTPS switch; the previous web settings were restored" + + ("" if rollback_ok else " but the previous web settings are also not healthy") + + f": {err or out}" + ) + + +def _https_schedule_restart() -> None: + systemd_run = shutil.which("systemd-run") or "/usr/bin/systemd-run" + unit = f"wgtools-https-reload-{os.getpid()}-{int(time.time() * 1000) % 1000000}" + rc, out, err = run([systemd_run, "--quiet", "--collect", f"--unit={unit}", "--on-active=5s", "/bin/systemctl", "restart", "wgtools.service"], timeout=15) + if rc != 0: + raise RuntimeError(f"Could not schedule WGTools web restart: {err or out}") + + +def _https_schedule_switch(previous: dict[str, Any]) -> None: + systemd_run = shutil.which("systemd-run") or "/usr/bin/systemd-run" + unit = f"wgtools-https-switch-{os.getpid()}-{int(time.time() * 1000) % 1000000}" + cmd = [ + systemd_run, "--quiet", "--collect", f"--unit={unit}", "--on-active=5s", + f"--setenv=WGTOOLS_HTTPS_ROLLBACK_ENABLED={'1' if previous.get('enabled') else '0'}", + f"--setenv=WGTOOLS_HTTPS_ROLLBACK_PORT={_https_normalize_port(previous.get('port') or 443)}", + f"--setenv=WGTOOLS_HTTPS_ROLLBACK_PATH={_https_normalize_access_path(previous.get('access_path') or '', required=False)}", + str(HELPER_INSTALL_PATH), "https_switch_commit", "wg0", + ] + rc, out, err = run(cmd, timeout=15) + if rc != 0: + raise RuntimeError(f"Could not schedule the guarded HTTPS switch: {err or out}") + + +def https_enable(payload: dict[str, Any]) -> dict[str, Any]: + kind, target = _https_normalize_target(str(payload.get("target_type") or "domain"), str(payload.get("target") or "")) + email = _https_validate_email(str(payload.get("email") or "")) + https_port = _https_normalize_port(payload.get("https_port") or 443) + access_path = _https_normalize_access_path(payload.get("access_path") or "", required=True) + cert = _https_cert_info() + if not cert.get("exists"): + raise RuntimeError("Obtain a Let's Encrypt certificate before enabling HTTPS") + if not _https_cert_contains_target(cert, kind, target): + raise RuntimeError("The existing certificate does not contain the requested domain/IP") + if int(cert.get("expires_at") or 0) <= int(time.time()) + 300: + raise RuntimeError("The existing certificate is expired; renew it before enabling HTTPS") + state = _https_read_state() + if str(state.get("target") or "") != target or str(state.get("target_type") or "") != kind: + raise RuntimeError("The existing certificate belongs to a different domain/IP. Obtain a certificate for the current value first.") + + env = _https_env_settings() + old_enabled = bool(env.get("enabled")) + old_port = int(env.get("port") or 443) + if not (old_enabled and https_port == old_port): + listener = _https_listener(https_port) + if not listener.get("free"): + raise RuntimeError(f"TCP port {https_port} is already in use by {listener.get('owner') or 'another process'}. WGTools will not replace or stop it.") + + state.update({ + "target_type": kind, + "target": target, + "email": email, + "https_port": https_port, + "access_path": access_path, + }) + _https_write_state(state) + _https_write_env(True, https_port=https_port, access_path=access_path) + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + rc, out, err = run([systemctl, "enable", "--now", HTTPS_RENEW_TIMER], timeout=20) + if rc != 0: + _https_write_env(old_enabled, https_port=old_port, access_path=str(env.get("access_path") or "")) + raise RuntimeError(f"Could not enable automatic certificate renewal: {err or out}") + try: + _https_schedule_switch({"enabled": old_enabled, "port": old_port, "access_path": str(env.get("access_path") or "")}) + except Exception: + if not old_enabled: + run([systemctl, "disable", "--now", HTTPS_RENEW_TIMER], timeout=20) + _https_write_env(old_enabled, https_port=old_port, access_path=str(env.get("access_path") or "")) + raise + return { + "ok": True, + "enabled": True, + "message": f"HTTPS enabled; WGTools will restart on TCP {https_port}", + "redirect_host": target, + "redirect_port": https_port, + "access_path": access_path, + } + + +def https_disable() -> dict[str, Any]: + env = _https_env_settings() + was_enabled = bool(env.get("enabled")) + _https_write_env(False, https_port=int(env.get("port") or 443), access_path=str(env.get("access_path") or "")) + systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" + run([systemctl, "disable", "--now", HTTPS_RENEW_TIMER], timeout=20) + try: + _https_schedule_switch({"enabled": was_enabled, "port": int(env.get("port") or 443), "access_path": str(env.get("access_path") or "")}) + except Exception: + if was_enabled: + _https_write_env(True, https_port=int(env.get("port") or 443), access_path=str(env.get("access_path") or "")) + run([systemctl, "enable", "--now", HTTPS_RENEW_TIMER], timeout=20) + raise + http_port = 8341 + try: + for raw in ENV_FILE.read_text(encoding="utf-8").splitlines(): + if raw.strip().startswith("WGTOOLS_PORT="): + http_port = int(raw.split("=", 1)[1].strip()) + break + except Exception: + pass + return {"ok": True, "enabled": False, "message": "Built-in HTTPS disabled; WGTools will return to HTTP", "http_port": http_port} + +def locked_call(func): + LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) + with LOCK_PATH.open("w") as lock: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + raise RuntimeError("Another WGTools operation is already running") from exc + return func() + + +def update_locked_call(func): + UPDATE_LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) + with UPDATE_LOCK_PATH.open("w") as lock: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + raise RuntimeError("Another WGTools update is already running") from exc + return func() + + +def main() -> int: + if os.geteuid() != 0: + print(json.dumps({"ok": False, "error": "helper must run as root"})) + return 1 + if len(sys.argv) != 3: + print(json.dumps({"ok": False, "error": "usage: wgtools-helper "})) + return 2 + + action, iface = sys.argv[1], sys.argv[2] + if action not in ALLOWED_ACTIONS or not ALLOWED_IFACE_RE.fullmatch(iface): + print(json.dumps({"ok": False, "error": "invalid arguments"})) + return 2 + + try: + if action == "snapshot": + payload = read_json_stdin() + result = build_snapshot(iface, str(payload.get("view") or "full")) + elif action == "interfaces_list": + result = interfaces_list(iface) + elif action == "interface_meta_set": + payload = read_json_stdin() + result = locked_call(lambda: interface_meta_set(iface, payload)) + elif action == "interface_delete": + result = locked_call(lambda: interface_delete(iface)) + elif action == "metrics_sample": + result = metrics_sample(iface) + elif action == "metrics_history": + result = metrics_history() + elif action == "traffic_reset": + result = locked_call(lambda: reset_wireguard_traffic(iface)) + elif action == "diagnostics": + result = build_diagnostics(iface) + elif action == "network_trace": + payload = read_json_stdin() + result = network_trace(payload) + elif action == "wireguard_start": + result = locked_call(lambda: wireguard_service_action(iface, "start")) + elif action == "wireguard_stop": + result = locked_call(lambda: wireguard_service_action(iface, "stop")) + elif action == "wireguard_restart": + result = locked_call(lambda: wireguard_service_action(iface, "restart")) + elif action == "install_wireguard": + result = locked_call(install_wireguard) + elif action == "create_server": + payload = read_json_stdin() + result = locked_call(lambda: create_server(iface, payload)) + elif action == "create_client": + payload = read_json_stdin() + result = locked_call(lambda: create_client(iface, payload)) + elif action == "update_client": + payload = read_json_stdin() + result = locked_call(lambda: update_client(iface, payload)) + elif action == "delete_client": + payload = read_json_stdin() + result = locked_call(lambda: delete_client(iface, payload)) + elif action == "rotate_client_credentials": + payload = read_json_stdin() + result = locked_call(lambda: rotate_client_credentials(iface, payload)) + elif action == "expire_clients": + result = locked_call(expire_clients) + elif action == "client_config": + payload = read_json_stdin() + result = build_client_config(iface, str(payload.get("public_key", "")).strip()) + elif action == "group_create": + payload = read_json_stdin() + result = locked_call(lambda: group_create(iface, payload)) + elif action == "group_update": + payload = read_json_stdin() + result = locked_call(lambda: group_update(iface, payload)) + elif action == "group_delete": + payload = read_json_stdin() + result = locked_call(lambda: group_delete(iface, payload)) + elif action == "server_settings_apply": + payload = read_json_stdin() + result = locked_call(lambda: server_settings_apply(iface, payload)) + elif action == "extended_snat_get": + result = extended_snat_get(iface) + elif action == "extended_snat_apply": + payload = read_json_stdin() + result = locked_call(lambda: extended_snat_apply(iface, payload)) + elif action == "extended_listen_get": + result = extended_listen_get(iface) + elif action == "extended_listen_apply": + payload = read_json_stdin() + result = locked_call(lambda: extended_listen_apply(iface, payload)) + elif action == "extended_ip_groups_get": + result = extended_ip_groups_get() + elif action == "extended_ip_groups_set": + payload = read_json_stdin() + result = locked_call(lambda: extended_ip_groups_set(payload)) + elif action == "extended_forward_get": + result = extended_forward_get(iface) + elif action == "extended_forward_add": + payload = read_json_stdin() + result = locked_call(lambda: extended_forward_add(iface, payload)) + elif action == "extended_forward_delete": + payload = read_json_stdin() + result = locked_call(lambda: extended_forward_delete(iface, payload)) + elif action == "update_file_schedule": + payload = read_json_stdin() + result = locked_call(lambda: update_file_schedule(iface, payload)) + elif action == "update_file_apply": + result = update_locked_call(lambda: update_file_apply(iface)) + elif action == "raw_config_get": + result = raw_config_get(iface) + elif action == "raw_config_apply": + payload = read_json_stdin() + result = locked_call(lambda: raw_config_apply(iface, payload)) + elif action == "route_create": + payload = read_json_stdin() + result = locked_call(lambda: route_create(iface, payload)) + elif action == "route_update": + payload = read_json_stdin() + result = locked_call(lambda: route_update(iface, payload)) + elif action == "route_delete": + payload = read_json_stdin() + result = locked_call(lambda: route_delete(iface, payload)) + elif action == "access_rule_create": + payload = read_json_stdin() + result = locked_call(lambda: access_rule_create(iface, payload)) + elif action == "access_rule_update": + payload = read_json_stdin() + result = locked_call(lambda: access_rule_update(iface, payload)) + elif action == "access_rule_delete": + payload = read_json_stdin() + result = locked_call(lambda: access_rule_delete(iface, payload)) + elif action == "migration_backup_create": + result = locked_call(lambda: migration_backup_create(iface)) + elif action == "migration_restore": + payload = read_json_stdin() + result = locked_call(lambda: migration_restore(iface, payload)) + elif action == "https_status": + result = https_status() + elif action == "https_ports": + payload = read_json_stdin() + result = https_ports(payload) + elif action == "https_issue": + payload = read_json_stdin() + result = locked_call(lambda: https_issue(payload)) + elif action == "https_enable": + payload = read_json_stdin() + result = locked_call(lambda: https_enable(payload)) + elif action == "https_disable": + result = locked_call(https_disable) + elif action == "https_switch_commit": + result = https_switch_commit() + elif action == "update_check": + result = update_check() + elif action == "update_notice": + result = update_notice() + elif action == "update_status": + result = update_status() + elif action == "update_schedule": + payload = read_json_stdin() + result = update_schedule(iface, payload) + elif action == "update_apply": + result = update_locked_call(lambda: update_apply(iface)) + else: + raise RuntimeError("Unsupported action") + print(json.dumps(result, ensure_ascii=False)) + return 0 + except Exception as exc: + print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False)) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/wgtools-web b/scripts/wgtools-web new file mode 100644 index 0000000..1a6c091 --- /dev/null +++ b/scripts/wgtools-web @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -euo pipefail + +APP_DIR=/opt/wgtools +UVICORN="$APP_DIR/.venv/bin/uvicorn" +HTTP_PORT="${WGTOOLS_PORT:-8341}" +HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}" +HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}" +CERT_FILE="${WGTOOLS_SSL_CERTFILE:-/etc/letsencrypt/live/wgtools/fullchain.pem}" +KEY_FILE="${WGTOOLS_SSL_KEYFILE:-/etc/letsencrypt/live/wgtools/privkey.pem}" + +args=(app.main:application --host 0.0.0.0 --workers 1) +if [[ "$HTTPS_ENABLED" == "1" ]]; then + if [[ ! -r "$CERT_FILE" || ! -r "$KEY_FILE" ]]; then + echo "WGTools HTTPS is enabled but certificate files are not readable:" >&2 + echo " cert: $CERT_FILE" >&2 + echo " key: $KEY_FILE" >&2 + exit 1 + fi + args+=(--port "$HTTPS_PORT" --ssl-certfile "$CERT_FILE" --ssl-keyfile "$KEY_FILE") +else + args+=(--port "$HTTP_PORT") +fi + +exec "$UVICORN" "${args[@]}" diff --git a/systemd/wgtools-certbot-renew.service b/systemd/wgtools-certbot-renew.service new file mode 100644 index 0000000..bdd3de9 --- /dev/null +++ b/systemd/wgtools-certbot-renew.service @@ -0,0 +1,8 @@ +[Unit] +Description=Renew WGTools Let's Encrypt certificate +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/opt/wgtools/.venv/bin/certbot renew --cert-name wgtools --quiet --deploy-hook /usr/local/libexec/wgtools-certbot-reload diff --git a/systemd/wgtools-certbot-renew.timer b/systemd/wgtools-certbot-renew.timer new file mode 100644 index 0000000..aa78ee0 --- /dev/null +++ b/systemd/wgtools-certbot-renew.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Check WGTools Let's Encrypt certificate renewal + +[Timer] +OnCalendar=*-*-* 03,15:17:00 +RandomizedDelaySec=45m +Persistent=true +Unit=wgtools-certbot-renew.service + +[Install] +WantedBy=timers.target diff --git a/systemd/wgtools-expiry.service b/systemd/wgtools-expiry.service new file mode 100644 index 0000000..be29353 --- /dev/null +++ b/systemd/wgtools-expiry.service @@ -0,0 +1,12 @@ +[Unit] +Description=WGTools client expiration and access schedule enforcement +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +User=root +Group=root +ExecStart=/usr/local/libexec/wgtools-helper expire_clients wg0 +StandardOutput=null +StandardError=journal diff --git a/systemd/wgtools-expiry.timer b/systemd/wgtools-expiry.timer new file mode 100644 index 0000000..9975070 --- /dev/null +++ b/systemd/wgtools-expiry.timer @@ -0,0 +1,12 @@ +[Unit] +Description=WGTools client access policy timer + +[Timer] +OnBootSec=30s +OnCalendar=*-*-* *:*:00 +AccuracySec=1s +Persistent=true +Unit=wgtools-expiry.service + +[Install] +WantedBy=timers.target diff --git a/systemd/wgtools-telegram.service b/systemd/wgtools-telegram.service new file mode 100644 index 0000000..528edd0 --- /dev/null +++ b/systemd/wgtools-telegram.service @@ -0,0 +1,19 @@ +[Unit] +Description=WGTools Telegram Bot +After=network-online.target wgtools.service +Wants=network-online.target + +[Service] +Type=simple +User=root +Group=root +WorkingDirectory=/opt/wgtools +EnvironmentFile=-/etc/wgtools/wgtools.env +ExecStart=/opt/wgtools/.venv/bin/python -m app.telegram_bot +Restart=on-failure +RestartSec=5 +PrivateTmp=true +ProtectHome=true + +[Install] +WantedBy=multi-user.target diff --git a/systemd/wgtools.service b/systemd/wgtools.service new file mode 100644 index 0000000..bdf4be3 --- /dev/null +++ b/systemd/wgtools.service @@ -0,0 +1,20 @@ +[Unit] +Description=WGTools WireGuard Server Manager +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=root +Group=root +WorkingDirectory=/opt/wgtools +EnvironmentFile=-/etc/wgtools/wgtools.env +EnvironmentFile=-/etc/wgtools/https.env +ExecStart=/opt/wgtools/scripts/wgtools-web +Restart=on-failure +RestartSec=3 +PrivateTmp=true +ProtectHome=true + +[Install] +WantedBy=multi-user.target diff --git a/tests/test_access_extended.py b/tests/test_access_extended.py new file mode 100644 index 0000000..5ebb3e2 --- /dev/null +++ b/tests/test_access_extended.py @@ -0,0 +1,25 @@ +import pytest + +from app.core import auth + + +def test_accounts_start_with_safe_access_and_can_be_scoped(tmp_path, monkeypatch): + monkeypatch.setattr(auth, "DATABASE_PATH", str(tmp_path / "users.db")) + admin = auth.create_user("admin", "password123") + user = auth.create_user("tester", "password123") + assert auth.get_user_access(admin["id"])["role"] == "admin" + assert auth.get_user_access(user["id"]) == {"role": "user", "interfaces": [], "permissions": {}} + auth.set_user_access(user["id"], "user", ["wg2", "wg1", "wg1"]) + assert auth.get_user_access(user["id"])["interfaces"] == ["wg1", "wg2"] + auth.set_user_access(user['id'], 'user', ['wg1'], {'wg1':['add']}) + assert auth.get_user_access(user['id'])['permissions'] == {'wg1':['add']} + with pytest.raises(ValueError): + auth.set_user_access(user["id"], "user", ["wg1;rm"]) + with pytest.raises(ValueError): + auth.set_user_access(user["id"], "user", ["wgnode0"]) + + +def test_legacy_accounts_keep_admin_access(tmp_path, monkeypatch): + monkeypatch.setattr(auth, "DATABASE_PATH", str(tmp_path / "legacy.db")) + user = auth.create_user("legacy", "password123") + assert auth.get_user_access(user["id"]) == {"role": "admin", "interfaces": [], "permissions": {}} diff --git a/tests/test_access_http.py b/tests/test_access_http.py new file mode 100644 index 0000000..3e43d83 --- /dev/null +++ b/tests/test_access_http.py @@ -0,0 +1,56 @@ +"""Exercise the authorization guard through the HTTP stack in an isolated process.""" +import os +from pathlib import Path +import subprocess +import sys +import textwrap + + +def test_user_is_restricted_to_assigned_interface(tmp_path): + root = Path(__file__).resolve().parents[1] + env = dict(os.environ, WGTOOLS_DATABASE=str(tmp_path / "test.db"), + WGTOOLS_SESSION_KEY_FILE=str(tmp_path / "session.key")) + script = textwrap.dedent(''' + from unittest.mock import patch + from fastapi.testclient import TestClient + import app.main as m + from app.core.auth import create_user, set_user_access + from app.core.preferences import update_branding + create_user('admin', 'password123') + user = create_user('tester', 'password123') + set_user_access(user['id'], 'user', ['wg1']) + update_branding('', '#123456', '') + def helper(action, payload=None, **kwargs): + if action == 'interfaces_list': + return {'ok': True, 'interfaces': [{'name': 'wg1'}, {'name': 'wg2'}]} + if action == 'snapshot': + return {'ok': True, 'config': {'interface': {'post_up': ['secret hook']}}, 'peers': []} + return {'ok': True} + with patch.object(m, 'run_helper', side_effect=helper), patch.object(m, 'merge_wireguard_last_seen', return_value=[]), patch.object(m, 'list_vps', return_value=[]): + c = TestClient(m.app) + assert 'WGTools' not in c.get('/login').text + assert c.post('/api/auth/login', json={'username':'tester','password':'password123'}).status_code == 200 + client_page = c.get('/clients') + assert client_page.status_code == 200 + assert 'Przekierowania portów' in client_page.text + assert 'href="/server"' not in client_page.text + assert c.post('/api/interfaces/delete', json={'interface':'wg1'}).status_code == 403 + assert c.post('/api/server/config/apply', json={'content':''}).status_code == 403 + assert c.post('/api/branding', json={}).status_code == 403 + assert c.post('/api/update/upload', content=b'invalid').status_code == 403 + assert c.get('/api/extended/ip-groups').status_code == 403 + assert [x['name'] for x in c.get('/api/interfaces').json()['interfaces']] == ['wg1'] + c.cookies.set('wgtools_interface', 'wg2') + assert c.get('/api/snapshot').status_code == 403 + assert c.get('/api/extended/forwardings').status_code == 403 + assert c.post('/api/clients/create', json={'name':'bad','type':'client'}).status_code == 403 + c.cookies.set('wgtools_interface', 'wg1') + response = c.get('/api/snapshot') + assert response.status_code == 200 + assert 'post_up' not in response.json()['config']['interface'] + assert c.post('/api/clients/create', json={'name':'bad','type':'site_to_site','remote_networks':['10.1.0.0/16']}).status_code == 403 + set_user_access(user['id'], 'user', ['wg1'], {'wg1':['add']}) + assert c.post('/api/extended/forwardings', json={'public_ip':'192.0.2.1','public_port':1234,'target_ip':'10.0.0.2','target_port':1234,'protocol':'tcp'}).status_code == 403 + assert c.post('/api/clients/update', json={'name':'peer','public_key':'x'*44}).status_code == 403 + ''') + subprocess.run([sys.executable, '-c', script], cwd=root, env=env, check=True, timeout=30) diff --git a/tests/test_extended_forward.py b/tests/test_extended_forward.py new file mode 100644 index 0000000..ec1c00f --- /dev/null +++ b/tests/test_extended_forward.py @@ -0,0 +1,86 @@ +from pathlib import Path +import runpy + +import pytest + + +@pytest.fixture +def network(tmp_path, monkeypatch): + pytest.importorskip('fcntl') + module = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper')) + gl = module['extended_forward_add'].__globals__ + configs = { + 'wg1': '[Interface]\nAddress = 10.0.1.1/24\nListenPort = 51821\nPrivateKey = key\n[Peer]\nPublicKey = client1\nAllowedIPs = 10.0.1.2/32\n', + 'wg2': '[Interface]\nAddress = 10.0.2.1/24\nListenPort = 51822\nPrivateKey = key\n[Peer]\nPublicKey = client2\nAllowedIPs = 10.0.2.2/32\n', + } + monkeypatch.setitem(gl, 'EXT_IP_GROUPS_PATH', tmp_path / 'groups.json') + monkeypatch.setitem(gl, '_configured_interface_names', lambda: set(configs)) + monkeypatch.setitem(gl, '_extended_configured', lambda: set(configs)) + monkeypatch.setitem(gl, '_extended_host_ips', lambda: {'192.0.2.10': 'eth0', '192.0.2.20': 'eth0'}) + monkeypatch.setitem(gl, '_extended_listener_conflict', lambda *args: False) + monkeypatch.setitem(gl, 'read_config_text', lambda iface: configs[iface]) + def apply(iface, payload): + configs[iface] = payload['content'] + return {'ok': True} + monkeypatch.setitem(gl, 'raw_config_apply', apply) + return module, configs + + +def test_groups_share_addresses_and_enforce_conflicts(network): + m, configs = network + m['extended_ip_groups_set']({'name':'shared','addresses':['192.0.2.10'],'interfaces':['wg1','wg2']}) + m['extended_ip_groups_set']({'name':'private','addresses':['192.0.2.20'],'interfaces':['wg2']}) + forward = {'public_ip':'192.0.2.10','public_port':25565,'target_ip':'10.0.1.2','target_port':25565,'protocol':'both'} + added = m['extended_forward_add']('wg1', forward)['forward'] + assert 'DNAT --to-destination 10.0.1.2:25565' in configs['wg1'] + assert m['extended_forward_get']('wg1')['addresses'] == ['192.0.2.10'] + with pytest.raises(ValueError, match='nie jest przypisany'): + m['extended_forward_add']('wg1', {**forward, 'public_ip':'192.0.2.20'}) + with pytest.raises(ValueError, match='już używane'): + m['extended_forward_add']('wg2', {**forward, 'target_ip':'10.0.2.2', 'protocol':'tcp'}) + with pytest.raises(ValueError, match='odebrałaby'): + m['extended_ip_groups_set']({'name':'shared', 'delete':True}) + m['extended_forward_delete']('wg1', {'id':added['id']}) + assert 'WGEXT-FORWARD' not in configs['wg1'] + m['extended_ip_groups_set']({'name':'shared', 'delete':True}) + + +def test_rejects_foreign_target_and_wireguard_port(network): + m, _ = network + m['extended_ip_groups_set']({'name':'shared','addresses':['192.0.2.10'],'interfaces':['wg1']}) + forward = {'public_ip':'192.0.2.10','public_port':1234,'target_ip':'10.0.2.2','target_port':1234,'protocol':'tcp'} + with pytest.raises(ValueError, match='nie należy'): + m['extended_forward_add']('wg1', forward) + with pytest.raises(ValueError, match='używany przez WireGuard'): + m['extended_forward_add']('wg1', {**forward,'target_ip':'10.0.1.2','public_port':51822,'protocol':'udp'}) + + +def test_wireguard_dump_accepts_disabled_keepalive(network, monkeypatch): + m, _ = network + gl = m['wg_dump'].__globals__ + monkeypatch.setattr(gl['shutil'], 'which', lambda name: '/usr/bin/wg') + dump = 'private\tpublic\t51821\toff\npeer\t(none)\t(none)\t10.0.1.2/32\t0\t0\t0\toff\n' + monkeypatch.setitem(gl, 'run', lambda *args: (0, dump, '')) + assert m['wg_dump']('wg1')['peers']['peer']['persistent_keepalive_runtime'] == 0 + + +def test_server_editor_preserves_extended_firewall_hooks(network): + m, _ = network + command = 'iptables -I FORWARD -i wg1 -m comment --comment wgext-forward-wg1-123 -j ACCEPT' + assert m['_managed_hook_kind'](command, 'wg1', {}, set()) is None + + +def test_migration_backup_includes_address_groups(network, tmp_path, monkeypatch): + m, _ = network + gl = m['_build_migration_archive'].__globals__ + monkeypatch.setitem(gl, 'DATABASE_PATH', tmp_path / 'absent.db') + monkeypatch.setitem(gl, 'CLIENT_DIR', tmp_path / 'clients') + monkeypatch.setitem(gl, 'WG_DIR', tmp_path / 'wireguard') + monkeypatch.setitem(gl, 'SYSCTL_FILE', tmp_path / 'sysctl') + monkeypatch.setitem(gl, 'INTERFACES_META_PATH', tmp_path / 'interfaces.json') + monkeypatch.setitem(gl, 'GROUPS_PATH', tmp_path / 'client-groups.json') + (tmp_path / 'groups.json').write_text('{"test": {"addresses": [], "interfaces": []}}', encoding='utf8') + archive = m['_build_migration_archive']('wg1', tmp_path / 'backups') + import tarfile + with tarfile.open(archive, 'r:gz') as tar: + assert 'data/extended-ip-groups.json' in tar.getnames() diff --git a/tests/test_extended_listen.py b/tests/test_extended_listen.py new file mode 100644 index 0000000..51cbe7d --- /dev/null +++ b/tests/test_extended_listen.py @@ -0,0 +1,31 @@ +from pathlib import Path +import runpy + +import pytest + + +@pytest.fixture +def helper(monkeypatch): + pytest.importorskip('fcntl') + module = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper')) + gl = module['extended_listen_apply'].__globals__ + monkeypatch.setitem(gl, 'read_config_text', lambda iface: '[Interface]\nAddress = 10.0.0.1/24\nListenPort = 51821\nPrivateKey = key\n[Peer]\nPublicKey = peer\n') + monkeypatch.setitem(gl, 'parse_config', lambda text, iface: {'interface': {'listen_port': 51821}}) + monkeypatch.setitem(gl, 'run', lambda cmd: (0, '[{"addr_info":[{"family":"inet","local":"192.0.2.10"}]}]', '')) + monkeypatch.setitem(gl, 'raw_config_apply', lambda iface, payload: {'ok': True, 'content': payload['content']}) + return module + + +def test_listen_rules_cover_ipv4_and_ipv6(helper): + result = helper['extended_listen_apply']('wg1', {'address': '192.0.2.10', 'interface': 'eth0'}) + config = result['content'] + assert '--dport 51821 -i eth0 -d 192.0.2.10' in config + assert 'ip6tables -w -I INPUT 1' in config + assert 'wgext-listen-wg1-drop -j DROP' in config + assert config.index('PostDown') < config.index('[Peer]') + + +def test_listen_rejects_unassigned_or_invalid_inputs(helper): + for address, interface in [('192.0.2.11', 'eth0'), ('192.0.2.10', 'eth0;id'), ('bad', '')]: + with pytest.raises(ValueError): + helper['extended_listen_apply']('wg1', {'address': address, 'interface': interface}) diff --git a/tests/test_extended_snat.py b/tests/test_extended_snat.py new file mode 100644 index 0000000..c786926 --- /dev/null +++ b/tests/test_extended_snat.py @@ -0,0 +1,30 @@ +from pathlib import Path +import runpy + +import pytest + + +@pytest.fixture +def helper(monkeypatch): + pytest.importorskip('fcntl') + mod = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper')) + gl = mod['extended_snat_apply'].__globals__ + config = '[Interface]\nAddress = 10.2.0.1/24\nPrivateKey = key\n\n[Peer]\nPublicKey = peer\n' + monkeypatch.setitem(gl, 'read_config_text', lambda iface: config) + monkeypatch.setitem(gl, 'parse_config', lambda text, iface: {'detected': {'vpn_network': '10.2.0.0/24', 'uplink_interface': 'eth0'}}) + monkeypatch.setitem(gl, 'run', lambda cmd: (0, '[{"addr_info":[{"family":"inet","local":"192.0.2.10"}]}]', '')) + monkeypatch.setitem(gl, 'raw_config_apply', lambda iface, payload: {'ok': True, 'content': payload['content']}) + return mod + + +def test_snat_uses_assigned_address_and_preserves_peers(helper): + result = helper['extended_snat_apply']('wg1', {'address': '192.0.2.10', 'uplink': 'eth0'}) + assert 'iptables -t nat -I POSTROUTING 1 -s 10.2.0.0/24 -o eth0' in result['content'] + assert '--to-source 192.0.2.10' in result['content'] + assert result['content'].index('PostDown') < result['content'].index('[Peer]') + + +def test_snat_rejects_unassigned_and_invalid_address(helper): + for address, uplink in [('192.0.2.11', 'eth0'), ('192.0.2.10', 'eth0;id'), ('bad', 'eth0')]: + with pytest.raises(ValueError): + helper['extended_snat_apply']('wg1', {'address': address, 'uplink': uplink}) diff --git a/tests/test_extended_update_disabled.py b/tests/test_extended_update_disabled.py new file mode 100644 index 0000000..14aa9fb --- /dev/null +++ b/tests/test_extended_update_disabled.py @@ -0,0 +1,15 @@ +"""The fork must not contact the upstream update service.""" +from pathlib import Path +import runpy + +import pytest + + +def test_upstream_update_is_disabled(): + pytest.importorskip('fcntl') + helper = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper')) + with pytest.raises(RuntimeError, match='Aktualizacje online są wyłączone'): + helper['update_check']() + with pytest.raises(RuntimeError, match='Aktualizacje online są wyłączone'): + helper['update_apply']('wg0') + assert helper['update_notice']()['update_available'] is False diff --git a/tests/test_gitea_release_extended.py b/tests/test_gitea_release_extended.py new file mode 100644 index 0000000..8471ecf --- /dev/null +++ b/tests/test_gitea_release_extended.py @@ -0,0 +1,40 @@ +import json +from pathlib import Path + +import pytest + +from scripts import gitea_release + + +def test_release_creates_draft_uploads_and_publishes(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + Path('VERSION').write_text('1.2.3', encoding='utf-8') + for key, value in {'GITHUB_REF_NAME':'v1.2.3', 'GITHUB_SERVER_URL':'https://git.example', 'GITHUB_REPOSITORY':'owner/project', 'GITEA_RELEASE_TOKEN':'test-token'}.items(): + monkeypatch.setenv(key, value) + calls = [] + def archive(args, **kwargs): + if args[1] == 'archive': + path = next(arg.removeprefix('--output=') for arg in args if arg.startswith('--output=')) + Path(path).write_bytes(b'test archive') + class Response: + def __enter__(self): return self + def __exit__(self, *args): pass + def read(self): return b'{"id": 42}' + def urlopen(request, timeout): + calls.append(request) + return Response() + monkeypatch.setattr(gitea_release.subprocess, 'run', archive) + monkeypatch.setattr(gitea_release, 'urlopen', urlopen) + gitea_release.main() + assert [r.method for r in calls] == ['POST', 'POST', 'PATCH'] + assert json.loads(calls[0].data)['draft'] is True + assert b'test archive' in calls[1].data + assert json.loads(calls[2].data)['draft'] is False + + +def test_release_rejects_version_mismatch(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + Path('VERSION').write_text('1.0.0', encoding='utf-8') + monkeypatch.setenv('GITHUB_REF_NAME', 'v1.0.1') + with pytest.raises(ValueError, match='VERSION'): + gitea_release.main() diff --git a/tests/test_help_localization.py b/tests/test_help_localization.py new file mode 100644 index 0000000..5a4b544 --- /dev/null +++ b/tests/test_help_localization.py @@ -0,0 +1,42 @@ +"""Prevent non-Russian, non-English help falling back to English again.""" +from __future__ import annotations +import json +import unittest +from pathlib import Path +from app.core.help_content import HELP, get_help_sections + +ROOT = Path(__file__).resolve().parents[1] +LANGUAGES = ('de', 'fr', 'it', 'es', 'pl') + +class HelpTranslationTests(unittest.TestCase): + def test_all_five_help_dictionaries_loaded(self): + original = get_help_sections('en') + for language in LANGUAGES: + with self.subTest(language=language): + file = ROOT/'app/core/help_locales'/f'{language}.json' + self.assertTrue(file.is_file()) + data = json.loads(file.read_text(encoding='utf8')) + self.assertEqual(data, get_help_sections(language)) + self.assertEqual(len(data),len(original)) + self.assertEqual([s['id'] for s in data], [s['id'] for s in original]) + self.assertNotEqual(data[0]['title'], original[0]['title']) + self.assertNotEqual(data[0]['topics'][0]['paragraphs'][0],original[0]['topics'][0]['paragraphs'][0]) + for section, ref_section in zip(data, original): + self.assertTrue(section['title'].strip()) + self.assertTrue(section['intro'].strip()) + self.assertEqual(len(section['topics']),len(ref_section['topics'])) + for topic, reference in zip(section['topics'],ref_section['topics']): + self.assertTrue(topic['title'].strip()) + self.assertTrue(all(x.strip() for x in topic['paragraphs'])) + self.assertEqual(bool(topic['example_lines']),bool(reference['example_lines'])) + self.assertEqual(bool(topic['warning']),bool(reference['warning'])) + # Common technical terms such as Diagnostics can legitimately match English. + self.assertNotEqual(topic['paragraphs'][0],reference['paragraphs'][0],"untranslated help paragraph") + self.assertTrue(all(x.strip() for x in topic['bullets'])) + def test_unknown_language_defaults_to_english(self): + self.assertEqual(get_help_sections('non-existent-language'), HELP['en']) + def test_version(self): + self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.0') + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_public_bootstrap.py b/tests/test_public_bootstrap.py new file mode 100644 index 0000000..1bddbf5 --- /dev/null +++ b/tests/test_public_bootstrap.py @@ -0,0 +1,21 @@ +"""The bootstrap runs the local installer and never downloads upstream code.""" +from pathlib import Path +import shutil +import subprocess + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +def test_bootstrap_uses_local_source(tmp_path): + bash = shutil.which('bash') + if not bash: + pytest.skip('bash is required') + source = tmp_path / 'source' + (source / 'scripts').mkdir(parents=True) + shutil.copyfile(ROOT / 'install.sh', source / 'install.sh') + (source / 'scripts' / 'install.sh').write_text('#!/bin/sh\nprintf "local installer: %s" "$1"\n', encoding='utf-8') + result = subprocess.run([bash, str(source / 'install.sh'), 'test'], capture_output=True, text=True, check=True) + assert result.stdout == 'local installer: test' + assert 'KindMich/WGTools' not in (ROOT / 'install.sh').read_text(encoding='utf-8') diff --git a/tests/test_release_0404.py b/tests/test_release_0404.py new file mode 100644 index 0000000..d51dea2 --- /dev/null +++ b/tests/test_release_0404.py @@ -0,0 +1,86 @@ +"""Regression tests for the v0.40.4 native candidate, no privileged side effects.""" +from __future__ import annotations + +import json +import re +import runpy +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +LANGS = ('en', 'ru', 'de', 'fr', 'it', 'es', 'pl') + + +class CandidateTests(unittest.TestCase): + def test_versions_and_locale_fallback_contract(self): + self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.0') + en = json.loads((ROOT/'app/locales/en.json').read_text()) + self.assertGreaterEqual(len(en), 1098) + for lang in LANGS: + content=(ROOT/'app/locales'/f'{lang}.json').read_bytes() + self.assertEqual(content,(ROOT/'app/static'/f'{lang}.json').read_bytes()) + self.assertEqual(content,(ROOT/'app/static/locales'/f'{lang}.json').read_bytes()) + data=json.loads(content) + self.assertEqual(set(data),set(en),lang) + # Every supported language resolves every possible UI key through English. + merged={**en,**data} + self.assertEqual(set(merged),set(en)) + for key,value in data.items(): + self.assertEqual(set(re.findall(r'\{\w+\}',value)), + set(re.findall(r'\{\w+\}',en[key])),(lang,key)) + + def test_delete_returns_exact_client_name_for_audit(self): + helper=runpy.run_path(str(ROOT/'scripts/wgtools-helper')) + fun=helper['delete_client'] + g=fun.__globals__ + g.update({ + 'read_config_text':lambda iface:'[Interface]\n', + 'parse_config':lambda text,iface:{'peers':[{'public_key':'PUBLICKEY','name':'Work laptop','remote_networks':[]}], 'detected':{}}, + 'replace_peer_block':lambda text,key,value:text, + 'update_route_hooks':lambda text,*args:text, + 'load_client_meta':lambda key:None, + 'delete_client_meta':lambda key:None, + 'sync_managed_client_policies':lambda text,iface:text, + 'write_config_transaction':lambda *args:'/tmp/test-backup', + }) + response=fun('wg0',{'public_key':'PUBLICKEY'}) + self.assertEqual(response['name'],'Work laptop') + self.assertTrue(response['ok']) + + def test_short_cache_and_no_runtime_tests(self): + helper=runpy.run_path(str(ROOT/'scripts/wgtools-helper')) + self.assertEqual(helper['UPDATE_NOTICE_MAX_AGE'],15*60) + installer=(ROOT/'scripts/install.sh').read_text() + self.assertIn('"$APP_DIR/tests"',installer) + self.assertIn('Preserving existing /etc/wgtools/wgtools.env',installer) + js=(ROOT/'app/static/js/app.js').read_text() + self.assertIn('topbar-theme-toggle',js) + self.assertIn('renderPeerTable(body,visiblePeers.map',js) + self.assertIn('topbar-update-notice',js) + + def test_online_breathes_without_reset_and_icon_is_svg(self): + css=(ROOT/'app/static/css/app.css').read_text() + js=(ROOT/'app/static/js/app.js').read_text() + template=(ROOT/'app/templates/base.html').read_text() + self.assertIn('.status-dot.peer-status-dot.offline{\n animation:none!important;',css) + self.assertNotIn('animation:wgtools-peer-breathe',css) + self.assertIn('animation:wgtools-peer-online-breathe 2.4s ease-in-out infinite',css) + self.assertIn('inset:-2px;',css) + self.assertIn('50%{transform:scale(1.10);opacity:.88}',css) + self.assertNotIn('0 0 9px rgba(105,193,125,.42)',css) + self.assertIn('prefers-reduced-motion:reduce',css) + self.assertIn('renderPeerTable(body,rowsHtml,5)',js) + self.assertIn('theme-icon-sun',template) + self.assertIn('theme-icon-moon',template) + self.assertNotIn('id="topbar-theme-icon"',template) + self.assertIn('old.innerHTML!==next.innerHTML',js) + self.assertIn('a.className===b.className&&a.textContent===b.textContent',js) + self.assertNotIn('pulse-phase',js) + self.assertNotIn('wgtools-peer-online-ripple',css) + self.assertIn('animation:none!important',css) + + +if __name__=='__main__': + unittest.main() diff --git a/tests/test_release_0405.py b/tests/test_release_0405.py new file mode 100644 index 0000000..a183687 --- /dev/null +++ b/tests/test_release_0405.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from app import telegram_bot +from app.core import audit + + +class Release405Tests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self._db = audit.DATABASE_PATH + audit.DATABASE_PATH = str(Path(self.tmp.name) / "audit.db") + audit.init_audit_database() + telegram_bot.PENDING.clear() + + def tearDown(self): + audit.DATABASE_PATH = self._db + telegram_bot.PENDING.clear() + self.tmp.cleanup() + + def test_audit_cursors_and_actor_across_admins(self): + for i in range(45): + audit.write_audit("admin" if i % 2 else "Telegram · @ops · ID 123", "client.created", object=f"wg0 · peer-{i}", result="created") + recent = audit.list_audit_page(limit=20) + self.assertEqual(len(recent["items"]), 20) + self.assertEqual(recent["items"][0]["object"], "wg0 · peer-44") + self.assertTrue(recent["has_older"]) + self.assertFalse(recent["has_newer"]) + older = audit.list_audit_page(before_id=recent["items"][-1]["id"]) + self.assertEqual(len(older["items"]), 20) + self.assertTrue(older["has_newer"]) + oldest = audit.list_audit_page(before_id=older["items"][-1]["id"]) + self.assertEqual(len(oldest["items"]), 5) + self.assertFalse(oldest["has_older"]) + newer = audit.list_audit_page(after_id=oldest["items"][0]["id"]) + self.assertEqual([x["id"] for x in newer["items"]], [x["id"] for x in older["items"]]) + self.assertNotIn("details", older["items"][0]) + text, keyboard = telegram_bot.audit_screen("ru", recent) + self.assertIn("аудита", text) + self.assertIn("peer-44", text) + self.assertTrue(any(btn.get("callback_data", "").startswith("audit:before") for row in keyboard["inline_keyboard"] for btn in row)) + + def test_bot_appends_screens_and_confirmation_requires_fresh_prompt(self): + messages = [] + def fake_send(token, chat_id, text, markup=None): + messages.append(text) + return {"message_id": 100 + len(messages)} + telegram_bot.PENDING[42] = {"step": "confirm_stop", "message_id": 17, "chat_id": 42} + with patch.object(telegram_bot, "send_message", fake_send), patch.object(telegram_bot, "edit_message") as edited: + telegram_bot.edit_or_send("token", 42, 17, "new screen", telegram_bot.back_keyboard("en")) + self.assertEqual(telegram_bot.PENDING[42]["message_id"], 101) + self.assertEqual(messages, ["new screen"]) + edited.assert_not_called() + + def test_stale_telegram_confirmation_cannot_restart_interface(self): + user = {"id": 42, "language_code": "en"} + def cb(data, mid): + return {"callback_query": {"id": "cb", "data": data, "from": user, + "message": {"message_id": mid, "chat": {"id": 42, "type": "private"}}}} + actions = [] + issued = [] + def fake_send(token, chat, text, markup=None): + issued.append((text, markup)) + return {"message_id": 300 + len(issued)} + with patch.object(telegram_bot, "send_message", fake_send), \ + patch.object(telegram_bot, "run_helper", side_effect=lambda action, *args, **kwargs: actions.append(action) or {"ok":True}), \ + patch.object(telegram_bot, "answer_callback"), \ + patch.object(telegram_bot, "clear_inline_keyboard"): + settings={"language":"en", "allowed_user_ids":[42]} + telegram_bot.handle_update(cb("stop", 9), settings, "token") + self.assertEqual(len(issued), 1) + confirmation_id=301 + telegram_bot.handle_update(cb("stop_yes", 9), settings, "token") + self.assertNotIn("wireguard_stop", actions) + telegram_bot.handle_update(cb("stop_yes", confirmation_id), settings, "token") + # The current confirmation works once; an earlier button cannot act. + self.assertEqual(actions.count("wireguard_stop"), 1) + telegram_bot.handle_update(cb("stop_yes", confirmation_id), settings, "token") + self.assertEqual(actions.count("wireguard_stop"), 1) + + def test_audit_permission_gate(self): + event = {"callback_query": {"id": "x", "data": "audit:latest", "from": {"id": 33, "language_code": "en"}, "message": {"message_id": 2, "chat": {"id": 33, "type": "private"}}}} + sent = [] + with patch.object(telegram_bot, "send_message", lambda *a, **kw: sent.append(a[2])), patch.object(telegram_bot,"answer_callback"): + telegram_bot.handle_update(event, {"language":"en", "allowed_user_ids":[]}, "token") + self.assertEqual(len(sent), 1) + self.assertIn("Access denied", sent[0]) + + def test_theme_and_audit_global_modal(self): + root = Path(__file__).resolve().parents[1] + base = (root / "app/templates/base.html").read_text() + settings = (root / "app/templates/settings.html").read_text() + js = (root / "app/static/js/app.js").read_text() + self.assertIn('id="topbar-audit-button"',base) + self.assertIn('id="audit-modal"',base) + self.assertNotIn('id="audit-modal"',settings) + self.assertNotIn('id="sidebar-update-notice"',base) + self.assertIn('id="sidebar-collapse-button"',base) + self.assertIn("button.dataset.tooltip=label;button.removeAttribute('title')",js) + self.assertNotIn("if(page!=='settings'||!body)return",js) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_telegram_audit.py b/tests/test_telegram_audit.py new file mode 100644 index 0000000..b963dbb --- /dev/null +++ b/tests/test_telegram_audit.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from app.core import audit +from app import telegram_bot + + +USER = {"id": 424242, "username": "audit_tester", "language_code": "en"} +CHAT_ID = 1001 +PUBLIC_KEY = "test-public-key" + + +def callback(data: str, user: dict | None = None, message_id: int = 10) -> dict: + return { + "callback_query": { + "id": f"cb-{message_id}", + "data": data, + "from": dict(user or USER), + "message": { + "message_id": message_id, + "chat": {"id": CHAT_ID, "type": "private"}, + }, + } + } + + +def message(text: str, user: dict | None = None) -> dict: + return { + "message": { + "text": text, + "from": dict(user or USER), + "chat": {"id": CHAT_ID, "type": "private"}, + } + } + + +class TelegramAuditTests(unittest.TestCase): + def setUp(self) -> None: + self.tmp = tempfile.TemporaryDirectory() + audit.DATABASE_PATH = str(Path(self.tmp.name) / "wgtools-test.db") + audit.init_audit_database() + telegram_bot.PENDING.clear() + telegram_bot.SELECTED_INTERFACES.clear() + self.peers: list[dict] = [] + self.settings = { + "allowed_user_ids": [USER["id"]], + "language": "en", + "default_endpoint": "vpn.example.com", + "default_dns": ["1.1.1.1"], + } + + def tearDown(self) -> None: + telegram_bot.PENDING.clear() + telegram_bot.SELECTED_INTERFACES.clear() + self.tmp.cleanup() + + def fake_helper(self, action: str, payload: dict | None = None, *, interface: str | None = None): + iface = interface or "wg0" + if action == "snapshot": + return { + "ok": True, + "interface": iface, + "listen_port": 51820, + "config": {"interface": {"listen_port": 51820}}, + "client_groups": [], + "peers": [dict(peer) for peer in self.peers], + } + if action == "create_client": + data = payload or {} + peer = { + "name": str(data.get("name") or "Peer"), + "public_key": PUBLIC_KEY, + "vpn_address": "10.0.0.2/32", + "managed": True, + } + self.peers.append(peer) + return {"ok": True, **peer} + if action == "client_config": + return {"ok": True, "filename": "audit-test.conf", "config": "[Interface]\nPrivateKey = SHOULD_NOT_BE_AUDITED\n"} + if action == "delete_client": + key = str((payload or {}).get("public_key") or "") + self.peers[:] = [peer for peer in self.peers if str(peer.get("public_key") or "") != key] + return {"ok": True, "name": "telegram-client"} + if action in {"wireguard_start", "wireguard_stop", "wireguard_restart"}: + return {"ok": True} + raise AssertionError(f"Unexpected helper action: {action}") + + def bot_patches(self): + return patch.multiple( + telegram_bot, + run_helper=self.fake_helper, + send_message=lambda *args, **kwargs: {"message_id": 99}, + edit_message=lambda *args, **kwargs: None, + answer_callback=lambda *args, **kwargs: None, + clear_inline_keyboard=lambda *args, **kwargs: None, + send_client_files=lambda *args, **kwargs: None, + get_preferences=lambda: {"online_threshold_seconds": 180}, + ) + + def test_create_and_delete_client_are_audited_with_telegram_identity(self) -> None: + with self.bot_patches(): + telegram_bot.handle_update(callback("create", message_id=1), self.settings, "token") + telegram_bot.handle_update(message("telegram-client"), self.settings, "token") + + telegram_bot.handle_update(callback("delete", message_id=2), self.settings, "token") + telegram_bot.handle_update(callback(f"delpick:{PUBLIC_KEY}", message_id=3), self.settings, "token") + telegram_bot.handle_update(callback(f"delyes:{PUBLIC_KEY}", message_id=99), self.settings, "token") + + # Read-only navigation must not create audit noise. + telegram_bot.handle_update(callback("status", message_id=5), self.settings, "token") + telegram_bot.handle_update(callback("clients", message_id=6), self.settings, "token") + + items = audit.list_audit(50) + telegram_items = [item for item in items if item["username"].startswith("Telegram")] + self.assertEqual([item["action"] for item in reversed(telegram_items)], ["client.created", "client.deleted"]) + for item in telegram_items: + self.assertEqual(item["username"], "Telegram · @audit_tester · ID 424242") + details = json.loads(item["details"]) + self.assertEqual(details["source"], "telegram") + self.assertEqual(details["telegram_user_id"], USER["id"]) + self.assertEqual(details["telegram_username"], USER["username"]) + self.assertEqual(details["interface"], "wg0") + self.assertNotIn("PrivateKey", item["details"]) + self.assertNotIn("SHOULD_NOT_BE_AUDITED", item["details"]) + + def test_wireguard_service_controls_are_audited(self) -> None: + with self.bot_patches(): + telegram_bot.handle_update(callback("start", message_id=20), self.settings, "token") + telegram_bot.handle_update(callback("stop", message_id=21), self.settings, "token") + telegram_bot.handle_update(callback("stop_yes", message_id=99), self.settings, "token") + telegram_bot.handle_update(callback("restart", message_id=23), self.settings, "token") + telegram_bot.handle_update(callback("restart_yes", message_id=99), self.settings, "token") + + items = list(reversed(audit.list_audit(20))) + self.assertEqual( + [item["action"] for item in items], + ["wireguard.started", "wireguard.stopped", "wireguard.restarted"], + ) + self.assertTrue(all(item["username"] == "Telegram · @audit_tester · ID 424242" for item in items)) + + def test_denied_state_change_is_audited_but_read_only_denial_is_not(self) -> None: + denied_settings = {**self.settings, "allowed_user_ids": []} + with self.bot_patches(): + telegram_bot.handle_update(callback("status", message_id=10), denied_settings, "token") + telegram_bot.handle_update(callback("start", message_id=11), denied_settings, "token") + + items = audit.list_audit(20) + self.assertEqual(len(items), 1) + self.assertEqual(items[0]["action"], "telegram.action_denied") + self.assertEqual(items[0]["result"], "denied") + self.assertIn("WireGuard start", items[0]["object"]) + self.assertIn("ID 424242", items[0]["username"]) + + def test_failure_text_is_redacted_before_storage(self) -> None: + secret_key = "A" * 43 + "=" + telegram_bot.telegram_audit_failure( + USER, + "Create client", + RuntimeError(f"PrivateKey={secret_key} bot token 123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"), + interface="wg0", + object="safe-client", + ) + item = audit.list_audit(1)[0] + self.assertEqual(item["action"], "telegram.action_failed") + self.assertNotIn(secret_key, item["result"]) + self.assertNotIn("123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef", item["result"]) + self.assertIn("[redacted]", item["result"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_telegram_audit_ui.py b/tests/test_telegram_audit_ui.py new file mode 100644 index 0000000..b989726 --- /dev/null +++ b/tests/test_telegram_audit_ui.py @@ -0,0 +1,73 @@ +"""Regression checks for Telegram audit navigation and HTML presentation (v0.40.5).""" +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from app import telegram_bot as bot +from app.core import audit + + +class AuditPresentationTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.prev_db = audit.DATABASE_PATH + audit.DATABASE_PATH = str(Path(self.tmp.name) / "audit.db") + audit.init_audit_database() + + def tearDown(self): + audit.DATABASE_PATH = self.prev_db + self.tmp.cleanup() + + def test_menu_label_and_clean_arrows(self): + menu = bot.main_keyboard("ru", 42)["inline_keyboard"] + audit_button = next(btn for row in menu for btn in row if btn["callback_data"] == "audit:latest") + self.assertEqual(audit_button["text"], "🧾 Аудит") + for i in range(45): + audit.write_audit("admin", "client.created", object=f"wg0 · test-{i}", result="created") + newest = audit.list_audit_page(limit=20) + newest_text, newest_kb = bot.audit_screen("ru", newest) + self.assertIn("", newest_text) + self.assertIn("", newest_text) + self.assertIn("test-44", newest_text) + self.assertEqual(len(newest["items"]), 20) + self.assertEqual([b["text"] for row in newest_kb["inline_keyboard"] for b in row], ["➡️", "⬅️ Меню"]) + self.assertTrue(all(b["callback_data"] != "audit:latest" for row in newest_kb["inline_keyboard"] for b in row)) + old = audit.list_audit_page(before_id=newest["items"][-1]["id"]) + old_txt, old_kb = bot.audit_screen("ru", old) + self.assertEqual([b["text"] for row in old_kb["inline_keyboard"] for b in row], ["⬅️", "➡️", "⬅️ Меню"]) + self.assertEqual(old_kb["inline_keyboard"][0][0]["callback_data"], f"audit:after:{old['items'][0]['id']}") + self.assertEqual(old_kb["inline_keyboard"][0][1]["callback_data"], f"audit:before:{old['items'][-1]['id']}") + self.assertLess(len(old_txt), 4096) + + def test_audit_html_escapes_untrusted_text(self): + audit.write_audit('', "client.deleted", object="wg0 · a&test", result="") + rendered, keyboard = bot.audit_screen("ru", audit.list_audit_page()) + self.assertIn("<admin & "root">", rendered) + self.assertIn("a&<b>test</b>", rendered) + self.assertIn("<bad>", rendered) + self.assertNotIn("", rendered) + self.assertNotIn("test", rendered) + self.assertIn("🗑️", rendered) + + def test_long_audit_still_keeps_20_entries_within_telegram_limit(self): + for i in range(20): + audit.write_audit("&" * 119, "client.updated", object="&" * 230, result="&" * 230) + text, _ = bot.audit_screen("ru", audit.list_audit_page()) + self.assertLess(len(text), 4096) + self.assertEqual(text.count(""), 20) + self.assertEqual(text.count("✏️"), 20) + + def test_audit_messages_use_html_but_normal_messages_remain_plain(self): + payloads = [] + with patch.object(bot, "telegram_api_call", side_effect=lambda token, action, payload, **kw: payloads.append((action, payload)) or {"message_id":99}): + bot.send_message("t", 42, "Plain message") + bot.send_message("t", 42, "Formatted", parse_mode="HTML") + self.assertNotIn("parse_mode", payloads[0][1]) + self.assertEqual(payloads[1][1]["parse_mode"], "HTML") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_update_upload_extended.py b/tests/test_update_upload_extended.py new file mode 100644 index 0000000..a757214 --- /dev/null +++ b/tests/test_update_upload_extended.py @@ -0,0 +1,47 @@ +import io +from pathlib import Path +import runpy +import tarfile + +import pytest + + +@pytest.fixture +def helper(): + pytest.importorskip('fcntl') + return runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper')) + + +def archive(path, entries): + with tarfile.open(path, 'w:gz') as tar: + for name, content in entries: + item = tarfile.TarInfo(name) + if content is None: + item.type = tarfile.SYMTYPE + item.linkname = '/etc/passwd' + tar.addfile(item) + else: + item.size = len(content) + tar.addfile(item, io.BytesIO(content)) + + +def test_uploaded_package_rejects_paths_and_links(helper, tmp_path): + for name, content in [('../escape', b'bad'), ('link', None), ('/etc/passwd', b'bad')]: + package = tmp_path / 'unsafe.bin' + archive(package, [(name, content)]) + with pytest.raises(ValueError): + helper['_extract_uploaded_update'](package, tmp_path / 'dest') + assert not (tmp_path / 'escape').exists() + + +def test_uploaded_package_requires_newer_version(helper, tmp_path, monkeypatch): + gl = helper['_uploaded_update_validate'].__globals__ + monkeypatch.setitem(gl, '_validate_update_source', lambda *args: None) + monkeypatch.setitem(gl, '_current_wgtools_version', lambda: '1.2.3') + package = tmp_path / 'update.bin' + archive(package, [('VERSION', b'1.2.4\n')]) + _, version = helper['_uploaded_update_validate'](package, tmp_path / 'good') + assert version == '1.2.4' + archive(package, [('VERSION', b'1.2.3\n')]) + with pytest.raises(ValueError, match='nowsza'): + helper['_uploaded_update_validate'](package, tmp_path / 'old')