2026-08-03 18:07:40 +02:00
package main
import (
2026-10-19 21:16:08 +00:00
"compress/gzip"
2026-08-03 18:07:40 +02:00
"context"
"embed"
"encoding/json"
2026-10-19 21:16:08 +00:00
"errors"
2026-08-03 18:07:40 +02:00
"fmt"
"io/fs"
2026-10-19 21:16:08 +00:00
"net"
2026-08-03 18:07:40 +02:00
"net/http"
"os"
"path"
"runtime"
"strings"
"time"
_ "github.com/joho/godotenv/autoload"
2026-09-01 01:34:48 +02:00
2026-09-13 21:11:53 +02:00
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
2026-09-10 11:56:17 +02:00
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
2026-09-23 04:56:42 +02:00
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
2026-08-03 18:07:40 +02:00
)
// 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 {
2026-09-10 11:56:17 +02:00
db * DB
2026-09-13 21:11:53 +02:00
auth * sharedauth . Service
2026-09-10 11:56:17 +02:00
startTime time . Time
internalServiceSecret string
coreConfig * coreconfig . Store
2026-10-19 21:16:08 +00:00
syncSlots chan struct {}
// trustedProxies are the TRUSTED_PROXIES networks whose X-Forwarded-For and
// X-Forwarded-Proto headers are believed. Nil trusts no proxy.
trustedProxies [] * net . IPNet
2026-08-03 18:07:40 +02:00
}
2026-10-19 21:16:08 +00:00
// Request body limits per route. Sync pushes can carry many rows at once, so
// they keep the larger limit; single-entity writes get the smaller one.
const (
jsonBodyLimit = 2 << 20
syncBodyLimit = 50 << 20
)
2026-08-03 18:07:40 +02:00
func main () {
2026-09-08 17:05:34 +02:00
port := envOrDefault ( "PORT" , "8080" )
2026-08-03 18:07:40 +02:00
connectionString := strings . TrimSpace ( os . Getenv ( "DATABASE_URL" ))
if connectionString == "" {
fmt . Fprintln ( os . Stderr , "DATABASE_URL environment variable is required" )
os . Exit ( 1 )
}
2026-09-15 13:22:50 +02:00
internalServiceSecret := strings . TrimSpace ( os . Getenv ( "SECRET" ))
2026-08-03 18:07:40 +02:00
2026-10-19 21:16:08 +00:00
trustedProxies , err := parseTrustedProxies ( os . Getenv ( "TRUSTED_PROXIES" ))
if err != nil {
fmt . Fprintln ( os . Stderr , err )
os . Exit ( 1 )
}
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
production := strings . EqualFold ( strings . TrimSpace ( os . Getenv ( "PRODUCTION" )), "true" )
if production && len ( trustedProxies ) == 0 {
fmt . Fprintln ( os . Stderr , "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there" )
os . Exit ( 1 )
}
2026-08-03 18:07:40 +02:00
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 )
2026-09-14 14:12:34 +02:00
// 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.
2026-09-01 01:34:48 +02:00
authGuardURL := strings . TrimSpace ( os . Getenv ( "AUTHGUARD_URL" ))
2026-09-14 14:12:34 +02:00
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 != "" :
2026-09-01 01:34:48 +02:00
fmt . Printf ( "auth: AuthGuard at %s\n" , authGuardURL )
2026-09-14 14:12:34 +02:00
default :
fmt . Println ( "auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then" )
2026-09-01 01:34:48 +02:00
}
2026-09-14 14:12:34 +02:00
auth := newAuthService ( database , authGuardURL , strings . EqualFold ( os . Getenv ( "COOKIE_SECURE" ), "true" ), authDisabled )
2026-09-01 01:34:48 +02:00
2026-09-10 11:56:17 +02:00
// 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".
2026-09-13 21:11:53 +02:00
// 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
2026-09-14 14:12:34 +02:00
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
2026-09-10 11:56:17 +02:00
carrierNodeURL := strings . TrimSpace ( os . Getenv ( "CARRIERNODE_URL" ))
coreConfig := coreconfig . NewStore ( coreconfig . Info { AuthGuardURL : authGuardURL , CarrierNodeURL : carrierNodeURL })
2026-09-13 21:11:53 +02:00
coreConfig . OnUpdate ( func ( info coreconfig . Info ) {
if info . AuthGuardURL != "" {
auth . SetAuthGuardBaseURL ( info . AuthGuardURL )
}
})
2026-09-10 11:56:17 +02:00
server := & Server {
db : database ,
auth : auth ,
startTime : time . Now (),
internalServiceSecret : internalServiceSecret ,
coreConfig : coreConfig ,
2026-10-19 21:16:08 +00:00
syncSlots : make ( chan struct {}, maxConcurrentSyncs ),
trustedProxies : trustedProxies ,
2026-09-10 11:56:17 +02:00
}
2026-08-03 18:07:40 +02:00
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 )
2026-10-19 21:16:08 +00:00
handler := withSecurityHeaders ( withGzip ( withCORS ( allowedOriginsFromEnv (), mux )))
if production {
handler = withHTTPSRequired ( trustedProxies , handler )
fmt . Println ( "PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https" )
} else {
fmt . Fprintln ( os . Stderr , "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP." )
}
2026-08-03 18:07:40 +02:00
httpServer := & http . Server {
Addr : ":" + port ,
2026-10-19 21:16:08 +00:00
Handler : handler ,
2026-08-03 18:07:40 +02:00
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 ) {
2026-09-23 04:56:42 +02:00
retryOptions := sharedpostgres . StartupRetryOptionsFromEnv ()
2026-08-03 18:07:40 +02:00
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 )
2026-09-23 04:56:42 +02:00
if retryOptions . MaxAttempts > 0 && attempt >= retryOptions . MaxAttempts {
2026-08-03 18:07:40 +02:00
return nil , err
}
2026-09-23 04:56:42 +02:00
fmt . Printf ( "[DB] Retrying in %s...\n" , retryOptions . Interval )
2026-08-03 18:07:40 +02:00
select {
case <- ctx . Done ():
return nil , ctx . Err ()
2026-09-23 04:56:42 +02:00
case <- time . After ( retryOptions . Interval ):
2026-08-03 18:07:40 +02:00
}
}
}
func ( s * Server ) registerRoutes ( mux * http . ServeMux , webRoot fs . FS ) {
2026-10-19 21:16:08 +00:00
// Budgets for setup, login, TOTP and token regeneration, keyed by client IP
// (and by account for failed logins). See ratelimit.go.
limits := newAuthRateLimits ( s . trustedProxies )
2026-08-03 18:07:40 +02:00
// Health and auth bootstrap routes are intentionally public.
mux . HandleFunc ( "GET /health" , s . handleHealth )
2026-09-04 15:07:02 +02:00
mux . HandleFunc ( "GET /api/info" , s . handleInfo )
2026-09-10 11:56:17 +02:00
// 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 ))
2026-09-13 21:11:53 +02:00
mux . HandleFunc ( "GET /api/auth/status" , s . auth . Status )
2026-10-19 21:16:08 +00:00
mux . Handle ( "POST /api/auth/setup" , limits . perClient ( http . HandlerFunc ( s . auth . Signup )))
mux . Handle ( "POST /api/auth/login" , limits . login ( http . HandlerFunc ( s . auth . Login )))
2026-09-17 00:32:46 +02:00
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 )))
2026-10-19 21:16:08 +00:00
// Managed-user routes check the caller's role here, not only in AuthGuard.
mux . Handle ( "GET /api/auth/users" , s . auth . RequireUserManager ( http . HandlerFunc ( s . auth . ManagedUsers )))
mux . Handle ( "POST /api/auth/users" , s . auth . RequireUserManager ( http . HandlerFunc ( s . auth . ManagedCreateUser )))
mux . Handle ( "PUT /api/auth/users/{id}" , s . auth . RequireUserManager ( http . HandlerFunc ( s . auth . ManagedUpdateUser )))
mux . Handle ( "PATCH /api/auth/users/{id}" , s . auth . RequireUserManager ( http . HandlerFunc ( s . auth . ManagedUpdateUser )))
mux . Handle ( "DELETE /api/auth/users/{id}" , s . auth . RequireUserManager ( http . HandlerFunc ( s . auth . ManagedDeleteUser )))
mux . Handle ( "GET /api/auth/totp/status" , limits . perClient ( s . auth . RequireIfLoginRequired ( http . HandlerFunc ( s . auth . TOTPStatus ))))
mux . Handle ( "POST /api/auth/totp/setup" , limits . perClient ( s . auth . RequireIfLoginRequired ( http . HandlerFunc ( s . auth . TOTPInitiate ))))
mux . Handle ( "POST /api/auth/totp/enable" , limits . perClient ( s . auth . RequireIfLoginRequired ( http . HandlerFunc ( s . auth . TOTPVerify ))))
mux . Handle ( "POST /api/auth/totp/disable" , limits . perClient ( s . auth . RequireIfLoginRequired ( http . HandlerFunc ( s . auth . TOTPDisable ))))
2026-09-17 00:32:46 +02:00
mux . Handle ( "GET /api/auth/token/status" , s . auth . RequireIfLoginRequired ( http . HandlerFunc ( s . handleTokenStatus )))
2026-10-19 21:16:08 +00:00
mux . Handle ( "POST /api/auth/token/regenerate" , limits . perClient ( s . auth . RequireIfLoginRequired ( http . HandlerFunc ( s . handleTokenRegenerate ))))
2026-08-03 18:07:40 +02:00
// 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 {
2026-09-13 21:11:53 +02:00
return requireAPIToken ( s . db )( handler )
2026-08-03 18:07:40 +02:00
}
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.
2026-09-17 00:32:46 +02:00
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 )))
2026-08-03 18:07:40 +02:00
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 (),
})
}
2026-09-04 15:07:02 +02:00
// 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 {
2026-10-13 21:23:07 +00:00
{ "key" : "overview" , "label" : "Overview" , "token" : "/" },
2026-09-04 15:07:02 +02:00
},
"mountTypes" : [] string {},
})
}
2026-08-03 18:07:40 +02:00
func envOrDefault ( name , fallback string ) string {
if value := strings . TrimSpace ( os . Getenv ( name )); value != "" {
return value
}
return fallback
}
2026-10-19 21:16:08 +00:00
func decodeJSON ( w http . ResponseWriter , r * http . Request , target any ) error {
return decodeJSONLimit ( w , r , target , jsonBodyLimit )
}
// decodeJSONLimit decodes a body of at most limit bytes. An oversized body fails
// with *http.MaxBytesError, which writeDecodeError turns into 413.
func decodeJSONLimit ( w http . ResponseWriter , r * http . Request , target any , limit int64 ) error {
decoder := json . NewDecoder ( http . MaxBytesReader ( w , r . Body , limit ))
return decoder . Decode ( target )
}
func writeDecodeError ( w http . ResponseWriter , err error , message string ) {
var tooLarge * http . MaxBytesError
if errors . As ( err , & tooLarge ) {
writeJSONError ( w , http . StatusRequestEntityTooLarge , "Request body too large" )
return
2026-08-03 18:07:40 +02:00
}
2026-10-19 21:16:08 +00:00
writeJSONError ( w , http . StatusBadRequest , message )
2026-08-03 18:07:40 +02:00
}
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 ,
})
}
2026-10-19 21:16:08 +00:00
// allowedOriginsFromEnv reads ALLOWED_ORIGINS, a comma-separated list of browser
// origins that may call the API cross-origin with credentials. It is empty by
// default: the dashboard is same-origin and needs no CORS headers.
func allowedOriginsFromEnv () [] string {
var origins [] string
for _ , origin := range strings . Split ( os . Getenv ( "ALLOWED_ORIGINS" ), "," ) {
if origin = strings . TrimSpace ( origin ); origin != "" {
origins = append ( origins , origin )
}
}
return origins
}
// withCORS sends CORS headers only for origins in allowedOrigins. Any other
// origin gets no Access-Control-Allow-Origin and no credentials header, so a
// browser refuses its cross-origin reads.
func withCORS ( allowedOrigins [] string , next http . Handler ) http . Handler {
allowed := make ( map [ string ] bool , len ( allowedOrigins ))
for _ , origin := range allowedOrigins {
allowed [ origin ] = true
}
2026-08-03 18:07:40 +02:00
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
origin := r . Header . Get ( "Origin" )
if origin != "" {
w . Header (). Add ( "Vary" , "Origin" )
}
2026-10-19 21:16:08 +00:00
permitted := origin != "" && allowed [ origin ]
if permitted {
w . Header (). Set ( "Access-Control-Allow-Origin" , origin )
w . Header (). Set ( "Access-Control-Allow-Credentials" , "true" )
}
2026-08-03 18:07:40 +02:00
if r . Method == http . MethodOptions {
2026-10-19 21:16:08 +00:00
if permitted {
w . Header (). Set ( "Access-Control-Allow-Headers" , "Authorization, Content-Type, X-Device-Id" )
w . Header (). Set ( "Access-Control-Allow-Methods" , "GET, POST, PUT, PATCH, DELETE, OPTIONS" )
}
2026-08-03 18:07:40 +02:00
w . WriteHeader ( http . StatusNoContent )
return
}
next . ServeHTTP ( w , r )
})
}
2026-10-19 21:16:08 +00:00
// withSecurityHeaders sets headers that stop the dashboard and API from being
// framed (clickjacking) or MIME-sniffed. The dashboard page replaces the
// Content-Security-Policy with the full one from dashboardCSP. HSTS is not set
// here: this process has no TLS, so the TLS proxy sets Strict-Transport-Security.
func withSecurityHeaders ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
headers := w . Header ()
headers . Set ( "X-Content-Type-Options" , "nosniff" )
headers . Set ( "X-Frame-Options" , "DENY" )
headers . Set ( "Content-Security-Policy" , "frame-ancestors 'none'" )
headers . Set ( "Referrer-Policy" , "strict-origin-when-cross-origin" )
next . ServeHTTP ( w , r )
})
}
// withHTTPSRequired is the PRODUCTION=true profile: a request that did not
// arrive over TLS, directly or through a trusted proxy, gets 403. The health
// probe is exempt so local container checks keep working.
func withHTTPSRequired ( trusted [] * net . IPNet , next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
if r . URL . Path == "/health" || requestIsHTTPS ( r , trusted ) {
next . ServeHTTP ( w , r )
return
}
writeJSONError ( w , http . StatusForbidden , "HTTPS is required on this server" )
})
}
// gzipResponseWriter compresses a response body when the client accepts gzip.
// Responses that carry no body (204, 304) are passed through unchanged.
type gzipResponseWriter struct {
http . ResponseWriter
gzipWriter * gzip . Writer
wroteHeader bool
}
func ( w * gzipResponseWriter ) WriteHeader ( status int ) {
if w . wroteHeader {
return
}
w . wroteHeader = true
// Partial (206) bodies are left alone: a byte range of the plain file is not a gzip stream.
if status != http . StatusNoContent && status != http . StatusNotModified && status != http . StatusPartialContent {
w . Header (). Set ( "Content-Encoding" , "gzip" )
w . Header (). Del ( "Content-Length" )
w . gzipWriter = gzip . NewWriter ( w . ResponseWriter )
}
w . ResponseWriter . WriteHeader ( status )
}
func ( w * gzipResponseWriter ) Write ( p [] byte ) ( int , error ) {
if ! w . wroteHeader {
w . WriteHeader ( http . StatusOK )
}
if w . gzipWriter == nil {
return w . ResponseWriter . Write ( p )
}
return w . gzipWriter . Write ( p )
}
// withGzip compresses responses for clients that send Accept-Encoding: gzip.
func withGzip ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
w . Header (). Add ( "Vary" , "Accept-Encoding" )
if ! strings . Contains ( r . Header . Get ( "Accept-Encoding" ), "gzip" ) {
next . ServeHTTP ( w , r )
return
}
compressed := & gzipResponseWriter { ResponseWriter : w }
next . ServeHTTP ( compressed , r )
if compressed . gzipWriter != nil {
_ = compressed . gzipWriter . Close ()
}
})
}
2026-08-03 18:07:40 +02:00
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" )
2026-10-19 21:16:08 +00:00
w . Header (). Set ( "Cache-Control" , "no-cache" )
w . Header (). Set ( "Content-Security-Policy" , dashboardCSP ( data ))
2026-08-03 18:07:40 +02:00
_ , _ = w . Write ( data )
}
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
2026-10-27 07:15:31 +00:00
// The path is cleaned as a rooted URL path, and it is only read from webRoot,
// an embed.FS, so it cannot name a file outside the embedded build.
// nosemgrep: go.lang.security.filepath-clean-misuse.filepath-clean-misuse
2026-08-03 18:07:40 +02:00
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
}
2026-10-19 21:16:08 +00:00
// SvelteKit names its content-hashed bundle files under _app/immutable/, so
// those can be cached for a long time. Everything else is revalidated.
if strings . HasPrefix ( cleanPath , "_app/immutable/" ) {
w . Header (). Set ( "Cache-Control" , "public, max-age=31536000, immutable" )
} else {
w . Header (). Set ( "Cache-Control" , "no-cache" )
}
2026-08-03 18:07:40 +02:00
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"`
}
2026-09-01 01:34:48 +02:00
func ( s * Server ) handleTechStack ( w http . ResponseWriter , _ * http . Request ) {
2026-08-03 18:07:40 +02:00
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)" },
},
})
}