Files
Deployr/internal/ui/server.go
T
ClaudeandClaude Opus 5 af2a96e072 Add the browser UI, terminal menu, and one-liner bootstrap
Deployr is now installable and drivable the way winutil is: one PowerShell or
shell line, no prior setup on the machine.

    irm .../scripts/install.ps1 | iex
    curl -fsSL .../scripts/install.sh | sh

The bootstrap self-elevates, picks the right binary for the machine's
architecture, verifies it against the release SHA256SUMS, puts it on PATH and
opens the UI. Arguments pass through for unattended use.

`deployr ui` serves a point-and-click page on loopback and opens a browser at
it: apps grouped by category, profile bundles, a filter box, and per-app
progress streamed live over SSE as the engine runs. A browser page rather than a
native window because it is the only GUI that behaves the same on all three
platforms without a toolkit or cgo, so the binary stays one static file.

It is not a hole in the endpoint: loopback-only on an OS-assigned port, a
session token minted per run and required on every request, plus Origin and
Host checks so no other page can drive a tool that installs software as SYSTEM.
A run keeps going if the tab closes -- aborting mid-installer is worse than
finishing without a spectator.

`deployr menu` is the same thing as a numbered terminal picker, for a machine
reached over SSH or a recovery console where no browser exists.

Engine gains optional OnAppStart/OnResult hooks, which is what makes progress
streamable instead of a report that only shows up at the end.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 17:16:52 -05:00

432 lines
11 KiB
Go

