1.0.0
Wydanie WGTools-Extended / release (push) Failing after 16s

This commit is contained in:
asminme committed 2026-10-30 00:35:08 +01:00
1 parent f5bdd7e21c
commit affe28ad71
110 files changed
+52936 -14

No files matched your search

+15
View File
@@ -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
+34
View File
@@ -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
+761
View File
@@ -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 `<details>` 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.
+43
View File
@@ -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.
+17 -13
View File
@@ -1,19 +1,23 @@
MIT License MIT License
Copyright (c) 2026 Asmin Studios 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 Permission is hereby granted, free of charge, to any person obtaining a copy
associated documentation files (the "Software"), to deal in the Software without restriction, including of this software and associated documentation files (the "Software"), to deal
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell in the Software without restriction, including without limitation the rights
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
following conditions: 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 The above copyright notice and this permission notice shall be included in all
portions of the Software. copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
USE OR OTHER DEALINGS IN THE SOFTWARE. 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.
+59
View File
@@ -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.
+309 -1
View File
@@ -1,3 +1,311 @@
# WGTools-Extended # WGTools-Extended
Production-ready fork of WGTools by Asmin Studios. 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
<details>
<summary><strong>Show WGTools screenshots</strong></summary>
<br>
### 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)
</details>
> 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/<interface>.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).
+296
View File
@@ -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 можно установить прямо со страницы **Сервер**.
## Скриншоты
<details>
<summary><strong>Показать скриншоты WGTools</strong></summary>
<br>
### Первый запуск
#### Создание первого пользователя
![Первичная настройка пользователя в веб-панели 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)
</details>
> На скриншотах используются лабораторные/примерные значения. Никогда не публикуйте приватные ключи, реальные 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/<interface>.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).
+19
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
1.0.0
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+452
View File
@@ -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"(?<![A-Za-z0-9+/])[A-Za-z0-9+/]{43}=(?![A-Za-z0-9+/=])"),
re.compile(
r"(?i)(password|bot[_ -]?token|private[_ -]?key|preshared[_ -]?key|psk|control[_ -]?token|ssh[_ -]?password|key[_ -]?passphrase|reset[_ -]?code|verification[_ -]?code|mfa[_ -]?(?:secret|code)|totp[_ -]?(?:secret|code)|recovery[_ -]?codes?)"
r"(\s*[:=]\s*)([^\s,;]+)"
),
)
def _redact_text(value: Any) -> 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<?", (cutoff,))
stale = conn.execute(
"SELECT id FROM audit_log ORDER BY id DESC LIMIT 1 OFFSET ?",
(MAX_AUDIT_ROWS,),
).fetchone()
if stale:
conn.execute("DELETE FROM audit_log WHERE id<=?", (int(stale["id"]),))
def init_audit_database() -> 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
+529
View File
@@ -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")
+841
View File
@@ -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/<interface>.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"]
+663
View File
@@ -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/<interface>.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": ""
}
]
}
]
+663
View File
@@ -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/<interface>.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": ""
}
]
}
]
+663
View File
@@ -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/<interface>.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": ""
}
]
}
]
+663
View File
@@ -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/<interface>.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": ""
}
]
}
]
+662
View File
@@ -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/<interface>.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": ""
}
]
}
]
+138
View File
@@ -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
+270
View File
@@ -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)
+2193
View File
File diff suppressed because it is too large. Load diff
+240
View File
@@ -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<?", (now - 7 * 24 * 60 * 60,))
conn.execute("DELETE FROM auth_rate_limits WHERE window_started<?", (now - 24 * 60 * 60,))
def _hash_code(code: str, salt: bytes, iterations: int = RESET_PBKDF2_ITERATIONS) -> 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 "")),
}
+104
View File
@@ -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()
+14
View File
@@ -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)))
+305
View File
@@ -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),
}
+1262
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+2075
View File
File diff suppressed because it is too large. Load diff
+429
View File
@@ -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}}
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

