Files
librenotes/internal/httpapi/router.go
T
libretechandClaude Opus 4.7 cdc7f26269 Add tenant-scoped notes REST API
internal/httpapi/notes.go exposes:
- GET    /api/notes            list summaries {id, title, updated_at}
- GET    /api/notes/{id}       full {id, title, content, updated_at}
- PUT    /api/notes/{id}       create/update; ?base=<unix> for
                                optimistic-locking conflict detection
- DELETE /api/notes/{id}       remove; ?base=<unix> guards against
                                deleting a row modified after the
                                client last saw it

Backed by tenant.FS so all reads/writes go through the per-user
sandbox — path traversal is rejected at parse time (regex slug)
and again by os.Root inside the FS layer.

On-disk format is plain Markdown: first line `# Title`, rest is
content. grep / cat / vim still produce a usable view of raw
files. Title round-trips through composeNote/splitTitle.

Conflict semantics: when the client supplies ?base=<unix>, the
server compares against the file's mtime. If the file is newer,
respond 409 with the current note body so the client can present
a merge UI. Same logic on DELETE returns 409 alone.

cmd/librenotes/serve.go grows a tenantPool that memoises FS
handles per user id; defer-closes them on shutdown.

Tests cover: full CRUD round-trip, cross-tenant isolation,
unauthenticated 401s, invalid IDs (regex rejection), and the
conflict path with a real mtime advance.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 22:42:43 +02:00

55 lines
1.4 KiB
Go

package httpapi
import (
"encoding/json"
"log"
"net/http"
"git.librete.ch/public/librenotes/internal/auth"
)
// Server wires routes for the multi-tenant backend. The auth endpoints
// live under /auth/* and are unauthenticated. Everything under /api/*
// is wrapped by AuthMiddleware and receives a Tenant on the context.
type Server struct {
Auth auth.Handlers
Signer *auth.Signer
Logger *log.Logger
Notes NotesHandler
}
// Routes returns an http.Handler with all routes mounted.
func (s *Server) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/auth/login", s.Auth.HandleLogin)
mux.HandleFunc("/auth/verify", s.Auth.HandleVerify)
protected := http.NewServeMux()
protected.HandleFunc("/api/whoami", s.handleWhoami)
if s.Notes.FSFor != nil {
s.Notes.Mount(protected)
}
mw := AuthMiddleware(s.Signer, s.Logger)
mux.Handle("/api/", mw(protected))
return mux
}
// handleWhoami returns the verified tenant identity. Useful for
// frontend session-bootstrapping and as the canonical example of a
// tenant-scoped handler.
func (s *Server) handleWhoami(w http.ResponseWriter, r *http.Request) {
t, err := TenantFrom(r.Context())
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"user_id": t.UserID,
"email": t.Email,
})
}