Files
Mako/internal/web/server.go
T
VeillaxandClaude Sonnet 5.5 994927c704
CI / test (push) Successful in 2m12s
Release / release (push) Successful in 3m42s
Move pages to and from the vault
A page, including a journal day, can be moved into the unlocked vault with its id kept. Links to it elsewhere become [[locked:id]], shown as Locked Page until the vault is unlocked, so its title is kept only in the vault. Move out reverses it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 01:58:29 -07:00

239 lines
8.4 KiB
Go

// Package web serves Mako's dashboard and its JSON API.
package web
import (
"crypto/sha256"
"embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"git.veillax.com/Veillax/mako/internal/config"
"git.veillax.com/Veillax/mako/internal/oidc"
"git.veillax.com/Veillax/mako/internal/store"
"git.veillax.com/Veillax/mako/internal/vault"
)
//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
vmu sync.Mutex
vstate map[string]*vaultState // unlocked vaults, by the folder name of their owner
vtoken map[string]string // vault cookie value to that folder name
vfails map[string][]time.Time // recent wrong passphrases, by the same name
}
// 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{},
vstate: map[string]*vaultState{}, vtoken: map[string]string{}, vfails: map[string][]time.Time{},
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 }
// userKey names a person's folder, from a hash of who they are.
func userKey(c config.Config, sub string) string {
sum := sha256.Sum256([]byte(c.OIDC.Issuer + "|" + sub))
return hex.EncodeToString(sum[:16])
}
// 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) {
key := userKey(c, sub)
s.mu.Lock()
defer s.mu.Unlock()
if st, ok := s.books[key]; ok {
return st, nil
}
box, err := vault.New(c.Key, c.OIDC.Issuer, sub)
if err != nil {
return nil, err
}
dir := filepath.Join(c.DataDir, "users", key)
st, err := store.Open(dir, box)
if err != nil {
log.Printf("could not open the notebook of %s <%s>: %v", name, email, err)
return nil, err
}
// Earlier versions left a plain note here naming the owner, which does not belong next to
// encrypted pages.
os.Remove(filepath.Join(dir, "owner.txt"))
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("POST /api/notes/{id}/vault", s.api(s.moveToVault))
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))
mux.HandleFunc("GET /api/vault", s.api(s.vaultInfo))
mux.HandleFunc("POST /api/vault", s.api(s.vaultCreate))
mux.HandleFunc("POST /api/vault/unlock", s.api(s.vaultUnlock))
mux.HandleFunc("POST /api/vault/lock", s.api(s.vaultLock))
mux.HandleFunc("GET /api/vault/pages", s.vaultAPI(s.pages))
mux.HandleFunc("GET /api/vault/notes", s.vaultAPI(s.listNotes))
mux.HandleFunc("POST /api/vault/notes", s.vaultAPI(s.createNote))
mux.HandleFunc("GET /api/vault/notes/{id}", s.vaultAPI(s.getNote))
mux.HandleFunc("PUT /api/vault/notes/{id}", s.vaultAPI(s.updateNote))
mux.HandleFunc("DELETE /api/vault/notes/{id}", s.vaultAPI(s.deleteNote))
mux.HandleFunc("POST /api/vault/notes/{id}/restore", s.vaultAPI(s.restoreNote))
mux.HandleFunc("POST /api/vault/notes/{id}/out", s.vaultAPI(s.moveFromVault))
mux.HandleFunc("DELETE /api/vault/trash", s.vaultAPI(s.emptyTrash))
mux.HandleFunc("GET /api/vault/find", s.vaultAPI(s.find))
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-Mako") != "1" {
fail(w, http.StatusForbidden, "missing X-Mako 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; the server's log says why")
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())
}
}