sonda/internal/api/http/web.go
tgiachi 2217a12042 feat(web): the app can be installed and opens offline (PWA)
- A web app manifest with the name, the colours, the display mode and the icons (also a maskable one), so a browser offers to install it; Settings has an Install button where the browser lets the page ask.
- A service worker keeps the files of the app (the page, its scripts and styles, the manifest and the icons) so it opens at once, and shows its own page when the server cannot be reached. It never touches /api/: nothing from the API is kept, answered from a cache, or asked for by the worker. Files that failed, and anything that is not a file of the app, are not kept; the scripts it keeps are capped.
- A new version waits until the page says it may take over: a line says a new version is ready and its button reloads the page after the new worker took over.
- The server gives the manifest its type (application/manifest+json); the worker and the manifest are asked again every time, and the policy of the page needs no change.
2026-11-13 12:22:00 +01:00

142 lines
5.3 KiB
Go

package httpapi
import (
"io/fs"
"mime"
"net/http"
"path"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// appPolicy is what the page of the web app may load: only things from its own server. No
// address, no wildcard and no inline or eval script, so a page of the app cannot reach another
// host. `style-src-attr` lets the app set `style="..."` on an element (bars and rings); stylesheets
// and scripts still have to come from the server.
const appPolicy = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; " +
"img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self'; connect-src 'self'; " +
"object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
func init() {
// The manifest of the app has no type in the tables of the system, and "text/plain" would stop a browser from installing it.
_ = mime.AddExtensionType(".webmanifest", "application/manifest+json")
}
// Files under assets/ have a hash in their name, so a name never means two different files.
const (
assetsDir = "assets"
foreverCache = "public, max-age=31536000, immutable"
askAgainCache = "no-cache"
pageNotBuilt = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sonda</title><body style="font-family:system-ui,sans-serif;max-width:40rem;margin:3rem auto;padding:0 1rem;line-height:1.5"><h1>Sonda</h1><p>The server is running, but the web app is not part of this build.</p><p>Build it with <code>make build</code> (or build the app in <code>web/</code> and then <code>go build -tags webui</code>), or use the Docker image, which has it.</p><p>The API is at <code>/api/v1</code> and its documentation at <a href="/api/docs/">/api/docs/</a>.</p></body></html>`
)
// appHeaders protects the page of the app: it cannot be framed, the browser does not guess content
// types, no address leaves in a Referer, and the policy keeps it to its own server.
func appHeaders(c *gin.Context) {
h := c.Writer.Header()
h.Set("Content-Security-Policy", appPolicy)
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "no-referrer")
}
// noRoute answers every address that no API route owns. A GET or HEAD outside /api is the web
// app: a file of it, or, for a link inside the app (/admin/users), its page. Everything else
// keeps the JSON 404 the API has always given, and so does a file that is not there: a script
// that is missing must never come back as the page, which the browser would try to run.
func noRoute(web fs.FS) gin.HandlerFunc {
hasApp := false
if web != nil {
if info, err := fs.Stat(web, "index.html"); err == nil && !info.IsDir() {
hasApp = true
}
}
return func(c *gin.Context) {
urlPath := c.Request.URL.Path
readOnly := c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead
if !readOnly || urlPath == "/api" || strings.HasPrefix(urlPath, "/api/") {
writeError(c, http.StatusNotFound, "not_found", "no such route")
return
}
appHeaders(c)
if !hasApp {
respond(c, "text/html; charset=utf-8", askAgainCache, []byte(pageNotBuilt))
return
}
name := strings.Trim(urlPath, "/")
if name == "" {
serveIndex(c, web)
return
}
// Hidden files and anything that is not a clean path inside the app are never served.
if hidden(name) || !fs.ValidPath(name) {
writeError(c, http.StatusNotFound, "not_found", "no such file")
return
}
if info, err := fs.Stat(web, name); err == nil && !info.IsDir() {
serveFile(c, web, name)
return
}
// Not a file: under assets/ or with an extension it is a file that is missing; anything else
// is a link inside the app, which the app itself resolves.
if name == assetsDir || strings.HasPrefix(name, assetsDir+"/") || path.Ext(name) != "" {
writeError(c, http.StatusNotFound, "not_found", "no such file")
return
}
serveIndex(c, web)
}
}
// hidden is true when any part of the path starts with a dot (.gitkeep, .env, ..).
func hidden(name string) bool {
for _, part := range strings.Split(name, "/") {
if strings.HasPrefix(part, ".") {
return true
}
}
return false
}
func serveIndex(c *gin.Context, web fs.FS) {
body, err := fs.ReadFile(web, "index.html")
if err != nil {
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
respond(c, "text/html; charset=utf-8", askAgainCache, body)
}
func serveFile(c *gin.Context, web fs.FS, name string) {
body, err := fs.ReadFile(web, name)
if err != nil {
writeError(c, http.StatusNotFound, "not_found", "no such file")
return
}
contentType := mime.TypeByExtension(path.Ext(name))
if contentType == "" {
contentType = http.DetectContentType(body)
}
cache := askAgainCache
if strings.HasPrefix(name, assetsDir+"/") {
cache = foreverCache
}
respond(c, contentType, cache, body)
}
// respond sends a body with its type and cache rule. A HEAD gets the same headers and no body.
func respond(c *gin.Context, contentType, cache string, body []byte) {
h := c.Writer.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Cache-Control", cache)
h.Set("Content-Type", contentType)
if c.Request.Method == http.MethodHead {
h.Set("Content-Length", strconv.Itoa(len(body)))
c.Status(http.StatusOK)
c.Writer.WriteHeaderNow()
return
}
c.Data(http.StatusOK, contentType, body)
}