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): NAT-traversing WireGuard tunnels to expose private services
Juan Denis7cf8d4e18ad6
diff --git a/.gitignore b/.gitignoreindex 7d221557..f6f1618e 100644--- a/.gitignore+++ b/.gitignore@@ -129,3 +129,4 @@ docs/PLAN_AGENT_FLEET.md/.github/skills/.playwright-mcpdocs/UI_CONSISTENCY_AUDIT.md+docs/REMOTE_ACCESS_ROADMAP.mddiff --git a/agent/go.mod b/agent/go.modindex 48563e98..740d59a2 100644--- a/agent/go.mod+++ b/agent/go.mod@@ -1,16 +1,20 @@module github.com/serverkit/agent-go 1.23.0+go 1.23.1require (fyne.io/systray v1.11.0github.com/creack/pty v1.1.21github.com/docker/docker v24.0.7+incompatible+ github.com/docker/go-connections v0.4.0github.com/gorilla/websocket v1.5.1+ github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808github.com/lxn/walk v0.0.0-20210112085537-c389da54e794github.com/shirou/gopsutil/v3 v3.24.1github.com/spf13/cobra v1.8.0- golang.org/x/term v0.27.0+ golang.org/x/sys v0.32.0+ golang.org/x/term v0.31.0+ golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446gopkg.in/natefinch/lumberjack.v2 v2.2.1gopkg.in/yaml.v3 v3.0.1)@@ -19,20 +23,19 @@ require (github.com/Microsoft/go-winio v0.6.1 // indirectgithub.com/distribution/reference v0.5.0 // indirectgithub.com/docker/distribution v2.8.3+incompatible // indirect- github.com/docker/go-connections v0.4.0 // indirectgithub.com/docker/go-units v0.5.0 // indirectgithub.com/go-ole/go-ole v1.3.0 // indirectgithub.com/godbus/dbus/v5 v5.1.0 // indirectgithub.com/gogo/protobuf v1.3.2 // indirect+ github.com/google/btree v1.1.2 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirect- github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 // indirectgithub.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirectgithub.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed // indirectgithub.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirectgithub.com/moby/term v0.5.0 // indirectgithub.com/morikuni/aec v1.0.0 // indirectgithub.com/opencontainers/go-digest v1.0.0 // indirect- github.com/opencontainers/image-spec v1.1.0-rc5 // indirect+ github.com/opencontainers/image-spec v1.1.0 // indirectgithub.com/pkg/errors v0.9.1 // indirectgithub.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirectgithub.com/shoenig/go-m1cpu v0.1.6 // indirect@@ -40,11 +43,14 @@ require (github.com/tklauser/go-sysconf v0.3.13 // indirectgithub.com/tklauser/numcpus v0.7.0 // indirectgithub.com/yusufpapurcu/wmi v1.2.3 // indirect- golang.org/x/mod v0.14.0 // indirect- golang.org/x/net v0.19.0 // indirect- golang.org/x/sys v0.28.0 // indirect- golang.org/x/time v0.5.0 // indirect- golang.org/x/tools v0.16.1 // indirect+ golang.org/x/crypto v0.37.0 // indirect+ golang.org/x/mod v0.21.0 // indirect+ golang.org/x/net v0.39.0 // indirect+ golang.org/x/sync v0.8.0 // indirect+ golang.org/x/time v0.7.0 // indirect+ golang.org/x/tools v0.26.0 // indirect+ golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirectgopkg.in/Knetic/govaluate.v3 v3.0.0 // indirectgotest.tools/v3 v3.5.1 // indirect+ gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c // indirect)diff --git a/agent/go.sum b/agent/go.sumindex c771112f..982b5fb8 100644--- a/agent/go.sum+++ b/agent/go.sum@@ -27,6 +27,8 @@ github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=+github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU=+github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=@@ -54,8 +56,8 @@ github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=-github.com/opencontainers/image-spec v1.1.0-rc5 h1:Ygwkfw9bpDvs+c9E34SdgGOj41dX/cbdlwvlWt0pnFI=-github.com/opencontainers/image-spec v1.1.0-rc5/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8=+github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=+github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=@@ -94,21 +96,23 @@ github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQgolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=+golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=+golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=-golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=-golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=+golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=+golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=-golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=-golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=+golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=+golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=-golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=-golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=+golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=+golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=@@ -121,24 +125,28 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=-golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=-golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=-golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=-golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=+golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=+golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=+golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=+golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=-golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=-golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=+golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ=+golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=-golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA=-golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=+golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ=+golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=+golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=+golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w=+golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=gopkg.in/Knetic/govaluate.v3 v3.0.0 h1:18mUyIt4ZlRlFZAAfVetz4/rzlJs9yhN+U02F4u1AOc=gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=@@ -150,3 +158,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=+gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI=+gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c/go.mod h1:3r5CMtNQMKIvBlrmM9xWUNamjKBYPOWyXOjmg5Kts3g=diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.goindex f292b6c2..857e3478 100644--- a/agent/internal/agent/agent.go+++ b/agent/internal/agent/agent.go@@ -32,29 +32,31 @@ import ("github.com/serverkit/agent/internal/transport""github.com/serverkit/agent/internal/transport/poll""github.com/serverkit/agent/internal/updater"+ "github.com/serverkit/agent/internal/wireguard""github.com/serverkit/agent/internal/ws""github.com/serverkit/agent/pkg/protocol")// Agent is the main agent that coordinates all componentstype Agent struct {- cfg *config.Config- log *logger.Logger- auth *auth.Authenticator+ cfg *config.Config+ log *logger.Logger+ auth *auth.Authenticator// ws is the active transport — either the WS client directly or the// fallback Manager that wraps WS+poll. Named "ws" for compatibility// with the dozens of existing call sites in this file.- ws transport.Transport+ ws transport.Transportdocker *docker.Clientmetrics *metrics.Collectorterminal *terminal.Managercron cron.Managercloudflared cloudflared.Manager+ wireguard wireguard.Manageripc *ipc.Server- sampler *metricSampler- events *events.Store- gui *gui.SDK- jobs *jobs.Registry+ sampler *metricSampler+ events *events.Store+ gui *gui.SDK+ jobs *jobs.Registry// pkgLock serializes package-manager mutations (install / remove /// upgrade / update_cache) inside a single agent so two concurrent@@ -144,6 +146,14 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {}eventStore := events.NewStore(200, events.DefaultPath(dataDir))+ // WireGuard private keys live in a root-only subdir of the agent's+ // data dir; empty dataDir falls back to a system default inside the+ // wireguard package.+ wgKeyDir := ""+ if dataDir != "" {+ wgKeyDir = filepath.Join(dataDir, "wireguard")+ }+agent := &Agent{cfg: cfg,log: log,@@ -154,6 +164,7 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {terminal: termManager,cron: cron.New(),cloudflared: cloudflared.New(),+ wireguard: wireguard.New(wgKeyDir),sampler: newMetricSampler(300), // 5 min @ 1 Hzevents: eventStore,gui: gui.New(log),@@ -166,7 +177,7 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {// At most one restart can be in-flight at a time anyway —// Restart() uses a non-blocking send and returns "already in// progress" if the slot is full.- restartCh: make(chan struct{}, 1),+ restartCh: make(chan struct{}, 1),}// Probe capabilities up-front so connectionWatcher can ship them on@@ -289,6 +300,24 @@ func (a *Agent) registerHandlers() {a.handlers[protocol.ActionCloudflaredTunnelRoute] = a.handleCloudflaredTunnelRoutea.handlers[protocol.ActionCloudflaredTunnelDelete] = a.handleCloudflaredTunnelDelete+ // WireGuard tunnel primitives. Registered unconditionally so+ // non-Linux agents return a clear "unsupported" error rather than+ // "unknown action"; the `wireguard` capability gates the panel's+ // Remote Access flow. See docs/REMOTE_ACCESS_ROADMAP.md.+ a.handlers[protocol.ActionWireguardKeygen] = a.handleWireguardKeygen+ a.handlers[protocol.ActionWireguardInterfaceUp] = a.handleWireguardInterfaceUp+ a.handlers[protocol.ActionWireguardInterfaceDown] = a.handleWireguardInterfaceDown+ a.handlers[protocol.ActionWireguardPeerSet] = a.handleWireguardPeerSet+ a.handlers[protocol.ActionWireguardPeerRemove] = a.handleWireguardPeerRemove+ a.handlers[protocol.ActionWireguardStatus] = a.handleWireguardStatus+ a.handlers[protocol.ActionWireguardForward] = a.handleWireguardForward+ a.handlers[protocol.ActionWireguardUnforward] = a.handleWireguardUnforward++ // Firewall — used by the tunnel broker to open the edge's WireGuard+ // UDP port (#10). Linux-only; returns a clear error elsewhere.+ a.handlers[protocol.ActionFirewallAllowPort] = a.handleFirewallAllowPort+ a.handlers[protocol.ActionFirewallDenyPort] = a.handleFirewallDenyPort+// Phase 4 primitives — packages, systemd, exec. Registered// unconditionally so non-Linux agents return a clear error rather// than "unknown action"; the capability probe gates the panel's@@ -999,8 +1028,9 @@ func (a *Agent) handleCredentialUpdate(data []byte) {// only when the signature is present, well-formed, and matches.//// The panel must compute hex(HMAC-SHA256(-// "rotation_id:agent_id:new_api_key:new_api_secret",-// current_api_secret)).+//+// "rotation_id:agent_id:new_api_key:new_api_secret",+// current_api_secret)).func (a *Agent) verifyCredentialRotation(msg protocol.CredentialUpdateMessage) error {if msg.RotationID == "" || msg.APIKey == "" || msg.APISecret == "" {return fmt.Errorf("rotation message missing required fields")@@ -1781,7 +1811,7 @@ func (a *Agent) handleAgentUpdate(ctx context.Context, params json.RawMessage) (// In a real implementation, we would use the provided URLs// For now, we'll let the updater handle it using its default logic// or extend it to use the provided URLs.-+err := u.UpdateTo(context.Background(), p.Version, p.DownloadURL, p.ChecksumsURL)if err != nil {a.log.Error("Update failed", "error", err)diff --git a/agent/internal/agent/firewall_handlers.go b/agent/internal/agent/firewall_handlers.gonew file mode 100644index 00000000..10a9fda3--- /dev/null+++ b/agent/internal/agent/firewall_handlers.go@@ -0,0 +1,86 @@+package agent++import (+ "context"+ "encoding/json"+ "fmt"+ "os/exec"+ "runtime"+ "strconv"+ "strings"+)++// Handlers for firewall:* actions. Minimal host-firewall control so the+// tunnel broker can open the edge's inbound WireGuard UDP port (roadmap+// #10). Linux-only; tries ufw → firewalld → iptables, first present.+// Requires root (the agent already runs privileged for systemd/packages);+// failures return a clear error and the broker falls back to surfacing+// the manual command.++func (a *Agent) handleFirewallAllowPort(_ context.Context, params json.RawMessage) (interface{}, error) {+ return firewallPort(params, true)+}++func (a *Agent) handleFirewallDenyPort(_ context.Context, params json.RawMessage) (interface{}, error) {+ return firewallPort(params, false)+}++func firewallPort(params json.RawMessage, allow bool) (interface{}, error) {+ var p struct {+ Port int `json:"port"`+ Protocol string `json:"protocol"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if p.Port < 1 || p.Port > 65535 {+ return nil, fmt.Errorf("invalid port %d", p.Port)+ }+ proto := strings.ToLower(strings.TrimSpace(p.Protocol))+ if proto != "tcp" && proto != "udp" {+ proto = "udp"+ }+ if runtime.GOOS != "linux" {+ return nil, fmt.Errorf("firewall management is only supported on Linux agents")+ }+ spec := fmt.Sprintf("%d/%s", p.Port, proto)++ if _, err := exec.LookPath("ufw"); err == nil {+ action := "allow"+ if !allow {+ action = "deny"+ }+ if out, err := exec.Command("ufw", action, spec).CombinedOutput(); err != nil {+ return nil, fmt.Errorf("ufw %s %s: %w (%s)", action, spec, err, strings.TrimSpace(string(out)))+ }+ return map[string]interface{}{"success": true, "method": "ufw", "spec": spec}, nil+ }++ if _, err := exec.LookPath("firewall-cmd"); err == nil {+ flag := "--add-port"+ if !allow {+ flag = "--remove-port"+ }+ if out, err := exec.Command("firewall-cmd", flag+"="+spec).CombinedOutput(); err != nil {+ return nil, fmt.Errorf("firewall-cmd %s=%s: %w (%s)", flag, spec, err, strings.TrimSpace(string(out)))+ }+ // Persist across reboots (best-effort) + reload.+ _, _ = exec.Command("firewall-cmd", flag+"="+spec, "--permanent").CombinedOutput()+ _, _ = exec.Command("firewall-cmd", "--reload").CombinedOutput()+ return map[string]interface{}{"success": true, "method": "firewalld", "spec": spec}, nil+ }++ if _, err := exec.LookPath("iptables"); err == nil {+ op := "-I" // insert (allow)+ if !allow {+ op = "-D" // delete the rule+ }+ out, err := exec.Command("iptables", op, "INPUT", "-p", proto, "--dport", strconv.Itoa(p.Port), "-j", "ACCEPT").CombinedOutput()+ if err != nil {+ return nil, fmt.Errorf("iptables %s %s: %w (%s)", op, spec, err, strings.TrimSpace(string(out)))+ }+ return map[string]interface{}{"success": true, "method": "iptables", "spec": spec}, nil+ }++ return nil, fmt.Errorf("no supported firewall found (ufw / firewalld / iptables)")+}diff --git a/agent/internal/agent/wireguard_handlers.go b/agent/internal/agent/wireguard_handlers.gonew file mode 100644index 00000000..e98aa5a8--- /dev/null+++ b/agent/internal/agent/wireguard_handlers.go@@ -0,0 +1,105 @@+package agent++import (+ "context"+ "encoding/json"+ "fmt"++ "github.com/serverkit/agent/internal/wireguard"+)++// Handlers for wireguard:* actions. Thin parse + dispatch; validation+// lives in the wireguard package. The panel's tunnel broker+// (backend/app/services/tunnel_broker_service.py) sequences these to+// pair two agents. See docs/REMOTE_ACCESS_ROADMAP.md.++func (a *Agent) handleWireguardKeygen(_ context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Interface string `json:"interface"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ return a.wireguard.Keygen(p.Interface)+}++func (a *Agent) handleWireguardInterfaceUp(_ context.Context, params json.RawMessage) (interface{}, error) {+ var req wireguard.InterfaceUpRequest+ if err := json.Unmarshal(params, &req); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if err := a.wireguard.InterfaceUp(req); err != nil {+ return nil, err+ }+ return map[string]bool{"success": true}, nil+}++func (a *Agent) handleWireguardInterfaceDown(_ context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Interface string `json:"interface"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if err := a.wireguard.InterfaceDown(p.Interface); err != nil {+ return nil, err+ }+ return map[string]bool{"success": true}, nil+}++func (a *Agent) handleWireguardPeerSet(_ context.Context, params json.RawMessage) (interface{}, error) {+ var req wireguard.PeerSetRequest+ if err := json.Unmarshal(params, &req); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if err := a.wireguard.SetPeer(req); err != nil {+ return nil, err+ }+ return map[string]bool{"success": true}, nil+}++func (a *Agent) handleWireguardPeerRemove(_ context.Context, params json.RawMessage) (interface{}, error) {+ var req wireguard.PeerRemoveRequest+ if err := json.Unmarshal(params, &req); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if err := a.wireguard.RemovePeer(req); err != nil {+ return nil, err+ }+ return map[string]bool{"success": true}, nil+}++func (a *Agent) handleWireguardStatus(_ context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Interface string `json:"interface"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ return a.wireguard.Status(p.Interface)+}++func (a *Agent) handleWireguardForward(_ context.Context, params json.RawMessage) (interface{}, error) {+ var req wireguard.ForwardRequest+ if err := json.Unmarshal(params, &req); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if err := a.wireguard.Forward(req); err != nil {+ return nil, err+ }+ return map[string]bool{"success": true}, nil+}++func (a *Agent) handleWireguardUnforward(_ context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Interface string `json:"interface"`+ ListenPort int `json:"listen_port"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if err := a.wireguard.Unforward(p.Interface, p.ListenPort); err != nil {+ return nil, err+ }+ return map[string]bool{"success": true}, nil+}diff --git a/agent/internal/capabilities/capabilities.go b/agent/internal/capabilities/capabilities.goindex 7d7e142c..755f73eb 100644--- a/agent/internal/capabilities/capabilities.go+++ b/agent/internal/capabilities/capabilities.go@@ -64,6 +64,15 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool, fileAc// happens in the cloudflared:status action).caps["cloudflared"] = probeCloudflared()+ // WireGuard — the agent can manage a tunnel interface: kernel WG on+ // Linux (`wg` + `ip`), userspace wireguard-go on Windows/macOS. The+ // panel gates the Remote Access / tunnel flow on this.+ caps["wireguard"] = probeWireguard()++ // Firewall — a supported host firewall is present so the broker can+ // open the edge's WireGuard UDP port (#10). Linux-only.+ caps["firewall"] = probeFirewall()+// Language runtimes — best-effort version probes. A missing key// means "not installed"; an empty string means "installed but// `--version` parse failed" so the panel can still light up the@@ -95,6 +104,8 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool, fileAc"php_fpm", caps["php_fpm"],"packages", caps["packages"],"cloudflared", caps["cloudflared"],+ "wireguard", caps["wireguard"],+ "firewall", caps["firewall"],"runtimes", runtimes,)}@@ -126,6 +137,26 @@ func probeCloudflared() bool {return hasOnPath("cloudflared")}+// probeWireguard — whether the agent can manage a WireGuard interface.+// On Linux that needs the kernel tools (`wg` + `ip`); on Windows/macOS+// the userspace wireguard-go backend (roadmap #6) is always available.+func probeWireguard() bool {+ if runtime.GOOS == "linux" {+ return hasOnPath("wg") && hasOnPath("ip")+ }+ return true+}++// probeFirewall — true on Linux when a supported host firewall+// (ufw / firewalld / iptables) is on PATH, so the tunnel broker can open+// the edge's WireGuard UDP port (#10).+func probeFirewall() bool {+ if runtime.GOOS != "linux" {+ return false+ }+ return hasOnPath("ufw") || hasOnPath("firewall-cmd") || hasOnPath("iptables")+}+// probeRuntimes detects common language runtimes by shelling out to// each "<bin> --version" and parsing the first line. Versions are kept// as raw strings (e.g. "3.11.4", "20.10.0", "8.2.0") so consumers candiff --git a/agent/internal/wireguard/wireguard.go b/agent/internal/wireguard/wireguard.gonew file mode 100644index 00000000..78a3d992--- /dev/null+++ b/agent/internal/wireguard/wireguard.go@@ -0,0 +1,326 @@+// Package wireguard manages a WireGuard interface on the agent host so+// the panel can pair two agents into a NAT-traversing tunnel (the+// "edge" agent on a public IP + a "private" agent behind NAT). See+// docs/REMOTE_ACCESS_ROADMAP.md.+//+// Split mirrors the cloudflared package:+// - wireguard.go — the platform-agnostic Manager interface,+// shared request/result types, key generation+// and validation.+// - wireguard_linux.go — the real backend (kernel WireGuard via the+// `wg` + `ip` tools).+// - wireguard_other.go — a stub that reports "unsupported" until the+// userspace wireguard-go backend (roadmap #6)+// lands for Windows/macOS private peers.+//+// Security model (stated once):+//+// Private keys NEVER leave the host. Keygen generates the keypair+// locally, persists the private key in a root-only file under the+// agent's key directory, and returns ONLY the public key in the+// command result. The panel brokers public keys + endpoints ++// allowed-IPs; it never sees, transmits or stores a private key.+package wireguard++import (+ "crypto/ecdh"+ "crypto/rand"+ "encoding/base64"+ "fmt"+ "io"+ "net"+ "regexp"+ "strconv"+ "strings"+)++// Keypair is a WireGuard (Curve25519 / X25519) keypair, base64-encoded+// in the canonical `wg` format. PrivateKey is host-only and must never+// be serialized to the panel — it carries `json:"-"` for that reason.+type Keypair struct {+ PrivateKey string `json:"-"`+ PublicKey string `json:"public_key"`+}++// KeygenResult is what the wireguard:keygen command returns to the+// panel: the public key only.+type KeygenResult struct {+ PublicKey string `json:"public_key"`+}++// InterfaceUpRequest brings up (or reconciles) a WireGuard interface.+// ListenPort is set only on the edge agent; the private agent dials+// out and lets the kernel pick an ephemeral source port.+type InterfaceUpRequest struct {+ Name string `json:"name"` // e.g. "skwg0"+ Address string `json:"address"` // CIDR, e.g. "10.88.0.2/24"+ ListenPort int `json:"listen_port"` // 0 = unset (private side)+}++// PeerSetRequest adds or updates a single peer on an interface. On the+// private side, Endpoint points at the edge (`ip:port`) and+// PersistentKeepalive is set (typically 25s) to punch and hold the NAT+// mapping. On the edge side, Endpoint is empty (learned on handshake).+type PeerSetRequest struct {+ Interface string `json:"interface"`+ PublicKey string `json:"public_key"`+ AllowedIPs []string `json:"allowed_ips"`+ Endpoint string `json:"endpoint,omitempty"`+ PersistentKeepalive int `json:"persistent_keepalive,omitempty"`+}++// PeerRemoveRequest removes a peer from an interface.+type PeerRemoveRequest struct {+ Interface string `json:"interface"`+ PublicKey string `json:"public_key"`+}++// PeerStatus mirrors one peer row from `wg show <iface> dump`.+type PeerStatus struct {+ PublicKey string `json:"public_key"`+ Endpoint string `json:"endpoint,omitempty"`+ AllowedIPs []string `json:"allowed_ips,omitempty"`+ LatestHandshake int64 `json:"latest_handshake"` // unix seconds; 0 = never+ TransferRx int64 `json:"transfer_rx"` // bytes+ TransferTx int64 `json:"transfer_tx"` // bytes+ PersistentKeepalive int `json:"persistent_keepalive,omitempty"`+}++// InterfaceStatus is the wireguard:status result for one interface.+// Up=false (with a nil/empty Peers) means the interface doesn't exist+// yet — the panel polls this on a not-yet-built tunnel without it being+// an error.+type InterfaceStatus struct {+ Name string `json:"name"`+ PublicKey string `json:"public_key,omitempty"`+ ListenPort int `json:"listen_port,omitempty"`+ Up bool `json:"up"`+ Peers []PeerStatus `json:"peers"`+}++// Manager is the platform-agnostic surface the agent's handlers call.+// The Linux build wires it to kernel WireGuard; non-Linux builds return+// "unsupported" until roadmap #6.+type Manager interface {+ // Available reports whether this host can manage WireGuard (kernel+ // tools present on Linux; userspace backend on others once #6 lands).+ Available() bool+ // Keygen generates a keypair for iface, persists the private key+ // locally (root-only), and returns the public key.+ Keygen(iface string) (*KeygenResult, error)+ // InterfaceUp creates/reconciles the interface using the persisted+ // private key. Idempotent.+ InterfaceUp(req InterfaceUpRequest) error+ // InterfaceDown tears the interface down. Idempotent (a missing+ // interface is a no-op success).+ InterfaceDown(iface string) error+ // SetPeer adds or updates a peer. Idempotent.+ SetPeer(req PeerSetRequest) error+ // RemovePeer removes a peer. Idempotent.+ RemovePeer(req PeerRemoveRequest) error+ // Status returns the live interface + peer state.+ Status(iface string) (*InterfaceStatus, error)+ // Forward starts a TCP forwarder: it accepts connections arriving over+ // the tunnel at ListenIP:ListenPort and proxies each to+ // TargetHost:TargetPort on the host. This is how a service behind a+ // userspace (netstack) peer is reached — and is uniform for the kernel+ // backend. Idempotent per (interface, ListenPort): re-Forward replaces.+ Forward(req ForwardRequest) error+ // Unforward stops the forwarder for ListenPort on iface (idempotent).+ Unforward(iface string, listenPort int) error+}++// ForwardRequest configures a tunnel→host TCP forwarder (roadmap #13).+// On the private peer, ListenIP is the peer's own WireGuard IP, and the+// service (e.g. Jellyfin) listens on TargetHost:TargetPort on the host.+type ForwardRequest struct {+ Interface string `json:"interface"`+ ListenIP string `json:"listen_ip"` // the WG IP to listen on, e.g. 10.88.3.2+ ListenPort int `json:"listen_port"` // WG-side port the edge proxies to+ TargetHost string `json:"target_host"` // default 127.0.0.1+ TargetPort int `json:"target_port"` // default = ListenPort+}++func (r ForwardRequest) normalized() ForwardRequest {+ if r.TargetHost == "" {+ r.TargetHost = "127.0.0.1"+ }+ if r.TargetPort == 0 {+ r.TargetPort = r.ListenPort+ }+ return r+}++func validateForward(req ForwardRequest) error {+ if err := validIfaceName(req.Interface); err != nil {+ return err+ }+ if net.ParseIP(req.ListenIP) == nil {+ return fmt.Errorf("invalid listen_ip %q", req.ListenIP)+ }+ if req.ListenPort < 1 || req.ListenPort > 65535 {+ return fmt.Errorf("invalid listen_port %d", req.ListenPort)+ }+ if req.TargetPort < 0 || req.TargetPort > 65535 {+ return fmt.Errorf("invalid target_port %d", req.TargetPort)+ }+ return nil+}++// forwardKey identifies a forwarder by interface + listen port.+func forwardKey(iface string, port int) string {+ return iface + ":" + strconv.Itoa(port)+}++// serveForward accepts on l and proxies each connection to+// targetHost:targetPort until l is closed. Backends create the listener+// (kernel: net.Listen on the real WG iface; userspace: tnet.ListenTCP)+// then hand it here.+func serveForward(l net.Listener, targetHost string, targetPort int) {+ target := net.JoinHostPort(targetHost, strconv.Itoa(targetPort))+ for {+ conn, err := l.Accept()+ if err != nil {+ return // listener closed+ }+ go proxyConn(conn, target)+ }+}++func proxyConn(client net.Conn, target string) {+ defer client.Close()+ server, err := net.Dial("tcp", target)+ if err != nil {+ return+ }+ defer server.Close()+ done := make(chan struct{}, 2)+ cp := func(dst, src net.Conn) { _, _ = io.Copy(dst, src); done <- struct{}{} }+ go cp(server, client)+ go cp(client, server)+ <-done // first side to close ends the pair (defers close both)+}++// GenerateKeypair produces a fresh WireGuard keypair. X25519 via+// crypto/ecdh, which clamps the scalar exactly as WireGuard expects;+// the byte layout and base64 encoding match `wg genkey | wg pubkey`.+// Shared across all platforms — keygen is pure crypto and works even+// where interface management doesn't.+func GenerateKeypair() (*Keypair, error) {+ priv, err := ecdh.X25519().GenerateKey(rand.Reader)+ if err != nil {+ return nil, fmt.Errorf("generate x25519 key: %w", err)+ }+ return &Keypair{+ PrivateKey: base64.StdEncoding.EncodeToString(priv.Bytes()),+ PublicKey: base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes()),+ }, nil+}++// PublicKeyFromPrivate derives the base64 WireGuard public key from a+// base64 private key (X25519 scalar-mult with the base point, matching+// `wg pubkey`). The userspace backend uses this for Status, where it+// only has the private key on hand.+func PublicKeyFromPrivate(privB64 string) (string, error) {+ raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(privB64))+ if err != nil || len(raw) != 32 {+ return "", fmt.Errorf("invalid private key")+ }+ priv, err := ecdh.X25519().NewPrivateKey(raw)+ if err != nil {+ return "", err+ }+ return base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes()), nil+}++// --- validation helpers (shared, so both backends and tests reuse) ---++// ifaceNameRegex constrains interface names to what the Linux kernel+// accepts (IFNAMSIZ is 16 including the NUL, so 15 usable chars) and+// what won't trip shell/`ip` parsing.+var ifaceNameRegex = regexp.MustCompile(`^[A-Za-z0-9_-]{1,15}$`)++func validIfaceName(name string) error {+ if !ifaceNameRegex.MatchString(name) {+ return fmt.Errorf("invalid interface name %q (alphanumeric, -, _, max 15 chars)", name)+ }+ return nil+}++// validPublicKey checks a base64 WireGuard key decodes to 32 bytes.+func validPublicKey(key string) error {+ raw, err := base64.StdEncoding.DecodeString(key)+ if err != nil {+ return fmt.Errorf("public key is not valid base64")+ }+ if len(raw) != 32 {+ return fmt.Errorf("public key must be 32 bytes, got %d", len(raw))+ }+ return nil+}++// validCIDR checks a "addr/prefix" string parses.+func validCIDR(cidr string) error {+ if _, _, err := net.ParseCIDR(cidr); err != nil {+ return fmt.Errorf("invalid CIDR %q: %w", cidr, err)+ }+ return nil+}++// validEndpoint checks a "host:port" with a numeric, in-range port.+func validEndpoint(ep string) error {+ host, port, err := net.SplitHostPort(ep)+ if err != nil {+ return fmt.Errorf("invalid endpoint %q (want host:port): %w", ep, err)+ }+ if host == "" {+ return fmt.Errorf("invalid endpoint %q: empty host", ep)+ }+ p := 0+ if _, err := fmt.Sscanf(port, "%d", &p); err != nil || p < 1 || p > 65535 {+ return fmt.Errorf("invalid endpoint port %q", port)+ }+ return nil+}++// validateInterfaceUp validates an InterfaceUpRequest. Shared so the+// stub can reject bad input identically to the real backend.+func validateInterfaceUp(req InterfaceUpRequest) error {+ if err := validIfaceName(req.Name); err != nil {+ return err+ }+ if err := validCIDR(req.Address); err != nil {+ return err+ }+ if req.ListenPort < 0 || req.ListenPort > 65535 {+ return fmt.Errorf("invalid listen_port %d", req.ListenPort)+ }+ return nil+}++// validatePeerSet validates a PeerSetRequest.+func validatePeerSet(req PeerSetRequest) error {+ if err := validIfaceName(req.Interface); err != nil {+ return err+ }+ if err := validPublicKey(req.PublicKey); err != nil {+ return err+ }+ if len(req.AllowedIPs) == 0 {+ return fmt.Errorf("allowed_ips is required")+ }+ for _, ip := range req.AllowedIPs {+ if err := validCIDR(strings.TrimSpace(ip)); err != nil {+ return err+ }+ }+ if req.Endpoint != "" {+ if err := validEndpoint(req.Endpoint); err != nil {+ return err+ }+ }+ if req.PersistentKeepalive < 0 || req.PersistentKeepalive > 65535 {+ return fmt.Errorf("invalid persistent_keepalive %d", req.PersistentKeepalive)+ }+ return nil+}diff --git a/agent/internal/wireguard/wireguard_dump_linux_test.go b/agent/internal/wireguard/wireguard_dump_linux_test.gonew file mode 100644index 00000000..94586ecf--- /dev/null+++ b/agent/internal/wireguard/wireguard_dump_linux_test.go@@ -0,0 +1,63 @@+//go:build linux++package wireguard++import "testing"++// TestParseWgDump checks the `wg show <iface> dump` parser, and in+// particular guards the security-critical invariant: the interface+// line's field[0] is the PRIVATE key and must never surface — we read+// field[1] (public) for InterfaceStatus.PublicKey.+func TestParseWgDump(t *testing.T) {+ dump := "PRIVATEKEYMUSTNOTLEAK=\tIFACEPUBKEY=\t51820\toff\n" ++ "PEERPUBKEY=\t(none)\t203.0.113.5:51820\t10.88.0.2/32\t1700000000\t1024\t2048\t25\n" ++ "PEER2PUBKEY=\t(none)\t(none)\t(none)\t0\t0\t0\toff\n"++ st := &InterfaceStatus{Name: "skwg0", Peers: []PeerStatus{}}+ parseWgDump(dump, st)++ if st.PublicKey != "IFACEPUBKEY=" {+ t.Errorf("interface PublicKey = %q, want field[1] IFACEPUBKEY=", st.PublicKey)+ }+ if st.PublicKey == "PRIVATEKEYMUSTNOTLEAK=" {+ t.Fatal("LEAK: interface private key surfaced as PublicKey")+ }+ if st.ListenPort != 51820 {+ t.Errorf("ListenPort = %d, want 51820", st.ListenPort)+ }+ if len(st.Peers) != 2 {+ t.Fatalf("want 2 peers, got %d", len(st.Peers))+ }++ p := st.Peers[0]+ if p.PublicKey != "PEERPUBKEY=" {+ t.Errorf("peer0 PublicKey = %q", p.PublicKey)+ }+ if p.Endpoint != "203.0.113.5:51820" {+ t.Errorf("peer0 Endpoint = %q", p.Endpoint)+ }+ if len(p.AllowedIPs) != 1 || p.AllowedIPs[0] != "10.88.0.2/32" {+ t.Errorf("peer0 AllowedIPs = %v", p.AllowedIPs)+ }+ if p.LatestHandshake != 1700000000 {+ t.Errorf("peer0 LatestHandshake = %d", p.LatestHandshake)+ }+ if p.TransferRx != 1024 || p.TransferTx != 2048 {+ t.Errorf("peer0 transfer rx/tx = %d/%d", p.TransferRx, p.TransferTx)+ }+ if p.PersistentKeepalive != 25 {+ t.Errorf("peer0 PersistentKeepalive = %d", p.PersistentKeepalive)+ }++ // peer1: "(none)" endpoint → empty, "off" keepalive → 0+ p2 := st.Peers[1]+ if p2.Endpoint != "" {+ t.Errorf("peer1 Endpoint = %q, want empty", p2.Endpoint)+ }+ if len(p2.AllowedIPs) != 0 {+ t.Errorf("peer1 AllowedIPs = %v, want empty", p2.AllowedIPs)+ }+ if p2.PersistentKeepalive != 0 {+ t.Errorf("peer1 PersistentKeepalive = %d, want 0", p2.PersistentKeepalive)+ }+}diff --git a/agent/internal/wireguard/wireguard_linux.go b/agent/internal/wireguard/wireguard_linux.gonew file mode 100644index 00000000..27aee77e--- /dev/null+++ b/agent/internal/wireguard/wireguard_linux.go@@ -0,0 +1,291 @@+//go:build linux++package wireguard++import (+ "bytes"+ "context"+ "fmt"+ "net"+ "os"+ "os/exec"+ "path/filepath"+ "strconv"+ "strings"+ "sync"+ "time"+)++// defaultKeyDir is used when the agent didn't supply a data directory.+const defaultKeyDir = "/etc/serverkit-agent/wireguard"++// New returns a Linux Manager backed by kernel WireGuard (`wg` + `ip`).+// keyDir is where per-interface private keys are persisted (root-only);+// empty falls back to defaultKeyDir.+func New(keyDir string) Manager {+ if keyDir == "" {+ keyDir = defaultKeyDir+ }+ return &linuxManager{keyDir: keyDir, forwards: map[string]net.Listener{}}+}++type linuxManager struct {+ keyDir string+ mu sync.Mutex+ forwards map[string]net.Listener+}++func (m *linuxManager) keyPath(iface string) string {+ return filepath.Join(m.keyDir, iface+".key")+}++func (m *linuxManager) Available() bool {+ return onPath("wg") && onPath("ip")+}++func onPath(bin string) bool {+ _, err := exec.LookPath(bin)+ return err == nil+}++// run executes a command with a short ceiling and returns stdout, with+// stderr folded into any error (the panel surfaces these directly).+func run(name string, args ...string) (string, error) {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, name, args...)+ var stdout, stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ if err := cmd.Run(); err != nil {+ return "", fmt.Errorf("%s %s: %w (%s)",+ name, strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))+ }+ return stdout.String(), nil+}++func (m *linuxManager) Keygen(iface string) (*KeygenResult, error) {+ if err := validIfaceName(iface); err != nil {+ return nil, err+ }+ kp, err := GenerateKeypair()+ if err != nil {+ return nil, err+ }+ if err := os.MkdirAll(m.keyDir, 0o700); err != nil {+ return nil, fmt.Errorf("create key dir: %w", err)+ }+ // 0600 + the key dir at 0700: the private key is readable only by+ // the agent's (root) user. It never travels to the panel.+ if err := os.WriteFile(m.keyPath(iface), []byte(kp.PrivateKey+"\n"), 0o600); err != nil {+ return nil, fmt.Errorf("persist private key: %w", err)+ }+ return &KeygenResult{PublicKey: kp.PublicKey}, nil+}++func (m *linuxManager) linkExists(iface string) bool {+ _, err := run("ip", "link", "show", iface)+ return err == nil+}++func (m *linuxManager) InterfaceUp(req InterfaceUpRequest) error {+ if err := validateInterfaceUp(req); err != nil {+ return err+ }+ keyPath := m.keyPath(req.Name)+ if _, err := os.Stat(keyPath); err != nil {+ return fmt.Errorf("no private key for %q — run wireguard:keygen first", req.Name)+ }++ // 1. Create the interface if it doesn't already exist (idempotent).+ if !m.linkExists(req.Name) {+ if _, err := run("ip", "link", "add", "dev", req.Name, "type", "wireguard"); err != nil {+ return err+ }+ }++ // 2. Apply the private key (+ listen port on the edge side).+ wgArgs := []string{"set", req.Name}+ if req.ListenPort > 0 {+ wgArgs = append(wgArgs, "listen-port", strconv.Itoa(req.ListenPort))+ }+ wgArgs = append(wgArgs, "private-key", keyPath)+ if _, err := run("wg", wgArgs...); err != nil {+ return err+ }++ // 3. Address — `replace` adds or updates, so re-running up is safe.+ if _, err := run("ip", "address", "replace", req.Address, "dev", req.Name); err != nil {+ return err+ }++ // 4. Bring it up.+ if _, err := run("ip", "link", "set", req.Name, "up"); err != nil {+ return err+ }+ return nil+}++func (m *linuxManager) InterfaceDown(iface string) error {+ if err := validIfaceName(iface); err != nil {+ return err+ }+ m.closeForwards(iface)+ if !m.linkExists(iface) {+ return nil // already gone — idempotent+ }+ _, err := run("ip", "link", "del", "dev", iface)+ return err+}++func (m *linuxManager) Forward(req ForwardRequest) error {+ if err := validateForward(req); err != nil {+ return err+ }+ req = req.normalized()+ // The WG IP is a real address on the kernel interface, so a normal+ // listen on it receives traffic arriving over the tunnel.+ l, err := net.Listen("tcp", net.JoinHostPort(req.ListenIP, strconv.Itoa(req.ListenPort)))+ if err != nil {+ return fmt.Errorf("listen %s:%d: %w", req.ListenIP, req.ListenPort, err)+ }+ key := forwardKey(req.Interface, req.ListenPort)+ m.mu.Lock()+ if old, ok := m.forwards[key]; ok {+ old.Close()+ }+ m.forwards[key] = l+ m.mu.Unlock()+ go serveForward(l, req.TargetHost, req.TargetPort)+ return nil+}++func (m *linuxManager) Unforward(iface string, listenPort int) error {+ if err := validIfaceName(iface); err != nil {+ return err+ }+ key := forwardKey(iface, listenPort)+ m.mu.Lock()+ defer m.mu.Unlock()+ if l, ok := m.forwards[key]; ok {+ l.Close()+ delete(m.forwards, key)+ }+ return nil+}++// closeForwards stops every forwarder bound to iface (called on teardown).+func (m *linuxManager) closeForwards(iface string) {+ m.mu.Lock()+ defer m.mu.Unlock()+ for k, l := range m.forwards {+ if strings.HasPrefix(k, iface+":") {+ l.Close()+ delete(m.forwards, k)+ }+ }+}++func (m *linuxManager) SetPeer(req PeerSetRequest) error {+ if err := validatePeerSet(req); err != nil {+ return err+ }+ args := []string{"set", req.Interface, "peer", req.PublicKey,+ "allowed-ips", strings.Join(req.AllowedIPs, ",")}+ if req.Endpoint != "" {+ args = append(args, "endpoint", req.Endpoint)+ }+ if req.PersistentKeepalive > 0 {+ args = append(args, "persistent-keepalive", strconv.Itoa(req.PersistentKeepalive))+ }+ _, err := run("wg", args...)+ return err+}++func (m *linuxManager) RemovePeer(req PeerRemoveRequest) error {+ if err := validIfaceName(req.Interface); err != nil {+ return err+ }+ if err := validPublicKey(req.PublicKey); err != nil {+ return err+ }+ _, err := run("wg", "set", req.Interface, "peer", req.PublicKey, "remove")+ return err+}++func (m *linuxManager) Status(iface string) (*InterfaceStatus, error) {+ if err := validIfaceName(iface); err != nil {+ return nil, err+ }+ st := &InterfaceStatus{Name: iface, Peers: []PeerStatus{}}++ out, err := run("wg", "show", iface, "dump")+ if err != nil {+ // The interface most likely doesn't exist yet — report "down"+ // rather than erroring so the panel can poll a tunnel that's+ // still being built.+ return st, nil+ }+ st.Up = true+ parseWgDump(out, st)+ return st, nil+}++// parseWgDump parses `wg show <iface> dump`. Line 1 is the interface+// (private-key, public-key, listen-port, fwmark); subsequent lines are+// peers (public-key, preshared-key, endpoint, allowed-ips,+// latest-handshake, transfer-rx, transfer-tx, persistent-keepalive).+//+// IMPORTANT: field [0] of the interface line is the PRIVATE key. We+// read field [1] (public) and deliberately never surface field [0].+func parseWgDump(out string, st *InterfaceStatus) {+ lines := strings.Split(strings.TrimSpace(out), "\n")+ for i, line := range lines {+ if line == "" {+ continue+ }+ f := strings.Split(line, "\t")+ if i == 0 {+ // interface line+ if len(f) >= 2 {+ st.PublicKey = f[1]+ }+ if len(f) >= 3 {+ st.ListenPort = atoiSafe(f[2])+ }+ continue+ }+ // peer line+ if len(f) < 8 {+ continue+ }+ p := PeerStatus{PublicKey: f[0]}+ if f[2] != "(none)" {+ p.Endpoint = f[2]+ }+ if f[3] != "(none)" && f[3] != "" {+ for _, a := range strings.Split(f[3], ",") {+ if a = strings.TrimSpace(a); a != "" {+ p.AllowedIPs = append(p.AllowedIPs, a)+ }+ }+ }+ p.LatestHandshake = atoi64Safe(f[4])+ p.TransferRx = atoi64Safe(f[5])+ p.TransferTx = atoi64Safe(f[6])+ if f[7] != "off" {+ p.PersistentKeepalive = atoiSafe(f[7])+ }+ st.Peers = append(st.Peers, p)+ }+}++func atoiSafe(s string) int {+ n, _ := strconv.Atoi(strings.TrimSpace(s))+ return n+}++func atoi64Safe(s string) int64 {+ n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)+ return n+}diff --git a/agent/internal/wireguard/wireguard_other.go b/agent/internal/wireguard/wireguard_other.gonew file mode 100644index 00000000..c46f0bc7--- /dev/null+++ b/agent/internal/wireguard/wireguard_other.go@@ -0,0 +1,358 @@+//go:build !linux++package wireguard++import (+ "encoding/base64"+ "encoding/hex"+ "fmt"+ "net"+ "net/netip"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "sync"++ "golang.zx2c4.com/wireguard/conn"+ "golang.zx2c4.com/wireguard/device"+ "golang.zx2c4.com/wireguard/tun/netstack"+)++// Userspace WireGuard backend (roadmap #6) — wireguard-go + gVisor+// netstack. Pure userspace: NO kernel module, NO TUN driver (no Wintun),+// NO admin. That's what makes it viable on a home Windows/macOS box+// (e.g. the user's Jellyfin host).+//+// Difference vs the Linux kernel backend: netstack is an in-process+// TCP/IP stack, not a transparent L3 interface. keygen / interface:up /+// peer:set / status are fully functional (the WireGuard handshake works),+// which is what Phases 0–1 need. Forwarding a host service over the+// tunnel happens in Phase 2 through the retained *netstack.Net (tnet);+// the iface struct keeps it for exactly that.++// New returns a userspace Manager. keyDir holds per-interface private+// keys (0600); empty falls back to the user-config dir.+func New(keyDir string) Manager {+ if keyDir == "" {+ keyDir = userspaceDefaultKeyDir()+ }+ return &userspaceManager{+ keyDir: keyDir,+ ifaces: map[string]*usIface{},+ forwards: map[string]net.Listener{},+ }+}++func userspaceDefaultKeyDir() string {+ if dir, err := os.UserConfigDir(); err == nil {+ return filepath.Join(dir, "serverkit-agent", "wireguard")+ }+ return filepath.Join(os.TempDir(), "serverkit-agent-wireguard")+}++type userspaceManager struct {+ keyDir string+ mu sync.Mutex+ ifaces map[string]*usIface+ forwards map[string]net.Listener+}++type usIface struct {+ dev *device.Device+ tnet *netstack.Net // retained for Phase 2 service forwarding+ pubKey string // base64; derived at up, surfaced by Status+ listen int+}++func (m *userspaceManager) keyPath(iface string) string {+ return filepath.Join(m.keyDir, iface+".key")+}++func (m *userspaceManager) Available() bool { return true }++func (m *userspaceManager) Keygen(iface string) (*KeygenResult, error) {+ if err := validIfaceName(iface); err != nil {+ return nil, err+ }+ kp, err := GenerateKeypair()+ if err != nil {+ return nil, err+ }+ if err := os.MkdirAll(m.keyDir, 0o700); err != nil {+ return nil, fmt.Errorf("create key dir: %w", err)+ }+ if err := os.WriteFile(m.keyPath(iface), []byte(kp.PrivateKey+"\n"), 0o600); err != nil {+ return nil, fmt.Errorf("persist private key: %w", err)+ }+ return &KeygenResult{PublicKey: kp.PublicKey}, nil+}++func (m *userspaceManager) InterfaceUp(req InterfaceUpRequest) error {+ if err := validateInterfaceUp(req); err != nil {+ return err+ }+ raw, err := os.ReadFile(m.keyPath(req.Name))+ if err != nil {+ return fmt.Errorf("no private key for %q — run wireguard:keygen first", req.Name)+ }+ privB64 := strings.TrimSpace(string(raw))+ privHex, err := keyB64ToHex(privB64)+ if err != nil {+ return fmt.Errorf("bad stored private key: %w", err)+ }+ pub, err := PublicKeyFromPrivate(privB64)+ if err != nil {+ return fmt.Errorf("derive public key: %w", err)+ }+ prefix, err := netip.ParsePrefix(req.Address)+ if err != nil {+ return fmt.Errorf("bad address %q: %w", req.Address, err)+ }++ m.mu.Lock()+ defer m.mu.Unlock()+ if _, ok := m.ifaces[req.Name]; ok {+ return nil // idempotent: already up+ }++ tunDev, tnet, err := netstack.CreateNetTUN([]netip.Addr{prefix.Addr()}, nil, device.DefaultMTU)+ if err != nil {+ return fmt.Errorf("create userspace tun: %w", err)+ }+ dev := device.NewDevice(tunDev, conn.NewDefaultBind(),+ device.NewLogger(device.LogLevelError, "wg/"+req.Name+" "))++ var cfg strings.Builder+ cfg.WriteString("private_key=" + privHex + "\n")+ if req.ListenPort > 0 {+ cfg.WriteString("listen_port=" + strconv.Itoa(req.ListenPort) + "\n")+ }+ if err := dev.IpcSet(cfg.String()); err != nil {+ dev.Close()+ return fmt.Errorf("configure device: %w", err)+ }+ if err := dev.Up(); err != nil {+ dev.Close()+ return fmt.Errorf("bring up device: %w", err)+ }+ m.ifaces[req.Name] = &usIface{dev: dev, tnet: tnet, pubKey: pub, listen: req.ListenPort}+ return nil+}++func (m *userspaceManager) InterfaceDown(iface string) error {+ if err := validIfaceName(iface); err != nil {+ return err+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ for k, l := range m.forwards {+ if strings.HasPrefix(k, iface+":") {+ l.Close()+ delete(m.forwards, k)+ }+ }+ if ifc, ok := m.ifaces[iface]; ok {+ ifc.dev.Close()+ delete(m.ifaces, iface)+ }+ return nil // idempotent+}++func (m *userspaceManager) Forward(req ForwardRequest) error {+ if err := validateForward(req); err != nil {+ return err+ }+ req = req.normalized()+ m.mu.Lock()+ ifc := m.ifaces[req.Interface]+ m.mu.Unlock()+ if ifc == nil {+ return fmt.Errorf("interface %q is not up", req.Interface)+ }+ ip, err := netip.ParseAddr(req.ListenIP)+ if err != nil {+ return fmt.Errorf("invalid listen_ip %q: %w", req.ListenIP, err)+ }+ // Listen INSIDE the netstack on the WG IP — this receives the+ // connections the edge proxies over the tunnel. serveForward then+ // dials the real host service over the OS network.+ l, err := ifc.tnet.ListenTCPAddrPort(netip.AddrPortFrom(ip, uint16(req.ListenPort)))+ if err != nil {+ return fmt.Errorf("netstack listen %s:%d: %w", req.ListenIP, req.ListenPort, err)+ }+ key := forwardKey(req.Interface, req.ListenPort)+ m.mu.Lock()+ if old, ok := m.forwards[key]; ok {+ old.Close()+ }+ m.forwards[key] = l+ m.mu.Unlock()+ go serveForward(l, req.TargetHost, req.TargetPort)+ return nil+}++func (m *userspaceManager) Unforward(iface string, listenPort int) error {+ if err := validIfaceName(iface); err != nil {+ return err+ }+ key := forwardKey(iface, listenPort)+ m.mu.Lock()+ defer m.mu.Unlock()+ if l, ok := m.forwards[key]; ok {+ l.Close()+ delete(m.forwards, key)+ }+ return nil+}++func (m *userspaceManager) SetPeer(req PeerSetRequest) error {+ if err := validatePeerSet(req); err != nil {+ return err+ }+ m.mu.Lock()+ ifc := m.ifaces[req.Interface]+ m.mu.Unlock()+ if ifc == nil {+ return fmt.Errorf("interface %q is not up", req.Interface)+ }+ pubHex, err := keyB64ToHex(req.PublicKey)+ if err != nil {+ return fmt.Errorf("bad peer public key: %w", err)+ }+ var cfg strings.Builder+ cfg.WriteString("public_key=" + pubHex + "\n")+ cfg.WriteString("replace_allowed_ips=true\n")+ for _, ip := range req.AllowedIPs {+ cfg.WriteString("allowed_ip=" + strings.TrimSpace(ip) + "\n")+ }+ if req.Endpoint != "" {+ cfg.WriteString("endpoint=" + req.Endpoint + "\n")+ }+ if req.PersistentKeepalive > 0 {+ cfg.WriteString("persistent_keepalive_interval=" + strconv.Itoa(req.PersistentKeepalive) + "\n")+ }+ return ifc.dev.IpcSet(cfg.String())+}++func (m *userspaceManager) RemovePeer(req PeerRemoveRequest) error {+ if err := validIfaceName(req.Interface); err != nil {+ return err+ }+ if err := validPublicKey(req.PublicKey); err != nil {+ return err+ }+ m.mu.Lock()+ ifc := m.ifaces[req.Interface]+ m.mu.Unlock()+ if ifc == nil {+ return nil // nothing to remove+ }+ pubHex, err := keyB64ToHex(req.PublicKey)+ if err != nil {+ return fmt.Errorf("bad peer public key: %w", err)+ }+ return ifc.dev.IpcSet("public_key=" + pubHex + "\nremove=true\n")+}++func (m *userspaceManager) Status(iface string) (*InterfaceStatus, error) {+ if err := validIfaceName(iface); err != nil {+ return nil, err+ }+ st := &InterfaceStatus{Name: iface, Peers: []PeerStatus{}}+ m.mu.Lock()+ ifc := m.ifaces[iface]+ m.mu.Unlock()+ if ifc == nil {+ return st, nil // down+ }+ st.Up = true+ st.PublicKey = ifc.pubKey+ st.ListenPort = ifc.listen+ cfg, err := ifc.dev.IpcGet()+ if err != nil {+ return st, nil+ }+ parseUAPIStatus(cfg, st)+ return st, nil+}++// parseUAPIStatus parses wireguard-go's IpcGet() output into peers.+// It deliberately ignores the interface's private_key line (never+// surfaced). Peer public keys are converted hex→base64 to match the+// panel and the kernel backend's `wg show dump` output.+func parseUAPIStatus(cfg string, st *InterfaceStatus) {+ var cur *PeerStatus+ flush := func() {+ if cur != nil {+ st.Peers = append(st.Peers, *cur)+ cur = nil+ }+ }+ for _, line := range strings.Split(cfg, "\n") {+ line = strings.TrimSpace(line)+ if line == "" {+ continue+ }+ k, v, ok := strings.Cut(line, "=")+ if !ok {+ continue+ }+ switch k {+ case "public_key": // begins a new peer section+ flush()+ cur = &PeerStatus{PublicKey: keyHexToB64(v)}+ case "endpoint":+ if cur != nil {+ cur.Endpoint = v+ }+ case "allowed_ip":+ if cur != nil {+ cur.AllowedIPs = append(cur.AllowedIPs, v)+ }+ case "last_handshake_time_sec":+ if cur != nil {+ cur.LatestHandshake = atoi64u(v)+ }+ case "rx_bytes":+ if cur != nil {+ cur.TransferRx = atoi64u(v)+ }+ case "tx_bytes":+ if cur != nil {+ cur.TransferTx = atoi64u(v)+ }+ case "persistent_keepalive_interval":+ if cur != nil {+ cur.PersistentKeepalive = int(atoi64u(v))+ }+ }+ // private_key / preshared_key / errno / protocol_version /+ // last_handshake_time_nsec / listen_port / fwmark → ignored.+ }+ flush()+}++func keyB64ToHex(b64 string) (string, error) {+ raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(b64))+ if err != nil {+ return "", err+ }+ if len(raw) != 32 {+ return "", fmt.Errorf("key must be 32 bytes, got %d", len(raw))+ }+ return hex.EncodeToString(raw), nil+}++func keyHexToB64(h string) string {+ raw, err := hex.DecodeString(strings.TrimSpace(h))+ if err != nil {+ return h // fall back to the raw value on parse failure+ }+ return base64.StdEncoding.EncodeToString(raw)+}++func atoi64u(s string) int64 {+ n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)+ return n+}diff --git a/agent/internal/wireguard/wireguard_test.go b/agent/internal/wireguard/wireguard_test.gonew file mode 100644index 00000000..72dc95b1--- /dev/null+++ b/agent/internal/wireguard/wireguard_test.go@@ -0,0 +1,149 @@+package wireguard++import (+ "encoding/base64"+ "io"+ "net"+ "strconv"+ "testing"+ "time"+)++func TestGenerateKeypair(t *testing.T) {+ kp, err := GenerateKeypair()+ if err != nil {+ t.Fatalf("GenerateKeypair: %v", err)+ }+ if err := validPublicKey(kp.PublicKey); err != nil {+ t.Errorf("generated public key invalid: %v", err)+ }+ priv, err := base64.StdEncoding.DecodeString(kp.PrivateKey)+ if err != nil || len(priv) != 32 {+ t.Errorf("private key not 32 base64 bytes: err=%v len=%d", err, len(priv))+ }+ if kp.PrivateKey == kp.PublicKey {+ t.Error("private and public key are identical")+ }+ kp2, _ := GenerateKeypair()+ if kp.PrivateKey == kp2.PrivateKey {+ t.Error("two keygens produced identical private keys")+ }+}++func TestValidPublicKey(t *testing.T) {+ kp, _ := GenerateKeypair()+ if err := validPublicKey(kp.PublicKey); err != nil {+ t.Errorf("valid key rejected: %v", err)+ }+ if validPublicKey("not base64!!!") == nil {+ t.Error("non-base64 key accepted")+ }+ if validPublicKey(base64.StdEncoding.EncodeToString([]byte("short"))) == nil {+ t.Error("wrong-length key accepted")+ }+}++func TestValidateInterfaceUp(t *testing.T) {+ ok := InterfaceUpRequest{Name: "skwg0", Address: "10.88.0.1/24", ListenPort: 51820}+ if err := validateInterfaceUp(ok); err != nil {+ t.Errorf("valid request rejected: %v", err)+ }+ bad := []InterfaceUpRequest{+ {Name: "bad iface!", Address: "10.88.0.1/24"},+ {Name: "skwg0", Address: "not-a-cidr"},+ {Name: "skwg0", Address: "10.88.0.1/24", ListenPort: 70000},+ {Name: "this-name-is-far-too-long", Address: "10.88.0.1/24"},+ }+ for i, b := range bad {+ if validateInterfaceUp(b) == nil {+ t.Errorf("invalid request %d was accepted", i)+ }+ }+}++func TestValidatePeerSet(t *testing.T) {+ kp, _ := GenerateKeypair()+ ok := PeerSetRequest{+ Interface: "skwg0", PublicKey: kp.PublicKey,+ AllowedIPs: []string{"10.88.0.2/32"},+ Endpoint: "203.0.113.5:51820", PersistentKeepalive: 25,+ }+ if err := validatePeerSet(ok); err != nil {+ t.Errorf("valid peer rejected: %v", err)+ }+ bad := []PeerSetRequest{+ {Interface: "skwg0", PublicKey: "bad", AllowedIPs: []string{"10.88.0.2/32"}},+ {Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: nil},+ {Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: []string{"nope"}},+ {Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: []string{"10.88.0.2/32"}, Endpoint: "no-port"},+ }+ for i, b := range bad {+ if validatePeerSet(b) == nil {+ t.Errorf("invalid peer %d was accepted", i)+ }+ }+}++func TestPublicKeyFromPrivate(t *testing.T) {+ kp, _ := GenerateKeypair()+ pub, err := PublicKeyFromPrivate(kp.PrivateKey)+ if err != nil {+ t.Fatalf("PublicKeyFromPrivate: %v", err)+ }+ if pub != kp.PublicKey {+ t.Errorf("derived public key %s != keypair public key %s", pub, kp.PublicKey)+ }+ if _, err := PublicKeyFromPrivate("not-a-key"); err == nil {+ t.Error("accepted an invalid private key")+ }+}++// TestForwarder proves serveForward's accept loop + bidirectional proxy+// with real sockets (the listener-creation differs per backend, but the+// proxy plumbing is shared and is what carries the user's traffic).+func TestForwarder(t *testing.T) {+ // Echo server standing in for the real local service (e.g. Jellyfin).+ target, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("target listen: %v", err)+ }+ defer target.Close()+ go func() {+ for {+ c, err := target.Accept()+ if err != nil {+ return+ }+ go func(c net.Conn) { _, _ = io.Copy(c, c); c.Close() }(c)+ }+ }()+ _, tportStr, _ := net.SplitHostPort(target.Addr().String())+ tport, _ := strconv.Atoi(tportStr)++ // Forwarder listener standing in for the WG-side listen.+ fwd, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("forwarder listen: %v", err)+ }+ defer fwd.Close()+ go serveForward(fwd, "127.0.0.1", tport)++ conn, err := net.Dial("tcp", fwd.Addr().String())+ if err != nil {+ t.Fatalf("dial forwarder: %v", err)+ }+ defer conn.Close()+ _ = conn.SetDeadline(time.Now().Add(3 * time.Second))++ msg := []byte("hello-tunnel")+ if _, err := conn.Write(msg); err != nil {+ t.Fatalf("write: %v", err)+ }+ buf := make([]byte, len(msg))+ if _, err := io.ReadFull(conn, buf); err != nil {+ t.Fatalf("read: %v", err)+ }+ if string(buf) != string(msg) {+ t.Errorf("echo mismatch: got %q want %q", buf, msg)+ }+}diff --git a/agent/internal/wireguard/wireguard_userspace_test.go b/agent/internal/wireguard/wireguard_userspace_test.gonew file mode 100644index 00000000..6da68c92--- /dev/null+++ b/agent/internal/wireguard/wireguard_userspace_test.go@@ -0,0 +1,70 @@+//go:build !linux++package wireguard++import "testing"++func TestKeyHexRoundTrip(t *testing.T) {+ kp, _ := GenerateKeypair()+ h, err := keyB64ToHex(kp.PublicKey)+ if err != nil {+ t.Fatalf("keyB64ToHex: %v", err)+ }+ if len(h) != 64 {+ t.Errorf("hex key length = %d, want 64", len(h))+ }+ if back := keyHexToB64(h); back != kp.PublicKey {+ t.Errorf("roundtrip mismatch: %s != %s", back, kp.PublicKey)+ }+}++// TestParseUAPIStatus checks the wireguard-go IpcGet() parser and guards+// the no-leak invariant: the interface's private_key line must never end+// up in any surfaced field.+func TestParseUAPIStatus(t *testing.T) {+ ifaceKp, _ := GenerateKeypair()+ peerKp, _ := GenerateKeypair()+ privHex, _ := keyB64ToHex(ifaceKp.PrivateKey)+ peerHex, _ := keyB64ToHex(peerKp.PublicKey)++ cfg := "private_key=" + privHex + "\n" ++ "listen_port=51820\n" ++ "public_key=" + peerHex + "\n" ++ "endpoint=203.0.113.5:51820\n" ++ "allowed_ip=10.88.0.1/32\n" ++ "last_handshake_time_sec=1700000000\n" ++ "rx_bytes=1024\n" ++ "tx_bytes=2048\n" ++ "persistent_keepalive_interval=25\n" ++ "protocol_version=1\n"++ st := &InterfaceStatus{Name: "skwg0", Peers: []PeerStatus{}}+ parseUAPIStatus(cfg, st)++ if len(st.Peers) != 1 {+ t.Fatalf("want 1 peer, got %d", len(st.Peers))+ }+ p := st.Peers[0]+ if p.PublicKey != peerKp.PublicKey {+ t.Errorf("peer PublicKey = %s, want %s (hex→base64)", p.PublicKey, peerKp.PublicKey)+ }+ if p.Endpoint != "203.0.113.5:51820" {+ t.Errorf("Endpoint = %q", p.Endpoint)+ }+ if len(p.AllowedIPs) != 1 || p.AllowedIPs[0] != "10.88.0.1/32" {+ t.Errorf("AllowedIPs = %v", p.AllowedIPs)+ }+ if p.LatestHandshake != 1700000000 {+ t.Errorf("LatestHandshake = %d", p.LatestHandshake)+ }+ if p.TransferRx != 1024 || p.TransferTx != 2048 {+ t.Errorf("transfer rx/tx = %d/%d", p.TransferRx, p.TransferTx)+ }+ if p.PersistentKeepalive != 25 {+ t.Errorf("PersistentKeepalive = %d", p.PersistentKeepalive)+ }+ // No-leak: the private key (as base64) must not appear in any field.+ if p.PublicKey == ifaceKp.PrivateKey {+ t.Fatal("LEAK: interface private key surfaced as a peer public key")+ }+}diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.goindex d029bba4..ae254bf6 100644--- a/agent/pkg/protocol/messages.go+++ b/agent/pkg/protocol/messages.go@@ -10,9 +10,9 @@ type MessageType stringconst (// Authentication- TypeAuth MessageType = "auth"- TypeAuthOK MessageType = "auth_ok"- TypeAuthFail MessageType = "auth_fail"+ TypeAuth MessageType = "auth"+ TypeAuthOK MessageType = "auth_ok"+ TypeAuthFail MessageType = "auth_fail"// HeartbeatTypeHeartbeat MessageType = "heartbeat"@@ -330,6 +330,30 @@ const (ActionCloudflaredTunnelRoute = "cloudflared:tunnel:route"ActionCloudflaredTunnelDelete = "cloudflared:tunnel:delete"+ // WireGuard actions — manage a WireGuard interface so the panel can+ // pair two agents into a NAT-traversing tunnel (edge ↔ private). The+ // agent generates its keypair locally and returns ONLY the public+ // key; private keys never reach the panel. Linux-only until the+ // userspace backend (roadmap #6) lands. See+ // docs/REMOTE_ACCESS_ROADMAP.md.+ ActionWireguardKeygen = "wireguard:keygen"+ ActionWireguardInterfaceUp = "wireguard:interface:up"+ ActionWireguardInterfaceDown = "wireguard:interface:down"+ ActionWireguardPeerSet = "wireguard:peer:set"+ ActionWireguardPeerRemove = "wireguard:peer:remove"+ ActionWireguardStatus = "wireguard:status"+ // wireguard:forward starts a TCP forwarder on the private peer so a+ // connection arriving over the tunnel reaches the real local service+ // (roadmap #13). Essential for the userspace/netstack backend.+ ActionWireguardForward = "wireguard:forward"+ ActionWireguardUnforward = "wireguard:unforward"++ // Firewall actions — minimal host-firewall control so the tunnel+ // broker can open the edge's inbound WireGuard UDP port (#10).+ // Linux-only (ufw / firewalld / iptables).+ ActionFirewallAllowPort = "firewall:allow_port"+ ActionFirewallDenyPort = "firewall:deny_port"+// File actionsActionFileRead = "file:read"ActionFileWrite = "file:write"@@ -374,8 +398,10 @@ const (// CredentialUpdateMessage is sent by server to rotate credentials.//// HMACSig is computed by the panel as-// hex(HMAC-SHA256("rotation_id:agent_id:new_api_key:new_api_secret",-// current_api_secret))+//+// hex(HMAC-SHA256("rotation_id:agent_id:new_api_key:new_api_secret",+// current_api_secret))+//// where current_api_secret is the agent's secret prior to rotation.// The agent recomputes this with its own current secret and rejects// the rotation if they don't match. This prevents a panel sessiondiff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 5b7509f2..69338b63 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -94,6 +94,7 @@ def create_app(config_name=None):# Register blueprints - Corefrom app.api.apps import apps_bpfrom app.api.domains import domains_bp+ from app.api.tunnels import tunnels_bpfrom app.api.private_urls import private_urls_bpapp.register_blueprint(apps_bp, url_prefix='/api/v1/apps')app.register_blueprint(domains_bp, url_prefix='/api/v1/domains')@@ -291,6 +292,9 @@ def create_app(config_name=None):from app.api.cloud_provisioning import cloud_provisioning_bpapp.register_blueprint(cloud_provisioning_bp, url_prefix='/api/v1/cloud')+ # Register blueprints - Remote Access (WireGuard tunnels; imported above)+ app.register_blueprint(tunnels_bp, url_prefix='/api/v1/tunnels')+# Register blueprints - Performancefrom app.api.performance import performance_bpapp.register_blueprint(performance_bp, url_prefix='/api/v1/performance')diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.pyindex 00027dba..1426d006 100644--- a/backend/app/agent_gateway.py+++ b/backend/app/agent_gateway.py@@ -296,6 +296,18 @@ class AgentNamespace(Namespace):agent_registry.update_capabilities(agent.server_id, data or {})+ # Panel-authoritative tunnel reconcile (#19): if this agent can+ # drive WireGuard, re-apply (in the background) any tunnel config+ # it participates in, so tunnels self-heal after an agent or panel+ # restart. See docs/REMOTE_ACCESS_ROADMAP.md.+ try:+ caps = (data or {}).get('capabilities') or {}+ if caps.get('wireguard'):+ from app.services.tunnel_broker_service import TunnelBrokerService+ TunnelBrokerService.schedule_reconcile(agent.server_id)+ except Exception:+ logger.debug("tunnel reconcile scheduling skipped", exc_info=True)+def on_stream(self, data):"""Handle streaming data from agent (logs, metrics).diff --git a/backend/app/api/tunnels.py b/backend/app/api/tunnels.pynew file mode 100644index 00000000..7b58c7c0--- /dev/null+++ b/backend/app/api/tunnels.py@@ -0,0 +1,123 @@+"""Tunnels API (roadmap Phase 1 — #9).++Brokers WireGuard pairings between two agents (a public-IP edge + a NAT'd+private host) so a service behind NAT can be reached over the tunnel.+See docs/REMOTE_ACCESS_ROADMAP.md.+"""++from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.models.tunnel import Tunnel+from app.services.tunnel_broker_service import TunnelBrokerService, TunnelBrokerError+from app.services.tunnel_publish_service import TunnelPublishService, TunnelPublishError+from app.middleware.rbac import developer_required++tunnels_bp = Blueprint('tunnels', __name__)+++def _error(e):+ return jsonify({'error': e.message, 'code': e.code}), e.status+++@tunnels_bp.route('/', methods=['GET'])+@jwt_required()+def list_tunnels():+ tunnels = Tunnel.query.order_by(Tunnel.created_at.desc()).all()+ return jsonify({'tunnels': [t.to_dict() for t in tunnels]})+++@tunnels_bp.route('/', methods=['POST'])+@jwt_required()+@developer_required+def create_tunnel():+ data = request.get_json(silent=True) or {}+ edge = (data.get('edge_server_id') or '').strip()+ private = (data.get('private_server_id') or '').strip()+ name = (data.get('name') or '').strip() or None+ if not edge or not private:+ return jsonify({'error': 'edge_server_id and private_server_id are required'}), 400+ try:+ tunnel = TunnelBrokerService.create_tunnel(edge, private, name=name, user_id=get_jwt_identity())+ except TunnelBrokerError as e:+ return _error(e)+ body = tunnel.to_dict()+ fw = TunnelBrokerService.firewall_hint(tunnel.listen_port)+ auto = getattr(tunnel, 'firewall_status', None)+ if auto is not None:+ fw['auto_open'] = auto # outcome of the agent-driven open (#10)+ body['firewall'] = fw+ return jsonify(body), 201+++@tunnels_bp.route('/<tunnel_id>', methods=['GET'])+@jwt_required()+def get_tunnel(tunnel_id):+ try:+ tunnel = TunnelBrokerService.get_tunnel(tunnel_id)+ except TunnelBrokerError as e:+ return _error(e)+ # Default: refresh live status. Pass ?refresh=0 for the cached row only.+ if request.args.get('refresh', '1') in ('0', 'false', 'no'):+ return jsonify({'tunnel': tunnel.to_dict()})+ try:+ return jsonify(TunnelBrokerService.refresh_status(tunnel, user_id=get_jwt_identity()))+ except TunnelBrokerError as e:+ return _error(e)+++@tunnels_bp.route('/<tunnel_id>', methods=['DELETE'])+@jwt_required()+@developer_required+def delete_tunnel(tunnel_id):+ try:+ TunnelBrokerService.teardown_tunnel(tunnel_id, user_id=get_jwt_identity())+ except TunnelBrokerError as e:+ return _error(e)+ return jsonify({'success': True})+++# ---- exposed services (Phase 2: publish a service over a tunnel) --------++@tunnels_bp.route('/<tunnel_id>/services', methods=['GET'])+@jwt_required()+def list_services(tunnel_id):+ services = TunnelPublishService.list_for_tunnel(tunnel_id)+ return jsonify({'services': [s.to_dict() for s in services]})+++@tunnels_bp.route('/<tunnel_id>/services', methods=['POST'])+@jwt_required()+@developer_required+def publish_service(tunnel_id):+ data = request.get_json(silent=True) or {}+ hostname = (data.get('hostname') or '').strip()+ port = data.get('port')+ if not hostname or port is None:+ return jsonify({'error': 'hostname and port are required'}), 400+ try:+ svc, steps = TunnelPublishService.publish(+ tunnel_id, hostname, port,+ require_auth=bool(data.get('require_auth')),+ auth_username=(data.get('auth_username') or '').strip() or None,+ auth_password=data.get('auth_password'),+ ssl=data.get('ssl', True),+ email=(data.get('email') or '').strip() or None,+ user_id=get_jwt_identity(),+ )+ except TunnelPublishError as e:+ return _error(e)+ body = svc.to_dict()+ body['steps'] = steps+ return jsonify(body), 201+++@tunnels_bp.route('/<tunnel_id>/services/<service_id>', methods=['DELETE'])+@jwt_required()+@developer_required+def unpublish_service(tunnel_id, service_id):+ try:+ TunnelPublishService.unpublish(service_id, user_id=get_jwt_identity())+ except TunnelPublishError as e:+ return _error(e)+ return jsonify({'success': True})diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex e3c02bb8..9d0e6f18 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -29,6 +29,8 @@ from app.models.agent_plugin import AgentPlugin, AgentPluginInstallfrom app.models.server_template import ServerTemplate, ServerTemplateAssignmentfrom app.models.workspace import Workspace, WorkspaceMember, WorkspaceApiKey, ResourceGrantfrom app.models.dns_zone import DNSZone, DNSRecord+from app.models.tunnel import Tunnel+from app.models.exposed_service import ExposedServicefrom app.models.status_page import StatusPage, StatusComponent, HealthCheck, StatusIncident, StatusIncidentUpdatefrom app.models.cloud_server import CloudProvider, CloudServer, CloudSnapshotfrom app.models.marketplace import Extension, ExtensionInstall@@ -51,6 +53,7 @@ __all__ = ['ServerTemplate', 'ServerTemplateAssignment','Workspace', 'WorkspaceMember', 'WorkspaceApiKey', 'ResourceGrant','DNSZone', 'DNSRecord',+ 'Tunnel', 'ExposedService','StatusPage', 'StatusComponent', 'HealthCheck', 'StatusIncident', 'StatusIncidentUpdate','CloudProvider', 'CloudServer', 'CloudSnapshot','Extension', 'ExtensionInstall',diff --git a/backend/app/models/exposed_service.py b/backend/app/models/exposed_service.pynew file mode 100644index 00000000..c9950d92--- /dev/null+++ b/backend/app/models/exposed_service.py@@ -0,0 +1,58 @@+import uuid+from datetime import datetime++from app import db+++class ExposedService(db.Model):+ """A service on a private (NAT'd) host published to the public internet+ over a WireGuard tunnel (roadmap Phase 2). The edge runs an nginx vhost+ for ``hostname`` that proxies to the private peer's WG IP; the private+ agent forwards that to the real local service on ``port``.+ See docs/REMOTE_ACCESS_ROADMAP.md.+ """+ __tablename__ = 'exposed_services'++ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))+ tunnel_id = db.Column(db.String(36), db.ForeignKey('tunnels.id'), nullable=False, index=True)++ hostname = db.Column(db.String(255), nullable=False) # e.g. jellyfin.example.com+ port = db.Column(db.Integer, nullable=False) # service port on the private host (e.g. 8096)+ nginx_site_name = db.Column(db.String(120)) # the edge vhost we created++ require_auth = db.Column(db.Boolean, default=False)+ auth_username = db.Column(db.String(100))+ ssl_enabled = db.Column(db.Boolean, default=False)++ status = db.Column(db.String(20), default='pending', index=True) # pending / published / error+ last_error = db.Column(db.Text)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ tunnel = db.relationship('Tunnel')++ def url(self):+ if not self.hostname:+ return None+ return ('https://' if self.ssl_enabled else 'http://') + self.hostname++ def to_dict(self):+ return {+ 'id': self.id,+ 'tunnel_id': self.tunnel_id,+ 'hostname': self.hostname,+ 'port': self.port,+ 'nginx_site_name': self.nginx_site_name,+ 'require_auth': self.require_auth,+ 'auth_username': self.auth_username,+ 'ssl_enabled': self.ssl_enabled,+ 'status': self.status,+ 'last_error': self.last_error,+ 'url': self.url(),+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }++ def __repr__(self):+ return '<ExposedService %s -> tunnel %s :%s>' % (self.hostname, self.tunnel_id, self.port)diff --git a/backend/app/models/tunnel.py b/backend/app/models/tunnel.pynew file mode 100644index 00000000..4e1fd0b4--- /dev/null+++ b/backend/app/models/tunnel.py@@ -0,0 +1,79 @@+import uuid+from datetime import datetime++from app import db+++class Tunnel(db.Model):+ """A WireGuard pairing between two ServerKit agents: a public-IP+ "edge" and a NAT'd "private" host. The data plane is kernel WireGuard+ running on the agents; this row is the panel's brokered record of it.++ SECURITY: stores PUBLIC keys only. Private keys are generated on and+ never leave the hosts. See docs/REMOTE_ACCESS_ROADMAP.md.+ """+ __tablename__ = 'tunnels'++ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))+ name = db.Column(db.String(120))++ # Two FKs to servers → relationships must name foreign_keys explicitly.+ edge_server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False, index=True)+ private_server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False, index=True)++ interface_name = db.Column(db.String(15), nullable=False)+ subnet = db.Column(db.String(43), nullable=False) # CIDR, e.g. 10.88.3.0/24+ edge_wg_ip = db.Column(db.String(45), nullable=False) # 10.88.3.1+ private_wg_ip = db.Column(db.String(45), nullable=False) # 10.88.3.2+ listen_port = db.Column(db.Integer, default=51820)++ # PUBLIC keys only — never private.+ edge_pubkey = db.Column(db.String(64))+ private_pubkey = db.Column(db.String(64))++ # pending → up → degraded / down / error+ status = db.Column(db.String(20), default='pending', index=True)+ last_handshake_at = db.Column(db.DateTime)+ last_error = db.Column(db.Text)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ edge_server = db.relationship('Server', foreign_keys=[edge_server_id])+ private_server = db.relationship('Server', foreign_keys=[private_server_id])++ def _prefix(self):+ return self.subnet.split('/')[-1] if self.subnet and '/' in self.subnet else '24'++ def edge_address(self):+ """CIDR address for the edge's interface, e.g. 10.88.3.1/24."""+ return "%s/%s" % (self.edge_wg_ip, self._prefix())++ def private_address(self):+ """CIDR address for the private host's interface, e.g. 10.88.3.2/24."""+ return "%s/%s" % (self.private_wg_ip, self._prefix())++ def to_dict(self):+ return {+ 'id': self.id,+ 'name': self.name,+ 'edge_server_id': self.edge_server_id,+ 'edge_server_name': self.edge_server.name if self.edge_server else None,+ 'private_server_id': self.private_server_id,+ 'private_server_name': self.private_server.name if self.private_server else None,+ 'interface_name': self.interface_name,+ 'subnet': self.subnet,+ 'edge_wg_ip': self.edge_wg_ip,+ 'private_wg_ip': self.private_wg_ip,+ 'listen_port': self.listen_port,+ 'edge_pubkey': self.edge_pubkey,+ 'private_pubkey': self.private_pubkey,+ 'status': self.status,+ 'last_handshake_at': self.last_handshake_at.isoformat() if self.last_handshake_at else None,+ 'last_error': self.last_error,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }++ def __repr__(self):+ return '<Tunnel %s %s->%s>' % (self.interface_name, self.edge_server_id, self.private_server_id)diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.pyindex f0f6439b..20295bbd 100644--- a/backend/app/services/nginx_service.py+++ b/backend/app/services/nginx_service.py@@ -151,6 +151,36 @@ class NginxService:proxy_send_timeout 60;}}}}+'''++ # Reverse proxy to a service reached over a WireGuard tunnel (roadmap+ # #12). The upstream is a peer's WG IP:port; the private agent forwards+ # it to the real service. proxy_buffering off keeps media/streaming+ # (e.g. Jellyfin) responsive.+ REMOTE_UPSTREAM_TEMPLATE = '''server {{+ listen 80;+ listen [::]:80;+ server_name {domains};++ access_log /var/log/nginx/{name}.access.log;+ error_log /var/log/nginx/{name}.error.log;++ location / {{+ proxy_pass http://{upstream};+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection 'upgrade';+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_cache_bypass $http_upgrade;+ proxy_buffering off;+ proxy_read_timeout 86400;+ proxy_connect_timeout 60;+ proxy_send_timeout 60;+ }}+}}'''SSL_BLOCK = '''@@ -390,7 +420,8 @@ location /p/ {{@classmethoddef create_site(cls, name: str, app_type: str, domains: List[str],root_path: str, port: int = None, php_version: str = '8.2',- ssl_cert: str = None, ssl_key: str = None) -> Dict:+ ssl_cert: str = None, ssl_key: str = None,+ upstream: str = None) -> Dict:"""Create a new site configuration.When ``ssl_cert``/``ssl_key`` are given the generated vhost serves HTTPS@@ -438,6 +469,14 @@ location /p/ {{domains=domains_str,port=port)+ elif app_type == 'remote':+ if not upstream:+ return {'success': False, 'error': 'upstream (host:port) is required for remote apps'}+ config = cls.REMOTE_UPSTREAM_TEMPLATE.format(+ name=name,+ domains=domains_str,+ upstream=upstream,+ )elif app_type == 'static':config = cls.STATIC_SITE_TEMPLATE.format(name=name,diff --git a/backend/app/services/tunnel_broker_service.py b/backend/app/services/tunnel_broker_service.pynew file mode 100644index 00000000..d4add129--- /dev/null+++ b/backend/app/services/tunnel_broker_service.py@@ -0,0 +1,376 @@+"""WireGuard tunnel broker (roadmap Phase 1 — #8 / #10 / #11).++Pairs two agents over the existing agent command channel:+keygen → interface:up → peer:set → verify. The panel is the source of+truth; private keys never leave the hosts (only public keys are brokered+and persisted). See docs/REMOTE_ACCESS_ROADMAP.md.+"""++import logging+import time+from datetime import datetime++from app import db+from app.models.server import Server+from app.models.tunnel import Tunnel+from app.services.agent_registry import agent_registry+from app.services import tunnel_netutil++logger = logging.getLogger(__name__)++KEEPALIVE_SECONDS = 25+DEFAULT_LISTEN_PORT = 51820+++class TunnelBrokerError(Exception):+ """A broker step failed. ``code`` mirrors the agent send_command codes+ (AGENT_OFFLINE, PERMISSION_DENIED, TIMEOUT) plus broker-specific ones+ (NOT_CONNECTED, NO_WIREGUARD, NO_EDGE_IP, POOL_EXHAUSTED, NOT_FOUND,+ BAD_REQUEST). ``status`` is the HTTP status the API should return."""++ def __init__(self, message, code='BROKER_ERROR', status=400):+ super().__init__(message)+ self.message = message+ self.code = code+ self.status = status+++class TunnelBrokerService:++ # ---- agent command helper ------------------------------------------++ @staticmethod+ def _cmd(server_id, action, params=None, user_id=None, timeout=20.0):+ """Send an agent command; raise TunnelBrokerError on failure.+ Returns the agent handler's ``data`` payload on success."""+ res = agent_registry.send_command(+ server_id=server_id, action=action, params=params or {},+ user_id=user_id, timeout=timeout,+ )+ if not res.get('success'):+ code = res.get('code', 'BROKER_ERROR')+ status = 409 if code == 'AGENT_OFFLINE' else (502 if code == 'TIMEOUT' else 400)+ raise TunnelBrokerError(+ "%s on %s failed: %s" % (action, server_id, res.get('error', 'unknown error')),+ code=code, status=status,+ )+ return res.get('data')++ # ---- preflight -----------------------------------------------------++ @staticmethod+ def _require_wireguard_agent(server_id, role):+ server = Server.query.get(server_id)+ if not server:+ raise TunnelBrokerError("%s server not found" % role, code='NOT_FOUND', status=404)+ agent = agent_registry.get_agent(server_id)+ if not agent:+ raise TunnelBrokerError(+ "%s server '%s' is not connected" % (role, server.name),+ code='NOT_CONNECTED', status=409,+ )+ if not (agent.capabilities or {}).get('wireguard'):+ raise TunnelBrokerError(+ "%s server '%s' lacks the wireguard capability "+ "(needs wireguard-tools + iproute2 on a Linux agent)" % (role, server.name),+ code='NO_WIREGUARD', status=409,+ )+ return server++ # ---- create --------------------------------------------------------++ @classmethod+ def create_tunnel(cls, edge_server_id, private_server_id, name=None, user_id=None):+ if not edge_server_id or not private_server_id:+ raise TunnelBrokerError("edge_server_id and private_server_id are required", code='BAD_REQUEST')+ if edge_server_id == private_server_id:+ raise TunnelBrokerError("edge and private servers must differ", code='BAD_REQUEST')++ edge = cls._require_wireguard_agent(edge_server_id, 'edge')+ private = cls._require_wireguard_agent(private_server_id, 'private')++ # The private peer dials the edge's public endpoint, so the edge+ # needs a reachable address.+ if not tunnel_netutil.validate_endpoint_host(edge.ip_address):+ raise TunnelBrokerError(+ "edge server '%s' has no usable public IP (ip_address=%r)" % (edge.name, edge.ip_address),+ code='NO_EDGE_IP', status=409,+ )++ used = [t.subnet for t in Tunnel.query.with_entities(Tunnel.subnet).all()]+ try:+ subnet, edge_ip, private_ip = tunnel_netutil.pick_subnet(used)+ except RuntimeError as e:+ raise TunnelBrokerError(str(e), code='POOL_EXHAUSTED', status=409)++ tunnel = Tunnel(+ name=name or ("%s → %s" % (edge.name, private.name)),+ edge_server_id=edge_server_id,+ private_server_id=private_server_id,+ subnet=subnet,+ edge_wg_ip=edge_ip,+ private_wg_ip=private_ip,+ listen_port=DEFAULT_LISTEN_PORT,+ status='pending',+ )+ db.session.add(tunnel)+ db.session.flush() # assign tunnel.id before deriving the interface name+ tunnel.interface_name = tunnel_netutil.interface_name_for(tunnel.id)+ db.session.commit()++ try:+ cls._bring_up(tunnel, edge, private, user_id)+ except TunnelBrokerError as e:+ tunnel.status = 'error'+ tunnel.last_error = e.message+ db.session.commit()+ raise++ return tunnel++ @classmethod+ def _bring_up(cls, tunnel, edge, private, user_id):+ iface = tunnel.interface_name++ # 1. keygen on both ends — public keys only come back.+ edge_kg = cls._cmd(edge.id, 'wireguard:keygen', {'interface': iface}, user_id)+ priv_kg = cls._cmd(private.id, 'wireguard:keygen', {'interface': iface}, user_id)+ edge_pub = (edge_kg or {}).get('public_key')+ priv_pub = (priv_kg or {}).get('public_key')+ if not edge_pub or not priv_pub:+ raise TunnelBrokerError("agent keygen returned no public key", code='BROKER_ERROR', status=502)+ tunnel.edge_pubkey = edge_pub+ tunnel.private_pubkey = priv_pub+ db.session.commit()++ # 2. interfaces up — the edge listens; the private side dials out.+ cls._cmd(edge.id, 'wireguard:interface:up',+ {'name': iface, 'address': tunnel.edge_address(), 'listen_port': tunnel.listen_port}, user_id)+ cls._cmd(private.id, 'wireguard:interface:up',+ {'name': iface, 'address': tunnel.private_address(), 'listen_port': 0}, user_id)++ # 3. peers — the private peer carries the edge endpoint + keepalive+ # so it punches and holds the NAT mapping.+ cls._cmd(edge.id, 'wireguard:peer:set', {+ 'interface': iface,+ 'public_key': priv_pub,+ 'allowed_ips': ["%s/32" % tunnel.private_wg_ip],+ }, user_id)+ cls._cmd(private.id, 'wireguard:peer:set', {+ 'interface': iface,+ 'public_key': edge_pub,+ 'allowed_ips': ["%s/32" % tunnel.edge_wg_ip],+ 'endpoint': "%s:%d" % (edge.ip_address, tunnel.listen_port),+ 'persistent_keepalive': KEEPALIVE_SECONDS,+ }, user_id)++ db.session.commit()++ # 4. open the edge's inbound WireGuard UDP port (best-effort, #10).+ tunnel.firewall_status = cls._ensure_edge_port(edge.id, tunnel.listen_port, user_id)++ # 5. best-effort immediate verify (handshake may take a few seconds;+ # #11 health-refresh confirms it later regardless).+ try:+ cls.refresh_status(tunnel, user_id=user_id)+ except TunnelBrokerError:+ logger.info("post-create status refresh failed for tunnel %s (will settle on next refresh)", tunnel.id)++ # ---- status / health (#11) -----------------------------------------++ @classmethod+ def refresh_status(cls, tunnel, user_id=None):+ """Poll wireguard:status on both ends and update the row's health.+ Returns {tunnel, edge, private}."""+ now = time.time()+ edge_status = cls._safe_status(tunnel.edge_server_id, tunnel.interface_name, user_id)+ private_status = cls._safe_status(tunnel.private_server_id, tunnel.interface_name, user_id)++ latest = max(cls._latest_handshake(edge_status), cls._latest_handshake(private_status))+ iface_up = bool((edge_status or {}).get('up')) and bool((private_status or {}).get('up'))+ tunnel.status = tunnel_netutil.derive_status(latest, now, interface_up=iface_up)+ if latest:+ tunnel.last_handshake_at = datetime.utcfromtimestamp(latest)+ db.session.commit()+ return {'tunnel': tunnel.to_dict(), 'edge': edge_status, 'private': private_status}++ @classmethod+ def _safe_status(cls, server_id, iface, user_id):+ """wireguard:status that returns None instead of raising — a+ disconnected end shouldn't blow up the whole status read."""+ try:+ return cls._cmd(server_id, 'wireguard:status', {'interface': iface}, user_id, timeout=10.0)+ except TunnelBrokerError:+ return None++ @staticmethod+ def _latest_handshake(status):+ if not status:+ return 0+ best = 0+ for p in (status.get('peers') or []):+ hs = p.get('latest_handshake') or 0+ if hs > best:+ best = hs+ return best++ # ---- teardown ------------------------------------------------------++ @classmethod+ def teardown_tunnel(cls, tunnel_id, user_id=None):+ tunnel = Tunnel.query.get(tunnel_id)+ if not tunnel:+ raise TunnelBrokerError("tunnel not found", code='NOT_FOUND', status=404)+ # Best-effort interface teardown on both ends — don't block delete on+ # a disconnected agent (the row is the source of truth; #19 reconciles).+ for sid in (tunnel.edge_server_id, tunnel.private_server_id):+ try:+ agent_registry.send_command(+ server_id=sid, action='wireguard:interface:down',+ params={'interface': tunnel.interface_name}, user_id=user_id, timeout=10.0,+ )+ except Exception:+ logger.info("interface:down on %s during teardown failed (continuing)", sid)+ db.session.delete(tunnel)+ db.session.commit()+ return True++ # ---- reads ---------------------------------------------------------++ @staticmethod+ def get_tunnel(tunnel_id):+ tunnel = Tunnel.query.get(tunnel_id)+ if not tunnel:+ raise TunnelBrokerError("tunnel not found", code='NOT_FOUND', status=404)+ return tunnel++ # ---- reconcile (#19: panel-authoritative persistence) --------------++ @staticmethod+ def schedule_reconcile(server_id):+ """Spawn a non-blocking background reconcile for a (re)connected+ server (#19). Safe to call from a Socket.IO handler — captures the+ Flask app and runs reconcile_server in its own context, so tunnels+ self-heal after an agent or panel restart."""+ try:+ from app import socketio+ from flask import current_app+ app = current_app._get_current_object()+ except Exception:+ logger.exception("reconcile: could not capture app/socketio")+ return++ def _run():+ with app.app_context():+ try:+ TunnelBrokerService.reconcile_server(server_id)+ except Exception:+ logger.exception("tunnel reconcile failed for %s", server_id)++ try:+ socketio.start_background_task(_run)+ except Exception:+ logger.exception("could not start reconcile task for %s", server_id)++ @classmethod+ def reconcile_server(cls, server_id, user_id=None):+ """Re-apply the config for every tunnel this server participates in.+ The panel is the source of truth; relies on the Phase-0 commands+ being idempotent. Best-effort per tunnel (a down peer doesn't block+ the others). Returns a per-tunnel result list."""+ from app.models.exposed_service import ExposedService+ tunnels = Tunnel.query.filter(+ ((Tunnel.edge_server_id == server_id) | (Tunnel.private_server_id == server_id)),+ Tunnel.status.in_(('up', 'degraded', 'pending')),+ ).all()+ out = []+ for t in tunnels:+ try:+ cls._reconcile_side(t, server_id, ExposedService, user_id)+ out.append({'tunnel_id': t.id, 'ok': True})+ except TunnelBrokerError as e:+ logger.info("reconcile of tunnel %s on %s failed: %s", t.id, server_id, e.message)+ out.append({'tunnel_id': t.id, 'ok': False, 'error': e.message})+ if out:+ logger.info("reconciled %d tunnel(s) for server %s", len(out), server_id)+ return out++ @classmethod+ def _reconcile_side(cls, tunnel, server_id, exposed_service_model, user_id):+ """Re-apply just the side of `tunnel` that belongs to server_id (the+ other end reconciles when it reconnects). Rebuilds from the stored+ public keys + endpoint — no private key ever needed here."""+ iface = tunnel.interface_name+ if tunnel.edge_server_id == server_id:+ cls._cmd(server_id, 'wireguard:interface:up',+ {'name': iface, 'address': tunnel.edge_address(),+ 'listen_port': tunnel.listen_port}, user_id)+ if tunnel.private_pubkey:+ cls._cmd(server_id, 'wireguard:peer:set',+ {'interface': iface, 'public_key': tunnel.private_pubkey,+ 'allowed_ips': ['%s/32' % tunnel.private_wg_ip]}, user_id)+ try:+ cls._ensure_edge_port(server_id, tunnel.listen_port, user_id)+ except Exception:+ pass+ else:+ cls._cmd(server_id, 'wireguard:interface:up',+ {'name': iface, 'address': tunnel.private_address(),+ 'listen_port': 0}, user_id)+ edge = Server.query.get(tunnel.edge_server_id)+ if tunnel.edge_pubkey and edge and edge.ip_address:+ cls._cmd(server_id, 'wireguard:peer:set',+ {'interface': iface, 'public_key': tunnel.edge_pubkey,+ 'allowed_ips': ['%s/32' % tunnel.edge_wg_ip],+ 'endpoint': '%s:%d' % (edge.ip_address, tunnel.listen_port),+ 'persistent_keepalive': KEEPALIVE_SECONDS}, user_id)+ # Re-apply the service forwarders for this tunnel.+ for svc in exposed_service_model.query.filter_by(tunnel_id=tunnel.id).all():+ try:+ cls._cmd(server_id, 'wireguard:forward',+ {'interface': iface, 'listen_ip': tunnel.private_wg_ip,+ 'listen_port': svc.port, 'target_host': '127.0.0.1',+ 'target_port': svc.port}, user_id)+ except TunnelBrokerError:+ pass++ # ---- firewall (#10) ------------------------------------------------++ @staticmethod+ def _ensure_edge_port(edge_server_id, port, user_id=None):+ """Open the edge's inbound UDP <port> via the agent's+ firewall:allow_port command (#10). Best-effort — a failure (no+ firewall present, missing `firewall:*` grant, or an older agent+ without the command) is non-fatal: the tunnel still works if the+ port is already open, and the create response always carries the+ manual commands too. Returns a small outcome dict for the UI."""+ try:+ res = agent_registry.send_command(+ server_id=edge_server_id, action='firewall:allow_port',+ params={'port': port, 'protocol': 'udp'}, user_id=user_id, timeout=15.0,+ )+ except Exception as e: # pragma: no cover - defensive+ logger.info("edge firewall open failed for %s: %s", edge_server_id, e)+ return {'opened': False, 'error': str(e)}+ if res.get('success'):+ data = res.get('data') or {}+ return {'opened': True, 'method': data.get('method')}+ logger.info("edge firewall open not applied for %s: %s", edge_server_id, res.get('error'))+ return {'opened': False, 'error': res.get('error'), 'code': res.get('code')}++ @staticmethod+ def firewall_hint(port):+ """The edge must accept inbound UDP for the WireGuard handshake.+ There's no dedicated firewall agent command yet (a small follow-up,+ like the wireguard:* primitives), so for now we surface the exact+ step/commands rather than guessing at system:exec."""+ return {+ 'port': port,+ 'protocol': 'udp',+ 'target': 'edge',+ 'note': "Open inbound UDP %d on the edge server for the WireGuard handshake." % port,+ 'commands': [+ "ufw allow %d/udp" % port,+ "firewall-cmd --add-port=%d/udp --permanent && firewall-cmd --reload" % port,+ ],+ }diff --git a/backend/app/services/tunnel_netutil.py b/backend/app/services/tunnel_netutil.pynew file mode 100644index 00000000..890883a2--- /dev/null+++ b/backend/app/services/tunnel_netutil.py@@ -0,0 +1,71 @@+"""Pure, dependency-free helpers for the WireGuard tunnel broker.++Kept import-light (stdlib only) so the subnet allocator, interface-name+derivation and health classification are unit-testable without booting+Flask/SQLAlchemy. See docs/REMOTE_ACCESS_ROADMAP.md (Phase 1, #7 / #11).+"""++import ipaddress++# The tunnel overlay pool: 10.88.0.0/16 carved into /24s. Deliberately an+# uncommon RFC-1918 block so it won't collide with a typical home LAN+# (192.168.x / 10.0.x). Each tunnel gets one /24 — .1 = edge, .2 = private.+TUNNEL_POOL = "10.88.0.0/16"++# A peer counts as "live" if it handshook within this window. WireGuard+# rehandshakes well inside it when persistent-keepalive is 25s.+HANDSHAKE_FRESH_SECONDS = 180+++def pick_subnet(used_subnets):+ """Return (subnet_cidr, edge_ip, private_ip) for the first free /24 in+ the pool. ``used_subnets`` is any iterable of CIDR strings already taken.++ Raises RuntimeError if the pool is exhausted (256 /24s).+ """+ used = set(used_subnets or [])+ for third in range(256):+ cidr = "10.88.%d.0/24" % third+ if cidr not in used:+ return cidr, "10.88.%d.1" % third, "10.88.%d.2" % third+ raise RuntimeError("tunnel subnet pool exhausted (10.88.0.0/16, 256 /24s)")+++def interface_name_for(tunnel_id):+ """Derive a stable, kernel-valid WireGuard interface name from a tunnel+ id. Linux caps interface names at 15 chars; 'skwg' + 8 hex is 12. The+ same name is used on both ends (they're different hosts).+ """+ compact = str(tunnel_id).replace("-", "")[:8] or "0"+ return "skwg%s" % compact+++def derive_status(latest_handshake_epoch, now_epoch, interface_up=True):+ """Classify tunnel health from a peer's latest-handshake timestamp.++ - 'down' — the interface isn't up+ - 'up' — handshook within HANDSHAKE_FRESH_SECONDS+ - 'degraded' — handshook before, but now stale (link may be recovering)+ - 'pending' — interface up but no handshake yet (just created)+ """+ if not interface_up:+ return "down"+ if latest_handshake_epoch and latest_handshake_epoch > 0:+ age = now_epoch - latest_handshake_epoch+ return "up" if age <= HANDSHAKE_FRESH_SECONDS else "degraded"+ return "pending"+++def validate_endpoint_host(ip_address):+ """True if ``ip_address`` is usable as the edge's public endpoint host.++ Accepts IPv4/IPv6; rejects empty, malformed, loopback and unspecified+ addresses. Private ranges are allowed (a lab/LAN edge is valid).+ """+ if not ip_address:+ return False+ try:+ ip = ipaddress.ip_address(str(ip_address).strip())+ except ValueError:+ return False+ return not (ip.is_loopback or ip.is_unspecified)diff --git a/backend/app/services/tunnel_publish_service.py b/backend/app/services/tunnel_publish_service.pynew file mode 100644index 00000000..947715a7--- /dev/null+++ b/backend/app/services/tunnel_publish_service.py@@ -0,0 +1,175 @@+"""Publish a private service over a WireGuard tunnel (roadmap Phase 2).++Ties the pieces together: start a forwarder on the private peer (#13),+write the edge nginx vhost that proxies to the peer's WG IP (#12), point+DNS at the edge (#14), put basic-auth in front (#16), and obtain a cert+(#15). The nginx / DNS / cert / auth steps run on the panel host, which+acts as the edge (where the WG edge interface and nginx live). See+docs/REMOTE_ACCESS_ROADMAP.md.+"""++import logging+import re++from app import db+from app.models.exposed_service import ExposedService+from app.models.server import Server+from app.models.tunnel import Tunnel+from app.services.agent_registry import agent_registry+from app.services.dns_provider_service import DNSProviderService+from app.services.environment_domain_service import EnvironmentDomainService+from app.services.nginx_service import NginxService+from app.services.ssl_service import SSLService++logger = logging.getLogger(__name__)++_HOSTNAME_RE = re.compile(+ r'^(?=.{1,253}$)(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.[A-Za-z0-9-]{1,63})+$'+)+++class TunnelPublishError(Exception):+ """A publish step failed. ``status`` is the HTTP status the API returns."""++ def __init__(self, message, code='PUBLISH_ERROR', status=400):+ super().__init__(message)+ self.message = message+ self.code = code+ self.status = status+++class TunnelPublishService:++ @staticmethod+ def list_for_tunnel(tunnel_id):+ return (ExposedService.query+ .filter_by(tunnel_id=tunnel_id)+ .order_by(ExposedService.created_at.desc())+ .all())++ @staticmethod+ def get(service_id):+ svc = ExposedService.query.get(service_id)+ if not svc:+ raise TunnelPublishError('exposed service not found', code='NOT_FOUND', status=404)+ return svc++ @classmethod+ def publish(cls, tunnel_id, hostname, port, *, require_auth=False,+ auth_username=None, auth_password=None, ssl=True,+ email=None, user_id=None):+ """Publish <hostname> → the private service on <port>. The forwarder+ and nginx steps are essential (failure aborts); DNS / auth / cert are+ best-effort and reported in the returned ``steps`` dict."""+ hostname = (hostname or '').strip().lower().rstrip('.')+ if not _HOSTNAME_RE.match(hostname):+ raise TunnelPublishError('invalid hostname', code='BAD_REQUEST')+ try:+ port = int(port)+ except (TypeError, ValueError):+ raise TunnelPublishError('port must be an integer', code='BAD_REQUEST')+ if port < 1 or port > 65535:+ raise TunnelPublishError('port out of range', code='BAD_REQUEST')+ if require_auth and (not auth_username or not auth_password):+ raise TunnelPublishError(+ 'auth_username and auth_password are required when require_auth is set',+ code='BAD_REQUEST')++ tunnel = Tunnel.query.get(tunnel_id)+ if not tunnel:+ raise TunnelPublishError('tunnel not found', code='NOT_FOUND', status=404)+ edge = Server.query.get(tunnel.edge_server_id)++ svc = ExposedService(+ tunnel_id=tunnel.id, hostname=hostname, port=port,+ nginx_site_name=hostname, require_auth=require_auth,+ auth_username=auth_username if require_auth else None,+ status='pending',+ )+ db.session.add(svc)+ db.session.commit()++ steps = {}+ try:+ # 1. Forwarder on the private peer (essential): WG IP:port → the+ # real local service on 127.0.0.1:port.+ fwd = agent_registry.send_command(+ server_id=tunnel.private_server_id, action='wireguard:forward',+ params={'interface': tunnel.interface_name, 'listen_ip': tunnel.private_wg_ip,+ 'listen_port': port, 'target_host': '127.0.0.1', 'target_port': port},+ user_id=user_id, timeout=15.0,+ )+ if not fwd.get('success'):+ raise TunnelPublishError(+ 'failed to start forwarder on private host: %s' % fwd.get('error'),+ code=fwd.get('code', 'FORWARD_FAILED'), status=502)+ steps['forward'] = {'ok': True}++ # 2. Edge nginx vhost (essential): proxy to the peer's WG IP.+ upstream = '%s:%d' % (tunnel.private_wg_ip, port)+ created = NginxService.create_site(+ name=hostname, app_type='remote', domains=[hostname],+ root_path='', upstream=upstream)+ if not created.get('success'):+ raise TunnelPublishError(+ 'failed to write nginx vhost: %s' % created.get('error'),+ code='NGINX_FAILED', status=500)+ enabled = NginxService.enable_site(hostname)+ if not enabled.get('success'):+ raise TunnelPublishError(+ 'failed to enable nginx vhost: %s' % enabled.get('error'),+ code='NGINX_FAILED', status=500)+ steps['nginx'] = {'ok': True}++ # 3. DNS A record → the edge's public IP (best-effort, #14).+ edge_ip = edge.ip_address if edge else None+ steps['dns'] = DNSProviderService.ensure_a_record(hostname, edge_ip)++ # 4. Basic-auth in front (best-effort, #16).+ if require_auth:+ steps['auth'] = EnvironmentDomainService.enable_basic_auth(+ hostname, auth_username, auth_password)++ # 5. Cert on the edge (best-effort, #15). certbot --nginx wires+ # the TLS into the vhost and reloads, so we only flag success.+ if ssl:+ cert = SSLService.obtain_certificate([hostname], email or ('admin@%s' % hostname))+ steps['ssl'] = {'ok': bool(cert.get('success')), 'error': cert.get('error')}+ if cert.get('success'):+ svc.ssl_enabled = True++ svc.status = 'published'+ db.session.commit()+ return svc, steps+ except TunnelPublishError as e:+ svc.status = 'error'+ svc.last_error = e.message+ db.session.commit()+ raise++ @classmethod+ def unpublish(cls, service_id, user_id=None):+ svc = ExposedService.query.get(service_id)+ if not svc:+ raise TunnelPublishError('exposed service not found', code='NOT_FOUND', status=404)+ tunnel = Tunnel.query.get(svc.tunnel_id)++ # Remove the edge nginx vhost (best-effort).+ try:+ NginxService.delete_site(svc.nginx_site_name or svc.hostname)+ except Exception:+ logger.info('nginx delete_site failed during unpublish of %s', svc.hostname)++ # Stop the forwarder on the private peer (best-effort).+ if tunnel:+ try:+ agent_registry.send_command(+ server_id=tunnel.private_server_id, action='wireguard:unforward',+ params={'interface': tunnel.interface_name, 'listen_port': svc.port},+ user_id=user_id, timeout=10.0)+ except Exception:+ logger.info('wireguard:unforward failed during unpublish of %s', svc.hostname)++ db.session.delete(svc)+ db.session.commit()+ return Truediff --git a/backend/tests/test_nginx_remote_upstream.py b/backend/tests/test_nginx_remote_upstream.pynew file mode 100644index 00000000..05f968cf--- /dev/null+++ b/backend/tests/test_nginx_remote_upstream.py@@ -0,0 +1,26 @@+"""Phase 2 #12: the nginx remote-upstream vhost. Pure template/validation+checks — no nginx or filesystem needed."""++from app.services.nginx_service import NginxService+++def test_remote_upstream_template_renders():+ cfg = NginxService.REMOTE_UPSTREAM_TEMPLATE.format(+ name='jellyfin.example.com',+ domains='jellyfin.example.com',+ upstream='10.88.3.2:8096',+ )+ assert 'proxy_pass http://10.88.3.2:8096;' in cfg+ assert 'server_name jellyfin.example.com;' in cfg+ # streaming + websocket essentials (Jellyfin)+ assert 'proxy_buffering off;' in cfg+ assert 'proxy_set_header Upgrade $http_upgrade;' in cfg+ assert "proxy_set_header Connection 'upgrade';" in cfg+++def test_create_site_remote_requires_upstream():+ # The 'remote' branch rejects a missing upstream before touching the FS.+ res = NginxService.create_site(+ name='x', app_type='remote', domains=['x.example.com'], root_path='')+ assert res.get('success') is False+ assert 'upstream' in res.get('error', '').lower()diff --git a/backend/tests/test_tunnel_netutil.py b/backend/tests/test_tunnel_netutil.pynew file mode 100644index 00000000..688be1e7--- /dev/null+++ b/backend/tests/test_tunnel_netutil.py@@ -0,0 +1,55 @@+"""Unit tests for the tunnel broker's pure helpers (roadmap #7 / #11).++These import only app.services.tunnel_netutil (stdlib-only) so they prove+the subnet allocator, interface-name derivation and health classification+without needing a DB or connected agents.+"""++from app.services import tunnel_netutil as tn+++def test_pick_subnet_first_free():+ cidr, edge, priv = tn.pick_subnet([])+ assert cidr == '10.88.0.0/24'+ assert edge == '10.88.0.1'+ assert priv == '10.88.0.2'+++def test_pick_subnet_skips_used():+ cidr, edge, priv = tn.pick_subnet(['10.88.0.0/24', '10.88.1.0/24'])+ assert cidr == '10.88.2.0/24'+ assert edge == '10.88.2.1'+ assert priv == '10.88.2.2'+++def test_pick_subnet_exhausted():+ used = ['10.88.%d.0/24' % i for i in range(256)]+ try:+ tn.pick_subnet(used)+ assert False, "expected RuntimeError on exhausted pool"+ except RuntimeError:+ pass+++def test_interface_name_is_stable_and_kernel_valid():+ name = tn.interface_name_for('3fa9c2b1-dead-beef-0000-111122223333')+ assert name == 'skwg3fa9c2b1'+ assert len(name) <= 15+ assert name.replace('skwg', '').isalnum()+++def test_derive_status():+ now = 1_000_000+ assert tn.derive_status(now - 10, now) == 'up'+ assert tn.derive_status(now - 10_000, now) == 'degraded'+ assert tn.derive_status(0, now) == 'pending'+ assert tn.derive_status(now, now, interface_up=False) == 'down'+++def test_validate_endpoint_host():+ assert tn.validate_endpoint_host('203.0.113.5') is True+ assert tn.validate_endpoint_host('10.0.0.5') is True # private edge OK+ assert tn.validate_endpoint_host('127.0.0.1') is False # loopback+ assert tn.validate_endpoint_host('0.0.0.0') is False # unspecified+ assert tn.validate_endpoint_host('') is False+ assert tn.validate_endpoint_host('not-an-ip') is Falsediff --git a/backend/tests/test_tunnel_reconcile.py b/backend/tests/test_tunnel_reconcile.pynew file mode 100644index 00000000..977d0336--- /dev/null+++ b/backend/tests/test_tunnel_reconcile.py@@ -0,0 +1,101 @@+"""Phase 3 #19: panel-authoritative tunnel reconcile.++Proves reconcile_server re-issues the right agent commands for each side+of a tunnel, by monkeypatching agent_registry.send_command to record calls+(no live agent needed).+"""++from app import db+from app.models.server import Server+from app.models.tunnel import Tunnel+from app.models.exposed_service import ExposedService+from app.services import agent_registry as ar_mod+from app.services.tunnel_broker_service import TunnelBrokerService+++def _server(name, ip=None):+ s = Server(name=name, ip_address=ip, status='online')+ db.session.add(s)+ db.session.commit()+ return s+++def _record_send(monkeypatch):+ calls = []++ def fake_send(server_id, action, params=None, user_id=None, timeout=30.0):+ calls.append({'server_id': server_id, 'action': action, 'params': params or {}})+ return {'success': True, 'data': {}}++ monkeypatch.setattr(ar_mod.agent_registry, 'send_command', fake_send)+ return calls+++def _tunnel(edge, priv, iface, third):+ t = Tunnel(+ edge_server_id=edge.id, private_server_id=priv.id,+ interface_name=iface, subnet='10.88.%d.0/24' % third,+ edge_wg_ip='10.88.%d.1' % third, private_wg_ip='10.88.%d.2' % third,+ listen_port=51820, edge_pubkey='EDGEPUB', private_pubkey='PRIVPUB',+ status='up',+ )+ db.session.add(t)+ db.session.commit()+ return t+++def test_reconcile_private_side(app, monkeypatch):+ calls = _record_send(monkeypatch)+ edge = _server('edge', ip='203.0.113.9')+ priv = _server('home')+ t = _tunnel(edge, priv, 'skwgrec01', 7)+ db.session.add(ExposedService(tunnel_id=t.id, hostname='jelly.example.com', port=8096, status='published'))+ db.session.commit()++ res = TunnelBrokerService.reconcile_server(priv.id)+ assert res and res[0]['ok']++ actions = [c['action'] for c in calls]+ assert 'wireguard:interface:up' in actions+ assert 'wireguard:peer:set' in actions+ assert 'wireguard:forward' in actions++ peer = next(c['params'] for c in calls if c['action'] == 'wireguard:peer:set')+ assert peer['public_key'] == 'EDGEPUB' # private peers with the edge+ assert peer['endpoint'] == '203.0.113.9:51820' # dials the edge endpoint+ assert peer['persistent_keepalive'] == 25++ fwd = next(c['params'] for c in calls if c['action'] == 'wireguard:forward')+ assert fwd['listen_port'] == 8096 and fwd['target_port'] == 8096+ assert fwd['listen_ip'] == '10.88.7.2'+++def test_reconcile_edge_side(app, monkeypatch):+ calls = _record_send(monkeypatch)+ edge = _server('edge2', ip='198.51.100.4')+ priv = _server('home2')+ _tunnel(edge, priv, 'skwgrec02', 8)++ TunnelBrokerService.reconcile_server(edge.id)++ actions = [c['action'] for c in calls]+ assert 'wireguard:interface:up' in actions+ assert 'wireguard:peer:set' in actions+ assert 'firewall:allow_port' in actions # edge re-opens its UDP port++ peer = next(c['params'] for c in calls if c['action'] == 'wireguard:peer:set')+ assert peer['public_key'] == 'PRIVPUB' # edge peers with the private host+ assert 'endpoint' not in peer # edge has no endpoint for the private peer+++def test_reconcile_skips_errored_tunnels(app, monkeypatch):+ calls = _record_send(monkeypatch)+ edge = _server('edge3', ip='192.0.2.7')+ priv = _server('home3')+ t = _tunnel(edge, priv, 'skwgrec03', 9)+ t.status = 'error'+ db.session.commit()++ res = TunnelBrokerService.reconcile_server(priv.id)+ assert res == []+ assert calls == []diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 5cb5cf7f..b712387c 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -43,6 +43,7 @@ import SSOCallback from './pages/SSOCallback';import SourceConnectionCallback from './pages/SourceConnectionCallback';import DatabaseMigration from './pages/DatabaseMigration';import ServerTemplates from './pages/ServerTemplates';+import RemoteAccess from './pages/RemoteAccess';import Workspaces from './pages/Workspaces';import WorkspaceDetail from './pages/WorkspaceDetail';import DNSZones from './pages/DNSZones';@@ -258,6 +259,7 @@ function AppRoutes() {<Route path="deployments/:jobId" element={<Deployments />} /><Route path="workflow" element={<WorkflowBuilder />} /><Route path="domains" element={<Domains />} />+ <Route path="remote-access" element={<RemoteAccess />} /><Route path="databases" element={<Databases />} /><Route path="databases/:tab" element={<Databases />} /><Route path="ssl" element={<SSLCertificates />} />diff --git a/frontend/src/components/sidebarItems.js b/frontend/src/components/sidebarItems.jsindex 1a358191..63feb479 100644--- a/frontend/src/components/sidebarItems.js+++ b/frontend/src/components/sidebarItems.js@@ -44,6 +44,13 @@ export const SIDEBAR_ITEMS = [category: 'infrastructure',icon: '<circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>'},+ {+ id: 'remote-access',+ label: 'Remote Access',+ route: '/remote-access',+ category: 'infrastructure',+ icon: '<rect x="16" y="16" width="6" height="6" rx="1"/><rect x="2" y="16" width="6" height="6" rx="1"/><rect x="9" y="2" width="6" height="6" rx="1"/><path d="M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3"/><path d="M12 12V8"/>'+ },{// Redesign: Services uses the top-bar layout (REDESIGN_MAP §6 decision 3).// New Service / Templates / Deploy Activity now live in the page's topdiff --git a/frontend/src/pages/RemoteAccess.jsx b/frontend/src/pages/RemoteAccess.jsxnew file mode 100644index 00000000..9c2984f3--- /dev/null+++ b/frontend/src/pages/RemoteAccess.jsx@@ -0,0 +1,437 @@+import { useState, useEffect, useCallback } from 'react';+import { Network, Plus, Trash2, Globe, Lock, ShieldCheck, ExternalLink } from 'lucide-react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';+import Spinner from '../components/Spinner';+import Modal from '../components/Modal';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Switch } from '@/components/ui/switch';+import { Badge } from '@/components/ui/badge';+import { Card, CardContent } from '@/components/ui/card';+import {+ Select,+ SelectTrigger,+ SelectContent,+ SelectItem,+ SelectValue,+} from '@/components/ui/select';++const STATUS_STYLES = {+ up: 'text-green-600 border-green-500/40',+ pending: 'text-yellow-600 border-yellow-500/40',+ degraded: 'text-yellow-600 border-yellow-500/40',+ published: 'text-green-600 border-green-500/40',+ down: 'text-red-600 border-red-500/40',+ error: 'text-red-600 border-red-500/40',+};++function StatusBadge({ status }) {+ const cls = STATUS_STYLES[status] || 'text-muted-foreground border-border';+ return (+ <Badge variant="outline" className={cls}>+ {status || 'unknown'}+ </Badge>+ );+}++const EMPTY_FORM = {+ privateServerId: '',+ edgeServerId: '',+ hostname: '',+ port: '',+ requireAuth: false,+ authUsername: '',+ authPassword: '',+ ssl: true,+};++const RemoteAccess = () => {+ const toast = useToast();+ const [tunnels, setTunnels] = useState([]);+ const [services, setServices] = useState({}); // tunnelId -> [service]+ const [servers, setServers] = useState([]);+ const [loading, setLoading] = useState(true);++ const [wizardOpen, setWizardOpen] = useState(false);+ const [wizardTunnel, setWizardTunnel] = useState(null); // preset when adding to an existing tunnel+ const [form, setForm] = useState(EMPTY_FORM);+ const [submitting, setSubmitting] = useState(false);++ const [teardown, setTeardown] = useState(null); // tunnel pending teardown++ const load = useCallback(async () => {+ setLoading(true);+ try {+ const [tRes, sRes] = await Promise.all([api.getTunnels(), api.getServers()]);+ const list = tRes.tunnels || [];+ setTunnels(list);+ setServers(sRes.servers || sRes || []);+ const entries = await Promise.all(+ list.map((t) =>+ api+ .getTunnelServices(t.id)+ .then((r) => [t.id, r.services || []])+ .catch(() => [t.id, []])+ )+ );+ setServices(Object.fromEntries(entries));+ } catch (e) {+ toast.error(e.message || 'Failed to load tunnels');+ } finally {+ setLoading(false);+ }+ }, [toast]);++ useEffect(() => {+ load();+ }, [load]);++ const openWizard = (tunnel = null) => {+ setWizardTunnel(tunnel);+ setForm({+ ...EMPTY_FORM,+ edgeServerId: tunnel ? tunnel.edge_server_id : '',+ privateServerId: tunnel ? tunnel.private_server_id : '',+ });+ setWizardOpen(true);+ };++ const closeWizard = () => {+ if (submitting) return;+ setWizardOpen(false);+ setWizardTunnel(null);+ setForm(EMPTY_FORM);+ };++ const setField = (k, v) => setForm((f) => ({ ...f, [k]: v }));++ const wizardValid =+ form.hostname.trim() &&+ form.port &&+ (wizardTunnel ||+ (form.edgeServerId && form.privateServerId && form.edgeServerId !== form.privateServerId)) &&+ (!form.requireAuth || (form.authUsername.trim() && form.authPassword));++ const submitWizard = async () => {+ if (!wizardValid || submitting) return;+ setSubmitting(true);+ try {+ // Ensure a tunnel between the two servers (reuse an existing one).+ let tunnelId = wizardTunnel?.id;+ if (!tunnelId) {+ const existing = tunnels.find(+ (t) =>+ t.edge_server_id === form.edgeServerId &&+ t.private_server_id === form.privateServerId+ );+ if (existing) {+ tunnelId = existing.id;+ } else {+ const created = await api.createTunnel({+ edge_server_id: form.edgeServerId,+ private_server_id: form.privateServerId,+ });+ tunnelId = created.id;+ }+ }+ const svc = await api.publishTunnelService(tunnelId, {+ hostname: form.hostname.trim(),+ port: Number(form.port),+ require_auth: form.requireAuth,+ auth_username: form.authUsername.trim() || undefined,+ auth_password: form.authPassword || undefined,+ ssl: form.ssl,+ });+ toast.success(`Exposed ${svc.hostname}`);+ closeWizard();+ load();+ } catch (e) {+ toast.error(e.message || 'Failed to expose service');+ } finally {+ setSubmitting(false);+ }+ };++ const confirmTeardown = async () => {+ if (!teardown) return;+ try {+ await api.deleteTunnel(teardown.id);+ toast.success('Tunnel torn down');+ setTeardown(null);+ load();+ } catch (e) {+ toast.error(e.message || 'Failed to tear down tunnel');+ }+ };++ const unpublish = async (tunnelId, svc) => {+ try {+ await api.unpublishTunnelService(tunnelId, svc.id);+ toast.success(`Removed ${svc.hostname}`);+ load();+ } catch (e) {+ toast.error(e.message || 'Failed to remove service');+ }+ };++ return (+ <div className="p-6 max-w-6xl mx-auto">+ <div className="flex items-start justify-between gap-4 mb-6">+ <div>+ <h1 className="text-2xl font-semibold flex items-center gap-2">+ <Network className="w-6 h-6 text-primary" />+ Remote Access+ </h1>+ <p className="text-muted-foreground mt-1 max-w-2xl">+ Expose a service running on a private machine (behind NAT, no port-forwarding) to a public+ hostname over a WireGuard tunnel between two of your agents.+ </p>+ </div>+ <Button onClick={() => openWizard(null)} disabled={loading}>+ <Plus className="w-4 h-4 mr-1" />+ Expose a Local Service+ </Button>+ </div>++ {loading ? (+ <div className="flex justify-center py-16">+ <Spinner />+ </div>+ ) : tunnels.length === 0 ? (+ <Card>+ <CardContent className="py-16 flex flex-col items-center text-center gap-3">+ <Network className="w-10 h-10 text-muted-foreground" />+ <h2 className="text-lg font-medium">No tunnels yet</h2>+ <p className="text-muted-foreground max-w-md">+ Pick a public-IP edge server and a private host, and ServerKit will pair them over+ WireGuard and publish your service — no router changes needed.+ </p>+ <Button onClick={() => openWizard(null)} className="mt-2">+ <Plus className="w-4 h-4 mr-1" />+ Expose a Local Service+ </Button>+ </CardContent>+ </Card>+ ) : (+ <div className="space-y-4">+ {tunnels.map((t) => (+ <Card key={t.id}>+ <CardContent className="p-5">+ <div className="flex items-start justify-between gap-4">+ <div>+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-medium">{t.private_server_name || t.private_server_id}</span>+ <span className="text-muted-foreground">→</span>+ <span className="font-medium">{t.edge_server_name || t.edge_server_id}</span>+ <StatusBadge status={t.status} />+ </div>+ <div className="text-sm text-muted-foreground mt-1">+ {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>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <Button variant="outline" size="sm" onClick={() => openWizard(t)}>+ <Plus className="w-4 h-4 mr-1" />+ Expose service+ </Button>+ <Button+ variant="ghost"+ size="sm"+ className="text-red-600"+ onClick={() => setTeardown(t)}+ title="Tear down tunnel"+ >+ <Trash2 className="w-4 h-4" />+ </Button>+ </div>+ </div>++ <div className="mt-4 border-t border-border pt-3">+ {(services[t.id] || []).length === 0 ? (+ <p className="text-sm text-muted-foreground">No services exposed on this tunnel.</p>+ ) : (+ <ul className="space-y-2">+ {(services[t.id] || []).map((svc) => (+ <li key={svc.id} className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2 min-w-0">+ <Globe className="w-4 h-4 text-muted-foreground shrink-0" />+ {svc.url ? (+ <a+ href={svc.url}+ target="_blank"+ rel="noreferrer"+ className="text-primary hover:underline truncate inline-flex items-center gap-1"+ >+ {svc.hostname}+ <ExternalLink className="w-3 h-3" />+ </a>+ ) : (+ <span className="truncate">{svc.hostname}</span>+ )}+ <span className="text-muted-foreground text-sm">→ :{svc.port}</span>+ {svc.require_auth && <Lock className="w-3 h-3 text-muted-foreground" title="Basic auth" />}+ {svc.ssl_enabled && <ShieldCheck className="w-3 h-3 text-green-600" title="HTTPS" />}+ <StatusBadge status={svc.status} />+ </div>+ <Button+ variant="ghost"+ size="sm"+ className="text-red-600 shrink-0"+ onClick={() => unpublish(t.id, svc)}+ >+ Remove+ </Button>+ </li>+ ))}+ </ul>+ )}+ </div>+ </CardContent>+ </Card>+ ))}+ </div>+ )}++ {/* Expose-a-service wizard */}+ <Modal+ open={wizardOpen}+ onClose={closeWizard}+ title="Expose a Local Service"+ size="lg"+ footer={+ <>+ <Button variant="outline" onClick={closeWizard} disabled={submitting}>+ Cancel+ </Button>+ <Button onClick={submitWizard} disabled={!wizardValid || submitting}>+ {submitting ? 'Publishing…' : 'Publish'}+ </Button>+ </>+ }+ >+ <div className="space-y-4">+ {!wizardTunnel && (+ <>+ <div className="space-y-1.5">+ <Label>Private host (where the service runs)</Label>+ <Select value={form.privateServerId} onValueChange={(v) => setField('privateServerId', v)}>+ <SelectTrigger>+ <SelectValue placeholder="Select a server" />+ </SelectTrigger>+ <SelectContent>+ {servers.map((s) => (+ <SelectItem key={s.id} value={s.id}>+ {s.name}{s.ip_address ? ` (${s.ip_address})` : ''}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label>Edge server (public IP — fronts the tunnel)</Label>+ <Select value={form.edgeServerId} onValueChange={(v) => setField('edgeServerId', v)}>+ <SelectTrigger>+ <SelectValue placeholder="Select a server" />+ </SelectTrigger>+ <SelectContent>+ {servers.map((s) => (+ <SelectItem key={s.id} value={s.id}>+ {s.name}{s.ip_address ? ` (${s.ip_address})` : ''}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-xs text-muted-foreground">+ A tunnel between these two is created (or reused) automatically.+ </p>+ </div>+ </>+ )}++ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <div className="sm:col-span-2 space-y-1.5">+ <Label>Public hostname</Label>+ <Input+ placeholder="jellyfin.example.com"+ value={form.hostname}+ onChange={(e) => setField('hostname', e.target.value)}+ />+ </div>+ <div className="space-y-1.5">+ <Label>Service port</Label>+ <Input+ type="number"+ placeholder="8096"+ value={form.port}+ onChange={(e) => setField('port', e.target.value)}+ />+ </div>+ </div>++ <div className="flex items-center justify-between">+ <div>+ <Label>HTTPS (Let's Encrypt)</Label>+ <p className="text-xs text-muted-foreground">Obtain a certificate on the edge.</p>+ </div>+ <Switch checked={form.ssl} onCheckedChange={(v) => setField('ssl', v)} />+ </div>++ <div className="flex items-center justify-between">+ <div>+ <Label>Require login (basic auth)</Label>+ <p className="text-xs text-muted-foreground">Put a username/password in front of the service.</p>+ </div>+ <Switch checked={form.requireAuth} onCheckedChange={(v) => setField('requireAuth', v)} />+ </div>++ {form.requireAuth && (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label>Username</Label>+ <Input+ value={form.authUsername}+ onChange={(e) => setField('authUsername', e.target.value)}+ />+ </div>+ <div className="space-y-1.5">+ <Label>Password</Label>+ <Input+ type="password"+ value={form.authPassword}+ onChange={(e) => setField('authPassword', e.target.value)}+ />+ </div>+ </div>+ )}+ </div>+ </Modal>++ {/* Tear-down confirmation */}+ <Modal+ open={!!teardown}+ onClose={() => setTeardown(null)}+ title="Tear down tunnel?"+ size="sm"+ footer={+ <>+ <Button variant="outline" onClick={() => setTeardown(null)}>+ Cancel+ </Button>+ <Button variant="destructive" onClick={confirmTeardown}>+ Tear down+ </Button>+ </>+ }+ >+ <p className="text-sm text-muted-foreground">+ This removes the WireGuard tunnel{teardown ? ` between ${teardown.private_server_name || teardown.private_server_id} and ${teardown.edge_server_name || teardown.edge_server_id}` : ''} and any services published over it. The agents' interfaces are brought down.+ </p>+ </Modal>+ </div>+ );+};++export default RemoteAccess;diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.jsindex 2262fc60..4e623052 100644--- a/frontend/src/services/api/index.js+++ b/frontend/src/services/api/index.js@@ -15,6 +15,7 @@ import * as pairingMethods from './pairing.js';import * as sourceConnectionMethods from './sourceConnections.js';import * as connectionMethods from './connections.js';import * as aiMethods from './ai.js';+import * as tunnelMethods from './tunnels.js';class ApiService extends ApiClient {constructor() {@@ -37,6 +38,7 @@ class ApiService extends ApiClient {sourceConnectionMethods,connectionMethods,aiMethods,+ tunnelMethods,];for (const mod of modules) {for (const [key, fn] of Object.entries(mod)) {diff --git a/frontend/src/services/api/tunnels.js b/frontend/src/services/api/tunnels.jsnew file mode 100644index 00000000..d250af72--- /dev/null+++ b/frontend/src/services/api/tunnels.js@@ -0,0 +1,32 @@+// Remote Access — WireGuard tunnels + the services published over them.+// Backend: backend/app/api/tunnels.py. See docs/REMOTE_ACCESS_ROADMAP.md.++export async function getTunnels() {+ return this.request('/tunnels/');+}++export async function getTunnel(id, { refresh = true } = {}) {+ return this.request(`/tunnels/${id}${refresh ? '' : '?refresh=0'}`);+}++export async function createTunnel(data) {+ // data: { edge_server_id, private_server_id, name? }+ return this.request('/tunnels/', { method: 'POST', body: data });+}++export async function deleteTunnel(id) {+ return this.request(`/tunnels/${id}`, { method: 'DELETE' });+}++export async function getTunnelServices(tunnelId) {+ return this.request(`/tunnels/${tunnelId}/services`);+}++export async function publishTunnelService(tunnelId, data) {+ // data: { hostname, port, require_auth?, auth_username?, auth_password?, ssl? }+ return this.request(`/tunnels/${tunnelId}/services`, { method: 'POST', body: data });+}++export async function unpublishTunnelService(tunnelId, serviceId) {+ return this.request(`/tunnels/${tunnelId}/services/${serviceId}`, { method: 'DELETE' });+}