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
asminme affe28ad71
Wydanie WGTools-Extended / release (push) Failing after 16s
1.0.0
2026-10-30 00:35:08 +01:00

1263 lines
59 KiB
Python

from __future__ import annotations
import contextlib
import ipaddress
import json
import os
import re
import secrets
import socket
import sqlite3
import subprocess
import tempfile
import time
import uuid
from pathlib import Path
from typing import Any, Iterator
from .settings import DATABASE_PATH
_HOST_RE = re.compile(r"^[A-Za-z0-9._:-]+$")
RELAY_CONTROL_PORT = 8787
RELAY_AGENT_SOURCE = Path(__file__).resolve().parents[2] / "relay" / "wgtools-relay-agent.py"
RELAY_AGENT_UNIT_SOURCE = Path(__file__).resolve().parents[2] / "relay" / "wgtools-relay-agent.service"
LOCAL_RELAY_DIR = Path(DATABASE_PATH).parent / "relay"
PUBLIC_COLUMNS = """id,name,host,ssh_port,ssh_user,endpoint_domain,relay_port,
transport_port,os_id,os_name,os_version,architecture,privilege_mode,status,
agent_id,tenant_id,controller_id,transport_interface,home_transport_ip,
relay_transport_ip,control_port,published_interface,home_wg_port,installed_at,
last_health,last_error,host_key_fingerprint,created_at,updated_at"""
def _connect_db() -> sqlite3.Connection:
Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DATABASE_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA foreign_keys=ON")
return conn
def _ensure_columns(conn: sqlite3.Connection, table: str, definitions: dict[str, str]) -> None:
existing = {str(row[1]) for row in conn.execute(f"PRAGMA table_info({table})").fetchall()}
for name, definition in definitions.items():
if name not in existing:
conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {definition}")
def init_vps_database() -> None:
with _connect_db() as conn:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS vps_relays (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
host TEXT NOT NULL,
ssh_port INTEGER NOT NULL,
ssh_user TEXT NOT NULL,
endpoint_domain TEXT NOT NULL DEFAULT '',
relay_port INTEGER NOT NULL,
transport_port INTEGER NOT NULL,
os_id TEXT NOT NULL DEFAULT '',
os_name TEXT NOT NULL DEFAULT '',
os_version TEXT NOT NULL DEFAULT '',
architecture TEXT NOT NULL DEFAULT '',
privilege_mode TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'candidate',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS vps_controller_identity (
id TEXT PRIMARY KEY,
created_at INTEGER NOT NULL
);
"""
)
_ensure_columns(
conn,
"vps_relays",
{
"agent_id": "TEXT NOT NULL DEFAULT ''",
"tenant_id": "TEXT NOT NULL DEFAULT ''",
"controller_id": "TEXT NOT NULL DEFAULT ''",
"control_token": "TEXT NOT NULL DEFAULT ''",
"transport_interface": "TEXT NOT NULL DEFAULT ''",
"home_transport_ip": "TEXT NOT NULL DEFAULT ''",
"relay_transport_ip": "TEXT NOT NULL DEFAULT ''",
"control_port": f"INTEGER NOT NULL DEFAULT {RELAY_CONTROL_PORT}",
"published_interface": "TEXT NOT NULL DEFAULT ''",
"home_wg_port": "INTEGER NOT NULL DEFAULT 0",
"home_transport_private_key": "TEXT NOT NULL DEFAULT ''",
"relay_transport_public_key": "TEXT NOT NULL DEFAULT ''",
"installed_at": "INTEGER NOT NULL DEFAULT 0",
"last_health": "INTEGER NOT NULL DEFAULT 0",
"last_error": "TEXT NOT NULL DEFAULT ''",
"host_key_fingerprint": "TEXT NOT NULL DEFAULT ''",
},
)
def controller_id() -> str:
init_vps_database()
with _connect_db() as conn:
row = conn.execute("SELECT id FROM vps_controller_identity ORDER BY created_at LIMIT 1").fetchone()
if row:
return str(row["id"])
value = uuid.uuid4().hex
conn.execute("INSERT INTO vps_controller_identity(id,created_at) VALUES(?,?)", (value, int(time.time())))
return value
def list_vps() -> list[dict[str, Any]]:
init_vps_database()
with _connect_db() as conn:
rows = conn.execute(f"SELECT {PUBLIC_COLUMNS} FROM vps_relays WHERE status!='detached' ORDER BY created_at,id").fetchall()
return [dict(row) for row in rows]
def get_vps(vps_id: str, *, include_secrets: bool = False) -> dict[str, Any] | None:
init_vps_database()
columns = PUBLIC_COLUMNS
if include_secrets:
columns += ",control_token,home_transport_private_key,relay_transport_public_key"
with _connect_db() as conn:
row = conn.execute(f"SELECT {columns} FROM vps_relays WHERE id=?", (vps_id,)).fetchone()
return dict(row) if row else None
def save_vps_candidate(payload: dict[str, Any], preflight: dict[str, Any]) -> dict[str, Any]:
init_vps_database()
now = int(time.time())
vps_id = str(payload.get("id") or preflight.get("reconnect_vps_id") or uuid.uuid4().hex)
name = str(payload.get("name") or "").strip()
host = str(payload.get("host") or "").strip()
ssh_user = str(payload.get("ssh_user") or "").strip()
endpoint_domain = str(payload.get("endpoint_domain") or "").strip()
ssh_port = int(payload.get("ssh_port") or 22)
# Preflight may move ports when an existing multi-tenant Relay Agent already
# owns the user's initial suggestion. Persist the verified suggestions.
relay_port = int(preflight.get("relay_port") or payload.get("relay_port") or 51820)
transport_port = int(preflight.get("transport_port") or payload.get("transport_port") or 51900)
if not name:
raise ValueError("VPS name is required")
with _connect_db() as conn:
existing = conn.execute("SELECT created_at,status FROM vps_relays WHERE id=?", (vps_id,)).fetchone()
created_at = int(existing["created_at"]) if existing else now
current_status = str(existing["status"]) if existing else "candidate"
if current_status == "installed":
raise ValueError("Installed Relay settings must be changed through Relay management")
target_status = "detached" if current_status == "detached" and preflight.get("reconnect_available") else "candidate"
conn.execute(
"""INSERT INTO vps_relays(
id,name,host,ssh_port,ssh_user,endpoint_domain,relay_port,transport_port,
os_id,os_name,os_version,architecture,privilege_mode,status,
host_key_fingerprint,created_at,updated_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET
name=excluded.name,host=excluded.host,ssh_port=excluded.ssh_port,
ssh_user=excluded.ssh_user,endpoint_domain=excluded.endpoint_domain,
relay_port=excluded.relay_port,transport_port=excluded.transport_port,
os_id=excluded.os_id,os_name=excluded.os_name,os_version=excluded.os_version,
architecture=excluded.architecture,privilege_mode=excluded.privilege_mode,
status=excluded.status,host_key_fingerprint=excluded.host_key_fingerprint,
updated_at=excluded.updated_at""",
(
vps_id, name, host, ssh_port, ssh_user, endpoint_domain, relay_port, transport_port,
str(preflight.get("os_id") or ""), str(preflight.get("os_name") or ""),
str(preflight.get("os_version") or ""), str(preflight.get("architecture") or ""),
str(preflight.get("privilege_mode") or ""), target_status,
str(preflight.get("host_key_fingerprint") or ""), created_at, now,
),
)
return get_vps(vps_id) or {"id": vps_id}
def delete_vps_candidate(vps_id: str) -> None:
init_vps_database()
with _connect_db() as conn:
row = conn.execute("SELECT status FROM vps_relays WHERE id=?", (vps_id,)).fetchone()
if not row:
raise ValueError("VPS entry not found")
if str(row["status"]) != "candidate":
raise ValueError("Only a VPS candidate can be removed")
conn.execute("DELETE FROM vps_relays WHERE id=?", (vps_id,))
def _validate_common(payload: dict[str, Any]) -> dict[str, Any]:
host = str(payload.get("host") or "").strip()
username = str(payload.get("ssh_user") or "").strip()
auth_method = str(payload.get("auth_method") or "password").strip().lower()
password = str(payload.get("password") or "")
private_key = str(payload.get("private_key") or "")
key_passphrase = str(payload.get("key_passphrase") or "")
try:
ssh_port = int(payload.get("ssh_port") or 22)
relay_port = int(payload.get("relay_port") or 51820)
transport_port = int(payload.get("transport_port") or 51900)
except (TypeError, ValueError) as exc:
raise ValueError("SSH and UDP ports must be numbers") from exc
if not host or len(host) > 255 or any(ch.isspace() for ch in host) or not _HOST_RE.fullmatch(host):
raise ValueError("VPS IP/hostname is invalid")
if not username or len(username) > 64 or any(ord(ch) < 33 for ch in username):
raise ValueError("SSH username is invalid")
for label, port in (("SSH", ssh_port), ("Relay", relay_port), ("Transport", transport_port)):
if not 1 <= port <= 65535:
raise ValueError(f"{label} port must be between 1 and 65535")
if relay_port == transport_port:
raise ValueError("Relay and transport UDP ports must be different")
if auth_method not in {"password", "key"}:
raise ValueError("SSH authentication method is invalid")
if auth_method == "password" and not password:
raise ValueError("SSH password is required")
if auth_method == "key" and not private_key.strip():
raise ValueError("SSH private key is required")
return {
"host": host, "ssh_user": username, "auth_method": auth_method,
"password": password, "private_key": private_key, "key_passphrase": key_passphrase,
"ssh_port": ssh_port, "relay_port": relay_port, "transport_port": transport_port,
}
def _parse_os_release(raw: str) -> dict[str, str]:
result: dict[str, str] = {}
for line in raw.splitlines():
if "=" not in line:
continue
key, value = line.split("=", 1)
result[key.strip()] = value.strip().strip('"').strip("'")
return result
def _run(cmd: list[str], *, input_text: str = "", env: dict[str, str] | None = None, timeout: int = 18) -> subprocess.CompletedProcess[str]:
try:
return subprocess.run(
cmd, input=input_text or None, text=True, capture_output=True, check=False,
env=env, timeout=timeout,
)
except subprocess.TimeoutExpired as exc:
raise ValueError("Operation timed out") from exc
def shutil_which(command: str) -> str | None:
for directory in os.environ.get("PATH", "").split(os.pathsep):
path = os.path.join(directory, command)
if os.path.isfile(path) and os.access(path, os.X_OK):
return path
return None
def _ssh_base(cfg: dict[str, Any], known_hosts: str, key_path: str = "") -> tuple[list[str], dict[str, str]]:
env = os.environ.copy()
cmd: list[str] = []
if cfg["auth_method"] == "password":
if not shutil_which("sshpass"):
raise ValueError("sshpass is not installed on the WGTools server")
env["SSHPASS"] = cfg["password"]
cmd += ["sshpass", "-e"]
cmd += [
"ssh", "-p", str(cfg["ssh_port"]),
"-o", "ConnectTimeout=10", "-o", "ConnectionAttempts=1",
"-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=1",
"-o", f"UserKnownHostsFile={known_hosts}", "-o", "StrictHostKeyChecking=accept-new",
"-o", "LogLevel=ERROR",
]
if cfg["auth_method"] == "password":
cmd += ["-o", "PreferredAuthentications=password,keyboard-interactive", "-o", "PubkeyAuthentication=no"]
else:
cmd += ["-o", "BatchMode=yes", "-i", key_path, "-o", "IdentitiesOnly=yes"]
cmd += [f"{cfg['ssh_user']}@{cfg['host']}"]
return cmd, env
def _ssh_exec(
cfg: dict[str, Any], command: str, known_hosts: str, key_path: str = "", *,
stdin_text: str = "", timeout: int = 18,
) -> tuple[int, str, str]:
base, env = _ssh_base(cfg, known_hosts, key_path)
proc = _run(base + [command], input_text=stdin_text, env=env, timeout=timeout)
return proc.returncode, proc.stdout.strip(), proc.stderr.strip()
def _root_exec(
cfg: dict[str, Any], command: str, known_hosts: str, key_path: str, privilege_mode: str, *,
stdin_text: str = "", timeout: int = 30,
) -> tuple[int, str, str]:
if privilege_mode == "root":
remote = command
data = stdin_text
elif privilege_mode == "sudo-nopasswd":
remote = f"sudo -n {command}"
data = stdin_text
elif privilege_mode == "sudo-password":
remote = f"sudo -S -p '' {command}"
data = cfg["password"] + "\n" + stdin_text
else:
raise ValueError("Remote root privileges are unavailable")
return _ssh_exec(cfg, remote, known_hosts, key_path, stdin_text=data, timeout=timeout)
def _host_key_fingerprint(known_hosts: str) -> str:
if not shutil_which("ssh-keygen"):
return ""
proc = _run(["ssh-keygen", "-lf", known_hosts, "-E", "sha256"], timeout=5)
if proc.returncode != 0 or not proc.stdout.strip():
return ""
line = proc.stdout.splitlines()[0].strip().split()
return line[1] if len(line) > 1 else ""
@contextlib.contextmanager
def _ssh_session(payload: dict[str, Any]) -> Iterator[tuple[dict[str, Any], str, str, str]]:
cfg = _validate_common(payload)
for tool in ("ssh", "ssh-keygen"):
if not shutil_which(tool):
raise ValueError(f"{tool} is not installed on the WGTools server")
try:
socket.getaddrinfo(cfg["host"], cfg["ssh_port"], type=socket.SOCK_STREAM)
except OSError as exc:
raise ValueError(f"VPS hostname could not be resolved: {exc}") from exc
with tempfile.TemporaryDirectory(prefix="wgtools-vps-") as tmp:
known_hosts = str(Path(tmp) / "known_hosts")
key_path = ""
if cfg["auth_method"] == "key":
key = Path(tmp) / "id_vps"
key.write_text(cfg["private_key"].strip() + "\n", encoding="utf-8")
key.chmod(0o600)
key_path = str(key)
if cfg["key_passphrase"]:
proc = _run(["ssh-keygen", "-p", "-P", cfg["key_passphrase"], "-N", "", "-f", key_path], timeout=8)
if proc.returncode != 0:
raise ValueError("SSH private key passphrase is incorrect or the key format is unsupported")
code, uid_out, error = _ssh_exec(cfg, "id -u", known_hosts, key_path)
if code != 0:
raise ValueError(f"SSH connection failed: {error or uid_out or 'authentication failed'}")
if not uid_out.isdigit():
raise ValueError("Could not determine the remote user privileges")
uid = int(uid_out)
privilege_mode = "root" if uid == 0 else ""
if uid != 0:
code, _, _ = _ssh_exec(cfg, "sudo -n true", known_hosts, key_path)
if code == 0:
privilege_mode = "sudo-nopasswd"
elif cfg["auth_method"] == "password":
code, _, _ = _ssh_exec(cfg, "sudo -S -p '' true", known_hosts, key_path, stdin_text=cfg["password"] + "\n")
if code == 0:
privilege_mode = "sudo-password"
if not privilege_mode:
raise ValueError("SSH login works, but root privileges are unavailable. Use root or a user with sudo access")
yield cfg, known_hosts, key_path, privilege_mode
def _remote_agent_info(
cfg: dict[str, Any], known_hosts: str, key_path: str, privilege_mode: str,
) -> dict[str, Any]:
# Secrets returned here stay inside the WGTools backend. preflight_vps()
# deliberately exposes only non-secret reconnect metadata to the browser.
script = r'''python3 - <<'PYREMOTE'
import json
import re
import subprocess
import time
from pathlib import Path
root=Path('/var/lib/wgtools-relay')
out={'installed':False,'agent':{},'tenants':[]}
agent=root/'agent.json'
if agent.is_file():
out['installed']=True
try: out['agent']=json.loads(agent.read_text())
except Exception: out['agent']={}
for p in sorted((root/'tenants').glob('*/config.json')) if (root/'tenants').exists() else []:
try:
d=json.loads(p.read_text())
item={k:d.get(k) for k in (
'tenant_id','controller_id','relay_port','transport_port','transport_interface',
'relay_transport_ip','home_transport_ip','published_interface','home_wg_port',
'control_token','control_port','created_at'
)}
iface=str(d.get('transport_interface') or '')
if iface:
try:
q=subprocess.run(['wg','show',iface,'public-key'],text=True,capture_output=True,timeout=2,check=False)
if q.returncode==0 and q.stdout.strip(): item['relay_transport_public_key']=q.stdout.strip()
except Exception: pass
try:
q=subprocess.run(['wg','show',iface,'peers'],text=True,capture_output=True,timeout=2,check=False)
if q.returncode==0 and q.stdout.strip(): item['home_transport_public_key']=q.stdout.splitlines()[0].strip()
except Exception: pass
try:
q=subprocess.run(['wg','show',iface,'latest-handshakes'],text=True,capture_output=True,timeout=2,check=False)
latest=0
if q.returncode==0:
for line in q.stdout.splitlines():
parts=line.split()
if len(parts)>=2:
try: latest=max(latest,int(parts[1]))
except ValueError: pass
item['transport_handshake_age']=max(0,int(time.time())-latest) if latest>0 else None
except Exception: item['transport_handshake_age']=None
conf=p.parent/(iface+'.conf')
if conf.is_file():
text=conf.read_text(errors='replace')
if not item.get('home_transport_public_key'):
m=re.search(r'(?mi)^PublicKey\s*=\s*(\S+)\s*$',text)
if m: item['home_transport_public_key']=m.group(1)
if not item.get('relay_transport_public_key'):
m=re.search(r'(?mi)^PrivateKey\s*=\s*(\S+)\s*$',text)
if m:
try:
q=subprocess.run(['wg','pubkey'],input=m.group(1)+'\n',text=True,capture_output=True,timeout=2,check=False)
if q.returncode==0 and q.stdout.strip(): item['relay_transport_public_key']=q.stdout.strip()
except Exception: pass
out['tenants'].append(item)
except Exception: pass
print(json.dumps(out,separators=(',',':')))
PYREMOTE'''
code, out, _ = _root_exec(cfg, "bash -s", known_hosts, key_path, privilege_mode, stdin_text=script)
if code != 0 or not out.strip():
return {"installed": False, "agent": {}, "tenants": []}
try:
data = json.loads(out.splitlines()[-1])
return data if isinstance(data, dict) else {"installed": False, "agent": {}, "tenants": []}
except Exception:
return {"installed": False, "agent": {}, "tenants": []}
def _controller_remote_tenant(agent_info: dict[str, Any], *, preferred_tenant_id: str = "") -> dict[str, Any] | None:
controller = controller_id()
tenants = [
dict(item) for item in list(agent_info.get("tenants") or [])
if str(item.get("controller_id") or "") == controller
]
if preferred_tenant_id:
for item in tenants:
if str(item.get("tenant_id") or "") == preferred_tenant_id:
return item
if len(tenants) == 1:
return tenants[0]
if len(tenants) > 1:
raise ValueError("Several existing Relay connections from this WGTools were found on the VPS. Remove stale duplicates manually before reconnecting")
return None
def _detached_vps_id_for_tenant(tenant_id: str) -> str:
if not tenant_id:
return ""
with _connect_db() as conn:
row = conn.execute(
"SELECT id FROM vps_relays WHERE tenant_id=? AND status='detached' ORDER BY updated_at DESC LIMIT 1",
(tenant_id,),
).fetchone()
return str(row["id"]) if row else ""
def _orphan_client_relay_vps_id() -> str:
"""Recover the v0.19.9-deleted VPS id when clients still reference it.
A detached Relay should keep its DB row in current releases. v0.19.9
deleted that row, but managed client metadata still contains relay_vps_id.
Reusing the single unambiguous orphan id reconnects those clients without
editing or recreating them.
"""
client_dir = Path(DATABASE_PATH).parent / "clients"
if not client_dir.exists():
return ""
with _connect_db() as conn:
existing = {str(row["id"]) for row in conn.execute("SELECT id FROM vps_relays").fetchall()}
orphaned: set[str] = set()
for path in client_dir.glob("*.json"):
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception:
continue
if not isinstance(data, dict) or str(data.get("connection_mode") or "") != "relay":
continue
value = str(data.get("relay_vps_id") or "").strip()
if value and value not in existing:
orphaned.add(value)
return next(iter(orphaned)) if len(orphaned) == 1 else ""
def _wg_public_key(private_key: str) -> str:
wg = shutil_which("wg")
if not wg or not private_key.strip():
return ""
proc = _run([wg, "pubkey"], input_text=private_key.strip() + "\n", timeout=5)
return proc.stdout.strip() if proc.returncode == 0 else ""
def _remote_set_home_public_key(
cfg: dict[str, Any], known_hosts: str, key_path: str, privilege_mode: str,
*, tenant: dict[str, Any], public_key: str,
) -> None:
tenant_id = str(tenant.get("tenant_id") or "")
iface = str(tenant.get("transport_interface") or "")
if not re.fullmatch(r"[0-9a-fA-F]{16,64}", tenant_id) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", iface):
raise ValueError("Existing Relay identity on the VPS is invalid")
if not public_key.strip():
raise ValueError("New Relay transport public key is empty")
conf = f"/var/lib/wgtools-relay/tenants/{tenant_id}/{iface}.conf"
service = _remote_service_name(tenant_id)
script = rf'''set -euo pipefail
python3 - <<'PYREKEY'
import re
from pathlib import Path
p=Path({json.dumps(conf)})
new={json.dumps(public_key.strip())}
text=p.read_text(encoding='utf-8')
updated,count=re.subn(r'(?mi)^PublicKey\s*=\s*\S+\s*$', 'PublicKey = '+new, text, count=1)
if count != 1:
raise SystemExit('Relay peer PublicKey was not found')
p.write_text(updated,encoding='utf-8')
p.chmod(0o600)
PYREKEY
systemctl restart {service}
'''
code, _out, err = _root_exec(
cfg, "bash -s", known_hosts, key_path, privilege_mode,
stdin_text=script, timeout=40,
)
if code != 0:
raise ValueError("Could not reconnect existing Relay transport on VPS: " + (err or "remote rekey failed"))
def _remote_set_home_wg_port(
cfg: dict[str, Any], known_hosts: str, key_path: str, privilege_mode: str,
*, tenant: dict[str, Any], home_wg_port: int,
) -> None:
"""Synchronize the preserved tenant with the current home WG listen port.
The Relay Agent watches config.json and reloads only the changed tenant, so
this does not restart or disturb other tenants on the same VPS.
"""
tenant_id = str(tenant.get("tenant_id") or "")
if not re.fullmatch(r"[0-9a-fA-F]{16,64}", tenant_id):
raise ValueError("Existing Relay identity on the VPS is invalid")
port = int(home_wg_port)
if not 1 <= port <= 65535:
raise ValueError("The selected WireGuard interface has no valid listen port")
config_path = f"/var/lib/wgtools-relay/tenants/{tenant_id}/config.json"
script = rf'''set -euo pipefail
python3 - <<'PYPORT'
import json
import os
from pathlib import Path
p=Path({json.dumps(config_path)})
port={port}
data=json.loads(p.read_text(encoding='utf-8'))
data['home_wg_port']=port
tmp=p.with_name(p.name+'.tmp')
tmp.write_text(json.dumps(data,separators=(',',':'))+'\n',encoding='utf-8')
tmp.chmod(0o600)
os.replace(tmp,p)
PYPORT
'''
code, _out, err = _root_exec(
cfg, "bash -s", known_hosts, key_path, privilege_mode,
stdin_text=script, timeout=20,
)
if code != 0:
raise ValueError("Could not update existing Relay listen port on VPS: " + (err or "remote tenant update failed"))
def _pick_free_port(start: int, busy: set[int], avoid: set[int] | None = None) -> int:
avoid = avoid or set()
for offset in range(0, 2048):
port = start + offset
if port > 65535:
port = 1024 + (port - 65536)
if port >= 1024 and port not in busy and port not in avoid:
return port
raise ValueError("No free UDP port could be suggested on the VPS")
def _listener_ports(raw: str) -> set[int]:
result: set[int] = set()
for line in raw.splitlines():
for match in re.finditer(r":(\d+)\b", line):
try:
result.add(int(match.group(1)))
except ValueError:
pass
return result
def preflight_vps(payload: dict[str, Any]) -> dict[str, Any]:
with _ssh_session(payload) as (cfg, known_hosts, key_path, privilege_mode):
_, os_raw, _ = _ssh_exec(cfg, "cat /etc/os-release 2>/dev/null || true", known_hosts, key_path)
os_data = _parse_os_release(os_raw)
os_id = os_data.get("ID", "").lower()
os_like = os_data.get("ID_LIKE", "").lower().split()
os_name = os_data.get("PRETTY_NAME") or os_data.get("NAME") or os_id or "Unknown Linux"
os_version = os_data.get("VERSION_ID", "")
_, arch, _ = _ssh_exec(cfg, "uname -m", known_hosts, key_path)
_, checks_raw, _ = _ssh_exec(
cfg,
"for c in apt-get systemctl ip ss python3; do command -v $c >/dev/null 2>&1 && echo $c=1 || echo $c=0; done; "
"command -v wg >/dev/null 2>&1 && echo wg=1 || echo wg=0; "
"command -v iptables >/dev/null 2>&1 && echo iptables=1 || echo iptables=0",
known_hosts, key_path,
)
checks: dict[str, bool] = {}
for line in checks_raw.splitlines():
if "=" in line:
key, value = line.split("=", 1)
checks[key.strip()] = value.strip() == "1"
compatible_os = os_id in {"debian", "ubuntu"} or "debian" in os_like or "ubuntu" in os_like
required = all(checks.get(name, False) for name in ("apt-get", "systemctl", "ip", "ss", "python3"))
if not compatible_os:
raise ValueError(f"Unsupported VPS operating system: {os_name}. Debian or Ubuntu is recommended")
if not required:
missing = [name for name in ("apt-get", "systemctl", "ip", "ss", "python3") if not checks.get(name, False)]
raise ValueError("VPS is missing required system tools: " + ", ".join(missing))
agent_info = _remote_agent_info(cfg, known_hosts, key_path, privilege_mode)
_, listeners, _ = _ssh_exec(cfg, "ss -H -lun 2>/dev/null || true", known_hosts, key_path)
busy = _listener_ports(listeners)
requested_relay = int(cfg["relay_port"])
requested_transport = int(cfg["transport_port"])
reconnect_tenant = _controller_remote_tenant(agent_info) if agent_info.get("installed") else None
if reconnect_tenant:
# This VPS already contains a tenant created by this WGTools controller.
# Re-use its actual ports instead of allocating a second connection.
relay_port = int(reconnect_tenant.get("relay_port") or requested_relay)
transport_port = int(reconnect_tenant.get("transport_port") or requested_transport)
elif agent_info.get("installed"):
# The Agent may serve another independent WGTools controller.
relay_port = _pick_free_port(requested_relay, busy)
transport_port = _pick_free_port(requested_transport, busy, {relay_port})
else:
busy_requested = [port for port in (requested_relay, requested_transport) if port in busy]
if busy_requested:
raise ValueError("UDP port is already in use on the VPS: " + ", ".join(map(str, busy_requested)))
relay_port = requested_relay
transport_port = requested_transport
agent = dict(agent_info.get("agent") or {})
tenants = list(agent_info.get("tenants") or [])
reconnect_tenant_id = str((reconnect_tenant or {}).get("tenant_id") or "")
reconnect_vps_id = _detached_vps_id_for_tenant(reconnect_tenant_id)
if reconnect_tenant and not reconnect_vps_id:
reconnect_vps_id = _orphan_client_relay_vps_id()
return {
"ok": True,
"host": cfg["host"], "ssh_port": cfg["ssh_port"], "ssh_user": cfg["ssh_user"],
"os_id": os_id, "os_name": os_name, "os_version": os_version,
"architecture": arch, "privilege_mode": privilege_mode,
"host_key_fingerprint": _host_key_fingerprint(known_hosts),
"wireguard_installed": bool(checks.get("wg")), "iptables_installed": bool(checks.get("iptables")),
"relay_port": relay_port, "transport_port": transport_port,
"requested_relay_port": requested_relay, "requested_transport_port": requested_transport,
"ports_adjusted": relay_port != requested_relay or transport_port != requested_transport,
"relay_agent_installed": bool(agent_info.get("installed")),
"relay_agent_id": str(agent.get("agent_id") or ""),
"relay_agent_version": str(agent.get("version") or ""),
"relay_tenant_count": len(tenants),
"relay_active_tenant_count": sum(1 for item in tenants if isinstance(item.get("transport_handshake_age"), int) and int(item["transport_handshake_age"]) <= 180),
"reconnect_available": bool(reconnect_tenant),
"reconnect_tenant_id": reconnect_tenant_id,
"reconnect_vps_id": reconnect_vps_id,
"checks": {
"ssh": True, "os": True, "apt": True, "systemd": True,
"network_tools": True, "python": True, "ports_free": True, "root_access": True,
},
}
def _wg_keypair() -> tuple[str, str]:
wg = shutil_which("wg")
if not wg:
raise ValueError("WireGuard tools are not installed on the WGTools server")
private = _run([wg, "genkey"], timeout=5)
if private.returncode != 0 or not private.stdout.strip():
raise ValueError("Could not generate WireGuard transport key")
priv = private.stdout.strip()
public = _run([wg, "pubkey"], input_text=priv + "\n", timeout=5)
if public.returncode != 0 or not public.stdout.strip():
raise ValueError("Could not derive WireGuard transport public key")
return priv, public.stdout.strip()
def _used_local_networks() -> list[ipaddress.IPv4Network]:
ip = shutil_which("ip") or "/usr/sbin/ip"
proc = _run([ip, "-4", "route", "show", "table", "all"], timeout=5)
result: list[ipaddress.IPv4Network] = []
if proc.returncode != 0:
return result
for line in proc.stdout.splitlines():
first = line.split()[0] if line.split() else ""
if first == "default":
continue
try:
result.append(ipaddress.ip_network(first, strict=False))
except Exception:
pass
return result
def _allocate_transport_network(tenant_id: str, remote_tenants: list[dict[str, Any]]) -> ipaddress.IPv4Network:
used = _used_local_networks()
for tenant in remote_tenants:
for key in ("home_transport_ip", "relay_transport_ip"):
value = str(tenant.get(key) or "")
if value:
try:
used.append(ipaddress.ip_network(value + "/30", strict=False))
except Exception:
pass
seed = int(tenant_id[:8], 16) % 16384
base = int(ipaddress.ip_address("10.254.0.0"))
for step in range(16384):
index = (seed + step) % 16384
network = ipaddress.ip_network((base + index * 4, 30))
if all(not network.overlaps(other) for other in used):
return network
raise ValueError("Could not allocate a conflict-free Relay transport network")
def _transport_interface_name(tenant_id: str) -> str:
return "wgrly" + tenant_id[:6]
def _remote_service_name(tenant_id: str) -> str:
return "wgtools-relay-transport-" + tenant_id[:12] + ".service"
def _local_service_name(tenant_id: str) -> str:
return "wgtools-relay-home-" + tenant_id[:12] + ".service"
def _remote_install_script(
*, agent_id: str, tenant: dict[str, Any], relay_private_key: str,
home_public_key: str, agent_source: str, agent_unit: str, agent_preexisting: bool,
) -> str:
tenant_id = str(tenant["tenant_id"])
iface = str(tenant["transport_interface"])
root = f"/var/lib/wgtools-relay/tenants/{tenant_id}"
config = dict(tenant)
config["enabled"] = True
agent_json = json.dumps({"agent_id": agent_id, "version": "0.1", "created_at": int(time.time())}, separators=(",", ":"))
tenant_json = json.dumps(config, separators=(",", ":"))
wg_conf = f"""[Interface]\nAddress = {tenant['relay_transport_ip']}/30\nListenPort = {tenant['transport_port']}\nPrivateKey = {relay_private_key}\n\n[Peer]\nPublicKey = {home_public_key}\nAllowedIPs = {tenant['home_transport_ip']}/32\n"""
service = f"""[Unit]\nDescription=WGTools Relay transport {tenant_id}\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\nExecStart=/usr/bin/wg-quick up {root}/{iface}.conf\nExecStop=/usr/bin/wg-quick down {root}/{iface}.conf\n\n[Install]\nWantedBy=multi-user.target\n"""
# Content is transmitted through SSH stdin, not command-line arguments.
payloads = {
"/opt/wgtools-relay/wgtools-relay-agent.py": agent_source,
"/etc/systemd/system/wgtools-relay-agent.service": agent_unit,
f"{root}/config.json": tenant_json + "\n",
f"{root}/{iface}.conf": wg_conf,
f"/etc/systemd/system/{_remote_service_name(tenant_id)}": service,
}
encoded = json.dumps(payloads)
package_setup = "" if agent_preexisting else "apt-get update >/dev/null\napt-get install -y wireguard-tools iproute2 iptables python3 >/dev/null\n"
return f'''set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
{package_setup}install -d -m 0755 /opt/wgtools-relay /var/lib/wgtools-relay/tenants
if [ ! -s /var/lib/wgtools-relay/agent.json ]; then
printf '%s\\n' {json.dumps(agent_json)} > /var/lib/wgtools-relay/agent.json
chmod 0600 /var/lib/wgtools-relay/agent.json
fi
python3 - <<'PYFILES'
import json
from pathlib import Path
files=json.loads({json.dumps(encoded)})
for name,content in files.items():
p=Path(name); p.parent.mkdir(parents=True,exist_ok=True); p.write_text(content,encoding='utf-8')
p.chmod(0o600 if name.endswith('.conf') or name.endswith('config.json') else (0o755 if name.endswith('.py') else 0o644))
PYFILES
systemctl daemon-reload
systemctl enable --now {_remote_service_name(tenant_id)} >/dev/null
systemctl enable --now wgtools-relay-agent.service >/dev/null
systemctl restart wgtools-relay-agent.service
'''
def _local_transport_apply(
*, vps_id: str, tenant: dict[str, Any], home_private_key: str, relay_public_key: str,
vps_host: str,
) -> tuple[Path, str]:
tenant_id = str(tenant["tenant_id"])
iface = str(tenant["transport_interface"])
directory = LOCAL_RELAY_DIR / vps_id
directory.mkdir(parents=True, exist_ok=True)
directory.chmod(0o700)
conf = directory / f"{iface}.conf"
conf.write_text(
f"""[Interface]\nAddress = {tenant['home_transport_ip']}/30\nPrivateKey = {home_private_key}\n\n[Peer]\nPublicKey = {relay_public_key}\nAllowedIPs = {tenant['relay_transport_ip']}/32\nEndpoint = {vps_host}:{tenant['transport_port']}\nPersistentKeepalive = 25\n""",
encoding="utf-8",
)
conf.chmod(0o600)
service_name = _local_service_name(tenant_id)
service_path = Path("/etc/systemd/system") / service_name
service_path.write_text(
f"""[Unit]\nDescription=WGTools Relay home transport {tenant_id}\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\nExecStart=/usr/bin/wg-quick up {conf}\nExecStop=/usr/bin/wg-quick down {conf}\n\n[Install]\nWantedBy=multi-user.target\n""",
encoding="utf-8",
)
service_path.chmod(0o644)
systemctl = shutil_which("systemctl") or "/usr/bin/systemctl"
proc = _run([systemctl, "daemon-reload"], timeout=15)
if proc.returncode != 0:
raise ValueError(proc.stderr.strip() or "systemd daemon-reload failed")
proc = _run([systemctl, "enable", "--now", service_name], timeout=35)
if proc.returncode != 0:
raise ValueError(proc.stderr.strip() or f"Could not start {service_name}")
return conf, service_name
def _local_transport_rollback(conf: Path | None, service_name: str | None) -> None:
systemctl = shutil_which("systemctl") or "/usr/bin/systemctl"
if service_name:
_run([systemctl, "disable", "--now", service_name], timeout=20)
try:
(Path("/etc/systemd/system") / service_name).unlink(missing_ok=True)
except Exception:
pass
_run([systemctl, "daemon-reload"], timeout=10)
if conf:
try:
conf.unlink(missing_ok=True)
except Exception:
pass
def _local_transport_remove(item: dict[str, Any]) -> None:
"""Detach only the local WGTools side of a Relay tenant.
The remote VPS tenant is deliberately left untouched so a restored WGTools
backup can reconnect to the same Relay identity later.
"""
tenant_id = str(item.get("tenant_id") or "").strip()
vps_id = str(item.get("id") or "").strip()
iface = str(item.get("transport_interface") or "").strip()
if not tenant_id or not vps_id:
raise ValueError("Relay identity is incomplete")
systemctl = shutil_which("systemctl") or "/usr/bin/systemctl"
service_name = _local_service_name(tenant_id)
service_path = Path("/etc/systemd/system") / service_name
directory = LOCAL_RELAY_DIR / vps_id
conf = directory / f"{iface}.conf" if iface else None
# wg-quick is normally stopped by systemd. Continue if the unit or config
# was already missing, then make sure no stale local interface survives.
_run([systemctl, "disable", "--now", service_name], timeout=30)
if iface:
ip = shutil_which("ip") or "/usr/sbin/ip"
probe = _run([ip, "link", "show", "dev", iface], timeout=5)
if probe.returncode == 0:
if conf and conf.exists():
wg_quick = shutil_which("wg-quick") or "/usr/bin/wg-quick"
_run([wg_quick, "down", str(conf)], timeout=20)
probe = _run([ip, "link", "show", "dev", iface], timeout=5)
if probe.returncode == 0:
_run([ip, "link", "delete", "dev", iface], timeout=10)
try:
service_path.unlink(missing_ok=True)
except OSError as exc:
raise ValueError(f"Could not remove local Relay service: {exc}") from exc
# This directory contains only the home-side private transport material for
# this WGTools record. The remote /var/lib/wgtools-relay tenant is not used.
if directory.exists():
import shutil
try:
shutil.rmtree(directory)
except OSError as exc:
raise ValueError(f"Could not remove local Relay state: {exc}") from exc
_run([systemctl, "daemon-reload"], timeout=15)
def detach_vps(vps_id: str) -> dict[str, Any]:
"""Remove an installed VPS from this WGTools instance only.
No SSH connection is made and nothing is deleted on the VPS. The remote
Relay Agent, tenant, keys and token remain available for disaster recovery.
"""
init_vps_database()
item = get_vps(vps_id, include_secrets=True)
if not item:
raise ValueError("VPS entry not found")
if str(item.get("status") or "") != "installed":
raise ValueError("Only an installed VPS Relay can be removed here")
_local_transport_remove(item)
# Keep the Relay identity and home-side private key in SQLite, but hide the
# entry from the active VPS list. This makes a later re-add on the same
# WGTools instance a real reconnect rather than a new tenant provision.
now = int(time.time())
with _connect_db() as conn:
conn.execute(
"UPDATE vps_relays SET status='detached',last_health=0,last_error='',updated_at=? WHERE id=?",
(now, vps_id),
)
return {
"ok": True,
"id": vps_id,
"name": str(item.get("name") or ""),
"tenant_id": str(item.get("tenant_id") or ""),
"remote_preserved": True,
}
def reconcile_local_relays() -> list[dict[str, Any]]:
"""Recreate missing home-side Relay transports from restored DB state.
Migration backups already contain the VPS Relay secrets in SQLite. This
makes a restored WGTools instance reconnect to the existing remote tenant
instead of provisioning a new one.
"""
init_vps_database()
results: list[dict[str, Any]] = []
with _connect_db() as conn:
rows = conn.execute("SELECT id FROM vps_relays WHERE status='installed' ORDER BY created_at,id").fetchall()
for row in rows:
vps_id = str(row["id"])
item = get_vps(vps_id, include_secrets=True) or {}
tenant_id = str(item.get("tenant_id") or "").strip()
iface = str(item.get("transport_interface") or "").strip()
home_private = str(item.get("home_transport_private_key") or "").strip()
relay_public = str(item.get("relay_transport_public_key") or "").strip()
host = str(item.get("host") or "").strip()
if not all((tenant_id, iface, home_private, relay_public, host)):
results.append({"id": vps_id, "ok": False, "error": "Relay restore data is incomplete"})
continue
try:
directory = LOCAL_RELAY_DIR / vps_id
conf = directory / f"{iface}.conf"
service_name = _local_service_name(tenant_id)
service_path = Path("/etc/systemd/system") / service_name
ip = shutil_which("ip") or "/usr/sbin/ip"
interface_up = _run([ip, "link", "show", "dev", iface], timeout=5).returncode == 0
changed = False
if not conf.exists() or not service_path.exists():
# Remove any partial local leftovers first. Remote state is never touched.
_local_transport_remove(item)
_local_transport_apply(
vps_id=vps_id,
tenant=item,
home_private_key=home_private,
relay_public_key=relay_public,
vps_host=host,
)
changed = True
elif not interface_up:
systemctl = shutil_which("systemctl") or "/usr/bin/systemctl"
proc = _run([systemctl, "restart", service_name], timeout=35)
if proc.returncode != 0:
raise ValueError(proc.stderr.strip() or f"Could not restart {service_name}")
changed = True
results.append({"id": vps_id, "ok": True, "changed": changed, "interface": iface})
except Exception as exc:
results.append({"id": vps_id, "ok": False, "error": str(exc)})
return results
def _relay_health_url(ip: str, port: int) -> str:
return f"http://{ip}:{port}/v1/health"
def _query_relay_health(item: dict[str, Any], *, timeout: float = 4.0) -> dict[str, Any]:
token = str(item.get("control_token") or "")
ip = str(item.get("relay_transport_ip") or "")
port = int(item.get("control_port") or RELAY_CONTROL_PORT)
if not token or not ip:
raise ValueError("Relay management connection is not configured")
request = (
f"GET /v1/health HTTP/1.1\r\nHost: {ip}\r\nAuthorization: Bearer {token}\r\n"
"Connection: close\r\n\r\n"
).encode("utf-8")
try:
with socket.create_connection((ip, port), timeout=timeout) as sock:
sock.settimeout(timeout)
sock.sendall(request)
chunks: list[bytes] = []
while True:
chunk = sock.recv(65536)
if not chunk:
break
chunks.append(chunk)
if sum(map(len, chunks)) > 1024 * 1024:
raise ValueError("Relay response is too large")
raw = b"".join(chunks)
header, body = raw.split(b"\r\n\r\n", 1)
status_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace")
if " 200 " not in status_line:
raise ValueError(f"Relay returned {status_line}")
data = json.loads(body.decode("utf-8"))
except (OSError, ValueError, json.JSONDecodeError) as exc:
raise ValueError(f"Relay management tunnel is not responding: {exc}") from exc
if not isinstance(data, dict) or not data.get("ok"):
raise ValueError(str(data.get("error") if isinstance(data, dict) else "Invalid Relay response"))
return data
def relay_health(vps_id: str) -> dict[str, Any]:
item = get_vps(vps_id, include_secrets=True)
if not item:
raise ValueError("VPS entry not found")
if str(item.get("status")) != "installed":
raise ValueError("Relay is not installed")
now = int(time.time())
try:
data = _query_relay_health(item)
with _connect_db() as conn:
conn.execute("UPDATE vps_relays SET last_health=?,last_error='',updated_at=? WHERE id=?", (now, now, vps_id))
data["status"] = "installed"
return data
except ValueError as exc:
with _connect_db() as conn:
conn.execute("UPDATE vps_relays SET last_error=?,updated_at=? WHERE id=?", (str(exc), now, vps_id))
raise
def install_relay(
vps_id: str,
credentials: dict[str, Any],
*, published_interface: str,
home_wg_port: int,
) -> dict[str, Any]:
init_vps_database()
current = get_vps(vps_id, include_secrets=True)
if not current:
raise ValueError("VPS candidate not found")
if str(current.get("status")) == "installed":
return {"ok": True, "item": get_vps(vps_id), "health": relay_health(vps_id), "changed": False}
if not published_interface or not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", published_interface):
raise ValueError("Invalid WireGuard interface selected for Relay")
if not 1 <= int(home_wg_port) <= 65535:
raise ValueError("The selected WireGuard interface has no valid listen port")
payload = {
**credentials,
"name": current["name"], "host": current["host"], "ssh_port": current["ssh_port"],
"ssh_user": current["ssh_user"], "endpoint_domain": current["endpoint_domain"],
"relay_port": current["relay_port"], "transport_port": current["transport_port"],
}
preflight = preflight_vps(payload)
saved_fingerprint = str(current.get("host_key_fingerprint") or "")
current_fingerprint = str(preflight.get("host_key_fingerprint") or "")
if saved_fingerprint and current_fingerprint and saved_fingerprint != current_fingerprint:
raise ValueError("The VPS SSH host key changed since preflight. Remove and re-add this VPS only after verifying the server identity")
controller = controller_id()
preferred_tenant_id = str(current.get("tenant_id") or "")
with _ssh_session(payload) as (cfg, known_hosts, key_path, privilege_mode):
agent_info = _remote_agent_info(cfg, known_hosts, key_path, privilege_mode)
existing_tenant = _controller_remote_tenant(agent_info, preferred_tenant_id=preferred_tenant_id)
if existing_tenant:
# Reconnect to the tenant already created by this WGTools controller.
# No second tenant or UDP port pair is created.
tenant = dict(existing_tenant)
tenant_id = str(tenant.get("tenant_id") or "")
transport_interface = str(tenant.get("transport_interface") or "")
relay_port = int(tenant.get("relay_port") or 0)
transport_port = int(tenant.get("transport_port") or 0)
home_ip = str(tenant.get("home_transport_ip") or "")
relay_ip = str(tenant.get("relay_transport_ip") or "")
control_token = str(tenant.get("control_token") or "")
control_port = int(tenant.get("control_port") or RELAY_CONTROL_PORT)
relay_public = str(tenant.get("relay_transport_public_key") or "")
remote_home_public = str(tenant.get("home_transport_public_key") or "")
remote_interface = str(tenant.get("published_interface") or "")
remote_home_wg_port = int(tenant.get("home_wg_port") or 0)
if not all((tenant_id, transport_interface, relay_port, transport_port, home_ip, relay_ip, control_token, relay_public)):
raise ValueError("Existing Relay tenant on the VPS is incomplete and cannot be reconnected safely")
if remote_interface and remote_interface != published_interface:
raise ValueError(f"Existing Relay belongs to WireGuard interface {remote_interface}, not {published_interface}")
# The tenant identity belongs to this WGTools controller and the same
# published interface. A changed WireGuard ListenPort is a normal
# server setting change, not a reason to provision a second tenant.
# Synchronize the preserved VPS tenant to the current home port.
effective_home_wg_port = int(home_wg_port)
port_updated = remote_home_wg_port != effective_home_wg_port
if port_updated:
_remote_set_home_wg_port(
cfg, known_hosts, key_path, privilege_mode,
tenant=tenant, home_wg_port=effective_home_wg_port,
)
tenant["home_wg_port"] = effective_home_wg_port
# v0.19.10+ keeps this private key in a detached DB row. If v0.19.9
# already deleted the row, recover the SAME tenant by rotating only
# its home-side transport peer key on the VPS.
home_private = ""
if preferred_tenant_id == tenant_id:
home_private = str(current.get("home_transport_private_key") or "")
home_public = _wg_public_key(home_private) if home_private else ""
rekeyed = False
old_remote_home_public = remote_home_public
if not home_private or not home_public or (remote_home_public and home_public != remote_home_public):
home_private, home_public = _wg_keypair()
_remote_set_home_public_key(
cfg, known_hosts, key_path, privilege_mode,
tenant=tenant, public_key=home_public,
)
rekeyed = True
conf: Path | None = None
local_service: str | None = None
try:
tenant.update({
"control_token": control_token,
"control_port": control_port,
"home_wg_port": effective_home_wg_port,
"published_interface": remote_interface or published_interface,
})
conf, local_service = _local_transport_apply(
vps_id=vps_id, tenant=tenant, home_private_key=home_private,
relay_public_key=relay_public, vps_host=str(current["host"]),
)
health: dict[str, Any] | None = None
last_error = ""
for _ in range(15):
time.sleep(1)
try:
probe_item = {**current, **tenant, "control_token": control_token, "status": "installed"}
health = _query_relay_health(probe_item, timeout=2.0)
break
except ValueError as exc:
last_error = str(exc)
if health is None:
raise ValueError(last_error or "Relay management tunnel did not become ready")
except Exception:
_local_transport_rollback(conf, local_service)
if rekeyed and old_remote_home_public:
try:
_remote_set_home_public_key(
cfg, known_hosts, key_path, privilege_mode,
tenant=tenant, public_key=old_remote_home_public,
)
except Exception:
pass
if port_updated and remote_home_wg_port:
try:
_remote_set_home_wg_port(
cfg, known_hosts, key_path, privilege_mode,
tenant=tenant, home_wg_port=remote_home_wg_port,
)
except Exception:
pass
raise
now = int(time.time())
agent_id = str((agent_info.get("agent") or {}).get("agent_id") or "")
with _connect_db() as conn:
conn.execute(
"""UPDATE vps_relays SET relay_port=?,transport_port=?,status='installed',
agent_id=?,tenant_id=?,controller_id=?,control_token=?,transport_interface=?,
home_transport_ip=?,relay_transport_ip=?,control_port=?,published_interface=?,
home_wg_port=?,home_transport_private_key=?,relay_transport_public_key=?,
installed_at=CASE WHEN installed_at>0 THEN installed_at ELSE ? END,
last_health=?,last_error='',updated_at=? WHERE id=?""",
(
relay_port, transport_port, agent_id, tenant_id, controller, control_token,
transport_interface, home_ip, relay_ip, control_port,
remote_interface or published_interface, effective_home_wg_port,
home_private, relay_public, int(tenant.get("created_at") or now),
now, now, vps_id,
),
)
return {
"ok": True, "changed": True, "reconnected": True,
"item": get_vps(vps_id), "health": health,
}
# No tenant from this controller exists on the VPS: provision a new one.
relay_port = int(preflight["relay_port"])
transport_port = int(preflight["transport_port"])
tenant_id = uuid.uuid4().hex
control_token = secrets.token_urlsafe(36)
transport_interface = _transport_interface_name(tenant_id)
remote_tenants = list(agent_info.get("tenants") or [])
network = _allocate_transport_network(tenant_id, remote_tenants)
home_ip = str(network.network_address + 1)
relay_ip = str(network.network_address + 2)
home_private, home_public = _wg_keypair()
relay_private, relay_public = _wg_keypair()
agent_id = str((agent_info.get("agent") or {}).get("agent_id") or uuid.uuid4().hex)
tenant = {
"tenant_id": tenant_id,
"controller_id": controller,
"relay_port": relay_port,
"transport_port": transport_port,
"transport_interface": transport_interface,
"home_transport_ip": home_ip,
"relay_transport_ip": relay_ip,
"home_wg_port": int(home_wg_port),
"published_interface": published_interface,
"control_token": control_token,
"control_port": RELAY_CONTROL_PORT,
"created_at": int(time.time()),
}
if not RELAY_AGENT_SOURCE.is_file() or not RELAY_AGENT_UNIT_SOURCE.is_file():
raise ValueError("WGTools Relay Agent files are missing from this installation")
remote_script = _remote_install_script(
agent_id=agent_id, tenant=tenant, relay_private_key=relay_private,
home_public_key=home_public,
agent_source=RELAY_AGENT_SOURCE.read_text(encoding="utf-8"),
agent_unit=RELAY_AGENT_UNIT_SOURCE.read_text(encoding="utf-8"),
agent_preexisting=bool(agent_info.get("installed")),
)
code, _out, err = _root_exec(
cfg, "bash -s", known_hosts, key_path, privilege_mode,
stdin_text=remote_script, timeout=300,
)
if code != 0:
raise ValueError("Relay installation on VPS failed: " + (err or "remote installer failed"))
conf: Path | None = None
local_service: str | None = None
try:
conf, local_service = _local_transport_apply(
vps_id=vps_id, tenant=tenant, home_private_key=home_private,
relay_public_key=relay_public, vps_host=str(current["host"]),
)
health: dict[str, Any] | None = None
last_error = ""
for _ in range(15):
time.sleep(1)
try:
probe_item = {**current, **tenant, "control_token": control_token, "status": "installed"}
health = _query_relay_health(probe_item, timeout=2.0)
break
except ValueError as exc:
last_error = str(exc)
if health is None:
raise ValueError(last_error or "Relay management tunnel did not become ready")
except Exception:
_local_transport_rollback(conf, local_service)
rollback_script = f'''set -e
systemctl disable --now {_remote_service_name(tenant_id)} >/dev/null 2>&1 || true
rm -f /etc/systemd/system/{_remote_service_name(tenant_id)}
rm -rf /var/lib/wgtools-relay/tenants/{tenant_id}
systemctl daemon-reload
systemctl restart wgtools-relay-agent.service >/dev/null 2>&1 || true
'''
_root_exec(cfg, "bash -s", known_hosts, key_path, privilege_mode, stdin_text=rollback_script, timeout=30)
raise
now = int(time.time())
with _connect_db() as conn:
conn.execute(
"""UPDATE vps_relays SET relay_port=?,transport_port=?,status='installed',
agent_id=?,tenant_id=?,controller_id=?,control_token=?,transport_interface=?,
home_transport_ip=?,relay_transport_ip=?,control_port=?,published_interface=?,
home_wg_port=?,home_transport_private_key=?,relay_transport_public_key=?,
installed_at=?,last_health=?,last_error='',updated_at=? WHERE id=?""",
(
relay_port, transport_port, agent_id, tenant_id, controller, control_token,
transport_interface, home_ip, relay_ip, RELAY_CONTROL_PORT, published_interface,
int(home_wg_port), home_private, relay_public, now, now, now, vps_id,
),
)
return {"ok": True, "changed": True, "reconnected": False, "item": get_vps(vps_id), "health": health}