ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(remote-access): per-edge port allocation + blocked-UDP diagnostic (Phase 4)
Juan Denisee7d492dd2fc
diff --git a/backend/app/services/tunnel_broker_service.py b/backend/app/services/tunnel_broker_service.pyindex d4add129..410d5689 100644--- a/backend/app/services/tunnel_broker_service.py+++ b/backend/app/services/tunnel_broker_service.py@@ -19,7 +19,6 @@ from app.services import tunnel_netutillogger = logging.getLogger(__name__)KEEPALIVE_SECONDS = 25-DEFAULT_LISTEN_PORT = 51820class TunnelBrokerError(Exception):@@ -103,6 +102,16 @@ class TunnelBrokerService:except RuntimeError as e:raise TunnelBrokerError(str(e), code='POOL_EXHAUSTED', status=409)+ # Allocate a listen port unique to this edge (#20) so one edge can+ # front multiple private peers without UDP-port conflicts.+ used_ports = [t.listen_port for t in Tunnel.query+ .with_entities(Tunnel.listen_port)+ .filter(Tunnel.edge_server_id == edge_server_id).all()]+ try:+ listen_port = tunnel_netutil.pick_listen_port(used_ports)+ except RuntimeError as e:+ raise TunnelBrokerError(str(e), code='PORT_POOL_EXHAUSTED', status=409)+tunnel = Tunnel(name=name or ("%s → %s" % (edge.name, private.name)),edge_server_id=edge_server_id,@@ -110,7 +119,7 @@ class TunnelBrokerService:subnet=subnet,edge_wg_ip=edge_ip,private_wg_ip=private_ip,- listen_port=DEFAULT_LISTEN_PORT,+ listen_port=listen_port,status='pending',)db.session.add(tunnel)@@ -192,7 +201,16 @@ class TunnelBrokerService:if latest:tunnel.last_handshake_at = datetime.utcfromtimestamp(latest)db.session.commit()- return {'tunnel': tunnel.to_dict(), 'edge': edge_status, 'private': private_status}+ # Reachability diagnostic (#21): flag a likely blocked-UDP case.+ age = None+ if tunnel.created_at:+ try:+ age = now - tunnel.created_at.timestamp()+ except Exception:+ age = None+ diagnostic = tunnel_netutil.diagnose_reachability(latest, age, iface_up)+ return {'tunnel': tunnel.to_dict(), 'edge': edge_status,+ 'private': private_status, 'diagnostic': diagnostic}@classmethoddef _safe_status(cls, server_id, iface, user_id):diff --git a/backend/app/services/tunnel_netutil.py b/backend/app/services/tunnel_netutil.pyindex 890883a2..048b4152 100644--- a/backend/app/services/tunnel_netutil.py+++ b/backend/app/services/tunnel_netutil.py@@ -16,6 +16,15 @@ TUNNEL_POOL = "10.88.0.0/16"# rehandshakes well inside it when persistent-keepalive is 25s.HANDSHAKE_FRESH_SECONDS = 180+# WireGuard listen ports are allocated per edge (#20) so ONE edge can front+# many private peers — each tunnel needs its own UDP port. 51820..52019.+DEFAULT_LISTEN_PORT = 51820+LISTEN_PORT_RANGE = 200++# A tunnel with both interfaces up but no handshake after this long likely+# has its outbound UDP blocked (#21).+HANDSHAKE_GRACE_SECONDS = 45+def pick_subnet(used_subnets):"""Return (subnet_cidr, edge_ip, private_ip) for the first free /24 in@@ -69,3 +78,41 @@ def validate_endpoint_host(ip_address):except ValueError:return Falsereturn not (ip.is_loopback or ip.is_unspecified)+++def pick_listen_port(used_ports):+ """First free WireGuard listen port for an edge, starting at+ DEFAULT_LISTEN_PORT. ``used_ports`` is the ports already taken by other+ tunnels on the SAME edge — so one edge can front many private peers (#20).+ Raises RuntimeError if the per-edge pool is exhausted.+ """+ used = set(used_ports or [])+ for port in range(DEFAULT_LISTEN_PORT, DEFAULT_LISTEN_PORT + LISTEN_PORT_RANGE):+ if port not in used:+ return port+ raise RuntimeError(+ "listen-port pool exhausted on this edge (%d..%d)"+ % (DEFAULT_LISTEN_PORT, DEFAULT_LISTEN_PORT + LISTEN_PORT_RANGE - 1)+ )+++def diagnose_reachability(latest_handshake_epoch, age_seconds, both_interfaces_up):+ """Near-term #21: classify why a tunnel isn't passing traffic, with an+ actionable hint. The actual relay data plane is deferred.++ - 'interface_down' — an agent hasn't brought its interface up+ - 'ok' — a handshake has happened+ - 'connecting' — interfaces up, still within the handshake grace window+ - 'no_handshake' — up + past grace + no handshake → outbound UDP likely blocked+ """+ if not both_interfaces_up:+ return {'state': 'interface_down',+ 'hint': 'One or both agents have not brought the WireGuard interface up.'}+ if latest_handshake_epoch and latest_handshake_epoch > 0:+ return {'state': 'ok'}+ if age_seconds is not None and age_seconds < HANDSHAKE_GRACE_SECONDS:+ return {'state': 'connecting', 'hint': 'Waiting for the first WireGuard handshake.'}+ return {'state': 'no_handshake',+ 'hint': ("No WireGuard handshake yet — the private host's outbound UDP to the "+ "edge may be blocked by its network. A relay (roadmap #21) would be "+ "needed to traverse it.")}diff --git a/backend/tests/test_tunnel_netutil.py b/backend/tests/test_tunnel_netutil.pyindex 688be1e7..f0ada3b4 100644--- a/backend/tests/test_tunnel_netutil.py+++ b/backend/tests/test_tunnel_netutil.py@@ -53,3 +53,27 @@ def test_validate_endpoint_host():assert tn.validate_endpoint_host('0.0.0.0') is False # unspecifiedassert tn.validate_endpoint_host('') is Falseassert tn.validate_endpoint_host('not-an-ip') is False+++def test_pick_listen_port():+ assert tn.pick_listen_port([]) == 51820+ assert tn.pick_listen_port([51820]) == 51821+ assert tn.pick_listen_port([51820, 51821, 51823]) == 51822 # fills the gap+++def test_pick_listen_port_exhausted():+ used = list(range(tn.DEFAULT_LISTEN_PORT, tn.DEFAULT_LISTEN_PORT + tn.LISTEN_PORT_RANGE))+ try:+ tn.pick_listen_port(used)+ assert False, "expected RuntimeError on exhausted port pool"+ except RuntimeError:+ pass+++def test_diagnose_reachability():+ assert tn.diagnose_reachability(0, None, False)['state'] == 'interface_down'+ assert tn.diagnose_reachability(1_700_000_000, 999, True)['state'] == 'ok'+ assert tn.diagnose_reachability(0, 5, True)['state'] == 'connecting'+ d = tn.diagnose_reachability(0, 600, True)+ assert d['state'] == 'no_handshake'+ assert 'blocked' in d['hint'].lower()diff --git a/frontend/src/pages/RemoteAccess.jsx b/frontend/src/pages/RemoteAccess.jsxindex 9c2984f3..e13abd89 100644--- a/frontend/src/pages/RemoteAccess.jsx+++ b/frontend/src/pages/RemoteAccess.jsx@@ -231,6 +231,11 @@ const RemoteAccess = () => {{t.subnet} · {t.interface_name} · UDP {t.listen_port}{t.last_handshake_at ? ` · handshake ${new Date(t.last_handshake_at).toLocaleString()}` : ' · no handshake yet'}</div>+ {!t.last_handshake_at && t.status !== 'up' && (+ <p className="text-xs text-yellow-600 mt-1">+ No handshake yet — if this persists, the private host's outbound UDP to the edge may be blocked (a relay is needed).+ </p>+ )}</div><div className="flex items-center gap-2 shrink-0"><Button variant="outline" size="sm" onClick={() => openWizard(t)}>