From 7d55a9c05d201347cdad0959e701003d6479c2f8 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Fri, 1 May 2026 05:52:11 -0400 Subject: [PATCH] Add panel-driven cloudflared login flow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Users had to SSH in to run `cloudflared tunnel login` before any of the Tunnels tab worked. Wire up the OAuth flow so the panel can trigger it and surface the auth URL for the user to open from their own browser. Agent: - New cloudflared.LoginEvent + Manager.Login() that spawns the process, regex-matches the dash.cloudflare.com/argotunnel URL on stdout/stderr, and watches cert.pem in parallel as a reliable completion signal. 15-minute hard ceiling. - New cloudflared:login action returns {job_id, channel} immediately; the goroutine emits start → status (with auth_url) → done events on the job channel. - Non-linux stub returns "unsupported". - jobs.HasTerminated() helper so handler shutdown paths can avoid double-emitting the terminator. Panel: - POST /servers//cloudflared/login + RemoteCloudflaredService.login - ApiService.startRemoteCloudflaredLogin Frontend: - CloudflaredTab gains a "Login to Cloudflare" CTA when not authed. Click → starts the agent flow, joins the job's Socket.IO room, listens for the auth_url event, and renders an Open-in-Browser button. Once the agent emits done, refreshes capabilities + status + tunnel list automatically — the rest of the tab unlocks itself. Co-Authored-By: Claude Opus 4.7 (1M context) --- agent/internal/agent/agent.go | 1 + agent/internal/agent/cloudflared_handlers.go | 77 ++++++++++ agent/internal/cloudflared/cloudflared.go | 17 +++ .../internal/cloudflared/cloudflared_linux.go | 121 +++++++++++++++ .../internal/cloudflared/cloudflared_other.go | 3 + agent/internal/jobs/jobs.go | 12 ++ agent/pkg/protocol/messages.go | 1 + backend/app/api/servers.py | 12 ++ .../services/remote_cloudflared_service.py | 9 ++ frontend/src/pages/ServerDetail.jsx | 144 +++++++++++++++++- frontend/src/services/api/servers.js | 9 ++ .../src/styles/pages/_server-packages.scss | 41 +++++ 12 files changed, 442 insertions(+), 5 deletions(-) diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go index 1991a6f8..9d7a1721 100644 --- a/agent/internal/agent/agent.go +++ b/agent/internal/agent/agent.go @@ -279,6 +279,7 @@ func (a *Agent) registerHandlers() { // 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.ActionCloudflaredLogin] = a.handleCloudflaredLogin a.handlers[protocol.ActionCloudflaredTunnelList] = a.handleCloudflaredTunnelList a.handlers[protocol.ActionCloudflaredTunnelCreate] = a.handleCloudflaredTunnelCreate a.handlers[protocol.ActionCloudflaredTunnelRoute] = a.handleCloudflaredTunnelRoute diff --git a/agent/internal/agent/cloudflared_handlers.go b/agent/internal/agent/cloudflared_handlers.go index e5827b36..624781a0 100644 --- a/agent/internal/agent/cloudflared_handlers.go +++ b/agent/internal/agent/cloudflared_handlers.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/serverkit/agent/internal/cloudflared" + "github.com/serverkit/agent/internal/jobs" ) // Handlers for cloudflared:* actions. Same shape as cron handlers: @@ -49,6 +50,82 @@ func (a *Agent) handleCloudflaredTunnelRoute(ctx context.Context, params json.Ra return map[string]bool{"success": true}, nil } +// handleCloudflaredLogin starts `cloudflared tunnel login` and streams +// progress on a job channel. Returns {job_id, channel} immediately so +// the panel can subscribe and surface the auth URL the moment +// cloudflared prints it. The flow: +// +// 1. Agent spawns `cloudflared tunnel login` with stdout/stderr piped +// 2. First line containing https://dash.cloudflare.com/argotunnel?... +// is reported as a 'status' event with auth_url +// 3. Panel renders a clickable button; user opens URL → authorises +// 4. cloudflared writes cert.pem and exits +// 5. Agent emits 'done' with the cert path; panel can refresh +// capabilities to flip the Authenticated badge. +// +// 15-minute hard ceiling (cloudflared blocks waiting for the OAuth +// callback) — long enough for a coffee break, short enough that a +// forgotten browser tab gets reaped. +func (a *Agent) handleCloudflaredLogin(ctx context.Context, _ json.RawMessage) (interface{}, error) { + // Use a background context for the subscription so the agent's + // 5-minute command timeout doesn't kill the login flow. + loginCtx := context.Background() + ch, err := a.cloudflared.Login(loginCtx) + if err != nil { + return nil, fmt.Errorf("start login: %w", err) + } + job := a.jobs.New(64) + go a.runCloudflaredLoginJob(job, ch) + return map[string]interface{}{ + "job_id": job.ID, + "channel": job.Channel, + }, nil +} + +func (a *Agent) runCloudflaredLoginJob(job *jobs.Job, events <-chan cloudflared.LoginEvent) { + exit := 0 + emit := func(ev jobs.Event) { _ = job.Push(a.ws, ev) } + emit(jobs.Event{Phase: jobs.PhaseStart, Message: "starting cloudflared tunnel login"}) + + for ev := range events { + switch { + case ev.AuthURL != "": + emit(jobs.Event{ + Phase: jobs.PhaseStatus, + Message: "Open this URL in your browser to authorise the agent", + Extra: map[string]interface{}{"auth_url": ev.AuthURL}, + }) + if ev.Line != "" { + emit(jobs.Event{Phase: jobs.PhaseLog, Lines: []string{ev.Line}}) + } + case ev.Done: + if ev.Error != "" { + exit = 1 + emit(jobs.Event{ + Phase: jobs.PhaseDone, + ExitCode: &exit, + Error: ev.Error, + }) + } else { + emit(jobs.Event{ + Phase: jobs.PhaseDone, + ExitCode: &exit, + Message: "authenticated", + Extra: map[string]interface{}{"cert_path": ev.CertPath}, + }) + } + case ev.Line != "": + emit(jobs.Event{Phase: jobs.PhaseLog, Lines: []string{ev.Line}}) + } + } + // Channel closed without explicit Done — emit a defensive + // terminator so the panel modal doesn't hang indefinitely. + if !job.HasTerminated() { + exit = 1 + emit(jobs.Event{Phase: jobs.PhaseDone, ExitCode: &exit, Error: "login stream ended unexpectedly"}) + } +} + func (a *Agent) handleCloudflaredTunnelDelete(ctx context.Context, params json.RawMessage) (interface{}, error) { var p struct { Ref string `json:"ref"` diff --git a/agent/internal/cloudflared/cloudflared.go b/agent/internal/cloudflared/cloudflared.go index 0c2e864e..c56345c3 100644 --- a/agent/internal/cloudflared/cloudflared.go +++ b/agent/internal/cloudflared/cloudflared.go @@ -69,6 +69,18 @@ type RouteRequest struct { Hostname string `json:"hostname"` } +// LoginEvent is emitted while a `cloudflared tunnel login` flow is in +// flight. AuthURL is the OAuth URL the user must open in a browser +// to authorise the agent host with their Cloudflare account; cert.pem +// is written by cloudflared once the OAuth round-trips. +type LoginEvent struct { + AuthURL string `json:"auth_url,omitempty"` + Line string `json:"line,omitempty"` + Done bool `json:"done,omitempty"` + CertPath string `json:"cert_path,omitempty"` + Error string `json:"error,omitempty"` +} + // Manager is the platform-agnostic interface; the Linux build wires // it up with real exec calls, non-Linux builds return "unsupported." type Manager interface { @@ -77,6 +89,11 @@ type Manager interface { Create(ctx context.Context, req CreateRequest) (*Tunnel, error) Route(ctx context.Context, req RouteRequest) error Delete(ctx context.Context, ref string) error + // Login starts `cloudflared tunnel login` and streams events on + // the returned channel. The first event carries the auth URL; the + // channel closes when cert.pem is written (Done=true) or the + // underlying process errors out. + Login(ctx context.Context) (<-chan LoginEvent, error) } // hasCloudflared is shared between the Linux backend and tests. diff --git a/agent/internal/cloudflared/cloudflared_linux.go b/agent/internal/cloudflared/cloudflared_linux.go index 53d30c60..844f2594 100644 --- a/agent/internal/cloudflared/cloudflared_linux.go +++ b/agent/internal/cloudflared/cloudflared_linux.go @@ -3,15 +3,18 @@ package cloudflared import ( + "bufio" "bytes" "context" "encoding/json" "fmt" + "io" "os" "os/exec" "path/filepath" "regexp" "strings" + "time" ) // New returns a Linux Manager that drives `cloudflared`. @@ -170,6 +173,124 @@ func (l *linuxManager) Route(ctx context.Context, req RouteRequest) error { return err } +// loginURLRegex matches the `https://dash.cloudflare.com/argotunnel?...` +// URL cloudflared prints to stdout during `tunnel login`. The exact +// text varies by version ("Please open the following URL", "Please +// visit", etc.), so we match the URL itself rather than the prompt. +var loginURLRegex = regexp.MustCompile(`https://dash\.cloudflare\.com/argotunnel\?\S+`) + +// Login spawns `cloudflared tunnel login` and streams a typed event +// channel. The first event after the URL is found carries AuthURL; +// the channel closes (with a final Done event) when cert.pem appears +// or the process exits / 15-minute hard ceiling fires. +// +// We can't just look at process exit because cloudflared sometimes +// prints the URL and exits cleanly while waiting on the OAuth callback +// in a separate flow. The cert.pem watcher is the source of truth. +func (l *linuxManager) Login(ctx context.Context) (<-chan LoginEvent, error) { + if _, ok := hasCloudflared(); !ok { + return nil, fmt.Errorf("cloudflared not installed") + } + // If cert.pem already exists, short-circuit — login would + // overwrite, which surprises the user. + if cert, ok := findCert(); ok { + out := make(chan LoginEvent, 1) + out <- LoginEvent{Done: true, CertPath: cert, Line: "already authenticated"} + close(out) + return out, nil + } + + out := make(chan LoginEvent, 8) + + // 15-minute ceiling on the login flow — long enough for a coffee + // break, short enough to garbage-collect a forgotten browser tab. + cctx, cancel := context.WithTimeout(ctx, 15*time.Minute) + + cmd := exec.CommandContext(cctx, "cloudflared", "tunnel", "login") + stdout, err := cmd.StdoutPipe() + if err != nil { + cancel() + return nil, fmt.Errorf("stdout pipe: %w", err) + } + stderr, err := cmd.StderrPipe() + if err != nil { + cancel() + return nil, fmt.Errorf("stderr pipe: %w", err) + } + if err := cmd.Start(); err != nil { + cancel() + return nil, fmt.Errorf("start cloudflared: %w", err) + } + + go func() { + defer cancel() + defer close(out) + + // Tee stdout + stderr into a single line stream. cloudflared + // has historically printed the auth URL on stderr (older + // versions) and stdout (newer), so listen to both. + lines := make(chan string, 32) + go scanLines(stdout, lines) + go scanLines(stderr, lines) + + urlSent := false + // Best-effort cert.pem watcher running in parallel. cloudflared + // itself exits as soon as the cert is fetched on success, but + // the watcher is the more reliable signal in case of weird + // stdout buffering. + certCheck := time.NewTicker(2 * time.Second) + defer certCheck.Stop() + + // Drain pipes + watch cert in the same select loop. + for { + select { + case <-cctx.Done(): + out <- LoginEvent{Done: true, Error: "login timed out"} + _ = cmd.Process.Kill() + return + case line, ok := <-lines: + if !ok { + // pipes closed — wait for cmd to reap and emit final. + _ = cmd.Wait() + if cert, ok := findCert(); ok { + out <- LoginEvent{Done: true, CertPath: cert} + } else { + out <- LoginEvent{Done: true, Error: "cloudflared exited without writing cert.pem"} + } + return + } + if !urlSent { + if u := loginURLRegex.FindString(line); u != "" { + urlSent = true + out <- LoginEvent{AuthURL: u, Line: line} + continue + } + } + out <- LoginEvent{Line: line} + case <-certCheck.C: + if cert, ok := findCert(); ok { + out <- LoginEvent{Done: true, CertPath: cert} + _ = cmd.Process.Kill() + return + } + } + } + }() + return out, nil +} + +// scanLines pumps r line-by-line into out. Closes out when r is +// exhausted; multiple producers are fine because the consumer treats +// a single closed channel as "all done." +func scanLines(r io.ReadCloser, out chan<- string) { + defer r.Close() + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 0, 64*1024), 1024*1024) + for sc.Scan() { + out <- sc.Text() + } +} + func (l *linuxManager) Delete(ctx context.Context, ref string) error { if ref == "" { return fmt.Errorf("ref is required") diff --git a/agent/internal/cloudflared/cloudflared_other.go b/agent/internal/cloudflared/cloudflared_other.go index 61f4a444..2bb1b071 100644 --- a/agent/internal/cloudflared/cloudflared_other.go +++ b/agent/internal/cloudflared/cloudflared_other.go @@ -23,3 +23,6 @@ func (stubManager) Create(ctx context.Context, _ CreateRequest) (*Tunnel, error) } func (stubManager) Route(ctx context.Context, _ RouteRequest) error { return errUnsupported } func (stubManager) Delete(ctx context.Context, _ string) error { return errUnsupported } +func (stubManager) Login(ctx context.Context) (<-chan LoginEvent, error) { + return nil, errUnsupported +} diff --git a/agent/internal/jobs/jobs.go b/agent/internal/jobs/jobs.go index 0614ee35..e87b5ff2 100644 --- a/agent/internal/jobs/jobs.go +++ b/agent/internal/jobs/jobs.go @@ -194,3 +194,15 @@ func (j *Job) Replay() []Event { // Done returns a channel closed when the job emits a final event with // Phase == PhaseDone. Useful for tests. func (j *Job) Done() <-chan struct{} { return j.done } + +// HasTerminated reports whether a Done event has already been emitted. +// Useful for handler shutdown paths that want to avoid double-emitting +// a final terminator if their primary loop already pushed one. +func (j *Job) HasTerminated() bool { + select { + case <-j.done: + return true + default: + return false + } +} diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.go index 118c791d..9e341ad8 100644 --- a/agent/pkg/protocol/messages.go +++ b/agent/pkg/protocol/messages.go @@ -322,6 +322,7 @@ const ( // `cloudflared tunnel login` (approach A from the design notes). // Status reflects "is binary installed AND has cert.pem". ActionCloudflaredStatus = "cloudflared:status" + ActionCloudflaredLogin = "cloudflared:login" ActionCloudflaredTunnelList = "cloudflared:tunnel:list" ActionCloudflaredTunnelCreate = "cloudflared:tunnel:create" ActionCloudflaredTunnelRoute = "cloudflared:tunnel:route" diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py index 7e85c930..c3616f09 100644 --- a/backend/app/api/servers.py +++ b/backend/app/api/servers.py @@ -2269,6 +2269,18 @@ def remote_cloudflared_status(server_id): return _agent_result(result) +@servers_bp.route('//cloudflared/login', methods=['POST']) +@jwt_required() +@developer_required +def remote_cloudflared_login(server_id): + """Start `cloudflared tunnel login` on the agent. Returns + {job_id, channel}; the panel subscribes to the corresponding + Socket.IO room and renders the auth_url the agent surfaces.""" + user_id = get_jwt_identity() + result = RemoteCloudflaredService.login(server_id, user_id=user_id) + return _agent_result(result) + + @servers_bp.route('//cloudflared/tunnels', methods=['GET']) @jwt_required() def remote_cloudflared_list(server_id): diff --git a/backend/app/services/remote_cloudflared_service.py b/backend/app/services/remote_cloudflared_service.py index 99990f4d..67f08f31 100644 --- a/backend/app/services/remote_cloudflared_service.py +++ b/backend/app/services/remote_cloudflared_service.py @@ -67,3 +67,12 @@ class RemoteCloudflaredService: params={'ref': ref}, user_id=user_id, timeout=30.0, ) + + @staticmethod + def login(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]: + # Returns {job_id, channel} immediately; the panel subscribes to + # the matching Socket.IO room for the auth_url + completion event. + return RemoteCloudflaredService._send( + server_id, 'cloudflared:login', + user_id=user_id, timeout=10.0, + ) diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsx index 19051378..92f18d7a 100644 --- a/frontend/src/pages/ServerDetail.jsx +++ b/frontend/src/pages/ServerDetail.jsx @@ -996,6 +996,9 @@ const CloudflaredTab = ({ serverId, serverStatus }) => { const [routeHostname, setRouteHostname] = useState(''); const [routing, setRouting] = useState(false); + // Login flow: { channel, authUrl, status: 'starting'|'awaiting'|'done'|'error', error, certPath } + const [login, setLogin] = useState(null); + const loadStatus = useCallback(async () => { try { const s = await api.getRemoteCloudflaredStatus(serverId); @@ -1088,6 +1091,65 @@ const CloudflaredTab = ({ serverId, serverStatus }) => { } } + // Triggers `cloudflared tunnel login` on the agent and subscribes + // to the streaming auth flow. The first event carries the auth URL + // we surface as a clickable button; the final event flips us back + // to ready state once cert.pem appears. + async function handleStartLogin() { + try { + const res = await api.startRemoteCloudflaredLogin(serverId); + const channel = res?.channel || `job:${res?.job_id}`; + setLogin({ channel, status: 'starting', authUrl: null, error: null, certPath: null }); + + // Reuse the live socket service to subscribe to the + // server_stream room. We don't open the JobProgressModal + // because the login flow needs a different shape (a single + // big "Open URL" CTA, not a log tail). + const { default: socketService } = await import('../services/socket'); + if (!socketService.socket) socketService.connect(); + const sock = socketService.socket; + if (!sock) { + setLogin(null); + toast.error('Socket not available'); + return; + } + const room = `server_${serverId}_${channel}`; + const onStream = (msg) => { + if (msg?.channel !== channel) return; + const ev = msg.data || {}; + const url = ev?.extra?.auth_url; + if (url) { + setLogin((cur) => cur ? { ...cur, status: 'awaiting', authUrl: url } : cur); + } + if (ev.phase === 'done') { + if (ev.error) { + setLogin((cur) => cur ? { ...cur, status: 'error', error: ev.error } : cur); + toast.error(`Login failed: ${ev.error}`); + } else { + setLogin((cur) => cur ? { ...cur, status: 'done', certPath: ev?.extra?.cert_path } : cur); + toast.success('Cloudflare login complete'); + // Refresh capabilities + status so the tab unlocks + // without a manual reload. + api.refreshRemoteCapabilities(serverId).catch(() => {}); + loadStatus(); + loadTunnels(); + } + sock.off('server_stream', onStream); + sock.emit('leave_room', { room }); + } + }; + sock.emit('join_room', { room }); + sock.on('server_stream', onStream); + } catch (err) { + toast.error(err.message || 'Failed to start login'); + setLogin(null); + } + } + + function handleCancelLogin() { + setLogin(null); + } + if (serverStatus !== 'online') { return (
@@ -1139,12 +1201,19 @@ const CloudflaredTab = ({ serverId, serverStatus }) => { Cloudflare docs . + ) : login ? ( + ) : ( - <> - On the server, run sudo cloudflared tunnel login. A browser - window will open and ask you to pick a Cloudflare zone. After that, click - Refresh here. - +
+

+ Cloudflare needs you to authorise this agent once. Click{' '} + Login below — we'll start the OAuth flow on the + server and surface the URL for you to open in your browser. Once you + authorise, the agent picks up the cert.pem automatically and the + rest of this tab unlocks. +

+ +
)}
)} @@ -1273,6 +1342,71 @@ const CloudflaredTab = ({ serverId, serverStatus }) => { ); }; +// CloudflaredLoginCard renders the in-flight OAuth login state. The +// agent has spawned `cloudflared tunnel login` on the server and is +// streaming progress on a job channel; we render either a spinner +// (while we wait for the URL), the Open-in-Browser CTA (once the URL +// arrives), or a final success/error message. +const CloudflaredLoginCard = ({ login, onCancel }) => { + if (!login) return null; + if (login.status === 'starting') { + return ( +
+