+1101
View File
File diff suppressed because it is too large. Load diff
+2985
View File
File diff suppressed because it is too large. Load diff
+160
View File
@@ -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);
});
})();
+20
View File
@@ -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 };
})();
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1101
View File
File diff suppressed because it is too large. Load diff
+1383
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="{{ language }}" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow,noarchive,nosnippet">
<script>
(()=>{try{const saved=localStorage.getItem('wgtools.theme')||'dark';const actual=saved==='system'?(matchMedia('(prefers-color-scheme: light)').matches?'light':'dark'):saved;document.documentElement.dataset.theme=actual;}catch(_){}})();
</script>
<title>{{ branding.name or 'Panel' }}</title>
<link rel="icon" type="image/png" href="{{ branding.logo or (base_path ~ '/static/img/favicon.png?v=' ~ version ~ '&r=' ~ asset_rev) }}">
<link rel="apple-touch-icon" href="{{ branding.logo or (base_path ~ '/static/img/wgtools-logo.png?v=' ~ version ~ '&r=' ~ asset_rev) }}">
<link rel="stylesheet" href="{{ base_path }}/static/css/app.css?v={{ version }}&r={{ asset_rev }}">
<style>html[data-theme] { --accent: {{ branding.color }}; }</style>
</head>
<body class="auth-body" data-base-path="{{ base_path }}">
<header class="auth-topbar">
<div class="brand">
<img class="brand-mark brand-logo" src="{{ branding.logo or (base_path ~ '/static/img/wgtools-logo.png?v=' ~ version ~ '&r=' ~ asset_rev) }}" alt="">
<div>
<div class="brand-title">{{ branding.name }}</div>
</div>
</div>
</header>
<main class="auth-shell">
{% block auth_content %}{% endblock %}
</main>
<script src="{{ base_path }}/static/js/auth.js?v={{ version }}&r={{ asset_rev }}"></script>
</body>
</html>
+195
View File
@@ -0,0 +1,195 @@
<!doctype html>
<html lang="{{ language }}" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow,noarchive,nosnippet">
<script>
(() => {
try {
const savedTheme = localStorage.getItem('wgtools.theme') || 'dark';
const actualTheme = savedTheme === 'system'
? (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark')
: savedTheme;
document.documentElement.dataset.theme = actualTheme;
const sidebarCollapsed = localStorage.getItem('wgtools.sidebar.collapsed') === '1';
if (sidebarCollapsed) document.documentElement.classList.add('sidebar-pref-collapsed');
const savedLanguage = localStorage.getItem('wgtools.language');
const cookieMatch = document.cookie.match(/(?:^|;\s*)wgtools_language=([^;]+)/);
const cookieLanguage = cookieMatch ? decodeURIComponent(cookieMatch[1]) : '';
if (['en','ru','de','fr','it','es','pl'].includes(savedLanguage) && savedLanguage !== cookieLanguage) {
document.documentElement.style.visibility = 'hidden';
document.cookie = `wgtools_language=${encodeURIComponent(savedLanguage)}; Path=/; Max-Age=31536000; SameSite=Lax`;
location.reload();
}
} catch (_) {}
})();
</script>
<title>{{ branding.name or 'Panel' }}</title>
<link rel="icon" type="image/png" href="{{ branding.logo or (base_path ~ '/static/img/favicon.png?v=' ~ version ~ '&r=' ~ asset_rev) }}">
<link rel="apple-touch-icon" href="{{ branding.logo or (base_path ~ '/static/img/wgtools-logo.png?v=' ~ version ~ '&r=' ~ asset_rev) }}">
<link rel="stylesheet" href="{{ base_path }}/static/css/app.css?v={{ version }}&r={{ asset_rev }}">
<style>html[data-theme] { --accent: {{ branding.color }}; }</style>
</head>
<body data-base-path="{{ base_path }}" data-page="{{ page }}" data-role="{{ request.state.access.role }}" data-interface="{{ interface }}" data-refresh="{{ refresh_seconds }}" data-online-threshold="{{ online_threshold }}">
<header class="topbar">
<div class="brand">
<img class="brand-mark brand-logo" src="{{ branding.logo or (base_path ~ '/static/img/wgtools-logo.png?v=' ~ version ~ '&r=' ~ asset_rev) }}" alt="">
<div>
<div class="brand-title">{{ branding.name }}</div>
</div>
</div>
<div class="topbar-right">
<div class="interface-switcher-wrap">
<button type="button" class="top-status interface-switcher-button" id="interface-switcher-button" aria-expanded="false" aria-haspopup="menu">
<span id="header-dot" class="status-dot unknown"></span>
<span id="header-status">{{ interface }} · {{ tr('common.checking') }}</span>
<span class="interface-switcher-caret">▾</span>
</button>
<div class="interface-switcher-menu" id="interface-switcher-menu" role="menu" hidden></div>
</div>
{% if current_user %}
<a class="topbar-update-link" id="topbar-update-notice" href="{{ base_path }}/settings#about" hidden aria-label="{{ tr('settings.update_sidebar') }}" title="{{ tr('settings.update_sidebar_hint') }}">↑ <span id="topbar-update-version"></span></a>
<button type="button" class="topbar-theme-toggle" id="topbar-theme-toggle" aria-label="{{ tr('settings.theme') }}" title="{{ tr('settings.theme') }}">
<span class="topbar-theme-icon" aria-hidden="true">
<svg class="theme-icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.42 1.42M17.65 17.65l1.42 1.42M2 12h2M20 12h2M4.93 19.07l1.42-1.42M17.65 6.35l1.42-1.42"/></svg>
<svg class="theme-icon-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20.985 12.486A9 9 0 0 1 11.514 3.015 9 9 0 1 0 20.985 12.486Z"/></svg>
</span>
</button>
{% if not current_user or request.state.access.role == 'admin' %}<button type="button" class="topbar-audit-toggle" id="topbar-audit-button" aria-label="{{ tr('settings.audit_log') }}" data-tooltip="{{ tr('settings.audit_log') }}">
<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="4" width="14" height="17" rx="2"/><path d="M9 4.5V3h6v1.5M9 10h6M9 14h6M9 18h4"/></svg>
</button>{% endif %}
{% if request.state.access.role == 'admin' %}<button type="button" class="topbar-help" id="help-button" title="{{ tr('help.open') }}" aria-label="{{ tr('help.open') }}">?</button>{% endif %}
<div class="user-chip"><span class="user-chip-name">{{ current_user.username }}</span><button type="button" class="topbar-logout" id="logout-button">{{ tr('auth.sign_out') }}</button></div>
{% endif %}
</div>
</header>
<aside class="sidebar" id="sidebar">
<nav aria-label="{{ tr('nav.navigation') }}">
<a href="{{ base_path }}/" class="nav-item {% if page == 'dashboard' %}active{% endif %}" data-tooltip="{{ tr('nav.dashboard') }}">
<span class="nav-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M3 11.5 12 4l9 7.5"/><path d="M5.5 10.5V20h13v-9.5"/><path d="M9.5 20v-6h5v6"/></svg></span>
<span class="nav-label" data-i18n="nav.dashboard">{{ tr('nav.dashboard') }}</span>
</a>
{% if not current_user or request.state.access.role == 'admin' %}<a href="{{ base_path }}/server" class="nav-item {% if page == 'server' %}active{% endif %}" data-tooltip="{{ tr('nav.server') }}">
<span class="nav-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="6" rx="1.5"/><rect x="4" y="14" width="16" height="6" rx="1.5"/><path d="M8 7h.01M8 17h.01M12 7h5M12 17h5"/></svg></span>
<span class="nav-label" data-i18n="nav.server">{{ tr('nav.server') }}</span>
</a>{% endif %}
<a href="{{ base_path }}/clients" class="nav-item {% if page == 'clients' %}active{% endif %}" data-tooltip="{{ tr('nav.clients') }}">
<span class="nav-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="9" cy="8" r="3"/><path d="M3.5 19c.6-3.4 2.5-5 5.5-5s4.9 1.6 5.5 5"/><circle cx="17" cy="9" r="2.3"/><path d="M15.5 14.5c2.8-.4 4.5 1.1 5 4.5"/></svg></span>
<span class="nav-label" data-i18n="nav.clients">{{ tr('nav.clients') }}</span>
</a>
{% if not current_user or request.state.access.role == 'admin' %}<a href="{{ base_path }}/settings" class="nav-item {% if page == 'settings' %}active{% endif %}" data-tooltip="{{ tr('nav.settings') }}">
<span class="nav-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.1-1.2l2-1.5-2-3.4-2.5 1A7 7 0 0 0 14.3 5L14 2h-4l-.3 3a7 7 0 0 0-2.1 1.2l-2.5-1-2 3.4 2 1.5A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.5 2 3.4 2.5-1A7 7 0 0 0 9.7 19l.3 3h4l.3-3a7 7 0 0 0 2.1-1.2l2.5 1 2-3.4-2-1.5c.1-.4.1-.8.1-1.2Z"/></svg></span>
<span class="nav-label" data-i18n="nav.settings">{{ tr('nav.settings') }}</span>
</a>{% endif %}
</nav>
<div class="sidebar-bottom">
<div class="sidebar-footer">
<button type="button" class="sidebar-collapse-button" id="sidebar-collapse-button" aria-expanded="true" aria-label="{{ tr('settings.collapse_sidebar') }}" data-tooltip="{{ tr('settings.collapse_sidebar') }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M9 4v16M16 9l-3 3 3 3"/></svg>
<span class="sidebar-collapse-caption" data-i18n="settings.collapse_sidebar">{{ tr('settings.collapse_sidebar') }}</span>
</button>
</div>
</div>
</aside>
<main class="content">
{% block content %}{% endblock %}
</main>
{% if current_user %}
<div class="modal-backdrop" id="audit-modal" data-refresh-seconds="{{ refresh_seconds }}" hidden>
<div class="modal-card modal-wide audit-modal" role="dialog" aria-modal="true" aria-labelledby="audit-modal-title">
<div class="modal-head">
<div><h2 id="audit-modal-title">{{ tr('settings.audit_log') }}</h2><p>{{ tr('settings.audit_log_subtitle') }}</p></div>
<button class="icon-btn" type="button" data-modal-close="audit-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<div class="modal-body audit-modal-body">
<div class="audit-toolbar">
<div class="quick-search-wrap audit-search-wrap">
<input id="audit-quick-search" class="quick-search-input" type="search" autocomplete="off" placeholder="{{ tr('settings.audit_search') }}" aria-label="{{ tr('settings.audit_search') }}">
<button class="quick-search-clear" id="audit-quick-search-clear" type="button" aria-label="{{ tr('settings.audit_search_clear') }}" data-tooltip="{{ tr('settings.audit_search_clear') }}" hidden>×</button>
</div>
<span class="audit-retention-note">{{ tr('settings.audit_retention_note') }}</span>
</div>
<div class="table-wrap audit-table-wrap">
<table>
<thead><tr><th>{{ tr('settings.audit_time') }}</th><th>{{ tr('settings.audit_user') }}</th><th>{{ tr('settings.audit_action') }}</th><th>{{ tr('settings.audit_object') }}</th><th>{{ tr('settings.audit_result') }}</th></tr></thead>
<tbody id="audit-table-body"><tr><td colspan="5" class="empty">{{ tr('common.loading') }}</td></tr></tbody>
</table>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="audit-modal">{{ tr('common.close') }}</button>
<button type="button" class="btn primary" id="audit-refresh-button">{{ tr('common.refresh') }}</button>
</div>
</div>
</div>
{% endif %}
{% if current_user %}
<div class="modal-backdrop" id="help-modal" hidden>
<div class="modal-card help-modal" role="dialog" aria-modal="true" aria-labelledby="help-modal-title">
<div class="modal-head help-modal-head">
<div>
<h2 id="help-modal-title">{{ tr('help.title') }}</h2>
<p>{{ tr('help.subtitle') }}</p>
</div>
<button class="icon-btn" type="button" data-modal-close="help-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<div class="help-layout">
<nav class="help-nav" aria-label="{{ tr('help.navigation') }}">
{% for section in help_sections %}
<button type="button" class="help-nav-item {% if loop.first %}active{% endif %}" data-help-target="{{ section.id }}">{{ section.title }}</button>
{% endfor %}
</nav>
<div class="help-content">
<div class="help-example-note">{{ tr('help.example_note') }}</div>
{% for section in help_sections %}
<section class="help-section" data-help-section="{{ section.id }}" {% if not loop.first %}hidden{% endif %}>
<div class="help-section-head">
<h3>{{ section.title }}</h3>
<p>{{ section.intro }}</p>
</div>
{% for topic in section.topics %}
<article class="help-topic">
<h4>{{ topic.title }}</h4>
{% for paragraph in topic.paragraphs %}<p>{{ paragraph }}</p>{% endfor %}
{% if topic.bullets %}
<ul>{% for bullet in topic.bullets %}<li>{{ bullet }}</li>{% endfor %}</ul>
{% endif %}
{% if topic.example_lines %}
<div class="help-example">
{% if topic.example_title %}<div class="help-example-title">{{ topic.example_title }}</div>{% endif %}
<pre>{{ topic.example_lines|join('\n') }}</pre>
</div>
{% endif %}
{% if topic.warning %}<div class="help-warning">{{ topic.warning }}</div>{% endif %}
</article>
{% endfor %}
</section>
{% endfor %}
</div>
</div>
<div class="modal-actions help-actions">
<button type="button" class="btn" data-modal-close="help-modal">{{ tr('common.close') }}</button>
</div>
</div>
</div>
{% endif %}
<div id="toast" class="toast"></div>
<script>
window.WGTOOLS_I18N = {language: {{ language|tojson }}, messages: {{ messages_json|safe }}};
</script>
<script src="{{ base_path }}/static/js/i18n.js?v={{ version }}&r={{ asset_rev }}"></script>
<script src="{{ base_path }}/static/js/app.js?v={{ version }}&r={{ asset_rev }}"></script>
</body>
</html>
+506
View File
@@ -0,0 +1,506 @@
{% extends "base.html" %}
{% block content %}
<section class="page-head page-head-actions">
<div>
<h1 data-i18n="clients.title">{{ tr('clients.title') }}</h1>
<p data-i18n="clients.subtitle">{{ tr('clients.subtitle') }}</p>
</div>
<div class="page-action-row">
{% if request.state.access.role == 'admin' %}<button class="btn" id="manage-groups-button" data-i18n="groups.manage">{{ tr('groups.manage') }}</button>{% endif %}
<button class="btn primary" id="add-client-button" data-i18n="clients.add">{{ tr('clients.add') }}</button>
</div>
</section>
<section class="card">
<div class="card-head"><div><h2>Przekierowania portów</h2><p>Wybierz dostępny adres publiczny i adres klienta tej sieci.</p></div></div>
<form id="extended-forward-form" class="settings-form-pad">
<div class="setup-grid">
<label><span>Publiczny adres IPv4</span><select id="extended-forward-public" required></select></label>
<label><span>Port publiczny</span><input id="extended-forward-public-port" type="number" min="1" max="65535" required></label>
<label><span>Adres IPv4 klienta</span><input id="extended-forward-target" placeholder="10.0.2.2" maxlength="15" required></label>
<label><span>Port klienta</span><input id="extended-forward-target-port" type="number" min="1" max="65535" required></label>
<label><span>Protokół</span><select id="extended-forward-protocol"><option value="tcp">TCP</option><option value="udp">UDP</option><option value="both">TCP i UDP</option></select></label>
</div>
<button class="btn primary" type="submit">Dodaj przekierowanie</button>
<div id="extended-forward-status" class="operation-status" hidden></div>
</form>
<div id="extended-forward-list" class="settings-form-pad"></div>
</section>
<section class="card">
<div class="card-head">
<div>
<h2 data-i18n="clients.peers">{{ tr('clients.peers') }}</h2>
<p data-i18n="clients.peers_subtitle">{{ tr('clients.peers_subtitle') }}</p>
</div>
<div class="client-table-tools">
<div class="quick-search-wrap">
<input id="client-quick-search" class="quick-search-input" type="search" autocomplete="off" placeholder="{{ tr('clients.quick_search') }}" aria-label="{{ tr('clients.quick_search') }}">
<button class="quick-search-clear" id="client-quick-search-clear" type="button" aria-label="{{ tr('clients.quick_search_clear') }}" data-tooltip="{{ tr('clients.quick_search_clear') }}" hidden>×</button>
</div>
<button class="btn" id="refresh-button" data-i18n="common.refresh">{{ tr('common.refresh') }}</button>
</div>
</div>
<div class="table-wrap client-table-wrap">
<table class="client-table">
<colgroup>
<col class="client-col-name">
<col class="client-col-group">
<col class="client-col-address">
<col class="client-col-remote">
<col class="client-col-keepalive">
<col class="client-col-status">
<col class="client-col-handshake">
<col class="client-col-traffic">
<col class="client-col-actions">
</colgroup>
<thead>
<tr>
<th data-i18n="clients.name">{{ tr('clients.name') }}</th>
<th data-i18n="groups.group">{{ tr('groups.group') }}</th>
<th data-i18n="clients.address">{{ tr('clients.address') }}</th>
<th data-i18n="clients.remote_networks">{{ tr('clients.remote_networks') }}</th>
<th data-i18n="clients.keepalive">{{ tr('clients.keepalive') }}</th>
<th data-i18n="clients.status">{{ tr('clients.status') }}</th>
<th data-i18n="clients.handshake">{{ tr('clients.handshake') }}</th>
<th>RX / TX</th>
<th data-i18n="clients.actions">{{ tr('clients.actions') }}</th>
</tr>
</thead>
<tbody id="client-body"><tr><td colspan="9" class="empty">{{ tr('common.loading') }}</td></tr></tbody>
</table>
</div>
</section>
<div class="modal-backdrop" id="client-editor-modal" hidden>
<div class="modal-card modal-wide client-editor-card" role="dialog" aria-modal="true" aria-labelledby="client-editor-title">
<div class="modal-head">
<div>
<h2 id="client-editor-title" data-i18n="clients.create_title">{{ tr('clients.create_title') }}</h2>
<p id="client-editor-subtitle" data-i18n="clients.create_subtitle">{{ tr('clients.create_subtitle') }}</p>
</div>
<button class="icon-btn" type="button" data-modal-close="client-editor-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="client-editor-form" class="client-editor-form-shell" novalidate>
<div class="client-editor-tabs" role="tablist" aria-label="Client settings">
<button type="button" class="client-editor-tab active" id="client-tab-button-basic" data-client-tab="basic" role="tab" aria-selected="true" aria-controls="client-tab-basic" data-i18n="clients.tab_basic">{{ tr('clients.tab_basic') }}</button>
<button type="button" class="client-editor-tab" id="client-tab-button-policy" data-client-tab="policy" role="tab" aria-selected="false" aria-controls="client-tab-policy" data-i18n="clients.tab_policy">{{ tr('clients.tab_policy') }}</button>
<button type="button" class="client-editor-tab" id="client-tab-button-config" data-client-tab="config" role="tab" aria-selected="false" aria-controls="client-tab-config" data-i18n="clients.tab_config">{{ tr('clients.tab_config') }}</button>
<button type="button" class="client-editor-tab" id="client-tab-button-security" data-client-tab="security" role="tab" aria-selected="false" aria-controls="client-tab-security" data-i18n="clients.tab_security">{{ tr('clients.tab_security') }}</button>
</div>
<div class="modal-body client-editor-body">
<section class="client-tab-panel" id="client-tab-basic" data-client-tab-panel="basic" role="tabpanel" aria-labelledby="client-tab-button-basic">
<div class="setup-section-title" data-i18n="clients.basic_details">{{ tr('clients.basic_details') }}</div>
<div class="setup-grid">
<label>
<span data-i18n="clients.name">{{ tr('clients.name') }}</span>
<input id="client-name" maxlength="64" placeholder="Peer name" required>
</label>
<label>
<span data-i18n="clients.type">{{ tr('clients.type') }}</span>
<select id="client-type">
<option value="client" data-i18n="clients.client">{{ tr('clients.client') }}</option>
{% if request.state.access.role == 'admin' %}<option value="site_to_site" data-i18n="clients.site_to_site">{{ tr('clients.site_to_site') }}</option>{% endif %}
</select>
</label>
<label>
<span data-i18n="clients.address">{{ tr('clients.address') }}</span>
<input id="client-vpn-address" class="mono" placeholder="10.0.0.10/32" required>
<small data-i18n="clients.address_hint">{{ tr('clients.address_hint') }}</small>
</label>
<label id="client-group-field">
<span data-i18n="groups.group">{{ tr('groups.group') }}</span>
<select id="client-group"></select>
<small data-i18n="groups.client_group_hint">{{ tr('groups.client_group_hint') }}</small>
</label>
</div>
<label class="field-block section-space-small" id="client-remote-networks-field" hidden>
<span data-i18n="clients.remote_networks">{{ tr('clients.remote_networks') }}</span>
<textarea id="client-remote-networks" class="mono controlled-textarea" rows="3" placeholder="192.168.60.0/24"></textarea>
<small data-i18n="clients.remote_hint">{{ tr('clients.remote_hint') }}</small>
</label>
<div id="client-basic-managed-fields">
<div class="setup-section-title section-space" data-i18n="clients.basic_connection">{{ tr('clients.basic_connection') }}</div>
<div class="setup-grid">
<label>
<span data-i18n="clients.server_host">{{ tr('clients.server_host') }}</span>
<div class="input-action-wrap">
<input id="client-server-host" class="mono" list="client-endpoint-history" autocomplete="off" placeholder="vpn.example.com" required>
<button class="input-action-button" type="button" id="client-use-panel-host" aria-label="{{ tr('clients.use_panel_host') }}" data-tooltip="{{ tr('clients.use_panel_host') }}">🌐</button>
</div>
<datalist id="client-endpoint-history"></datalist>
<small data-i18n="clients.server_host_hint">{{ tr('clients.server_host_hint') }}</small>
</label>
<label>
<span data-i18n="clients.server_port">{{ tr('clients.server_port') }}</span>
<input id="client-server-port" class="mono" type="number" min="1" max="65535" readonly>
<small data-i18n="clients.server_port_hint">{{ tr('clients.server_port_hint') }}</small>
</label>
</div>
</div>
<div class="inline-note warn-note" id="unmanaged-client-note" hidden data-i18n="clients.unmanaged_note">{{ tr('clients.unmanaged_note') }}</div>
</section>
<section class="client-tab-panel" id="client-tab-policy" data-client-tab-panel="policy" role="tabpanel" aria-labelledby="client-tab-button-policy" hidden>
<div id="client-group-policy-section" hidden>
<div class="setup-section-title" data-i18n="groups.access_policy">{{ tr('groups.access_policy') }}</div>
<div class="setup-grid">
<label>
<span data-i18n="groups.policy_mode">{{ tr('groups.policy_mode') }}</span>
<select id="client-policy-mode">
<option value="inherit" data-i18n="groups.policy_inherit">{{ tr('groups.policy_inherit') }}</option>
<option value="custom" data-i18n="groups.policy_custom">{{ tr('groups.policy_custom') }}</option>
</select>
<small data-i18n="groups.policy_mode_hint">{{ tr('groups.policy_mode_hint') }}</small>
</label>
<div></div>
<label>
<span data-i18n="groups.internet_access">{{ tr('groups.internet_access') }}</span>
<select id="client-internet-access"></select>
</label>
<label>
<span data-i18n="groups.local_access">{{ tr('groups.local_access') }}</span>
<select id="client-local-access"></select>
</label>
</div>
<div class="setup-grid section-space-small">
<label>
<span id="client-policy-allow-label" data-i18n="groups.additional_allowed">{{ tr('groups.additional_allowed') }}</span>
<input id="client-policy-allow" class="mono" placeholder="192.168.50.115, 203.0.113.0/24">
<small data-i18n="groups.policy_addresses_hint">{{ tr('groups.policy_addresses_hint') }}</small>
</label>
<label>
<span id="client-policy-deny-label" data-i18n="groups.additional_blocked">{{ tr('groups.additional_blocked') }}</span>
<input id="client-policy-deny" class="mono" placeholder="192.168.50.200">
<small data-i18n="groups.policy_addresses_hint">{{ tr('groups.policy_addresses_hint') }}</small>
</label>
</div>
<div class="policy-preview section-space-small">
<div class="policy-preview-title" data-i18n="groups.effective_policy">{{ tr('groups.effective_policy') }}</div>
<div id="client-policy-preview"></div>
</div>
</div>
</section>
<section class="client-tab-panel" id="client-tab-config" data-client-tab-panel="config" role="tabpanel" aria-labelledby="client-tab-button-config" hidden>
<div id="client-config-fields">
<div id="client-relay-connection-section" hidden>
<div class="setup-section-title" data-i18n="clients.connection_path">{{ tr('clients.connection_path') }}</div>
<div class="setup-grid section-space-small">
<label>
<span data-i18n="clients.connection_via">{{ tr('clients.connection_via') }}</span>
<select id="client-connection-mode">
<option value="direct" data-i18n="clients.connection_direct">{{ tr('clients.connection_direct') }}</option>
<option value="relay" data-i18n="clients.connection_relay">{{ tr('clients.connection_relay') }}</option>
</select>
<small data-i18n="clients.connection_via_hint">{{ tr('clients.connection_via_hint') }}</small>
</label>
<label id="client-relay-vps-field" hidden>
<span data-i18n="clients.relay_vps">{{ tr('clients.relay_vps') }}</span>
<select id="client-relay-vps"></select>
<small data-i18n="clients.relay_vps_hint">{{ tr('clients.relay_vps_hint') }}</small>
</label>
</div>
<div class="inline-note" id="client-relay-endpoint-note" hidden></div>
</div>
<div class="setup-section-title" data-i18n="clients.generated_config">{{ tr('clients.generated_config') }}</div>
<div class="policy-preview group-config-mode" id="client-group-defaults-wrap" hidden>
<div class="policy-preview-title" data-i18n="groups.client_config_source">{{ tr('groups.client_config_source') }}</div>
<label class="choice-row"><input type="checkbox" id="client-config-override"> <span data-i18n="groups.override_client_config">{{ tr('groups.override_client_config') }}</span></label>
<small data-i18n="groups.override_client_config_hint">{{ tr('groups.override_client_config_hint') }}</small>
<div class="inline-note warn-note" id="client-group-config-warning" hidden data-i18n="groups.config_differs">{{ tr('groups.config_differs') }}</div>
<button type="button" class="btn small section-space-small" id="apply-group-defaults-button" hidden data-i18n="groups.apply_current_template">{{ tr('groups.apply_current_template') }}</button>
</div>
<div class="setup-grid section-space-small">
<label>
<span data-i18n="groups.traffic_through_vpn">{{ tr('groups.traffic_through_vpn') }}</span>
<select id="client-route-preset">
<option value="full" data-i18n="clients.route_full">{{ tr('clients.route_full') }}</option>
<option value="full_except_local" data-i18n="clients.route_full_except_local">{{ tr('clients.route_full_except_local') }}</option>
<option value="vpn_lan" data-i18n="clients.route_vpn_lan">{{ tr('clients.route_vpn_lan') }}</option>
<option value="vpn" data-i18n="clients.route_vpn">{{ tr('clients.route_vpn') }}</option>
<option value="custom" data-i18n="clients.route_custom">{{ tr('clients.route_custom') }}</option>
</select>
</label>
<label>
<span data-i18n="clients.dns">{{ tr('clients.dns') }}</span>
<input id="client-dns" class="mono" placeholder="192.168.50.1">
<small data-i18n="clients.dns_hint">{{ tr('clients.dns_hint') }}</small>
</label>
<label>
<span data-i18n="clients.keepalive">{{ tr('clients.keepalive') }}</span>
<input id="client-keepalive" type="number" min="0" max="65535" value="25">
<small data-i18n="clients.keepalive_hint">{{ tr('clients.keepalive_hint') }}</small>
</label>
</div>
<label class="field-block section-space-small" id="client-local-access-exceptions-field" hidden>
<span data-i18n="clients.local_access_exceptions">{{ tr('clients.local_access_exceptions') }}</span>
<input id="client-local-access-exceptions" class="mono" placeholder="192.168.50.10, 192.168.50.20">
<small data-i18n="clients.local_access_exceptions_hint">{{ tr('clients.local_access_exceptions_hint') }}</small>
</label>
<label class="field-block section-space-small">
<span data-i18n="clients.client_allowed_ips">{{ tr('clients.client_allowed_ips') }}</span>
<textarea id="client-allowed-ips" class="mono controlled-textarea" rows="3" placeholder="0.0.0.0/0" required></textarea>
<small data-i18n="clients.route_hint">{{ tr('clients.route_hint') }}</small>
</label>
<div class="route-reference section-space-small" id="client-protected-networks-reference" hidden>
<span data-i18n="clients.protected_networks_reference">{{ tr('clients.protected_networks_reference') }}</span>
<div class="route-reference-list mono" id="client-protected-networks-list"></div>
<small data-i18n="clients.protected_networks_reference_hint">{{ tr('clients.protected_networks_reference_hint') }}</small>
</div>
</div>
</section>
<section class="client-tab-panel" id="client-tab-security" data-client-tab-panel="security" role="tabpanel" aria-labelledby="client-tab-button-security" hidden>
<div id="client-managed-options-section">
<div class="setup-section-title" data-i18n="clients.security_access">{{ tr('clients.security_access') }}</div>
<div class="setup-grid">
<div class="field-button-wrap">
<span data-i18n="clients.psk">{{ tr('clients.psk') }}</span>
<label class="choice-row compact-choice"><input type="checkbox" id="client-use-psk" checked> <span data-i18n="clients.psk_enable">{{ tr('clients.psk_enable') }}</span></label>
<small data-i18n="clients.psk_hint">{{ tr('clients.psk_hint') }}</small>
</div>
<label>
<span data-i18n="clients.expiration">{{ tr('clients.expiration') }}</span>
<select id="client-expiry-preset">
<option value="never" data-i18n="clients.expire_never">{{ tr('clients.expire_never') }}</option>
<option value="1h" data-i18n="clients.expire_1h">{{ tr('clients.expire_1h') }}</option>
<option value="3h" data-i18n="clients.expire_3h">{{ tr('clients.expire_3h') }}</option>
<option value="6h" data-i18n="clients.expire_6h">{{ tr('clients.expire_6h') }}</option>
<option value="1d" data-i18n="clients.expire_1d">{{ tr('clients.expire_1d') }}</option>
<option value="custom" data-i18n="clients.expire_custom">{{ tr('clients.expire_custom') }}</option>
</select>
<small data-i18n="clients.expiration_hint">{{ tr('clients.expiration_hint') }}</small>
</label>
<label id="client-expiry-custom-field" hidden>
<span data-i18n="clients.expiration_datetime">{{ tr('clients.expiration_datetime') }}</span>
<input id="client-expiry-custom" type="datetime-local">
<small data-i18n="clients.expiration_datetime_hint">{{ tr('clients.expiration_datetime_hint') }}</small>
</label>
<div class="field-button-wrap" id="client-expiry-action-field" hidden>
<span data-i18n="clients.expiration_action">{{ tr('clients.expiration_action') }}</span>
<label class="choice-row compact-choice"><input type="checkbox" id="client-expiry-delete" checked> <span data-i18n="clients.expiration_delete">{{ tr('clients.expiration_delete') }}</span></label>
<small data-i18n="clients.expiration_action_hint">{{ tr('clients.expiration_action_hint') }}</small>
</div>
<div class="inline-note warn-note" id="client-expired-disabled-note" hidden data-i18n="clients.expired_disabled_hint">{{ tr('clients.expired_disabled_hint') }}</div>
<div class="field-button-wrap span-2" id="client-peer-isolation-field">
<span data-i18n="clients.peer_isolation">{{ tr('clients.peer_isolation') }}</span>
<label class="choice-row compact-choice"><input type="checkbox" id="client-peer-isolation"> <span data-i18n="clients.peer_isolation_enable">{{ tr('clients.peer_isolation_enable') }}</span></label>
<small data-i18n="clients.peer_isolation_hint">{{ tr('clients.peer_isolation_hint') }}</small>
</div>
</div>
<div class="setup-section-title section-space" id="client-schedule-title" data-i18n="clients.schedule_title">{{ tr('clients.schedule_title') }}</div>
<div id="client-schedule-section">
<label class="choice-row schedule-enable-row"><input type="checkbox" id="client-schedule-enabled"> <span data-i18n="clients.schedule_enable">{{ tr('clients.schedule_enable') }}</span></label>
<small class="schedule-help" data-i18n="clients.schedule_hint">{{ tr('clients.schedule_hint') }}</small>
<div class="schedule-editor section-space-small" id="client-schedule-editor" hidden>
<div>
<span class="field-caption" data-i18n="clients.schedule_days">{{ tr('clients.schedule_days') }}</span>
<div class="schedule-days">
<label><input type="checkbox" data-schedule-day="0" checked><span data-i18n="clients.day_mon">{{ tr('clients.day_mon') }}</span></label>
<label><input type="checkbox" data-schedule-day="1" checked><span data-i18n="clients.day_tue">{{ tr('clients.day_tue') }}</span></label>
<label><input type="checkbox" data-schedule-day="2" checked><span data-i18n="clients.day_wed">{{ tr('clients.day_wed') }}</span></label>
<label><input type="checkbox" data-schedule-day="3" checked><span data-i18n="clients.day_thu">{{ tr('clients.day_thu') }}</span></label>
<label><input type="checkbox" data-schedule-day="4" checked><span data-i18n="clients.day_fri">{{ tr('clients.day_fri') }}</span></label>
<label><input type="checkbox" data-schedule-day="5"><span data-i18n="clients.day_sat">{{ tr('clients.day_sat') }}</span></label>
<label><input type="checkbox" data-schedule-day="6"><span data-i18n="clients.day_sun">{{ tr('clients.day_sun') }}</span></label>
</div>
</div>
<div class="schedule-time-grid">
<label>
<span data-i18n="clients.schedule_from">{{ tr('clients.schedule_from') }}</span>
<input id="client-schedule-start" type="time" value="08:00">
</label>
<label>
<span data-i18n="clients.schedule_to">{{ tr('clients.schedule_to') }}</span>
<input id="client-schedule-end" type="time" value="19:00">
</label>
</div>
<small data-i18n="clients.schedule_timezone_hint">{{ tr('clients.schedule_timezone_hint') }}</small>
</div>
<div class="inline-note warn-note" id="client-schedule-disabled-note" hidden data-i18n="clients.schedule_disabled_hint">{{ tr('clients.schedule_disabled_hint') }}</div>
</div>
<div class="setup-grid section-space">
<div class="field-button-wrap span-2" id="client-rotate-credentials-wrap" hidden>
<span data-i18n="clients.credentials_rotate">{{ tr('clients.credentials_rotate') }}</span>
<button type="button" class="btn" id="rotate-credentials-button" data-i18n="clients.credentials_rotate_button">{{ tr('clients.credentials_rotate_button') }}</button>
<small data-i18n="clients.credentials_rotate_hint">{{ tr('clients.credentials_rotate_hint') }}</small>
</div>
</div>
</div>
</section>
</div>
<div class="client-editor-status-wrap">
<div class="operation-status" id="client-editor-status" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="client-editor-modal" data-i18n="common.cancel">{{ tr('common.cancel') }}</button>
<button type="submit" class="btn primary" id="save-client-button" data-i18n="common.save">{{ tr('common.save') }}</button>
</div>
</form>
</div>
</div>
<div class="modal-backdrop" id="groups-modal" hidden>
<div class="modal-card modal-wide" role="dialog" aria-modal="true" aria-labelledby="groups-title">
<div class="modal-head">
<div>
<h2 id="groups-title" data-i18n="groups.title">{{ tr('groups.title') }}</h2>
<p data-i18n="groups.subtitle">{{ tr('groups.subtitle') }}</p>
</div>
<button class="icon-btn" type="button" data-modal-close="groups-modal" aria-label="{{ tr('common.close') }}">×</button>
</div>
<div class="modal-body">
<div id="groups-list" class="group-list"></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="groups-modal" data-i18n="common.close">{{ tr('common.close') }}</button>
<button type="button" class="btn primary" id="create-group-button" data-i18n="groups.create">{{ tr('groups.create') }}</button>
</div>
</div>
</div>
<div class="modal-backdrop" id="group-editor-modal" hidden>
<div class="modal-card modal-wide" role="dialog" aria-modal="true" aria-labelledby="group-editor-title">
<div class="modal-head">
<div>
<h2 id="group-editor-title" data-i18n="groups.create_title">{{ tr('groups.create_title') }}</h2>
<p data-i18n="groups.editor_subtitle">{{ tr('groups.editor_subtitle') }}</p>
</div>
<button class="icon-btn" type="button" data-modal-close="group-editor-modal" aria-label="{{ tr('common.close') }}">×</button>
</div>
<form id="group-editor-form">
<div class="modal-body">
<div class="setup-section-title" data-i18n="groups.basic">{{ tr('groups.basic') }}</div>
<div class="setup-grid">
<label>
<span data-i18n="groups.name">{{ tr('groups.name') }}</span>
<input id="group-name" maxlength="64" required placeholder="Contractors">
</label>
<label>
<span data-i18n="groups.description">{{ tr('groups.description') }}</span>
<input id="group-description" maxlength="240" placeholder="Temporary staff and contractors">
</label>
</div>
<div class="setup-section-title section-space" data-i18n="groups.access_policy">{{ tr('groups.access_policy') }}</div>
<div class="setup-grid">
<label>
<span data-i18n="groups.internet_access">{{ tr('groups.internet_access') }}</span>
<select id="group-internet-access">
<option value="allow" data-i18n="groups.allow">{{ tr('groups.allow') }}</option>
<option value="block" data-i18n="groups.block">{{ tr('groups.block') }}</option>
</select>
</label>
<label>
<span data-i18n="groups.local_access">{{ tr('groups.local_access') }}</span>
<select id="group-local-access">
<option value="allow" data-i18n="groups.allow">{{ tr('groups.allow') }}</option>
<option value="block" data-i18n="groups.block">{{ tr('groups.block') }}</option>
</select>
</label>
<label>
<span data-i18n="groups.allowed_addresses">{{ tr('groups.allowed_addresses') }}</span>
<input id="group-policy-allow" class="mono" placeholder="192.168.50.115">
<small data-i18n="groups.policy_addresses_hint">{{ tr('groups.policy_addresses_hint') }}</small>
</label>
<label>
<span data-i18n="groups.blocked_addresses">{{ tr('groups.blocked_addresses') }}</span>
<input id="group-policy-deny" class="mono" placeholder="192.168.50.200">
<small data-i18n="groups.policy_addresses_hint">{{ tr('groups.policy_addresses_hint') }}</small>
</label>
</div>
<div class="setup-section-title section-space" data-i18n="groups.new_client_defaults">{{ tr('groups.new_client_defaults') }}</div>
<div class="setup-grid">
<label>
<span data-i18n="groups.traffic_through_vpn">{{ tr('groups.traffic_through_vpn') }}</span>
<select id="group-route-preset">
<option value="full" data-i18n="clients.route_full">{{ tr('clients.route_full') }}</option>
<option value="full_except_local" data-i18n="clients.route_full_except_local">{{ tr('clients.route_full_except_local') }}</option>
<option value="vpn_lan" data-i18n="clients.route_vpn_lan">{{ tr('clients.route_vpn_lan') }}</option>
<option value="vpn" data-i18n="clients.route_vpn">{{ tr('clients.route_vpn') }}</option>
<option value="custom" data-i18n="clients.route_custom">{{ tr('clients.route_custom') }}</option>
</select>
</label>
<label>
<span data-i18n="clients.dns">{{ tr('clients.dns') }}</span>
<input id="group-dns" class="mono" placeholder="192.168.50.1">
</label>
<label>
<span data-i18n="clients.keepalive">{{ tr('clients.keepalive') }}</span>
<input id="group-keepalive" type="number" min="0" max="65535" value="25">
</label>
</div>
<label class="field-block section-space-small">
<span data-i18n="clients.client_allowed_ips">{{ tr('clients.client_allowed_ips') }}</span>
<textarea id="group-allowed-ips" class="mono controlled-textarea" rows="3" required></textarea>
<small data-i18n="groups.defaults_hint">{{ tr('groups.defaults_hint') }}</small>
</label>
<div class="operation-status" id="group-editor-status" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="group-editor-modal" data-i18n="common.cancel">{{ tr('common.cancel') }}</button>
<button type="submit" class="btn primary" id="save-group-button" data-i18n="common.save">{{ tr('common.save') }}</button>
</div>
</form>
</div>
</div>
<div class="modal-backdrop" id="group-delete-modal" hidden>
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="group-delete-title">
<div class="modal-head">
<div>
<h2 id="group-delete-title" data-i18n="groups.delete_title">{{ tr('groups.delete_title') }}</h2>
<p id="group-delete-text"></p>
</div>
<button class="icon-btn" type="button" data-modal-close="group-delete-modal" aria-label="{{ tr('common.close') }}">×</button>
</div>
<div class="modal-body" id="group-delete-options">
<label class="choice-row"><input type="radio" name="group-delete-mode" value="unassign" checked> <span data-i18n="groups.delete_unassign">{{ tr('groups.delete_unassign') }}</span></label>
<label class="choice-row"><input type="radio" name="group-delete-mode" value="move"> <span data-i18n="groups.delete_move">{{ tr('groups.delete_move') }}</span></label>
<select id="group-delete-target"></select>
<div class="operation-status" id="group-delete-status" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="group-delete-modal" data-i18n="common.cancel">{{ tr('common.cancel') }}</button>
<button type="button" class="btn danger" id="confirm-delete-group-button" data-i18n="common.delete">{{ tr('common.delete') }}</button>
</div>
</div>
</div>
<div class="modal-backdrop" id="client-config-modal" hidden>
<div class="modal-card config-modal" role="dialog" aria-modal="true" aria-labelledby="client-config-title">
<div class="modal-head">
<div>
<h2 id="client-config-title" data-i18n="clients.config_title">{{ tr('clients.config_title') }}</h2>
<p data-i18n="clients.config_private_warning">{{ tr('clients.config_private_warning') }}</p>
</div>
<button class="icon-btn" type="button" data-modal-close="client-config-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<div class="config-layout">
<div>
<textarea id="client-config-text" class="config-text mono" readonly></textarea>
<div class="config-buttons">
<button class="btn" type="button" id="copy-config-button" data-i18n="clients.copy_config">{{ tr('clients.copy_config') }}</button>
<button class="btn primary" type="button" id="download-config-button" data-i18n="clients.download_config">{{ tr('clients.download_config') }}</button>
</div>
</div>
<div class="qr-panel">
<div id="client-qr-loading" class="muted" data-i18n="clients.qr_loading">{{ tr('clients.qr_loading') }}</div>
<img id="client-qr-image" alt="WireGuard QR code" hidden>
</div>
</div>
</div>
</div>
{% endblock %}
+94
View File
@@ -0,0 +1,94 @@
{% extends "base.html" %}
{% block content %}
<section class="page-head page-head-actions dashboard-head">
<div>
<h1 data-i18n="dashboard.title">{{ tr('dashboard.title') }}</h1>
<p data-i18n="dashboard.subtitle">{{ tr('dashboard.subtitle') }}</p>
</div>
<div class="wg-control-row" aria-label="WireGuard controls">
<button class="btn small success-control" id="wg-start-button" type="button">▶ {{ tr('dashboard.start') }}</button>
<button class="btn small" id="wg-restart-button" type="button">↻ {{ tr('dashboard.restart') }}</button>
<button class="btn small danger" id="wg-stop-button" type="button">■ {{ tr('dashboard.stop') }}</button>
</div>
</section>
<div class="metric-grid">
<section class="card metric-card">
<div class="metric-title" data-i18n="dashboard.wireguard">{{ tr('dashboard.wireguard') }}</div>
<div class="metric-value"><span id="wg-state-dot" class="status-dot unknown"></span><span id="wg-state">{{ tr('common.checking') }}</span></div>
<div class="metric-lines"><span id="wg-interface">wg0</span><span id="wg-address">—</span><span id="wg-port">—</span></div>
</section>
<section class="card metric-card">
<div class="metric-title" data-i18n="dashboard.peers">{{ tr('dashboard.peers') }}</div>
<div class="metric-value"><span id="peer-online">0</span> <small data-i18n="common.online">{{ tr('common.online') }}</small></div>
<div class="metric-lines"><span><span data-i18n="common.total">{{ tr('common.total') }}</span>: <b id="peer-total">0</b></span><span><span data-i18n="dashboard.site_to_site">{{ tr('dashboard.site_to_site') }}</span>: <b id="peer-s2s">0</b></span></div>
</section>
<section class="card metric-card">
<div class="metric-title-row">
<div class="metric-title" data-i18n="dashboard.traffic">{{ tr('dashboard.traffic') }}</div>
<button class="btn small traffic-reset-button" id="traffic-reset-button" type="button" data-i18n="dashboard.traffic_reset">{{ tr('dashboard.traffic_reset') }}</button>
</div>
<div class="traffic-pair"><div><span class="traffic-arrow">↓</span><b id="rx-total">0 B</b><small>RX</small></div><div><span class="traffic-arrow">↑</span><b id="tx-total">0 B</b><small>TX</small></div></div>
</section>
<section class="card metric-card">
<div class="metric-title" data-i18n="dashboard.routing">{{ tr('dashboard.routing') }}</div>
<div class="health-list compact"><div><span id="forwarding-icon">○</span><span data-i18n="server.ip_forwarding">{{ tr('server.ip_forwarding') }}</span></div><div><span id="nat-icon">○</span><span data-i18n="server.nat">{{ tr('server.nat') }}</span></div><div><span id="table-icon">○</span><span data-i18n="server.policy_table">{{ tr('server.policy_table') }}</span> <b id="policy-table">—</b></div></div>
</section>
</div>
<div class="resource-grid">
<section class="card resource-card">
<div class="resource-head"><span class="resource-icon">◉</span><span>{{ tr('dashboard.cpu') }}</span></div>
<div class="resource-value"><span id="cpu-percent">—</span><small>%</small></div>
<div class="resource-sub" id="cpu-detail">—</div>
<div class="resource-bar"><span id="cpu-bar"></span></div>
<div class="resource-history">
<div class="history-stats" aria-label="24 hour CPU statistics">
<span><small>{{ tr('dashboard.history_min') }}</small><b id="cpu-history-min">—</b></span>
<span><small>{{ tr('dashboard.history_avg') }}</small><b id="cpu-history-avg">—</b></span>
<span><small>{{ tr('dashboard.history_max') }}</small><b id="cpu-history-max">—</b></span>
</div>
<svg class="history-chart" viewBox="0 0 320 64" preserveAspectRatio="none" aria-hidden="true"><path class="history-grid" d="M0 63.5H320 M0 32H320 M0 .5H320"></path><path class="history-line primary" id="cpu-history-line"></path></svg>
<div class="history-caption"><span>{{ tr('dashboard.history_24h') }}</span><span>{{ tr('dashboard.history_now') }}</span></div>
</div>
</section>
<section class="card resource-card">
<div class="resource-head"><span class="resource-icon">▣</span><span>{{ tr('dashboard.memory') }}</span></div>
<div class="resource-value"><span id="memory-percent">—</span><small>%</small></div>
<div class="resource-sub" id="memory-detail">—</div>
<div class="resource-bar"><span id="memory-bar"></span></div>
<div class="resource-history">
<div class="history-stats" aria-label="24 hour memory statistics">
<span><small>{{ tr('dashboard.history_min') }}</small><b id="memory-history-min">—</b></span>
<span><small>{{ tr('dashboard.history_avg') }}</small><b id="memory-history-avg">—</b></span>
<span><small>{{ tr('dashboard.history_max') }}</small><b id="memory-history-max">—</b></span>
</div>
<svg class="history-chart" viewBox="0 0 320 64" preserveAspectRatio="none" aria-hidden="true"><path class="history-grid" d="M0 63.5H320 M0 32H320 M0 .5H320"></path><path class="history-line memory" id="memory-history-line"></path></svg>
<div class="history-caption"><span>{{ tr('dashboard.history_24h') }}</span><span>{{ tr('dashboard.history_now') }}</span></div>
</div>
</section>
<section class="card resource-card network-resource-card">
<div class="resource-head"><span class="resource-icon">⇄</span><span>{{ tr('dashboard.network') }}</span></div>
<div class="network-speed-row"><div><small>↓ RX</small><b id="network-rx-rate">—</b></div><div><small>↑ TX</small><b id="network-tx-rate">—</b></div></div>
<div class="resource-sub"><span id="network-interface">—</span> · <span id="server-uptime">—</span></div>
<div class="resource-history network-history">
<div class="history-stats network-history-stats" aria-label="24 hour network statistics">
<div class="network-stat-row rx"><strong>RX</strong><span><small>{{ tr('dashboard.history_min') }}</small><b id="network-rx-history-min">—</b></span><span><small>{{ tr('dashboard.history_avg') }}</small><b id="network-rx-history-avg">—</b></span><span><small>{{ tr('dashboard.history_max') }}</small><b id="network-rx-history-max">—</b></span></div>
<div class="network-stat-row tx"><strong>TX</strong><span><small>{{ tr('dashboard.history_min') }}</small><b id="network-tx-history-min">—</b></span><span><small>{{ tr('dashboard.history_avg') }}</small><b id="network-tx-history-avg">—</b></span><span><small>{{ tr('dashboard.history_max') }}</small><b id="network-tx-history-max">—</b></span></div>
</div>
<svg class="history-chart" viewBox="0 0 320 64" preserveAspectRatio="none" aria-hidden="true"><path class="history-grid" d="M0 63.5H320 M0 32H320 M0 .5H320"></path><path class="history-line network-rx" id="network-rx-history-line"></path><path class="history-line network-tx" id="network-tx-history-line"></path></svg>
<div class="history-caption"><span>{{ tr('dashboard.history_24h') }} · RX / TX</span><span>{{ tr('dashboard.history_now') }}</span></div>
</div>
</section>
</div>
<section class="card">
<div class="card-head"><div><h2 data-i18n="dashboard.active_peers">{{ tr('dashboard.active_peers') }}</h2><p data-i18n="dashboard.active_peers_subtitle">{{ tr('dashboard.active_peers_subtitle') }}</p></div><div class="dashboard-peer-tools"><div class="quick-search-wrap"><input id="dashboard-peer-search" class="quick-search-input" type="search" autocomplete="off" placeholder="{{ tr('dashboard.quick_search') }}" aria-label="{{ tr('dashboard.quick_search') }}"><button class="quick-search-clear" id="dashboard-peer-search-clear" type="button" aria-label="{{ tr('dashboard.quick_search_clear') }}" data-tooltip="{{ tr('dashboard.quick_search_clear') }}" hidden>×</button></div><button class="btn" id="refresh-button" data-i18n="common.refresh">{{ tr('common.refresh') }}</button></div></div>
<div class="table-wrap"><table><thead><tr><th data-i18n="clients.name">{{ tr('clients.name') }}</th><th data-i18n="clients.address">{{ tr('clients.address') }}</th><th data-i18n="clients.type">{{ tr('clients.type') }}</th><th data-i18n="clients.status">{{ tr('clients.status') }}</th><th data-i18n="clients.handshake">{{ tr('clients.handshake') }}</th><th>RX</th><th>TX</th></tr></thead><tbody id="dashboard-peer-body"><tr><td colspan="7" class="empty">{{ tr('common.loading') }}</td></tr></tbody></table></div>
</section>
<section class="card">
<div class="card-head"><div><h2 data-i18n="dashboard.activity">{{ tr('dashboard.activity') }}</h2><p data-i18n="dashboard.activity_subtitle">{{ tr('dashboard.activity_subtitle') }}</p></div><span id="last-update" class="muted">—</span></div>
<div id="diagnostic-strip" class="diagnostic-grid"></div>
</section>
{% endblock %}
+36
View File
@@ -0,0 +1,36 @@
{% extends "auth_base.html" %}
{% block auth_content %}
<section class="auth-card">
<div class="auth-card-head">
<img class="brand-mark auth-mark brand-logo" src="{{ branding.logo or (base_path ~ '/static/img/wgtools-logo.png?v=' ~ version ~ '&r=' ~ asset_rev) }}" alt="">
<div>
<h1>{{ tr('auth.reset_title') }}</h1>
<p>{{ tr('auth.reset_subtitle') }}</p>
</div>
</div>
{% if password_recovery_available %}
<form id="password-reset-request-form" class="auth-form">
<label><span>{{ tr('auth.reset_identifier') }}</span><input id="reset-identifier" autocomplete="username" maxlength="254" required autofocus><small>{{ tr('auth.reset_identifier_help') }}</small></label>
<div id="auth-error" class="operation-status error" hidden></div>
<button type="submit" class="btn primary auth-submit">{{ tr('auth.send_reset_code') }}</button>
<div class="auth-secondary-row"><a href="{{ base_path }}/login">{{ tr('auth.back_to_login') }}</a></div>
</form>
<form id="password-reset-confirm-form" class="auth-form" hidden>
<input id="reset-confirm-identifier" type="hidden">
<div class="inline-note success-note auth-reset-note">{{ tr('auth.reset_code_sent_generic') }}</div>
<label><span>{{ tr('auth.reset_code') }}</span><input id="reset-code" inputmode="numeric" pattern="[0-9]{6}" minlength="6" maxlength="6" autocomplete="one-time-code" required></label>
<label><span>{{ tr('settings.new_password') }}</span><input id="reset-password" type="password" minlength="8" maxlength="256" autocomplete="new-password" required></label>
<label><span>{{ tr('auth.password_repeat') }}</span><input id="reset-password-repeat" type="password" minlength="8" maxlength="256" autocomplete="new-password" required></label>
<div id="reset-confirm-status" class="operation-status" hidden></div>
<button type="submit" class="btn primary auth-submit">{{ tr('auth.set_new_password') }}</button>
<button type="button" class="btn auth-submit" id="reset-request-again">{{ tr('auth.request_another_code') }}</button>
<div class="auth-secondary-row"><a href="{{ base_path }}/login">{{ tr('auth.back_to_login') }}</a></div>
</form>
{% else %}
<div class="auth-form">
<div class="inline-note">{{ tr('auth.reset_not_configured') }}</div>
<div class="auth-secondary-row"><a href="{{ base_path }}/login">{{ tr('auth.back_to_login') }}</a></div>
</div>
{% endif %}
</section>
{% endblock %}
+31
View File
@@ -0,0 +1,31 @@
{% extends "auth_base.html" %}
{% block auth_content %}
<section class="auth-card">
<div class="auth-card-head">
<img class="brand-mark auth-mark brand-logo" src="{{ branding.logo or (base_path ~ '/static/img/wgtools-logo.png?v=' ~ version ~ '&r=' ~ asset_rev) }}" alt="">
<div>
<h1>{{ tr('auth.login_title') }}</h1>
<p>{{ tr('auth.login_subtitle') }}</p>
</div>
</div>
<form id="login-form" class="auth-form">
<label><span>{{ tr('auth.username') }}</span><input id="auth-username" name="username" autocomplete="username" maxlength="64" required autofocus></label>
<label><span>{{ tr('auth.password') }}</span><input id="auth-password" name="password" type="password" autocomplete="current-password" maxlength="256" required></label>
{% if password_recovery_available %}
<div class="auth-secondary-row"><a href="{{ base_path }}/forgot-password">{{ tr('auth.forgot_password') }}</a></div>
{% endif %}
<div id="auth-error" class="operation-status error" hidden></div>
<button type="submit" class="btn primary auth-submit">{{ tr('auth.sign_in') }}</button>
</form>
<form id="mfa-login-form" class="auth-form" hidden>
<div class="auth-mfa-intro">
<b>{{ tr('auth.mfa_title') }}</b>
<p>{{ tr('auth.mfa_login_help') }}</p>
</div>
<label><span>{{ tr('auth.mfa_code') }}</span><input id="auth-mfa-code" name="code" autocomplete="one-time-code" maxlength="32" autocapitalize="characters" spellcheck="false" required></label>
<div id="mfa-auth-error" class="operation-status error" hidden></div>
<button type="submit" class="btn primary auth-submit">{{ tr('auth.mfa_verify') }}</button>
<button type="button" class="btn auth-submit" id="mfa-login-back">{{ tr('auth.mfa_back') }}</button>
</form>
</section>
{% endblock %}
+750
View File
@@ -0,0 +1,750 @@
{% extends "base.html" %}
{% block content %}
<section class="page-head page-head-actions">
<div>
<h1 data-i18n="server.title">{{ tr('server.title') }}</h1>
<p data-i18n="server.subtitle">{{ tr('server.subtitle') }}</p>
</div>
<div class="page-head-button-row">
<button class="btn primary" id="add-interface-button" hidden>{{ tr('interfaces.add') }}</button>
<button class="btn primary" id="edit-server-button" hidden>{{ tr('server.edit_server') }}</button>
</div>
</section>
<section class="card" id="extended-snat-card">
<div class="card-head"><div><h2>Główny adres IPv4 dla ruchu wychodzącego</h2><p>Adres musi być przypisany do interfejsu wyjściowego serwera. Puste pole wyłącza regułę SNAT.</p></div></div>
<form id="extended-snat-form" class="settings-form-pad">
<div class="setup-grid">
<label><span>Publiczny adres IPv4</span><input id="extended-snat-address" placeholder="203.0.113.10" maxlength="15"></label>
<label><span>Interfejs wyjściowy</span><input id="extended-snat-uplink" placeholder="eth0" maxlength="15"></label>
</div>
<button class="btn primary" type="submit">Zapisz adres SNAT</button>
<div id="extended-snat-status" class="operation-status" hidden></div>
</form>
</section>
<section class="card" id="extended-listen-card">
<div class="card-head"><div><h2>Ograniczenie nasłuchiwania WireGuard</h2><p>Wybierz adres IPv4, interfejs wejściowy lub oba. Dla tego ograniczenia IPv6 zostanie zablokowane. Puste pola wyłączają ograniczenie.</p></div></div>
<form id="extended-listen-form" class="settings-form-pad">
<div class="setup-grid">
<label><span>Adres IPv4</span><input id="extended-listen-address" placeholder="203.0.113.10" maxlength="15"></label>
<label><span>Interfejs wejściowy</span><input id="extended-listen-interface" placeholder="eth0" maxlength="15"></label>
</div>
<button class="btn primary" type="submit">Zapisz ograniczenie</button>
<div id="extended-listen-status" class="operation-status" hidden></div>
</form>
</section>
<section class="card">
<div class="card-head"><div><h2>Grupy publicznych adresów IPv4</h2><p>Grupy przydzielają adresy do sieci. Ten sam adres może należeć do wielu grup.</p></div></div>
<form id="extended-group-form" class="settings-form-pad">
<div class="setup-grid">
<label><span>Nazwa grupy</span><input id="extended-group-name" maxlength="64" required></label>
<label><span>Adresy IPv4 oddzielone przecinkami</span><input id="extended-group-addresses" placeholder="203.0.113.10, 203.0.113.11"></label>
<label><span>Sieci oddzielone przecinkami</span><input id="extended-group-interfaces" placeholder="wg1, wg2"></label>
</div>
<button class="btn primary" type="submit">Zapisz grupę</button>
<div id="extended-group-status" class="operation-status" hidden></div>
</form>
<div id="extended-groups-list" class="settings-form-pad"></div>
</section>
<section class="card provisioning-card" id="wireguard-install-card" hidden>
<div class="card-head">
<div>
<h2 data-i18n="server.wg_not_installed">{{ tr('server.wg_not_installed') }}</h2>
<p data-i18n="server.wg_not_installed_subtitle">{{ tr('server.wg_not_installed_subtitle') }}</p>
</div>
<span class="badge warn" data-i18n="server.setup_required">{{ tr('server.setup_required') }}</span>
</div>
<div class="provision-body">
<div class="provision-icon">WG</div>
<div class="provision-copy">
<b data-i18n="server.install_wireguard_title">{{ tr('server.install_wireguard_title') }}</b>
<p data-i18n="server.install_wireguard_help">{{ tr('server.install_wireguard_help') }}</p>
</div>
<button class="btn primary" id="install-wireguard-button" data-i18n="server.install_wireguard">{{ tr('server.install_wireguard') }}</button>
</div>
<div class="operation-status" id="install-status" hidden></div>
</section>
<section class="card" id="create-server-card" hidden>
<div class="card-head">
<div>
<h2 data-i18n="server.create_title">{{ tr('server.create_title') }}</h2>
<p data-i18n="server.create_subtitle">{{ tr('server.create_subtitle') }}</p>
</div>
<span class="badge warn" data-i18n="server.not_configured">{{ tr('server.not_configured') }}</span>
</div>
<form id="create-server-form" class="setup-form">
<div class="setup-section">
<div class="setup-section-title" data-i18n="server.basic_settings">{{ tr('server.basic_settings') }}</div>
<div class="setup-grid">
<label>
<span data-i18n="server.interface_name">{{ tr('server.interface_name') }}</span>
<input id="setup-interface" value="{{ interface }}" disabled>
<small data-i18n="server.interface_hint">{{ tr('server.interface_hint') }}</small>
</label>
<label>
<span data-i18n="server.listen_port">{{ tr('server.listen_port') }}</span>
<input id="setup-port" type="number" min="1" max="65535" value="51820" required>
</label>
<label>
<span data-i18n="interfaces.display_name">{{ tr('interfaces.display_name') }}</span>
<input id="setup-display-name" maxlength="64" placeholder="Home">
<small data-i18n="interfaces.display_name_hint">{{ tr('interfaces.display_name_hint') }}</small>
</label>
<label>
<span data-i18n="server.mtu">{{ tr('server.mtu') }}</span>
<input id="setup-mtu" type="number" min="576" max="65535" placeholder="1420">
<small data-i18n="server.mtu_hint">{{ tr('server.mtu_hint') }}</small>
</label>
<label>
<span data-i18n="server.vpn_network">{{ tr('server.vpn_network') }}</span>
<input id="setup-vpn-network" class="mono" value="10.0.0.0/24" placeholder="10.0.0.0/24" required>
<small data-i18n="server.vpn_network_hint">{{ tr('server.vpn_network_hint') }}</small>
</label>
<label>
<span data-i18n="server.server_address">{{ tr('server.server_address') }}</span>
<input id="setup-server-address" class="mono" value="10.0.0.1/24" placeholder="10.0.0.1/24" required>
<small data-i18n="server.server_address_hint">{{ tr('server.server_address_hint') }}</small>
</label>
</div>
</div>
<div class="setup-section">
<div class="setup-section-title" data-i18n="server.network_settings">{{ tr('server.network_settings') }}</div>
<div class="setup-grid">
<label>
<span data-i18n="server.uplink">{{ tr('server.uplink') }}</span>
<input id="setup-uplink" class="mono" placeholder="enp6s18" required>
</label>
<label>
<span data-i18n="server.gateway">{{ tr('server.gateway') }}</span>
<input id="setup-gateway" class="mono" placeholder="192.168.50.1">
<small data-i18n="server.gateway_hint">{{ tr('server.gateway_hint') }}</small>
</label>
<label>
<span data-i18n="server.local_network">{{ tr('server.local_network') }}</span>
<input id="setup-local-network" class="mono" placeholder="192.168.50.0/24">
<small data-i18n="server.local_network_hint">{{ tr('server.local_network_hint') }}</small>
</label>
<label>
<span data-i18n="server.policy_table">{{ tr('server.policy_table') }}</span>
<input id="setup-policy-table" class="mono" placeholder="200">
<small data-i18n="server.policy_table_hint">{{ tr('server.policy_table_hint') }}</small>
</label>
</div>
<div class="toggle-row">
<label class="check-label"><input type="checkbox" id="setup-forwarding" checked><span data-i18n="server.enable_forwarding">{{ tr('server.enable_forwarding') }}</span></label>
<label class="check-label"><input type="checkbox" id="setup-nat" checked><span data-i18n="server.enable_nat">{{ tr('server.enable_nat') }}</span></label>
</div>
</div>
<div class="setup-preview">
<div>
<b data-i18n="server.what_happens">{{ tr('server.what_happens') }}</b>
<ul>
<li data-i18n="server.create_step_key">{{ tr('server.create_step_key') }}</li>
<li data-i18n="server.create_step_conf">{{ tr('server.create_step_conf') }}</li>
<li data-i18n="server.create_step_forward">{{ tr('server.create_step_forward') }}</li>
<li data-i18n="server.create_step_start">{{ tr('server.create_step_start') }}</li>
</ul>
</div>
<button type="submit" class="btn primary danger-confirm" id="create-server-button" data-i18n="server.create_server">{{ tr('server.create_server') }}</button>
</div>
<div class="operation-status" id="create-status" hidden></div>
</form>
</section>
<div id="configured-server" hidden>
<div class="server-editor-tabs" role="tablist" aria-label="{{ tr('server.tabs_aria') }}">
<button type="button" class="server-editor-tab active" data-server-tab="interface" role="tab" aria-selected="true">{{ tr('server.tab_interface') }}</button>
<button type="button" class="server-editor-tab" data-server-tab="routing" role="tab" aria-selected="false">{{ tr('server.tab_routing') }}</button>
<button type="button" class="server-editor-tab" data-server-tab="nodes" role="tab" aria-selected="false">{{ tr('server.tab_nodes') }}</button>
<button type="button" class="server-editor-tab" data-server-tab="vps" role="tab" aria-selected="false">{{ tr('server.tab_vps') }}</button>
<button type="button" class="server-editor-tab" data-server-tab="trace" role="tab" aria-selected="false">{{ tr('server.tab_trace') }}</button>
<button type="button" class="server-editor-tab" data-server-tab="config" role="tab" aria-selected="false">{{ tr('server.tab_config') }}</button>
</div>
<div class="server-tab-panel" data-server-tab-panel="interface">
<section class="card interface-manager-card" id="interface-manager-card" hidden>
<div class="card-head">
<div>
<h2>{{ tr('interfaces.title') }}</h2>
<p>{{ tr('interfaces.subtitle') }}</p>
</div>
</div>
<div class="interface-manager-list" id="interface-manager-list"></div>
</section>
<section class="card">
<div class="card-head"><h2 data-i18n="server.interface">{{ tr('server.interface') }}</h2></div>
<dl class="kv-list" id="interface-kv"></dl>
</section>
<section class="card">
<div class="card-head">
<div><h2 data-i18n="server.diagnostics">{{ tr('server.diagnostics') }}</h2><p data-i18n="server.diagnostics_subtitle">{{ tr('server.diagnostics_subtitle') }}</p></div>
<button class="btn" id="diagnostics-button" data-i18n="server.run_diagnostics">{{ tr('server.run_diagnostics') }}</button>
</div>
<div id="diagnostics-list" class="diagnostics-list"></div>
</section>
</div>
<div class="server-tab-panel" data-server-tab-panel="trace" hidden>
<section class="card network-trace-card">
<div class="card-head">
<div>
<h2>{{ tr('trace.title') }}</h2>
<p>{{ tr('trace.subtitle') }}</p>
</div>
</div>
<form id="network-trace-form" class="trace-toolbar">
<label class="trace-target-field">
<span>{{ tr('trace.target') }}</span>
<input id="network-trace-target" class="mono" maxlength="320" placeholder="vpn.example.com / 203.0.113.10" required>
</label>
<label class="check-label trace-geo-toggle">
<input id="network-trace-geolocate" type="checkbox" checked>
<span>{{ tr('trace.show_map') }}</span>
</label>
<button type="submit" class="btn primary" id="network-trace-button">{{ tr('trace.run') }}</button>
</form>
<div class="trace-privacy-note">{{ tr('trace.geo_note') }}<br>{{ tr('trace.latency_note') }}</div>
<div class="operation-status trace-operation-status" id="network-trace-status" hidden></div>
<div id="network-trace-results" hidden>
<div class="trace-summary-grid" id="network-trace-summary"></div>
<div class="trace-map-panel" id="network-trace-map-panel" hidden>
<div class="trace-map-head">
<b>{{ tr('trace.map') }}</b>
<span>{{ tr('trace.map_hint') }}</span>
</div>
<div class="trace-map-route-summary" id="network-trace-map-route-summary" hidden></div>
<div class="trace-latency-legend" aria-label="{{ tr('trace.latency_legend') }}">
<span><i class="trace-legend-dot trace-legend-ok"></i>{{ tr('trace.latency_ok') }}</span>
<span><i class="trace-legend-dot trace-legend-warn"></i>{{ tr('trace.latency_warn') }}</span>
<span><i class="trace-legend-dot trace-legend-bad"></i>{{ tr('trace.latency_bad') }}</span>
</div>
<div class="trace-map" id="network-trace-map">
<div class="trace-map-stage" id="network-trace-map-stage">
<div class="trace-map-tiles" id="network-trace-map-tiles" aria-hidden="true"></div>
<svg id="network-trace-map-svg" aria-label="{{ tr('trace.map') }}"></svg>
</div>
<div class="trace-map-controls" aria-label="{{ tr('trace.map_controls') }}">
<button type="button" class="trace-map-control" id="network-trace-map-zoom-in" title="{{ tr('trace.zoom_in') }}">+</button>
<button type="button" class="trace-map-control" id="network-trace-map-zoom-out" title="{{ tr('trace.zoom_out') }}">−</button>
<button type="button" class="trace-map-control trace-map-fit" id="network-trace-map-fit" title="{{ tr('trace.fit_route') }}">{{ tr('trace.fit') }}</button>
</div>
<div class="trace-map-popup" id="network-trace-map-popup" hidden></div>
<div class="trace-map-attribution">© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap</a> contributors</div>
</div>
</div>
<div class="table-wrap trace-table-wrap">
<table class="trace-table">
<thead><tr>
<th>#</th>
<th>{{ tr('trace.hop') }}</th>
<th>{{ tr('trace.location') }}</th>
<th>{{ tr('trace.avg_rtt') }}</th>
<th>{{ tr('trace.delta') }}</th>
<th>{{ tr('trace.loss') }}</th>
</tr></thead>
<tbody id="network-trace-body"></tbody>
</table>
</div>
</div>
</section>
</div>
<div class="server-tab-panel" data-server-tab-panel="routing" hidden>
<section class="card"><div class="card-head"><h2 data-i18n="server.routing">{{ tr('server.routing') }}</h2></div><dl class="kv-list" id="routing-kv"></dl></section>
<section class="card">
<div class="card-head">
<div><h2>{{ tr('server.routes') }}</h2><p>{{ tr('server.routes_subtitle_v08') }}</p></div>
<button class="btn" id="add-route-button">{{ tr('server.add_route') }}</button>
</div>
<div class="table-wrap"><table><thead><tr>
<th>{{ tr('server.network') }}</th><th>{{ tr('server.via') }}</th><th>{{ tr('server.table') }}</th><th>{{ tr('server.route_type') }}</th><th>{{ tr('common.actions') }}</th>
</tr></thead><tbody id="route-body"></tbody></table></div>
</section>
<section class="card">
<div class="card-head">
<div><h2>{{ tr('server.firewall') }}</h2><p>{{ tr('server.firewall_subtitle_v08') }}</p></div>
<button class="btn" id="add-access-rule-button">{{ tr('server.add_access_rule') }}</button>
</div>
<div class="table-wrap"><table><thead><tr>
<th>{{ tr('server.rule_type') }}</th><th>{{ tr('server.source') }}</th><th>{{ tr('server.destination') }}</th><th>{{ tr('server.action') }}</th><th>{{ tr('server.details') }}</th><th>{{ tr('common.actions') }}</th>
</tr></thead><tbody id="firewall-body"></tbody></table></div>
</section>
</div>
<div class="server-tab-panel" data-server-tab-panel="nodes" hidden>
<section class="card nodes-card">
<div class="card-head">
<div>
<h2>{{ tr('nodes.title') }}</h2>
<p>{{ tr('nodes.subtitle') }}</p>
</div>
<div class="action-row" id="nodes-primary-actions">
<button class="btn primary" type="button" id="nodes-enable-hub-button">{{ tr('nodes.enable_hub') }}</button>
<button class="btn" type="button" id="nodes-connect-button">{{ tr('nodes.connect_hub') }}</button>
<button class="btn" type="button" id="nodes-settings-button" hidden>{{ tr('nodes.settings_action') }}</button>
<button class="btn" type="button" id="nodes-sync-button" hidden>{{ tr('nodes.sync_now') }}</button>
<button class="btn danger" type="button" id="nodes-disable-button" hidden>{{ tr('nodes.disable_action') }}</button>
</div>
</div>
<div id="nodes-status" class="nodes-status"></div>
<div class="operation-status" id="nodes-operation-status" hidden></div>
</section>
<section class="card" id="nodes-join-card" hidden>
<div class="card-head">
<div>
<h2>{{ tr('nodes.join_title') }}</h2>
<p>{{ tr('nodes.join_help') }}</p>
</div>
<button class="btn" type="button" id="nodes-create-code-button">{{ tr('nodes.create_code') }}</button>
</div>
<div class="nodes-code-row" id="nodes-code-row" hidden>
<input class="mono" id="nodes-join-code" readonly>
<button class="btn" type="button" id="nodes-copy-code-button">{{ tr('common.copy') }}</button>
</div>
<p class="hint" id="nodes-code-expiry"></p>
</section>
<section class="card" id="nodes-list-card" hidden>
<div class="card-head">
<div>
<h2>{{ tr('nodes.connected_nodes') }}</h2>
<p>{{ tr('nodes.connected_nodes_help') }}</p>
</div>
<button class="btn" type="button" id="nodes-refresh-button">{{ tr('common.refresh') }}</button>
</div>
<div id="nodes-list" class="nodes-list"></div>
</section>
</div>
<div class="server-tab-panel" data-server-tab-panel="vps" hidden>
<section class="card vps-card">
<div class="card-head">
<div>
<h2>{{ tr('vps.title') }}</h2>
<p>{{ tr('vps.subtitle') }}</p>
</div>
<button class="btn primary" type="button" id="vps-add-button">{{ tr('vps.add') }}</button>
</div>
<div id="vps-empty" class="vps-empty" hidden>
<div class="vps-empty-icon">VPS</div>
<div>
<b>{{ tr('vps.empty_title') }}</b>
<p>{{ tr('vps.empty_help') }}</p>
</div>
</div>
<div id="vps-list" class="vps-list"></div>
<div class="inline-note">{{ tr('vps.phase_note') }}</div>
</section>
</div>
<div class="server-tab-panel" data-server-tab-panel="config" hidden>
<section class="card advanced-card">
<div class="card-head">
<div>
<h2>{{ tr('settings.raw_config_title') }}</h2>
<p>{{ tr('settings.raw_config_help') }}</p>
</div>
<span class="badge warn">{{ tr('settings.expert_mode') }}</span>
</div>
<div class="advanced-action-row">
<div>
<b class="mono">/etc/wireguard/{{ interface }}.conf</b>
<p class="hint">{{ tr('server.config_tab_help') }}</p>
</div>
<button class="btn" id="raw-config-button">{{ tr('settings.edit_raw_config') }}</button>
</div>
</section>
</div>
</div>
<div class="modal-backdrop" id="node-hub-modal" hidden>
<div class="modal-card modal-wide">
<div class="modal-head">
<div><h2>{{ tr('nodes.enable_hub') }}</h2><p>{{ tr('nodes.enable_hub_help') }}</p></div>
<button class="icon-btn" type="button" data-modal-close="node-hub-modal" aria-label="{{ tr('common.close') }}">×</button>
</div>
<form id="node-hub-form">
<div class="modal-body">
<div class="setup-grid">
<label><span>{{ tr('nodes.node_name') }}</span><input id="node-hub-name" maxlength="64" required></label>
<label><span>{{ tr('nodes.service_port') }}</span><input id="node-hub-port" type="number" min="1" max="65535" value="51950" required><small>{{ tr('nodes.service_port_help') }}</small></label>
<label><span>{{ tr('nodes.transport_network') }}</span><input id="node-hub-network" class="mono" value="10.254.240.0/24" required><small>{{ tr('nodes.transport_help') }}</small></label>
<label class="span-2"><span>{{ tr('nodes.published_networks') }}</span><textarea id="node-hub-extra" class="mono controlled-textarea" rows="4"></textarea><small>{{ tr('nodes.published_networks_select_help') }}</small></label>
</div>
<div class="inline-note">{{ tr('nodes.hub_port_forward_note') }}</div>
<div class="operation-status" id="node-hub-status" hidden></div>
</div>
<div class="modal-actions"><button type="button" class="btn" data-modal-close="node-hub-modal">{{ tr('common.cancel') }}</button><button type="submit" class="btn primary" id="node-hub-save">{{ tr('nodes.enable_hub') }}</button></div>
</form>
</div>
</div>
<div class="modal-backdrop" id="node-connect-modal" hidden>
<div class="modal-card modal-wide">
<div class="modal-head">
<div><h2>{{ tr('nodes.connect_hub') }}</h2><p>{{ tr('nodes.connect_help') }}</p></div>
<button class="icon-btn" type="button" data-modal-close="node-connect-modal" aria-label="{{ tr('common.close') }}">×</button>
</div>
<form id="node-connect-form">
<div class="modal-body">
<div class="setup-grid">
<label><span>{{ tr('nodes.node_name') }}</span><input id="node-connect-name" maxlength="64" required></label>
<label><span>{{ tr('nodes.hub_endpoint') }}</span><input id="node-connect-hub-endpoint" class="mono" placeholder="vpn.example.com:51950" required><small>{{ tr('nodes.hub_endpoint_help') }}</small></label>
<label class="span-2"><span>{{ tr('nodes.join_code') }}</span><input id="node-connect-code" class="mono" autocomplete="off" required></label>
<label class="span-2"><span>{{ tr('nodes.published_networks') }}</span><textarea id="node-connect-extra" class="mono controlled-textarea" rows="4"></textarea><small>{{ tr('nodes.published_networks_select_help') }}</small></label>
</div>
<div class="inline-note">{{ tr('nodes.connect_reachability_note') }}</div>
<div class="operation-status" id="node-connect-status" hidden></div>
</div>
<div class="modal-actions"><button type="button" class="btn" data-modal-close="node-connect-modal">{{ tr('common.cancel') }}</button><button type="submit" class="btn primary" id="node-connect-save">{{ tr('nodes.connect') }}</button></div>
</form>
</div>
</div>
<div class="modal-backdrop" id="node-settings-modal" hidden>
<div class="modal-card modal-wide">
<div class="modal-head">
<div><h2>{{ tr('nodes.settings') }}</h2><p>{{ tr('nodes.settings_help') }}</p></div>
<button class="icon-btn" type="button" data-modal-close="node-settings-modal" aria-label="{{ tr('common.close') }}">×</button>
</div>
<form id="node-settings-form">
<div class="modal-body">
<div class="setup-grid">
<label><span>{{ tr('nodes.node_name') }}</span><input id="node-settings-name" maxlength="64" required></label>
<label><span>{{ tr('nodes.panel_url') }}</span><input id="node-settings-panel-url" class="mono"></label>
<label class="span-2"><span>{{ tr('nodes.published_networks') }}</span><textarea id="node-settings-extra" class="mono controlled-textarea" rows="4"></textarea><small>{{ tr('nodes.published_networks_settings_help') }}</small><small id="node-settings-available" class="nodes-available-networks"></small></label>
</div>
<div class="inline-note warn-note" id="node-settings-network-change" hidden></div>
<div class="operation-status" id="node-settings-status" hidden></div>
</div>
<div class="modal-actions"><button type="button" class="btn" data-modal-close="node-settings-modal">{{ tr('common.cancel') }}</button><button type="submit" class="btn primary" id="node-settings-save">{{ tr('common.save') }}</button></div>
</form>
</div>
</div>
<div class="modal-backdrop" id="node-details-modal" hidden>
<div class="modal-card modal-wide node-details-modal">
<div class="modal-head">
<div><h2 id="node-details-title">{{ tr('nodes.details') }}</h2><p id="node-details-subtitle"></p></div>
<button class="icon-btn" type="button" data-modal-close="node-details-modal" aria-label="{{ tr('common.close') }}">×</button>
</div>
<div class="modal-body" id="node-details-body"></div>
<div class="modal-actions"><button type="button" class="btn" data-modal-close="node-details-modal">{{ tr('common.close') }}</button></div>
</div>
</div>
<div class="modal-backdrop" id="interface-create-modal" hidden>
<div class="modal-card modal-wide interface-create-modal">
<div class="modal-head">
<div>
<h2>{{ tr('interfaces.create_title') }}</h2>
<p>{{ tr('interfaces.create_subtitle') }}</p>
</div>
<button class="icon-btn" type="button" data-modal-close="interface-create-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="interface-create-form">
<div class="modal-body">
<div class="setup-section-title">{{ tr('interfaces.identity') }}</div>
<div class="setup-grid">
<label>
<span>{{ tr('interfaces.system_name') }}</span>
<input id="new-interface-name" class="mono" placeholder="wg1" required maxlength="15">
<small>{{ tr('interfaces.system_name_hint') }}</small>
</label>
<label>
<span>{{ tr('interfaces.display_name') }}</span>
<input id="new-interface-display-name" placeholder="Work" maxlength="64">
<small>{{ tr('interfaces.display_name_hint') }}</small>
</label>
</div>
<div class="setup-section-title section-space">{{ tr('server.interface_section') }}</div>
<div class="setup-grid">
<label>
<span>{{ tr('server.vpn_network') }}</span>
<input id="new-interface-vpn-network" class="mono" placeholder="10.0.1.0/24" required>
<small>{{ tr('server.vpn_network_hint') }}</small>
</label>
<label>
<span>{{ tr('server.server_address') }}</span>
<input id="new-interface-server-address" class="mono" placeholder="10.0.1.1/24" required>
</label>
<label>
<span>{{ tr('server.listen_port') }}</span>
<input id="new-interface-port" type="number" min="1" max="65535" required>
<small>{{ tr('interfaces.unique_port_hint') }}</small>
</label>
<label>
<span>{{ tr('server.mtu') }}</span>
<input id="new-interface-mtu" type="number" min="576" max="65535" placeholder="1420">
<small>{{ tr('server.mtu_hint') }}</small>
</label>
<label>
<span>{{ tr('server.uplink') }}</span>
<input id="new-interface-uplink" class="mono" placeholder="enp6s18" required>
</label>
<label>
<span>{{ tr('server.gateway') }}</span>
<input id="new-interface-gateway" class="mono" placeholder="192.168.50.1">
</label>
<label>
<span>{{ tr('server.local_network') }}</span>
<input id="new-interface-local-network" class="mono" placeholder="192.168.50.0/24">
</label>
<label>
<span>{{ tr('server.policy_table') }}</span>
<input id="new-interface-policy-table" class="mono" placeholder="201">
<small>{{ tr('interfaces.unique_table_hint') }}</small>
</label>
</div>
<div class="toggle-row section-space-small">
<label class="check-label"><input type="checkbox" id="new-interface-forwarding" checked><span>{{ tr('server.enable_forwarding') }}</span></label>
<label class="check-label"><input type="checkbox" id="new-interface-nat" checked><span>{{ tr('server.enable_nat') }}</span></label>
</div>
<div class="inline-note">{{ tr('interfaces.create_hint') }}</div>
<div class="operation-status" id="interface-create-status" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="interface-create-modal">{{ tr('common.cancel') }}</button>
<button type="submit" class="btn primary" id="interface-create-save">{{ tr('interfaces.create') }}</button>
</div>
</form>
</div>
</div>
<div class="modal-backdrop" id="server-edit-modal" hidden>
<div class="modal-card modal-wide server-edit-modal">
<div class="modal-head">
<div>
<h2>{{ tr('server.edit_title') }}</h2>
<p>{{ tr('server.edit_subtitle') }}</p>
</div>
<button class="icon-btn" data-modal-close="server-edit-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="server-edit-form">
<div class="modal-body">
<div class="setup-section-title">{{ tr('server.interface_section') }}</div>
<div class="setup-grid">
<label>
<span>{{ tr('server.interface_name') }}</span>
<input id="server-edit-interface" class="mono" disabled>
</label>
<label>
<span>{{ tr('interfaces.display_name') }}</span>
<input id="server-edit-display-name" maxlength="64" placeholder="Work">
<small>{{ tr('interfaces.display_name_edit_hint') }}</small>
</label>
<label>
<span>{{ tr('server.listen_port') }}</span>
<input id="server-edit-port" type="number" min="1" max="65535" required>
</label>
<label>
<span>{{ tr('server.mtu') }}</span>
<input id="server-edit-mtu" type="number" min="576" max="65535" placeholder="1420">
<small>{{ tr('server.mtu_hint') }}</small>
</label>
<label>
<span>{{ tr('server.vpn_pool') }}</span>
<input id="server-edit-vpn-network" class="mono" placeholder="10.0.0.0/24" required>
<small>{{ tr('server.vpn_network_hint') }}</small>
</label>
<label>
<span>{{ tr('server.server_address') }}</span>
<input id="server-edit-address" class="mono" placeholder="10.0.0.1/24" required>
<small>{{ tr('server.server_address_hint') }}</small>
</label>
</div>
<div class="section-space">
<div class="setup-section-title">{{ tr('server.routing_section') }}</div>
<div class="setup-grid">
<label>
<span>{{ tr('server.uplink') }}</span>
<input id="server-edit-uplink" class="mono" placeholder="enp6s18" required>
</label>
<label>
<span>{{ tr('server.local_network') }}</span>
<input id="server-edit-local-network" class="mono" placeholder="192.168.50.0/24">
</label>
</div>
<div class="toggle-row">
<label class="check-label"><input type="checkbox" id="server-edit-policy-enabled"><span>{{ tr('server.policy_enabled') }}</span></label>
</div>
<div class="setup-grid section-space-small" id="server-policy-fields">
<label>
<span>{{ tr('server.policy_table') }}</span>
<input id="server-edit-policy-table" class="mono" placeholder="200">
<small>{{ tr('server.policy_table_hint') }}</small>
</label>
<label>
<span>{{ tr('server.gateway') }}</span>
<input id="server-edit-gateway" class="mono" placeholder="192.168.50.1">
<small>{{ tr('server.gateway_hint') }}</small>
</label>
</div>
<div class="inline-note">{{ tr('server.policy_disabled_hint') }}</div>
</div>
<div class="section-space">
<div class="setup-section-title">{{ tr('server.forwarding_section') }}</div>
<div class="toggle-stack">
<label class="check-label"><input type="checkbox" id="server-edit-ip-forwarding"><span>{{ tr('server.enable_forwarding') }}</span></label>
<label class="check-label"><input type="checkbox" id="server-edit-forward-from"><span>{{ tr('server.forward_from_vpn') }}</span></label>
<label class="check-label"><input type="checkbox" id="server-edit-forward-to"><span>{{ tr('server.forward_to_vpn') }}</span></label>
<label class="check-label"><input type="checkbox" id="server-edit-nat"><span>{{ tr('server.enable_nat') }}</span></label>
</div>
</div>
<div class="inline-note warn-note">{{ tr('server.edit_warning') }}</div>
<div class="inline-note">{{ tr('server.custom_preserved') }}</div>
<div class="operation-status" id="server-edit-status" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="server-edit-modal">{{ tr('common.cancel') }}</button>
<button type="submit" class="btn primary" id="server-edit-save">{{ tr('server.apply_settings') }}</button>
</div>
</form>
</div>
</div>
<div class="modal-backdrop" id="route-edit-modal" hidden>
<div class="modal-card">
<div class="modal-head">
<div><h2 id="route-edit-title">{{ tr('server.add_route') }}</h2><p>{{ tr('server.route_editor_help') }}</p></div>
<button class="icon-btn" data-modal-close="route-edit-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="route-edit-form">
<div class="modal-body">
<div class="setup-grid">
<label><span>{{ tr('server.network') }}</span><input id="route-network" class="mono" placeholder="10.20.0.0/24" required><small>{{ tr('server.route_network_hint') }}</small></label>
<label><span>{{ tr('server.table') }}</span><input id="route-table" class="mono" value="main" placeholder="main"><small>{{ tr('server.route_table_hint') }}</small></label>
<label><span>{{ tr('server.gateway') }}</span><input id="route-gateway" class="mono" placeholder="192.168.50.1"><small>{{ tr('server.route_gateway_hint') }}</small></label>
<label><span>{{ tr('server.interface_name') }}</span><input id="route-device" class="mono" placeholder="wg0"><small>{{ tr('server.route_device_hint') }}</small></label>
</div>
<div class="inline-note warn-note">{{ tr('server.rule_apply_warning') }}</div>
<div class="operation-status" id="route-edit-status" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="route-edit-modal">{{ tr('common.cancel') }}</button>
<button type="submit" class="btn primary" id="route-edit-save">{{ tr('server.save_apply') }}</button>
</div>
</form>
</div>
</div>
<div class="modal-backdrop" id="access-rule-modal" hidden>
<div class="modal-card">
<div class="modal-head">
<div><h2 id="access-rule-title">{{ tr('server.add_access_rule') }}</h2><p>{{ tr('server.access_rule_help') }}</p></div>
<button class="icon-btn" data-modal-close="access-rule-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="access-rule-form">
<div class="modal-body">
<div class="setup-grid">
<label><span>{{ tr('server.source') }}</span><input id="access-source" class="mono" placeholder="10.0.0.100-10.0.0.120"><small>{{ tr('server.source_hint') }}</small></label>
<label><span>{{ tr('server.destination') }}</span><input id="access-destination" class="mono" placeholder="192.168.50.0/24, 192.168.60.0/24"><small>{{ tr('server.destination_hint') }}</small></label>
<label><span>{{ tr('server.action') }}</span><select id="access-action"><option value="REJECT">REJECT</option><option value="DROP">DROP</option><option value="ACCEPT">ACCEPT</option></select><small>{{ tr('server.action_hint') }}</small></label>
<label><span>{{ tr('server.protocol') }}</span><select id="access-protocol"><option value="any">{{ tr('server.any_protocol') }}</option><option value="tcp">TCP</option><option value="udp">UDP</option></select></label>
<label><span>{{ tr('server.destination_port') }}</span><input id="access-dport" class="mono" placeholder="443"><small>{{ tr('server.destination_port_hint') }}</small></label>
</div>
<div class="inline-note">{{ tr('server.access_rule_order_hint') }}</div>
<div class="inline-note warn-note">{{ tr('server.rule_apply_warning') }}</div>
<div class="operation-status" id="access-rule-status" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="access-rule-modal">{{ tr('common.cancel') }}</button>
<button type="submit" class="btn primary" id="access-rule-save">{{ tr('server.save_apply') }}</button>
</div>
</form>
</div>
</div>
<div class="modal-backdrop" id="vps-modal" hidden>
<div class="modal-card modal-wide vps-modal" role="dialog" aria-modal="true" aria-labelledby="vps-modal-title">
<div class="modal-head">
<div><h2 id="vps-modal-title">{{ tr('vps.add_title') }}</h2><p>{{ tr('vps.add_help') }}</p></div>
<button class="icon-btn" type="button" data-modal-close="vps-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="vps-form" novalidate>
<div class="modal-body">
<div class="setup-section-title">{{ tr('vps.identity') }}</div>
<div class="setup-grid">
<label><span>{{ tr('vps.name') }}</span><input id="vps-name" maxlength="64" placeholder="Relay VPS"></label>
<label><span>{{ tr('vps.host') }}</span><input id="vps-host" class="mono" maxlength="255" placeholder="203.0.113.10"></label>
<label><span>{{ tr('vps.ssh_port') }}</span><input id="vps-ssh-port" type="number" min="1" max="65535" value="22"></label>
<label><span>{{ tr('vps.ssh_user') }}</span><input id="vps-ssh-user" maxlength="64" value="root" placeholder="root"></label>
</div>
<div class="setup-section-title section-space">{{ tr('vps.authentication') }}</div>
<div class="setup-grid">
<label><span>{{ tr('vps.auth_method') }}</span><select id="vps-auth-method"><option value="password">{{ tr('vps.password') }}</option><option value="key">{{ tr('vps.ssh_key') }}</option></select></label>
<label id="vps-password-wrap"><span>{{ tr('vps.password') }}</span><input id="vps-password" type="password" autocomplete="new-password"><small>{{ tr('vps.credentials_not_saved') }}</small></label>
<label id="vps-key-wrap" class="span-2" hidden><span>{{ tr('vps.private_key') }}</span><textarea id="vps-private-key" class="mono" rows="6" spellcheck="false" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"></textarea><small>{{ tr('vps.credentials_not_saved') }}</small></label>
<label id="vps-key-passphrase-wrap" hidden><span>{{ tr('vps.key_passphrase') }}</span><input id="vps-key-passphrase" type="password" autocomplete="new-password"></label>
</div>
<div class="setup-section-title section-space">{{ tr('vps.public_endpoint') }}</div>
<div class="setup-grid">
<label><span>{{ tr('vps.endpoint_domain') }}</span><input id="vps-endpoint-domain" class="mono" placeholder="vpn.example.com"><small>{{ tr('vps.endpoint_domain_hint') }}</small></label>
<label><span>{{ tr('vps.relay_port') }}</span><input id="vps-relay-port" type="number" min="1" max="65535" value="51820"></label>
<label><span>{{ tr('vps.transport_port') }}</span><input id="vps-transport-port" type="number" min="1" max="65535" value="51900"><small>{{ tr('vps.transport_port_hint') }}</small></label>
</div>
<div class="operation-status vps-operation-status" id="vps-preflight-status" hidden></div>
<div id="vps-preflight-result" class="vps-preflight-result" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="vps-modal">{{ tr('common.cancel') }}</button>
<button type="button" class="btn" id="vps-check-button">{{ tr('vps.check') }}</button>
<button type="submit" class="btn primary" id="vps-save-button" hidden disabled>{{ tr('vps.save_candidate') }}</button>
<button type="button" class="btn primary" id="vps-install-button" hidden disabled>{{ tr('vps.install_relay') }}</button>
</div>
</form>
</div>
</div>
<div class="modal-backdrop" id="raw-config-modal" hidden>
<div class="modal-card raw-config-modal" role="dialog" aria-modal="true" aria-labelledby="raw-config-title">
<div class="modal-head">
<div>
<h2 id="raw-config-title">{{ tr('settings.raw_config_title') }}</h2>
<p><span id="raw-config-path" class="mono">/etc/wireguard/{{ interface }}.conf</span></p>
</div>
<button class="icon-btn" type="button" data-modal-close="raw-config-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<div class="modal-body">
<div class="inline-note danger-note">{{ tr('settings.raw_config_warning') }}</div>
<div class="raw-config-toolbar">
<span class="muted">{{ tr('settings.syntax_hint') }}</span>
<button class="btn small" type="button" id="reload-raw-config-button">{{ tr('settings.reload_config') }}</button>
</div>
<div class="wg-config-editor" id="wg-config-editor">
<pre id="raw-config-highlight" aria-hidden="true"></pre>
<textarea id="raw-config-text" class="mono" wrap="off" spellcheck="false" autocomplete="off" autocapitalize="off"></textarea>
</div>
<div class="operation-status" id="raw-config-status" hidden></div>
</div>
<div class="modal-actions">
<button type="button" class="btn" data-modal-close="raw-config-modal">{{ tr('common.cancel') }}</button>
<button type="button" class="btn primary danger-confirm" id="apply-raw-config-button">{{ tr('settings.save_apply') }}</button>
</div>
</div>
</div>
{% endblock %}
+387
View File
@@ -0,0 +1,387 @@
{% extends "base.html" %}
{% block content %}
<section class="page-head page-head-actions">
<div><h1 data-i18n="settings.title">{{ tr('settings.title') }}</h1><p data-i18n="settings.subtitle">{{ tr('settings.subtitle') }}</p></div>
<button type="button" class="btn" id="audit-log-button">{{ tr('settings.audit_log') }}</button>
</section>
<div class="settings-tabs" role="tablist" aria-label="{{ tr('settings.tabs_aria') }}">
<button type="button" class="settings-tab active" data-settings-tab="general" role="tab" aria-selected="true">{{ tr('settings.tab_general') }}</button>
<button type="button" class="settings-tab" data-settings-tab="backups" role="tab" aria-selected="false">{{ tr('settings.tab_backups') }}</button>
<button type="button" class="settings-tab" data-settings-tab="telegram" role="tab" aria-selected="false">{{ tr('settings.tab_telegram') }}</button>
<button type="button" class="settings-tab" data-settings-tab="mail" role="tab" aria-selected="false">{{ tr('settings.tab_mail') }}</button>
<button type="button" class="settings-tab" data-settings-tab="https" role="tab" aria-selected="false">{{ tr('settings.tab_https') }}</button>
<button type="button" class="settings-tab" data-settings-tab="users" role="tab" aria-selected="false">{{ tr('settings.tab_users') }}</button>
<button type="button" class="settings-tab" data-settings-tab="branding" role="tab" aria-selected="false">Wygląd marki</button>
<button type="button" class="settings-tab" data-settings-tab="about" role="tab" aria-selected="false">{{ tr('settings.tab_about') }}</button>
</div>
<div class="settings-tab-panel" data-settings-tab-panel="branding" hidden>
<section class="card">
<div class="card-head"><h2>Wygląd marki</h2></div>
<form id="branding-form" class="settings-form-pad">
<input id="branding-current-logo" type="hidden" value="{{ branding.logo }}">
<div class="setup-grid">
<label><span>Nazwa w nagłówku (pusta ukrywa tekst)</span><input id="branding-name" maxlength="80" value="{{ branding.name }}"></label>
<label><span>Kolor akcentu</span><input id="branding-color" type="color" value="{{ branding.color }}"></label>
<label><span>Logo PNG (maks. 300 KB)</span><input id="branding-logo" type="file" accept="image/png"></label>
<label class="check-label"><input id="branding-reset-logo" type="checkbox"><span>Przywróć domyślne logo</span></label>
</div>
<button class="btn primary" type="submit">Zapisz</button>
<div id="branding-status" class="operation-status" hidden></div>
</form>
</section>
</div>
<div class="settings-tab-panel" data-settings-tab-panel="general">
<div class="two-col">
<section class="card">
<div class="card-head"><h2 data-i18n="settings.appearance">{{ tr('settings.appearance') }}</h2></div>
<div class="form-grid settings-form-pad">
<label><span data-i18n="settings.theme">{{ tr('settings.theme') }}</span><select id="theme-select"><option value="dark">{{ tr('settings.theme_dark') }}</option><option value="light">{{ tr('settings.theme_light') }}</option><option value="system">{{ tr('settings.theme_system') }}</option></select></label>
<label><span data-i18n="settings.language">{{ tr('settings.language') }}</span><select id="language-select"><option value="en">English</option><option value="ru">Русский</option><option value="de">Deutsch</option><option value="fr">Français</option><option value="it">Italiano</option><option value="es">Español</option><option value="pl">Polski</option></select></label>
<label class="check-label"><input id="sidebar-collapsed-toggle" type="checkbox"><span>{{ tr('settings.collapse_sidebar') }}</span></label>
</div>
</section>
<section class="card">
<div class="card-head"><div><h2 data-i18n="settings.status">{{ tr('settings.status') }}</h2><p>{{ tr('settings.status_help') }}</p></div></div>
<form id="app-settings-form" class="settings-form-pad">
<div class="setup-grid">
<label><span>{{ tr('settings.refresh_interval') }}</span><input id="settings-refresh-seconds" type="number" min="2" max="60" value="{{ refresh_seconds }}"><small>{{ tr('settings.refresh_help') }}</small></label>
<label><span>{{ tr('settings.online_threshold') }}</span><input id="settings-online-threshold" type="number" min="30" max="3600" value="{{ online_threshold }}"><small>{{ tr('settings.online_help') }}</small></label>
<label><span>{{ tr('server.interface') }}</span><input value="{{ interface }}" disabled><small>{{ tr('settings.interface_help') }}</small></label>
</div>
<div class="settings-save-row"><button class="btn primary" type="submit">{{ tr('common.save') }}</button></div>
<div class="operation-status" id="app-settings-status" hidden></div>
</form>
</section>
</div>
</div>
<div class="settings-tab-panel" data-settings-tab-panel="backups" hidden>
<div class="settings-backup-grid">
<section class="card backup-card">
<div class="card-head">
<div><h2>{{ tr('settings.backups') }}</h2><p>{{ tr('settings.backups_subtitle') }}</p></div>
<span class="badge managed">{{ tr('settings.backups_always_on') }}</span>
</div>
<div class="backup-settings-grid backup-settings-grid-single">
<label><span>{{ tr('settings.backup_retention') }}</span><input id="settings-backup-retention" type="number" min="1" max="200" value="{{ backup_retention }}"><small>{{ tr('settings.backup_retention_help') }}</small></label>
<dl class="kv-list compact-kv"><div><dt>{{ tr('settings.backup_count') }}</dt><dd id="settings-backup-count">—</dd></div><div><dt>{{ tr('settings.last_backup') }}</dt><dd id="settings-last-backup">—</dd></div></dl>
</div>
<div class="backup-save-row"><button class="btn" type="button" id="save-backup-settings-button">{{ tr('common.save') }}</button></div>
</section>
<section class="card full-backup-card">
<div class="card-head">
<div><h2>{{ tr('settings.full_backup_title') }}</h2><p>{{ tr('settings.full_backup_help') }}</p></div>
</div>
<div class="migration-backup-block">
<div class="migration-backup-copy">
<div class="inline-note danger-note migration-secret-warning">{{ tr('settings.full_backup_secret_warning') }}</div>
<ul class="migration-components">
<li>{{ tr('settings.full_backup_component_wg') }}</li>
<li>{{ tr('settings.full_backup_component_db') }}</li>
<li>{{ tr('settings.full_backup_component_clients') }}</li>
<li>{{ tr('settings.full_backup_component_relay') }}</li>
<li>{{ tr('settings.full_backup_component_system') }}</li>
</ul>
</div>
<div class="migration-actions">
<input id="migration-backup-file" type="file" accept=".wgtbackup,application/octet-stream" hidden>
<button class="btn primary" type="button" id="migration-backup-download-button">{{ tr('settings.full_backup_download') }}</button>
<button class="btn" type="button" id="migration-backup-select-button">{{ tr('settings.full_backup_select') }}</button>
<div class="migration-selected-file" id="migration-selected-file">{{ tr('settings.full_backup_no_file') }}</div>
<button class="btn danger" type="button" id="migration-backup-restore-button" disabled>{{ tr('settings.full_backup_restore') }}</button>
</div>
</div>
<div class="operation-status migration-status" id="migration-backup-status" hidden></div>
</section>
</div>
</div>
<div class="settings-tab-panel" data-settings-tab-panel="telegram" hidden>
<section class="card telegram-card">
<div class="card-head">
<div><h2>{{ tr('settings.telegram') }}</h2><p>{{ tr('settings.telegram_subtitle') }}</p></div>
<span class="badge" id="telegram-status-badge">{{ tr('settings.telegram_not_configured') }}</span>
</div>
<form id="telegram-settings-form" class="telegram-settings-body">
<div class="telegram-enable-row">
<label class="checkbox"><input id="telegram-enabled" type="checkbox"><span>{{ tr('settings.telegram_enabled') }}</span></label>
<div class="telegram-runtime"><b id="telegram-bot-name">—</b><span id="telegram-last-poll" class="muted">—</span></div>
</div>
<div class="telegram-grid">
<label><span>{{ tr('settings.telegram_token') }}</span><input id="telegram-token" type="password" maxlength="256" autocomplete="off" placeholder=""><small>{{ tr('settings.telegram_token_help') }} {{ tr('settings.telegram_token_keep') }}</small></label>
<label><span>{{ tr('settings.telegram_language') }}</span><select id="telegram-language"><option value="auto">{{ tr('settings.telegram_language_auto') }}</option><option value="en">English</option><option value="ru">Русский</option></select><small>{{ tr('settings.telegram_setup_note') }}</small></label>
<label><span>{{ tr('settings.telegram_endpoint') }}</span><input id="telegram-endpoint" maxlength="253" autocomplete="off" placeholder="vpn.example.com"><small>{{ tr('settings.telegram_endpoint_help') }}</small></label>
<label><span>{{ tr('settings.telegram_dns') }}</span><input id="telegram-dns" maxlength="255" autocomplete="off" placeholder="1.1.1.1, 8.8.8.8"><small>{{ tr('settings.telegram_dns_help') }}</small></label>
<label class="telegram-ids-field"><span>{{ tr('settings.telegram_allowed_ids') }}</span><textarea id="telegram-allowed-ids" class="controlled-textarea mono" rows="5" placeholder="123456789"></textarea><small>{{ tr('settings.telegram_allowed_ids_help') }}</small></label>
</div>
<div class="operation-status" id="telegram-settings-status" hidden></div>
<div class="telegram-actions">
<button class="btn small danger" type="button" id="telegram-remove-token-button">{{ tr('settings.telegram_remove_token') }}</button>
<span class="telegram-actions-spacer"></span>
<button class="btn" type="button" id="telegram-test-button">{{ tr('settings.telegram_test') }}</button>
<button class="btn primary" type="submit">{{ tr('settings.telegram_save') }}</button>
</div>
</form>
</section>
</div>
<div class="settings-tab-panel" data-settings-tab-panel="mail" hidden>
<section class="card mail-card">
<div class="card-head">
<div><h2>{{ tr('settings.mail') }}</h2><p>{{ tr('settings.mail_subtitle') }}</p></div>
<span class="badge" id="mail-status-badge">{{ tr('settings.mail_not_configured') }}</span>
</div>
<form id="mail-settings-form" class="mail-settings-body">
<div class="mail-enable-row">
<label class="checkbox"><input id="mail-enabled" type="checkbox"><span>{{ tr('settings.mail_enabled') }}</span></label>
</div>
<div class="mail-grid">
<label><span>{{ tr('settings.mail_smtp_host') }}</span><input id="mail-smtp-host" maxlength="253" autocomplete="off" placeholder="smtp.example.com"></label>
<label><span>{{ tr('settings.mail_security') }}</span><select id="mail-security"><option value="starttls">STARTTLS</option><option value="tls">TLS / SSL</option><option value="none">{{ tr('settings.mail_security_none') }}</option></select></label>
<label><span>{{ tr('settings.mail_smtp_port') }}</span><input id="mail-smtp-port" type="number" min="1" max="65535" value="587"></label>
<label><span>{{ tr('settings.mail_from_name') }}</span><input id="mail-from-name" maxlength="120" autocomplete="off" value="WGTools"></label>
<label><span>{{ tr('settings.mail_username') }}</span><input id="mail-username" maxlength="254" autocomplete="off"><small>{{ tr('settings.mail_username_help') }}</small></label>
<label><span>{{ tr('settings.mail_password') }}</span><input id="mail-password" type="password" maxlength="512" autocomplete="new-password"><small>{{ tr('settings.mail_password_keep') }}</small></label>
<label class="mail-test-recipient-field"><span>{{ tr('settings.mail_test_recipient') }}</span><input id="mail-test-recipient" type="email" maxlength="254" autocomplete="off" placeholder="admin@example.com"><small>{{ tr('settings.mail_test_recipient_help') }}</small></label>
</div>
<div class="operation-status" id="mail-settings-status" hidden></div>
<div class="mail-actions">
<button class="btn small danger" type="button" id="mail-remove-password-button">{{ tr('settings.mail_remove_password') }}</button>
<span class="mail-actions-spacer"></span>
<button class="btn" type="button" id="mail-test-button">{{ tr('settings.mail_test') }}</button>
<button class="btn primary" type="submit">{{ tr('settings.mail_save') }}</button>
</div>
</form>
</section>
</div>
<div class="settings-tab-panel" data-settings-tab-panel="https" hidden>
<section class="card https-card">
<div class="card-head">
<div><h2>{{ tr('settings.https_title') }}</h2><p>{{ tr('settings.https_subtitle') }}</p></div>
<span class="badge" id="https-status-badge">{{ tr('settings.https_disabled') }}</span>
</div>
<form id="https-settings-form" class="settings-form-pad">
<div class="https-enable-block">
<label class="check-label https-enable-row"><input id="https-enabled" type="checkbox" disabled><span>{{ tr('settings.https_enable') }}</span></label>
<small id="https-enable-help" class="https-enable-help">{{ tr('settings.https_enable_need_certificate') }}</small>
</div>
<div class="setup-grid https-settings-grid">
<label>
<span>{{ tr('settings.https_type') }}</span>
<select id="https-target-type"><option value="domain">{{ tr('settings.https_domain') }}</option><option value="ip">{{ tr('settings.https_public_ip') }}</option></select>
</label>
<label>
<span>{{ tr('settings.https_target') }}</span>
<div class="input-action-wrap">
<input id="https-target" class="mono" maxlength="255" autocomplete="off" placeholder="wg.example.com">
<button class="input-action-button" type="button" id="https-use-panel-host" data-tooltip="{{ tr('settings.https_use_panel_host') }}" aria-label="{{ tr('settings.https_use_panel_host') }}">🌐</button>
</div>
</label>
<label>
<span>{{ tr('settings.https_email') }}</span>
<input id="https-email" type="email" maxlength="254" autocomplete="off" placeholder="admin@example.com">
</label>
<label>
<span>{{ tr('settings.https_port') }}</span>
<input id="https-port" type="number" min="1" max="65535" value="443">
</label>
<label class="span-2">
<span>{{ tr('settings.https_access_path') }}</span>
<input id="https-access-path" class="mono" maxlength="100" autocomplete="off" placeholder="/MyPrivateWGToolsPath/">
<small>{{ tr('settings.https_access_path_help') }}</small>
</label>
</div>
<div class="inline-note warn-note https-port-note">{{ tr('settings.https_port80_note') }}</div>
<div class="https-port-status">
<div><span>TCP 80</span><b id="https-port-80">—</b></div>
<div><span id="https-panel-port-label">TCP 443</span><b id="https-panel-port">—</b></div>
<button class="btn small" type="button" id="https-check-ports-button">{{ tr('settings.https_check_ports') }}</button>
</div>
<div class="https-certificate-block">
<dl class="kv-list compact-kv">
<div><dt>{{ tr('settings.https_certificate') }}</dt><dd id="https-certificate-state">—</dd></div>
<div><dt>{{ tr('settings.https_expires') }}</dt><dd id="https-certificate-expiry">—</dd></div>
<div><dt>{{ tr('settings.https_renewal') }}</dt><dd id="https-renewal-state">—</dd></div>
<div><dt>Certbot</dt><dd id="https-certbot-version">—</dd></div>
</dl>
<div class="https-paths" id="https-paths" hidden>
<label><span>{{ tr('settings.https_certificate_path') }}</span><div class="input-action-wrap"><input id="https-certificate-path" class="mono" readonly><button class="input-action-button path-copy-button" type="button" data-copy-path="https-certificate-path" data-tooltip="{{ tr('common.copy') }}">⧉</button></div></label>
<label><span>{{ tr('settings.https_private_key_path') }}</span><div class="input-action-wrap"><input id="https-private-key-path" class="mono" readonly><button class="input-action-button path-copy-button" type="button" data-copy-path="https-private-key-path" data-tooltip="{{ tr('common.copy') }}">⧉</button></div></label>
</div>
</div>
<div class="operation-status" id="https-settings-status" hidden></div>
<div class="https-actions">
<button class="btn" type="button" id="https-issue-button">{{ tr('settings.https_issue') }}</button>
<span class="https-actions-spacer"></span>
<button class="btn primary" type="submit">{{ tr('common.save') }}</button>
</div>
</form>
</section>
</div>
<div class="settings-tab-panel" data-settings-tab-panel="users" hidden>
<section class="card users-card">
<div class="card-head">
<div>
<h2>{{ tr('settings.users') }}</h2>
<p>{{ tr('settings.users_subtitle') }}</p>
</div>
<button type="button" class="btn" id="add-user-button">{{ tr('settings.add_user') }}</button>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>{{ tr('settings.user_name') }}</th><th>{{ tr('settings.user_email') }}</th><th>{{ tr('settings.user_mfa') }}</th><th>{{ tr('settings.user_created') }}</th><th>{{ tr('settings.user_last_login') }}</th><th>{{ tr('settings.user_actions') }}</th></tr></thead>
<tbody id="users-table-body"><tr><td colspan="6" class="empty">{{ tr('common.loading') }}</td></tr></tbody>
</table>
</div>
</section>
</div>
<div class="settings-tab-panel" data-settings-tab-panel="about" id="about" hidden>
<section class="card about-card">
<div class="card-head">
<div><h2 data-i18n="settings.about">{{ tr('settings.about') }}</h2><p>{{ tr('settings.update_subtitle') }}</p></div>
<span class="badge" id="update-status-badge">Aktualizacja z pliku</span>
</div>
<dl class="kv-list about-kv">
<div><dt>{{ tr('settings.current_version') }}</dt><dd>v<span id="update-current-version">{{ version }}</span></dd></div>
<div hidden><dt>{{ tr('settings.latest_version') }}</dt><dd id="update-latest-version">—</dd></div>
<div><dt data-i18n="settings.mode">{{ tr('settings.mode') }}</dt><dd data-i18n="settings.full_mode">{{ tr('settings.full_mode') }}</dd></div>
</dl>
<div class="update-panel">
<div class="update-notes" id="update-release-notes-wrap" hidden>
<div class="update-notes-head"><b>{{ tr('settings.release_notes') }}</b><a id="update-release-link" href="#" target="_blank" rel="noopener noreferrer">{{ tr('settings.open_release') }}</a></div>
<pre id="update-release-notes"></pre>
</div>
<div class="update-actions">
<label><span>Pakiet wydania (.bin)</span><input type="file" id="update-upload-file" accept=".bin"></label>
<button class="btn primary" type="button" id="update-upload-button">Wgraj i zainstaluj</button>
<span class="update-actions-spacer"></span>
<button class="btn" type="button" id="check-updates-button" hidden>{{ tr('settings.check_updates') }}</button>
<button class="btn primary" type="button" id="apply-update-button" hidden>{{ tr('settings.update_wgtools') }}</button>
</div>
<div class="operation-status" id="update-operation-status" hidden></div>
<p class="hint update-safety-hint">{{ tr('settings.update_safety_hint') }}</p>
</div>
</section>
</div>
<div class="modal-backdrop" id="user-modal" hidden>
<div class="modal-card user-modal" role="dialog" aria-modal="true" aria-labelledby="user-modal-title">
<div class="modal-head">
<div><h2 id="user-modal-title">{{ tr('settings.add_user') }}</h2><p>Nowe konto nie ma dostępu do sieci. Przydziel go w ustawieniach uprawnień.</p></div>
<button class="icon-btn" type="button" data-modal-close="user-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="user-form">
<div class="modal-body">
<div class="setup-grid user-form-grid">
<label><span>{{ tr('auth.username') }}</span><input id="new-user-name" maxlength="64" autocomplete="off" required></label>
<label><span>{{ tr('auth.email') }}</span><input id="new-user-email" type="email" maxlength="254" autocomplete="off"><small>{{ tr('settings.user_email_help') }}</small></label>
<label><span>{{ tr('auth.password') }}</span><input id="new-user-password" type="password" minlength="8" maxlength="256" autocomplete="new-password" required></label>
<label><span>{{ tr('auth.password_repeat') }}</span><input id="new-user-password-repeat" type="password" minlength="8" maxlength="256" autocomplete="new-password" required></label>
</div>
<div class="operation-status" id="user-form-status" hidden></div>
</div>
<div class="modal-actions"><button type="button" class="btn" data-modal-close="user-modal">{{ tr('common.cancel') }}</button><button type="submit" class="btn primary">{{ tr('common.save') }}</button></div>
</form>
</div>
</div>
<div class="modal-backdrop" id="mfa-modal" hidden>
<div class="modal-card user-modal mfa-modal" role="dialog" aria-modal="true" aria-labelledby="mfa-modal-title">
<div class="modal-head">
<div><h2 id="mfa-modal-title">{{ tr('settings.mfa_title') }}</h2><p id="mfa-user-name"></p></div>
<button class="icon-btn" type="button" data-modal-close="mfa-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<div class="modal-body">
<div id="mfa-disabled-panel">
<p class="hint">{{ tr('settings.mfa_google_help') }}</p>
<div class="setup-grid user-form-grid">
<label><span>{{ tr('settings.current_password') }}</span><input id="mfa-setup-password" type="password" maxlength="256" autocomplete="current-password"></label>
</div>
<div class="mfa-inline-actions"><button class="btn primary" type="button" id="mfa-start-button">{{ tr('settings.mfa_start') }}</button></div>
<div id="mfa-setup-details" class="mfa-setup-details" hidden>
<div class="mfa-qr-wrap"><img id="mfa-qr-image" alt="Google Authenticator QR"></div>
<div class="mfa-secret-wrap"><span>{{ tr('settings.mfa_secret') }}</span><code id="mfa-secret"></code></div>
<p class="hint">{{ tr('settings.mfa_scan_help') }}</p>
<div class="setup-grid user-form-grid">
<label><span>{{ tr('settings.mfa_code') }}</span><input id="mfa-confirm-code" maxlength="6" inputmode="numeric" autocomplete="one-time-code"></label>
</div>
<div class="mfa-inline-actions"><button class="btn primary" type="button" id="mfa-confirm-button">{{ tr('settings.mfa_enable') }}</button></div>
</div>
</div>
<div id="mfa-enabled-panel" hidden>
<div class="mfa-status-row"><span class="badge success">{{ tr('settings.mfa_enabled') }}</span><span id="mfa-recovery-remaining" class="subtle"></span></div>
<p class="hint">{{ tr('settings.mfa_manage_help') }}</p>
<div class="setup-grid user-form-grid">
<label><span>{{ tr('settings.current_password') }}</span><input id="mfa-manage-password" type="password" maxlength="256" autocomplete="current-password"></label>
<label><span>{{ tr('settings.mfa_code_or_recovery') }}</span><input id="mfa-manage-code" maxlength="32" autocomplete="one-time-code" autocapitalize="characters" spellcheck="false"></label>
</div>
<div class="mfa-manage-actions">
<button class="btn" type="button" id="mfa-regenerate-button">{{ tr('settings.mfa_regenerate') }}</button>
<button class="btn danger" type="button" id="mfa-disable-button">{{ tr('settings.mfa_disable') }}</button>
</div>
</div>
<div id="mfa-recovery-panel" class="mfa-recovery-panel" hidden>
<h3>{{ tr('settings.mfa_recovery_title') }}</h3>
<p class="hint">{{ tr('settings.mfa_recovery_help') }}</p>
<pre id="mfa-recovery-codes"></pre>
<div class="mfa-inline-actions"><button class="btn" type="button" id="mfa-copy-recovery-button">{{ tr('common.copy') }}</button></div>
</div>
<div class="operation-status" id="mfa-form-status" hidden></div>
</div>
<div class="modal-actions"><button type="button" class="btn" data-modal-close="mfa-modal">{{ tr('common.close') }}</button></div>
</div>
</div>
<div class="modal-backdrop" id="email-modal" hidden>
<div class="modal-card user-modal" role="dialog" aria-modal="true" aria-labelledby="email-modal-title">
<div class="modal-head">
<div><h2 id="email-modal-title">{{ tr('settings.change_email') }}</h2><p id="email-user-name"></p></div>
<button class="icon-btn" type="button" data-modal-close="email-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="email-form">
<div class="modal-body">
<input type="hidden" id="email-user-id">
<div class="setup-grid user-form-grid">
<label><span>{{ tr('auth.email') }}</span><input id="email-new" type="email" maxlength="254" autocomplete="off"><small>{{ tr('settings.user_email_help') }}</small></label>
</div>
<div class="operation-status" id="email-form-status" hidden></div>
</div>
<div class="modal-actions"><button type="button" class="btn" data-modal-close="email-modal">{{ tr('common.cancel') }}</button><button type="submit" class="btn primary">{{ tr('common.save') }}</button></div>
</form>
</div>
</div>
<div class="modal-backdrop" id="password-modal" hidden>
<div class="modal-card user-modal" role="dialog" aria-modal="true" aria-labelledby="password-modal-title">
<div class="modal-head">
<div><h2 id="password-modal-title">{{ tr('settings.change_password') }}</h2><p id="password-user-name"></p></div>
<button class="icon-btn" type="button" data-modal-close="password-modal" aria-label="{{ tr('common.close') }}" data-tooltip="{{ tr('common.close') }}">×</button>
</div>
<form id="password-form">
<div class="modal-body">
<input type="hidden" id="password-user-id">
<div class="setup-grid user-form-grid">
<label><span>{{ tr('settings.new_password') }}</span><input id="password-new" type="password" minlength="8" maxlength="256" autocomplete="new-password" required></label>
<label><span>{{ tr('auth.password_repeat') }}</span><input id="password-repeat" type="password" minlength="8" maxlength="256" autocomplete="new-password" required></label>
</div>
<div class="operation-status" id="password-form-status" hidden></div>
</div>
<div class="modal-actions"><button type="button" class="btn" data-modal-close="password-modal">{{ tr('common.cancel') }}</button><button type="submit" class="btn primary">{{ tr('common.save') }}</button></div>
</form>
</div>
</div>
{% endblock %}
+21
View File
@@ -0,0 +1,21 @@
{% extends "auth_base.html" %}
{% block auth_content %}
<section class="auth-card">
<div class="auth-card-head">
<img class="brand-mark auth-mark brand-logo" src="{{ branding.logo or (base_path ~ '/static/img/wgtools-logo.png?v=' ~ version ~ '&r=' ~ asset_rev) }}" alt="">
<div>
<h1>{{ tr('auth.setup_title') }}</h1>
<p>{{ tr('auth.setup_subtitle') }}</p>
</div>
</div>
<form id="setup-user-form" class="auth-form">
<label><span>{{ tr('auth.username') }}</span><input id="auth-username" name="username" autocomplete="username" maxlength="64" required autofocus></label>
<label><span>{{ tr('auth.email') }}</span><input id="auth-email" name="email" type="email" autocomplete="email" maxlength="254"><small>{{ tr('auth.email_optional_help') }}</small></label>
<label><span>{{ tr('auth.password') }}</span><input id="auth-password" name="password" type="password" autocomplete="new-password" minlength="8" maxlength="256" required></label>
<label><span>{{ tr('auth.password_repeat') }}</span><input id="auth-password-repeat" type="password" autocomplete="new-password" minlength="8" maxlength="256" required></label>
<p class="auth-hint">{{ tr('auth.setup_help') }}</p>
<div id="auth-error" class="operation-status error" hidden></div>
<button type="submit" class="btn primary auth-submit">{{ tr('auth.create_user') }}</button>
</form>
</section>
{% endblock %}
+83
View File
@@ -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.
+48
View File
@@ -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.
+38
View File
@@ -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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+5
View File
@@ -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" "$@"
+348
View File
@@ -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
+18
View File
@@ -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
+7
View File
@@ -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
+144
View File
@@ -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."
+51
View File
@@ -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()
+238
View File
@@ -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 <<ENV
WGTOOLS_INTERFACE=$WG_INTERFACE
WGTOOLS_PORT=$WEB_PORT
WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper
WGTOOLS_REFRESH_SECONDS=5
WGTOOLS_ONLINE_THRESHOLD_SECONDS=180
WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db
WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key
WGTOOLS_SESSION_MAX_AGE_SECONDS=2592000
ENV
chmod 0644 /etc/wgtools/wgtools.env
else
echo "Preserving existing /etc/wgtools/wgtools.env"
fi
rm -f /etc/sudoers.d/wgtools
echo "[5/8] Installing systemd services (run as root)..."
cp "$APP_DIR/systemd/wgtools.service" /etc/systemd/system/wgtools.service
cp "$APP_DIR/systemd/wgtools-telegram.service" /etc/systemd/system/wgtools-telegram.service
cp "$APP_DIR/systemd/wgtools-expiry.service" /etc/systemd/system/wgtools-expiry.service
cp "$APP_DIR/systemd/wgtools-expiry.timer" /etc/systemd/system/wgtools-expiry.timer
cp "$APP_DIR/systemd/wgtools-certbot-renew.service" /etc/systemd/system/wgtools-certbot-renew.service
cp "$APP_DIR/systemd/wgtools-certbot-renew.timer" /etc/systemd/system/wgtools-certbot-renew.timer
systemctl daemon-reload
systemctl enable wgtools.service >/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" </dev/null >/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" </dev/null >/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"
+54
View File
@@ -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
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
/bin/systemctl try-restart wgtools.service
+783
View File
@@ -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 <interface>"
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
File diff suppressed because it is too large. Load diff
+25
View File
@@ -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[@]}"
+8
View File
@@ -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
+11
View File
@@ -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
+12
View File
@@ -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
+12
View File
@@ -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
+19
View File
@@ -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
+20
View File
@@ -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
+25
View File
@@ -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": {}}
+56
View File
@@ -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)
+86
View File
@@ -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()
+31
View File
@@ -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})
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more