This repository has been archived on 2026-11-15. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
WGTools-Extended/app/core/nodes.py
T
asminme affe28ad71
Wydanie WGTools-Extended / release (push) Failing after 16s
1.0.0
2026-10-30 00:35:08 +01:00

2194 lines
95 KiB
Python

from __future__ import annotations
import hashlib
import ipaddress
import json
import os
import secrets
import socket
import sqlite3
import ssl
import subprocess
import threading
import time
import urllib.parse
import uuid
from pathlib import Path
from typing import Any
from .helper import HelperError, run_helper
from .settings import DATABASE_PATH, ONLINE_THRESHOLD_SECONDS, VERSION
NODE_INTERFACE = "wgnode0"
DEFAULT_TRANSPORT_NETWORK = "10.254.240.0/24"
DEFAULT_LISTEN_PORT = 51950
JOIN_TTL_SECONDS = 15 * 60
SYNC_INTERVAL_SECONDS = 15
MAX_EXPORTED_NETWORKS = 64
MAX_CLIENT_SUMMARY = 1000
NODE_CONTROL_DIR = Path("/etc/wgtools/nodes")
NODE_CONTROL_CERT_FILE = NODE_CONTROL_DIR / "control.crt"
NODE_CONTROL_KEY_FILE = NODE_CONTROL_DIR / "control.key"
NODE_CONTROL_PROTOCOL = "wgtools-nodes-v1"
NODE_CONTROL_MAX_BYTES = 2 * 1024 * 1024
_lock = threading.RLock()
_certificate_lock = threading.RLock()
_control_status_lock = threading.RLock()
_control_active_port = 0
_control_last_error = ""
class NodeNetworkConflictError(ValueError):
"""A published network overlaps the transport network or another Node."""
code = "network_conflict"
def __init__(self, conflicts: list[dict[str, str]]):
self.conflicts = conflicts
parts: list[str] = []
for item in conflicts:
network = str(item.get("network") or "")
owner_name = str(item.get("owner_name") or "")
owner_network = str(item.get("owner_network") or "")
if item.get("owner_type") == "transport":
parts.append(f"{network} overlaps Nodes transport network {owner_network}")
else:
parts.append(f"{network} overlaps {owner_network} on node {owner_name or 'WGTools'}")
super().__init__("Nodes network conflict: " + "; ".join(parts))
def _connect() -> sqlite3.Connection:
Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DATABASE_PATH, timeout=15)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
return conn
def init_nodes_database() -> None:
with _connect() as conn:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS wg_node_state (
id INTEGER PRIMARY KEY CHECK(id=1),
data TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS wg_node_peers (
node_id TEXT PRIMARY KEY,
name TEXT NOT NULL,
public_key TEXT NOT NULL UNIQUE,
preshared_key TEXT NOT NULL,
secret TEXT NOT NULL UNIQUE,
transport_ip TEXT NOT NULL UNIQUE,
panel_url TEXT NOT NULL DEFAULT '',
version TEXT NOT NULL DEFAULT '',
exports_json TEXT NOT NULL DEFAULT '[]',
clients_json TEXT NOT NULL DEFAULT '[]',
connected_at INTEGER NOT NULL,
last_seen INTEGER NOT NULL DEFAULT 0,
last_error TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS wg_node_join_codes (
code_hash TEXT PRIMARY KEY,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS wg_node_cache (
id INTEGER PRIMARY KEY CHECK(id=1),
data TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
"""
)
def _json_load(raw: str | None, default: Any) -> Any:
try:
value = json.loads(raw or "")
return value
except Exception:
return default
def _load_state() -> dict[str, Any]:
init_nodes_database()
with _connect() as conn:
row = conn.execute("SELECT data FROM wg_node_state WHERE id=1").fetchone()
data = _json_load(row["data"] if row else None, {})
return data if isinstance(data, dict) else {}
def _save_state(data: dict[str, Any]) -> None:
init_nodes_database()
now = int(time.time())
encoded = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
with _connect() as conn:
conn.execute(
"INSERT INTO wg_node_state(id,data,updated_at) VALUES(1,?,?) "
"ON CONFLICT(id) DO UPDATE SET data=excluded.data,updated_at=excluded.updated_at",
(encoded, now),
)
def _load_cache() -> dict[str, Any]:
init_nodes_database()
with _connect() as conn:
row = conn.execute("SELECT data FROM wg_node_cache WHERE id=1").fetchone()
data = _json_load(row["data"] if row else None, {})
return data if isinstance(data, dict) else {}
def _save_cache(data: dict[str, Any]) -> None:
now = int(time.time())
encoded = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
with _connect() as conn:
conn.execute(
"INSERT INTO wg_node_cache(id,data,updated_at) VALUES(1,?,?) "
"ON CONFLICT(id) DO UPDATE SET data=excluded.data,updated_at=excluded.updated_at",
(encoded, now),
)
def _normalize_name(value: str, fallback: str = "WGTools") -> str:
text = " ".join(str(value or "").strip().split())
if not text:
text = fallback
if len(text) > 64 or any(ord(ch) < 32 for ch in text):
raise ValueError("Node name must contain 1 to 64 printable characters")
return text
def _normalize_panel_url(value: str, *, allow_empty: bool = True) -> str:
text = str(value or "").strip()
if not text and allow_empty:
return ""
if len(text) > 512:
raise ValueError("Panel URL is too long")
parsed = urllib.parse.urlsplit(text)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("Panel URL must start with http:// or https://")
path = parsed.path or "/"
if not path.endswith("/"):
path += "/"
return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, path, "", ""))
def _normalize_endpoint_host(value: str) -> str:
host = str(value or "").strip()
if not host or len(host) > 253 or any(ch.isspace() for ch in host):
raise ValueError("HUB endpoint host/domain is required")
if host.startswith("[") and host.endswith("]"):
host = host[1:-1]
return host
def _endpoint_text(host: str, port: int) -> str:
wrapped = f"[{host}]" if ":" in host and not host.startswith("[") else host
return f"{wrapped}:{int(port)}"
def _parse_endpoint(value: str, *, default_port: int = DEFAULT_LISTEN_PORT) -> tuple[str, int]:
text = str(value or "").strip()
if not text:
raise ValueError("HUB endpoint is required")
if "://" in text:
raise ValueError("Enter the HUB as host:port without http:// or https://")
host = ""
port = int(default_port)
if text.startswith("["):
end = text.find("]")
if end < 0:
raise ValueError("Invalid HUB endpoint")
host = text[1:end]
suffix = text[end + 1 :]
if suffix:
if not suffix.startswith(":") or not suffix[1:].isdigit():
raise ValueError("Invalid HUB endpoint port")
port = int(suffix[1:])
else:
# A single colon means host:port. Multiple colons are treated as a raw
# IPv6 literal and use the default port; bracket IPv6 when specifying a port.
if text.count(":") == 1:
possible_host, possible_port = text.rsplit(":", 1)
if possible_port.isdigit():
host, port = possible_host, int(possible_port)
else:
host = text
else:
host = text
host = _normalize_endpoint_host(host)
if not 1 <= port <= 65535:
raise ValueError("Invalid HUB endpoint port")
return host, port
def _normalize_networks(values: list[str] | tuple[str, ...] | None, *, label: str = "Published networks") -> list[str]:
result: list[str] = []
seen: set[str] = set()
for raw in list(values or []):
text = str(raw or "").strip()
if not text:
continue
try:
net = ipaddress.ip_network(text, strict=False)
except ValueError as exc:
raise ValueError(f"Invalid network in {label}: {text}") from exc
if net.version != 4:
raise ValueError("WGTools Nodes v1 supports IPv4 networks only")
if net.prefixlen == 0:
raise ValueError("0.0.0.0/0 cannot be published as a WGTools Node network")
canonical = str(net)
if canonical not in seen:
result.append(canonical)
seen.add(canonical)
if len(result) > MAX_EXPORTED_NETWORKS:
raise ValueError(f"Too many networks in {label}")
return result
def _run(cmd: list[str], *, input_text: str | None = None, timeout: int = 30) -> tuple[int, str, str]:
proc = subprocess.run(cmd, input=input_text, text=True, capture_output=True, timeout=timeout, check=False)
return proc.returncode, proc.stdout.strip(), proc.stderr.strip()
def _certificate_fingerprint(cert_file: Path | None = None) -> str:
cert_file = cert_file or NODE_CONTROL_CERT_FILE
try:
pem = cert_file.read_text(encoding="utf-8")
der = ssl.PEM_cert_to_DER_cert(pem)
except Exception as exc:
raise RuntimeError("Could not read WGTools Node control certificate") from exc
return hashlib.sha256(der).hexdigest()
def _ensure_control_certificate() -> tuple[Path, Path, str]:
"""Create/restore the private certificate used only by the Node control socket.
The PEM material is also kept in the SQLite Node state so WGTools full
backup/restore preserves the HUB identity pinned by already-connected spokes.
Files under /etc/wgtools/nodes are runtime copies with strict permissions.
"""
with _certificate_lock:
NODE_CONTROL_DIR.mkdir(parents=True, exist_ok=True)
state = _load_state()
saved_cert = str(state.get("control_cert_pem") or "")
saved_key = str(state.get("control_key_pem") or "")
if saved_cert and saved_key:
if not NODE_CONTROL_CERT_FILE.exists() or NODE_CONTROL_CERT_FILE.read_text(encoding="utf-8", errors="replace") != saved_cert:
NODE_CONTROL_CERT_FILE.write_text(saved_cert, encoding="utf-8")
if not NODE_CONTROL_KEY_FILE.exists() or NODE_CONTROL_KEY_FILE.read_text(encoding="utf-8", errors="replace") != saved_key:
NODE_CONTROL_KEY_FILE.write_text(saved_key, encoding="utf-8")
elif NODE_CONTROL_CERT_FILE.exists() and NODE_CONTROL_KEY_FILE.exists():
saved_cert = NODE_CONTROL_CERT_FILE.read_text(encoding="utf-8")
saved_key = NODE_CONTROL_KEY_FILE.read_text(encoding="utf-8")
state["control_cert_pem"] = saved_cert
state["control_key_pem"] = saved_key
_save_state(state)
else:
cert_tmp = NODE_CONTROL_CERT_FILE.with_suffix(".crt.tmp")
key_tmp = NODE_CONTROL_KEY_FILE.with_suffix(".key.tmp")
cert_tmp.unlink(missing_ok=True)
key_tmp.unlink(missing_ok=True)
rc, out, err = _run(
[
"openssl", "req", "-x509", "-newkey", "rsa:2048", "-sha256", "-nodes",
"-days", "3650", "-subj", "/CN=WGTools Node Control",
"-keyout", str(key_tmp), "-out", str(cert_tmp),
],
timeout=30,
)
if rc != 0 or not cert_tmp.exists() or not key_tmp.exists():
cert_tmp.unlink(missing_ok=True)
key_tmp.unlink(missing_ok=True)
raise RuntimeError(err or out or "Could not generate WGTools Node control certificate")
os.chmod(key_tmp, 0o600)
os.chmod(cert_tmp, 0o644)
key_tmp.replace(NODE_CONTROL_KEY_FILE)
cert_tmp.replace(NODE_CONTROL_CERT_FILE)
saved_cert = NODE_CONTROL_CERT_FILE.read_text(encoding="utf-8")
saved_key = NODE_CONTROL_KEY_FILE.read_text(encoding="utf-8")
state["control_cert_pem"] = saved_cert
state["control_key_pem"] = saved_key
_save_state(state)
os.chmod(NODE_CONTROL_KEY_FILE, 0o600)
os.chmod(NODE_CONTROL_CERT_FILE, 0o644)
return NODE_CONTROL_CERT_FILE, NODE_CONTROL_KEY_FILE, _certificate_fingerprint()
def _join_code_fingerprint(code: str) -> str:
text = str(code or "").strip()
prefix = "WGTOOLS-NODE-v1."
if not text.startswith(prefix):
raise ValueError("Invalid WGTools Node connection code")
parts = text[len(prefix):].split(".", 1)
if len(parts) != 2 or len(parts[0]) != 64 or any(ch not in "0123456789abcdefABCDEF" for ch in parts[0]) or not parts[1]:
raise ValueError("Invalid WGTools Node connection code")
return parts[0].lower()
def _recv_control_json(sock: ssl.SSLSocket) -> dict[str, Any]:
chunks: list[bytes] = []
total = 0
while True:
chunk = sock.recv(min(65536, NODE_CONTROL_MAX_BYTES - total + 1))
if not chunk:
break
chunks.append(chunk)
total += len(chunk)
if total > NODE_CONTROL_MAX_BYTES:
raise ValueError("WGTools Node control message is too large")
if b"\n" in chunk:
break
raw = b"".join(chunks).split(b"\n", 1)[0]
if not raw:
raise ValueError("Empty WGTools Node control message")
try:
value = json.loads(raw.decode("utf-8"))
except Exception as exc:
raise ValueError("Invalid WGTools Node control message") from exc
if not isinstance(value, dict):
raise ValueError("Invalid WGTools Node control message")
return value
def _send_control_json(sock: ssl.SSLSocket, payload: dict[str, Any]) -> None:
encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n"
if len(encoded) > NODE_CONTROL_MAX_BYTES:
raise ValueError("WGTools Node control response is too large")
sock.sendall(encoded)
def _control_json(
host: str,
port: int,
payload: dict[str, Any],
*,
expected_fingerprint: str,
timeout: int = 12,
) -> dict[str, Any]:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
deadline = time.monotonic() + max(1, int(timeout))
last_error: Exception | None = None
while time.monotonic() < deadline:
remaining = max(0.5, deadline - time.monotonic())
try:
with socket.create_connection((host, int(port)), timeout=min(3.0, remaining)) as raw:
raw.settimeout(remaining)
with context.wrap_socket(raw, server_hostname=host) as tls:
certificate = tls.getpeercert(binary_form=True)
actual = hashlib.sha256(certificate or b"").hexdigest()
if not certificate or not secrets.compare_digest(actual, str(expected_fingerprint or "").lower()):
raise RuntimeError("HUB identity does not match the connection code")
_send_control_json(tls, {"protocol": NODE_CONTROL_PROTOCOL, **payload})
result = _recv_control_json(tls)
if not result.get("ok"):
exc = RuntimeError(str(result.get("error") or "Invalid HUB control response"))
if result.get("error_code"):
setattr(exc, "error_code", str(result.get("error_code")))
if isinstance(result.get("conflicts"), list):
setattr(exc, "conflicts", result.get("conflicts"))
raise exc
return result
except RuntimeError:
# Identity or application errors are deterministic; retrying them
# would only burn the full timeout and could consume a one-time code.
raise
except Exception as exc:
last_error = exc
if time.monotonic() >= deadline:
break
time.sleep(min(0.35, max(0.05, deadline - time.monotonic())))
raise RuntimeError(f"Could not reach WGTools HUB control service: {last_error or 'connection timed out'}") from last_error
def _wg_available() -> bool:
return Path("/usr/bin/wg").exists() or subprocess.run(["sh", "-lc", "command -v wg >/dev/null 2>&1"], check=False).returncode == 0
def _ensure_identity(state: dict[str, Any]) -> dict[str, Any]:
if state.get("private_key") and state.get("public_key"):
return state
if not _wg_available():
raise RuntimeError("WireGuard is not installed. Install WireGuard before enabling WGTools Nodes.")
rc, private_key, err = _run(["wg", "genkey"])
if rc != 0 or not private_key:
raise RuntimeError(err or "Could not generate WGTools Node private key")
rc, public_key, err = _run(["wg", "pubkey"], input_text=private_key + "\n")
if rc != 0 or not public_key:
raise RuntimeError(err or "Could not generate WGTools Node public key")
state["private_key"] = private_key
state["public_key"] = public_key
state.setdefault("node_id", uuid.uuid4().hex)
_save_state(state)
return state
def _interface_inventory() -> dict[str, Any]:
try:
data = run_helper("interfaces_list")
except HelperError:
return {"interfaces": []}
return data if isinstance(data, dict) else {"interfaces": []}
def _local_policy_tables() -> list[str]:
values: list[str] = []
for item in _interface_inventory().get("interfaces") or []:
if not item.get("configured"):
continue
value = item.get("policy_table")
if value in (None, ""):
continue
text = str(value)
if text.isdigit() and text not in values:
values.append(text)
return values
def _automatic_exports(inventory: dict[str, Any] | None = None) -> list[dict[str, str]]:
"""Networks WGTools can derive from its managed WireGuard configuration."""
result: list[dict[str, str]] = []
seen: set[str] = set()
def add(raw: Any, kind: str, label: str) -> None:
text = str(raw or "").strip()
if not text:
return
try:
net = ipaddress.ip_network(text, strict=False)
except ValueError:
return
if net.version != 4 or net.prefixlen == 0:
return
canonical = str(net)
if canonical in seen or len(result) >= MAX_EXPORTED_NETWORKS:
return
seen.add(canonical)
result.append({"network": canonical, "kind": kind, "label": label or canonical})
inventory = inventory or _interface_inventory()
for item in inventory.get("interfaces") or []:
if not item.get("configured"):
continue
interface_label = str(item.get("display_name") or item.get("name") or "WireGuard")
add(item.get("vpn_network"), "vpn", interface_label)
for raw in item.get("remote_networks") or []:
add(raw, "site_to_site", interface_label)
return result
def _direct_private_networks(
state: dict[str, Any] | None = None,
*,
inventory: dict[str, Any] | None = None,
) -> list[dict[str, str]]:
"""Conservatively discover directly-routed private LANs for the picker.
These networks are *options*, not automatic exports. This lets the connect
dialog offer a local LAN such as 10.10.10.0/24 without silently publishing
Docker/Node/internal routes.
"""
state = state or _load_state()
transport_raw = str(state.get("transport_network") or DEFAULT_TRANSPORT_NETWORK)
try:
transport = ipaddress.ip_network(transport_raw, strict=False)
except ValueError:
transport = ipaddress.ip_network(DEFAULT_TRANSPORT_NETWORK)
rc, out, _err = _run(["ip", "-4", "route", "show", "scope", "link"], timeout=5)
if rc != 0:
return []
result: list[dict[str, str]] = []
seen: set[str] = set()
skipped_prefixes = ("docker", "br-", "veth", "virbr", "lxcbr", "cni", "flannel", "podman")
inventory = inventory or _interface_inventory()
wireguard_devices = {
str(item.get("name") or "").strip()
for item in (inventory.get("interfaces") or [])
if item.get("configured") and str(item.get("name") or "").strip()
}
for line in out.splitlines():
parts = line.split()
if not parts or parts[0] in {"default", "broadcast", "local", "unreachable", "blackhole", "prohibit", "throw"}:
continue
try:
net = ipaddress.ip_network(parts[0], strict=False)
except ValueError:
continue
if net.version != 4 or net.prefixlen == 0 or net.prefixlen > 30 or not net.is_private or net.is_link_local:
continue
dev = parts[parts.index("dev") + 1] if "dev" in parts and parts.index("dev") + 1 < len(parts) else ""
# WireGuard routes are already represented by _automatic_exports().
# Treating them as direct LAN candidates makes an old/current VPN pool
# look like a local LAN and hides pool-change warnings.
if dev == NODE_INTERFACE or dev == "lo" or dev in wireguard_devices or dev.startswith(skipped_prefixes):
continue
if net.overlaps(transport):
continue
canonical = str(net)
if canonical in seen or len(result) >= MAX_EXPORTED_NETWORKS:
continue
seen.add(canonical)
result.append({"network": canonical, "kind": "custom", "label": f"LAN · {dev}" if dev else canonical})
return result
def _available_publish_networks(
state: dict[str, Any] | None = None,
*,
inventory: dict[str, Any] | None = None,
direct_networks: list[dict[str, str]] | None = None,
include_remembered: bool = True,
) -> list[dict[str, str]]:
"""Return all currently known networks that the user may choose to publish."""
state = state or _load_state()
result: list[dict[str, str]] = []
seen: set[str] = set()
def add_item(item: dict[str, str]) -> None:
raw = str(item.get("network") or "").strip()
if not raw:
return
try:
canonical = str(ipaddress.ip_network(raw, strict=False))
except ValueError:
return
if canonical in seen or len(result) >= MAX_EXPORTED_NETWORKS:
return
seen.add(canonical)
result.append({**item, "network": canonical})
for item in _automatic_exports(inventory):
add_item(item)
if direct_networks is None:
direct_networks = _direct_private_networks(state, inventory=inventory)
for item in direct_networks:
add_item(item)
if include_remembered:
remembered = list(state.get("published_networks") or []) + list(state.get("extra_networks") or [])
for raw in _normalize_networks(remembered, label="Published networks"):
add_item({"network": raw, "kind": "custom", "label": raw})
return result
def _selection_legacy_extras(selected: list[str]) -> list[str]:
automatic = {item["network"] for item in _automatic_exports()}
return [network for network in selected if network not in automatic]
def _apply_publication_payload(state: dict[str, Any], payload: dict[str, Any]) -> None:
"""Apply the v0.20.34 explicit publication allow-list with API fallback."""
if payload.get("published_networks") is not None:
selected = _normalize_networks(payload.get("published_networks") or [], label="Published networks")
state["published_networks"] = selected
# Keep non-WG-derived entries in the old key as a rollback-friendly
# compatibility copy. v0.20.34 itself uses published_networks.
state["extra_networks"] = _selection_legacy_extras(selected)
elif "published_networks" not in state:
state["extra_networks"] = _normalize_networks(payload.get("extra_networks") or [], label="Additional published networks")
def _remember_current_detection(
state: dict[str, Any],
*,
inventory: dict[str, Any] | None = None,
direct_networks: list[dict[str, str]] | None = None,
) -> list[dict[str, str]]:
"""Remember the local networks visible when the publication list was accepted.
Later discovery changes are surfaced to the user instead of silently
modifying the explicit Nodes allow-list.
"""
inventory = inventory or _interface_inventory()
if direct_networks is None:
direct_networks = _direct_private_networks(state, inventory=inventory)
automatic = _automatic_exports(inventory)
detected = _available_publish_networks(
state,
inventory=inventory,
direct_networks=direct_networks,
include_remembered=False,
)
# Keep typed baselines. A WireGuard VPN/Site-to-Site network must not be
# confused with a directly routed LAN when routes change underneath Nodes.
state["publication_seen_automatic_networks"] = [item["network"] for item in automatic]
state["publication_seen_direct_networks"] = [item["network"] for item in direct_networks]
# Compatibility with v0.20.44 and older state.
state["publication_seen_networks"] = [item["network"] for item in detected]
return detected
def _network_detection_changes(
state: dict[str, Any],
*,
automatic_networks: list[str],
direct_networks: list[str],
detected_networks: list[str],
) -> dict[str, Any]:
"""Compare current discovery with the last user-confirmed baseline."""
has_typed_baseline = (
"publication_seen_automatic_networks" in state
or "publication_seen_direct_networks" in state
)
if has_typed_baseline:
seen_automatic = _normalize_networks(
state.get("publication_seen_automatic_networks") or [],
label="Previously detected WireGuard networks",
)
seen_direct = _normalize_networks(
state.get("publication_seen_direct_networks") or [],
label="Previously detected LAN networks",
)
auto_seen_set, auto_current_set = set(seen_automatic), set(automatic_networks)
direct_seen_set, direct_current_set = set(seen_direct), set(direct_networks)
added_automatic = [net for net in automatic_networks if net not in auto_seen_set]
removed_automatic = [net for net in seen_automatic if net not in auto_current_set]
added_direct = [net for net in direct_networks if net not in direct_seen_set]
removed_direct = [net for net in seen_direct if net not in direct_current_set]
added = list(dict.fromkeys(added_automatic + added_direct))
removed = list(dict.fromkeys(removed_automatic + removed_direct))
else:
seen_networks = _normalize_networks(
state.get("publication_seen_networks") or [], label="Previously detected networks"
)
seen_set, current_set = set(seen_networks), set(detected_networks)
added = [net for net in detected_networks if net not in seen_set]
removed = [net for net in seen_networks if net not in current_set]
added_automatic = list(added)
removed_automatic = list(removed)
added_direct = []
removed_direct = []
return {
"changed": bool(added or removed),
"added": added,
"removed": removed,
"automatic_added": added_automatic,
"automatic_removed": removed_automatic,
"direct_added": added_direct,
"direct_removed": removed_direct,
}
def _vpn_pool_publication_mismatch(
state: dict[str, Any],
*,
inventory: dict[str, Any],
direct_networks: list[dict[str, str]],
) -> dict[str, Any]:
"""Detect a managed VPN pool that changed while Nodes still publishes the old pool.
This is intentionally separate from generic discovery drift. A user may
deliberately omit the current VPN pool from the Nodes allow-list, so that
alone is not an error. We only flag a pool-change mismatch when the
published list still contains a network that was previously observed as a
managed/local candidate and that candidate disappeared while a current VPN
pool is missing from the publication list.
The legacy publication_seen_networks key is used as a migration hint for
v0.20.44/v0.20.45 state so an already stale 10.0.1.0/24 -> 10.0.2.0/24
installation is detected immediately after upgrade.
"""
selected = _normalize_networks(state.get("published_networks") or [], label="Published networks")
if not selected:
return {"changed": False, "published_old": [], "current_vpn": []}
automatic = _automatic_exports(inventory)
current_vpn = [item["network"] for item in automatic if item.get("kind") == "vpn"]
current_auto = {item["network"] for item in automatic}
current_direct = {item.get("network") for item in direct_networks if item.get("network")}
selected_set = set(selected)
missing_current = [net for net in current_vpn if net not in selected_set]
if not missing_current:
return {"changed": False, "published_old": [], "current_vpn": []}
historical = _normalize_networks(
state.get("publication_seen_automatic_networks")
or state.get("publication_seen_networks")
or [],
label="Previously detected networks",
)
historical_set = set(historical)
stale = [
net for net in selected
if net in historical_set and net not in current_auto and net not in current_direct
]
if not stale:
return {"changed": False, "published_old": [], "current_vpn": []}
return {
"changed": True,
"published_old": stale,
"current_vpn": missing_current,
}
def _candidate_network_conflicts(
state: dict[str, Any],
candidate_exports: list[dict[str, str]],
*,
peers: list[dict[str, Any]] | None = None,
local_exports: list[dict[str, str]] | None = None,
exclude_node_id: str = "",
candidate_owner_id: str = "candidate",
) -> list[dict[str, str]]:
"""Return detailed overlap conflicts for a proposed publication list."""
peers = peers if peers is not None else _peer_rows()
owners: list[tuple[str, str, str, ipaddress.IPv4Network]] = []
if local_exports is not None and candidate_owner_id != "local":
local_name = _normalize_name(str(state.get("node_name") or "HUB"), "HUB")
local_id = str(state.get("node_id") or "hub")
for item in local_exports:
raw = str(item.get("network") if isinstance(item, dict) else item or "").strip()
try:
owners.append((local_id, local_name, raw, ipaddress.ip_network(raw, strict=False)))
except ValueError:
continue
for peer in peers:
node_id = str(peer.get("node_id") or "")
if node_id and node_id == exclude_node_id:
continue
owner_name = str(peer.get("name") or node_id or "WGTools")
for item in peer.get("exports") or []:
raw = str(item.get("network") if isinstance(item, dict) else item or "").strip()
try:
owners.append((node_id, owner_name, raw, ipaddress.ip_network(raw, strict=False)))
except ValueError:
continue
transport = _transport_network(state)
conflicts: list[dict[str, str]] = []
seen: set[tuple[str, str, str]] = set()
for item in candidate_exports:
raw = str(item.get("network") if isinstance(item, dict) else item or "").strip()
try:
net = ipaddress.ip_network(raw, strict=False)
except ValueError:
continue
if net.overlaps(transport):
key = (str(net), "transport", str(transport))
if key not in seen:
seen.add(key)
conflicts.append({
"network": str(net),
"owner_type": "transport",
"owner_name": "WGTools Nodes",
"owner_network": str(transport),
})
for owner_id, owner_name, owner_raw, owner_net in owners:
if owner_id == candidate_owner_id:
continue
if net.overlaps(owner_net):
key = (str(net), owner_id or owner_name, str(owner_net))
if key in seen:
continue
seen.add(key)
conflicts.append({
"network": str(net),
"owner_type": "node",
"owner_name": owner_name,
"owner_network": str(owner_net),
"owner_id": owner_id,
})
return conflicts
def _raise_network_conflicts(conflicts: list[dict[str, str]]) -> None:
if conflicts:
raise NodeNetworkConflictError(conflicts)
def _local_exports(
state: dict[str, Any] | None = None,
*,
inventory: dict[str, Any] | None = None,
available_networks: list[dict[str, str]] | None = None,
) -> list[dict[str, str]]:
"""Return the explicit network allow-list published into the Nodes fabric.
New configurations store ``published_networks``: the connect/HUB dialog is
pre-filled with all detected VPN, Site-to-Site and local LAN candidates and
the user removes anything that should stay private. Legacy installations
without that key keep the v0.20.32 behaviour (all WG-derived networks plus
``extra_networks``) until their Node settings are saved once.
"""
state = state or _load_state()
if "published_networks" in state:
selected = _normalize_networks(state.get("published_networks") or [], label="Published networks")
if available_networks is None:
available_networks = _available_publish_networks(state, inventory=inventory)
candidates = {item["network"]: item for item in available_networks}
result: list[dict[str, str]] = []
for network in selected[:MAX_EXPORTED_NETWORKS]:
item = candidates.get(network) or {"network": network, "kind": "custom", "label": network}
result.append(item)
return result
# Backward compatibility for Nodes created before explicit publication
# selection existed. Do not add newly discovered host LANs silently.
result = list(_automatic_exports(inventory))
seen = {item["network"] for item in result}
for raw in _normalize_networks(state.get("extra_networks") or [], label="Additional published networks"):
if raw in seen or len(result) >= MAX_EXPORTED_NETWORKS:
continue
seen.add(raw)
result.append({"network": raw, "kind": "custom", "label": raw})
return result
def _local_clients(inventory: dict[str, Any] | None = None) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
inventory = inventory or _interface_inventory()
for item in inventory.get("interfaces") or []:
iface = str(item.get("name") or "").strip()
if not iface or not item.get("configured"):
continue
try:
snap = run_helper("snapshot", {"view": "peers"}, interface=iface)
except HelperError:
continue
for peer in snap.get("peers") or []:
latest = int(peer.get("latest_handshake") or 0)
remote_networks = list(peer.get("remote_networks") or [])
result.append({
"name": str(peer.get("name") or "Unnamed")[:64],
"interface": iface,
"vpn_address": str(peer.get("vpn_address") or "")[:64],
"type": "site_to_site" if remote_networks else "client",
"online": bool(latest and time.time() - latest <= ONLINE_THRESHOLD_SECONDS),
"last_seen": latest,
})
if len(result) >= MAX_CLIENT_SUMMARY:
return result
return result
def local_summary(
state: dict[str, Any] | None = None,
*,
inventory: dict[str, Any] | None = None,
exports: list[dict[str, str]] | None = None,
clients: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
state = state or _load_state()
name = _normalize_name(str(state.get("node_name") or socket.gethostname() or "WGTools"), "WGTools")
return {
"node_id": str(state.get("node_id") or ""),
"name": name,
"role": str(state.get("mode") or "none"),
"version": VERSION,
"transport_ip": str(state.get("transport_ip") or ""),
"panel_url": str(state.get("panel_url") or ""),
"exports": exports if exports is not None else _local_exports(state, inventory=inventory),
"clients": clients if clients is not None else _local_clients(inventory),
"last_seen": int(time.time()),
}
def _peer_rows() -> list[dict[str, Any]]:
init_nodes_database()
with _connect() as conn:
rows = conn.execute("SELECT * FROM wg_node_peers ORDER BY connected_at,node_id").fetchall()
result: list[dict[str, Any]] = []
for row in rows:
item = dict(row)
item["exports"] = _json_load(item.pop("exports_json", "[]"), [])
item["clients"] = _json_load(item.pop("clients_json", "[]"), [])
result.append(item)
return result
def _peer_by_id(node_id: str) -> dict[str, Any] | None:
for item in _peer_rows():
if item.get("node_id") == node_id:
return item
return None
def _peer_by_public_key(public_key: str) -> dict[str, Any] | None:
for item in _peer_rows():
if str(item.get("public_key") or "") == str(public_key or ""):
return item
return None
def _write_peer_record(peer: dict[str, Any]) -> None:
"""Restore/insert one peer row from a normalized _peer_rows() record."""
with _connect() as conn:
conn.execute(
"INSERT OR REPLACE INTO wg_node_peers(node_id,name,public_key,preshared_key,secret,transport_ip,panel_url,version,exports_json,clients_json,connected_at,last_seen,last_error) "
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
peer.get("node_id"), peer.get("name"), peer.get("public_key"), peer.get("preshared_key"), peer.get("secret"),
peer.get("transport_ip"), peer.get("panel_url") or "", peer.get("version") or "",
json.dumps(peer.get("exports") or [], ensure_ascii=False), json.dumps(peer.get("clients") or [], ensure_ascii=False),
int(peer.get("connected_at") or time.time()), int(peer.get("last_seen") or 0), str(peer.get("last_error") or ""),
),
)
def _transport_network(state: dict[str, Any]) -> ipaddress.IPv4Network:
raw = str(state.get("transport_network") or DEFAULT_TRANSPORT_NETWORK)
try:
net = ipaddress.ip_network(raw, strict=False)
except ValueError as exc:
raise ValueError("Invalid Node transport network") from exc
if net.version != 4 or net.prefixlen > 29 or net.prefixlen < 16:
raise ValueError("Node transport network must be an IPv4 /16 to /29 network")
if not net.is_private:
raise ValueError("Node transport network must use private IPv4 addressing")
if net.num_addresses < 8:
raise ValueError("Node transport network is too small")
return net
def _assign_transport_ip(state: dict[str, Any]) -> str:
net = _transport_network(state)
used = {str(item.get("transport_ip") or "") for item in _peer_rows()}
hosts = net.hosts()
try:
next(hosts) # hub owns the first host
except StopIteration as exc:
raise RuntimeError("Node transport network is too small") from exc
for ip in hosts:
if str(ip) not in used:
return str(ip)
raise RuntimeError("Node transport network has no free addresses")
def _network_conflicts(
state: dict[str, Any],
peers: list[dict[str, Any]],
*,
local: dict[str, Any] | None = None,
) -> tuple[dict[str, list[str]], dict[str, list[str]]]:
owners: list[tuple[str, str, ipaddress.IPv4Network]] = []
local = local or local_summary(state)
local_id = str(local.get("node_id") or "hub")
for exp in local.get("exports") or []:
try:
owners.append((local_id, str(exp.get("network") or ""), ipaddress.ip_network(str(exp.get("network") or ""), strict=False)))
except ValueError:
continue
for peer in peers:
node_id = str(peer.get("node_id") or "")
for exp in peer.get("exports") or []:
raw = str(exp.get("network") if isinstance(exp, dict) else exp)
try:
owners.append((node_id, raw, ipaddress.ip_network(raw, strict=False)))
except ValueError:
continue
conflicts: dict[str, list[str]] = {}
valid: dict[str, list[str]] = {}
transport = _transport_network(state)
for node_id, raw, net in owners:
bad = net.overlaps(transport)
if not bad:
for other_id, other_raw, other in owners:
if (other_id, other_raw) == (node_id, raw):
continue
if node_id != other_id and net.overlaps(other):
bad = True
break
if bad:
conflicts.setdefault(node_id, []).append(raw)
else:
valid.setdefault(node_id, []).append(raw)
for mapping in (conflicts, valid):
for key in list(mapping):
mapping[key] = sorted(set(mapping[key]), key=lambda x: (ipaddress.ip_network(x).network_address, ipaddress.ip_network(x).prefixlen))
return conflicts, valid
def _node_runtime() -> dict[str, dict[str, Any]]:
if not _wg_available():
return {}
rc, out, _ = _run(["wg", "show", NODE_INTERFACE, "dump"])
if rc != 0 or not out:
return {}
lines = out.splitlines()
result: dict[str, dict[str, Any]] = {}
for line in lines[1:]:
parts = line.split("\t")
if len(parts) < 8:
continue
pub = parts[0]
try:
latest = int(parts[4] or 0)
rx = int(parts[5] or 0)
tx = int(parts[6] or 0)
except ValueError:
latest, rx, tx = 0, 0, 0
result[pub] = {"endpoint": parts[2], "latest_handshake": latest, "rx_bytes": rx, "tx_bytes": tx}
return result
def _topology(
state: dict[str, Any] | None = None,
*,
local: dict[str, Any] | None = None,
) -> dict[str, Any]:
state = state or _load_state()
mode = str(state.get("mode") or "none")
if mode == "hub":
peers = _peer_rows()
hub = local or local_summary(state)
conflicts, valid = _network_conflicts(state, peers, local=hub)
runtime = _node_runtime()
hub["conflicts"] = conflicts.get(str(hub.get("node_id") or "hub"), [])
hub["valid_exports"] = valid.get(str(hub.get("node_id") or "hub"), [])
nodes = [hub]
now = int(time.time())
for peer in peers:
rt = runtime.get(str(peer.get("public_key") or ""), {})
latest = max(int(peer.get("last_seen") or 0), int(rt.get("latest_handshake") or 0))
clients = peer.get("clients") if isinstance(peer.get("clients"), list) else []
node_id = str(peer.get("node_id") or "")
handshake = int(rt.get("latest_handshake") or 0)
control_seen = int(peer.get("last_seen") or 0)
freshness = max(45, SYNC_INTERVAL_SECONDS * 4)
nodes.append({
"node_id": node_id,
"name": peer.get("name"),
"role": "spoke",
"version": peer.get("version"),
"transport_ip": peer.get("transport_ip"),
"panel_url": peer.get("panel_url"),
"exports": peer.get("exports") or [],
"clients": clients,
"last_seen": latest,
"last_handshake": handshake,
"control_last_seen": control_seen,
"tunnel_online": bool(handshake and now - handshake <= freshness),
"control_online": bool(control_seen and now - control_seen <= freshness),
"online": bool(handshake and now - handshake <= freshness),
"endpoint": rt.get("endpoint") or "",
"rx_bytes": int(rt.get("rx_bytes") or 0),
"tx_bytes": int(rt.get("tx_bytes") or 0),
"conflicts": conflicts.get(node_id, []),
"valid_exports": valid.get(node_id, []),
"last_error": peer.get("last_error") or "",
})
return {"generated_at": now, "hub_id": hub.get("node_id"), "nodes": nodes}
cache = _load_cache()
if isinstance(cache.get("topology"), dict):
return cache["topology"]
return {"generated_at": int(time.time()), "hub_id": "", "nodes": []}
def _remote_routes_for_spoke(state: dict[str, Any], topology: dict[str, Any]) -> list[str]:
own_id = str(state.get("node_id") or "")
result: list[str] = []
for node in topology.get("nodes") or []:
if str(node.get("node_id") or "") == own_id:
continue
for raw in node.get("valid_exports") or []:
if raw not in result:
result.append(str(raw))
return result
def _local_service_egress_networks(state: dict[str, Any], topology: dict[str, Any] | None = None) -> list[str]:
"""Networks where Node transport addresses need a local return-path helper.
A device in a published LAN normally has no route back to the internal Node
transport network. We therefore NAT only traffic whose *source* is the
Node transport network and whose *destination* is a network published by
this WGTools instance. Site-to-site LAN traffic keeps its original source
address and is not affected by these rules.
"""
own_id = str(state.get("node_id") or "")
if topology:
for node in topology.get("nodes") or []:
if str(node.get("node_id") or "") != own_id:
continue
values = []
for raw in node.get("valid_exports") or []:
text = str(raw or "").strip()
if text and text not in values:
values.append(text)
return values
transport = _transport_network(state)
result: list[str] = []
for item in _local_exports(state):
raw = str(item.get("network") or "").strip()
if not raw:
continue
try:
network = ipaddress.ip_network(raw, strict=False)
except ValueError:
continue
if network.version != 4 or network.overlaps(transport):
continue
canonical = str(network)
if canonical not in result:
result.append(canonical)
return result
def _remote_vpn_source_networks(state: dict[str, Any], topology: dict[str, Any] | None = None) -> list[str]:
"""Return valid VPN client pools published by other Nodes.
Only remote exports explicitly typed as ``vpn`` are selected. Routed LAN
and Site-to-Site sources keep their original addresses end to end.
"""
topology = topology or _topology(state)
own_id = str(state.get("node_id") or "")
result: list[str] = []
for node in topology.get("nodes") or []:
if str(node.get("node_id") or "") == own_id:
continue
valid = {str(raw or "").strip() for raw in node.get("valid_exports") or []}
for item in node.get("exports") or []:
if not isinstance(item, dict) or str(item.get("kind") or "") != "vpn":
continue
raw = str(item.get("network") or "").strip()
if raw not in valid:
continue
try:
canonical = str(ipaddress.ip_network(raw, strict=False))
except ValueError:
continue
if canonical not in result:
result.append(canonical)
return result
def _config_text(state: dict[str, Any], topology: dict[str, Any] | None = None) -> str:
mode = str(state.get("mode") or "none")
if mode not in {"hub", "spoke"}:
raise ValueError("WGTools Nodes is not configured")
private_key = str(state.get("private_key") or "")
if not private_key:
raise RuntimeError("WGTools Node private key is missing")
transport = _transport_network(state)
lines = ["# Managed by WGTools Nodes. Do not edit manually.", "[Interface]"]
if mode == "hub":
address = str(state.get("transport_ip") or next(transport.hosts()))
lines += [f"Address = {address}/{transport.prefixlen}", f"ListenPort = {int(state.get('listen_port') or DEFAULT_LISTEN_PORT)}"]
else:
address = str(state.get("transport_ip") or "")
if not address:
raise RuntimeError("Spoke transport address is missing")
lines += [f"Address = {address}/32"]
lines += [f"PrivateKey = {private_key}", "SaveConfig = false"]
lines += [
"PostUp = sysctl -w net.ipv4.ip_forward=1",
f"PostUp = iptables -C FORWARD -i {NODE_INTERFACE} -j ACCEPT 2>/dev/null || iptables -A FORWARD -i {NODE_INTERFACE} -j ACCEPT",
f"PostUp = iptables -C FORWARD -o {NODE_INTERFACE} -j ACCEPT 2>/dev/null || iptables -A FORWARD -o {NODE_INTERFACE} -j ACCEPT",
f"PostDown = iptables -D FORWARD -i {NODE_INTERFACE} -j ACCEPT 2>/dev/null || true",
f"PostDown = iptables -D FORWARD -o {NODE_INTERFACE} -j ACCEPT 2>/dev/null || true",
]
# Keep Node-service NAT in a dedicated chain. Besides keeping the user's
# POSTROUTING table tidy, this makes config changes safe: the chain is
# rebuilt on every wgnode0 start, so removed published networks cannot
# leave stale MASQUERADE rules behind.
service_nat_chain = "WGTOOLS-NODES-NAT"
service_nat_comment = "wgtools-nodes-service-egress"
transport_source = str(transport)
lines += [
f"PostUp = iptables -t nat -N {service_nat_chain} 2>/dev/null || true",
f"PostUp = iptables -t nat -F {service_nat_chain}",
f"PostUp = iptables -t nat -C POSTROUTING -s {transport_source} -m comment --comment {service_nat_comment} -j {service_nat_chain} 2>/dev/null || iptables -t nat -A POSTROUTING -s {transport_source} -m comment --comment {service_nat_comment} -j {service_nat_chain}",
]
for raw in _local_service_egress_networks(state, topology):
lines.append(f"PostUp = iptables -t nat -A {service_nat_chain} -d {raw} -j MASQUERADE")
lines += [
f"PostDown = iptables -t nat -D POSTROUTING -s {transport_source} -m comment --comment {service_nat_comment} -j {service_nat_chain} 2>/dev/null || true",
f"PostDown = iptables -t nat -F {service_nat_chain} 2>/dev/null || true",
f"PostDown = iptables -t nat -X {service_nat_chain} 2>/dev/null || true",
]
# A normal WG client on a remote Node arrives with an address from that
# Node's VPN pool (for example 10.0.7.0/24). A LAN device published here
# normally has no return route to that remote client pool. Apply a narrow
# return-path NAT only for remote VPN pools -> locally published networks.
# Site-to-Site and custom LAN sources remain routed without NAT.
client_nat_chain = "WGTOOLS-NODES-CLIENT-NAT"
client_nat_comment = "wgtools-nodes-client-egress"
local_destinations = _local_service_egress_networks(state, topology)
remote_vpn_sources = _remote_vpn_source_networks(state, topology)
lines += [
f"PostUp = iptables -t nat -N {client_nat_chain} 2>/dev/null || true",
f"PostUp = iptables -t nat -F {client_nat_chain}",
f"PostUp = iptables -t nat -C POSTROUTING -m comment --comment {client_nat_comment} -j {client_nat_chain} 2>/dev/null || iptables -t nat -A POSTROUTING -m comment --comment {client_nat_comment} -j {client_nat_chain}",
]
for source in remote_vpn_sources:
for destination in local_destinations:
lines.append(f"PostUp = iptables -t nat -A {client_nat_chain} -s {source} -d {destination} -j MASQUERADE")
lines += [
f"PostDown = iptables -t nat -D POSTROUTING -m comment --comment {client_nat_comment} -j {client_nat_chain} 2>/dev/null || true",
f"PostDown = iptables -t nat -F {client_nat_chain} 2>/dev/null || true",
f"PostDown = iptables -t nat -X {client_nat_chain} 2>/dev/null || true",
]
if mode == "hub":
peers = _peer_rows()
_conflicts, valid = _network_conflicts(state, peers)
local_id = str(state.get("node_id") or "")
remote_networks: list[str] = []
for peer in peers:
remote_networks.extend(valid.get(str(peer.get("node_id") or ""), []))
for table in _local_policy_tables():
for raw in sorted(set(remote_networks)):
lines.append(f"PostUp = ip route replace {raw} dev {NODE_INTERFACE} table {table}")
lines.append(f"PostDown = ip route del {raw} dev {NODE_INTERFACE} table {table} 2>/dev/null || true")
for peer in peers:
allowed = [f"{peer['transport_ip']}/32"] + valid.get(str(peer.get("node_id") or ""), [])
lines += ["", f"# ---node:{peer['node_id']}---", "[Peer]", f"PublicKey = {peer['public_key']}", f"PresharedKey = {peer['preshared_key']}", f"AllowedIPs = {','.join(allowed)}"]
else:
if topology is None:
topology = _topology(state)
remote_routes = _remote_routes_for_spoke(state, topology)
for table in _local_policy_tables():
for raw in remote_routes:
lines.append(f"PostUp = ip route replace {raw} dev {NODE_INTERFACE} table {table}")
lines.append(f"PostDown = ip route del {raw} dev {NODE_INTERFACE} table {table} 2>/dev/null || true")
allowed = [str(transport)] + remote_routes
lines += [
"",
"# ---WGTools HUB---",
"[Peer]",
f"PublicKey = {state.get('hub_public_key')}",
f"PresharedKey = {state.get('preshared_key')}",
f"AllowedIPs = {','.join(dict.fromkeys(allowed))}",
f"Endpoint = {_endpoint_text(str(state.get('hub_endpoint_host') or ''), int(state.get('hub_endpoint_port') or DEFAULT_LISTEN_PORT))}",
"PersistentKeepalive = 25",
]
return "\n".join(lines).rstrip() + "\n"
def _apply_config(state: dict[str, Any], topology: dict[str, Any] | None = None) -> dict[str, Any]:
text = _config_text(state, topology)
path = Path("/etc/wireguard") / f"{NODE_INTERFACE}.conf"
path.parent.mkdir(parents=True, exist_ok=True)
old = path.read_text(encoding="utf-8") if path.exists() else None
if old is not None and not old.startswith("# Managed by WGTools Nodes."):
raise RuntimeError(f"{NODE_INTERFACE}.conf already exists and is not managed by WGTools Nodes")
if old == text:
if subprocess.run(["systemctl", "is-active", "--quiet", f"wg-quick@{NODE_INTERFACE}.service"], check=False).returncode != 0:
rc, out, err = _run(["systemctl", "enable", "--now", f"wg-quick@{NODE_INTERFACE}.service"], timeout=45)
if rc != 0:
raise RuntimeError(err or out or "Could not start WGTools Node tunnel")
return {"changed": False}
tmp = path.with_suffix(".conf.tmp")
tmp.write_text(text, encoding="utf-8")
os.chmod(tmp, 0o600)
tmp.replace(path)
os.chmod(path, 0o600)
rc, out, err = _run(["systemctl", "enable", f"wg-quick@{NODE_INTERFACE}.service"], timeout=30)
if rc != 0:
if old is None:
path.unlink(missing_ok=True)
else:
path.write_text(old, encoding="utf-8")
os.chmod(path, 0o600)
raise RuntimeError(err or out or "Could not enable WGTools Node tunnel")
action = "restart" if old is not None or subprocess.run(["systemctl", "is-active", "--quiet", f"wg-quick@{NODE_INTERFACE}.service"], check=False).returncode == 0 else "start"
rc, out, err = _run(["systemctl", action, f"wg-quick@{NODE_INTERFACE}.service"], timeout=45)
if rc != 0:
if old is None:
# A failed first start must not leave an enabled dead unit behind.
_run(["systemctl", "disable", "--now", f"wg-quick@{NODE_INTERFACE}.service"], timeout=30)
path.unlink(missing_ok=True)
else:
path.write_text(old, encoding="utf-8")
os.chmod(path, 0o600)
_run(["systemctl", "restart", f"wg-quick@{NODE_INTERFACE}.service"], timeout=45)
raise RuntimeError(err or out or "WGTools Node tunnel failed to start")
return {"changed": True}
def _remove_config() -> None:
_run(["systemctl", "disable", "--now", f"wg-quick@{NODE_INTERFACE}.service"], timeout=45)
_run(["ip", "link", "delete", NODE_INTERFACE], timeout=10)
Path(f"/etc/wireguard/{NODE_INTERFACE}.conf").unlink(missing_ok=True)
def _validate_hub_network(state: dict[str, Any], network: str) -> str:
net = ipaddress.ip_network(network, strict=False)
if net.version != 4 or net.prefixlen > 29 or net.prefixlen < 16 or not net.is_private:
raise ValueError("Transport network must be a private IPv4 /16 to /29 network")
for item in _interface_inventory().get("interfaces") or []:
raw = str(item.get("vpn_network") or "").strip()
if not raw:
continue
try:
other = ipaddress.ip_network(raw, strict=False)
except ValueError:
continue
if net.overlaps(other):
raise ValueError(f"Node transport network {net} overlaps WireGuard network {other}")
return str(net)
def enable_hub(payload: dict[str, Any]) -> dict[str, Any]:
with _lock:
state = _load_state()
current_mode = str(state.get("mode") or "none")
if current_mode == "spoke":
raise ValueError("Disconnect this WGTools instance from its current HUB before enabling HUB mode")
state = _ensure_identity(state)
previous_state = dict(state)
node_name = _normalize_name(str(payload.get("node_name") or socket.gethostname()), socket.gethostname())
listen_port = int(payload.get("listen_port") or DEFAULT_LISTEN_PORT)
if not 1 <= listen_port <= 65535:
raise ValueError("Invalid HUB Node port")
inventory = _interface_inventory()
for item in inventory.get("interfaces") or []:
try:
if item.get("configured") and int(item.get("listen_port") or 0) == listen_port:
raise ValueError(f"UDP port {listen_port} is already used by {item.get('name')}")
except (TypeError, ValueError) as exc:
if isinstance(exc, ValueError) and "already used" in str(exc):
raise
if current_mode != "hub" or int(state.get("listen_port") or 0) != listen_port:
try:
probe = _open_control_listener(listen_port)
probe.close()
except Exception as exc:
raise ValueError(f"TCP port {listen_port} is not available for WGTools Nodes: {exc}") from exc
transport_network = _validate_hub_network(state, str(payload.get("transport_network") or DEFAULT_TRANSPORT_NETWORK))
net = ipaddress.ip_network(transport_network)
state.update({
"mode": "hub",
"node_name": node_name,
"listen_port": listen_port,
"transport_network": transport_network,
"transport_ip": str(next(net.hosts())),
"last_error": "",
})
_apply_publication_payload(state, payload)
direct_networks = _direct_private_networks(state, inventory=inventory)
available_networks = _available_publish_networks(
state, inventory=inventory, direct_networks=direct_networks
)
candidate_exports = _local_exports(
state, inventory=inventory, available_networks=available_networks
)
_raise_network_conflicts(
_candidate_network_conflicts(
state, candidate_exports, peers=_peer_rows(), candidate_owner_id="local"
)
)
_remember_current_detection(state, inventory=inventory, direct_networks=direct_networks)
# v0.20.29 stored web/published endpoint data in the HUB state. The Node
# control plane no longer needs either value for pairing. panel_url is
# retained only when it was configured separately in Node settings.
state.pop("endpoint_host", None)
_save_state(state)
_ensure_control_certificate()
state = _load_state()
try:
_apply_config(state, _topology(state))
except Exception:
# Keep the generated Node identity, but do not report HUB mode when
# its system tunnel could not be activated.
_save_state(previous_state)
raise
return get_nodes_status()
def update_local_settings(payload: dict[str, Any]) -> dict[str, Any]:
with _lock:
state = _load_state()
if str(state.get("mode") or "none") not in {"hub", "spoke"}:
raise ValueError("WGTools Nodes is not configured")
previous_state = dict(state)
if "node_name" in payload:
state["node_name"] = _normalize_name(str(payload.get("node_name") or ""))
if "panel_url" in payload:
state["panel_url"] = _normalize_panel_url(str(payload.get("panel_url") or ""), allow_empty=True)
_apply_publication_payload(state, payload)
inventory = _interface_inventory()
direct_networks = _direct_private_networks(state, inventory=inventory)
available_networks = _available_publish_networks(
state, inventory=inventory, direct_networks=direct_networks
)
candidate_exports = _local_exports(
state, inventory=inventory, available_networks=available_networks
)
if state.get("mode") == "hub":
_raise_network_conflicts(
_candidate_network_conflicts(
state, candidate_exports, peers=_peer_rows(), candidate_owner_id="local"
)
)
_remember_current_detection(state, inventory=inventory, direct_networks=direct_networks)
_save_state(state)
if state.get("mode") == "hub":
try:
_apply_config(state, _topology(state))
except Exception:
_save_state(previous_state)
raise
else:
# The HUB is authoritative for conflicts because it knows every
# published network in the fabric. If it rejects the new allow-list,
# restore the previous local settings instead of leaving the UI and
# tunnel out of sync.
try:
sync_spoke_once()
except Exception as exc:
previous_state["last_error"] = str(exc)[:500]
_save_state(previous_state)
raise
return get_nodes_status()
def create_join_code() -> dict[str, Any]:
with _lock:
state = _load_state()
if str(state.get("mode") or "") != "hub":
raise ValueError("Enable HUB mode first")
_cert, _key, fingerprint = _ensure_control_certificate()
code = f"WGTOOLS-NODE-v1.{fingerprint}.{secrets.token_urlsafe(24)}"
digest = hashlib.sha256(code.encode("utf-8")).hexdigest()
now = int(time.time())
expires = now + JOIN_TTL_SECONDS
with _connect() as conn:
conn.execute("DELETE FROM wg_node_join_codes WHERE expires_at<?", (now,))
conn.execute("INSERT INTO wg_node_join_codes(code_hash,created_at,expires_at) VALUES(?,?,?)", (digest, now, expires))
return {"ok": True, "code": code, "expires_at": expires}
def _consume_join_code(code: str) -> None:
digest = hashlib.sha256(str(code or "").strip().encode("utf-8")).hexdigest()
now = int(time.time())
with _connect() as conn:
row = conn.execute("SELECT expires_at FROM wg_node_join_codes WHERE code_hash=?", (digest,)).fetchone()
if not row or int(row["expires_at"]) < now:
conn.execute("DELETE FROM wg_node_join_codes WHERE code_hash=?", (digest,))
raise ValueError("The WGTools Node connection code is invalid or expired")
conn.execute("DELETE FROM wg_node_join_codes WHERE code_hash=?", (digest,))
def _clean_remote_exports(values: Any) -> list[dict[str, str]]:
result: list[dict[str, str]] = []
networks: list[str] = []
items = values if isinstance(values, list) else []
for item in items:
raw = str(item.get("network") if isinstance(item, dict) else item).strip()
if raw:
networks.append(raw)
valid = _normalize_networks(networks, label="Remote Node networks")
by_net: dict[str, dict[str, str]] = {}
for item in items:
if not isinstance(item, dict):
continue
raw = str(item.get("network") or "").strip()
try:
canonical = str(ipaddress.ip_network(raw, strict=False))
except ValueError:
continue
if canonical in valid:
by_net[canonical] = {"network": canonical, "kind": str(item.get("kind") or "remote")[:24], "label": str(item.get("label") or canonical)[:64]}
return [by_net.get(net, {"network": net, "kind": "remote", "label": net}) for net in valid]
def _clean_remote_clients(values: Any) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
for item in values if isinstance(values, list) else []:
if not isinstance(item, dict):
continue
result.append({
"name": str(item.get("name") or "Unnamed")[:64],
"interface": str(item.get("interface") or "")[:15],
"vpn_address": str(item.get("vpn_address") or "")[:64],
"type": "site_to_site" if str(item.get("type") or "") == "site_to_site" else "client",
"online": bool(item.get("online")),
"last_seen": int(item.get("last_seen") or 0),
})
if len(result) >= MAX_CLIENT_SUMMARY:
break
return result
def public_join(payload: dict[str, Any]) -> dict[str, Any]:
with _lock:
state = _load_state()
if str(state.get("mode") or "") != "hub":
raise ValueError("This WGTools instance is not operating as a HUB")
public_key = str(payload.get("public_key") or "").strip()
if len(public_key) < 40 or len(public_key) > 64:
raise ValueError("Invalid Node WireGuard public key")
name = _normalize_name(str(payload.get("node_name") or "WGTools Node"))
panel_url = _normalize_panel_url(str(payload.get("panel_url") or ""), allow_empty=True)
exports = _clean_remote_exports(payload.get("exports"))
clients = _clean_remote_clients(payload.get("clients"))
node_id = str(payload.get("node_id") or "").strip()
if not re_node_id(node_id):
node_id = uuid.uuid4().hex
existing = _peer_by_id(node_id)
same_key = _peer_by_public_key(public_key)
displaced = same_key if same_key and str(same_key.get("node_id") or "") != node_id else None
replaced_ids = {node_id}
if displaced:
replaced_ids.add(str(displaced.get("node_id") or ""))
comparison_peers = [
item for item in _peer_rows()
if str(item.get("node_id") or "") not in replaced_ids
]
_raise_network_conflicts(
_candidate_network_conflicts(
state,
exports,
peers=comparison_peers,
local_exports=_local_exports(state),
candidate_owner_id=node_id,
)
)
preserved_peer = existing or displaced
transport_ip = str(preserved_peer.get("transport_ip") or _assign_transport_ip(state)) if preserved_peer else _assign_transport_ip(state)
rc, psk, err = _run(["wg", "genpsk"])
if rc != 0 or not psk:
raise RuntimeError(err or "Could not generate Node preshared key")
secret = secrets.token_urlsafe(32)
now = int(time.time())
# Consume only after all request validation and key generation succeeded.
_consume_join_code(str(payload.get("join_code") or ""))
if displaced:
with _connect() as conn:
conn.execute("DELETE FROM wg_node_peers WHERE node_id=?", (displaced.get("node_id"),))
with _connect() as conn:
conn.execute(
"INSERT INTO wg_node_peers(node_id,name,public_key,preshared_key,secret,transport_ip,panel_url,version,exports_json,clients_json,connected_at,last_seen,last_error) "
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) "
"ON CONFLICT(node_id) DO UPDATE SET name=excluded.name,public_key=excluded.public_key,preshared_key=excluded.preshared_key,secret=excluded.secret,transport_ip=excluded.transport_ip,panel_url=excluded.panel_url,version=excluded.version,exports_json=excluded.exports_json,clients_json=excluded.clients_json,last_seen=excluded.last_seen,last_error=''",
(node_id, name, public_key, psk, secret, transport_ip, panel_url, str(payload.get("version") or "")[:32], json.dumps(exports, ensure_ascii=False), json.dumps(clients, ensure_ascii=False), now, now, ""),
)
topology = _topology(state)
try:
_apply_config(state, topology)
except Exception:
# _apply_config already restored the previous on-disk tunnel. Match
# SQLite to that rollback as well so the topology is transactional.
with _connect() as conn:
conn.execute("DELETE FROM wg_node_peers WHERE node_id=?", (node_id,))
if existing:
_write_peer_record(existing)
if displaced and (not existing or displaced.get("node_id") != existing.get("node_id")):
_write_peer_record(displaced)
raise
return {
"ok": True,
"node_id": node_id,
"node_secret": secret,
"transport_ip": transport_ip,
"transport_network": str(state.get("transport_network") or DEFAULT_TRANSPORT_NETWORK),
"hub": {
"node_id": state.get("node_id"),
"name": state.get("node_name"),
"public_key": state.get("public_key"),
"transport_ip": state.get("transport_ip"),
"panel_url": state.get("panel_url"),
},
"preshared_key": psk,
"topology": _topology(state),
}
def re_node_id(value: str) -> bool:
return bool(value) and len(value) <= 64 and all(ch.isalnum() or ch in "-_" for ch in value)
def public_sync(node_id: str, secret: str, payload: dict[str, Any], *, defer_apply: bool = False) -> dict[str, Any]:
with _lock:
peer = _peer_by_id(node_id)
if not peer or not secrets.compare_digest(str(peer.get("secret") or ""), str(secret or "")):
raise PermissionError("Invalid WGTools Node credentials")
name = _normalize_name(str(payload.get("node_name") or peer.get("name") or "WGTools Node"))
panel_url = _normalize_panel_url(str(payload.get("panel_url") or peer.get("panel_url") or ""), allow_empty=True)
exports = _clean_remote_exports(payload.get("exports"))
clients = _clean_remote_clients(payload.get("clients"))
old_exports = peer.get("exports") or []
state = _load_state()
comparison_peers = [
item for item in _peer_rows()
if str(item.get("node_id") or "") != str(node_id or "")
]
_raise_network_conflicts(
_candidate_network_conflicts(
state,
exports,
peers=comparison_peers,
local_exports=_local_exports(state),
exclude_node_id=node_id,
candidate_owner_id=node_id,
)
)
now = int(time.time())
with _connect() as conn:
conn.execute(
"UPDATE wg_node_peers SET name=?,panel_url=?,version=?,exports_json=?,clients_json=?,last_seen=?,last_error='' WHERE node_id=?",
(name, panel_url, str(payload.get("version") or "")[:32], json.dumps(exports, ensure_ascii=False), json.dumps(clients, ensure_ascii=False), now, node_id),
)
topology = _topology(state)
if old_exports != exports:
if defer_apply:
return {"ok": True, "topology": topology, "_deferred_previous_peer": peer}
try:
_apply_config(state, topology)
except Exception as exc:
# Keep DB exports aligned with the WireGuard config that
# _apply_config rolled back to. A later sync will retry.
_write_peer_record(peer)
with _connect() as conn:
conn.execute("UPDATE wg_node_peers SET last_error=? WHERE node_id=?", (str(exc)[:500], node_id))
raise
return {"ok": True, "topology": topology}
def _finish_deferred_sync(previous_peer: dict[str, Any]) -> None:
"""Apply HUB topology after the in-tunnel sync response is already sent.
Restarting wgnode0 while a TCP response is still in flight can tear down
the very connection carrying that response. Pairing is public TCP, but
steady-state sync is intentionally inside wgnode0, so configuration changes
are committed immediately after the response has been flushed.
"""
with _lock:
node_id = str(previous_peer.get("node_id") or "")
try:
state = _load_state()
_apply_config(state, _topology(state))
except Exception as exc:
_write_peer_record(previous_peer)
with _connect() as conn:
conn.execute("UPDATE wg_node_peers SET last_error=? WHERE node_id=?", (str(exc)[:500], node_id))
def _finish_deferred_sync_later(previous_peer: dict[str, Any]) -> None:
# Give the TLS/TCP response a brief window to leave the interface before a
# possible wgnode0 restart removes and recreates the transport address.
time.sleep(0.25)
_finish_deferred_sync(previous_peer)
def public_leave(node_id: str, secret: str) -> dict[str, Any]:
"""Remove a spoke from the HUB using its node-scoped secret."""
with _lock:
state = _load_state()
if str(state.get("mode") or "") != "hub":
raise ValueError("This WGTools instance is not operating as a HUB")
peer = _peer_by_id(node_id)
if not peer or not secrets.compare_digest(str(peer.get("secret") or ""), str(secret or "")):
raise PermissionError("Invalid WGTools Node credentials")
with _connect() as conn:
conn.execute("DELETE FROM wg_node_peers WHERE node_id=?", (node_id,))
try:
_apply_config(state, _topology(state))
except Exception:
_write_peer_record(peer)
raise
return {"ok": True}
def _require_tunnel_source(node_id: str, source_ip: str) -> None:
peer = _peer_by_id(node_id)
source = str(source_ip or "")
try:
parsed = ipaddress.ip_address(source)
if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped:
source = str(parsed.ipv4_mapped)
else:
source = str(parsed)
except ValueError:
pass
if not peer or str(peer.get("transport_ip") or "") != source:
raise PermissionError("WGTools Node service requests must arrive through the Node tunnel")
def _serve_control_client(raw: socket.socket, address: tuple[Any, ...], context: ssl.SSLContext) -> None:
"""TLS wrapper that can return application errors after the handshake."""
source_ip = str(address[0] if address else "")
try:
raw.settimeout(20)
tls = context.wrap_socket(raw, server_side=True)
except Exception:
try:
raw.close()
except Exception:
pass
return
try:
request = _recv_control_json(tls)
if request.get("protocol") != NODE_CONTROL_PROTOCOL:
raise ValueError("Unsupported WGTools Node control protocol")
action = str(request.get("action") or "")
if action == "join":
result = public_join(request)
try:
from .audit import write_audit
write_audit("system", "nodes.peer_joined", object=str(result.get("node_id") or request.get("node_name") or "node"), result="joined")
except Exception:
pass
elif action == "sync":
node_id = str(request.get("node_id") or "")
_require_tunnel_source(node_id, source_ip)
result = public_sync(node_id, str(request.get("node_secret") or ""), request, defer_apply=True)
elif action == "leave":
node_id = str(request.get("node_id") or "")
_require_tunnel_source(node_id, source_ip)
result = public_leave(node_id, str(request.get("node_secret") or ""))
try:
from .audit import write_audit
write_audit("system", "nodes.peer_left", object=node_id, result="left")
except Exception:
pass
elif action == "cancel_join":
# Used only when the spoke received pairing data but failed to
# create its local wgnode0. The node-scoped secret is already
# required, and TLS remains pinned to the join-code fingerprint.
node_id = str(request.get("node_id") or "")
result = public_leave(node_id, str(request.get("node_secret") or ""))
else:
raise ValueError("Unknown WGTools Node control action")
deferred_peer = result.pop("_deferred_previous_peer", None) if isinstance(result, dict) else None
_send_control_json(tls, result)
if deferred_peer:
threading.Thread(target=_finish_deferred_sync_later, args=(deferred_peer,), name="wgtools-node-apply", daemon=True).start()
except Exception as exc:
try:
payload = {"ok": False, "error": str(exc)[:500]}
error_code = str(getattr(exc, "code", "") or getattr(exc, "error_code", ""))
if error_code:
payload["error_code"] = error_code
conflicts = getattr(exc, "conflicts", None)
if isinstance(conflicts, list):
payload["conflicts"] = conflicts[:64]
_send_control_json(tls, payload)
except Exception:
pass
finally:
try:
tls.close()
except Exception:
pass
def _open_control_listener(port: int) -> socket.socket:
errors: list[str] = []
for family, address in ((socket.AF_INET6, ("::", port)), (socket.AF_INET, ("0.0.0.0", port))):
listener = socket.socket(family, socket.SOCK_STREAM)
try:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if family == socket.AF_INET6:
listener.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
listener.bind(address)
listener.listen(32)
listener.settimeout(1)
return listener
except OSError as exc:
errors.append(str(exc))
listener.close()
raise RuntimeError(f"Could not listen on Nodes TCP port {port}: {'; '.join(errors)}")
def node_control_server_loop() -> None:
"""Serve pairing on HUB TCP port; sync/leave use the same socket via wgnode0.
Keep the worker alive across transient SQLite/certificate/socket failures so a
HUB can recover without restarting the whole WGTools web process.
"""
global _control_active_port, _control_last_error
while True:
try:
state = _load_state()
if str(state.get("mode") or "") != "hub":
with _control_status_lock:
_control_active_port = 0
_control_last_error = ""
time.sleep(1)
continue
port = int(state.get("listen_port") or DEFAULT_LISTEN_PORT)
cert_file, key_file, _fingerprint = _ensure_control_certificate()
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.load_cert_chain(str(cert_file), str(key_file))
with _open_control_listener(port) as listener:
with _control_status_lock:
_control_active_port = port
_control_last_error = ""
while True:
current = _load_state()
if str(current.get("mode") or "") != "hub" or int(current.get("listen_port") or DEFAULT_LISTEN_PORT) != port:
break
try:
raw, address = listener.accept()
except socket.timeout:
continue
threading.Thread(target=_serve_control_client, args=(raw, address, context), name="wgtools-node-control-client", daemon=True).start()
except Exception as exc:
with _control_status_lock:
_control_active_port = 0
_control_last_error = str(exc)[:500]
time.sleep(2)
def _leave_hub_best_effort(state: dict[str, Any], *, public_fallback: bool = False) -> None:
if str(state.get("mode") or "") != "spoke":
return
node_id = str(state.get("node_id") or "")
secret = str(state.get("node_secret") or "")
fingerprint = str(state.get("hub_control_fingerprint") or "")
hub_transport_ip = str(state.get("hub_transport_ip") or "")
hub_endpoint_host = str(state.get("hub_endpoint_host") or "")
hub_endpoint_port = int(state.get("hub_endpoint_port") or DEFAULT_LISTEN_PORT)
if not node_id or not secret or not fingerprint:
return
request = {"action": "leave", "node_id": node_id, "node_secret": secret}
if hub_transport_ip:
try:
_control_json(hub_transport_ip, hub_endpoint_port, request, expected_fingerprint=fingerprint, timeout=8)
return
except Exception:
pass
if public_fallback and hub_endpoint_host:
try:
_control_json(
hub_endpoint_host,
hub_endpoint_port,
{"action": "cancel_join", "node_id": node_id, "node_secret": secret},
expected_fingerprint=fingerprint,
timeout=8,
)
except Exception:
pass
def connect_to_hub(payload: dict[str, Any]) -> dict[str, Any]:
with _lock:
state = _load_state()
current_mode = str(state.get("mode") or "none")
if current_mode == "hub":
raise ValueError("Disable HUB mode before connecting this WGTools instance to another HUB")
if current_mode == "spoke":
raise ValueError("Disconnect this WGTools instance from its current HUB before connecting to another HUB")
state = _ensure_identity(state)
node_name = _normalize_name(str(payload.get("node_name") or socket.gethostname()), socket.gethostname())
hub_endpoint_host, hub_endpoint_port = _parse_endpoint(str(payload.get("hub_endpoint") or ""))
join_code = str(payload.get("join_code") or "").strip()
fingerprint = _join_code_fingerprint(join_code)
# Panel URL is deliberately not part of pairing. It is optional metadata
# configured separately in Node settings and survives reconnects.
panel_url = _normalize_panel_url(str(state.get("panel_url") or ""), allow_empty=True)
state.update({"node_name": node_name, "panel_url": panel_url})
_apply_publication_payload(state, payload)
inventory = _interface_inventory()
direct_networks = _direct_private_networks(state, inventory=inventory)
available_networks = _available_publish_networks(
state, inventory=inventory, direct_networks=direct_networks
)
exports = _local_exports(state, inventory=inventory, available_networks=available_networks)
summary = local_summary(state, inventory=inventory, exports=exports)
response = _control_json(
hub_endpoint_host,
hub_endpoint_port,
{
"action": "join",
"join_code": join_code,
"node_id": state.get("node_id"),
"node_name": node_name,
"public_key": state.get("public_key"),
"panel_url": panel_url,
"version": VERSION,
"exports": summary.get("exports") or [],
"clients": summary.get("clients") or [],
},
expected_fingerprint=fingerprint,
timeout=15,
)
hub = response.get("hub") if isinstance(response.get("hub"), dict) else {}
state.update({
"mode": "spoke",
"node_id": response.get("node_id") or state.get("node_id"),
"transport_ip": response.get("transport_ip"),
"transport_network": response.get("transport_network") or DEFAULT_TRANSPORT_NETWORK,
"hub_node_id": hub.get("node_id"),
"hub_name": hub.get("name"),
"hub_public_key": hub.get("public_key"),
"hub_transport_ip": hub.get("transport_ip"),
"hub_endpoint_host": hub_endpoint_host,
"hub_endpoint_port": hub_endpoint_port,
"hub_panel_url": hub.get("panel_url") or "",
"hub_control_fingerprint": fingerprint,
"node_secret": response.get("node_secret"),
"preshared_key": response.get("preshared_key"),
"last_sync": int(time.time()),
"last_error": "",
})
_remember_current_detection(
state, inventory=inventory, direct_networks=_direct_private_networks(state, inventory=inventory)
)
# Remove the obsolete v0.20.29 web-control state if this installation
# was previously used for the prototype.
state.pop("hub_url", None)
state.pop("verify_tls", None)
_save_state(state)
topology = response.get("topology") if isinstance(response.get("topology"), dict) else {}
_save_cache({"topology": topology, "updated_at": int(time.time())})
try:
_apply_config(state, topology)
except Exception as exc:
# Pairing already created the peer on the HUB. Revoke it through the
# pinned public control socket because a failed local wgnode0 cannot
# carry the normal in-tunnel leave request.
_leave_hub_best_effort(state, public_fallback=True)
preserved = {
"private_key": state.get("private_key"),
"public_key": state.get("public_key"),
"node_id": state.get("node_id"),
"panel_url": state.get("panel_url"),
}
_save_state({k: v for k, v in preserved.items() if v})
with _connect() as conn:
conn.execute("DELETE FROM wg_node_cache")
_remove_config()
raise RuntimeError(str(exc)) from exc
return get_nodes_status()
def sync_spoke_once() -> dict[str, Any]:
with _lock:
state = _load_state()
if str(state.get("mode") or "") != "spoke":
return {"ok": True, "skipped": True}
secret = str(state.get("node_secret") or "")
node_id = str(state.get("node_id") or "")
hub_transport_ip = str(state.get("hub_transport_ip") or "")
fingerprint = str(state.get("hub_control_fingerprint") or "")
hub_port = int(state.get("hub_endpoint_port") or DEFAULT_LISTEN_PORT)
if not secret or not node_id or not hub_transport_ip or not fingerprint:
if state.get("hub_url") and not fingerprint:
raise RuntimeError("This Node connection uses the v0.20.29 prototype. Disconnect it and pair again with a new connection code.")
raise RuntimeError("WGTools Node connection state is incomplete")
summary = local_summary(state)
try:
response = _control_json(
hub_transport_ip,
hub_port,
{
"action": "sync",
"node_id": node_id,
"node_secret": secret,
"node_name": summary.get("name"),
"panel_url": summary.get("panel_url"),
"version": VERSION,
"exports": summary.get("exports") or [],
"clients": summary.get("clients") or [],
},
expected_fingerprint=fingerprint,
timeout=12,
)
topology = response.get("topology") if isinstance(response.get("topology"), dict) else {}
old_topology = _load_cache().get("topology")
if old_topology != topology:
# Apply first. If it fails, keep the old cache so the next sync
# retries instead of considering an unapplied topology current.
_apply_config(state, topology)
_save_cache({"topology": topology, "updated_at": int(time.time())})
state["last_sync"] = int(time.time())
state["last_error"] = ""
_save_state(state)
return {"ok": True, "topology": topology}
except Exception as exc:
state["last_error"] = str(exc)[:500]
_save_state(state)
raise
def reconcile_node() -> None:
with _lock:
state = _load_state()
if str(state.get("mode") or "") not in {"hub", "spoke"}:
return
try:
state = _ensure_identity(state)
if "publication_seen_networks" not in state:
_remember_current_detection(state)
_apply_config(state, _topology(state))
state["last_error"] = ""
_save_state(state)
except Exception as exc:
state["last_error"] = str(exc)[:500]
_save_state(state)
def remove_peer(node_id: str) -> dict[str, Any]:
with _lock:
state = _load_state()
if str(state.get("mode") or "") != "hub":
raise ValueError("Only a HUB can remove connected nodes")
peer = _peer_by_id(node_id)
if not peer:
raise ValueError("WGTools Node was not found")
with _connect() as conn:
conn.execute("DELETE FROM wg_node_peers WHERE node_id=?", (node_id,))
try:
_apply_config(state, _topology(state))
except Exception:
_write_peer_record(peer)
raise
return get_nodes_status()
def disable_nodes() -> dict[str, Any]:
with _lock:
state = _load_state()
mode = str(state.get("mode") or "none")
if mode == "none":
return get_nodes_status()
if mode == "hub":
with _connect() as conn:
conn.execute("DELETE FROM wg_node_peers")
conn.execute("DELETE FROM wg_node_join_codes")
elif mode == "spoke":
_leave_hub_best_effort(state)
with _connect() as conn:
conn.execute("DELETE FROM wg_node_cache")
preserved = {"private_key": state.get("private_key"), "public_key": state.get("public_key"), "node_id": state.get("node_id")}
_save_state({k: v for k, v in preserved.items() if v})
_remove_config()
return get_nodes_status()
def get_nodes_status() -> dict[str, Any]:
state = _load_state()
mode = str(state.get("mode") or "none")
configured = mode in {"hub", "spoke"}
# One status request must collect local WG/network discovery only once.
# Prior to v0.20.38 the same helpers were invoked repeatedly through
# local_summary -> topology -> exports -> available_networks, which made
# even a local HUB tab wait on several duplicate privileged subprocesses.
inventory = _interface_inventory()
direct_networks = _direct_private_networks(state, inventory=inventory)
detected_networks = _available_publish_networks(
state,
inventory=inventory,
direct_networks=direct_networks,
include_remembered=False,
)
available_networks = _available_publish_networks(
state,
inventory=inventory,
direct_networks=direct_networks,
)
local_exports = _local_exports(
state,
inventory=inventory,
available_networks=available_networks,
) if configured else []
# The status page does not render this node's client inventory. Remote
# Nodes receive that inventory through the background/pairing sync paths,
# where local_summary() still performs fresh snapshots. Avoiding snapshots
# here keeps opening Server -> Nodes responsive even with many WG peers.
local = local_summary(
state,
inventory=inventory,
exports=local_exports,
clients=[],
) if configured else None
service_active = False
if configured:
service_active = subprocess.run(
["systemctl", "is-active", "--quiet", f"wg-quick@{NODE_INTERFACE}.service"],
check=False,
).returncode == 0
topology = _topology(state, local=local)
own_id = str(state.get("node_id") or "")
remote_nodes: list[dict[str, Any]] = []
now = int(time.time())
spoke_runtime = _node_runtime() if mode == "spoke" else {}
for node in topology.get("nodes") or []:
if str(node.get("node_id") or "") == own_id:
continue
clients = node.get("clients") if isinstance(node.get("clients"), list) else []
online_clients = sum(1 for item in clients if item.get("online"))
latest = int(node.get("last_seen") or 0)
node_online = bool(node.get("online", latest and now - latest <= max(45, SYNC_INTERVAL_SECONDS * 4)))
# A spoke has a direct WG peer only to its HUB, so use its own runtime
# handshake for that row instead of treating control sync as tunnel health.
if mode == "spoke" and str(node.get("node_id") or "") == str(state.get("hub_node_id") or ""):
rt = spoke_runtime.get(str(state.get("hub_public_key") or ""), {})
handshake = int(rt.get("latest_handshake") or 0)
node_online = bool(handshake and now - handshake <= max(45, SYNC_INTERVAL_SECONDS * 4))
node = {**node, "last_handshake": handshake, "tunnel_online": node_online}
remote_nodes.append({
**node,
"client_count": len(clients),
"online_clients": online_clients,
"online": node_online,
})
if local is not None:
local["service_active"] = service_active
local["last_error"] = str(state.get("last_error") or "")
current_automatic = [item.get("network") for item in _automatic_exports(inventory) if item.get("network")]
current_direct = [item.get("network") for item in direct_networks if item.get("network")]
current_detected = [item.get("network") for item in detected_networks if item.get("network")]
network_changes = _network_detection_changes(
state,
automatic_networks=current_automatic,
direct_networks=current_direct,
detected_networks=current_detected,
)
vpn_pool_mismatch = _vpn_pool_publication_mismatch(
state, inventory=inventory, direct_networks=direct_networks
)
with _control_status_lock:
control_active = bool(mode == "hub" and _control_active_port == int(state.get("listen_port") or DEFAULT_LISTEN_PORT))
control_error = str(_control_last_error or "")
return {
"ok": True,
"mode": mode,
"interface": NODE_INTERFACE,
"service_active": service_active,
"local": local,
"nodes": remote_nodes,
"hub": {
"endpoint_host": "" if mode == "hub" else state.get("hub_endpoint_host"),
"endpoint_port": state.get("listen_port") if mode == "hub" else state.get("hub_endpoint_port"),
"transport_network": state.get("transport_network") or DEFAULT_TRANSPORT_NETWORK,
"transport_ip": state.get("transport_ip") or "",
"hub_name": (state.get("node_name") or "") if mode == "hub" else (state.get("hub_name") or ""),
},
"control_active": control_active,
"control_error": control_error,
"last_sync": int(state.get("last_sync") or 0),
"last_error": str(state.get("last_error") or ""),
"extra_networks": list(state.get("extra_networks") or []),
"published_networks": [item.get("network") for item in local_exports],
"available_networks": available_networks,
"detected_networks": detected_networks,
"network_changes": network_changes,
"vpn_pool_mismatch": vpn_pool_mismatch,
"topology_generated_at": int(topology.get("generated_at") or 0),
}
def node_details(node_id: str) -> dict[str, Any]:
status = get_nodes_status()
for node in status.get("nodes") or []:
if str(node.get("node_id") or "") == str(node_id or ""):
return {"ok": True, "node": node}
raise ValueError("WGTools Node was not found")