// SPDX-License-Identifier: AGPL-3.0-or-later // Package spa serves the built Docwell web app (Web-App/frontend, output // copied to dist/ by `npm run build:web`) together with its runtime config. package spa import ( "embed" "encoding/json" "io/fs" "net/http" "net/http/httputil" "net/url" "path" "strings" ) //go:embed all:dist var dist embed.FS // RuntimeConfig is served at /config.json so one build works in any deployment. type RuntimeConfig struct { APIURL string `json:"apiUrl"` CollabURL string `json:"collabUrl"` Version string `json:"version"` } type Options struct { Config RuntimeConfig // ProxyTarget, when set, reverse-proxies /api/ and /collab to // docwell-server so the app and API share one origin. ProxyTarget *url.URL // Files overrides the embedded build (used in tests). Files fs.FS } func Handler(opts Options) http.Handler { files := opts.Files if files == nil { files, _ = fs.Sub(dist, "dist") } fileServer := http.FileServerFS(files) cfgJSON, _ := json.Marshal(opts.Config) mux := http.NewServeMux() mux.HandleFunc("GET /config.json", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-cache") w.Write(cfgJSON) }) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"status":"ok"}`)) }) if opts.ProxyTarget != nil { proxy := httputil.NewSingleHostReverseProxy(opts.ProxyTarget) mux.Handle("/api/", proxy) mux.Handle("/collab", proxy) mux.Handle("/admin/", proxy) } // Registered without a method so it does not conflict with the proxy routes. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet && r.Method != http.MethodHead { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } name := strings.TrimPrefix(path.Clean(r.URL.Path), "/") if name == "" { name = "index.html" } if _, err := fs.Stat(files, name); err != nil { name = "index.html" } if _, err := fs.Stat(files, "index.html"); err != nil { http.Error(w, "web app not built: run `npm run build:web`", http.StatusServiceUnavailable) return } if name == "index.html" { w.Header().Set("Cache-Control", "no-cache") http.ServeFileFS(w, r, files, "index.html") return } if strings.HasPrefix(name, "assets/") { w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") } fileServer.ServeHTTP(w, r) }) return securityHeaders(mux) } func securityHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() h.Set("X-Content-Type-Options", "nosniff") h.Set("Referrer-Policy", "strict-origin-when-cross-origin") h.Set("X-Frame-Options", "SAMEORIGIN") next.ServeHTTP(w, r) }) }