Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 18 additions & 13 deletions src/web/backend/middleware.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package backend

import (
"fmt"
"net/http"
"strings"
"sync"
"time"
"fmt"
)

type sessionResponseWriter struct {
Expand All @@ -28,7 +29,7 @@ func (w *sessionResponseWriter) Write(b []byte) (int, error) {
func (w *sessionResponseWriter) WriteHeader(code int) {
// write essential headers
w.Header().Add("Vary", "Cookie")
w.Header().Add("Cache-Control", `no-cache="Set-Cookie"`)
w.Header().Add("Cache-Control", `no-cache="Set-Cookie"`)

writeCookieIfNecessary(w)

Expand Down Expand Up @@ -60,10 +61,10 @@ func (s *InMemorySessionStore) read(id string) (*Session, error) {

session, ok := s.sessions[id]
if !ok {
return nil, fmt.Errorf("session not found")
return nil, fmt.Errorf("session not found")
}
return session, nil

return session, nil
}

func (s *InMemorySessionStore) write(session *Session) error {
Expand Down Expand Up @@ -96,7 +97,6 @@ func (s *InMemorySessionStore) gc(absoluteExpiration time.Duration) error {

return nil
}

func (m *SessionManager) Handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Start the session
Expand All @@ -111,17 +111,16 @@ func (m *SessionManager) Handle(next http.Handler) http.Handler {

isMutating :=
r.Method == http.MethodPost ||
r.Method == http.MethodPut ||
r.Method == http.MethodPatch ||
r.Method == http.MethodDelete
r.Method == http.MethodPut ||
r.Method == http.MethodPatch ||
r.Method == http.MethodDelete

if isMutating && r.URL.Path != "/login" {
if isMutating && rws.URL.Path != "/api/ui/login" {
if !m.verifyCSRFToken(rws, session) {
http.Error(sw, "CSRF token mismatch", http.StatusForbidden)
return
}
}


// Call the next handler and pass the new response writer and new request
next.ServeHTTP(sw, rws)
Expand All @@ -141,6 +140,10 @@ func writeCookieIfNecessary(w *sessionResponseWriter) {
panic("session not found in request context")
}

if w.request.TLS != nil || strings.EqualFold(w.request.Header.Get("X-Forwarded-Proto"), "https") {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
}

cookie := &http.Cookie{
Name: w.sessionManager.cookieName,
Value: session.id,
Expand All @@ -150,8 +153,10 @@ func writeCookieIfNecessary(w *sessionResponseWriter) {
Expires: time.Now().Add(w.sessionManager.absoluteExpiration),
MaxAge: int(w.sessionManager.absoluteExpiration / time.Second),
}

if w.request.TLS != nil || strings.EqualFold(w.request.Header.Get("X-Forwarded-Proto"), "https") {
cookie.Secure = true
}
http.SetCookie(w.ResponseWriter, cookie)

w.done = true
}
}
131 changes: 87 additions & 44 deletions src/web/backend/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ func newManualRunState() manualRunState {
}

type Server struct {
cfg config.ServerConfig
cfg config.ServerConfig
mux *http.ServeMux
server *http.Server
authStore *AuthStore
cronJobs *Jobs
cronJobs *Jobs
sessionManager *SessionManager
manualRun manualRunState
}
Expand All @@ -87,25 +87,25 @@ func NewServer(cfg config.ServerConfig) *Server {
)

authStore := NewAuthStore(
cfg.Username,
cfg.Password,
sessionManager,
)
cfg.Username,
cfg.Password,
sessionManager,
)

cronJobs := NewJobs()

mux := http.NewServeMux()
s := &Server{
cfg: cfg,
mux: mux,
mux: mux,
server: &http.Server{
Addr: cfg.Port,
Handler: sessionManager.Handle(mux),
},
authStore: authStore,
cronJobs: cronJobs,
authStore: authStore,
cronJobs: cronJobs,
sessionManager: sessionManager,
manualRun: newManualRunState(),
manualRun: newManualRunState(),
}

s.registerRoutes()
Expand Down Expand Up @@ -144,8 +144,13 @@ func checkForUpdate() {
c := parseVer(config.Version)
newer := false
for i := range 3 {
if l[i] > c[i] { newer = true; break }
if l[i] < c[i] { break }
if l[i] > c[i] {
newer = true
break
}
if l[i] < c[i] {
break
}
}
if newer {
slog.Info("new version available!", "latest", release.TagName, "current", config.Version)
Expand Down Expand Up @@ -181,7 +186,7 @@ func (s *Server) startJobs() {
s.cronJobs.Start()
}

func(s *Server) PrefetchCovers() {
func (s *Server) PrefetchCovers() {

coversDir := filepath.Join(s.cfg.WebDataDir, "cache", "covers")

Expand Down Expand Up @@ -223,32 +228,70 @@ func (s *Server) registerRoutes() {
slog.Error("failed writing to http", "msg", err.Error())
}
})
s.mux.Handle("GET /api/ui/config", s.authStore.RequireAuth(http.HandlerFunc(s.handleGetConfig)))
s.mux.Handle("GET /api/ui/config/raw", s.authStore.RequireAuth(http.HandlerFunc(s.handleGetConfigRaw)))
s.mux.Handle("POST /api/ui/config", s.authStore.RequireAuth(http.HandlerFunc(s.handleSaveConfig)))
s.mux.Handle("POST /api/ui/config/reset", s.authStore.RequireAuth(http.HandlerFunc(s.handleResetConfig)))
s.mux.Handle("POST /api/ui/config/schedules", s.authStore.RequireAuth(http.HandlerFunc(s.handleSaveSchedule)))
s.mux.Handle("POST /api/ui/wizard/step1", s.authStore.RequireAuth(http.HandlerFunc(s.handleWizardStep1)))
s.mux.Handle("POST /api/ui/wizard/step2", s.authStore.RequireAuth(http.HandlerFunc(s.handleWizardStep2)))
s.mux.Handle("POST /api/ui/wizard/step3", s.authStore.RequireAuth(http.HandlerFunc(s.handleWizardStep3)))
s.mux.Handle("GET /api/ui/browse", s.authStore.RequireAuth(http.HandlerFunc(s.handleBrowse)))
s.mux.Handle("POST /api/ui/run", s.authStore.RequireAuth(http.HandlerFunc(s.handleRun)))
s.mux.Handle("GET /api/ui/run/events", s.authStore.RequireAuth(http.HandlerFunc(s.handleRunEvents)))
s.mux.Handle("POST /api/ui/run/stop", s.authStore.RequireAuth(http.HandlerFunc(s.handleStopRun)))
s.mux.Handle("GET /api/ui/run/status", s.authStore.RequireAuth(http.HandlerFunc(s.handleRunStatus)))
s.mux.Handle("GET /api/ui/logs", s.authStore.RequireAuth(http.HandlerFunc(s.handleGetLog)))
s.mux.Handle("GET /api/ui/playlists", s.authStore.RequireAuth(http.HandlerFunc(s.handleGetPlaylist)))
s.mux.Handle("POST /api/ui/playlists/prefetch", s.authStore.RequireAuth(http.HandlerFunc(s.handlePrefetchCovers)))
s.mux.Handle("GET /api/ui/custom-playlists", s.authStore.RequireAuth(http.HandlerFunc(s.handleGetCustomPlaylists)))
s.mux.Handle("POST /api/ui/custom-playlists", s.authStore.RequireAuth(http.HandlerFunc(s.handleImportCustomPlaylist)))
s.mux.Handle("DELETE /api/ui/custom-playlists/{id}", s.authStore.RequireAuth(http.HandlerFunc(s.handleDeleteCustomPlaylist)))
s.mux.Handle("POST /api/ui/custom-playlists/{id}/refresh", s.authStore.RequireAuth(http.HandlerFunc(s.handleRefreshCustomPlaylist)))
s.mux.Handle("POST /api/ui/logout", s.authStore.RequireAuth(http.HandlerFunc(s.handleLogout)))
s.mux.HandleFunc("GET /api/ui/csrf", s.csrfHandler)
s.mux.HandleFunc("POST /api/ui/login", s.handleLogin)
s.mux.HandleFunc("GET /api/ui/auth/status", s.handleAuthStatus)
s.mux.HandleFunc("GET /api/ui/background-art", s.handleBackgroundArt)
s.mux.HandleFunc("GET /api/ui/setup-status", s.handleSetupStatus)

// /api/ui/config — GET = read, POST = save (both require auth)
s.mux.HandleFunc("/api/ui/config", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
s.authStore.RequireAuth(http.HandlerFunc(s.handleGetConfig)).ServeHTTP(w, r)
case http.MethodPost:
s.authStore.RequireAuth(http.HandlerFunc(s.handleSaveConfig)).ServeHTTP(w, r)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})
s.mux.Handle("/api/ui/config/raw", s.authStore.RequireAuth(http.HandlerFunc(s.handleGetConfigRaw)))
s.mux.Handle("/api/ui/config/reset", s.authStore.RequireAuth(http.HandlerFunc(s.handleResetConfig)))
s.mux.Handle("/api/ui/config/schedules", s.authStore.RequireAuth(http.HandlerFunc(s.handleSaveSchedule)))

// Wizard steps (POST) — require auth
s.mux.Handle("/api/ui/wizard/step1", s.authStore.RequireAuth(http.HandlerFunc(s.handleWizardStep1)))
s.mux.Handle("/api/ui/wizard/step2", s.authStore.RequireAuth(http.HandlerFunc(s.handleWizardStep2)))
s.mux.Handle("/api/ui/wizard/step3", s.authStore.RequireAuth(http.HandlerFunc(s.handleWizardStep3)))

s.mux.Handle("/api/ui/browse", s.authStore.RequireAuth(http.HandlerFunc(s.handleBrowse)))
s.mux.Handle("/api/ui/run", s.authStore.RequireAuth(http.HandlerFunc(s.handleRun)))
s.mux.Handle("/api/ui/run/events", s.authStore.RequireAuth(http.HandlerFunc(s.handleRunEvents)))
s.mux.Handle("/api/ui/run/stop", s.authStore.RequireAuth(http.HandlerFunc(s.handleStopRun)))
s.mux.Handle("/api/ui/run/status", s.authStore.RequireAuth(http.HandlerFunc(s.handleRunStatus)))

s.mux.Handle("/api/ui/logs", s.authStore.RequireAuth(http.HandlerFunc(s.handleGetLog)))
s.mux.Handle("/api/ui/playlists", s.authStore.RequireAuth(http.HandlerFunc(s.handleGetPlaylist)))
s.mux.Handle("/api/ui/playlists/prefetch", s.authStore.RequireAuth(http.HandlerFunc(s.handlePrefetchCovers)))

// TODO: Uncomment when jeffs branch is in
// custom playlists: GET list, POST import (same path); per-ID actions under prefix
s.mux.HandleFunc("/api/ui/custom-playlists", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
s.authStore.RequireAuth(http.HandlerFunc(s.handleGetCustomPlaylists)).ServeHTTP(w, r)
case http.MethodPost:
s.authStore.RequireAuth(http.HandlerFunc(s.handleImportCustomPlaylist)).ServeHTTP(w, r)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})
// ID-specific routes: DELETE /api/ui/custom-playlists/{id} and POST .../{id}/refresh
s.mux.HandleFunc("/api/ui/custom-playlists/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
s.authStore.RequireAuth(http.HandlerFunc(s.handleDeleteCustomPlaylist)).ServeHTTP(w, r)
return
}
if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/refresh") {
s.authStore.RequireAuth(http.HandlerFunc(s.handleRefreshCustomPlaylist)).ServeHTTP(w, r)
return
}
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
})

s.mux.Handle("/api/ui/logout", s.authStore.RequireAuth(http.HandlerFunc(s.handleLogout)))

// public/special routes
s.mux.HandleFunc("/api/ui/csrf", s.csrfHandler)
s.mux.HandleFunc("/api/ui/login", s.handleLogin)
s.mux.HandleFunc("/api/ui/auth/status", s.handleAuthStatus)
s.mux.HandleFunc("/api/ui/background-art", s.handleBackgroundArt)
s.mux.HandleFunc("/api/ui/setup-status", s.handleSetupStatus)

coversDir := filepath.Join(s.cfg.WebDataDir, "cache", "covers")
s.mux.Handle("/api/covers/", http.StripPrefix("/api/covers/", http.FileServer(http.Dir(coversDir))))
Expand Down Expand Up @@ -385,7 +428,7 @@ func parseEnvText(text string) map[string]string {
if len(v) >= 2 {
if (v[0] == '\'' && v[len(v)-1] == '\'') ||
(v[0] == '"' && v[len(v)-1] == '"') {
v = v[1 : len(v)-1]
v = v[1 : len(v)-1]
}
}
out[k] = v
Expand Down Expand Up @@ -559,7 +602,7 @@ func updateEnvKeys(path string, updates map[string]string, fallback []byte) erro
// Append any keys that weren't already in the file
for k, v := range updates {
if !touched[k] && v != "" {
lines = append(lines, k + "=" + formatEnvValue(v))
lines = append(lines, k+"="+formatEnvValue(v))
}
}

Expand Down Expand Up @@ -695,7 +738,7 @@ func (s *Server) handleWizardStep3(w http.ResponseWriter, r *http.Request) {
FilterList string `json:"filter_list"`
SlskdURL string `json:"slskd_url"`
SlskdAPIKey string `json:"slskd_api_key"`
Extensions string `json:"extensions"` // slskd
Extensions string `json:"extensions"` // slskd
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
Expand Down Expand Up @@ -725,8 +768,8 @@ func (s *Server) handleWizardStep3(w http.ResponseWriter, r *http.Request) {
"FILTER_LIST": body.FilterList,
"SLSKD_URL": body.SlskdURL,
"SLSKD_API_KEY": body.SlskdAPIKey,
"EXTENSIONS": body.Extensions, // slskd
"WIZARD_COMPLETE": "true",
"EXTENSIONS": body.Extensions, // slskd
"WIZARD_COMPLETE": "true",
}

if err := updateEnvKeys(s.cfg.WebEnvPath, updates, web.SampleEnv); err != nil {
Expand Down
Loading