// backend/main.go package main import ( "embed" "encoding/json" "fmt" "io/fs" "log" "net/http" "os" "path/filepath" "regexp" "strings" "time" "github.com/go-chi/chi/v5" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/tus/tusd/pkg/filestore" tusd "github.com/tus/tusd/pkg/handler" "github.com/tus/tusd/pkg/memorylocker" "scm.bstein.dev/bstein/Pegasus/backend/internal" ) //go:embed web/dist var webFS embed.FS var ( mediaRoot = env("PEGASUS_MEDIA_ROOT", "/media") userMapFile = env("PEGASUS_USER_MAP_FILE", "/config/user-map.yaml") tusDir = env("PEGASUS_TUS_DIR", filepath.Join(mediaRoot, ".pegasus-tus")) jf = internal.NewJellyfin() ) var ( version = "dev" // set via -ldflags "-X main.version=1.2.0 -X main.git=$(git rev-parse --short HEAD) -X main.builtAt=$(date -u +%Y-%m-%dT%H:%M:%SZ)" git = "" builtAt = "" ) type loggingRW struct { http.ResponseWriter status int } func (l *loggingRW) WriteHeader(code int) { l.status = code; l.ResponseWriter.WriteHeader(code) } func main() { internal.Logf("PEGASUS_DEBUG=%v, DRY_RUN=%v, TUS_DIR=%s, MEDIA_ROOT=%s", internal.Debug, internal.DryRun, tusDir, mediaRoot) if os.Getenv("PEGASUS_SESSION_KEY") == "" { log.Fatal("PEGASUS_SESSION_KEY is not set") } um, err := internal.LoadUserMap(userMapFile) must(err, "load user map") // === tusd setup (resumable uploads) === store := filestore.FileStore{Path: tusDir} // ensure upload scratch dir exists if err := os.MkdirAll(tusDir, 0o755); err != nil { log.Fatalf("mkdir %s: %v", tusDir, err) } locker := memorylocker.New() composer := tusd.NewStoreComposer() store.UseIn(composer) locker.UseIn(composer) // completeC := make(chan tusd.HookEvent) config := tusd.Config{ BasePath: "/tus/", StoreComposer: composer, NotifyCompleteUploads: true, // CompleteUploads: completeC, MaxSize: 4 * 1024 * 1024 * 1024, // 4GB per file } tusHandler, err := tusd.NewUnroutedHandler(config) must(err, "init tus handler") completeC := tusHandler.CompleteUploads // ---- post-finish hook: enforce naming & mapping ---- go func() { for ev := range completeC { claims, err := claimsFromHook(ev) if err != nil { internal.Logf("tus: no session: %v", err) continue } // read metadata set by the UI meta := ev.Upload.MetaData desc := strings.TrimSpace(meta["desc"]) if desc == "" { internal.Logf("tus: missing desc; rejecting") continue } date := strings.TrimSpace(meta["date"]) // YYYY-MM-DD or empty subdir := strings.Trim(strings.TrimSpace(meta["subdir"]), "/") orig := meta["filename"] if orig == "" { orig = "upload.bin" } // resolve per-user root userRootRel, err := um.Resolve(claims.Username) if err != nil { internal.Logf("tus: user map missing: %v", err) continue } // compose final name & target finalName, err := internal.ComposeFinalName(date, desc, orig) if err != nil { internal.Logf("tus: bad target name: %v", err) continue } rootAbs, _ := internal.SafeJoin(mediaRoot, userRootRel) var targetAbs string if subdir == "" { targetAbs, err = internal.SafeJoin(rootAbs, finalName) } else { targetAbs, err = internal.SafeJoin(rootAbs, filepath.Join(subdir, finalName)) } if err != nil { internal.Logf("tus: path escape prevented: %v", err) continue } srcPath := ev.Upload.Storage["Path"] _ = os.MkdirAll(filepath.Dir(targetAbs), 0o755) if internal.DryRun { internal.Logf("[DRY] move %s -> %s", srcPath, targetAbs) } else if err := os.Rename(srcPath, targetAbs); err != nil { internal.Logf("move failed: %v", err) continue } internal.Logf("uploaded: %s", targetAbs) // kick Jellyfin refresh jf.RefreshLibrary(claims.JFToken) } }() // === chi router === r := chi.NewRouter() r.Use(corsForTus) // health/version r.Get("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("ok")) }) r.Get("/version", func(w http.ResponseWriter, _ *http.Request) { _ = json.NewEncoder(w).Encode(map[string]any{ "version": version, "git": git, "built_at": builtAt, }) }) // auth r.Post("/api/login", func(w http.ResponseWriter, r *http.Request) { var f struct { Username string `json:"username"` Password string `json:"password"` } if err := json.NewDecoder(r.Body).Decode(&f); err != nil { http.Error(w, "bad json", http.StatusBadRequest) return } res, err := jf.AuthenticateByName(f.Username, f.Password) if err != nil { http.Error(w, "invalid credentials", http.StatusUnauthorized) return } if err := internal.SetSession(w, res.User.Username, res.AccessToken); err != nil { http.Error(w, "session error", http.StatusInternalServerError) return } _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) }) r.Post("/api/logout", func(w http.ResponseWriter, _ *http.Request) { internal.ClearSession(w) _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) }) // whoami r.Get("/api/whoami", func(w http.ResponseWriter, r *http.Request) { cl, err := internal.CurrentUser(r) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } dr, err := um.Resolve(cl.Username) if err != nil { http.Error(w, "no mapping", http.StatusForbidden) return } _ = json.NewEncoder(w).Encode(map[string]any{"username": cl.Username, "root": dr}) }) // list entries r.Get("/api/list", func(w http.ResponseWriter, r *http.Request) { cl, err := internal.CurrentUser(r) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } rootRel, err := um.Resolve(cl.Username) if err != nil { http.Error(w, "forbidden", http.StatusForbidden) return } q := strings.TrimPrefix(r.URL.Query().Get("path"), "/") rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel) var dirAbs string if q == "" { dirAbs = rootAbs } else { dirAbs, err = internal.SafeJoin(rootAbs, q) if err != nil { http.Error(w, "forbidden", http.StatusForbidden) return } } ents, err := os.ReadDir(dirAbs) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } type entry struct { Name string Path string IsDir bool Size int64 Mtime int64 } var out []entry for _, d := range ents { info, _ := d.Info() out = append(out, entry{ Name: d.Name(), Path: filepath.Join(q, d.Name()), IsDir: d.IsDir(), Size: func() int64 { if info != nil && !d.IsDir() { return info.Size() } return 0 }(), Mtime: func() int64 { if info != nil { return info.ModTime().Unix() } return 0 }(), }) } _ = json.NewEncoder(w).Encode(out) }) // rename var finalNameRe = regexp.MustCompile(`^\d{4}\.\d{2}\.\d{2}\.[A-Za-z0-9_-]{1,64}\.[A-Za-z0-9]{1,8}$`) r.Post("/api/rename", func(w http.ResponseWriter, r *http.Request) { cl, err := internal.CurrentUser(r) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } var p struct { From string `json:"from"` To string `json:"to"` } if err := json.NewDecoder(r.Body).Decode(&p); err != nil { http.Error(w, "bad json", http.StatusBadRequest) return } // enforce final name on files (allow any name for directories) if filepath.Ext(p.To) != "" && !finalNameRe.MatchString(filepath.Base(p.To)) { http.Error(w, "new name must match YYYY.MM.DD.Description.ext", http.StatusBadRequest) return } rootRel, _ := um.Resolve(cl.Username) rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel) fromAbs, err := internal.SafeJoin(rootAbs, p.From) if err != nil { http.Error(w, "forbidden", http.StatusForbidden) return } toAbs, err := internal.SafeJoin(rootAbs, p.To) if err != nil { http.Error(w, "forbidden", http.StatusForbidden) return } _ = os.MkdirAll(filepath.Dir(toAbs), 0o755) if internal.DryRun { internal.Logf("[DRY] mv %s -> %s", fromAbs, toAbs) } else if err := os.Rename(fromAbs, toAbs); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } jf.RefreshLibrary(cl.JFToken) _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) }) // delete r.Delete("/api/file", func(w http.ResponseWriter, r *http.Request) { cl, err := internal.CurrentUser(r) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } rootRel, _ := um.Resolve(cl.Username) path := r.URL.Query().Get("path") rec := r.URL.Query().Get("recursive") == "true" rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel) abs, err := internal.SafeJoin(rootAbs, path) if err != nil { http.Error(w, "forbidden", http.StatusForbidden) return } if rec { err = os.RemoveAll(abs) } else { err = os.Remove(abs) } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } jf.RefreshLibrary(cl.JFToken) _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) }) // mkdir (create subdirectory under the user's mapped root) r.Post("/api/mkdir", func(w http.ResponseWriter, r *http.Request) { cl, err := internal.CurrentUser(r) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized); return } var p struct{ Path string `json:"path"` } // e.g., "Trips/2025-09" if err := json.NewDecoder(r.Body).Decode(&p); err != nil { http.Error(w, "bad json", http.StatusBadRequest); return } rootRel, err := um.Resolve(cl.Username) if err != nil { http.Error(w, "forbidden", http.StatusForbidden); return } rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel) abs, err := internal.SafeJoin(rootAbs, strings.TrimPrefix(p.Path, "/")) if err != nil { http.Error(w, "forbidden", http.StatusForbidden); return } if internal.DryRun { internal.Logf("[DRY] mkdir -p %s", abs) } else if err := os.MkdirAll(abs, 0o755); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError); return } _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) }) // mount tus (behind auth) r.Route("/tus", func(rt chi.Router) { rt.Use(sessionRequired) // Create upload: POST /tus/ rt.Post("/", tusHandler.PostFile) // Upload resource endpoints: /tus/{id} rt.Head("/{id}", tusHandler.HeadFile) rt.Patch("/{id}", tusHandler.PatchFile) rt.Delete("/{id}", tusHandler.DelFile) rt.Get("/{id}", tusHandler.GetFile) // optional }) // metrics r.Handle("/metrics", promhttp.Handler()) // static app (serve embedded web/dist) appFS, _ := fs.Sub(webFS, "web/dist") static := http.FileServer(http.FS(appFS)) r.Get("/", func(w http.ResponseWriter, r *http.Request) { static.ServeHTTP(w, r) }) // catch-all for SPA routes, GET only r.Method("GET", "/*", http.StripPrefix("/", static)) // debug endpoints (registered before server starts) r.Get("/debug/env", func(w http.ResponseWriter, r *http.Request) { if !internal.Debug { http.Error(w, "disabled", http.StatusForbidden) return } _ = json.NewEncoder(w).Encode(map[string]any{ "mediaRoot": mediaRoot, "tusDir": tusDir, "userMapFile": userMapFile, }) }) r.Get("/debug/write-test", func(w http.ResponseWriter, r *http.Request) { if !internal.Debug { http.Error(w, "disabled", http.StatusForbidden) return } cl, err := internal.CurrentUser(r) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } rootRel, err := um.Resolve(cl.Username) if err != nil { http.Error(w, "forbidden", http.StatusForbidden) return } rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel) test := filepath.Join(rootAbs, fmt.Sprintf("TEST.%d.txt", time.Now().Unix())) if internal.DryRun { internal.Logf("[DRY] write %s", test) } else { _ = os.WriteFile(test, []byte("ok\n"), 0o644) } _ = json.NewEncoder(w).Encode(map[string]string{"wrote": test}) }) r.NotFound(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "no route for "+r.Method+" "+r.URL.Path, http.StatusNotFound) }) // ---- wrap router with verbose request logging in debug ---- root := http.Handler(r) if internal.Debug { root = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { id := time.Now().UnixNano() internal.Logf(">> %d %s %s %v", id, req.Method, req.URL.Path, internal.RedactHeaders(req.Header)) rw := &loggingRW{ResponseWriter: w, status: 200} start := time.Now() r.ServeHTTP(rw, req) internal.Logf("<< %d %s %s %d %s", id, req.Method, req.URL.Path, rw.status, time.Since(start)) }) } addr := env("PEGASUS_BIND", ":8080") log.Printf("Pegasus listening on %s", addr) srv := &http.Server{Addr: addr, Handler: root, ReadTimeout: 0, WriteTimeout: 0} log.Fatal(srv.ListenAndServe()) } // === helpers & middleware === func sessionRequired(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if _, err := internal.CurrentUser(r); err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } func corsForTus(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // CORS for tus (preflight must succeed; cookies allowed) if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", origin) // cannot be * when credentials=true w.Header().Set("Vary", "Origin") } w.Header().Set("Access-Control-Allow-Credentials", "true") w.Header().Set("Access-Control-Allow-Methods", "GET,POST,HEAD,PATCH,DELETE,OPTIONS") w.Header().Set("Access-Control-Max-Age", "86400") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Tus-Resumable, Upload-Length, Upload-Defer-Length, Upload-Metadata, Upload-Offset, Upload-Concat, Upload-Checksum, X-Requested-With") w.Header().Set("Access-Control-Expose-Headers", "Location, Upload-Offset, Upload-Length, Tus-Resumable, Upload-Checksum") if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) return } next.ServeHTTP(w, r) }) } func claimsFromHook(ev tusd.HookEvent) (internal.Claims, error) { // Parse our session cookie from incoming request headers captured by tusd req := ev.HTTPRequest if req.Header == nil { return internal.Claims{}, http.ErrNoCookie } // Re-create a dummy http.Request to reuse cookie parsing & jwt verification r := http.Request{Header: http.Header(req.Header)} return internal.CurrentUser(&r) } func env(k, def string) string { if v := os.Getenv(k); v != "" { return v }; return def } func must(err error, msg string) { if err != nil { log.Fatalf("%s: %v", msg, err) } }