Asking the agent to start the Cloudflare login flow…

+ +
+ ); + } + if (login.status === 'awaiting' && login.authUrl) { + return ( +
+

+ Step 1 / 2: open the following URL in your browser, sign in + to Cloudflare, and pick the zone you want to associate with this agent. +

+
+ + Open Cloudflare login + + +
+

+ Step 2 / 2: waiting for the agent to receive cert.pem from + Cloudflare. This page will refresh automatically once authorisation completes. +

+ +
+ ); + } + if (login.status === 'done') { + return ( +
+ Authenticated. Refreshing… +
+ ); + } + if (login.status === 'error') { + return ( +
+ Login failed: {login.error || 'unknown error'} + +
+ ); + } + return null; +}; + const MetricsTab = ({ serverId, metrics }) => { const formatBytes = (bytes) => { if (!bytes) return 'N/A'; diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.js index ee4c61eb..84cac707 100644 --- a/frontend/src/services/api/servers.js +++ b/frontend/src/services/api/servers.js @@ -370,6 +370,15 @@ export async function getRemoteCloudflaredStatus(serverId) { return this.request(`/servers/${serverId}/cloudflared/status`); } +// Triggers `cloudflared tunnel login` on the agent. Returns +// {job_id, channel}; subscribe via JobProgressModal to receive the +// auth URL, then watch for the done event when cert.pem lands. +export async function startRemoteCloudflaredLogin(serverId) { + return this.request(`/servers/${serverId}/cloudflared/login`, { + method: 'POST' + }); +} + export async function getRemoteCloudflaredTunnels(serverId) { return this.request(`/servers/${serverId}/cloudflared/tunnels`); } diff --git a/frontend/src/styles/pages/_server-packages.scss b/frontend/src/styles/pages/_server-packages.scss index 328028d0..8b6b68db 100644 --- a/frontend/src/styles/pages/_server-packages.scss +++ b/frontend/src/styles/pages/_server-packages.scss @@ -228,6 +228,47 @@ } } +// Cloudflared login flow: surfaces the auth URL the agent captures +// from `cloudflared tunnel login` so the user can authorise from +// their own browser. +.cloudflared-login-prompt { + p { + margin: 0 0 0.75rem; + } +} + +.cloudflared-login-card { + padding: 1rem; + border: 1px solid var(--border); + border-radius: 0.5rem; + background: var(--card); + display: flex; + flex-direction: column; + gap: 0.75rem; + + &--success { + border-color: var(--success, #16a34a); + background: color-mix(in srgb, var(--success, #16a34a) 8%, transparent); + } + + &--error { + border-color: var(--destructive, #ef4444); + background: color-mix(in srgb, var(--destructive, #ef4444) 8%, transparent); + } + + &__actions { + display: flex; + gap: 0.5rem; + flex-wrap: wrap; + } + + &__hint { + font-size: 0.85rem; + color: var(--muted-foreground); + margin: 0; + } +} + // Shared by JobProgressModal — kept here because Packages is its primary // consumer. Services tab logs use a different component path. .job-progress-modal {