Merge pull request 'feat: serve the web app from sondad (F4)' (#82) from feat/serve-web into main
This commit is contained in:
commit
66a4ea5b5a
13 changed files with 484 additions and 11 deletions
|
|
@ -3,7 +3,10 @@
|
|||
.gitignore
|
||||
bin
|
||||
data
|
||||
web
|
||||
# The web app is built in the image; its dependencies and a build of it on this machine are not sent.
|
||||
web/node_modules
|
||||
web/dist
|
||||
internal/webui/dist
|
||||
**/*.db
|
||||
**/*.db-wal
|
||||
**/*.db-shm
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -1,4 +1,6 @@
|
|||
/bin/
|
||||
# The built web app, embedded in the binary by a build with -tags webui: an artifact, never committed.
|
||||
/internal/webui/dist/
|
||||
*.test
|
||||
*.out
|
||||
sonda.toml
|
||||
|
|
|
|||
15
Dockerfile
15
Dockerfile
|
|
@ -1,7 +1,17 @@
|
|||
# syntax=docker/dockerfile:1
|
||||
|
||||
# The web app: built once here, written (by its Vite config) to /src/internal/webui/dist, where the Go
|
||||
# build below embeds it. Nothing of Node reaches the final image.
|
||||
FROM node:24-alpine AS web
|
||||
WORKDIR /src/web
|
||||
COPY web/package.json web/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY web ./
|
||||
RUN npm run build
|
||||
|
||||
# Build: Sonda has no CGO (SQLite, PostgreSQL and the tag reader are pure Go), so the binary
|
||||
# is static and the final image needs nothing but it and the CA certificates.
|
||||
# is static and the final image needs nothing but it and the CA certificates. The web app is inside it
|
||||
# (-tags webui), so sondad serves it on / and the API on /api.
|
||||
FROM golang:1.27-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
|
|
@ -9,7 +19,8 @@ RUN go mod download
|
|||
COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
COPY migrations ./migrations
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/sondad ./cmd/sondad
|
||||
COPY --from=web /src/internal/webui/dist ./internal/webui/dist
|
||||
RUN CGO_ENABLED=0 go build -tags webui -trimpath -ldflags="-s -w" -o /out/sondad ./cmd/sondad
|
||||
|
||||
FROM alpine:3.22
|
||||
LABEL org.opencontainers.image.title="Sonda" \
|
||||
|
|
|
|||
20
Makefile
Normal file
20
Makefile
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
# Sonda with its web app inside the binary.
|
||||
#
|
||||
# make build build the web app, then sondad with the app embedded (bin/sondad)
|
||||
# make web only the web app (it is written to internal/webui/dist)
|
||||
# make test the Go tests and the web tests
|
||||
#
|
||||
# A plain `go build ./cmd/sondad` still works: it gives the API only, and / says how to build the app.
|
||||
|
||||
.PHONY: build web test
|
||||
|
||||
build: web
|
||||
CGO_ENABLED=0 go build -tags webui -trimpath -ldflags="-s -w" -o bin/sondad ./cmd/sondad
|
||||
|
||||
web:
|
||||
cd web && npm ci && npm run build
|
||||
|
||||
test:
|
||||
go vet ./...
|
||||
go test ./...
|
||||
cd web && npm test
|
||||
18
README.md
18
README.md
|
|
@ -4,7 +4,7 @@ Sonda is a privacy-first, self-hosted music server written in Go. It streams the
|
|||
|
||||
It is a single executable, one database (SQLite by default, PostgreSQL if you prefer) and the folders that hold your music. There is no Redis, no message broker and no cloud account.
|
||||
|
||||
> **Status: early.** The local-playback part works end to end: accounts, libraries, scanning, search, and streaming with HTTP Range. Suggestions of new artists work too (Discover). Radio queues and OpenSubsonic compatibility are not built yet, and the web client in `web/` is a work in progress (see [What is not there yet](#what-is-not-there-yet) and [Web app](#web-app)). The API may still change.
|
||||
> **Status: early.** The local-playback part works end to end: accounts, libraries, scanning, search, and streaming with HTTP Range. Suggestions of new artists work too (Discover). Radio queues and OpenSubsonic compatibility are not built yet, and the web client in `web/`, which `sondad` serves, is young (see [What is not there yet](#what-is-not-there-yet) and [Web app](#web-app)). The API may still change.
|
||||
|
||||
## What works today
|
||||
|
||||
|
|
@ -27,7 +27,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
|
||||
## What is not there yet
|
||||
|
||||
Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and its admin area covers everything the API can do for an admin: libraries and scanning, users, the external providers and the bulk jobs.
|
||||
Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client is built into the binary (see [Web app](#web-app)), and its admin area covers everything the API can do for an admin: libraries and scanning, users, the external providers and the bulk jobs.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
|
@ -38,12 +38,16 @@ Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz inte
|
|||
## Build
|
||||
|
||||
```bash
|
||||
go build -o bin/sondad ./cmd/sondad
|
||||
make build # the web app (needs Node), then bin/sondad with the app inside
|
||||
```
|
||||
|
||||
`make build` runs `npm ci` and `npm run build` in `web/`, which writes the app to `internal/webui/dist`, and then builds `sondad` with the tag `webui`, which embeds it: one program that serves the app on `/` and the API on `/api`. You can do the same by hand: `(cd web && npm ci && npm run build) && go build -tags webui -o bin/sondad ./cmd/sondad`.
|
||||
|
||||
A plain `go build -o bin/sondad ./cmd/sondad` needs no Node and gives the API only; `/` then shows a page that says how to build the app. `make test` runs the Go tests and the web tests.
|
||||
|
||||
### Docker
|
||||
|
||||
The image holds `sondad` and nothing else (the web client is not in it: `sondad` does not serve it yet). It runs as an ordinary user, keeps the database and the files Sonda makes under `/data`, listens on port 8080 inside the container, and does not start without `SONDA_JWT_SECRET`.
|
||||
The image holds `sondad` with the web app inside, and nothing else: it builds the app itself, so you need no Node on your machine. It runs as an ordinary user, keeps the database and the files Sonda makes under `/data`, listens on port 8080 inside the container, and does not start without `SONDA_JWT_SECRET`.
|
||||
|
||||
```bash
|
||||
docker build -t sonda .
|
||||
|
|
@ -320,7 +324,9 @@ Back up the database and `sonda.toml`. Your music stays wherever you keep it.
|
|||
|
||||
## Web app
|
||||
|
||||
A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. `sondad` does not serve it yet, so for now it runs next to the server:
|
||||
A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. With the app built into the binary (`make build`, or the Docker image) `sondad` serves it: open the address of the server, for example `http://127.0.0.1:8080`, and sign in. The page carries a strict Content-Security-Policy (only resources of the server itself, no inline scripts), cannot be framed and sends no referrer, and a link inside the app (`/admin/users`) works when you reload it.
|
||||
|
||||
To work on the interface itself, run the Vite dev server next to a running `sondad` (set `SONDA_URL` to where it listens: the default is `http://127.0.0.1:8080`):
|
||||
|
||||
```bash
|
||||
cd web
|
||||
|
|
@ -330,7 +336,7 @@ SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api
|
|||
|
||||
What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys, a volume slider with mute (remembered in the browser) and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. The bulk jobs (album covers, artist pictures, artist descriptions) each have a card that says what the job sends and to whom: starting one asks first and says it goes through the whole library, reading everything again is a separate choice, a job whose providers are off cannot be started, and the page follows its progress and can stop it. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings.
|
||||
|
||||
More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). Serving the app from the binary comes later.
|
||||
More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). `npm run build` writes to `internal/webui/dist` (git-ignored), not to `web/dist`.
|
||||
|
||||
## Development
|
||||
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ import (
|
|||
"codeberg.org/squidd/sonda/internal/streaming"
|
||||
"codeberg.org/squidd/sonda/internal/taste"
|
||||
"codeberg.org/squidd/sonda/internal/usersettings"
|
||||
"codeberg.org/squidd/sonda/internal/webui"
|
||||
"codeberg.org/squidd/sonda/migrations"
|
||||
)
|
||||
|
||||
|
|
@ -284,6 +285,7 @@ func run() error {
|
|||
About: descriptions,
|
||||
Settings: userSettings,
|
||||
Streams: streaming.NewService(libraryRepo),
|
||||
Web: webui.FS(),
|
||||
})
|
||||
|
||||
// No WriteTimeout: audio streaming (later) needs long responses.
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ package httpapi
|
|||
|
||||
import (
|
||||
"context"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
|
@ -158,6 +159,9 @@ type Deps struct {
|
|||
ArtistImages artistImageService
|
||||
Settings userSettingsService
|
||||
Streams streamService
|
||||
// Web is the built web app, served on / and for its own links. It is optional: with none (a build
|
||||
// without the app) / shows a page that says how to build it, and the API works the same.
|
||||
Web fs.FS
|
||||
}
|
||||
|
||||
// missingDeps names the services of d that were not set. Every field but the logger is an
|
||||
|
|
@ -167,7 +171,7 @@ func missingDeps(d Deps) []string {
|
|||
v := reflect.ValueOf(d)
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
f := v.Type().Field(i)
|
||||
if f.Name == "Logger" {
|
||||
if f.Name == "Logger" || f.Name == "Web" {
|
||||
continue
|
||||
}
|
||||
if v.Field(i).Kind() == reflect.Interface && v.Field(i).IsNil() {
|
||||
|
|
@ -186,7 +190,7 @@ func NewRouter(d Deps) *gin.Engine {
|
|||
r := gin.New()
|
||||
_ = r.SetTrustedProxies(nil) // use the socket address; no forwarded-header trust yet
|
||||
r.Use(gin.Recovery(), limitBody(maxBodyBytes), requestLog(d.Logger))
|
||||
r.NoRoute(func(c *gin.Context) { writeError(c, http.StatusNotFound, "not_found", "no such route") })
|
||||
r.NoRoute(noRoute(d.Web))
|
||||
|
||||
v1 := r.Group("/api/v1")
|
||||
v1.GET("/health", health)
|
||||
|
|
|
|||
137
internal/api/http/web.go
Normal file
137
internal/api/http/web.go
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
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'"
|
||||
|
||||
// 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)
|
||||
}
|
||||
236
internal/api/http/web_test.go
Normal file
236
internal/api/http/web_test.go
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
const indexHTML = `<!doctype html><title>Sonda app</title><script type="module" src="/assets/app-abc123.js"></script>`
|
||||
|
||||
// theApp is a small built web app: a page, hashed assets, a top-level file, and files that must never be served.
|
||||
func theApp() fstest.MapFS {
|
||||
return fstest.MapFS{
|
||||
"index.html": {Data: []byte(indexHTML)},
|
||||
"favicon.svg": {Data: []byte("<svg xmlns='http://www.w3.org/2000/svg'/>")},
|
||||
"assets/app-abc123.js": {Data: []byte("console.log('app')")},
|
||||
"assets/app-abc123.css": {Data: []byte("body{margin:0}")},
|
||||
"assets/font-1.woff2": {Data: []byte("font")},
|
||||
"assets/.hidden": {Data: []byte("secret")},
|
||||
".gitkeep": {Data: []byte("")},
|
||||
}
|
||||
}
|
||||
|
||||
func serve(t *testing.T, app fstest.MapFS, method, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
h, _ := newTestEnv(t, func(d *Deps) {
|
||||
if app != nil {
|
||||
d.Web = app
|
||||
}
|
||||
})
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestRootServesTheAppWithItsHeaders(t *testing.T) {
|
||||
rec := serve(t, theApp(), http.MethodGet, "/")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d, want 200", rec.Code)
|
||||
}
|
||||
if rec.Body.String() != indexHTML {
|
||||
t.Errorf("body %q is not the page of the app", rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
|
||||
t.Errorf("Content-Type %q, want text/html", ct)
|
||||
}
|
||||
if got := rec.Header().Get("Cache-Control"); got != "no-cache" {
|
||||
t.Errorf("Cache-Control %q: the page must be asked again, so that an update shows at once", got)
|
||||
}
|
||||
for header, want := range map[string]string{
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Frame-Options": "DENY",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
} {
|
||||
if got := rec.Header().Get(header); got != want {
|
||||
t.Errorf("%s = %q, want %q", header, got, want)
|
||||
}
|
||||
}
|
||||
csp := rec.Header().Get("Content-Security-Policy")
|
||||
for _, directive := range []string{
|
||||
"default-src 'self'", "script-src 'self'", "connect-src 'self'", "img-src 'self' data: blob:",
|
||||
"media-src 'self' blob:", "font-src 'self'", "object-src 'none'", "frame-ancestors 'none'",
|
||||
"base-uri 'self'", "form-action 'self'", "style-src 'self'", "style-src-attr 'unsafe-inline'",
|
||||
} {
|
||||
if !strings.Contains(csp, directive) {
|
||||
t.Errorf("the policy %q lacks %q", csp, directive)
|
||||
}
|
||||
}
|
||||
// Nothing in the policy may let the page reach another server.
|
||||
if strings.Contains(csp, "http:") || strings.Contains(csp, "https:") || strings.Contains(csp, "*") {
|
||||
t.Errorf("the policy %q allows resources from outside", csp)
|
||||
}
|
||||
if strings.Contains(csp, "script-src 'self' 'unsafe") || strings.Contains(csp, "'unsafe-eval'") {
|
||||
t.Errorf("the policy %q allows inline or eval scripts", csp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectLinksOfTheAppServeThePage(t *testing.T) {
|
||||
for _, path := range []string{"/admin/users", "/artists/5", "/search?q=bjork", "/settings"} {
|
||||
rec := serve(t, theApp(), http.MethodGet, path)
|
||||
if rec.Code != http.StatusOK || rec.Body.String() != indexHTML {
|
||||
t.Errorf("GET %s: status %d, body %q; want the page of the app", path, rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Header().Get("Content-Security-Policy") == "" {
|
||||
t.Errorf("GET %s: no policy", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssetsAreServedWithTheirTypeAndForever(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"/assets/app-abc123.js": "javascript",
|
||||
"/assets/app-abc123.css": "text/css",
|
||||
"/assets/font-1.woff2": "font/woff2",
|
||||
}
|
||||
for path, wantType := range cases {
|
||||
rec := serve(t, theApp(), http.MethodGet, path)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("GET %s: status %d, want 200", path, rec.Code)
|
||||
continue
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, wantType) {
|
||||
t.Errorf("GET %s: Content-Type %q, want %q", path, ct, wantType)
|
||||
}
|
||||
if got := rec.Header().Get("Cache-Control"); got != "public, max-age=31536000, immutable" {
|
||||
t.Errorf("GET %s: Cache-Control %q: a file with a hash in its name never changes", path, got)
|
||||
}
|
||||
if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
|
||||
t.Errorf("GET %s: no nosniff", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestATopLevelFileIsServedButAskedAgain(t *testing.T) {
|
||||
rec := serve(t, theApp(), http.MethodGet, "/favicon.svg")
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Header().Get("Content-Type"), "svg") {
|
||||
t.Fatalf("status %d, type %q; want the icon", rec.Code, rec.Header().Get("Content-Type"))
|
||||
}
|
||||
if got := rec.Header().Get("Cache-Control"); got != "no-cache" {
|
||||
t.Errorf("Cache-Control %q: a file with no hash in its name may change", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A script that is missing must never come back as the HTML page: the browser would try to run it.
|
||||
func TestAMissingFileIsA404NotThePage(t *testing.T) {
|
||||
for _, path := range []string{"/assets/nope.js", "/assets/", "/assets", "/missing.js", "/some/deep/missing.css", "/robots.txt"} {
|
||||
rec := serve(t, theApp(), http.MethodGet, path)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("GET %s: status %d, want 404", path, rec.Code)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "Sonda app") {
|
||||
t.Errorf("GET %s: answered with the page of the app", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHiddenFilesAreNeverServed(t *testing.T) {
|
||||
for _, path := range []string{"/.gitkeep", "/assets/.hidden", "/.env", "/assets/../.gitkeep"} {
|
||||
rec := serve(t, theApp(), http.MethodGet, path)
|
||||
if rec.Code == http.StatusOK && rec.Body.String() != indexHTML {
|
||||
t.Errorf("GET %s: served %q", path, rec.Body.String())
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "secret") {
|
||||
t.Errorf("GET %s: leaked a hidden file", path)
|
||||
}
|
||||
}
|
||||
if rec := serve(t, theApp(), http.MethodGet, "/assets/.hidden"); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("a hidden file under assets: status %d, want 404", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeadWorksAndSendsNoBody(t *testing.T) {
|
||||
rec := serve(t, theApp(), http.MethodHead, "/")
|
||||
if rec.Code != http.StatusOK || rec.Body.Len() != 0 {
|
||||
t.Errorf("HEAD /: status %d with %d bytes", rec.Code, rec.Body.Len())
|
||||
}
|
||||
if rec := serve(t, theApp(), http.MethodHead, "/assets/app-abc123.js"); rec.Code != http.StatusOK {
|
||||
t.Errorf("HEAD of an asset: status %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOtherMethodsOutsideTheAPIAreAJSON404(t *testing.T) {
|
||||
for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch} {
|
||||
rec := serve(t, theApp(), method, "/admin/users")
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("%s /admin/users: status %d, want 404", method, rec.Code)
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), `"code":"not_found"`) {
|
||||
t.Errorf("%s /admin/users: body %q, want the JSON error", method, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The API keeps answering as it did: an unknown address under /api is a JSON 404, never the page.
|
||||
func TestUnknownAPIAddressesStayJSON404(t *testing.T) {
|
||||
for _, path := range []string{"/api/v1/not-there", "/api/nothing", "/api"} {
|
||||
rec := serve(t, theApp(), http.MethodGet, path)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("GET %s: status %d, want 404", path, rec.Code)
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), `"code":"not_found"`) || strings.Contains(rec.Body.String(), "Sonda app") {
|
||||
t.Errorf("GET %s: body %q, want the JSON error", path, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheAPIAndItsDocsAreNotAffected(t *testing.T) {
|
||||
if rec := serve(t, theApp(), http.MethodGet, "/api/v1/health"); rec.Code != http.StatusOK {
|
||||
t.Errorf("health: status %d", rec.Code)
|
||||
}
|
||||
rec := serve(t, theApp(), http.MethodGet, "/api/docs/")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("docs: status %d", rec.Code)
|
||||
}
|
||||
if strings.Contains(rec.Header().Get("Content-Security-Policy"), "default-src") {
|
||||
t.Errorf("the docs page got the policy of the app: %q", rec.Header().Get("Content-Security-Policy"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathsThatTryToLeaveTheAppDoNotBreakAnything(t *testing.T) {
|
||||
for _, path := range []string{"/..%2f..%2fetc%2fpasswd", "/%2e%2e/%2e%2e/etc/passwd", "/assets/..%2f..%2fgo.mod", "/%00"} {
|
||||
rec := serve(t, theApp(), http.MethodGet, path)
|
||||
if rec.Code >= 500 {
|
||||
t.Errorf("GET %s: status %d", path, rec.Code)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "root:") || strings.Contains(rec.Body.String(), "module codeberg.org") {
|
||||
t.Errorf("GET %s: left the app", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With no app in the binary (a build without the webui tag) / says how to build it, and the API works.
|
||||
func TestWithNoAppTheRootSaysHowToBuildIt(t *testing.T) {
|
||||
for name, app := range map[string]fstest.MapFS{"nil": nil, "empty": {}} {
|
||||
for _, path := range []string{"/", "/admin/users"} {
|
||||
rec := serve(t, app, http.MethodGet, path)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("%s FS, GET %s: status %d, want 200", name, path, rec.Code)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, want := range []string{"make build", "/api/docs/", "/api/v1"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("%s FS, GET %s: the page does not mention %q", name, path, want)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/html") {
|
||||
t.Errorf("%s FS: Content-Type %q", name, rec.Header().Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
if rec := serve(t, app, http.MethodGet, "/api/v1/health"); rec.Code != http.StatusOK {
|
||||
t.Errorf("%s FS: the API does not work, status %d", name, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
23
internal/webui/embed_dist.go
Normal file
23
internal/webui/embed_dist.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
//go:build webui
|
||||
|
||||
// Package webui carries the built web app inside the binary.
|
||||
package webui
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
// dist is what `npm run build` writes in web/: build the app first, then build with -tags webui.
|
||||
//
|
||||
//go:embed all:dist
|
||||
var dist embed.FS
|
||||
|
||||
// FS is the built web app, with index.html at its root.
|
||||
func FS() fs.FS {
|
||||
sub, err := fs.Sub(dist, "dist")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return sub
|
||||
}
|
||||
10
internal/webui/embed_none.go
Normal file
10
internal/webui/embed_none.go
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
//go:build !webui
|
||||
|
||||
// Package webui carries the built web app inside the binary.
|
||||
package webui
|
||||
|
||||
import "io/fs"
|
||||
|
||||
// FS is nil in a build without the app (no webui tag), so that a plain go build and go test
|
||||
// work without building the web app first. The server then shows a page saying how to build it.
|
||||
func FS() fs.FS { return nil }
|
||||
13
internal/webui/webui_test.go
Normal file
13
internal/webui/webui_test.go
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
//go:build !webui
|
||||
|
||||
package webui
|
||||
|
||||
import "testing"
|
||||
|
||||
// A build without the webui tag has no app, and says so with a nil FS, not with an empty one that
|
||||
// looks like an app.
|
||||
func TestWithoutTheTagThereIsNoApp(t *testing.T) {
|
||||
if FS() != nil {
|
||||
t.Error("FS is not nil in a build without the webui tag")
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,12 @@ export default defineConfig({
|
|||
resolve: {
|
||||
alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
|
||||
},
|
||||
// The build goes where the Go server embeds it (build sondad with -tags webui). It is outside the web
|
||||
// folder, so Vite has to be told that it may empty it.
|
||||
build: {
|
||||
outDir: '../internal/webui/dist',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
proxy: { '/api': { target, changeOrigin: false } },
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in a new issue