Files
CollabTable/backend/server.go
T

358 lines
13 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"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
)
// 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 *sharedauth.Service
startTime time.Time
internalServiceSecret string
coreConfig *coreconfig.Store
carrierNode *carriernodeclient.Client
}
func main() {
port := envOrDefault("PORT", "8080")
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if connectionString == "" {
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
os.Exit(1)
}
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
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 integration has three states now (see auth.go's top-of-file
// doc comment and sharedauth's own "Auth-disabled mode" section): an
// AUTHGUARD_URL set is used immediately; unset with AUTH_DISABLED
// unset/false is "pending" (fully gated, failing closed until
// ProjectConfigurator's push arrives); AUTH_DISABLED=true is an explicit
// opt-out where every request is treated as already authenticated, with
// nothing gated -- for local development or a standalone deployment, not
// a degraded fallback.
authGuardURL := strings.TrimSpace(os.Getenv("AUTHGUARD_URL"))
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
switch {
case authDisabled:
fmt.Println("auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
case authGuardURL != "":
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
default:
fmt.Println("auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then")
}
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled)
// coreConfig holds the AuthGuard/CarrierNode URLs ProjectConfigurator pushes once this project
// is registered there (PUT /api/core-services/internal, see registerRoutes) -- AUTHGUARD_URL and
// CARRIERNODE_URL above/below are only the bootstrap fallback used until the first push arrives.
// See Core/ProjectConfigurator/README.md's "Pushing core service info to other projects".
// auth.SetAuthGuardBaseURL retargets the live AuthGuard client sharedauth.Service holds
// internally on every push, so AuthGuard moving to a new URL takes effect without a restart -- it
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
coreConfig.OnUpdate(func(info coreconfig.Info) {
if info.AuthGuardURL != "" {
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
}
})
carrierNode := carriernodeclient.New(internalServiceSecret, func(context.Context) string {
return coreConfig.CarrierNodeURL()
})
server := &Server{
db: database,
auth: auth,
startTime: time.Now(),
internalServiceSecret: internalServiceSecret,
coreConfig: coreConfig,
carrierNode: carrierNode,
}
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/info", s.handleInfo)
// X-Internal-Auth-gated, not browser-session-gated -- ProjectConfigurator calls this directly
// to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above).
mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig))
mux.HandleFunc("GET /api/auth/status", s.auth.Status)
mux.HandleFunc("POST /api/auth/setup", s.auth.Signup)
mux.HandleFunc("POST /api/auth/login", s.auth.Login)
mux.Handle("PUT /api/auth/access/internal", s.auth.SetLoginRequiredInternal(s.internalServiceSecret))
mux.Handle("POST /api/auth/logout", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.Logout)))
mux.Handle("POST /api/auth/credentials", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.UpdateMe)))
mux.Handle("GET /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUsers)))
mux.Handle("POST /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedCreateUser)))
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedDeleteUser)))
mux.Handle("GET /api/auth/totp/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus)))
mux.Handle("POST /api/auth/totp/setup", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate)))
mux.Handle("POST /api/auth/totp/enable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify)))
mux.Handle("POST /api/auth/totp/disable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable)))
mux.Handle("GET /api/auth/token/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenStatus)))
mux.Handle("POST /api/auth/token/regenerate", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.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 requireAPIToken(s.db)(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.RequireIfLoginRequired(http.HandlerFunc(s.handleTechStack)))
mux.Handle("GET /web/data", s.auth.RequireIfLoginRequired(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(),
})
}
// handleInfo is CollabTable's self-describe endpoint: ProjectConfigurator's Projects workspace
// calls this (via its server-side /api/discover-service proxy) when an operator adds CollabTable
// by URL, to populate its display name, navigable tabs, and mount path types (none - CollabTable
// keeps all of its data in PostgreSQL, with no shared file mounts of its own) without any manual
// entry.
func (s *Server) handleInfo(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"name": "CollabTable",
"tabs": []map[string]string{
{"label": "Overview", "token": "/"},
{"label": "About", "token": "/about"},
},
"mountTypes": []string{},
})
}
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)"},
},
})
}