// Package ui serves deployr's point-and-click interface as a small local web
// app. A browser page is the only GUI that works identically on Windows, macOS
// and Linux without dragging a toolkit -- and without cgo -- so the binary stays
// a single static file you can drop on any endpoint.
package ui
import (
"context"
"crypto/rand"
"crypto/subtle"
"embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os/exec"
"runtime"
"strings"
"sync"
"time"
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
"git.starwarslab.us/ATOM_IT/Deployr/internal/detect"
"git.starwarslab.us/ATOM_IT/Deployr/internal/engine"
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
"git.starwarslab.us/ATOM_IT/Deployr/internal/version"
)
//go:embed assets/*
var assets embed.FS
// Config controls the UI server.
type Config struct {
Catalog *catalog.Catalog
Log *logx.Logger
// Addr is the listen address. Defaults to 127.0.0.1:0 -- loopback only, on
// a port the OS picks, so two technicians on one terminal server do not
// collide and nothing is exposed to the network.
Addr string
// NoBrowser suppresses opening the default browser.
NoBrowser bool
// Timeout is per-installer, passed through to the engine.
Timeout time.Duration
// DryRun plans without changing the machine.
DryRun bool
}
// Server is a running UI instance.
type Server struct {
cfg Config
token string
url string
mu sync.Mutex
running bool
subs map[chan event]struct{}
}
type event struct {
Kind string `json:"kind"` // start, result, done, log
App string `json:"app,omitempty"`
Name string `json:"name,omitempty"`
Message string `json:"message,omitempty"`
Result *engine.Result `json:"result,omitempty"`
Summary *engine.Summary `json:"summary,omitempty"`
}
// Serve starts the UI and blocks until the context is cancelled or the page
// asks to shut down.
func Serve(ctx context.Context, cfg Config) error {
if cfg.Addr == "" {
cfg.Addr = "127.0.0.1:0"
}
tokenBytes := make([]byte, 24)
if _, err := rand.Read(tokenBytes); err != nil {
return fmt.Errorf("generate session token: %w", err)
}
s := &Server{
cfg: cfg,
token: hex.EncodeToString(tokenBytes),
subs: map[chan event]struct{}{},
}
ln, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return fmt.Errorf("listen on %s: %w", cfg.Addr, err)
}
s.url = fmt.Sprintf("http://%s/?t=%s", ln.Addr().String(), s.token)
shutdown := make(chan struct{})
srv := &http.Server{
Handler: s.routes(shutdown),
ReadHeaderTimeout: 10 * time.Second,
}
go func() {
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) && cfg.Log != nil {
cfg.Log.Errorf("ui server: %v", err)
}
}()
if cfg.Log != nil {
cfg.Log.Infof("Deployr UI: %s", s.url)
cfg.Log.Infof("press Ctrl+C to stop")
}
if !cfg.NoBrowser {
openBrowser(s.url, cfg.Log)
}
select {
case <-ctx.Done():
case <-shutdown:
}
stopCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return srv.Shutdown(stopCtx)
}
// URL is the address the UI is served on, including the session token.
func (s *Server) URL() string { return s.url }
func (s *Server) routes(shutdown chan struct{}) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /", s.guard(s.handleIndex))
mux.HandleFunc("GET /api/state", s.guard(s.handleState))
mux.HandleFunc("POST /api/run", s.guard(s.handleRun))
mux.HandleFunc("GET /api/events", s.guard(s.handleEvents))
mux.HandleFunc("POST /api/quit", s.guard(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
select {
case <-shutdown:
default:
close(shutdown)
}
}))
return mux
}
// guard enforces the session token and rejects cross-origin requests. Without
// this, any web page the technician has open could drive a tool that installs
// software as SYSTEM.
func (s *Server) guard(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
if !strings.HasSuffix(origin, r.Host) {
http.Error(w, "cross-origin requests are not allowed", http.StatusForbidden)
return
}
}
// A Host header that is not our loopback listener means someone
// resolved a name to 127.0.0.1 to reach us (DNS rebinding).
if !isLoopbackHost(r.Host) {
http.Error(w, "unexpected host", http.StatusForbidden)
return
}
token := r.URL.Query().Get("t")
if token == "" {
token = r.Header.Get("X-Deployr-Token")
}
if subtle.ConstantTimeCompare([]byte(token), []byte(s.token)) != 1 {
http.Error(w, "invalid or missing session token", http.StatusForbidden)
return
}
next(w, r)
}
}
func isLoopbackHost(host string) bool {
h, _, err := net.SplitHostPort(host)
if err != nil {
h = host
}
if h == "localhost" {
return true
}
ip := net.ParseIP(h)
return ip != nil && ip.IsLoopback()
}
func (s *Server) handleIndex(w http.ResponseWriter, _ *http.Request) {
page, err := assets.ReadFile("assets/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Write(page)
}
type stateApp struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Category string `json:"category"`
Homepage string `json:"homepage,omitempty"`
Installed bool `json:"installed"`
Version string `json:"version,omitempty"`
Provider string `json:"provider"`
}
type state struct {
Version string `json:"version"`
Host string `json:"host"`
OS string `json:"os"`
Arch string `json:"arch"`
Elevated bool `json:"elevated"`
DryRun bool `json:"dry_run"`
Running bool `json:"running"`
Apps []stateApp `json:"apps"`
Profiles map[string][]string `json:"profiles"`
Installed int `json:"installed"`
}
func (s *Server) handleState(w http.ResponseWriter, _ *http.Request) {
st := state{
Version: version.Version,
Host: platform.Hostname(),
OS: runtime.GOOS,
Arch: runtime.GOARCH,
Elevated: platform.IsElevated(),
DryRun: s.cfg.DryRun,
Profiles: map[string][]string{},
}
s.mu.Lock()
st.Running = s.running
s.mu.Unlock()
for _, app := range s.cfg.Catalog.ForPlatform(runtime.GOOS) {
target := app.TargetFor(runtime.GOOS)
installed, ver := detect.Installed(target.Detect)
if installed {
st.Installed++
}
category := "other"
if len(app.Categories) > 0 {
category = app.Categories[0]
}
provider := ""
if len(target.Sources) > 0 {
provider = target.Sources[0].Provider
}
st.Apps = append(st.Apps, stateApp{
ID: app.ID, Name: app.Name, Description: app.Description,
Category: category, Homepage: app.Homepage,
Installed: installed, Version: ver, Provider: provider,
})
}
// Only offer profiles that actually have members on this platform.
supported := map[string]bool{}
for _, a := range st.Apps {
supported[a.ID] = true
}
for name, members := range s.cfg.Catalog.Profiles {
var usable []string
for _, id := range members {
if supported[id] {
usable = append(usable, id)
}
}
if len(usable) > 0 {
st.Profiles[name] = usable
}
}
writeJSON(w, st)
}
type runRequest struct {
Action string `json:"action"`
Apps []string `json:"apps"`
}
func (s *Server) handleRun(w http.ResponseWriter, r *http.Request) {
var req runRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest)
return
}
switch engine.Action(req.Action) {
case engine.ActionInstall, engine.ActionUpdate, engine.ActionUninstall:
default:
http.Error(w, "unknown action "+req.Action, http.StatusBadRequest)
return
}
apps, unknown := s.cfg.Catalog.Resolve(req.Apps)
if len(unknown) > 0 {
http.Error(w, "unknown apps: "+strings.Join(unknown, ", "), http.StatusBadRequest)
return
}
if len(apps) == 0 {
http.Error(w, "nothing selected", http.StatusBadRequest)
return
}
s.mu.Lock()
if s.running {
s.mu.Unlock()
http.Error(w, "a run is already in progress", http.StatusConflict)
return
}
s.running = true
s.mu.Unlock()
go s.execute(engine.Action(req.Action), apps)
w.WriteHeader(http.StatusAccepted)
}
// execute runs the engine and fans results out to every connected page. It
// deliberately uses its own context: closing the browser tab must not abort an
// installer that is already writing to the machine.
func (s *Server) execute(action engine.Action, apps []*catalog.App) {
defer func() {
s.mu.Lock()
s.running = false
s.mu.Unlock()
}()
summary := engine.Run(context.Background(), apps, engine.Config{
Action: action,
DryRun: s.cfg.DryRun,
Timeout: s.cfg.Timeout,
CacheDir: platform.CacheDir(),
Log: s.cfg.Log,
OnAppStart: func(app *catalog.App) {
s.broadcast(event{Kind: "start", App: app.ID, Name: app.Name})
},
OnResult: func(res engine.Result) {
r := res
s.broadcast(event{Kind: "result", App: res.App, Name: res.Name, Result: &r})
},
})
s.broadcast(event{Kind: "done", Summary: &summary})
}
func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
flusher.Flush()
ch := make(chan event, 64)
s.mu.Lock()
s.subs[ch] = struct{}{}
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.subs, ch)
s.mu.Unlock()
}()
// A comment line every 20s keeps proxies and impatient browsers from
// dropping an idle stream during a long installer.
ping := time.NewTicker(20 * time.Second)
defer ping.Stop()
for {
select {
case <-r.Context().Done():
return
case <-ping.C:
fmt.Fprint(w, ": ping\n\n")
flusher.Flush()
case ev := <-ch:
data, err := json.Marshal(ev)
if err != nil {
continue
}
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
}
}
}
// broadcast delivers an event to every open page, dropping it for any listener
// that has fallen behind rather than blocking the install.
func (s *Server) broadcast(ev event) {
s.mu.Lock()
defer s.mu.Unlock()
for ch := range s.subs {
select {
case ch <- ev:
default:
}
}
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
json.NewEncoder(w).Encode(v)
}
// openBrowser asks the desktop to open the UI. A failure is not fatal: the URL
// is printed either way, which is all a headless or SSH session needs.
func openBrowser(url string, log *logx.Logger) {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
case "darwin":
cmd = exec.Command("/usr/bin/open", url)
default:
cmd = exec.Command("xdg-open", url)
}
if err := cmd.Start(); err != nil {
if log != nil {
log.Debugf("could not open a browser (%v); open the URL above yourself", err)
}
return
}
go cmd.Wait()
}