Files
CollabTable/backend/server.go
T

299 lines
10 KiB
Go
Raw Normal View History

package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path"
"runtime"
"strings"
"time"
_ "github.com/joho/godotenv/autoload"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// The SvelteKit build is copied here by the Docker builder before go build.
// Keeping a tiny tracked placeholder in web/ also lets go test run from a
// checkout before the dashboard has been built.
//
//go:embed all:web
var webFS embed.FS
type Server struct {
db *DB
auth *AuthService
startTime time.Time
}
func main() {
port := envOrDefault("PORT", "3000")
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if connectionString == "" {
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
os.Exit(1)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
database, err := connectWithRetry(ctx, connectionString)
if err != nil {
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
os.Exit(1)
}
defer database.close()
go database.pruneExpiredSessions(ctx)
go database.cleanupNotifications(ctx)
// AuthGuard is optional (see auth.go's top-of-file "Auth-disabled mode"
// section): a nil client means every request is treated as already
// authenticated, with nothing gated -- an explicit choice for local
// development or a standalone deployment, not a degraded fallback.
authGuardURL := strings.TrimSpace(os.Getenv("AUTHGUARD_URL"))
var authGuard *authclient.Client
if authGuardURL != "" {
authGuard = authclient.New(authGuardURL)
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
} else {
fmt.Println("auth: DISABLED (AUTHGUARD_URL not set) -- every request is treated as authenticated")
}
auth := newAuthService(authGuard, database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
server := &Server{db: database, auth: auth, startTime: time.Now()}
webRoot, err := fs.Sub(webFS, "web")
if err != nil {
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
os.Exit(1)
}
mux := http.NewServeMux()
server.registerRoutes(mux, webRoot)
httpServer := &http.Server{
Addr: ":" + port,
Handler: withCORS(mux),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
}
fmt.Printf("CollabTable Go server listening on :%s\n", port)
fmt.Printf("Database: PostgreSQL (pgx)\n")
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
os.Exit(1)
}
}
func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) {
interval := time.Duration(envInt64("DB_INIT_RETRY_INTERVAL_MS", 5000)) * time.Millisecond
if interval < 250*time.Millisecond {
interval = 250 * time.Millisecond
}
maxAttempts := envInt64("DB_INIT_RETRY_MAX_ATTEMPTS", 0)
for attempt := int64(1); ; attempt++ {
database, err := connectDB(ctx, connectionString)
if err == nil {
if schemaErr := database.initSchema(ctx); schemaErr == nil {
if attempt > 1 {
fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt)
}
return database, nil
} else {
database.close()
err = schemaErr
}
}
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
if maxAttempts > 0 && attempt >= maxAttempts {
return nil, err
}
fmt.Printf("[DB] Retrying in %s...\n", interval)
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(interval):
}
}
}
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
// Health and auth bootstrap routes are intentionally public.
mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus)
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
mux.Handle("POST /api/auth/logout", s.auth.requireSession(http.HandlerFunc(s.auth.handleLogout)))
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(http.HandlerFunc(s.auth.handleUpdateCredentials)))
mux.Handle("GET /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers)))
mux.Handle("POST /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers)))
mux.Handle("PUT /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
mux.Handle("GET /api/auth/totp/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPStatus)))
mux.Handle("POST /api/auth/totp/setup", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPSetup)))
mux.Handle("POST /api/auth/totp/enable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPEnable)))
mux.Handle("POST /api/auth/totp/disable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPDisable)))
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenStatus)))
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenRegenerate)))
// Sync/collaboration API routes use a long-lived bearer token shared by the
// user's devices. This is deliberately separate from browser sessions.
api := func(handler http.Handler) http.Handler {
return s.auth.requireAPIToken(handler)
}
mux.Handle("GET /api/lists", api(http.HandlerFunc(s.handleListCollection)))
mux.Handle("POST /api/lists", api(http.HandlerFunc(s.handleListCollection)))
mux.Handle("GET /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
mux.Handle("PUT /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
mux.Handle("DELETE /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
mux.Handle("POST /api/fields", api(http.HandlerFunc(s.handleFieldCollection)))
mux.Handle("GET /api/fields/list/{listId}", api(http.HandlerFunc(s.handleFieldsForList)))
mux.Handle("PUT /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
mux.Handle("DELETE /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
mux.Handle("POST /api/items", api(http.HandlerFunc(s.handleItemCollection)))
mux.Handle("POST /api/items/values", api(http.HandlerFunc(s.handleItemValueCollection)))
// These item paths overlap under the Go ServeMux pattern rules (for
// example /items/list/values), so dispatch the legacy subroutes in one
// prefix handler while keeping /items/values exact for POST.
mux.Handle("/api/items/", api(http.HandlerFunc(s.handleItemPath)))
mux.Handle("POST /api/sync", api(http.HandlerFunc(s.handleSync)))
mux.Handle("GET /api/notifications/poll", api(http.HandlerFunc(s.handleNotificationPoll)))
// The dashboard is a public SPA shell, but its data and tech-stack endpoints
// are protected by the browser session.
mux.Handle("GET /api/tech-stack", s.auth.requireSession(http.HandlerFunc(s.handleTechStack)))
mux.Handle("GET /web/data", s.auth.requireSession(http.HandlerFunc(s.handleWebData)))
mux.Handle("/", spaFileServer(webRoot))
}
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"status": "ok",
"timestamp": time.Now().UnixMilli(),
})
}
func envOrDefault(name, fallback string) string {
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value
}
return fallback
}
func envInt64(name string, fallback int64) int64 {
value := strings.TrimSpace(os.Getenv(name))
if value == "" {
return fallback
}
var parsed int64
if _, err := fmt.Sscan(value, &parsed); err != nil {
return fallback
}
return parsed
}
func decodeJSON(r *http.Request, target any) error {
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
if err := decoder.Decode(target); err != nil {
return err
}
return nil
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeJSONError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{
"error": message,
"message": message,
})
}
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Add("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func spaFileServer(root fs.FS) http.Handler {
fileServer := http.FileServer(http.FS(root))
serveIndex := func(w http.ResponseWriter, r *http.Request) {
data, err := fs.ReadFile(root, "index.html")
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(data)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
serveIndex(w, r)
return
}
if _, err := fs.Stat(root, cleanPath); err != nil {
serveIndex(w, r)
return
}
fileServer.ServeHTTP(w, r)
})
}
type dependency struct {
Name string `json:"name"`
Version string `json:"version"`
}
type techStackResponse struct {
AppVersion string `json:"appVersion"`
Stack []stackEntry `json:"stack"`
}
type stackEntry struct {
Label string `json:"label"`
Value string `json:"value"`
}
func (s *Server) handleTechStack(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, techStackResponse{
AppVersion: envOrDefault("APP_VERSION", "dev"),
Stack: []stackEntry{
{Label: "Runtime", Value: "Go " + runtime.Version()},
{Label: "Web Framework", Value: "net/http"},
{Label: "Database", Value: "PostgreSQL (pgx/v5)"},
},
})
}