Files
nidus/cmd/server/main.go
T
arnefandCopilot ab3c7f44d5 Add web UI: login, dashboard, and share management (templ + Tailwind + htmx)
New internal/web package mounted at /ui/, separate from DAV Basic Auth:

- Cookie-based sessions (opaque random tokens in a new web_sessions
  SQLite table, internal/db/sessions.go), checked against the same
  cfg.Users/bcrypt credentials as DAV Basic Auth.
- Dashboard listing the logged-in user's own calendars/address books,
  who they're shared with, and what's shared with them.
- Share/unshare directly from the dashboard, updated in place via htmx
  partial swaps (POST to create/update, DELETE to revoke). Always
  verifies the resource actually belongs to the logged-in user before
  granting a share.
- Templates written in templ (internal/web/templates/*.templ, generated
  *_templ.go committed), styled with Tailwind CSS v4 (web/input.css,
  compiled to web/static/app.css), with htmx vendored as a static file
  for the dynamic bits. Both are embedded into the binary at build time
  (web/staticassets.go) so the compiled server has no Node.js/web/
  runtime dependency.
- Wired into cmd/server/main.go at /ui/ alongside the existing /cal/,
  /card/, /files/ routes; welcome page links to it.
- Tests: internal/web/server_test.go covers login success/failure, the
  login-required redirect, dashboard rendering, share/unshare including
  the htmx-v2-sends-DELETE-params-as-query-string quirk, and rejecting
  shares of resources the user doesn't own.
- Docs: README (new 'Web UI' section, updated sharing section, project
  layout, dependencies) and copilot-instructions updated accordingly.
  Makefile: new templ-generate/web-deps/web-css targets.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-08-19 07:12:56 +02:00

262 lines
7.7 KiB
Go

package main
import (
"context"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/yourusername/caldav-server/internal/auth"
"github.com/yourusername/caldav-server/internal/caldav"
"github.com/yourusername/caldav-server/internal/carddav"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
"github.com/yourusername/caldav-server/internal/web"
filewebdav "github.com/yourusername/caldav-server/internal/webdav"
webstatic "github.com/yourusername/caldav-server/web"
)
func main() {
var cfgPath string
flag.StringVar(&cfgPath, "config", "config.yaml", "path to configuration file")
flag.Parse()
// ---- Configuration ----
cfg, err := config.Load(cfgPath)
if err != nil {
fmt.Fprintf(os.Stderr, "error loading config: %v\n", err)
os.Exit(1)
}
// ---- Logging ----
logger := buildLogger(cfg)
logger.Info("starting DAV server",
"host", cfg.Server.Host,
"port", cfg.Server.Port,
"base_url", cfg.Server.BaseURL,
"tls", cfg.TLS.Enabled)
// ---- Storage ----
st, err := store.NewStore(cfg.Storage.DataDir)
if err != nil {
logger.Error("initialising store", "error", err)
os.Exit(1)
}
// ---- Database (calendar/address-book sharing, future user mgmt) ----
dbPath := filepath.Join(cfg.Storage.DataDir, "nidus.db")
dbase, err := db.Open(dbPath)
if err != nil {
logger.Error("initialising database", "error", err)
os.Exit(1)
}
defer dbase.Close()
// Pre-create default collections for each user
for username, user := range cfg.Users {
for _, cal := range user.Calendars {
if err := st.EnsureCollection(username, "cal-"+cal); err != nil {
logger.Warn("creating calendar collection", "user", username, "cal", cal, "error", err)
}
}
for _, book := range user.AddressBooks {
if err := st.EnsureCollection(username, "card-"+book); err != nil {
logger.Warn("creating address book collection", "user", username, "book", book, "error", err)
}
}
}
// ---- Middleware ----
authMw := auth.NewMiddleware(cfg, logger)
// ---- Handlers ----
calHandler := caldav.NewHandler(cfg, st, dbase, logger)
cardHandler := carddav.NewHandler(cfg, st, dbase, logger)
fileHandler := filewebdav.NewHandler(cfg, cfg.Storage.DataDir, logger)
webUI := web.NewServer(cfg, st, dbase, logger)
mux := buildMux(cfg, authMw, calHandler, cardHandler, fileHandler, webUI, logger)
// ---- HTTP Server ----
addr := net.JoinHostPort(cfg.Server.Host, fmt.Sprintf("%d", cfg.Server.Port))
srv := &http.Server{
Addr: addr,
Handler: withRequestLogging(mux, logger),
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
// ---- Graceful shutdown ----
idleConnsClosed := make(chan struct{})
go func() {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
logger.Info("shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
logger.Error("graceful shutdown failed", "error", err)
}
close(idleConnsClosed)
}()
logger.Info("server ready", "addr", addr)
if cfg.TLS.Enabled {
err = srv.ListenAndServeTLS(cfg.TLS.CertFile, cfg.TLS.KeyFile)
} else {
err = srv.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
logger.Error("server error", "error", err)
os.Exit(1)
}
<-idleConnsClosed
logger.Info("server stopped")
}
// buildMux creates the top-level HTTP multiplexer.
func buildMux(
cfg *config.Config,
authMw *auth.Middleware,
calHandler, cardHandler, fileHandler http.Handler,
webUI *web.Server,
logger *slog.Logger,
) *http.ServeMux {
mux := http.NewServeMux()
// Web UI (own cookie-based auth, not Basic Auth) — dashboard, login,
// share management.
mux.Handle("/ui/", webUI.Handler(webstatic.FS()))
// /.well-known/ redirects for auto-discovery
mux.HandleFunc("/.well-known/caldav", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, cfg.Server.BaseURL+"/cal/", http.StatusMovedPermanently)
})
mux.HandleFunc("/.well-known/carddav", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, cfg.Server.BaseURL+"/card/", http.StatusMovedPermanently)
})
// Health check (unauthenticated)
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
})
// CalDAV, CardDAV, and file WebDAV — all behind Basic Auth
mux.Handle("/cal/", authMw.Wrap(calHandler))
mux.Handle("/card/", authMw.Wrap(cardHandler))
mux.Handle("/files/", authMw.Wrap(fileHandler))
// Root — simple HTML welcome page (unauthenticated)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
// Only plain GET/HEAD get the welcome page. Any other method
// (PROPFIND, LOCK, PUT, ...) hitting "/" means a client is pointed
// at the wrong URL — reject it explicitly instead of returning a
// misleading 200 OK, which breaks WebDAV clients expecting 207.
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "not a WebDAV collection; use /cal/, /card/ or /files/", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, welcomePage, cfg.Server.BaseURL, cfg.Server.BaseURL, cfg.Server.BaseURL, cfg.Server.BaseURL, cfg.Server.BaseURL)
})
return mux
}
// withRequestLogging wraps a handler with access-log middleware.
func withRequestLogging(next http.Handler, logger *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &responseWriter{ResponseWriter: w, code: http.StatusOK}
next.ServeHTTP(rw, r)
logger.Info("request",
"method", r.Method,
"path", r.URL.Path,
"status", rw.code,
"duration_ms", time.Since(start).Milliseconds(),
"remote_addr", r.RemoteAddr,
)
})
}
// responseWriter captures the status code for logging.
type responseWriter struct {
http.ResponseWriter
code int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.code = code
rw.ResponseWriter.WriteHeader(code)
}
// buildLogger creates a slog.Logger based on config.
func buildLogger(cfg *config.Config) *slog.Logger {
level := slog.LevelInfo
switch cfg.Logging.Level {
case "debug":
level = slog.LevelDebug
case "warn":
level = slog.LevelWarn
case "error":
level = slog.LevelError
}
var handler slog.Handler
opts := &slog.HandlerOptions{Level: level}
if cfg.Logging.Format == "json" {
handler = slog.NewJSONHandler(os.Stdout, opts)
} else {
handler = slog.NewTextHandler(os.Stdout, opts)
}
return slog.New(handler)
}
const welcomePage = `<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>DAV Server</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 640px; margin: 4rem auto; padding: 0 1rem; }
h1 { color: #333; }
code { background: #f4f4f4; padding: 2px 6px; border-radius: 3px; }
ul { line-height: 2; }
</style>
</head>
<body>
<h1>🗓 DAV Server</h1>
<p>This server provides CalDAV, CardDAV, and WebDAV access.</p>
<h2>Endpoints</h2>
<ul>
<li><strong>CalDAV</strong> — <code>%s/cal/</code></li>
<li><strong>CardDAV</strong> — <code>%s/card/</code></li>
<li><strong>WebDAV files</strong> — <code>%s/files/</code></li>
</ul>
<h2>Auto-discovery</h2>
<ul>
<li><code>%s/.well-known/caldav</code></li>
<li><code>%s/.well-known/carddav</code></li>
</ul>
<p><em>Authentication: HTTP Basic Auth</em></p>
<p><a href="/ui/">Open the web dashboard →</a></p>
</body>
</html>`