// Package web serves Basking's dashboard and its JSON API. package web import ( "crypto/sha256" "embed" "encoding/hex" "encoding/json" "errors" "fmt" "io/fs" "net/http" "os" "path/filepath" "strings" "sync" "git.veillax.com/Veillax/basking/internal/config" "git.veillax.com/Veillax/basking/internal/oidc" "git.veillax.com/Veillax/basking/internal/store" ) //go:embed static var staticFiles embed.FS const maxRequestBody = store.MaxBody + 4096 type Server struct { cfg *config.Holder oidc *oidc.Client version string mu sync.Mutex books map[string]*store.Store } // principal is who is making a request, with the notebook that is theirs alone. type principal struct { Sub, Name, Email string st *store.Store } // New checks that Authentik is set up and returns the server. func New(h *config.Holder, version string) (*Server, error) { c := h.Get() if err := c.Check(); err != nil { return nil, err } return &Server{cfg: h, version: version, books: map[string]*store.Store{}, oidc: oidc.New(c.OIDC.Issuer, c.OIDC.ClientID, c.OIDC.ClientSecret, c.RedirectURL())}, nil } // OIDC is the sign-in client, for the check command. func (s *Server) OIDC() *oidc.Client { return s.oidc } // notebook opens the notes that belong to one person. Their folder is named from a hash of who they // are, so nothing a person controls ever becomes part of a path. func (s *Server) notebook(c config.Config, sub, name, email string) (*store.Store, error) { sum := sha256.Sum256([]byte(c.OIDC.Issuer + "|" + sub)) key := hex.EncodeToString(sum[:16]) s.mu.Lock() defer s.mu.Unlock() if st, ok := s.books[key]; ok { return st, nil } dir := filepath.Join(c.DataDir, "users", key) st, err := store.Open(dir) if err != nil { return nil, err } // A note for whoever looks after the server, so a folder can be matched to a person. who := fmt.Sprintf("%s <%s>\n", name, email) if b, _ := os.ReadFile(filepath.Join(dir, "owner.txt")); string(b) != who { os.WriteFile(filepath.Join(dir, "owner.txt"), []byte(who), 0o644) } s.books[key] = st return st, nil } // Handler returns the whole site. func (s *Server) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "ok") }) mux.HandleFunc("GET /auth/login", s.authLogin) mux.HandleFunc("GET /auth/callback", s.authCallback) mux.HandleFunc("POST /api/logout", s.api(s.logout)) mux.HandleFunc("GET /api/me", s.api(s.me)) mux.HandleFunc("GET /api/pages", s.api(s.pages)) mux.HandleFunc("GET /api/notes", s.api(s.listNotes)) mux.HandleFunc("POST /api/notes", s.api(s.createNote)) mux.HandleFunc("GET /api/notes/{id}", s.api(s.getNote)) mux.HandleFunc("PUT /api/notes/{id}", s.api(s.updateNote)) mux.HandleFunc("DELETE /api/notes/{id}", s.api(s.deleteNote)) mux.HandleFunc("POST /api/notes/{id}/restore", s.api(s.restoreNote)) mux.HandleFunc("DELETE /api/trash", s.api(s.emptyTrash)) mux.HandleFunc("POST /api/daily", s.api(s.daily)) mux.HandleFunc("GET /api/find", s.api(s.find)) mux.HandleFunc("GET /api/export", s.api(s.export)) static, _ := fs.Sub(staticFiles, "static") mux.Handle("GET /", http.FileServerFS(static)) return s.secure(mux) } // secure adds headers that keep the page from being framed, sniffed or fed outside scripts. func (s *Server) secure(next http.Handler) http.Handler { hsts := s.cfg.Get().Secure() return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() h.Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'") h.Set("X-Content-Type-Options", "nosniff") h.Set("X-Frame-Options", "DENY") h.Set("Referrer-Policy", "no-referrer") h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") if hsts { h.Set("Strict-Transport-Security", "max-age=31536000") } if strings.HasPrefix(r.URL.Path, "/api/") || strings.HasPrefix(r.URL.Path, "/auth/") { h.Set("Cache-Control", "no-store") } next.ServeHTTP(w, r) }) } type handlerFunc func(w http.ResponseWriter, r *http.Request, p principal) // api wraps a handler with sign-in and CSRF protection. func (s *Server) api(fn handlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { c := s.cfg.Get() ses, ok := s.session(c, r) if !ok { fail(w, http.StatusUnauthorized, "sign in required") return } // A browser must send a header a web page on another site cannot add. if r.Method != http.MethodGet && r.Header.Get("X-Basking") != "1" { fail(w, http.StatusForbidden, "missing X-Basking header") return } st, err := s.notebook(c, ses.Sub, ses.Name, ses.Email) if err != nil { fail(w, http.StatusInternalServerError, "could not open your notes: "+err.Error()) return } r.Body = http.MaxBytesReader(w, r.Body, maxRequestBody) fn(w, r, principal{Sub: ses.Sub, Name: ses.Name, Email: ses.Email, st: st}) } } // ---- helpers ---- func writeJSON(w http.ResponseWriter, v any) { writeJSONStatus(w, http.StatusOK, v) } func writeJSONStatus(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) json.NewEncoder(w).Encode(v) } // fail answers with an error. Messages are capitalized here, once, so they read as sentences. func fail(w http.ResponseWriter, code int, msg string) { failCode(w, code, msg, "") } func failCode(w http.ResponseWriter, code int, msg, kind string) { if r := []rune(msg); len(r) > 0 { msg = strings.ToUpper(string(r[:1])) + string(r[1:]) } writeJSONStatus(w, code, map[string]string{"error": msg, "code": kind}) } func decode(w http.ResponseWriter, r *http.Request, v any) bool { if err := json.NewDecoder(r.Body).Decode(v); err != nil { var mbe *http.MaxBytesError if errors.As(err, &mbe) { fail(w, http.StatusRequestEntityTooLarge, "request too large") } else { fail(w, http.StatusBadRequest, "bad request: "+err.Error()) } return false } return true } // storeFail turns a store error into the right status. func storeFail(w http.ResponseWriter, err error) { switch { case errors.Is(err, store.ErrNotFound): fail(w, http.StatusNotFound, err.Error()) case errors.Is(err, store.ErrConflict): fail(w, http.StatusConflict, err.Error()) case errors.Is(err, store.ErrTitleTaken): failCode(w, http.StatusUnprocessableEntity, err.Error(), "title_taken") case errors.Is(err, store.ErrEmpty), errors.Is(err, store.ErrBadDate), errors.Is(err, store.ErrNotTrash), errors.Is(err, store.ErrBadID), errors.Is(err, store.ErrDailyTitle), errors.Is(err, store.ErrBadParent): fail(w, http.StatusBadRequest, err.Error()) case errors.Is(err, store.ErrTooLong): fail(w, http.StatusRequestEntityTooLarge, err.Error()) default: fail(w, http.StatusInternalServerError, "could not save: "+err.Error()) } }