// Package adminui serves the admin single-page app built from /admin. package adminui import ( "bytes" "embed" "io/fs" "net/http" "path" "strings" "time" ) // dist holds the Vite build. A fresh checkout contains only .gitkeep: the // daemon still builds and answers 503 until `make admin` has run. // //go:embed all:dist var dist embed.FS // Embedded returns the handler for the UI built into the binary. func Embedded() http.Handler { sub, err := fs.Sub(dist, "dist") if err != nil { panic(err) // dist is a compile-time constant directory } return New(sub) } const csp = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; " + "object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'" // New serves a built single-page app from fsys. Unknown paths without a file // extension fall back to index.html so client-side routes survive a reload. func New(fsys fs.FS) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() h.Set("Content-Security-Policy", csp) h.Set("X-Content-Type-Options", "nosniff") h.Set("Referrer-Policy", "no-referrer") h.Set("X-Frame-Options", "DENY") if r.Method != http.MethodGet && r.Method != http.MethodHead { h.Set("Allow", "GET, HEAD") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } p := path.Clean("/" + r.URL.Path) if p == "/api" || strings.HasPrefix(p, "/api/") { http.NotFound(w, r) // the API is mounted separately; never answer with HTML return } if _, err := fs.Stat(fsys, "index.html"); err != nil { http.Error(w, "the admin UI is not built: run `make admin` and rebuild the binary", http.StatusServiceUnavailable) return } name := strings.TrimPrefix(p, "/") if name == "" { name = "index.html" } switch { case name == "assets" || strings.HasPrefix(name, "assets/"): // Vite fingerprints everything under assets/. if !serve(w, r, fsys, name, "public, max-age=31536000, immutable") { http.NotFound(w, r) } case serve(w, r, fsys, name, "no-cache"): case path.Ext(name) != "": http.NotFound(w, r) default: serve(w, r, fsys, "index.html", "no-cache") } }) } // serve writes a regular file and reports whether it exists. func serve(w http.ResponseWriter, r *http.Request, fsys fs.FS, name, cache string) bool { if info, err := fs.Stat(fsys, name); err != nil || info.IsDir() { return false } b, err := fs.ReadFile(fsys, name) if err != nil { return false } w.Header().Set("Cache-Control", cache) http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(b)) return true }