Skip to content

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.

Add Cloudflared tunnel management

Juan Denis8ddd60f83d19
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go
index beb99a58..fe8d719f 100644
--- a/agent/internal/agent/agent.go
+++ b/agent/internal/agent/agent.go
@@ -19,6 +19,7 @@ import (
"github.com/serverkit/agent/internal/auth"
"github.com/serverkit/agent/internal/capabilities"
+ "github.com/serverkit/agent/internal/cloudflared"
"github.com/serverkit/agent/internal/config"
"github.com/serverkit/agent/internal/cron"
"github.com/serverkit/agent/internal/docker"
@@ -44,11 +45,12 @@ type Agent struct {
// fallback Manager that wraps WS+poll. Named "ws" for compatibility
// with the dozens of existing call sites in this file.
ws transport.Transport
- docker *docker.Client
- metrics *metrics.Collector
- terminal *terminal.Manager
- cron cron.Manager
- ipc *ipc.Server
+ docker *docker.Client
+ metrics *metrics.Collector
+ terminal *terminal.Manager
+ cron cron.Manager
+ cloudflared cloudflared.Manager
+ ipc *ipc.Server
sampler *metricSampler
events *events.Store
gui *gui.SDK
@@ -130,6 +132,7 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
metrics: metricsCollector,
terminal: termManager,
cron: cron.New(),
+ cloudflared: cloudflared.New(),
sampler: newMetricSampler(300), // 5 min @ 1 Hz
events: eventStore,
gui: gui.New(log),
@@ -230,6 +233,16 @@ func (a *Agent) registerHandlers() {
a.handlers[protocol.ActionCronRemove] = a.handleCronRemove
a.handlers[protocol.ActionCronToggle] = a.handleCronToggle
+ // Cloudflared commands — same Linux-only/stub pattern. Auth state
+ // (cert.pem present) is exposed via :status, not via the
+ // capabilities probe, so the panel can distinguish "binary
+ // installed but not logged in" from "not installed at all."
+ a.handlers[protocol.ActionCloudflaredStatus] = a.handleCloudflaredStatus
+ a.handlers[protocol.ActionCloudflaredTunnelList] = a.handleCloudflaredTunnelList
+ a.handlers[protocol.ActionCloudflaredTunnelCreate] = a.handleCloudflaredTunnelCreate
+ a.handlers[protocol.ActionCloudflaredTunnelRoute] = a.handleCloudflaredTunnelRoute
+ a.handlers[protocol.ActionCloudflaredTunnelDelete] = a.handleCloudflaredTunnelDelete
+
// Agent commands
a.handlers[protocol.ActionAgentUpdate] = a.handleAgentUpdate
diff --git a/agent/internal/agent/cloudflared_handlers.go b/agent/internal/agent/cloudflared_handlers.go
new file mode 100644
index 00000000..e5827b36
--- /dev/null
+++ b/agent/internal/agent/cloudflared_handlers.go
@@ -0,0 +1,63 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/serverkit/agent/internal/cloudflared"
+)
+
+// Handlers for cloudflared:* actions. Same shape as cron handlers:
+// thin parse + dispatch. Validation lives in the cloudflared package.
+
+func (a *Agent) handleCloudflaredStatus(ctx context.Context, _ json.RawMessage) (interface{}, error) {
+ return a.cloudflared.Status(ctx)
+}
+
+func (a *Agent) handleCloudflaredTunnelList(ctx context.Context, _ json.RawMessage) (interface{}, error) {
+ tunnels, err := a.cloudflared.List(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if tunnels == nil {
+ tunnels = []cloudflared.Tunnel{}
+ }
+ return map[string]interface{}{"tunnels": tunnels}, nil
+}
+
+func (a *Agent) handleCloudflaredTunnelCreate(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var req cloudflared.CreateRequest
+ if err := json.Unmarshal(params, &req); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ tunnel, err := a.cloudflared.Create(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+ return tunnel, nil
+}
+
+func (a *Agent) handleCloudflaredTunnelRoute(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var req cloudflared.RouteRequest
+ if err := json.Unmarshal(params, &req); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ if err := a.cloudflared.Route(ctx, req); err != nil {
+ return nil, err
+ }
+ return map[string]bool{"success": true}, nil
+}
+
+func (a *Agent) handleCloudflaredTunnelDelete(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ Ref string `json:"ref"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ if err := a.cloudflared.Delete(ctx, p.Ref); 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.go
index 6bac973f..464c9e19 100644
--- a/agent/internal/capabilities/capabilities.go
+++ b/agent/internal/capabilities/capabilities.go
@@ -14,7 +14,9 @@ import (
"os"
"os/exec"
"path/filepath"
+ "regexp"
"runtime"
+ "strings"
"sync"
"github.com/serverkit/agent/internal/logger"
@@ -45,6 +47,18 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool) protoc
caps["php_fpm"] = probePHPFPM()
caps["packages"] = probePackageManager()
+ // Cloudflared — present if the binary is on PATH. The panel uses
+ // this to decide whether to show the Cloudflare Tunnels tab; it
+ // doesn't imply the user has authenticated yet (cert.pem check
+ // happens in the cloudflared:status action).
+ caps["cloudflared"] = probeCloudflared()
+
+ // 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
+ // runtime indicator without claiming a wrong version.
+ runtimes := probeRuntimes(ctx)
+
// Platform / distro for any code that needs more than the booleans
// (e.g. "use apt vs dnf" — Phase 4 territory, but we capture it
// now so we don't have to add another roundtrip later).
@@ -69,6 +83,8 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool) protoc
"nginx", caps["nginx"],
"php_fpm", caps["php_fpm"],
"packages", caps["packages"],
+ "cloudflared", caps["cloudflared"],
+ "runtimes", runtimes,
)
}
@@ -77,7 +93,82 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool) protoc
Platform: platform,
Distro: distro,
DistroVersion: distroVer,
+ Runtimes: runtimes,
+ }
+}
+
+// probeCloudflared — true if cloudflared is on PATH. The capability
+// flips to true at install time, well before the user has logged in
+// (cloudflared tunnel login). The auth state is exposed separately by
+// the cloudflared:status action so the UI can show "binary installed,
+// not authenticated" without having to teach the panel about
+// /etc/cloudflared/cert.pem locations.
+func probeCloudflared() bool {
+ return hasOnPath("cloudflared")
+}
+
+// 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 can
+// do their own semver compares without us guessing the schema.
+//
+// Per-binary timeout is short — every probe is bounded so a hung
+// subprocess can't block the agent from connecting.
+func probeRuntimes(ctx context.Context) map[string]string {
+ results := map[string]string{}
+ probes := []struct {
+ key string
+ bins []string // try in order; first match wins
+ }{
+ {key: "python", bins: []string{"python3", "python"}},
+ {key: "node", bins: []string{"node", "nodejs"}},
+ {key: "php", bins: []string{"php"}},
+ {key: "go", bins: []string{"go"}},
+ {key: "ruby", bins: []string{"ruby"}},
+ {key: "java", bins: []string{"java"}},
+ }
+ for _, p := range probes {
+ for _, bin := range p.bins {
+ if !hasOnPath(bin) {
+ continue
+ }
+ ver := readVersion(ctx, bin)
+ results[p.key] = ver
+ break // don't keep trying once we found one
+ }
+ }
+ return results
+}
+
+// versionPattern grabs the first dotted-number sequence in a version
+// string. Works across the messy outputs:
+// - python: "Python 3.11.4"
+// - node: "v20.10.0"
+// - php: "PHP 8.2.0 (cli) ..."
+// - go: "go version go1.22.0 linux/amd64"
+// - ruby: "ruby 3.2.2p53 ..."
+// - java: "openjdk version \"17.0.6\" 2023-01-17"
+var versionPattern = regexp.MustCompile(`(\d+\.\d+(?:\.\d+)?)`)
+
+func readVersion(ctx context.Context, bin string) string {
+ // java and a few others print version on stderr; capture both.
+ cmd := exec.CommandContext(ctx, bin, "--version")
+ out, err := cmd.CombinedOutput()
+ if err != nil || len(out) == 0 {
+ // Some binaries reject "--version" but accept "-version" (java).
+ cmd = exec.CommandContext(ctx, bin, "-version")
+ out, _ = cmd.CombinedOutput()
+ }
+ if len(out) == 0 {
+ return ""
+ }
+ first := strings.SplitN(strings.TrimSpace(string(out)), "\n", 2)[0]
+ if m := versionPattern.FindString(first); m != "" {
+ return m
}
+ // Fall through with the raw first line so the panel at least shows
+ // something rather than a blank.
+ return first
}
// probeCron — present if `crontab` is on PATH OR a cron daemon is
diff --git a/agent/internal/cloudflared/cloudflared.go b/agent/internal/cloudflared/cloudflared.go
new file mode 100644
index 00000000..0c2e864e
--- /dev/null
+++ b/agent/internal/cloudflared/cloudflared.go
@@ -0,0 +1,89 @@
+// Package cloudflared manages Cloudflare named tunnels via the
+// cloudflared CLI. Linux-only.
+//
+// Auth model (approach A):
+//
+// The user runs `cloudflared tunnel login` once per host. That writes
+// ~/.cloudflared/cert.pem (or /etc/cloudflared/cert.pem when run as
+// root). The cert is the long-lived "I'm allowed to manage tunnels
+// for account X" credential. We never see, copy, or store the user's
+// Cloudflare API token; the panel only ever shells out to
+// `cloudflared` and trusts whatever auth the binary already has.
+//
+// Status() reports two flags:
+// - Available: cloudflared is on PATH
+// - Authenticated: cert.pem is present in one of the standard
+// locations
+//
+// The panel uses both: the tab is gated on `capabilities.cloudflared`
+// (binary installed, set by capabilities.Probe at agent startup) and
+// the tab body shows an "authenticate first" affordance when
+// Authenticated=false.
+//
+// Tunnel lifecycle:
+//
+// 1. Create: `cloudflared tunnel create <name>`
+// (writes <UUID>.json credentials file)
+// 2. Route: `cloudflared tunnel route dns <name|UUID> <hostname>`
+// (creates a Cloudflare DNS record pointing the
+// hostname at the tunnel — *the* useful action)
+// 3. Run: out of scope here; the operator wires up
+// `cloudflared tunnel run <name>` as a systemd service
+// with a config.yml ingress mapping. Future iteration.
+// 4. Delete: `cloudflared tunnel delete <name|UUID>`
+package cloudflared
+
+import (
+ "context"
+ "os/exec"
+)
+
+// Status reports usability and auth state.
+type Status struct {
+ Available bool `json:"available"` // binary installed
+ Authenticated bool `json:"authenticated"` // cert.pem present
+ CertPath string `json:"cert_path,omitempty"` // detected cert.pem path, if any
+ Reason string `json:"reason,omitempty"` // explanation when Available=false
+ LoginHint string `json:"login_hint,omitempty"` // canned "run this command" when Authenticated=false
+ Version string `json:"version,omitempty"` // cloudflared --version line, best-effort
+}
+
+// Tunnel mirrors `cloudflared tunnel list --output json` rows.
+type Tunnel struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ CreatedAt string `json:"created_at,omitempty"`
+ Connections []string `json:"connections,omitempty"`
+}
+
+// CreateRequest creates a new named tunnel.
+type CreateRequest struct {
+ Name string `json:"name"`
+}
+
+// RouteRequest binds a hostname to an existing tunnel via Cloudflare
+// DNS. TunnelRef can be the tunnel name or UUID — cloudflared accepts
+// either.
+type RouteRequest struct {
+ TunnelRef string `json:"tunnel_ref"`
+ Hostname string `json:"hostname"`
+}
+
+// Manager is the platform-agnostic interface; the Linux build wires
+// it up with real exec calls, non-Linux builds return "unsupported."
+type Manager interface {
+ Status(ctx context.Context) (*Status, error)
+ List(ctx context.Context) ([]Tunnel, error)
+ Create(ctx context.Context, req CreateRequest) (*Tunnel, error)
+ Route(ctx context.Context, req RouteRequest) error
+ Delete(ctx context.Context, ref string) error
+}
+
+// hasCloudflared is shared between the Linux backend and tests.
+func hasCloudflared() (string, bool) {
+ p, err := exec.LookPath("cloudflared")
+ if err != nil {
+ return "", false
+ }
+ return p, true
+}
diff --git a/agent/internal/cloudflared/cloudflared_linux.go b/agent/internal/cloudflared/cloudflared_linux.go
new file mode 100644
index 00000000..53d30c60
--- /dev/null
+++ b/agent/internal/cloudflared/cloudflared_linux.go
@@ -0,0 +1,181 @@
+//go:build linux
+
+package cloudflared
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+// New returns a Linux Manager that drives `cloudflared`.
+func New() Manager { return &linuxManager{} }
+
+type linuxManager struct{}
+
+// validNameRegex constrains tunnel names to characters that won't
+// trip cloudflared or shell escaping. Matches the cloudflared docs:
+// up to 32 chars, alphanumeric + dash + underscore.
+var validNameRegex = regexp.MustCompile(`^[A-Za-z0-9_\-]{1,32}$`)
+
+// validHostnameRegex is a permissive FQDN check — no protocol, no
+// path, no spaces. Cloudflare itself does the authoritative check.
+var validHostnameRegex = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?)+$`)
+
+// certSearchPaths covers the two install patterns: the user ran
+// `cloudflared tunnel login` as a regular user (~/.cloudflared) or as
+// root / via the official install (/etc/cloudflared).
+func certSearchPaths() []string {
+ paths := []string{"/etc/cloudflared/cert.pem"}
+ if home, err := os.UserHomeDir(); err == nil {
+ paths = append(paths, filepath.Join(home, ".cloudflared", "cert.pem"))
+ }
+ return paths
+}
+
+func findCert() (string, bool) {
+ for _, p := range certSearchPaths() {
+ if _, err := os.Stat(p); err == nil {
+ return p, true
+ }
+ }
+ return "", false
+}
+
+func (l *linuxManager) Status(ctx context.Context) (*Status, error) {
+ binPath, ok := hasCloudflared()
+ if !ok {
+ return &Status{
+ Available: false,
+ Reason: "cloudflared not installed on host",
+ LoginHint: "Install cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/get-started/",
+ }, nil
+ }
+
+ cert, authed := findCert()
+
+ // Best-effort version probe — failure is non-fatal, we still
+ // report Available=true based on PATH.
+ verCmd := exec.CommandContext(ctx, binPath, "--version")
+ verOut, _ := verCmd.Output()
+ version := strings.TrimSpace(strings.SplitN(string(verOut), "\n", 2)[0])
+
+ st := &Status{
+ Available: true,
+ Authenticated: authed,
+ CertPath: cert,
+ Version: version,
+ }
+ if !authed {
+ st.LoginHint = "Run on the server: sudo cloudflared tunnel login"
+ }
+ return st, nil
+}
+
+// runTunnel runs `cloudflared tunnel <args>` and returns
+// (stdout, error). Errors include the full stderr because the user
+// will likely see them in the panel UI when something goes wrong.
+func (l *linuxManager) runTunnel(ctx context.Context, args ...string) ([]byte, error) {
+ args = append([]string{"tunnel"}, args...)
+ cmd := exec.CommandContext(ctx, "cloudflared", args...)
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+ if err := cmd.Run(); err != nil {
+ return nil, fmt.Errorf("cloudflared %s: %w (%s)",
+ strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
+ }
+ return stdout.Bytes(), nil
+}
+
+func (l *linuxManager) List(ctx context.Context) ([]Tunnel, error) {
+ out, err := l.runTunnel(ctx, "list", "--output", "json")
+ if err != nil {
+ return nil, err
+ }
+
+ // cloudflared prints `[]` (sometimes with trailing whitespace) when
+ // no tunnels exist; json.Unmarshal handles both. Tunnel rows have
+ // more fields than we surface — we cherry-pick id, name,
+ // created_at, connections.
+ var raw []struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ CreatedAt string `json:"created_at"`
+ Connections []map[string]interface{} `json:"connections"`
+ }
+ if err := json.Unmarshal(bytes.TrimSpace(out), &raw); err != nil {
+ return nil, fmt.Errorf("parse tunnel list: %w", err)
+ }
+
+ out2 := make([]Tunnel, 0, len(raw))
+ for _, r := range raw {
+ conns := make([]string, 0, len(r.Connections))
+ for _, c := range r.Connections {
+ if origin, ok := c["origin_ip"].(string); ok && origin != "" {
+ conns = append(conns, origin)
+ }
+ }
+ out2 = append(out2, Tunnel{
+ ID: r.ID, Name: r.Name, CreatedAt: r.CreatedAt, Connections: conns,
+ })
+ }
+ return out2, nil
+}
+
+func (l *linuxManager) Create(ctx context.Context, req CreateRequest) (*Tunnel, error) {
+ if !validNameRegex.MatchString(req.Name) {
+ return nil, fmt.Errorf("invalid tunnel name (alphanumeric, -, _, max 32 chars)")
+ }
+ // `cloudflared tunnel create <name>` prints something like:
+ // Created tunnel <name> with id <UUID>
+ // Newer versions also have --output json on create; we parse the
+ // stdout text to be portable across versions.
+ out, err := l.runTunnel(ctx, "create", req.Name)
+ if err != nil {
+ return nil, err
+ }
+ // Look up by name afterwards so we have the full Tunnel record
+ // (the create stdout is informational, not structured JSON across
+ // all cloudflared versions).
+ _ = out
+ tunnels, err := l.List(ctx)
+ if err != nil {
+ return nil, err
+ }
+ for _, t := range tunnels {
+ if t.Name == req.Name {
+ return &t, nil
+ }
+ }
+ return nil, fmt.Errorf("tunnel created but not found in list")
+}
+
+func (l *linuxManager) Route(ctx context.Context, req RouteRequest) error {
+ if req.TunnelRef == "" {
+ return fmt.Errorf("tunnel_ref is required")
+ }
+ if !validHostnameRegex.MatchString(req.Hostname) {
+ return fmt.Errorf("invalid hostname")
+ }
+ // `cloudflared tunnel route dns <tunnel> <hostname>` creates the
+ // CNAME in Cloudflare DNS.
+ _, err := l.runTunnel(ctx, "route", "dns", req.TunnelRef, req.Hostname)
+ return err
+}
+
+func (l *linuxManager) Delete(ctx context.Context, ref string) error {
+ if ref == "" {
+ return fmt.Errorf("ref is required")
+ }
+ // -f forces deletion when the tunnel still has active connections;
+ // safer default for a panel-driven flow.
+ _, err := l.runTunnel(ctx, "delete", "-f", ref)
+ return err
+}
diff --git a/agent/internal/cloudflared/cloudflared_other.go b/agent/internal/cloudflared/cloudflared_other.go
new file mode 100644
index 00000000..61f4a444
--- /dev/null
+++ b/agent/internal/cloudflared/cloudflared_other.go
@@ -0,0 +1,25 @@
+//go:build !linux
+
+package cloudflared
+
+import (
+ "context"
+ "fmt"
+)
+
+// New returns a stub Manager on non-Linux platforms.
+func New() Manager { return stubManager{} }
+
+type stubManager struct{}
+
+var errUnsupported = fmt.Errorf("cloudflared is only supported on Linux agents")
+
+func (stubManager) Status(ctx context.Context) (*Status, error) {
+ return &Status{Available: false, Reason: "cloudflared is only supported on Linux agents"}, nil
+}
+func (stubManager) List(ctx context.Context) ([]Tunnel, error) { return nil, errUnsupported }
+func (stubManager) Create(ctx context.Context, _ CreateRequest) (*Tunnel, error) {
+ return nil, errUnsupported
+}
+func (stubManager) Route(ctx context.Context, _ RouteRequest) error { return errUnsupported }
+func (stubManager) Delete(ctx context.Context, _ string) error { return errUnsupported }
diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.go
index 037d41f7..24904b83 100644
--- a/agent/pkg/protocol/messages.go
+++ b/agent/pkg/protocol/messages.go
@@ -168,6 +168,12 @@ type CapabilitiesMessage struct {
Platform string `json:"platform"` // "linux", "windows", "darwin"
Distro string `json:"distro,omitempty"` // "ubuntu", "debian", "rhel", ...
DistroVersion string `json:"distro_version,omitempty"` // "22.04"
+ // Runtimes is a name → version map for language runtimes the agent
+ // detected at startup ("python": "3.11.4", "node": "20.10.0").
+ // Missing keys mean "not installed"; an empty string value means
+ // "installed but the version probe failed." Forward-compatible —
+ // new keys just light up in the panel without protocol changes.
+ Runtimes map[string]string `json:"runtimes,omitempty"`
}
// SystemInfo contains detailed system information
@@ -236,6 +242,17 @@ const (
ActionCronRemove = "cron:remove"
ActionCronToggle = "cron:toggle"
+ // Cloudflared actions — manage Cloudflare named tunnels via the
+ // cloudflared CLI. The agent never stores Cloudflare API tokens;
+ // the user authenticates once on the host with
+ // `cloudflared tunnel login` (approach A from the design notes).
+ // Status reflects "is binary installed AND has cert.pem".
+ ActionCloudflaredStatus = "cloudflared:status"
+ ActionCloudflaredTunnelList = "cloudflared:tunnel:list"
+ ActionCloudflaredTunnelCreate = "cloudflared:tunnel:create"
+ ActionCloudflaredTunnelRoute = "cloudflared:tunnel:route"
+ ActionCloudflaredTunnelDelete = "cloudflared:tunnel:delete"
+
// File actions
ActionFileRead = "file:read"
ActionFileWrite = "file:write"
diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py
index 87e80e99..202cb392 100644
--- a/backend/app/api/servers.py
+++ b/backend/app/api/servers.py
@@ -290,6 +290,7 @@ def get_server(server_id):
# agents that don't speak the protocol yet. Consumers (UI target
# pickers, etc.) should treat missing keys as false.
result['capabilities'] = dict(agent.capabilities) if agent else {}
+ result['runtimes'] = dict(agent.runtimes) if agent else {}
if agent:
result['platform'] = agent.platform
result['distro'] = agent.distro
@@ -2225,3 +2226,73 @@ def remote_cron_toggle(server_id, job_id):
enabled = bool(data.get('enabled', True))
result = RemoteCronService.toggle_job(server_id, job_id, enabled, user_id=user_id)
return _agent_result(result)
+
+
+# ==================== Remote Cloudflared Operations ====================
+#
+# Auth: the user runs `cloudflared tunnel login` once per server.
+# That writes ~/.cloudflared/cert.pem (or /etc/cloudflared/cert.pem
+# when run as root). The panel never sees a Cloudflare API token —
+# every cloudflared:* action just shells out to the binary, which
+# uses the cert for auth.
+#
+# /status surfaces both "binary installed" and "cert present" so the
+# UI can show a "log in first" prompt before letting users hit the
+# CRUD actions and getting confusing errors.
+
+from app.services.remote_cloudflared_service import RemoteCloudflaredService
+
+
+@servers_bp.route('/<server_id>/cloudflared/status', methods=['GET'])
+@jwt_required()
+def remote_cloudflared_status(server_id):
+ user_id = get_jwt_identity()
+ result = RemoteCloudflaredService.status(server_id, user_id=user_id)
+ return _agent_result(result)
+
+
+@servers_bp.route('/<server_id>/cloudflared/tunnels', methods=['GET'])
+@jwt_required()
+def remote_cloudflared_list(server_id):
+ user_id = get_jwt_identity()
+ result = RemoteCloudflaredService.list_tunnels(server_id, user_id=user_id)
+ return _agent_result(result)
+
+
+@servers_bp.route('/<server_id>/cloudflared/tunnels', methods=['POST'])
+@jwt_required()
+@developer_required
+def remote_cloudflared_create(server_id):
+ user_id = get_jwt_identity()
+ data = request.get_json(silent=True) or {}
+ name = (data.get('name') or '').strip()
+ if not name:
+ return jsonify({'error': 'name is required'}), 400
+
+ result = RemoteCloudflaredService.create_tunnel(server_id, name, user_id=user_id)
+ return _agent_result(result, ok_status=201)
+
+
+@servers_bp.route('/<server_id>/cloudflared/tunnels/<tunnel_ref>/route', methods=['POST'])
+@jwt_required()
+@developer_required
+def remote_cloudflared_route(server_id, tunnel_ref):
+ user_id = get_jwt_identity()
+ data = request.get_json(silent=True) or {}
+ hostname = (data.get('hostname') or '').strip()
+ if not hostname:
+ return jsonify({'error': 'hostname is required'}), 400
+
+ result = RemoteCloudflaredService.route_tunnel(
+ server_id, tunnel_ref, hostname, user_id=user_id,
+ )
+ return _agent_result(result)
+
+
+@servers_bp.route('/<server_id>/cloudflared/tunnels/<tunnel_ref>', methods=['DELETE'])
+@jwt_required()
+@developer_required
+def remote_cloudflared_delete(server_id, tunnel_ref):
+ user_id = get_jwt_identity()
+ result = RemoteCloudflaredService.delete_tunnel(server_id, tunnel_ref, user_id=user_id)
+ return _agent_result(result)
diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.py
index 487fb6a4..db57762f 100644
--- a/backend/app/services/agent_registry.py
+++ b/backend/app/services/agent_registry.py
@@ -53,6 +53,10 @@ class ConnectedAgent:
platform: Optional[str] = None
distro: Optional[str] = None
distro_version: Optional[str] = None
+ # Runtimes is name → version detected at agent startup
+ # ({"python": "3.11.4", "node": "20.10.0"}). Empty for older
+ # agents and for hosts where no runtime probes matched.
+ runtimes: Dict[str, str] = field(default_factory=dict)
@dataclass
@@ -748,6 +752,15 @@ class AgentRegistry:
# casting protects the API consumer (UI) from malformed types.
clean_caps = {str(k): bool(v) for k, v in caps.items() if isinstance(k, str)}
+ # Coerce runtimes the same way — agents are trusted but we
+ # don't want a malformed payload to crash the consumer.
+ raw_runtimes = payload.get('runtimes') or {}
+ clean_runtimes: Dict[str, str] = {}
+ if isinstance(raw_runtimes, dict):
+ for k, v in raw_runtimes.items():
+ if isinstance(k, str) and isinstance(v, (str, type(None))):
+ clean_runtimes[k] = v or ''
+
with self._lock:
agent = self._agents.get(server_id)
if not agent:
@@ -756,6 +769,7 @@ class AgentRegistry:
agent.platform = payload.get('platform') or None
agent.distro = payload.get('distro') or None
agent.distro_version = payload.get('distro_version') or None
+ agent.runtimes = clean_runtimes
logger.info(
"Capabilities updated for server %s: %s",
diff --git a/backend/app/services/remote_cloudflared_service.py b/backend/app/services/remote_cloudflared_service.py
new file mode 100644
index 00000000..99990f4d
--- /dev/null
+++ b/backend/app/services/remote_cloudflared_service.py
@@ -0,0 +1,69 @@
+"""
+Remote Cloudflared Service
+
+Mirrors RemoteCronService: a thin dispatcher that forwards
+cloudflared:* actions to the agent.
+
+Auth model — approach A (the user runs `cloudflared tunnel login`
+once on each server). The panel never touches Cloudflare credentials
+directly; the cert.pem on the host IS the credential, and cloudflared
+uses it for every subsequent call. The /status endpoint surfaces
+"cert present? yes/no" so the UI can show a "log in first" prompt
+instead of letting actions fail with confusing errors.
+"""
+
+from typing import Any, Dict, Optional
+
+from app.services.agent_registry import agent_registry
+
+
+class RemoteCloudflaredService:
+ @staticmethod
+ def _send(server_id: str, action: str, params: Optional[Dict[str, Any]] = None,
+ user_id: Optional[int] = None, timeout: float = 30.0) -> Dict[str, Any]:
+ return agent_registry.send_command(
+ server_id=server_id,
+ action=action,
+ params=params or {},
+ user_id=user_id,
+ timeout=timeout,
+ )
+
+ @staticmethod
+ def status(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:
+ return RemoteCloudflaredService._send(server_id, 'cloudflared:status',
+ user_id=user_id, timeout=8.0)
+
+ @staticmethod
+ def list_tunnels(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:
+ # Tunnel list hits Cloudflare API server-side, so allow more time
+ # than for crontab parsing.
+ return RemoteCloudflaredService._send(server_id, 'cloudflared:tunnel:list',
+ user_id=user_id, timeout=30.0)
+
+ @staticmethod
+ def create_tunnel(server_id: str, name: str,
+ user_id: Optional[int] = None) -> Dict[str, Any]:
+ return RemoteCloudflaredService._send(
+ server_id, 'cloudflared:tunnel:create',
+ params={'name': name},
+ user_id=user_id, timeout=30.0,
+ )
+
+ @staticmethod
+ def route_tunnel(server_id: str, tunnel_ref: str, hostname: str,
+ user_id: Optional[int] = None) -> Dict[str, Any]:
+ return RemoteCloudflaredService._send(
+ server_id, 'cloudflared:tunnel:route',
+ params={'tunnel_ref': tunnel_ref, 'hostname': hostname},
+ user_id=user_id, timeout=30.0,
+ )
+
+ @staticmethod
+ def delete_tunnel(server_id: str, ref: str,
+ user_id: Optional[int] = None) -> Dict[str, Any]:
+ return RemoteCloudflaredService._send(
+ server_id, 'cloudflared:tunnel:delete',
+ params={'ref': ref},
+ user_id=user_id, timeout=30.0,
+ )
diff --git a/frontend/src/components/LogViewer.jsx b/frontend/src/components/LogViewer.jsx
index d05f7c29..46771820 100644
--- a/frontend/src/components/LogViewer.jsx
+++ b/frontend/src/components/LogViewer.jsx
@@ -2,6 +2,7 @@ import React from 'react';
import { Search, RefreshCw, FileText } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
+import { Switch } from '@/components/ui/switch';
export function LogViewer({
files = [],
@@ -77,7 +78,7 @@ export function LogViewer({
<select
value={lineCount}
onChange={(e) => onLineCountChange(parseInt(e.target.value, 10))}
- className="lines-select"
+ className="form-select lines-select"
>
{lineCountOptions.map(n => (
<option key={n} value={n}>{n} lines</option>
@@ -88,10 +89,9 @@ export function LogViewer({
<div className="toolbar-right">
{onAutoRefreshChange && (
<label className="auto-refresh-toggle">
- <input
- type="checkbox"
+ <Switch
checked={autoRefresh}
- onChange={(e) => onAutoRefreshChange(e.target.checked)}
+ onCheckedChange={onAutoRefreshChange}
/>
<span>Auto-refresh</span>
</label>
diff --git a/frontend/src/components/ProcessTable.jsx b/frontend/src/components/ProcessTable.jsx
index 9292e47d..f888f4e7 100644
--- a/frontend/src/components/ProcessTable.jsx
+++ b/frontend/src/components/ProcessTable.jsx
@@ -24,7 +24,13 @@ export function ProcessTable({
}) {
return (
<div className="processes-table-wrapper">
- <table className="table processes-table">
+ <table
+ className="table processes-table"
+ spellCheck={false}
+ data-gramm="false"
+ data-gramm_editor="false"
+ data-enable-grammarly="false"
+ >
<thead>
<tr>
<th>PID</th>
diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx
index 05e5014f..e18730c5 100644
--- a/frontend/src/pages/FileManager.jsx
+++ b/frontend/src/pages/FileManager.jsx
@@ -331,7 +331,7 @@ function FileManager() {
const displayedEntries = searchResults || entries;
return (
- <div className={`file-manager ${sidebarVisible ? 'sidebar-open' : ''}`}>
+ <div className={`page-container file-manager-page file-manager ${sidebarVisible ? 'sidebar-open' : ''}`}>
<div className="page-header">
<div className="page-header-content">
<h1>File Manager</h1>
diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsx
index dd6d0a29..faf75261 100644
--- a/frontend/src/pages/ServerDetail.jsx
+++ b/frontend/src/pages/ServerDetail.jsx
@@ -25,7 +25,7 @@ const ServerDetail = () => {
const [showTokenModal, setShowTokenModal] = useState(false);
const toast = useToast();
- const validTabs = ['overview', 'docker', 'cron', 'metrics', 'settings'];
+ const validTabs = ['overview', 'docker', 'cron', 'cloudflared', 'metrics', 'settings'];
const activeTab = validTabs.includes(tab) ? tab : 'overview';
const loadServer = useCallback(async () => {
@@ -167,6 +167,7 @@ const ServerDetail = () => {
{ id: 'overview', label: 'Overview' },
{ id: 'docker', label: 'Docker' },
...(server.capabilities?.cron ? [{ id: 'cron', label: 'Cron' }] : []),
+ ...(server.capabilities?.cloudflared ? [{ id: 'cloudflared', label: 'Tunnels' }] : []),
{ id: 'metrics', label: 'Metrics' },
{ id: 'settings', label: 'Settings' }
];
@@ -259,6 +260,11 @@ const ServerDetail = () => {
<CronTab serverId={id} serverStatus={server.status} />
</TabsContent>
)}
+ {server.capabilities?.cloudflared && (
+ <TabsContent value="cloudflared">
+ <CloudflaredTab serverId={id} serverStatus={server.status} />
+ </TabsContent>
+ )}
<TabsContent value="metrics">
<MetricsTab serverId={id} metrics={metrics} />
</TabsContent>
@@ -902,6 +908,309 @@ const CronTab = ({ serverId, serverStatus }) => {
);
};
+// CloudflaredTab — manage Cloudflare named tunnels via the agent.
+//
+// Auth model: the user runs `cloudflared tunnel login` once on the
+// server. That writes ~/.cloudflared/cert.pem (or
+// /etc/cloudflared/cert.pem when run as root). The panel never sees
+// a Cloudflare API token — every action shells out to cloudflared
+// using that cert. /status surfaces both "binary present" and
+// "cert present" so we can show "log in first" before users hit
+// CRUD actions and get confusing errors back.
+const CloudflaredTab = ({ serverId, serverStatus }) => {
+ const toast = useToast();
+ const { confirm: confirmCf, confirmState: confirmCfState, handleConfirm: handleCfConfirm, handleCancel: handleCfCancel } = useConfirm();
+ const [status, setStatus] = useState(null);
+ const [tunnels, setTunnels] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+
+ const [showCreateModal, setShowCreateModal] = useState(false);
+ const [createName, setCreateName] = useState('');
+ const [creating, setCreating] = useState(false);
+
+ const [showRouteModal, setShowRouteModal] = useState(false);
+ const [routeTunnel, setRouteTunnel] = useState(null);
+ const [routeHostname, setRouteHostname] = useState('');
+ const [routing, setRouting] = useState(false);
+
+ const loadStatus = useCallback(async () => {
+ try {
+ const s = await api.getRemoteCloudflaredStatus(serverId);
+ setStatus(s);
+ } catch (err) {
+ console.error('Failed to load cloudflared status:', err);
+ }
+ }, [serverId]);
+
+ const loadTunnels = useCallback(async () => {
+ try {
+ const data = await api.getRemoteCloudflaredTunnels(serverId);
+ setTunnels(data?.tunnels || []);
+ setError(null);
+ } catch (err) {
+ // Auth errors here are common when the user hasn't logged
+ // in yet — the status banner already explains; don't show
+ // a redundant scary alert.
+ setError(err.message || 'Failed to load tunnels');
+ }
+ }, [serverId]);
+
+ useEffect(() => {
+ if (serverStatus !== 'online') {
+ setLoading(false);
+ return;
+ }
+ let cancelled = false;
+ (async () => {
+ setLoading(true);
+ await loadStatus();
+ await loadTunnels();
+ if (!cancelled) setLoading(false);
+ })();
+ return () => { cancelled = true; };
+ }, [serverStatus, loadStatus, loadTunnels]);
+
+ async function handleCreate(e) {
+ e.preventDefault();
+ const name = createName.trim();
+ if (!name) {
+ toast.error('Name is required');
+ return;
+ }
+ setCreating(true);
+ try {
+ await api.createRemoteCloudflaredTunnel(serverId, name);
+ toast.success(`Tunnel "${name}" created`);
+ setShowCreateModal(false);
+ setCreateName('');
+ loadTunnels();
+ } catch (err) {
+ toast.error(err.message || 'Failed to create tunnel');
+ } finally {
+ setCreating(false);
+ }
+ }
+
+ async function handleRoute(e) {
+ e.preventDefault();
+ const hostname = routeHostname.trim();
+ if (!hostname || !routeTunnel) return;
+ setRouting(true);
+ try {
+ await api.routeRemoteCloudflaredTunnel(serverId, routeTunnel.id || routeTunnel.name, hostname);
+ toast.success(`${hostname} → ${routeTunnel.name}`);
+ setShowRouteModal(false);
+ setRouteHostname('');
+ setRouteTunnel(null);
+ } catch (err) {
+ toast.error(err.message || 'Failed to add route');
+ } finally {
+ setRouting(false);
+ }
+ }
+
+ async function handleDelete(tunnel) {
+ const ok = await confirmCf({
+ title: 'Delete Tunnel',
+ message: `Delete tunnel "${tunnel.name}"? Active connections will be force-closed.`,
+ variant: 'danger',
+ });
+ if (!ok) return;
+ try {
+ await api.deleteRemoteCloudflaredTunnel(serverId, tunnel.id || tunnel.name);
+ toast.success('Tunnel deleted');
+ loadTunnels();
+ } catch (err) {
+ toast.error(err.message || 'Failed to delete tunnel');
+ }
+ }
+
+ if (serverStatus !== 'online') {
+ return (
+ <div className="offline-notice">
+ <OfflineIcon />
+ <h4>Server Offline</h4>
+ <p>Tunnel management requires the server to be online.</p>
+ </div>
+ );
+ }
+
+ if (loading) {
+ return <div className="loading">Loading tunnels...</div>;
+ }
+
+ // Status banner — three distinct states the UI cares about:
+ // 1. binary missing → "install cloudflared"
+ // 2. binary, no cert → "log in once"
+ // 3. binary + cert → ready to manage tunnels
+ const notInstalled = status?.available === false;
+ const notAuthed = status?.available && status?.authenticated === false;
+
+ return (
+ <div className="cloudflared-tab">
+ <div className="cron-tab__header">
+ <div className="cron-tab__status">
+ {notInstalled ? (
+ <Badge variant="warning">cloudflared not installed</Badge>
+ ) : notAuthed ? (
+ <Badge variant="warning">not authenticated — run cloudflared tunnel login</Badge>
+ ) : (
+ <Badge variant="success">cloudflared ready{status?.version ? ` (${status.version})` : ''}</Badge>
+ )}
+ <span className="cron-tab__count">{tunnels.length} tunnel{tunnels.length === 1 ? '' : 's'}</span>
+ </div>
+ <div className="cron-tab__actions">
+ <Button variant="outline" onClick={loadTunnels} disabled={notInstalled}>Refresh</Button>
+ <Button onClick={() => setShowCreateModal(true)} disabled={notInstalled || notAuthed}>
+ Create Tunnel
+ </Button>
+ </div>
+ </div>
+
+ {(notInstalled || notAuthed) && (
+ <div className="cloudflared-tab__hint">
+ {notInstalled ? (
+ <>
+ Install cloudflared on the server, then return here. See the{' '}
+ <a href="https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/get-started/" target="_blank" rel="noreferrer">
+ Cloudflare docs
+ </a>.
+ </>
+ ) : (
+ <>
+ On the server, run <code>sudo cloudflared tunnel login</code>. A browser
+ window will open and ask you to pick a Cloudflare zone. After that, click
+ Refresh here.
+ </>
+ )}
+ </div>
+ )}
+
+ {error && !notAuthed && !notInstalled && (
+ <div className="alert alert-danger">{error}</div>
+ )}
+
+ {!notInstalled && !notAuthed && (
+ tunnels.length === 0 ? (
+ <div className="empty-list">
+ No tunnels on this server. Click &quot;Create Tunnel&quot; to make one.
+ </div>
+ ) : (
+ <table className="data-table">
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>ID</th>
+ <th>Connections</th>
+ <th className="actions-cell">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {tunnels.map(t => (
+ <tr key={t.id || t.name}>
+ <td><span className="cron-tab__name">{t.name}</span></td>
+ <td className="mono">{(t.id || '').substring(0, 8)}…</td>
+ <td>{t.connections?.length || 0}</td>
+ <td className="actions-cell">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => { setRouteTunnel(t); setShowRouteModal(true); }}
+ >
+ Route subdomain
+ </Button>
+ <button
+ className="btn-icon danger"
+ onClick={() => handleDelete(t)}
+ title="Delete"
+ >
+ <TrashIcon />
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )
+ )}
+
+ {showCreateModal && (
+ <div className="modal-overlay" onClick={() => !creating && setShowCreateModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h3>Create Tunnel</h3>
+ <button className="modal-close" onClick={() => setShowCreateModal(false)} disabled={creating}>×</button>
+ </div>
+ <form onSubmit={handleCreate}>
+ <div className="modal-body">
+ <div className="form-group">
+ <label htmlFor="cf-name">Tunnel Name</label>
+ <Input
+ id="cf-name"
+ value={createName}
+ onChange={(e) => setCreateName(e.target.value)}
+ placeholder="my-app"
+ required
+ autoFocus
+ />
+ <p className="form-hint">Letters, numbers, dashes, underscores. Up to 32 chars.</p>
+ </div>
+ </div>
+ <div className="modal-footer">
+ <Button type="button" variant="outline" onClick={() => setShowCreateModal(false)} disabled={creating}>Cancel</Button>
+ <Button type="submit" disabled={creating}>{creating ? 'Creating…' : 'Create'}</Button>
+ </div>
+ </form>
+ </div>
+ </div>
+ )}
+
+ {showRouteModal && routeTunnel && (
+ <div className="modal-overlay" onClick={() => !routing && setShowRouteModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h3>Route Subdomain → {routeTunnel.name}</h3>
+ <button className="modal-close" onClick={() => setShowRouteModal(false)} disabled={routing}>×</button>
+ </div>
+ <form onSubmit={handleRoute}>
+ <div className="modal-body">
+ <div className="form-group">
+ <label htmlFor="cf-host">Hostname</label>
+ <Input
+ id="cf-host"
+ value={routeHostname}
+ onChange={(e) => setRouteHostname(e.target.value)}
+ placeholder="app.example.com"
+ required
+ autoFocus
+ />
+ <p className="form-hint">A CNAME for this hostname will be created in Cloudflare DNS, pointing at the tunnel.</p>
+ </div>
+ </div>
+ <div className="modal-footer">
+ <Button type="button" variant="outline" onClick={() => setShowRouteModal(false)} disabled={routing}>Cancel</Button>
+ <Button type="submit" disabled={routing}>{routing ? 'Adding…' : 'Add Route'}</Button>
+ </div>
+ </form>
+ </div>
+ </div>
+ )}
+
+ <ConfirmDialog
+ isOpen={confirmCfState.isOpen}
+ title={confirmCfState.title}
+ message={confirmCfState.message}
+ confirmText={confirmCfState.confirmText}
+ cancelText={confirmCfState.cancelText}
+ variant={confirmCfState.variant}
+ onConfirm={handleCfConfirm}
+ onCancel={handleCfCancel}
+ />
+ </div>
+ );
+};
+
const MetricsTab = ({ serverId, metrics }) => {
const formatBytes = (bytes) => {
if (!bytes) return 'N/A';
diff --git a/frontend/src/pages/StyleGuide.jsx b/frontend/src/pages/StyleGuide.jsx
index 859deffa..34ea3708 100644
--- a/frontend/src/pages/StyleGuide.jsx
+++ b/frontend/src/pages/StyleGuide.jsx
@@ -72,18 +72,16 @@ export default function StyleGuide() {
</div>
</div>
- <div className="styleguide__nav">
- {sections.map(s => (
- <button
- key={s.id}
- className={`styleguide__nav-btn ${activeSection === s.id ? 'active' : ''}`}
- onClick={() => setActiveSection(s.id)}
- >
- <s.icon size={14} />
- {s.label}
- </button>
- ))}
- </div>
+ <Tabs value={activeSection} onValueChange={setActiveSection}>
+ <TabsList>
+ {sections.map(s => (
+ <TabsTrigger key={s.id} value={s.id}>
+ <s.icon size={14} />
+ {s.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
<div className="styleguide__content">
diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.js
index aa5eb4a6..c6d54606 100644
--- a/frontend/src/services/api/servers.js
+++ b/frontend/src/services/api/servers.js
@@ -199,6 +199,35 @@ export async function toggleRemoteCronJob(serverId, jobId, enabled) {
});
}
+// Remote Cloudflared (Tunnels)
+export async function getRemoteCloudflaredStatus(serverId) {
+ return this.request(`/servers/${serverId}/cloudflared/status`);
+}
+
+export async function getRemoteCloudflaredTunnels(serverId) {
+ return this.request(`/servers/${serverId}/cloudflared/tunnels`);
+}
+
+export async function createRemoteCloudflaredTunnel(serverId, name) {
+ return this.request(`/servers/${serverId}/cloudflared/tunnels`, {
+ method: 'POST',
+ body: { name }
+ });
+}
+
+export async function routeRemoteCloudflaredTunnel(serverId, tunnelRef, hostname) {
+ return this.request(`/servers/${serverId}/cloudflared/tunnels/${encodeURIComponent(tunnelRef)}/route`, {
+ method: 'POST',
+ body: { hostname }
+ });
+}
+
+export async function deleteRemoteCloudflaredTunnel(serverId, tunnelRef) {
+ return this.request(`/servers/${serverId}/cloudflared/tunnels/${encodeURIComponent(tunnelRef)}`, {
+ method: 'DELETE'
+ });
+}
+
// Get available servers for Docker operations
export async function getAvailableServers() {
return this.request('/servers/available');
diff --git a/frontend/src/styles/pages/_servers.scss b/frontend/src/styles/pages/_servers.scss
index 047cfb1e..5b845089 100644
--- a/frontend/src/styles/pages/_servers.scss
+++ b/frontend/src/styles/pages/_servers.scss
@@ -1287,6 +1287,39 @@
}
}
+// Cloudflared tab — reuses .cron-tab__* helpers; add only the auth
+// hint banner since it's unique to this surface.
+.cloudflared-tab {
+ background: $bg-card;
+ border: 1px solid $border-subtle;
+ border-radius: $radius-lg;
+ overflow: hidden;
+
+ &__hint {
+ margin: $space-4;
+ padding: $space-3 $space-4;
+ background: rgba($accent-primary, 0.08);
+ border: 1px solid rgba($accent-primary, 0.3);
+ border-radius: $radius-md;
+ color: $text-secondary;
+ font-size: $font-size-sm;
+
+ code {
+ background: $bg-elevated;
+ padding: 0 $space-1;
+ border-radius: $radius-sm;
+ font-family: $font-mono;
+ font-size: $font-size-xs;
+ color: $text-primary;
+ }
+
+ a {
+ color: $accent-primary;
+ text-decoration: underline;
+ }
+ }
+}
+
.docker-sub-tabs {
display: flex;
border-bottom: 1px solid $border-subtle;
diff --git a/frontend/src/styles/pages/_terminal.scss b/frontend/src/styles/pages/_terminal.scss
index 7fc3f2ac..a60ea379 100644
--- a/frontend/src/styles/pages/_terminal.scss
+++ b/frontend/src/styles/pages/_terminal.scss
@@ -652,6 +652,8 @@
display: flex;
flex-direction: column;
gap: $space-2;
+ flex: 1 1 240px;
+ min-width: 240px;
.service-header {
display: flex;
@@ -714,9 +716,10 @@
.service-actions {
display: flex;
- gap: $space-1;
- margin-top: $space-2;
- padding-top: $space-2;
+ flex-wrap: wrap;
+ gap: $space-2;
+ margin-top: auto;
+ padding-top: $space-3;
border-top: 1px solid $border-subtle;
}
}