Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: switch to sql migrations, and key value store for settings (#353)
Kyle Mendell21623fb328aa
diff --git a/backend/go.mod b/backend/go.modindex ffe22c982..f36e71bf9 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -21,7 +21,7 @@ require ()require (- github.com/Microsoft/go-winio v0.4.14 // indirect+ github.com/Microsoft/go-winio v0.6.2 // indirectgithub.com/bytedance/sonic v1.13.2 // indirectgithub.com/bytedance/sonic/loader v0.2.4 // indirectgithub.com/cloudwego/base64x v0.1.5 // indirect@@ -42,6 +42,9 @@ require (github.com/go-viper/mapstructure/v2 v2.0.0 // indirectgithub.com/goccy/go-json v0.10.5 // indirectgithub.com/gogo/protobuf v1.3.2 // indirect+ github.com/golang-migrate/migrate/v4 v4.18.3 // indirect+ github.com/hashicorp/errwrap v1.1.0 // indirect+ github.com/hashicorp/go-multierror v1.1.1 // indirectgithub.com/jackc/pgpassfile v1.0.0 // indirectgithub.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirectgithub.com/jackc/pgx/v5 v5.6.0 // indirect@@ -52,6 +55,7 @@ require (github.com/json-iterator/go v1.1.12 // indirectgithub.com/klauspost/cpuid/v2 v2.2.10 // indirectgithub.com/leodido/go-urn v1.4.0 // indirect+ github.com/lib/pq v1.10.9 // indirectgithub.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirectgithub.com/mattn/go-isatty v0.0.20 // indirectgithub.com/mattn/go-shellwords v1.0.12 // indirect@@ -85,6 +89,7 @@ require (go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.36.0 // indirectgo.opentelemetry.io/otel/metric v1.36.0 // indirectgo.opentelemetry.io/otel/trace v1.36.0 // indirect+ go.uber.org/atomic v1.7.0 // indirectgolang.org/x/arch v0.16.0 // indirectgolang.org/x/net v0.40.0 // indirectgolang.org/x/sync v0.14.0 // indirectdiff --git a/backend/go.sum b/backend/go.sumindex 43595149d..acfcaaeb5 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -2,6 +2,7 @@ github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKgithub.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU=github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=@@ -66,6 +67,8 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=+github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs=+github.com/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY=github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=@@ -74,6 +77,11 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo=github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI=+github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=+github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=+github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=+github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=+github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=@@ -105,6 +113,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=+github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=+github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=@@ -208,6 +218,8 @@ go.opentelemetry.io/otel/trace v1.36.0 h1:ahxWNuqZjpdiFAyrIoQ4GIiAIhxAunQR6MUoKrgo.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA=go.opentelemetry.io/proto/otlp v1.6.0 h1:jQjP+AQyTf+Fe7OKj/MfkDrmK4MNVtw2NpXsf9fefDI=go.opentelemetry.io/proto/otlp v1.6.0/go.mod h1:cicgGehlFuNdgZkcALOCh3VE6K/u2tAjzlRhDwmVpZc=+go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=+go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=golang.org/x/arch v0.16.0 h1:foMtLTdyOmIniqWCHjY6+JxuC54XP1fDwx4N0ASyW+U=diff --git a/backend/internal/api/routes.go b/backend/internal/api/routes.goindex ef2fdd46e..a16f35b40 100644--- a/backend/internal/api/routes.go+++ b/backend/internal/api/routes.go@@ -225,9 +225,9 @@ func setupSettingsRoutes(api *gin.RouterGroup, services *Services, appConfig *cosettings.GET("/public", settingsHandler.GetPublicSettings)settings.GET("", settingsHandler.GetSettings)settings.PUT("", settingsHandler.UpdateSettings)- settings.PUT("/auth", settingsHandler.UpdateAuth)- settings.PUT("/onboarding", settingsHandler.UpdateOnboarding)- settings.POST("/registry-credentials", settingsHandler.AddRegistryCredential)+ // settings.PUT("/auth", settingsHandler.UpdateAuth)+ // settings.PUT("/onboarding", settingsHandler.UpdateOnboarding)+ // settings.POST("/registry-credentials", settingsHandler.AddRegistryCredential)oidcHandler := NewOidcHandler(services.Auth, services.Oidc, appConfig)settings.GET("/oidc/status", oidcHandler.GetOidcStatus)settings.GET("/oidc/config", oidcHandler.GetOidcConfig)diff --git a/backend/internal/api/settings_handler.go b/backend/internal/api/settings_handler.goindex 974d2c475..637d92ab7 100644--- a/backend/internal/api/settings_handler.go+++ b/backend/internal/api/settings_handler.go@@ -5,7 +5,6 @@ import ("github.com/gin-gonic/gin""github.com/ofkm/arcane-backend/internal/dto"- "github.com/ofkm/arcane-backend/internal/models""github.com/ofkm/arcane-backend/internal/services")@@ -29,234 +28,88 @@ func (h *SettingsHandler) GetSettings(c *gin.Context) {return}- c.JSON(http.StatusOK, gin.H{- "success": true,- "settings": settings,- })-}--func (h *SettingsHandler) UpdateSettings(c *gin.Context) {- var req dto.UpdateSettingsDto- if err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid request format",- })- return- }-- settings, err := h.settingsService.GetSettings(c.Request.Context())- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to fetch current settings",- })- return- }-- if req.StacksDirectory != nil {- settings.StacksDirectory = *req.StacksDirectory- }- if req.AutoUpdate != nil {- settings.AutoUpdate = *req.AutoUpdate- }- if req.AutoUpdateInterval != nil {- settings.AutoUpdateInterval = *req.AutoUpdateInterval- }- if req.PollingEnabled != nil {- settings.PollingEnabled = *req.PollingEnabled- }- if req.PollingInterval != nil {- settings.PollingInterval = *req.PollingInterval- }- if req.PruneMode != nil {- settings.PruneMode = req.PruneMode- }- if req.RegistryCredentials != nil {- settings.RegistryCredentials = *req.RegistryCredentials- }- if req.TemplateRegistries != nil {- settings.TemplateRegistries = *req.TemplateRegistries- }- if req.Auth != nil {- settings.Auth = *req.Auth- }- if req.Onboarding != nil {- settings.Onboarding = *req.Onboarding- }- if req.BaseServerURL != nil {- settings.BaseServerURL = req.BaseServerURL- }-- updatedSettings, err := h.settingsService.UpdateSettings(c.Request.Context(), settings)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to update settings",- })- return- }+ settingsSlice := settings.ToSettingVariableSlice(true, true)- c.JSON(http.StatusOK, gin.H{- "success": true,- "settings": updatedSettings,- "message": "Settings updated successfully",- })-}--func (h *SettingsHandler) UpdateAuth(c *gin.Context) {- var authSettings models.JSON- if err := c.ShouldBindJSON(&authSettings); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid auth settings format",- })- return- }-- settings, err := h.settingsService.GetSettings(c.Request.Context())- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to fetch settings",- })- return- }-- settings.Auth = authSettings- updatedSettings, err := h.settingsService.UpdateSettings(c.Request.Context(), settings)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to update auth settings",+ settingDtos := make([]dto.SettingDto, 0, len(settingsSlice))+ for _, setting := range settingsSlice {+ _, isPublic, _, _ := settings.FieldByKey(setting.Key)+ settingDtos = append(settingDtos, dto.SettingDto{+ PublicSettingDto: dto.PublicSettingDto{+ Key: setting.Key,+ Type: "string",+ Value: setting.Value,+ IsPublic: isPublic,+ },})- return}c.JSON(http.StatusOK, gin.H{"success": true,- "settings": updatedSettings,- "message": "Auth settings updated successfully",+ "settings": settingDtos,})}-func (h *SettingsHandler) UpdateOnboarding(c *gin.Context) {- var onboardingData models.JSON- if err := c.ShouldBindJSON(&onboardingData); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid onboarding data format",- })- return- }-- settings, err := h.settingsService.GetSettings(c.Request.Context())+func (h *SettingsHandler) GetPublicSettings(c *gin.Context) {+ publicSettings, err := h.settingsService.GetPublicSettings(c.Request.Context())if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to fetch settings",+ "error": "Failed to fetch public settings",})return}- settings.Onboarding = onboardingData- updatedSettings, err := h.settingsService.UpdateSettings(c.Request.Context(), settings)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to update onboarding settings",+ // Convert to DTO format+ settingDtos := make([]dto.PublicSettingDto, 0, len(publicSettings))+ for _, setting := range publicSettings {+ settingDtos = append(settingDtos, dto.PublicSettingDto{+ Key: setting.Key,+ Type: "string", // All stored as strings in new structure+ Value: setting.Value,+ IsPublic: true,})- return}c.JSON(http.StatusOK, gin.H{"success": true,- "settings": updatedSettings,- "message": "Onboarding settings updated successfully",+ "settings": settingDtos,})}-func (h *SettingsHandler) AddRegistryCredential(c *gin.Context) {- type AddRegistryRequest struct {- URL string `json:"url" binding:"required"`- Username string `json:"username" binding:"required"`- Password string `json:"password" binding:"required"`- }-- var req AddRegistryRequest+func (h *SettingsHandler) UpdateSettings(c *gin.Context) {+ var req dto.UpdateSettingsDtoif err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Invalid registry credential format",+ "error": "Invalid request format",})return}- settings, err := h.settingsService.GetSettings(c.Request.Context())+ updatedSettings, err := h.settingsService.UpdateSettings(c.Request.Context(), req)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to fetch settings",+ "error": "Failed to update settings",})return}- credentials := settings.RegistryCredentials- if credentials == nil {- credentials = make(models.JSON)- }-- if credArray, ok := credentials["credentials"].([]interface{}); ok {- newCred := map[string]interface{}{- "url": req.URL,- "username": req.Username,- "password": req.Password,- }- credArray = append(credArray, newCred)- credentials["credentials"] = credArray- } else {- credentials["credentials"] = []interface{}{- map[string]interface{}{- "url": req.URL,- "username": req.Username,- "password": req.Password,+ // Convert to DTO format+ settingDtos := make([]dto.SettingDto, 0, len(updatedSettings))+ for _, setting := range updatedSettings {+ settingDtos = append(settingDtos, dto.SettingDto{+ PublicSettingDto: dto.PublicSettingDto{+ Key: setting.Key,+ Type: "string",+ Value: setting.Value,+ IsPublic: false, // We'll determine this from the struct later if needed},- }- }-- settings.RegistryCredentials = credentials- updatedSettings, err := h.settingsService.UpdateSettings(c.Request.Context(), settings)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to add registry credential",})- return}c.JSON(http.StatusOK, gin.H{"success": true,- "settings": updatedSettings,- "message": "Registry credential added successfully",- })-}--func (h *SettingsHandler) GetPublicSettings(c *gin.Context) {- settings, err := h.settingsService.GetSettings(c.Request.Context())- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to retrieve settings: " + err.Error(),- })- return- }-- publicSettings := map[string]interface{}{- "auth": settings.Auth,- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": publicSettings,+ "settings": settingDtos,})}diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex 30e3ae6c4..c8880d427 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -56,6 +56,14 @@ func InitializeApp() (*App, error) {return nil, fmt.Errorf("services initialization failed: %w", err)}+ slog.InfoContext(appCtx, "Ensuring default settings are initialized")+ if err := appServices.Settings.EnsureDefaultSettings(appCtx); err != nil {+ slog.WarnContext(appCtx, "Failed to initialize default settings",+ slog.String("error", err.Error()))+ } else {+ slog.InfoContext(appCtx, "Default settings initialized successfully")+ }+scheduler, err := initializeScheduler()if err != nil {db.Close()@@ -65,7 +73,7 @@ func InitializeApp() (*App, error) {router := setupRouter(cfg, appServices)- if dockerClient, err := dockerClientService.CreateConnection(context.Background()); err != nil {+ if dockerClient, err := dockerClientService.CreateConnection(appCtx); err != nil {slog.WarnContext(appCtx, "Docker connection failed during init, local Docker features may be unavailable",slog.String("error", err.Error()))} else {@@ -86,7 +94,7 @@ func InitializeApp() (*App, error) {}if cfg.OidcEnabled {- if err := appServices.Auth.SyncOidcEnvToDatabase(context.Background()); err != nil {+ if _, err := appServices.Settings.SyncOidcEnvToDatabase(appCtx); err != nil {slog.WarnContext(appCtx, "Failed to sync OIDC environment variables to database",slog.String("error", err.Error()))}diff --git a/backend/internal/bootstrap/db_bootstrap.go b/backend/internal/bootstrap/db_bootstrap.goindex 4651ad86d..40c01df33 100644--- a/backend/internal/bootstrap/db_bootstrap.go+++ b/backend/internal/bootstrap/db_bootstrap.go@@ -14,11 +14,6 @@ func initializeDBAndMigrate(cfg *config.Config) (*database.DB, error) {return nil, fmt.Errorf("failed to initialize database: %w", err)}- log.Printf("Running database migrations...")- log.Printf("DB URL: %s", cfg.DatabaseURL)- if err := db.Migrate(); err != nil {- db.Close()- return nil, fmt.Errorf("failed to run migrations: %w", err)- }+ log.Printf("Database initialized successfully")return db, nil}diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex 553d40f9d..3948d11f0 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -12,7 +12,7 @@ import (func initializeServices(db *database.DB, cfg *config.Config) (*api.Services, *services.DockerClientService, error) {log.Println("Initializing services...")converterService := services.NewConverterService()- settingsService := services.NewSettingsService(db)+ settingsService := services.NewSettingsService(db, cfg)dockerClientService := services.NewDockerClientService(db)userService := services.NewUserService(db)stackService := services.NewStackService(db, settingsService)diff --git a/backend/internal/database/database.go b/backend/internal/database/database.goindex d7697e971..1552121eb 100644--- a/backend/internal/database/database.go+++ b/backend/internal/database/database.go@@ -1,19 +1,26 @@package databaseimport (+ "errors""fmt""log"+ "log/slog""net/url""os""strings""time"+ "github.com/golang-migrate/migrate/v4"+ "github.com/golang-migrate/migrate/v4/database"+ postgresMigrate "github.com/golang-migrate/migrate/v4/database/postgres"+ sqliteMigrate "github.com/golang-migrate/migrate/v4/database/sqlite3"+ "github.com/golang-migrate/migrate/v4/source/iofs""gorm.io/driver/postgres""gorm.io/driver/sqlite""gorm.io/gorm""gorm.io/gorm/logger"- "github.com/ofkm/arcane-backend/internal/models"+ "github.com/ofkm/arcane-backend/resources")type DB struct {@@ -21,6 +28,92 @@ type DB struct {}func Initialize(databaseURL string, environment string) (*DB, error) {+ // First connect to database+ db, err := connectDatabase(databaseURL, environment)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to database: %w", err)+ }++ // Get underlying sql.DB for migrations+ sqlDB, err := db.DB.DB()+ if err != nil {+ return nil, fmt.Errorf("failed to get sql.DB: %w", err)+ }++ // Determine database provider for migrations+ var dbProvider string+ switch {+ case strings.HasPrefix(databaseURL, "file:"):+ dbProvider = "sqlite"+ case strings.HasPrefix(databaseURL, "postgres"):+ dbProvider = "postgres"+ default:+ return nil, fmt.Errorf("unsupported database type in URL: %s", databaseURL)+ }++ // Choose the correct driver for migrations+ var driver database.Driver+ switch dbProvider {+ case "sqlite":+ driver, err = sqliteMigrate.WithInstance(sqlDB, &sqliteMigrate.Config{})+ case "postgres":+ driver, err = postgresMigrate.WithInstance(sqlDB, &postgresMigrate.Config{})+ default:+ return nil, fmt.Errorf("unsupported database provider: %s", dbProvider)+ }+ if err != nil {+ return nil, fmt.Errorf("failed to create migration driver: %w", err)+ }++ // Run migrations with backup on failure+ if err := migrateDatabase(driver, dbProvider, databaseURL); err != nil {+ slog.Error("Failed to run migrations", "error", err)++ // If migration fails and it's SQLite, try to backup and retry+ if dbProvider == "sqlite" {+ if backupErr := backupSQLiteDatabase(databaseURL); backupErr != nil {+ slog.Error("Failed to backup database", "error", backupErr)+ return nil, fmt.Errorf("failed to run migrations and backup failed: %w", err)+ }++ slog.Info("Database backed up to arcane-db.old, retrying migrations with fresh database")++ // Close current connection+ db.Close()++ // Reconnect and try migrations again+ db, err = connectDatabase(databaseURL, environment)+ if err != nil {+ return nil, fmt.Errorf("failed to reconnect after backup: %w", err)+ }++ sqlDB, err = db.DB.DB()+ if err != nil {+ return nil, fmt.Errorf("failed to get sql.DB after backup: %w", err)+ }++ driver, err = sqliteMigrate.WithInstance(sqlDB, &sqliteMigrate.Config{})+ if err != nil {+ return nil, fmt.Errorf("failed to create migration driver after backup: %w", err)+ }++ if retryErr := migrateDatabase(driver, dbProvider, databaseURL); retryErr != nil {+ return nil, fmt.Errorf("failed to run migrations even after backup: %w", retryErr)+ }+ } else {+ return nil, fmt.Errorf("failed to run migrations: %w", err)+ }+ }++ // Set connection pool settings+ sqlDB.SetMaxIdleConns(10)+ sqlDB.SetMaxOpenConns(100)+ sqlDB.SetConnMaxLifetime(time.Hour)++ return db, nil+}++func connectDatabase(databaseURL string, environment string) (*DB, error) {var dialector gorm.Dialectorswitch {@@ -38,29 +131,92 @@ func Initialize(databaseURL string, environment string) (*DB, error) {gormLogger := getLogger(environment)- db, err := gorm.Open(dialector, &gorm.Config{- Logger: gormLogger,- NowFunc: func() time.Time {- return time.Now().UTC()- },- PrepareStmt: true,- IgnoreRelationshipsWhenMigrating: true,- })+ // Retry connection up to 3 times+ var db *gorm.DB+ var err error+ for i := 1; i <= 3; i++ {+ db, err = gorm.Open(dialector, &gorm.Config{+ Logger: gormLogger,+ NowFunc: func() time.Time {+ return time.Now().UTC()+ },+ PrepareStmt: true,+ IgnoreRelationshipsWhenMigrating: true,+ })+ if err == nil {+ return &DB{db}, nil+ }+ slog.Info("Failed to initialize database", slog.Int("attempt", i))+ if i < 3 {+ time.Sleep(3 * time.Second)+ }+ }++ return nil, err+}++func migrateDatabase(driver database.Driver, dbProvider string, databaseURL string) error {+ // Use the embedded migrations+ source, err := iofs.New(resources.FS, "migrations/"+dbProvider)if err != nil {- return nil, fmt.Errorf("failed to connect to database: %w", err)+ return fmt.Errorf("failed to create embedded migration source: %w", err)}- sqlDB, err := db.DB()+ m, err := migrate.NewWithInstance("iofs", source, "arcane", driver)if err != nil {- return nil, fmt.Errorf("failed to get underlying sql.DB: %w", err)+ return fmt.Errorf("failed to create migration instance: %w", err)}- sqlDB.SetMaxIdleConns(10)- sqlDB.SetMaxOpenConns(100)- sqlDB.SetConnMaxLifetime(time.Hour)+ err = m.Up()+ if err != nil && !errors.Is(err, migrate.ErrNoChange) {+ return fmt.Errorf("failed to apply migrations: %w", err)+ }++ if errors.Is(err, migrate.ErrNoChange) {+ slog.Info("Database schema is up to date")+ } else {+ slog.Info("Database migrations completed successfully")+ }- return &DB{db}, nil+ return nil+}++func backupSQLiteDatabase(databaseURL string) error {+ // Extract file path from SQLite URL+ connStringUrl, err := url.Parse(databaseURL)+ if err != nil {+ return fmt.Errorf("failed to parse database URL: %w", err)+ }++ dbPath := connStringUrl.Path+ if dbPath == "" {+ return fmt.Errorf("empty database path in URL")+ }++ // Check if database file exists+ if _, err := os.Stat(dbPath); os.IsNotExist(err) {+ // Database doesn't exist, no need to backup+ slog.Info("Database file doesn't exist, no backup needed")+ return nil+ }++ backupPath := strings.TrimSuffix(dbPath, ".db") + ".old"++ // Remove existing backup if it exists+ if _, err := os.Stat(backupPath); err == nil {+ if err := os.Remove(backupPath); err != nil {+ return fmt.Errorf("failed to remove existing backup: %w", err)+ }+ }++ // Move current database to backup+ if err := os.Rename(dbPath, backupPath); err != nil {+ return fmt.Errorf("failed to backup database: %w", err)+ }++ slog.Info("Database backed up successfully", "backup_path", backupPath)+ return nil}func parseSqliteConnectionString(connString string) (string, error) {@@ -76,14 +232,22 @@ func parseSqliteConnectionString(connString string) (string, error) {qs := make(url.Values, len(connStringUrl.Query()))for k, v := range connStringUrl.Query() {switch k {- case "_journal_mode":- qs.Add("_pragma", "journal_mode("+v[0]+")")+ case "_auto_vacuum", "_vacuum":+ qs.Add("_pragma", "auto_vacuum("+v[0]+")")case "_busy_timeout", "_timeout":qs.Add("_pragma", "busy_timeout("+v[0]+")")+ case "_case_sensitive_like", "_cslike":+ qs.Add("_pragma", "case_sensitive_like("+v[0]+")")case "_foreign_keys", "_fk":qs.Add("_pragma", "foreign_keys("+v[0]+")")+ case "_locking_mode", "_locking":+ qs.Add("_pragma", "locking_mode("+v[0]+")")+ case "_secure_delete":+ qs.Add("_pragma", "secure_delete("+v[0]+")")case "_synchronous", "_sync":qs.Add("_pragma", "synchronous("+v[0]+")")+ case "_journal_mode":+ qs.Add("_pragma", "journal_mode("+v[0]+")")case "_txlock":qs.Add("_txlock", v[0])default:@@ -109,7 +273,7 @@ func getLogger(environment string) logger.Interface {return logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags),logger.Config{- SlowThreshold: time.Second,+ SlowThreshold: 200 * time.Millisecond,LogLevel: logLevel,IgnoreRecordNotFoundError: true,Colorful: environment == "development",@@ -117,31 +281,6 @@ func getLogger(environment string) logger.Interface {)}-func (db *DB) Migrate() error {- err := db.AutoMigrate(- &models.Settings{},- &models.User{},- &models.UserSession{},- &models.Stack{},- &models.Environment{},- &models.Container{},- &models.Image{},- &models.Volume{},- &models.Network{},- &models.ImageUpdateRecord{},- &models.TemplateRegistry{},- &models.ComposeTemplate{},- &models.ContainerRegistry{},- &models.AutoUpdateRecord{},- )-- if err != nil {- return fmt.Errorf("failed to migrate database: %w", err)- }-- return nil-}-func (db *DB) Close() error {sqlDB, err := db.DB.DB()if err != nil {diff --git a/backend/internal/dto/settings_dto.go b/backend/internal/dto/settings_dto.goindex 7ccdc7537..d1c8fb917 100644--- a/backend/internal/dto/settings_dto.go+++ b/backend/internal/dto/settings_dto.go@@ -1,17 +1,39 @@package dto-import "github.com/ofkm/arcane-backend/internal/models"+type PublicSettingDto struct {+ Key string `json:"key"`+ Type string `json:"type"`+ Value string `json:"value"`+ IsPublic bool `json:"isPublic"`+}++type SettingDto struct {+ PublicSettingDto+}type UpdateSettingsDto struct {- StacksDirectory *string `json:"stacksDirectory,omitempty"`- AutoUpdate *bool `json:"autoUpdate,omitempty"`- AutoUpdateInterval *int `json:"autoUpdateInterval,omitempty"`- PollingEnabled *bool `json:"pollingEnabled,omitempty"`- PollingInterval *int `json:"pollingInterval,omitempty"`- PruneMode *string `json:"pruneMode,omitempty"`- RegistryCredentials *models.JSON `json:"registryCredentials,omitempty"`- TemplateRegistries *models.JSON `json:"templateRegistries,omitempty"`- Auth *models.JSON `json:"auth,omitempty"`- Onboarding *models.JSON `json:"onboarding,omitempty"`- BaseServerURL *string `json:"baseServerUrl,omitempty"`+ // Core settings+ StacksDirectory *string `json:"stacksDirectory,omitempty"`+ AutoUpdate *string `json:"autoUpdate,omitempty"`+ AutoUpdateInterval *string `json:"autoUpdateInterval,omitempty"`+ PollingEnabled *string `json:"pollingEnabled,omitempty"`+ PollingInterval *string `json:"pollingInterval,omitempty"`+ PruneMode *string `json:"pruneMode,omitempty"`+ BaseServerURL *string `json:"baseServerUrl,omitempty"`++ // Authentication settings+ AuthLocalEnabled *string `json:"authLocalEnabled,omitempty"`+ AuthOidcEnabled *string `json:"authOidcEnabled,omitempty"`+ AuthSessionTimeout *string `json:"authSessionTimeout,omitempty"`+ AuthPasswordPolicy *string `json:"authPasswordPolicy,omitempty"`+ AuthRbacEnabled *string `json:"authRbacEnabled,omitempty"`+ AuthOidcConfig *string `json:"authOidcConfig,omitempty"`++ // Onboarding settings+ OnboardingCompleted *string `json:"onboardingCompleted,omitempty"`+ OnboardingSteps *string `json:"onboardingSteps,omitempty"`++ // Registry settings+ RegistryCredentials *string `json:"registryCredentials,omitempty"`+ TemplateRegistries *string `json:"templateRegistries,omitempty"`}diff --git a/backend/internal/job/auto_update_job.go b/backend/internal/job/auto_update_job.goindex 26cdef1b2..0cd828ea5 100644--- a/backend/internal/job/auto_update_job.go+++ b/backend/internal/job/auto_update_job.go@@ -22,70 +22,16 @@ func NewAutoUpdateJob(autoUpdateService *services.AutoUpdateService, settingsSer}}-func (j *AutoUpdateJob) Execute(ctx context.Context) error {- log.Println("=== Starting scheduled auto-update check ===")-- settings, err := j.settingsService.GetSettings(ctx)- if err != nil {- log.Printf("Failed to get settings during scheduled update: %v", err)- return err- }-- if !settings.AutoUpdate {- log.Println("Auto-update disabled, skipping scheduled check")- return nil- }-- // Use image-based approach for scheduled updates- req := dto.AutoUpdateCheckDto{- Type: "all", // This will trigger image-based updates- ForceUpdate: false,- DryRun: false,- }-- result, err := j.autoUpdateService.CheckForUpdates(ctx, req)- if err != nil {- log.Printf("Error during auto-update: %v", err)- return err- }-- log.Printf("Auto-update completed: %d checked, %d updated, %d skipped, %d failed",- result.Checked, result.Updated, result.Skipped, result.Failed)-- if result.Failed > 0 {- log.Printf("Auto-update had %d failures", result.Failed)- for _, res := range result.Results {- if res.Error != "" {- log.Printf("Failed to update %s (%s): %s", res.ResourceName, res.ResourceType, res.Error)- }- }- }-- if result.Updated > 0 {- log.Printf("Successfully updated %d resources", result.Updated)- for _, res := range result.Results {- if res.UpdateApplied {- log.Printf("Updated %s (%s)", res.ResourceName, res.ResourceType)- }- }- }-- log.Println("=== Scheduled auto-update check completed ===")- return nil-}-func RegisterAutoUpdateJob(ctx context.Context, scheduler *Scheduler, autoUpdateService *services.AutoUpdateService, settingsService *services.SettingsService) error {- settings, err := settingsService.GetSettings(ctx)- if err != nil {- return err- }+ autoUpdateEnabled := settingsService.GetBoolSetting(ctx, "autoUpdateEnabled", false)+ autoUpdateInterval := settingsService.GetIntSetting(ctx, "autoUpdateInterval", 300)- if !settings.AutoUpdate {+ if !autoUpdateEnabled {log.Println("Auto-update is disabled, not registering auto-update job")return nil}- interval := time.Duration(settings.AutoUpdateInterval) * time.Minute+ interval := time.Duration(autoUpdateInterval) * time.Secondif interval < 5*time.Minute {interval = 60 * time.Minutelog.Printf("Auto-update interval too low, using default 60 minutes")@@ -106,18 +52,45 @@ func RegisterAutoUpdateJob(ctx context.Context, scheduler *Scheduler, autoUpdate)}-func UpdateAutoUpdateJobSchedule(ctx context.Context, scheduler *Scheduler, autoUpdateService *services.AutoUpdateService, settingsService *services.SettingsService) error {+func (j *AutoUpdateJob) Execute(ctx context.Context) error {+ log.Println("=== Starting scheduled auto-update check ===")- settings, err := settingsService.GetSettings(ctx)+ // Get individual settings+ autoUpdateEnabled := j.settingsService.GetBoolSetting(ctx, "autoUpdateEnabled", false)++ if !autoUpdateEnabled {+ log.Println("Auto-update disabled, skipping scheduled check")+ return nil+ }++ req := dto.AutoUpdateCheckDto{+ Type: "all",+ ForceUpdate: false,+ DryRun: false,+ }++ result, err := j.autoUpdateService.CheckForUpdates(ctx, req)if err != nil {+ log.Printf("Error during auto-update: %v", err)return err}- if !settings.AutoUpdate {+ log.Printf("Auto-update completed: %d checked, %d updated, %d skipped, %d failed",+ result.Checked, result.Updated, result.Skipped, result.Failed)++ return nil+}++func UpdateAutoUpdateJobSchedule(ctx context.Context, scheduler *Scheduler, autoUpdateService *services.AutoUpdateService, settingsService *services.SettingsService) error {+ autoUpdateEnabled := settingsService.GetBoolSetting(ctx, "autoUpdateEnabled", false)+ autoUpdateInterval := settingsService.GetIntSetting(ctx, "autoUpdateInterval", 300)++ if !autoUpdateEnabled {log.Println("Auto-update disabled, job will be skipped")return nil}- interval := time.Duration(settings.AutoUpdateInterval) * time.Minute++ interval := time.Duration(autoUpdateInterval) * time.Secondlog.Printf("Auto-update settings changed - new interval: %v", interval)return nildiff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex 0389da0bd..39e824c02 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -1,27 +1,183 @@package models-type AuthSettings struct {- LocalAuthEnabled bool `json:"localAuthEnabled"`- OidcEnabled bool `json:"oidcEnabled"`- SessionTimeout int `json:"sessionTimeout"`- PasswordPolicy string `json:"passwordPolicy"`- RbacEnabled bool `json:"rbacEnabled"`- Oidc *OidcConfig `json:"oidc,omitempty"`+import (+ "errors"+ "fmt"+ "reflect"+ "slices"+ "strconv"+ "strings"+ "time"+)++type SettingVariable struct {+ Key string `gorm:"primaryKey;not null"`+ Value string}-type OidcConfig struct {- ClientID string `json:"clientId"`- ClientSecret string `json:"clientSecret"`- IssuerURL string `json:"issuerUrl"`- Scopes string `json:"scopes"`+// IsTrue returns true if the value is a truthy string+func (s *SettingVariable) IsTrue() bool {+ ok, _ := strconv.ParseBool(s.Value)+ return ok+}- // These will be auto-discovered and cached- AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`- TokenEndpoint string `json:"tokenEndpoint,omitempty"`- UserinfoEndpoint string `json:"userinfoEndpoint,omitempty"`- JwksURI string `json:"jwksUri,omitempty"`+// AsInt returns the value as an integer+func (s *SettingVariable) AsInt() int {+ val, _ := strconv.Atoi(s.Value)+ return val+}++// AsDurationSeconds returns the value as a time.Duration in seconds+func (s *SettingVariable) AsDurationSeconds() time.Duration {+ val, err := strconv.Atoi(s.Value)+ if err != nil {+ return 0+ }+ return time.Duration(val) * time.Second+}++type Settings struct {+ // Docker+ StacksDirectory SettingVariable `key:"stacksDirectory"`+ AutoUpdate SettingVariable `key:"autoUpdate"`+ AutoUpdateInterval SettingVariable `key:"autoUpdateInterval"`+ PollingEnabled SettingVariable `key:"pollingEnabled"`+ PollingInterval SettingVariable `key:"pollingInterval"`+ PruneMode SettingVariable `key:"dockerPruneMode"`+ BaseServerURL SettingVariable `key:"baseServerUrl"`++ // Authentication+ AuthLocalEnabled SettingVariable `key:"authLocalEnabled,public"`+ AuthOidcEnabled SettingVariable `key:"authOidcEnabled,public"`+ AuthSessionTimeout SettingVariable `key:"authSessionTimeout"`+ AuthPasswordPolicy SettingVariable `key:"authPasswordPolicy"`+ AuthRbacEnabled SettingVariable `key:"authRbacEnabled"`+ AuthOidcConfig SettingVariable `key:"authOidcConfig,sensitive"`++ // Onboarding+ OnboardingCompleted SettingVariable `key:"onboardingCompleted,public"`+ OnboardingSteps SettingVariable `key:"onboardingSteps"`++ // Registries+ RegistryCredentials SettingVariable `key:"registryCredentials,sensitive"`+ TemplateRegistries SettingVariable `key:"templateRegistries"`+}++func (SettingVariable) TableName() string {+ return "settings"+}++func (s *Settings) ToSettingVariableSlice(showAll bool, redactSensitiveValues bool) []SettingVariable {+ cfgValue := reflect.ValueOf(s).Elem()+ cfgType := cfgValue.Type()++ var res []SettingVariable++ for i := range cfgType.NumField() {+ field := cfgType.Field(i)++ key, attrs, _ := strings.Cut(field.Tag.Get("key"), ",")+ if key == "" {+ continue+ }++ if !showAll && attrs != "public" {+ continue+ }++ value := cfgValue.Field(i).FieldByName("Value").String()++ // Redact sensitive values if requested+ if value != "" && redactSensitiveValues && attrs == "sensitive" {+ value = "XXXXXXXXXX"+ }++ settingVariable := SettingVariable{+ Key: key,+ Value: value,+ }++ res = append(res, settingVariable)+ }++ return res+}++func (s *Settings) FieldByKey(key string) (defaultValue string, isPublic bool, isSensitive bool, err error) {+ rv := reflect.ValueOf(s).Elem()+ rt := rv.Type()++ for i := range rt.NumField() {+ tagValue := strings.Split(rt.Field(i).Tag.Get("key"), ",")+ keyFromTag := tagValue[0]+ isPublic = slices.Contains(tagValue, "public")+ isSensitive = slices.Contains(tagValue, "sensitive")++ if keyFromTag != key {+ continue+ }++ valueField := rv.Field(i).FieldByName("Value")+ return valueField.String(), isPublic, isSensitive, nil+ }++ return "", false, false, SettingKeyNotFoundError{field: key}+}++func (s *Settings) UpdateField(key string, value string, noSensitive bool) error {+ rv := reflect.ValueOf(s).Elem()+ rt := rv.Type()++ for i := range rt.NumField() {+ tagValue, attrs, _ := strings.Cut(rt.Field(i).Tag.Get("key"), ",")+ if tagValue != key {+ continue+ }++ // If the field is sensitive and noSensitive is true, we skip that+ if noSensitive && attrs == "sensitive" {+ return SettingSensitiveForbiddenError{field: key}+ }++ valueField := rv.Field(i).FieldByName("Value")+ if !valueField.CanSet() {+ return fmt.Errorf("field Value in SettingVariable is not settable for config key '%s'", key)+ }++ valueField.SetString(value)+ return nil+ }++ return SettingKeyNotFoundError{field: key}+}++type SettingKeyNotFoundError struct {+ field string+}++func (e SettingKeyNotFoundError) Error() string {+ return "cannot find setting key '" + e.field + "'"+}++func (e SettingKeyNotFoundError) Is(target error) bool {+ x := SettingKeyNotFoundError{}+ return errors.As(target, &x)}+type SettingSensitiveForbiddenError struct {+ field string+}++func (e SettingSensitiveForbiddenError) Error() string {+ return "field '" + e.field + "' is sensitive and can't be updated"+}++func (e SettingSensitiveForbiddenError) Is(target error) bool {+ x := SettingSensitiveForbiddenError{}+ return errors.As(target, &x)+}++// Legacy types for backward compatibilitytype RegistryCredential struct {URL string `json:"url"`Username string `json:"username"`@@ -36,33 +192,14 @@ type TemplateRegistryConfig struct {CacheTTL *int `json:"cacheTtl,omitempty"`}-type Onboarding struct {- Completed bool `json:"completed"`- CompletedAt *int64 `json:"completedAt,omitempty"`- Steps *struct {- Welcome *bool `json:"welcome,omitempty"`- Password *bool `json:"password,omitempty"`- Settings *bool `json:"settings,omitempty"`- } `json:"steps,omitempty"`-}+type OidcConfig struct {+ ClientID string `json:"clientId"`+ ClientSecret string `json:"clientSecret"`+ IssuerURL string `json:"issuerUrl"`+ Scopes string `json:"scopes"`-type Settings struct {- ID uint `json:"id" gorm:"primaryKey;autoIncrement"`- DockerTLSCert string `json:"dockerTLSCert" gorm:"column:docker_tls_cert"`- StacksDirectory string `json:"stacksDirectory" gorm:"column:stacks_directory;not null"`- AutoUpdate bool `json:"autoUpdate" gorm:"column:auto_update;default:false"`- AutoUpdateInterval int `json:"autoUpdateInterval" gorm:"column:auto_update_interval;default:300"`- PollingEnabled bool `json:"pollingEnabled" gorm:"column:polling_enabled;default:true"`- PollingInterval int `json:"pollingInterval" gorm:"column:polling_interval;default:5"`- PruneMode *string `json:"pruneMode,omitempty" gorm:"column:prune_mode"`- RegistryCredentials JSON `json:"registryCredentials" gorm:"type:text;column:registry_credentials;default:'[]'"`- TemplateRegistries JSON `json:"templateRegistries" gorm:"type:text;column:template_registries;default:'[]'"`- Auth JSON `json:"auth" gorm:"type:text;not null"`- Onboarding JSON `json:"onboarding,omitempty" gorm:"type:text"`- BaseServerURL *string `json:"baseServerUrl,omitempty" gorm:"column:base_server_url"`- BaseModel-}--func (Settings) TableName() string {- return "settings_table"+ AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`+ TokenEndpoint string `json:"tokenEndpoint,omitempty"`+ UserinfoEndpoint string `json:"userinfoEndpoint,omitempty"`+ JwksURI string `json:"jwksUri,omitempty"`}diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.goindex 42cf54f88..a2dac7dde 100644--- a/backend/internal/services/auth_service.go+++ b/backend/internal/services/auth_service.go@@ -7,13 +7,14 @@ import ("encoding/json""errors""fmt"- "log""strings""time""github.com/golang-jwt/jwt/v5""github.com/ofkm/arcane-backend/internal/config"+ "github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/models"+ "github.com/ofkm/arcane-backend/internal/utils")// Common errors@@ -80,7 +81,6 @@ type AuthService struct {config *config.Config}-// NewAuthService creates a new auth service instancefunc NewAuthService(userService *UserService, settingsService *SettingsService, jwtSecret string, cfg *config.Config) *AuthService {var secretBytes []byteif jwtSecret != "" {@@ -102,88 +102,27 @@ func NewAuthService(userService *UserService, settingsService *SettingsService,}}-func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {- if !s.config.OidcEnabled {- return errors.New("OIDC sync called but OIDC_ENABLED is false")- }-+func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error) {settings, err := s.settingsService.GetSettings(ctx)if err != nil {- return fmt.Errorf("failed to get settings for OIDC sync: %w", err)- }-- var currentAuthMap map[string]interface{}- if len(settings.Auth) > 0 {- currentAuthMap = make(map[string]interface{})- for k, v := range settings.Auth {- currentAuthMap[k] = v- }- } else {- currentAuthMap = make(map[string]interface{})- }-- envOidcConfig := models.OidcConfig{- ClientID: s.config.OidcClientID,- ClientSecret: s.config.OidcClientSecret,- IssuerURL: s.config.OidcIssuerURL,- Scopes: s.config.OidcScopes,- }-- oidcConfigBytes, err := json.Marshal(envOidcConfig)- if err != nil {- return fmt.Errorf("failed to marshal OIDC config from env: %w", err)- }- var oidcConfigMap map[string]interface{}- if err := json.Unmarshal(oidcConfigBytes, &oidcConfigMap); err != nil {- return fmt.Errorf("failed to unmarshal OIDC config map from env: %w", err)- }-- // Update the auth map- currentAuthMap["oidcEnabled"] = true- currentAuthMap["oidc"] = oidcConfigMap-- settings.Auth = models.JSON(currentAuthMap)-- _, err = s.settingsService.UpdateSettings(ctx, settings)- if err != nil {- return fmt.Errorf("failed to update settings in DB with OIDC env config: %w", err)+ return nil, fmt.Errorf("failed to get settings: %w", err)}- return nil-}--func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error) {- dbSettings, err := s.settingsService.GetSettings(ctx)- if err != nil {- return nil, err+ authSettings := &AuthSettings{+ LocalAuthEnabled: settings.AuthLocalEnabled.IsTrue(),+ OidcEnabled: settings.AuthOidcEnabled.IsTrue(),+ SessionTimeout: settings.AuthSessionTimeout.AsInt() / 60, // Convert seconds to minutes}- var effectiveAuthSettings AuthSettings- if len(dbSettings.Auth) > 0 {- authBytes, err := json.Marshal(dbSettings.Auth)- if err != nil {- log.Printf("Error marshalling auth settings from DB: %v. DB Auth: %v", err, dbSettings.Auth)- return nil, fmt.Errorf("failed to marshal auth settings from DB: %w. Value: %v", err, dbSettings.Auth)+ // Parse OIDC config from JSON if enabled+ if authSettings.OidcEnabled && settings.AuthOidcConfig.Value != "" {+ var oidcConfig models.OidcConfig+ if err := json.Unmarshal([]byte(settings.AuthOidcConfig.Value), &oidcConfig); err == nil {+ authSettings.Oidc = &oidcConfig}- if err := json.Unmarshal(authBytes, &effectiveAuthSettings); err != nil {- log.Printf("Error unmarshalling auth settings from DB: %v. DB Auth JSON: %s", err, string(authBytes))- return nil, fmt.Errorf("failed to unmarshal auth settings from DB: %w. JSON: %s", err, string(authBytes))- }- } else {- log.Println("Auth settings not found or empty in DB, returning default auth settings.")- return &AuthSettings{- LocalAuthEnabled: true,- OidcEnabled: false,- SessionTimeout: 60,- Oidc: nil,- }, nil- }-- if s.config.OidcEnabled && !effectiveAuthSettings.OidcEnabled {- log.Printf("Warning: PUBLIC_OIDC_ENABLED is true, but effective OIDC settings from DB show oidcEnabled=false. This might indicate an issue with the initial sync or subsequent manual changes.")}- return &effectiveAuthSettings, nil+ return authSettings, nil}func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*OidcStatusInfo, error) {@@ -215,39 +154,45 @@ func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*OidcStatreturn status, nil}-func (s *AuthService) updateAuthSettings(ctx context.Context, authSettings *AuthSettings) error {- settings, err := s.settingsService.GetSettings(ctx)- if err != nil {- return err+func (s *AuthService) updateAuthSettings(ctx context.Context, authSettings *AuthSettings) ([]models.SettingVariable, error) {+ // Convert minutes to seconds for timeout+ timeoutSeconds := authSettings.SessionTimeout * 60++ updates := dto.UpdateSettingsDto{+ AuthLocalEnabled: utils.Ptr(fmt.Sprintf("%t", authSettings.LocalAuthEnabled)),+ AuthOidcEnabled: utils.Ptr(fmt.Sprintf("%t", authSettings.OidcEnabled)),+ AuthSessionTimeout: utils.Ptr(fmt.Sprintf("%d", timeoutSeconds)),}- authBytes, err := json.Marshal(authSettings)- if err != nil {- return fmt.Errorf("failed to marshal auth settings: %w", err)+ // Add OIDC config if present+ if authSettings.Oidc != nil {+ oidcConfigBytes, err := json.Marshal(authSettings.Oidc)+ if err != nil {+ return nil, fmt.Errorf("failed to marshal OIDC config: %w", err)+ }+ updates.AuthOidcConfig = utils.Ptr(string(oidcConfigBytes))}- var authMap map[string]interface{}- if err := json.Unmarshal(authBytes, &authMap); err != nil {- return fmt.Errorf("failed to unmarshal to map: %w", err)+ settings, err := s.settingsService.UpdateSettings(ctx, updates)+ if err != nil {+ return nil, fmt.Errorf("failed to update auth settings: %w", err)}- settings.Auth = models.JSON(authMap)- _, err = s.settingsService.UpdateSettings(ctx, settings)- return err+ return settings, nil}// GetSessionTimeout returns the configured session timeout in minutesfunc (s *AuthService) GetSessionTimeout(ctx context.Context) (int, error) {- authSettings, err := s.getAuthSettings(ctx)+ settings, err := s.settingsService.GetSettings(ctx)if err != nil {- return 1440, err+ return 60, err // Default 60 minutes}- if authSettings.SessionTimeout <= 0 {- return 1440, nil+ timeoutSeconds := settings.AuthSessionTimeout.AsInt()+ if timeoutSeconds == 0 {+ timeoutSeconds = 3600 // Default 1 hour}-- return authSettings.SessionTimeout, nil+ return timeoutSeconds / 60, nil}func (s *AuthService) UpdateSessionTimeout(ctx context.Context, minutes int) error {@@ -255,33 +200,23 @@ func (s *AuthService) UpdateSessionTimeout(ctx context.Context, minutes int) errreturn errors.New("session timeout must be positive")}- authSettings, err := s.getAuthSettings(ctx)- if err != nil {- return err- }-- authSettings.SessionTimeout = minutes- return s.updateAuthSettings(ctx, authSettings)+ return s.settingsService.UpdateSetting(ctx, "authSessionTimeout", fmt.Sprintf("%d", minutes*60))}-// IsLocalAuthEnabled checks if local authentication is enabledfunc (s *AuthService) IsLocalAuthEnabled(ctx context.Context) (bool, error) {- authSettings, err := s.getAuthSettings(ctx)+ settings, err := s.settingsService.GetSettings(ctx)if err != nil {- return false, err+ return true, err // Default to enabled}-- return authSettings.LocalAuthEnabled, nil+ return settings.AuthLocalEnabled.IsTrue(), nil}-// IsOidcEnabled checks if OIDC authentication is enabledfunc (s *AuthService) IsOidcEnabled(ctx context.Context) (bool, error) {- authSettings, err := s.getAuthSettings(ctx)+ settings, err := s.settingsService.GetSettings(ctx)if err != nil {return false, err}-- return authSettings.OidcEnabled, nil+ return settings.AuthOidcEnabled.IsTrue(), nil}// GetOidcConfig retrieves the OIDC configuration@@ -298,40 +233,23 @@ func (s *AuthService) GetOidcConfig(ctx context.Context) (*models.OidcConfig, erreturn authSettings.Oidc, nil}-// SetLocalAuthEnabled enables or disables local authenticationfunc (s *AuthService) SetLocalAuthEnabled(ctx context.Context, enabled bool) error {- authSettings, err := s.getAuthSettings(ctx)- if err != nil {- return err- }-- authSettings.LocalAuthEnabled = enabled- return s.updateAuthSettings(ctx, authSettings)+ return s.settingsService.UpdateSetting(ctx, "authLocalEnabled", fmt.Sprintf("%t", enabled))}-// SetOidcEnabled enables or disables OIDC authenticationfunc (s *AuthService) SetOidcEnabled(ctx context.Context, enabled bool) error {- authSettings, err := s.getAuthSettings(ctx)- if err != nil {- return err- }-- authSettings.OidcEnabled = enabled- return s.updateAuthSettings(ctx, authSettings)+ return s.settingsService.UpdateSetting(ctx, "authOidcEnabled", fmt.Sprintf("%t", enabled))}-// UpdateOidcConfig updates the OIDC configurationfunc (s *AuthService) UpdateOidcConfig(ctx context.Context, oidcConfig *models.OidcConfig) error {- authSettings, err := s.getAuthSettings(ctx)+ oidcConfigBytes, err := json.Marshal(oidcConfig)if err != nil {- return err+ return fmt.Errorf("failed to marshal OIDC config: %w", err)}- authSettings.Oidc = oidcConfig- return s.updateAuthSettings(ctx, authSettings)+ return s.settingsService.UpdateSetting(ctx, "authOidcConfig", string(oidcConfigBytes))}-// Login authenticates a user with username and passwordfunc (s *AuthService) Login(ctx context.Context, username, password string) (*models.User, *TokenPair, error) {localEnabled, err := s.IsLocalAuthEnabled(ctx)if err != nil {diff --git a/backend/internal/services/auto_update_service.go b/backend/internal/services/auto_update_service.goindex 35515d617..43650a9ab 100644--- a/backend/internal/services/auto_update_service.go+++ b/backend/internal/services/auto_update_service.go@@ -71,28 +71,24 @@ func (s *AutoUpdateService) CheckForUpdates(ctx context.Context, req dto.AutoUpdResults: []dto.AutoUpdateResourceResult{},}- settings, err := s.settingsService.GetSettings(ctx)- if err != nil {- return nil, fmt.Errorf("failed to get settings: %w", err)- }+ // Get individual setting instead of full settings struct+ autoUpdateEnabled := s.settingsService.GetBoolSetting(ctx, "autoUpdateEnabled", false)- if !settings.AutoUpdate && !req.ForceUpdate {+ if !autoUpdateEnabled && !req.ForceUpdate {result.Skipped = 1result.EndTime = time.Now().Format(time.RFC3339)result.Duration = time.Since(startTime).String()return result, nil}- // Use image-based update approach instead of checking containers individually+ // Use image-based update approachif req.Type == "" || req.Type == "all" || req.Type == "images" {- if err := s.processImageUpdates(ctx, req, result, settings); err != nil {+ if err := s.processImageUpdates(ctx, req, result); err != nil {log.Printf("Image update process failed, falling back to container-based approach: %v", err)- // Fall back to original approach- return s.processContainerBasedUpdates(ctx, req, result, settings, startTime)+ return s.processContainerBasedUpdates(ctx, req, result, startTime)}} else {- // For specific container/stack requests, use original approach- return s.processContainerBasedUpdates(ctx, req, result, settings, startTime)+ return s.processContainerBasedUpdates(ctx, req, result, startTime)}result.EndTime = time.Now().Format(time.RFC3339)@@ -101,7 +97,7 @@ func (s *AutoUpdateService) CheckForUpdates(ctx context.Context, req dto.AutoUpd}// New method to handle image-based updates-func (s *AutoUpdateService) processImageUpdates(ctx context.Context, req dto.AutoUpdateCheckDto, result *dto.AutoUpdateResultDto, settings *models.Settings) error {+func (s *AutoUpdateService) processImageUpdates(ctx context.Context, req dto.AutoUpdateCheckDto, result *dto.AutoUpdateResultDto) error {imageUpdates, err := s.imageUpdateService.CheckAllImages(ctx, 0)if err != nil {return fmt.Errorf("failed to check image updates: %w", err)@@ -187,7 +183,7 @@ func (s *AutoUpdateService) processImageUpdates(ctx context.Context, req dto.Aut}// Refactored method to handle container-based updates (original approach)-func (s *AutoUpdateService) processContainerBasedUpdates(ctx context.Context, req dto.AutoUpdateCheckDto, result *dto.AutoUpdateResultDto, settings *models.Settings, startTime time.Time) (*dto.AutoUpdateResultDto, error) {+func (s *AutoUpdateService) processContainerBasedUpdates(ctx context.Context, req dto.AutoUpdateCheckDto, result *dto.AutoUpdateResultDto, startTime time.Time) (*dto.AutoUpdateResultDto, error) {var wg sync.WaitGroupresultsChan := make(chan dto.AutoUpdateResourceResult, 1000)errorsChan := make(chan error, 100)@@ -201,7 +197,7 @@ func (s *AutoUpdateService) processContainerBasedUpdates(ctx context.Context, rewg.Add(1)go func() {defer wg.Done()- s.checkContainers(ctx, req, settings, resultsChan, errorsChan)+ s.checkContainers(ctx, req, resultsChan, errorsChan)}()}@@ -209,7 +205,7 @@ func (s *AutoUpdateService) processContainerBasedUpdates(ctx context.Context, rewg.Add(1)go func() {defer wg.Done()- s.checkStacks(ctx, req, settings, resultsChan, errorsChan)+ s.checkStacks(ctx, req, resultsChan, errorsChan)}()}@@ -341,8 +337,7 @@ func (s *AutoUpdateService) restartContainersUsingImages(ctx context.Context, ups.updatingContainers[cnt.ID] = trues.mutex.Unlock()- // Use existing updateContainerWithLatestImage method- if err := s.updateContainerWithLatestImage(ctx, cnt, containerJSON, newImageRef, nil); err != nil {+ if err := s.updateContainerWithLatestImage(ctx, cnt, containerJSON, newImageRef); err != nil {result.Status = "failed"result.Error = fmt.Sprintf("Failed to restart container: %v", err)} else {@@ -376,7 +371,6 @@ func (s *AutoUpdateService) imageMatches(containerImage, updatedImage string) bofunc (s *AutoUpdateService) checkContainers(ctx context.Context,req dto.AutoUpdateCheckDto,- settings *models.Settings,results chan<- dto.AutoUpdateResourceResult,errors chan<- error,) {@@ -402,7 +396,7 @@ func (s *AutoUpdateService) checkContainers(continue}- result := s.checkSingleContainer(ctx, cnt, settings, req.DryRun)+ result := s.checkSingleContainer(ctx, cnt, req.DryRun)results <- result}}@@ -410,7 +404,6 @@ func (s *AutoUpdateService) checkContainers(func (s *AutoUpdateService) checkSingleContainer(ctx context.Context,cnt container.Summary,- settings *models.Settings,dryRun bool,) dto.AutoUpdateResourceResult {containerName := s.getContainerName(cnt)@@ -458,7 +451,6 @@ func (s *AutoUpdateService) checkSingleContainer(imageRef := containerJSON.Config.Imageresult.OldImages["main"] = fmt.Sprintf("%s@%s", imageRef, cnt.ImageID)- // Use ImageUpdateService to check for updatesupdateResult, err := s.imageUpdateService.CheckImageUpdate(ctx, imageRef)if err != nil {result.Status = "failed"@@ -474,16 +466,17 @@ func (s *AutoUpdateService) checkSingleContainer(result.UpdateAvailable = updateResult.HasUpdateif updateResult.HasUpdate {- // Set the new image reference based on update typenewImageRef := imageRefif updateResult.UpdateType == "tag" && updateResult.LatestVersion != "" {- // For tag updates, construct new image reference with latest tagnewImageRef = s.constructImageRefWithTag(imageRef, updateResult.LatestVersion)}result.NewImages["main"] = newImageRef- if !dryRun && settings.AutoUpdate {- if err := s.updateContainerWithLatestImage(ctx, cnt, containerJSON, newImageRef, settings); err != nil {+ // Get auto update setting when needed+ autoUpdateEnabled := s.settingsService.GetBoolSetting(ctx, "autoUpdateEnabled", false)++ if !dryRun && autoUpdateEnabled {+ if err := s.updateContainerWithLatestImage(ctx, cnt, containerJSON, newImageRef); err != nil {result.Status = "failed"result.Error = fmt.Sprintf("Failed to update container: %v", err)return result@@ -500,13 +493,11 @@ func (s *AutoUpdateService) checkSingleContainer(return result}-// New method to update container with latest imagefunc (s *AutoUpdateService) updateContainerWithLatestImage(ctx context.Context,cnt container.Summary,containerJSON container.InspectResponse,newImageRef string,- settings *models.Settings,) error {dockerClient, err := s.dockerService.CreateConnection(ctx)if err != nil {@@ -518,13 +509,10 @@ func (s *AutoUpdateService) updateContainerWithLatestImage(pullOptions := image.PullOptions{}- // Use existing getAuthConfigForImage methodauthConfig, err := s.getAuthConfigForImage(ctx, newImageRef)if err != nil {log.Printf("Warning: Failed to get auth config for image %s: %v", newImageRef, err)- // Continue without authentication - may work for public registries} else if authConfig != nil {- // Encode auth config for Docker APIauthJSON, err := json.Marshal(authConfig)if err != nil {return fmt.Errorf("failed to marshal auth config: %w", err)@@ -589,7 +577,6 @@ func (s *AutoUpdateService) constructImageRefWithTag(imageRef, newTag string) stfunc (s *AutoUpdateService) checkStacks(ctx context.Context,req dto.AutoUpdateCheckDto,- settings *models.Settings,results chan<- dto.AutoUpdateResourceResult,errors chan<- error,) {@@ -608,15 +595,15 @@ func (s *AutoUpdateService) checkStacks(continue}- result := s.checkSingleStack(ctx, stack, settings, req.DryRun)+ result := s.checkSingleStack(ctx, stack, req.DryRun)results <- result}}+// Update checkSingleStack to remove settings parameterfunc (s *AutoUpdateService) checkSingleStack(ctx context.Context,stack models.Stack,- settings *models.Settings,dryRun bool,) dto.AutoUpdateResourceResult {result := dto.AutoUpdateResourceResult{@@ -658,7 +645,7 @@ func (s *AutoUpdateService) checkSingleStack(}}- hasUpdates, imageUpdates, err := s.checkStackImagesForUpdates(ctx, stack, settings)+ hasUpdates, imageUpdates, err := s.checkStackImagesForUpdates(ctx, stack)if err != nil {result.Status = "failed"result.Error = fmt.Sprintf("Failed to check for updates: %v", err)@@ -672,7 +659,7 @@ func (s *AutoUpdateService) checkSingleStack(}if !dryRun {- if err := s.updateStack(ctx, stack, settings); err != nil {+ if err := s.updateStack(ctx, stack); err != nil {result.Status = "failed"result.Error = fmt.Sprintf("Failed to update stack: %v", err)return result@@ -692,7 +679,6 @@ func (s *AutoUpdateService) checkSingleStack(func (s *AutoUpdateService) updateStack(ctx context.Context,stack models.Stack,- settings *models.Settings,) error {log.Printf("Updating stack: %s", stack.Name)@@ -714,7 +700,6 @@ func (s *AutoUpdateService) checkImageForUpdate(ctx context.Context,imageRef string,currentImageID string,- settings *models.Settings,) (bool, string, error) {if s.isDigestBasedImage(imageRef) {return false, "", nil@@ -736,7 +721,6 @@ func (s *AutoUpdateService) checkImageForUpdate(authConfig, err := s.getAuthConfigForImage(ctx, imageRef)if err != nil {log.Printf("Warning: Failed to get auth config for image %s: %v", imageRef, err)- // Continue without authentication - may work for public registries}var creds *utils.RegistryCredentials@@ -1110,7 +1094,7 @@ func (s *AutoUpdateService) normalizeRegistryURL(url string) string {return url}-func (s *AutoUpdateService) checkStackImagesForUpdates(ctx context.Context, stack models.Stack, settings *models.Settings) (bool, map[string]string, error) {+func (s *AutoUpdateService) checkStackImagesForUpdates(ctx context.Context, stack models.Stack) (bool, map[string]string, error) {composeContent, _, err := s.stackService.GetStackContent(ctx, stack.ID)if err != nil {return false, nil, err@@ -1144,7 +1128,7 @@ func (s *AutoUpdateService) checkStackImagesForUpdates(ctx context.Context, staccurrentImageID := serviceImageIDs[serviceName]- hasUpdate, newDigest, err := s.checkImageForUpdate(ctx, imageRef, currentImageID, settings)+ hasUpdate, newDigest, err := s.checkImageForUpdate(ctx, imageRef, currentImageID)if err != nil {log.Printf("Error checking updates for %s in stack %s: %v", imageRef, stack.Name, err)continuediff --git a/backend/internal/services/playwright_service.go b/backend/internal/services/playwright_service.goindex 82bcd7f6f..3be6cca51 100644--- a/backend/internal/services/playwright_service.go+++ b/backend/internal/services/playwright_service.go@@ -6,8 +6,6 @@ import ("context""fmt""log/slog"-- "github.com/ofkm/arcane-backend/internal/models")type PlaywrightService struct {@@ -23,17 +21,8 @@ func NewPlaywrightService(settingsService *SettingsService) *PlaywrightService {func (ps *PlaywrightService) SkipOnboarding(ctx context.Context) error {slog.Info("Playwright: Skipping onboarding for test environment")- settings, err := ps.settingsService.GetSettings(ctx)+ err := ps.settingsService.SetBoolSetting(ctx, "onboardingCompleted", true)if err != nil {- return fmt.Errorf("failed to get settings: %w", err)- }-- // Update onboarding to completed- settings.Onboarding = models.JSON{- "completed": true,- }-- if _, err := ps.settingsService.UpdateSettings(ctx, settings); err != nil {return fmt.Errorf("failed to skip onboarding: %w", err)}@@ -44,18 +33,9 @@ func (ps *PlaywrightService) SkipOnboarding(ctx context.Context) error {func (ps *PlaywrightService) ResetOnboarding(ctx context.Context) error {slog.Info("Playwright: Resetting onboarding for test environment")- settings, err := ps.settingsService.GetSettings(ctx)+ err := ps.settingsService.SetBoolSetting(ctx, "onboardingCompleted", false)if err != nil {- return fmt.Errorf("failed to get settings: %w", err)- }-- // Reset onboarding to not completed- settings.Onboarding = models.JSON{- "completed": false,- }-- if _, err := ps.settingsService.UpdateSettings(ctx, settings); err != nil {- return fmt.Errorf("failed to reset onboarding: %w", err)+ return fmt.Errorf("failed to skip onboarding: %w", err)}slog.Info("Playwright: Onboarding reset successfully")diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.goindex edb24df5c..fcc6723dc 100644--- a/backend/internal/services/settings_service.go+++ b/backend/internal/services/settings_service.go@@ -2,73 +2,295 @@ package servicesimport ("context"+ "encoding/json""errors""fmt"- "time"+ "reflect"+ "strings"+ "gorm.io/gorm"++ "github.com/ofkm/arcane-backend/internal/config""github.com/ofkm/arcane-backend/internal/database"+ "github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/models"- "gorm.io/gorm")type SettingsService struct {- db *database.DB+ db *database.DB+ config *config.Config // Add config field}-func NewSettingsService(db *database.DB) *SettingsService {- return &SettingsService{db: db}+func NewSettingsService(db *database.DB, cfg *config.Config) *SettingsService {+ return &SettingsService{+ db: db,+ config: cfg,+ }}func (s *SettingsService) GetSettings(ctx context.Context) (*models.Settings, error) {- var settings models.Settings- if err := s.db.WithContext(ctx).First(&settings).Error; err != nil {- if errors.Is(err, gorm.ErrRecordNotFound) {- return s.createDefaultSettings(ctx)+ var settingVars []models.SettingVariable+ err := s.db.WithContext(ctx).Find(&settingVars).Error+ if err != nil {+ return nil, err+ }++ settings := &models.Settings{}++ // Load values from database into the struct+ for _, sv := range settingVars {+ if err := settings.UpdateField(sv.Key, sv.Value, false); err != nil {+ // If key not found, it's okay - might be a deprecated setting+ if _, ok := err.(models.SettingKeyNotFoundError); !ok {+ return nil, fmt.Errorf("failed to load setting %s: %w", sv.Key, err)+ }}- return nil, fmt.Errorf("failed to get settings: %w", err)}- return &settings, nil++ return settings, nil}-func (s *SettingsService) UpdateSettings(ctx context.Context, settings *models.Settings) (*models.Settings, error) {- now := time.Now()- settings.UpdatedAt = &now+func (s *SettingsService) getDefaultSettings() *models.Settings {+ return &models.Settings{+ // Docker settings+ StacksDirectory: models.SettingVariable{Value: "data/stacks"},+ AutoUpdate: models.SettingVariable{Value: "true"},+ AutoUpdateInterval: models.SettingVariable{Value: "3600"},+ PollingEnabled: models.SettingVariable{Value: "true"},+ PollingInterval: models.SettingVariable{Value: "300"}, // 5 minutes in seconds+ PruneMode: models.SettingVariable{Value: "dangling"},+ BaseServerURL: models.SettingVariable{Value: ""},++ // Authentication settings+ AuthLocalEnabled: models.SettingVariable{Value: "true"},+ AuthOidcEnabled: models.SettingVariable{Value: "false"},+ AuthSessionTimeout: models.SettingVariable{Value: "86400"}, // 24 hours in seconds+ AuthPasswordPolicy: models.SettingVariable{Value: "strong"},+ AuthRbacEnabled: models.SettingVariable{Value: "false"},+ AuthOidcConfig: models.SettingVariable{Value: "{}"},- if err := s.db.WithContext(ctx).Save(settings).Error; err != nil {- return nil, fmt.Errorf("failed to update settings: %w", err)+ // Onboarding settings+ OnboardingCompleted: models.SettingVariable{Value: "false"},+ OnboardingSteps: models.SettingVariable{Value: "[]"},++ // Registry settings+ RegistryCredentials: models.SettingVariable{Value: "[]"},+ TemplateRegistries: models.SettingVariable{Value: "[]"},}- return settings, nil}-func (s *SettingsService) createDefaultSettings(ctx context.Context) (*models.Settings, error) {- defaultAuth := models.JSON{- "localAuthEnabled": true,- "oidcEnabled": false,- "sessionTimeout": 3600,- "passwordPolicy": "basic",- "rbacEnabled": false,+func (s *SettingsService) SyncOidcEnvToDatabase(ctx context.Context) ([]models.SettingVariable, error) {+ if !s.config.OidcEnabled {+ return nil, errors.New("OIDC sync called but OIDC_ENABLED is false")}- defaultPruneMode := "dangling"+ // Add validation to ensure required env vars are present+ if s.config.OidcClientID == "" || s.config.OidcIssuerURL == "" {+ return nil, errors.New("required OIDC environment variables are missing (OIDC_CLIENT_ID or OIDC_ISSUER_URL)")+ }- settings := &models.Settings{- StacksDirectory: "data/stacks",- AutoUpdate: false,- AutoUpdateInterval: 300,- PollingEnabled: true,- PollingInterval: 5,- PruneMode: &defaultPruneMode,- RegistryCredentials: models.JSON{},- TemplateRegistries: models.JSON{},- Auth: defaultAuth,- BaseModel: models.BaseModel{- CreatedAt: time.Now(),- },+ envOidcConfig := models.OidcConfig{+ ClientID: s.config.OidcClientID,+ ClientSecret: s.config.OidcClientSecret,+ IssuerURL: s.config.OidcIssuerURL,+ Scopes: s.config.OidcScopes,}- if err := s.db.WithContext(ctx).Create(settings).Error; err != nil {- return nil, fmt.Errorf("failed to create default settings: %w", err)+ oidcConfigBytes, err := json.Marshal(envOidcConfig)+ if err != nil {+ return nil, fmt.Errorf("failed to marshal OIDC config from env: %w", err)}- return settings, nil+ fmt.Printf("DEBUG: OIDC config JSON being saved: %s\n", string(oidcConfigBytes))++ // Force update the settings directly to bypass empty value checks+ err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ // Force update AuthOidcEnabled+ if err := tx.Save(&models.SettingVariable{+ Key: "authOidcEnabled",+ Value: "true",+ }).Error; err != nil {+ return fmt.Errorf("failed to update authOidcEnabled: %w", err)+ }++ // Force update AuthOidcConfig+ if err := tx.Save(&models.SettingVariable{+ Key: "authOidcConfig",+ Value: string(oidcConfigBytes),+ }).Error; err != nil {+ return fmt.Errorf("failed to update authOidcConfig: %w", err)+ }++ return nil+ })++ if err != nil {+ return nil, fmt.Errorf("failed to sync OIDC settings to database: %w", err)+ }++ // Return the updated settings+ settings, err := s.GetSettings(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to retrieve updated settings: %w", err)+ }++ return settings.ToSettingVariableSlice(false, false), nil+}++func (s *SettingsService) GetPublicSettings(ctx context.Context) ([]models.SettingVariable, error) {+ settings, err := s.GetSettings(ctx)+ if err != nil {+ return nil, err+ }++ return settings.ToSettingVariableSlice(false, false), nil+}++func (s *SettingsService) UpdateSetting(ctx context.Context, key, value string) error {+ settingVar := &models.SettingVariable{+ Key: key,+ Value: value,+ }++ return s.db.WithContext(ctx).Save(settingVar).Error+}++func (s *SettingsService) UpdateSettings(ctx context.Context, updates dto.UpdateSettingsDto) ([]models.SettingVariable, error) {+ // Load current and default settings+ defaultCfg := s.getDefaultSettings()+ cfg, err := s.GetSettings(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to load current settings: %w", err)+ }++ rt := reflect.TypeOf(updates)+ rv := reflect.ValueOf(updates)+ valuesToUpdate := make([]models.SettingVariable, 0)++ // Iterate through fields using reflection+ for i := 0; i < rt.NumField(); i++ {+ field := rt.Field(i)+ fieldValue := rv.Field(i)++ // Skip if the field is nil (not provided in request)+ if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {+ continue+ }++ // Get the value and json key+ key, _, _ := strings.Cut(field.Tag.Get("json"), ",")+ var value string+ if fieldValue.Kind() == reflect.Ptr {+ value = fieldValue.Elem().String()+ }++ // Determine the actual value to use and save+ var valueToSave string+ var err error++ if value == "" {+ // Use default value for empty strings+ defaultValue, _, _, _ := defaultCfg.FieldByKey(key)+ valueToSave = defaultValue+ err = cfg.UpdateField(key, defaultValue, true)+ } else {+ // Use the provided value+ valueToSave = value+ err = cfg.UpdateField(key, value, true)+ }++ // Handle internal field errors+ if errors.Is(err, models.SettingSensitiveForbiddenError{}) {+ continue+ } else if err != nil {+ return nil, fmt.Errorf("failed to update in-memory config for key '%s': %w", key, err)+ }++ // Save the correct value to database+ valuesToUpdate = append(valuesToUpdate, models.SettingVariable{+ Key: key,+ Value: valueToSave,+ })+ }++ err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ for _, setting := range valuesToUpdate {+ if err := tx.Save(&setting).Error; err != nil {+ return fmt.Errorf("failed to update setting %s: %w", setting.Key, err)+ }+ }+ return nil+ })++ if err != nil {+ return nil, err+ }++ settings, err := s.GetSettings(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to retrieve updated settings: %w", err)+ }++ return settings.ToSettingVariableSlice(false, false), nil+}++func (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error {+ defaultSettings := s.getDefaultSettings()+ defaultSettingVars := defaultSettings.ToSettingVariableSlice(true, false)++ return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ for _, defaultSetting := range defaultSettingVars {+ var existing models.SettingVariable+ err := tx.Where("key = ?", defaultSetting.Key).First(&existing).Error++ if errors.Is(err, gorm.ErrRecordNotFound) {+ if err := tx.Create(&defaultSetting).Error; err != nil {+ return fmt.Errorf("failed to create default setting %s: %w", defaultSetting.Key, err)+ }+ } else if err != nil {+ return fmt.Errorf("failed to check for existing setting %s: %w", defaultSetting.Key, err)+ }+ // If setting exists, leave it as is (don't overwrite user values)+ }+ return nil+ })+}++func (s *SettingsService) GetBoolSetting(ctx context.Context, key string, defaultValue bool) bool {+ var sv models.SettingVariable+ err := s.db.WithContext(ctx).Where("key = ?", key).First(&sv).Error+ if err != nil {+ return defaultValue+ }+ return sv.IsTrue()+}++func (s *SettingsService) GetIntSetting(ctx context.Context, key string, defaultValue int) int {+ var sv models.SettingVariable+ err := s.db.WithContext(ctx).Where("key = ?", key).First(&sv).Error+ if err != nil {+ return defaultValue+ }+ return sv.AsInt()+}++func (s *SettingsService) GetStringSetting(ctx context.Context, key, defaultValue string) string {+ var sv models.SettingVariable+ err := s.db.WithContext(ctx).Where("key = ?", key).First(&sv).Error+ if err != nil {+ return defaultValue+ }+ return sv.Value+}++func (s *SettingsService) SetBoolSetting(ctx context.Context, key string, value bool) error {+ return s.UpdateSetting(ctx, key, fmt.Sprintf("%t", value))+}++func (s *SettingsService) SetIntSetting(ctx context.Context, key string, value int) error {+ return s.UpdateSetting(ctx, key, fmt.Sprintf("%d", value))+}++func (s *SettingsService) SetStringSetting(ctx context.Context, key, value string) error {+ return s.UpdateSetting(ctx, key, value)}diff --git a/backend/internal/services/stack_service.go b/backend/internal/services/stack_service.goindex bf8710fea..a616de4e8 100644--- a/backend/internal/services/stack_service.go+++ b/backend/internal/services/stack_service.go@@ -1054,14 +1054,12 @@ func (s *StackService) sanitizeStackName(name string) string {func (s *StackService) getStacksDirectory(ctx context.Context) (string, error) {settings, err := s.settingsService.GetSettings(ctx)if err != nil {- return "", fmt.Errorf("failed to get settings: %w", err)+ return "data/stacks", fmt.Errorf("failed to get settings: %w", err)}- if settings.StacksDirectory == "" {- return "data/stacks", nil- }+ stacksDirectory := settings.StacksDirectory.Value- return settings.StacksDirectory, nil+ return stacksDirectory, nil}func (s *StackService) saveStackFiles(stackPath, composeContent string, envContent *string) error {diff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.goindex 1fdd20ad0..43dc6acd7 100644--- a/backend/internal/services/system_service.go+++ b/backend/internal/services/system_service.go@@ -133,16 +133,9 @@ func (s *SystemService) PruneAll(ctx context.Context, req dto.PruneSystemDto) (*}func (s *SystemService) getDanglingModeFromSettings(ctx context.Context) (bool, error) {- settings, err := s.settingsService.GetSettings(ctx)- if err != nil {- return true, fmt.Errorf("failed to get settings: %w", err)- }-- if settings.PruneMode == nil {- return true, nil- }+ pruneMode := s.settingsService.GetStringSetting(ctx, "dockerPruneMode", "dangling")- switch *settings.PruneMode {+ switch pruneMode {case "dangling":return true, nilcase "all":@@ -359,19 +352,11 @@ func (s *SystemService) PruneSystem(ctx context.Context, all bool) (*PruneAllResdanglingOnly := trueif all {- settings, err := s.settingsService.GetSettings(ctx)- if err == nil && settings.PruneMode != nil {- danglingOnly = *settings.PruneMode == "dangling"- slog.DebugContext(ctx, "Retrieved prune mode from settings",- slog.String("prune_mode", *settings.PruneMode),- slog.Bool("dangling_only", danglingOnly))- } else {- danglingOnly = false- if err != nil {- slog.WarnContext(ctx, "Failed to get prune mode from settings, defaulting to all unused",- slog.String("error", err.Error()))- }- }+ pruneMode := s.settingsService.GetStringSetting(ctx, "dockerPruneMode", "dangling")+ danglingOnly = pruneMode == "dangling"+ slog.DebugContext(ctx, "Retrieved prune mode from settings",+ slog.String("prune_mode", pruneMode),+ slog.Bool("dangling_only", danglingOnly))}slog.DebugContext(ctx, "Starting container pruning")diff --git a/backend/internal/utils/ptr_util.go b/backend/internal/utils/ptr_util.gonew file mode 100644index 000000000..947538cda--- /dev/null+++ b/backend/internal/utils/ptr_util.go@@ -0,0 +1,5 @@+package utils++func Ptr[T any](v T) *T {+ return &v+}diff --git a/backend/resources/migrations/postgres/001_initial_schema.down.sql b/backend/resources/migrations/postgres/001_initial_schema.down.sqlnew file mode 100644index 000000000..47e3cad9c--- /dev/null+++ b/backend/resources/migrations/postgres/001_initial_schema.down.sql@@ -0,0 +1,28 @@+-- Drop all tables in reverse order of dependencies (PostgreSQL)++DROP INDEX IF EXISTS idx_auto_update_start_time;+DROP INDEX IF EXISTS idx_auto_update_resource_id;+DROP INDEX IF EXISTS idx_image_update_tag;+DROP INDEX IF EXISTS idx_image_update_repository;+DROP INDEX IF EXISTS idx_images_tag;+DROP INDEX IF EXISTS idx_images_repo;+DROP INDEX IF EXISTS idx_containers_stack_id;+DROP INDEX IF EXISTS idx_user_sessions_token;+DROP INDEX IF EXISTS idx_user_sessions_user_id;+DROP INDEX IF EXISTS idx_settings_public;+DROP INDEX IF EXISTS idx_settings_key;++DROP TABLE IF EXISTS auto_update_records;+DROP TABLE IF EXISTS container_registries;+DROP TABLE IF EXISTS compose_templates;+DROP TABLE IF EXISTS template_registries;+DROP TABLE IF EXISTS image_update_table;+DROP TABLE IF EXISTS networks_table;+DROP TABLE IF EXISTS volumes_table;+DROP TABLE IF EXISTS images_table;+DROP TABLE IF EXISTS containers_table;+DROP TABLE IF EXISTS environments;+DROP TABLE IF EXISTS stacks_table;+DROP TABLE IF EXISTS user_sessions_table;+DROP TABLE IF EXISTS users_table;+DROP TABLE IF EXISTS settings;\ No newline at end of filediff --git a/backend/resources/migrations/postgres/001_initial_schema.up.sql b/backend/resources/migrations/postgres/001_initial_schema.up.sqlnew file mode 100644index 000000000..9275fade1--- /dev/null+++ b/backend/resources/migrations/postgres/001_initial_schema.up.sql@@ -0,0 +1,217 @@+CREATE TABLE IF NOT EXISTS settings (+ key TEXT NOT NULL PRIMARY KEY,+ value TEXT NOT NULL,+ type TEXT NOT NULL DEFAULT 'string',+ isPublic BOOLEAN DEFAULT FALSE NOT NULL,+ isInternal BOOLEAN DEFAULT FALSE NOT NULL,+ createdAt TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updatedAt TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS users_table (+ id TEXT PRIMARY KEY,+ username TEXT NOT NULL UNIQUE,+ password_hash TEXT NOT NULL,+ display_name TEXT,+ email TEXT,+ roles JSONB NOT NULL DEFAULT '[]',+ require_password_change BOOLEAN NOT NULL DEFAULT false,+ oidc_subject_id TEXT,+ last_login TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS user_sessions_table (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ username TEXT NOT NULL,+ token TEXT NOT NULL UNIQUE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ last_accessed TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ expires_at TIMESTAMPTZ,+ is_active BOOLEAN NOT NULL DEFAULT true,+ updated_at TIMESTAMPTZ,+ FOREIGN KEY (user_id) REFERENCES users_table(id) ON DELETE CASCADE+);+++CREATE TABLE IF NOT EXISTS stacks_table (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ dir_name TEXT UNIQUE,+ path TEXT NOT NULL,+ status TEXT NOT NULL,+ service_count INTEGER NOT NULL DEFAULT 0,+ running_count INTEGER NOT NULL DEFAULT 0,+ auto_update BOOLEAN NOT NULL DEFAULT false,+ is_external BOOLEAN NOT NULL DEFAULT false,+ is_legacy BOOLEAN NOT NULL DEFAULT false,+ is_remote BOOLEAN NOT NULL DEFAULT false,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS environments (+ id TEXT PRIMARY KEY,+ hostname TEXT NOT NULL,+ api_url TEXT NOT NULL,+ description TEXT,+ status TEXT NOT NULL DEFAULT 'offline',+ enabled BOOLEAN NOT NULL DEFAULT true,+ last_seen TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS containers_table (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ image TEXT NOT NULL,+ status TEXT NOT NULL,+ state TEXT NOT NULL,+ ports JSONB,+ mounts JSONB,+ networks JSONB,+ labels JSONB,+ environment JSONB,+ command JSONB,+ stack_id TEXT,+ started_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ,+ FOREIGN KEY (stack_id) REFERENCES stacks_table(id) ON DELETE SET NULL+);++CREATE TABLE IF NOT EXISTS images_table (+ id TEXT PRIMARY KEY,+ repo_tags JSONB,+ repo_digests JSONB,+ size BIGINT NOT NULL,+ virtual_size BIGINT NOT NULL DEFAULT 0,+ labels JSONB,+ created TIMESTAMPTZ NOT NULL,+ repo TEXT,+ tag TEXT,+ in_use BOOLEAN NOT NULL DEFAULT false,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS volumes_table (+ name TEXT PRIMARY KEY,+ driver TEXT NOT NULL,+ mountpoint TEXT NOT NULL,+ labels JSONB,+ scope TEXT NOT NULL,+ options JSONB,+ in_use BOOLEAN NOT NULL DEFAULT false,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS networks_table (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ driver TEXT NOT NULL,+ scope TEXT NOT NULL,+ internal BOOLEAN NOT NULL DEFAULT false,+ attachable BOOLEAN NOT NULL DEFAULT false,+ ingress BOOLEAN NOT NULL DEFAULT false,+ ipam JSONB,+ labels JSONB,+ options JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS image_update_table (+ id TEXT PRIMARY KEY,+ repository TEXT NOT NULL,+ tag TEXT NOT NULL,+ has_update BOOLEAN NOT NULL DEFAULT false,+ update_type TEXT,+ current_version TEXT NOT NULL,+ latest_version TEXT,+ current_digest TEXT,+ latest_digest TEXT,+ check_time TIMESTAMPTZ NOT NULL,+ response_time_ms INTEGER NOT NULL DEFAULT 0,+ last_error TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS template_registries (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ url TEXT NOT NULL UNIQUE,+ enabled BOOLEAN NOT NULL DEFAULT true,+ description TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS compose_templates (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ content TEXT,+ env_content TEXT,+ is_custom BOOLEAN NOT NULL DEFAULT true,+ is_remote BOOLEAN NOT NULL DEFAULT false,+ registry_id TEXT,+ meta_version TEXT,+ meta_author TEXT,+ meta_tags TEXT,+ meta_remote_url TEXT,+ meta_env_url TEXT,+ meta_documentation_url TEXT,+ meta_icon_url TEXT,+ meta_updated_at TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ,+ FOREIGN KEY (registry_id) REFERENCES template_registries(id) ON DELETE SET NULL+);++CREATE TABLE IF NOT EXISTS container_registries (+ id TEXT PRIMARY KEY,+ url TEXT NOT NULL,+ username TEXT NOT NULL,+ token TEXT NOT NULL,+ description TEXT,+ insecure BOOLEAN NOT NULL DEFAULT false,+ enabled BOOLEAN NOT NULL DEFAULT true,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE TABLE IF NOT EXISTS auto_update_records (+ id TEXT PRIMARY KEY,+ resource_id TEXT NOT NULL,+ resource_type TEXT NOT NULL,+ resource_name TEXT NOT NULL,+ status TEXT NOT NULL,+ start_time TIMESTAMPTZ NOT NULL,+ end_time TIMESTAMPTZ,+ update_available BOOLEAN NOT NULL DEFAULT false,+ update_applied BOOLEAN NOT NULL DEFAULT false,+ old_image_versions JSONB,+ new_image_versions JSONB,+ error TEXT,+ details JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++CREATE INDEX IF NOT EXISTS idx_settings_key ON settings(key);+CREATE INDEX IF NOT EXISTS idx_settings_ispublic ON settings(isPublic);+CREATE INDEX IF NOT EXISTS idx_user_sessions_user_id ON user_sessions_table(user_id);+CREATE INDEX IF NOT EXISTS idx_user_sessions_token ON user_sessions_table(token);+CREATE INDEX IF NOT EXISTS idx_containers_stack_id ON containers_table(stack_id);+CREATE INDEX IF NOT EXISTS idx_images_repo ON images_table(repo);+CREATE INDEX IF NOT EXISTS idx_images_tag ON images_table(tag);+CREATE INDEX IF NOT EXISTS idx_image_update_repository ON image_update_table(repository);+CREATE INDEX IF NOT EXISTS idx_image_update_tag ON image_update_table(tag);+CREATE INDEX IF NOT EXISTS idx_auto_update_resource_id ON auto_update_records(resource_id);+CREATE INDEX IF NOT EXISTS idx_auto_update_start_time ON auto_update_records(start_time);\ No newline at end of filediff --git a/backend/resources/migrations/psql/001_initial_schema.up.sql b/backend/resources/migrations/psql/001_initial_schema.up.sqldeleted file mode 100644index e69de29bb..000000000diff --git a/backend/resources/migrations/sqlite/001_initial_schema.down.sql b/backend/resources/migrations/sqlite/001_initial_schema.down.sqlnew file mode 100644index 000000000..4702af74c--- /dev/null+++ b/backend/resources/migrations/sqlite/001_initial_schema.down.sql@@ -0,0 +1,28 @@+-- Drop all tables in reverse order of dependencies++DROP INDEX IF EXISTS idx_auto_update_start_time;+DROP INDEX IF EXISTS idx_auto_update_resource_id;+DROP INDEX IF EXISTS idx_image_update_tag;+DROP INDEX IF EXISTS idx_image_update_repository;+DROP INDEX IF EXISTS idx_images_tag;+DROP INDEX IF EXISTS idx_images_repo;+DROP INDEX IF EXISTS idx_containers_stack_id;+DROP INDEX IF EXISTS idx_user_sessions_token;+DROP INDEX IF EXISTS idx_user_sessions_user_id;+DROP INDEX IF EXISTS idx_settings_public;+DROP INDEX IF EXISTS idx_settings_key;++DROP TABLE IF EXISTS auto_update_records;+DROP TABLE IF EXISTS container_registries;+DROP TABLE IF EXISTS compose_templates;+DROP TABLE IF EXISTS template_registries;+DROP TABLE IF EXISTS image_update_table;+DROP TABLE IF EXISTS networks_table;+DROP TABLE IF EXISTS volumes_table;+DROP TABLE IF EXISTS images_table;+DROP TABLE IF EXISTS containers_table;+DROP TABLE IF EXISTS environments;+DROP TABLE IF EXISTS stacks_table;+DROP TABLE IF EXISTS user_sessions_table;+DROP TABLE IF EXISTS users_table;+DROP TABLE IF EXISTS settings;\ No newline at end of filediff --git a/backend/resources/migrations/sqlite/001_initial_schema.up.sql b/backend/resources/migrations/sqlite/001_initial_schema.up.sqlindex 79d87cb1a..5faf8c59f 100644--- a/backend/resources/migrations/sqlite/001_initial_schema.up.sql+++ b/backend/resources/migrations/sqlite/001_initial_schema.up.sql@@ -1,30 +1,21 @@-CREATE TABLE IF NOT EXISTS settings_table (- id INTEGER PRIMARY KEY AUTOINCREMENT,- docker_tls_cert TEXT NOT NULL DEFAULT '',- stacks_directory TEXT NOT NULL,- auto_update BOOLEAN NOT NULL DEFAULT 0,- auto_update_interval INTEGER NOT NULL DEFAULT 300,- polling_enabled BOOLEAN NOT NULL DEFAULT 1,- polling_interval INTEGER NOT NULL DEFAULT 5,- prune_mode TEXT,- registry_credentials TEXT NOT NULL DEFAULT '[]',- template_registries TEXT NOT NULL DEFAULT '[]',- auth TEXT NOT NULL,- onboarding TEXT,- base_server_url TEXT,- maturity_threshold_days INTEGER NOT NULL DEFAULT 30,- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- updated_at DATETIME+CREATE TABLE IF NOT EXISTS settings (+ key TEXT NOT NULL PRIMARY KEY,+ value TEXT NOT NULL,+ type TEXT NOT NULL DEFAULT 'string',+ isPublic BOOLEAN DEFAULT FALSE NOT NULL,+ isInternal BOOLEAN DEFAULT FALSE NOT NULL,+ createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updatedAt DATETIME);CREATE TABLE IF NOT EXISTS users_table (id TEXT PRIMARY KEY,username TEXT NOT NULL UNIQUE,- password_hash TEXT NOT NULL DEFAULT '',+ password_hash TEXT NOT NULL,display_name TEXT,email TEXT,roles TEXT NOT NULL DEFAULT '[]',- require_password_change BOOLEAN NOT NULL DEFAULT 0,+ require_password_change BOOLEAN NOT NULL DEFAULT false,oidc_subject_id TEXT,last_login DATETIME,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,@@ -39,7 +30,7 @@ CREATE TABLE IF NOT EXISTS user_sessions_table (created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,last_accessed DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,expires_at DATETIME,- is_active BOOLEAN NOT NULL DEFAULT 1,+ is_active BOOLEAN NOT NULL DEFAULT true,updated_at DATETIME,FOREIGN KEY (user_id) REFERENCES users_table(id) ON DELETE CASCADE);@@ -49,13 +40,13 @@ CREATE TABLE IF NOT EXISTS stacks_table (name TEXT NOT NULL,dir_name TEXT UNIQUE,path TEXT NOT NULL,- status TEXT NOT NULL DEFAULT 'unknown',+ status TEXT NOT NULL,service_count INTEGER NOT NULL DEFAULT 0,running_count INTEGER NOT NULL DEFAULT 0,- auto_update BOOLEAN NOT NULL DEFAULT 0,- is_external BOOLEAN NOT NULL DEFAULT 0,- is_legacy BOOLEAN NOT NULL DEFAULT 0,- is_remote BOOLEAN NOT NULL DEFAULT 0,+ auto_update BOOLEAN NOT NULL DEFAULT false,+ is_external BOOLEAN NOT NULL DEFAULT false,+ is_legacy BOOLEAN NOT NULL DEFAULT false,+ is_remote BOOLEAN NOT NULL DEFAULT false,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME);@@ -66,7 +57,7 @@ CREATE TABLE IF NOT EXISTS environments (api_url TEXT NOT NULL,description TEXT,status TEXT NOT NULL DEFAULT 'offline',- enabled BOOLEAN NOT NULL DEFAULT 1,+ enabled BOOLEAN NOT NULL DEFAULT true,last_seen DATETIME,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME@@ -95,13 +86,14 @@ CREATE TABLE IF NOT EXISTS images_table (id TEXT PRIMARY KEY,repo_tags TEXT,repo_digests TEXT,- size INTEGER NOT NULL DEFAULT 0,+ size INTEGER NOT NULL,virtual_size INTEGER NOT NULL DEFAULT 0,labels TEXT,- created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- repo TEXT NOT NULL DEFAULT '',- tag TEXT NOT NULL DEFAULT '',- in_use BOOLEAN NOT NULL DEFAULT 0,+ created DATETIME NOT NULL,+ repo TEXT,+ tag TEXT,+ in_use BOOLEAN NOT NULL DEFAULT false,+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME);@@ -112,7 +104,7 @@ CREATE TABLE IF NOT EXISTS volumes_table (labels TEXT,scope TEXT NOT NULL,options TEXT,- in_use BOOLEAN NOT NULL DEFAULT 0,+ in_use BOOLEAN NOT NULL DEFAULT false,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME);@@ -122,9 +114,9 @@ CREATE TABLE IF NOT EXISTS networks_table (name TEXT NOT NULL UNIQUE,driver TEXT NOT NULL,scope TEXT NOT NULL,- internal BOOLEAN NOT NULL DEFAULT 0,- attachable BOOLEAN NOT NULL DEFAULT 0,- ingress BOOLEAN NOT NULL DEFAULT 0,+ internal BOOLEAN NOT NULL DEFAULT false,+ attachable BOOLEAN NOT NULL DEFAULT false,+ ingress BOOLEAN NOT NULL DEFAULT false,ipam TEXT,labels TEXT,options TEXT,@@ -132,46 +124,41 @@ CREATE TABLE IF NOT EXISTS networks_table (updated_at DATETIME);-CREATE TABLE IF NOT EXISTS image_maturity_table (+CREATE TABLE IF NOT EXISTS image_update_table (id TEXT PRIMARY KEY,repository TEXT NOT NULL,tag TEXT NOT NULL,- current_version TEXT NOT NULL DEFAULT '',+ has_update BOOLEAN NOT NULL DEFAULT false,+ update_type TEXT,+ current_version TEXT NOT NULL,latest_version TEXT,- status TEXT NOT NULL,- updates_available BOOLEAN NOT NULL DEFAULT 0,- current_image_date DATETIME,- latest_image_date DATETIME,- days_since_creation INTEGER,- registry_domain TEXT,- is_private_registry BOOLEAN NOT NULL DEFAULT 0,- last_checked DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- check_count INTEGER NOT NULL DEFAULT 0,+ current_digest TEXT,+ latest_digest TEXT,+ check_time DATETIME NOT NULL,+ response_time_ms INTEGER NOT NULL DEFAULT 0,last_error TEXT,- response_time_ms INTEGER,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- updated_at DATETIME,- FOREIGN KEY (id) REFERENCES images_table(id) ON DELETE CASCADE+ updated_at DATETIME);CREATE TABLE IF NOT EXISTS template_registries (id TEXT PRIMARY KEY,name TEXT NOT NULL,url TEXT NOT NULL UNIQUE,- enabled BOOLEAN NOT NULL DEFAULT 1,- description TEXT NOT NULL DEFAULT '',+ enabled BOOLEAN NOT NULL DEFAULT true,+ description TEXT,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP+ updated_at DATETIME);CREATE TABLE IF NOT EXISTS compose_templates (id TEXT PRIMARY KEY,name TEXT NOT NULL,- description TEXT NOT NULL DEFAULT '',- content TEXT NOT NULL,+ description TEXT,+ content TEXT,env_content TEXT,- is_custom BOOLEAN NOT NULL DEFAULT 1,- is_remote BOOLEAN NOT NULL DEFAULT 0,+ is_custom BOOLEAN NOT NULL DEFAULT true,+ is_remote BOOLEAN NOT NULL DEFAULT false,registry_id TEXT,meta_version TEXT,meta_author TEXT,@@ -182,7 +169,7 @@ CREATE TABLE IF NOT EXISTS compose_templates (meta_icon_url TEXT,meta_updated_at TEXT,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME,FOREIGN KEY (registry_id) REFERENCES template_registries(id) ON DELETE SET NULL);@@ -192,25 +179,38 @@ CREATE TABLE IF NOT EXISTS container_registries (username TEXT NOT NULL,token TEXT NOT NULL,description TEXT,- insecure BOOLEAN NOT NULL DEFAULT 0,- enabled BOOLEAN NOT NULL DEFAULT 1,+ insecure BOOLEAN NOT NULL DEFAULT false,+ enabled BOOLEAN NOT NULL DEFAULT true,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP+ updated_at DATETIME+);++CREATE TABLE IF NOT EXISTS auto_update_records (+ id TEXT PRIMARY KEY,+ resource_id TEXT NOT NULL,+ resource_type TEXT NOT NULL,+ resource_name TEXT NOT NULL,+ status TEXT NOT NULL,+ start_time DATETIME NOT NULL,+ end_time DATETIME,+ update_available BOOLEAN NOT NULL DEFAULT false,+ update_applied BOOLEAN NOT NULL DEFAULT false,+ old_image_versions TEXT,+ new_image_versions TEXT,+ error TEXT,+ details TEXT,+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME);-CREATE INDEX IF NOT EXISTS idx_users_username ON users_table(username);+CREATE INDEX IF NOT EXISTS idx_settings_key ON settings(key);+CREATE INDEX IF NOT EXISTS idx_settings_ispublic ON settings(isPublic);CREATE INDEX IF NOT EXISTS idx_user_sessions_user_id ON user_sessions_table(user_id);CREATE INDEX IF NOT EXISTS idx_user_sessions_token ON user_sessions_table(token);CREATE INDEX IF NOT EXISTS idx_containers_stack_id ON containers_table(stack_id);-CREATE INDEX IF NOT EXISTS idx_containers_name ON containers_table(name);-CREATE INDEX IF NOT EXISTS idx_containers_image ON containers_table(image);-CREATE INDEX IF NOT EXISTS idx_containers_status ON containers_table(status);-CREATE INDEX IF NOT EXISTS idx_containers_state ON containers_table(state);CREATE INDEX IF NOT EXISTS idx_images_repo ON images_table(repo);CREATE INDEX IF NOT EXISTS idx_images_tag ON images_table(tag);-CREATE INDEX IF NOT EXISTS idx_images_in_use ON images_table(in_use);-CREATE INDEX IF NOT EXISTS idx_stacks_name ON stacks_table(name);-CREATE INDEX IF NOT EXISTS idx_stacks_status ON stacks_table(status);-CREATE INDEX IF NOT EXISTS idx_image_maturity_repository ON image_maturity_table(repository);-CREATE INDEX IF NOT EXISTS idx_image_maturity_tag ON image_maturity_table(tag);-CREATE INDEX IF NOT EXISTS idx_image_maturity_status ON image_maturity_table(status);\ No newline at end of file+CREATE INDEX IF NOT EXISTS idx_image_update_repository ON image_update_table(repository);+CREATE INDEX IF NOT EXISTS idx_image_update_tag ON image_update_table(tag);+CREATE INDEX IF NOT EXISTS idx_auto_update_resource_id ON auto_update_records(resource_id);+CREATE INDEX IF NOT EXISTS idx_auto_update_start_time ON auto_update_records(start_time);\ No newline at end of filediff --git a/frontend/src/lib/components/dialogs/oidc-config-dialog.svelte b/frontend/src/lib/components/dialogs/oidc-config-dialog.svelteindex b84aaa786..81a2d8e28 100644--- a/frontend/src/lib/components/dialogs/oidc-config-dialog.svelte+++ b/frontend/src/lib/components/dialogs/oidc-config-dialog.svelte@@ -3,7 +3,6 @@import { Input } from '$lib/components/ui/input/index.js';import { Key, AlertTriangle, Info, ChevronDown, Copy } from '@lucide/svelte';import * as Dialog from '$lib/components/ui/dialog/index.js';- import * as Collapsible from '$lib/components/ui/collapsible/index.js';import { Label } from '$lib/components/ui/label/index.js';import { toast } from 'svelte-sonner';import type { Settings } from '$lib/types/settings.type';@@ -41,6 +40,30 @@let advancedSettingsOpen = $state(false);let redirectUri = $derived(`${window.location.origin}/auth/oidc/callback`);+ // Parse OIDC config from JSON string+ let parsedOidcConfig = $derived(() => {+ if (!currentSettings.authOidcConfig) {+ return {+ clientId: '',+ clientSecret: '',+ issuerUrl: '',+ scopes: 'openid email profile'+ };+ }++ try {+ return JSON.parse(currentSettings.authOidcConfig);+ } catch (error) {+ console.warn('Failed to parse OIDC config:', error);+ return {+ clientId: '',+ clientSecret: '',+ issuerUrl: '',+ scopes: 'openid email profile'+ };+ }+ });+async function copyToClipboard(text: string) {try {await navigator.clipboard.writeText(text);@@ -90,12 +113,18 @@The following OIDC settings are loaded from the server environment:</p>- {#if currentSettings.auth?.oidc}+ {#if currentSettings.authOidcEnabled}<div class="space-y-3"><div class="flex justify-between items-center py-2 border-b border-border/50"><span class="font-medium text-sm">Client ID</span><code class="bg-muted px-2 py-1 rounded text-xs">- {currentSettings.auth.oidc.clientId}+ {parsedOidcConfig().clientId || 'Not configured'}+ </code>+ </div>+ <div class="flex justify-between items-center py-2 border-b border-border/50">+ <span class="font-medium text-sm">Issuer URL</span>+ <code class="bg-muted px-2 py-1 rounded text-xs">+ {parsedOidcConfig().issuerUrl || 'Not configured'}</code></div><div class="flex justify-between items-center py-2 border-b border-border/50">@@ -107,7 +136,7 @@<div class="flex justify-between items-center py-2"><span class="font-medium text-sm">Scopes</span><code class="bg-muted px-2 py-1 rounded text-xs">- {currentSettings.auth.oidc.scopes}+ {parsedOidcConfig().scopes || 'openid email profile'}</code></div></div>diff --git a/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte b/frontend/src/lib/components/sheets/add-template-registry-sheet.svelteindex 2b33665f4..8148cdd29 100644--- a/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte+++ b/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte@@ -11,7 +11,12 @@type TemplateRegistryFormProps = {open: boolean;- onSubmit: (registry: { name: string; url: string; description?: string; enabled: boolean }) => void;+ onSubmit: (registry: {+ name: string;+ url: string;+ description?: string;+ enabled: boolean;+ }) => void;isLoading: boolean;};@@ -31,90 +36,45 @@let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));- // Validation state- let validationState = $state<{- isValidating: boolean;- result: {- valid: boolean;- name?: string;- errors: string[];- warnings: string[];- } | null;- }>({- isValidating: false,- result: null- });+ // Submission error state+ let submitError = $state<string | null>(null);- // Validate registry URL- async function validateRegistryUrl(url: string) {- if (!url.trim()) {- validationState.result = null;- return;- }+ async function handleSubmit() {+ // Clear previous errors+ submitError = null;- validationState.isValidating = true;- try {- new URL(url);+ const data = form.validate();+ if (!data) return;- const data = await templateAPI.fetchRegistry(url);+ try {+ // Validate the registry URL by fetching it+ const registryData = await templateAPI.fetchRegistry(data.url);- if (!data.name || !data.templates || !Array.isArray(data.templates)) {+ if (!registryData.name || !registryData.templates || !Array.isArray(registryData.templates)) {throw new Error('Invalid registry format: missing required fields (name, templates)');}- validationState.result = {- valid: true,- name: data.name,- errors: [],- warnings: data.templates.length === 0 ? ['Registry contains no templates'] : []+ // Submit with the name from the registry+ const registryPayload = {+ name: registryData.name,+ url: data.url,+ description: data.description || undefined,+ enabled: data.enabled};++ onSubmit(registryPayload);} catch (error) {- validationState.result = {- valid: false,- errors: [error instanceof Error ? error.message : 'Invalid registry URL'],- warnings: []- };- } finally {- validationState.isValidating = false;+ submitError = error instanceof Error ? error.message : 'Failed to validate registry URL';}}- function handleSubmit() {- const data = form.validate();- if (!data) return;-- console.log(validationState);- if (!validationState.result || !validationState.result.valid || !validationState.result.name) {- return;- }-- // Include the name from the JSON validation- const registryData = {- name: validationState.result.name,- url: data.url,- description: data.description ? data.description : undefined,- enabled: data.enabled- };-- onSubmit(registryData);- }-function handleOpenChange(newOpenState: boolean) {open = newOpenState;- }-- // Watch URL changes for validation with debounce- $effect(() => {- if ($inputs.url.value) {- const timeoutId = setTimeout(() => {- validateRegistryUrl($inputs.url.value);- }, 500);-- return () => clearTimeout(timeoutId);- } else {- validationState.result = null;+ // Clear errors when closing+ if (!newOpenState) {+ submitError = null;}- });+ }</script><Sheet.Root bind:open onOpenChange={handleOpenChange}>@@ -126,54 +86,54 @@</div><div><Sheet.Title class="text-xl font-semibold">Add Template Registry</Sheet.Title>- <Sheet.Description class="text-sm text-muted-foreground mt-1">Add a remote template registry to access community templates.</Sheet.Description>+ <Sheet.Description class="text-sm text-muted-foreground mt-1"+ >Add a remote template registry to access community templates.</Sheet.Description+ ></div></div></Sheet.Header><form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-4">- <div class="space-y-1">- <FormInput label="Registry URL *" type="text" placeholder="https://templates.arcane.ofkm.dev/registry.json" description="URL to the registry JSON manifest" bind:input={$inputs.url} />-- {#if validationState.isValidating}- <div class="flex items-center gap-2 text-sm text-muted-foreground">- <RefreshCw class="size-3 animate-spin" />- Validating registry...- </div>- {:else if validationState.result}- {#if validationState.result.valid}- <div class="flex items-center gap-2 text-sm text-green-600">- <CheckCircle class="size-3" />- Valid registry found: <strong>{validationState.result.name}</strong>- </div>- {:else}- <div class="flex items-center gap-2 text-sm text-red-600">- <AlertCircle class="size-3" />- {validationState.result.errors[0]}- </div>- {/if}- {/if}- </div>-- <FormInput label="Description" type="text" placeholder="A collection of useful Docker Compose templates" description="Optional description for this registry" bind:input={$inputs.description} />-- <SwitchWithLabel id="enabledSwitch" label="Enable Registry" description="Enable this registry to fetch templates" bind:checked={$inputs.enabled.value} />-- {#if validationState.result && validationState.result.warnings.length > 0}- <Alert.Root class="border-yellow-200 bg-yellow-50 dark:border-yellow-800 dark:bg-yellow-950">+ <FormInput+ label="Registry URL *"+ type="text"+ placeholder="https://templates.arcane.ofkm.dev/registry.json"+ description="URL to the registry JSON manifest"+ bind:input={$inputs.url}+ />++ <FormInput+ label="Description"+ type="text"+ placeholder="A collection of useful Docker Compose templates"+ description="Optional description for this registry"+ bind:input={$inputs.description}+ />++ <SwitchWithLabel+ id="enabledSwitch"+ label="Enable Registry"+ description="Enable this registry to fetch templates"+ bind:checked={$inputs.enabled.value}+ />++ {#if submitError}+ <Alert.Root class="border-red-200 bg-red-50 dark:border-red-800 dark:bg-red-950"><AlertCircle class="size-4" />- <Alert.Title>Warnings</Alert.Title>- <Alert.Description>- <ul class="list-inside list-disc space-y-1">- {#each validationState.result.warnings as warning}- <li class="text-sm">{warning}</li>- {/each}- </ul>- </Alert.Description>+ <Alert.Title>Validation Error</Alert.Title>+ <Alert.Description class="text-sm">{submitError}</Alert.Description></Alert.Root>{/if}<Sheet.Footer class="flex flex-row gap-2">- <Button type="button" class="arcane-button-cancel flex-1" variant="outline" onclick={() => (open = false)} disabled={isLoading}>Cancel</Button>+ <Button+ type="button"+ class="arcane-button-cancel flex-1"+ variant="outline"+ onclick={() => (open = false)}+ disabled={isLoading}+ >+ Cancel+ </Button><Button type="submit" class="arcane-button-create flex-1" disabled={isLoading}>{#if isLoading}<Loader2 class="mr-2 size-4 animate-spin" />diff --git a/frontend/src/lib/services/api/settings-api-service.ts b/frontend/src/lib/services/api/settings-api-service.tsindex 3b74bc25d..843f9cb14 100644--- a/frontend/src/lib/services/api/settings-api-service.ts+++ b/frontend/src/lib/services/api/settings-api-service.ts@@ -1,52 +1,83 @@import BaseAPIService from './api-service';-import type { Settings, OidcStatusInfo } from '$lib/types/settings.type';+import type { Settings, SettingRawResponse, OidcStatusInfo } from '$lib/types/settings.type';export default class SettingsAPIService extends BaseAPIService {async getSettings(): Promise<Settings> {- try {- const response = await this.api.get('/settings');- const data = response.data?.settings || response.data?.data || response.data;- return data;- } catch (error) {- console.error('Error fetching settings:', error);- throw error;- }+ const response = await this.api.get('/settings');+ const parsed = this.parseConfigList(response.data.settings);+ return parsed;}async getPublicSettings(): Promise<Settings> {- try {- const response = await this.api.get('/settings/public');- const data = response.data?.settings || response.data?.data || response.data;- return data;- } catch (error) {- console.error('Error fetching settings:', error);- throw error;- }+ const response = await this.api.get('/settings/public');+ const parsed = this.parseConfigList(response.data.settings);+ return parsed;}- async updateSettings(settings: Partial<Settings>): Promise<Settings> {- try {- const response = await this.api.put('/settings', settings);- const data = response.data?.settings || response.data?.data || response.data;- return data;- } catch (error) {- console.error('Error updating settings:', error);- throw error;+ async updateSettings(settings: Settings) {+ // Convert all values to string, with special handling for objects+ const settingsConvertedToString = {};+ for (const key in settings) {+ const value = (settings as any)[key];+ if (typeof value === 'object' && value !== null) {+ // Serialize objects to JSON string+ (settingsConvertedToString as any)[key] = JSON.stringify(value);+ } else {+ // Convert primitives to string+ (settingsConvertedToString as any)[key] = value.toString();+ }}- }+ const res = await this.api.put('/settings', settingsConvertedToString);- async resetSettings(): Promise<Settings> {- try {- const response = await this.api.post('/settings/reset');- const data = response.data?.settings || response.data?.data || response.data;- return data;- } catch (error) {- console.error('Error resetting settings:', error);- throw error;+ // Check if response has the expected structure+ if (res.data && res.data.settings && Array.isArray(res.data.settings)) {+ return this.parseConfigList(res.data.settings);+ } else {+ // If the response doesn't have the expected array format, return the response as-is+ // or handle it differently based on your API's actual response structure+ console.warn('Unexpected response format from updateSettings:', res.data);+ return res.data;}}async getOidcStatus(): Promise<OidcStatusInfo> {return this.handleResponse(this.api.get('/oidc/status'));}++ private parseConfigList(data: SettingRawResponse) {+ const settings: Partial<Settings> = {};+ data.forEach(({ key, value }) => {+ (settings as any)[key] = this.parseValue(key, value);+ });++ return settings as Settings;+ }++ private parseValue(key: string, value: string) {+ // Special handling for JSON fields+ if (+ key === 'onboardingSteps' ||+ key === 'registryCredentials' ||+ key === 'templateRegistries'+ ) {+ try {+ return JSON.parse(value);+ } catch {+ // Return default empty object/array if parsing fails+ if (key === 'onboardingSteps') return {};+ return [];+ }+ }++ // Handle other data types+ if (value === 'true') {+ return true;+ } else if (value === 'false') {+ return false;+ } else if (/^-?\d+(\.\d+)?$/.test(value)) {+ return parseFloat(value);+ } else {+ return value;+ }+ }}diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.tsindex 26b205dd3..de78a961e 100644--- a/frontend/src/lib/types/settings.type.ts+++ b/frontend/src/lib/types/settings.type.ts@@ -1,3 +1,57 @@+export type SettingRawResponse = {+ key: string;+ type: string;+ value: string;+ isPublic?: boolean;+}[];++export type Settings = {+ // Docker settings+ stacksDirectory: string;+ autoUpdateEnabled: boolean;+ autoUpdateInterval: number;+ pollingEnabled: boolean;+ pollingInterval: number;+ dockerPruneMode: string;+ baseServerUrl: string;++ // Authentication settings+ authLocalEnabled: boolean;+ authOidcEnabled: boolean;+ authSessionTimeout: number;+ authPasswordPolicy: string;+ authRbacEnabled: boolean;+ authOidcConfig: string;++ // Onboarding settings+ onboardingCompleted: boolean;+ onboardingSteps: {+ welcome?: boolean;+ password?: boolean;+ docker?: boolean;+ security?: boolean;+ settings?: boolean;+ };++ // Registry settings+ registryCredentials: RegistryCredential[];+ templateRegistries: TemplateRegistryConfig[];+};++export interface RegistryCredential {+ url: string;+ username: string;+ password: string;+}++export interface TemplateRegistryConfig {+ url: string;+ name: string;+ enabled: boolean;+ lastUpdated?: number;+ cacheTtl?: number;+}+export interface AuthSettings {localAuthEnabled: boolean;oidcEnabled: boolean;@@ -12,6 +66,11 @@ export interface OidcConfig {clientSecret?: string;issuerUrl: string;scopes: string;+ // Optional OIDC discovery endpoints (from backend)+ authorizationEndpoint?: string;+ tokenEndpoint?: string;+ userinfoEndpoint?: string;+ jwksUri?: string;}export interface OidcStatusInfo {@@ -22,47 +81,3 @@ export interface OidcStatusInfo {effectivelyEnabled: boolean;effectivelyConfigured: boolean;}--export interface RegistryCredential {- url: string;- username: string;- password: string;-}--export interface TemplateRegistryConfig {- url: string;- name: string;- enabled: boolean;- lastUpdated?: number;- cacheTtl?: number;-}--export interface Onboarding {- completed: boolean;- completedAt?: number;- steps?: {- welcome?: boolean;- password?: boolean;- docker?: boolean;- security?: boolean;- settings?: boolean;- };-}--export interface Settings {- id: number;- dockerTLSCert: string;- stacksDirectory: string;- autoUpdate: boolean;- autoUpdateInterval: number;- pollingEnabled: boolean;- pollingInterval: number;- pruneMode?: string;- registryCredentials: RegistryCredential[];- templateRegistries: TemplateRegistryConfig[];- auth: AuthSettings;- onboarding?: Onboarding;- baseServerUrl?: string;- createdAt: string;- updatedAt: string;-}diff --git a/frontend/src/lib/utils/redirect.util.ts b/frontend/src/lib/utils/redirect.util.tsindex be2f4ca32..9923c86ba 100644--- a/frontend/src/lib/utils/redirect.util.ts+++ b/frontend/src/lib/utils/redirect.util.ts@@ -16,7 +16,7 @@ export function getAuthRedirectPath(path: string, user: User | null, settings: Spath === '/img' ||path.startsWith('/img') ||path === '/favicon.ico';-+const isPublicPath = ['/authorize', '/device', '/health', '/healthz'].includes(path);const isOnboardingPath = path === '/onboarding' || path.startsWith('/onboarding');@@ -24,13 +24,13 @@ export function getAuthRedirectPath(path: string, user: User | null, settings: Sreturn '/auth/login';}- if (isSignedIn && settings && (!settings.onboarding || !settings.onboarding.completed)) {+ if (isSignedIn && settings && !settings.onboardingCompleted) {if (!isOnboardingPath) {return '/onboarding/welcome';}}- if (isUnauthenticatedOnlyPath && isSignedIn && settings?.onboarding?.completed) {+ if (isUnauthenticatedOnlyPath && isSignedIn && settings?.onboardingCompleted) {return '/dashboard';}diff --git a/frontend/src/routes/auth/login/+page.svelte b/frontend/src/routes/auth/login/+page.svelteindex fac209653..cd5874798 100644--- a/frontend/src/routes/auth/login/+page.svelte+++ b/frontend/src/routes/auth/login/+page.svelte@@ -7,7 +7,6 @@import { AlertCircle, LogIn, Lock, User } from '@lucide/svelte';import type { PageData } from './$types';import { goto, invalidateAll } from '$app/navigation';- import { env } from '$env/dynamic/public';import { authService } from '$lib/services/api/auth-api-service';let { data }: { data: PageData } = $props();@@ -17,11 +16,10 @@let username = $state('');let password = $state('');- const oidcForcedByEnv = env.PUBLIC_OIDC_ENABLED === 'true';- const oidcEnabledBySettings = data.settings?.auth?.oidcEnabled === true;- const showOidcLoginButton = $derived(oidcForcedByEnv || oidcEnabledBySettings);+ const oidcEnabledBySettings = data.settings?.authOidcEnabled === true;+ const showOidcLoginButton = $derived(oidcEnabledBySettings);- const localAuthEnabledBySettings = data.settings?.auth?.localAuthEnabled !== false;+ const localAuthEnabledBySettings = data.settings?.authLocalEnabled !== false;const showLocalLoginForm = $derived(localAuthEnabledBySettings);function handleOidcLogin() {diff --git a/frontend/src/routes/onboarding/complete/+page.svelte b/frontend/src/routes/onboarding/complete/+page.svelteindex fbeab6898..5324b28c3 100644--- a/frontend/src/routes/onboarding/complete/+page.svelte+++ b/frontend/src/routes/onboarding/complete/+page.svelte@@ -5,6 +5,9 @@import { goto, invalidateAll } from '$app/navigation';import { Loader2, CheckCircle, ArrowRight } from '@lucide/svelte';+ let { data } = $props();+ let currentSettings = $state(data.settings);+let isLoading = $state(false);async function completeOnboarding() {@@ -12,16 +15,14 @@try {await settingsAPI.updateSettings({- onboarding: {- completed: true,- completedAt: Date.now(),- steps: {- welcome: true,- password: true,- docker: true,- security: true,- settings: true- }+ ...currentSettings,+ onboardingCompleted: true,+ onboardingSteps: {+ welcome: true,+ password: true,+ docker: true,+ security: true,+ settings: true}});diff --git a/frontend/src/routes/onboarding/complete/+page.ts b/frontend/src/routes/onboarding/complete/+page.tsnew file mode 100644index 000000000..4c62ab239--- /dev/null+++ b/frontend/src/routes/onboarding/complete/+page.ts@@ -0,0 +1,13 @@+import { redirect } from '@sveltejs/kit';+import { settingsAPI } from '$lib/services/api';+import type { PageLoad } from './$types';++export const load: PageLoad = async () => {+ const settings = await settingsAPI.getSettings();++ if (settings.onboardingCompleted) {+ throw redirect(302, '/dashboard');+ }++ return { settings };+};diff --git a/frontend/src/routes/onboarding/docker/+page.svelte b/frontend/src/routes/onboarding/docker/+page.svelteindex 9dbea3e2d..7b3d0f721 100644--- a/frontend/src/routes/onboarding/docker/+page.svelte+++ b/frontend/src/routes/onboarding/docker/+page.svelte@@ -9,57 +9,33 @@import { settingsAPI } from '$lib/services/api';import { toast } from 'svelte-sonner';import { goto } from '$app/navigation';- import { Loader2, CheckCircle, AlertCircle } from '@lucide/svelte';+ import { Loader2 } from '@lucide/svelte';++ let { data } = $props();+ let currentSettings = $state(data.settings);let isLoading = $state(false);- let testingConnection = $state(false);- let connectionStatus = $state<'success' | 'error' | null>(null);let dockerSettings = $state({- stacksDirectory: '/opt/stacks',- dockerTLSCert: '',+ stacksDirectory: 'data/stacks',pollingEnabled: true,pollingInterval: '5'});- async function testDockerConnection() {- testingConnection = true;- connectionStatus = null;-- try {- await settingsAPI.updateSettings({- stacksDirectory: dockerSettings.stacksDirectory,- dockerTLSCert: dockerSettings.dockerTLSCert,- pollingEnabled: dockerSettings.pollingEnabled,- pollingInterval: parseInt(dockerSettings.pollingInterval)- });-- connectionStatus = 'success';- toast.success('Docker connection successful!');- } catch (error) {- connectionStatus = 'error';- toast.error('Docker connection failed. Please check your settings.');- } finally {- testingConnection = false;- }- }-async function handleNext() {isLoading = true;try {+ const currentSettings = await settingsAPI.getSettings();await settingsAPI.updateSettings({+ ...currentSettings,stacksDirectory: dockerSettings.stacksDirectory,- dockerTLSCert: dockerSettings.dockerTLSCert,pollingEnabled: dockerSettings.pollingEnabled,pollingInterval: parseInt(dockerSettings.pollingInterval),- onboarding: {- completed: false,- steps: {- welcome: true,- password: true,- docker: true- }+ onboardingCompleted: false,+ onboardingSteps: {+ ...currentSettings.onboardingSteps,+ docker: true}});@@ -102,17 +78,6 @@Directory where Docker Compose files will be stored</p></div>-- <div class="space-y-2">- <Label for="docker-tls">Docker TLS Certificate (Optional)</Label>- <Textarea- id="docker-tls"- bind:value={dockerSettings.dockerTLSCert}- placeholder="-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"- rows={4}- />- <p class="text-xs text-muted-foreground">Leave empty for local Docker daemon</p>- </div></Card.Content></Card.Root>@@ -146,26 +111,6 @@</Select.Root></div>{/if}-- <Button- variant="outline"- onclick={testDockerConnection}- disabled={testingConnection}- class="w-full"- >- {#if testingConnection}- <Loader2 class="mr-2 size-4 animate-spin" />- Testing Connection...- {:else if connectionStatus === 'success'}- <CheckCircle class="mr-2 size-4 text-green-500" />- Connection Successful- {:else if connectionStatus === 'error'}- <AlertCircle class="mr-2 size-4 text-red-500" />- Connection Failed- {:else}- Test Docker Connection- {/if}- </Button></Card.Content></Card.Root></div>diff --git a/frontend/src/routes/onboarding/docker/+page.ts b/frontend/src/routes/onboarding/docker/+page.tsindex 17886c85e..476d17ce0 100644--- a/frontend/src/routes/onboarding/docker/+page.ts+++ b/frontend/src/routes/onboarding/docker/+page.ts@@ -3,11 +3,11 @@ import type { PageLoad } from './$types';import { settingsAPI } from '$lib/services/api';export const load: PageLoad = async () => {- const settings = await settingsAPI.getSettings();-- if (settings.onboarding?.completed) {- throw redirect(302, '/');- }-- return { settings };-};\ No newline at end of file+ const settings = await settingsAPI.getSettings();++ if (settings.onboardingCompleted) {+ throw redirect(302, '/dashboard');+ }++ return { settings };+};diff --git a/frontend/src/routes/onboarding/password/+page.svelte b/frontend/src/routes/onboarding/password/+page.svelteindex 526962f52..f7dedcb16 100644--- a/frontend/src/routes/onboarding/password/+page.svelte+++ b/frontend/src/routes/onboarding/password/+page.svelte@@ -7,33 +7,26 @@import { preventDefault } from '$lib/utils/form.utils';import { userAPI } from '$lib/services/api';import { goto } from '$app/navigation';- import type { Settings } from '$lib/types/settings.type';import settingsStore from '$lib/stores/config-store';import { settingsAPI } from '$lib/services/api';let { data } = $props();let currentSettings = $state(data.settings);- const updatedSettings: Partial<Settings> = {- onboarding: {- steps: {- welcome: true,- password: true,- settings: false- },- completed: false- }- };-async function continueToNextStep() {- currentSettings = await settingsAPI.updateSettings({+ const updatedSettings = await settingsAPI.updateSettings({...currentSettings,- ...updatedSettings+ onboardingCompleted: false,+ onboardingSteps: {+ ...currentSettings.onboardingSteps,+ password: true+ }});- settingsStore.reload();+ currentSettings = updatedSettings;+ settingsStore.set(updatedSettings);- goto('/onboarding/settings');+ goto('/onboarding/docker');}let password = $state('');@@ -64,8 +57,6 @@});await continueToNextStep();-- goto('/onboarding/settings', { invalidateAll: true });} catch (err) {console.error('Error in handleSubmit:', err);error = err instanceof Error ? err.message : 'An unexpected error occurred';@@ -79,7 +70,9 @@<h1 class="mb-8 text-center text-3xl font-bold">Change Admin Password</h1><div class="mb-8 space-y-2">- <p class="text-md text-center">For security reasons, please change the default admin password.</p>+ <p class="text-md text-center">+ For security reasons, please change the default admin password.+ </p></div>{#if error}@@ -94,19 +87,35 @@<div class="space-y-6"><div class="space-y-4"><Label for="password" class="mb-2 block text-base">New Password</Label>- <Input id="password" type="password" bind:value={password} placeholder="Enter new password" class="bg-muted/10 h-12 px-4" required />+ <Input+ id="password"+ type="password"+ bind:value={password}+ placeholder="Enter new password"+ class="bg-muted/10 h-12 px-4"+ required+ /></div><div class="space-y-4"><Label for="confirmPassword" class="mb-2 block text-base">Confirm Password</Label>- <Input id="confirmPassword" type="password" bind:value={confirmPassword} placeholder="Confirm new password" class="bg-muted/10 h-12 px-4" required />+ <Input+ id="confirmPassword"+ type="password"+ bind:value={confirmPassword}+ placeholder="Confirm new password"+ class="bg-muted/10 h-12 px-4"+ required+ /></div></div><div class="flex justify-center pt-8"><Button type="submit" disabled={loading} class="flex h-12 w-[80%] items-center px-8">{#if loading}- <span class="inline-block size-4 animate-spin rounded-full border-2 border-white border-t-transparent"></span>+ <span+ class="inline-block size-4 animate-spin rounded-full border-2 border-white border-t-transparent"+ ></span>{/if}Continue<ChevronRight class="size-4" />diff --git a/frontend/src/routes/onboarding/password/+page.ts b/frontend/src/routes/onboarding/password/+page.tsindex 9870ef301..4c62ab239 100644--- a/frontend/src/routes/onboarding/password/+page.ts+++ b/frontend/src/routes/onboarding/password/+page.ts@@ -5,8 +5,8 @@ import type { PageLoad } from './$types';export const load: PageLoad = async () => {const settings = await settingsAPI.getSettings();- if (settings.onboarding?.completed) {- throw redirect(302, '/');+ if (settings.onboardingCompleted) {+ throw redirect(302, '/dashboard');}return { settings };diff --git a/frontend/src/routes/onboarding/security/+page.svelte b/frontend/src/routes/onboarding/security/+page.svelteindex 5f3cf070c..f8de1c96f 100644--- a/frontend/src/routes/onboarding/security/+page.svelte+++ b/frontend/src/routes/onboarding/security/+page.svelte@@ -9,6 +9,10 @@import { toast } from 'svelte-sonner';import { goto } from '$app/navigation';import { Loader2 } from '@lucide/svelte';+ import settingsStore from '$lib/stores/config-store';++ let { data } = $props();+ let currentSettings = $state(data.settings);let isLoading = $state(false);@@ -18,43 +22,41 @@oidcClientId: '',oidcClientSecret: '',oidcScopes: 'openid email profile',- sessionTimeout: '24',- requireTLS: false+ sessionTimeout: '24'});async function handleNext() {isLoading = true;try {- const authSettings = {- localAuthEnabled: securitySettings.authType === 'local',- oidcEnabled: securitySettings.authType === 'oidc',- sessionTimeout: parseInt(securitySettings.sessionTimeout) * 60, // Convert hours to minutes- passwordPolicy: 'strong',- rbacEnabled: false,- ...(securitySettings.authType === 'oidc' && {- oidc: {- clientId: securitySettings.oidcClientId,- clientSecret: securitySettings.oidcClientSecret,- issuerUrl: securitySettings.oidcIssuerUrl,- scopes: securitySettings.oidcScopes- }- })- };-- await settingsAPI.updateSettings({- auth: authSettings,- onboarding: {- completed: false,- steps: {- welcome: true,- password: true,- docker: true,- security: true- }+ let authOidcConfig = '';+ if (securitySettings.authType === 'oidc') {+ authOidcConfig = JSON.stringify({+ clientId: securitySettings.oidcClientId,+ clientSecret: securitySettings.oidcClientSecret,+ issuerUrl: securitySettings.oidcIssuerUrl,+ scopes: securitySettings.oidcScopes+ });+ }++ const updatedSettings = await settingsAPI.updateSettings({+ ...currentSettings,+ authLocalEnabled: securitySettings.authType === 'local',+ authOidcEnabled: securitySettings.authType === 'oidc',+ authSessionTimeout: parseInt(securitySettings.sessionTimeout) * 3600,+ authPasswordPolicy: 'strong',+ authRbacEnabled: false,+ authOidcConfig: authOidcConfig,+ onboardingCompleted: false,+ onboardingSteps: {+ ...currentSettings.onboardingSteps,+ security: true}});+ currentSettings = updatedSettings;+ settingsStore.set(updatedSettings);+goto('/onboarding/settings');} catch (error) {toast.error('Failed to save security settings');diff --git a/frontend/src/routes/onboarding/security/+page.ts b/frontend/src/routes/onboarding/security/+page.tsindex 17886c85e..476d17ce0 100644--- a/frontend/src/routes/onboarding/security/+page.ts+++ b/frontend/src/routes/onboarding/security/+page.ts@@ -3,11 +3,11 @@ import type { PageLoad } from './$types';import { settingsAPI } from '$lib/services/api';export const load: PageLoad = async () => {- const settings = await settingsAPI.getSettings();-- if (settings.onboarding?.completed) {- throw redirect(302, '/');- }-- return { settings };-};\ No newline at end of file+ const settings = await settingsAPI.getSettings();++ if (settings.onboardingCompleted) {+ throw redirect(302, '/dashboard');+ }++ return { settings };+};diff --git a/frontend/src/routes/onboarding/settings/+page.svelte b/frontend/src/routes/onboarding/settings/+page.svelteindex 84aaae81a..927581ebe 100644--- a/frontend/src/routes/onboarding/settings/+page.svelte+++ b/frontend/src/routes/onboarding/settings/+page.svelte@@ -10,6 +10,9 @@import { goto } from '$app/navigation';import { Loader2 } from '@lucide/svelte';+ let { data } = $props();+ let currentSettings = $state(data.settings);+let isLoading = $state(false);let appSettings = $state({@@ -25,19 +28,15 @@try {await settingsAPI.updateSettings({- autoUpdate: appSettings.autoUpdate,+ ...currentSettings,+ autoUpdateEnabled: appSettings.autoUpdate,autoUpdateInterval: parseInt(appSettings.autoUpdateInterval),- pruneMode: appSettings.pruneMode,+ dockerPruneMode: appSettings.pruneMode,baseServerUrl: appSettings.baseServerUrl,- onboarding: {- completed: false,- steps: {- welcome: true,- password: true,- docker: true,- security: true,- settings: true- }+ onboardingCompleted: false,+ onboardingSteps: {+ ...currentSettings.onboardingSteps,+ settings: true}});diff --git a/frontend/src/routes/onboarding/settings/+page.ts b/frontend/src/routes/onboarding/settings/+page.tsindex 9870ef301..4c62ab239 100644--- a/frontend/src/routes/onboarding/settings/+page.ts+++ b/frontend/src/routes/onboarding/settings/+page.ts@@ -5,8 +5,8 @@ import type { PageLoad } from './$types';export const load: PageLoad = async () => {const settings = await settingsAPI.getSettings();- if (settings.onboarding?.completed) {- throw redirect(302, '/');+ if (settings.onboardingCompleted) {+ throw redirect(302, '/dashboard');}return { settings };diff --git a/frontend/src/routes/onboarding/welcome/+page.svelte b/frontend/src/routes/onboarding/welcome/+page.svelteindex 63643b6eb..4aaef5cd2 100644--- a/frontend/src/routes/onboarding/welcome/+page.svelte+++ b/frontend/src/routes/onboarding/welcome/+page.svelte@@ -2,28 +2,20 @@import { Button } from '$lib/components/ui/button/index.js';import { CheckCircle2, ChevronRight } from '@lucide/svelte';import { goto } from '$app/navigation';- import type { Settings } from '$lib/types/settings.type';import settingsStore from '$lib/stores/config-store';import { settingsAPI } from '$lib/services/api';let { data } = $props();let currentSettings = $state(data.settings);- const updatedSettings: Partial<Settings> = {- onboarding: {- steps: {- welcome: true,- password: false,- settings: false- },- completed: false- }- };-async function continueToNextStep() {- currentSettings = await settingsAPI.updateSettings({+ await settingsAPI.updateSettings({...currentSettings,- ...updatedSettings+ onboardingCompleted: false,+ onboardingSteps: {+ ...currentSettings.onboardingSteps,+ welcome: true+ }});settingsStore.reload();@@ -36,7 +28,9 @@<h1 class="mb-6 text-3xl font-bold">Welcome to Arcane</h1><div class="mb-8 space-y-6">- <p class="text-xl">Thank you for installing Arcane! Let's get you set up with a few quick steps.</p>+ <p class="text-xl">+ Thank you for installing Arcane! Let's get you set up with a few quick steps.+ </p><div class="space-y-4"><p class="text-lg font-medium">This wizard will help you:</p>@@ -69,7 +63,11 @@</div><div class="flex justify-center pt-8">- <Button type="button" onclick={() => continueToNextStep()} class="flex h-12 w-[80%] items-center gap-2 px-8">+ <Button+ type="button"+ onclick={() => continueToNextStep()}+ class="flex h-12 w-[80%] items-center gap-2 px-8"+ >Continue<ChevronRight class="size-4" /></Button>diff --git a/frontend/src/routes/onboarding/welcome/+page.ts b/frontend/src/routes/onboarding/welcome/+page.tsindex 9870ef301..4c62ab239 100644--- a/frontend/src/routes/onboarding/welcome/+page.ts+++ b/frontend/src/routes/onboarding/welcome/+page.ts@@ -5,8 +5,8 @@ import type { PageLoad } from './$types';export const load: PageLoad = async () => {const settings = await settingsAPI.getSettings();- if (settings.onboarding?.completed) {- throw redirect(302, '/');+ if (settings.onboardingCompleted) {+ throw redirect(302, '/dashboard');}return { settings };diff --git a/frontend/src/routes/settings/docker/+page.svelte b/frontend/src/routes/settings/docker/+page.svelteindex 730b6e2ab..209ab8bd1 100644--- a/frontend/src/routes/settings/docker/+page.svelte+++ b/frontend/src/routes/settings/docker/+page.svelte@@ -22,19 +22,23 @@});async function updateSettingsConfig(updatedSettings: Partial<Settings>) {- currentSettings = await settingsAPI.updateSettings({- ...currentSettings,- ...updatedSettings- });-- settingsStore.reload();+ try {+ currentSettings = await settingsAPI.updateSettings({+ ...currentSettings,+ ...updatedSettings+ });+ settingsStore.reload();+ } catch (error) {+ console.error('Error updating settings:', error);+ throw error;+ }}function handleDockerSettingUpdates() {isLoading.saving = true;updateSettingsConfig({- pruneMode: 'all',- autoUpdate: autoUpdateSwitch.value,+ dockerPruneMode: 'all',+ autoUpdateEnabled: autoUpdateSwitch.value,pollingEnabled: pollingEnabledSwitch.value,pollingInterval: pollingIntervalInput.value,autoUpdateInterval: autoUpdateIntervalInput.value@@ -43,6 +47,10 @@toast.success(`Settings Saved Successfully`);await invalidateAll();})+ .catch((error) => {+ toast.error('Failed to save settings');+ console.error('Settings save error:', error);+ }).finally(() => {isLoading.saving = false;});@@ -69,10 +77,10 @@});$effect(() => {- pollingIntervalInput.value = currentSettings.pollingInterval;- pollingEnabledSwitch.value = currentSettings.pollingEnabled;- autoUpdateSwitch.value = currentSettings.autoUpdate;- autoUpdateIntervalInput.value = currentSettings.autoUpdateInterval;+ pollingIntervalInput.value = currentSettings.pollingInterval || 60;+ pollingEnabledSwitch.value = currentSettings.pollingEnabled || false;+ autoUpdateSwitch.value = currentSettings.autoUpdateEnabled || false;+ autoUpdateIntervalInput.value = currentSettings.autoUpdateInterval || 60;});let isPollingConfigValid = $derived(@@ -116,7 +124,7 @@</div><!-- Alert Section -->- {#if currentSettings.autoUpdate && currentSettings.pollingEnabled}+ {#if currentSettings.autoUpdateEnabled && currentSettings.pollingEnabled}<div class="settings-alert"><Alert.Root variant="warning"><Zap class="size-4" />@@ -183,7 +191,7 @@description="Automatically update containers when newer images are found"/>- {#if currentSettings.autoUpdate}+ {#if currentSettings.autoUpdateEnabled}<div class="pl-4"><FormInputbind:input={autoUpdateIntervalInput}@@ -202,7 +210,7 @@<Alert.Title>Automation Summary</Alert.Title><Alert.Description><ul class="list-inside list-disc text-sm">- {#if currentSettings.autoUpdate}+ {#if currentSettings.autoUpdateEnabled}<li>Images checked every {pollingIntervalInput.value || 60} minutes</li>{:else}<li>Manual updates only (auto-update disabled)</li>@@ -232,13 +240,14 @@<Label for="pruneMode" class="text-base font-medium">Prune Action Behavior</Label><RadioGroup.Root- value={currentSettings.pruneMode}+ value={currentSettings.dockerPruneMode || 'all'}onValueChange={(val) => {- settingsAPI.updateSettings({- ...currentSettings,- pruneMode: val as 'all' | 'dangling'+ updateSettingsConfig({+ dockerPruneMode: val as 'all' | 'dangling'+ }).catch((error) => {+ toast.error('Failed to update prune mode');+ console.error('Error updating prune mode:', error);});- settingsStore.reload();}}class="space-y-3"id="pruneMode"@@ -278,7 +287,7 @@<p class="text-muted-foreground text-sm"><strong>Note:</strong> This setting affects the "Prune Unused Images" action on theImages page.- {currentSettings.pruneMode === 'all'+ {(currentSettings.dockerPruneMode || 'all') === 'all'? 'All unused images will be removed, which frees up more space but may require re-downloading images later.': 'Only dangling images will be removed, which is safer but may leave some unused images behind.'}</p>diff --git a/frontend/src/routes/settings/general/+page.svelte b/frontend/src/routes/settings/general/+page.svelteindex bd36b479f..39adeb6a4 100644--- a/frontend/src/routes/settings/general/+page.svelte+++ b/frontend/src/routes/settings/general/+page.svelte@@ -14,11 +14,16 @@let currentSettings = $state(data.settings);async function updateSettingsConfig(updatedSettings: Partial<Settings>) {- currentSettings = await settingsAPI.updateSettings({- ...currentSettings,- ...updatedSettings- });- settingsStore.reload();+ try {+ currentSettings = await settingsAPI.updateSettings({+ ...currentSettings,+ ...updatedSettings+ });+ settingsStore.reload();+ } catch (error) {+ console.error('Error updating settings:', error);+ throw error;+ }}function handleGeneralSettingUpdates() {@@ -31,6 +36,10 @@toast.success(`Settings Saved Successfully`);await invalidateAll();})+ .catch((error) => {+ toast.error('Failed to save settings');+ console.error('Settings save error:', error);+ }).finally(() => {isLoading.saving = false;});@@ -51,7 +60,7 @@});$effect(() => {- stacksDirectoryInput.value = currentSettings.stacksDirectory;+ stacksDirectoryInput.value = currentSettings.stacksDirectory || '';baseServerUrlInput.value = currentSettings.baseServerUrl || 'localhost';});</script>diff --git a/frontend/src/routes/settings/rbac/+page.svelte b/frontend/src/routes/settings/rbac/+page.sveltedeleted file mode 100644index 363666493..000000000--- a/frontend/src/routes/settings/rbac/+page.svelte+++ /dev/null@@ -1,234 +0,0 @@-<script lang="ts">- import * as Card from '$lib/components/ui/card/index.js';- import { Button } from '$lib/components/ui/button/index.js';- import { Input } from '$lib/components/ui/input/index.js';- import { Shield, Plus, Users, Settings, Save, RefreshCw } from '@lucide/svelte';- import type { PageData } from './$types';- import Switch from '$lib/components/ui/switch/switch.svelte';- import settingsStore from '$lib/stores/config-store';-- let { data }: { data: PageData } = $props();-- let isLoading = $state({- saving: false- });-- const roles = [- {- id: 1,- name: 'Admin',- description: 'Full system access',- permissions: [- 'containers:manage',- 'stacks:manage',- 'volumes:manage',- 'networks:manage',- 'settings:manage',- 'users:manage'- ]- },- {- id: 2,- name: 'User',- description: 'Container and stack operations',- permissions: [- 'containers:view',- 'containers:manage',- 'stacks:view',- 'stacks:manage',- 'volumes:view',- 'networks:view'- ]- },- {- id: 3,- name: 'Viewer',- description: 'Read-only access',- permissions: ['containers:view', 'stacks:view', 'volumes:view', 'networks:view']- }- ];-- // Available permissions categories- const permissionCategories = [- {- name: 'Containers',- permissions: ['containers:view', 'containers:manage', 'containers:deploy']- },- {- name: 'Stacks',- permissions: ['stacks:view', 'stacks:manage', 'stacks:deploy']- },- {- name: 'Volumes',- permissions: ['volumes:view', 'volumes:manage', 'volumes:create']- },- {- name: 'Networks',- permissions: ['networks:view', 'networks:manage', 'networks:create']- },- {- name: 'Settings',- permissions: ['settings:view', 'settings:manage']- },- {- name: 'Users',- permissions: ['users:view', 'users:manage', 'users:create']- }- ];-- let selectedRole = $state(roles[0]);-</script>--<div class="space-y-6">- <div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">- <div>- <h1 class="text-3xl font-bold tracking-tight">Role-Based Access Control</h1>- <p class="text-muted-foreground mt-1 text-sm">Manage user roles and permissions</p>- </div>-- <Button disabled={isLoading.saving} class="arcane-button-save h-10">- {#if isLoading.saving}- <RefreshCw class="size-4 animate-spin" />- Saving...- {:else}- <Save class="size-4" />- Save Settings- {/if}- </Button>- </div>-- <div class="mb-6">- <div class="bg-muted/30 flex items-center justify-between rounded-lg border p-4">- <div class="space-y-0.5">- <label for="rbacEnabledSwitch" class="text-base font-medium"- >Enable Role-Based Access Control</label- >- <p class="text-muted-foreground text-sm">- Control user permissions with customizable roles- </p>- </div>- <Switch- id="rbacEnabledSwitch"- name="rbacEnabled"- checked={$settingsStore.auth?.rbacEnabled}- onCheckedChange={() => {}}- />- </div>- </div>-- <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">- <div class="lg:col-span-1">- <Card.Root class="h-full border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center justify-between">- <div class="flex items-center gap-2">- <div class="rounded-full bg-blue-500/10 p-2">- <Users class="size-5 text-blue-500" />- </div>- <Card.Title>Roles</Card.Title>- </div>- <Button variant="outline" size="sm">- <Plus class="mr-1 size-4" /> Add- </Button>- </div>- </Card.Header>- <Card.Content>- <div class="space-y-2">- {#each roles as role (role.id)}- <button- class="flex w-full items-center justify-between rounded-md border p-3 text-left transition-colors {selectedRole.id ===- role.id- ? 'bg-primary text-primary-foreground border-primary'- : 'hover:bg-muted/50'}"- onclick={() => (selectedRole = role)}- >- <div>- <div class="font-medium">{role.name}</div>- <div- class="text-xs {selectedRole.id === role.id- ? 'text-primary-foreground/90'- : 'text-muted-foreground'}"- >- {role.description}- </div>- </div>- <Shield class="size-4 opacity-70" />- </button>- {/each}- </div>- </Card.Content>- </Card.Root>- </div>-- <div class="lg:col-span-2">- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center justify-between">- <div class="flex items-center gap-2">- <div class="rounded-full bg-purple-500/10 p-2">- <Settings class="size-5 text-purple-500" />- </div>- <div>- <Card.Title>Role: {selectedRole.name}</Card.Title>- <Card.Description>{selectedRole.description}</Card.Description>- </div>- </div>- <div class="space-x-2">- <Button variant="outline" size="sm">Delete</Button>- <Button size="sm">Save Changes</Button>- </div>- </div>- </Card.Header>- <Card.Content>- <div class="space-y-6">- <!-- Role Info -->- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">- <div class="space-y-2">- <label for="roleName" class="text-sm font-medium">Role Name</label>- <Input- id="roleName"- name="roleName"- value={selectedRole.name}- placeholder="Enter role name"- />- </div>- <div class="space-y-2">- <label for="roleDescription" class="text-sm font-medium">Description</label>- <Input- id="roleDescription"- name="roleDescription"- value={selectedRole.description}- placeholder="Brief description"- />- </div>- </div>-- <!-- Permissions -->- <div>- <h3 class="mb-3 text-sm font-medium">Permissions</h3>- <div class="divide-y rounded-md border">- {#each permissionCategories as category (category.name)}- <div class="p-3">- <h4 class="mb-2 font-medium">{category.name}</h4>- <div class="grid grid-cols-1 gap-2 sm:grid-cols-2">- {#each category.permissions as permission (permission)}- <label class="flex items-center space-x-2 text-sm">- <input- type="checkbox"- class="text-primary focus:ring-primary rounded border-gray-300"- checked={selectedRole.permissions.includes(permission)}- />- <span>{permission.split(':')[1]}</span>- </label>- {/each}- </div>- </div>- {/each}- </div>- </div>- </div>- </Card.Content>- </Card.Root>- </div>- </div>-</div>diff --git a/frontend/src/routes/settings/rbac/+page.ts b/frontend/src/routes/settings/rbac/+page.tsdeleted file mode 100644index 5b0721811..000000000--- a/frontend/src/routes/settings/rbac/+page.ts+++ /dev/null@@ -1,25 +0,0 @@-import type { PageLoad } from './$types';-import { settingsAPI, userAPI } from '$lib/services/api';--export const load: PageLoad = async () => {- try {- const [settings, users, roles] = await Promise.all([settingsAPI.getSettings(), userAPI.list().catch(() => []), userAPI.getRoles().catch(() => [])]);-- return {- settings,- users,- roles- };- } catch (error) {- console.error('Failed to load RBAC settings:', error);- return {- settings: {- auth: {- rbacEnabled: false- }- },- users: [],- roles: []- };- }-};diff --git a/frontend/src/routes/settings/security/+page.svelte b/frontend/src/routes/settings/security/+page.svelteindex bc701da60..177bfa688 100644--- a/frontend/src/routes/settings/security/+page.svelte+++ b/frontend/src/routes/settings/security/+page.svelte@@ -35,49 +35,67 @@let isOidcViewMode = $derived(data.oidcStatus.envForced && data.oidcStatus.envConfigured);$effect(() => {- localAuthEnabled = currentSettings.auth?.localAuthEnabled ?? true;- oidcEnabled = currentSettings.auth?.oidcEnabled ?? false;- sessionTimeout = currentSettings.auth?.sessionTimeout ?? 60;- passwordPolicy = currentSettings.auth?.passwordPolicy ?? 'strong';+ localAuthEnabled = currentSettings.authLocalEnabled ?? true;+ oidcEnabled = currentSettings.authOidcEnabled ?? false;+ sessionTimeout = currentSettings.authSessionTimeout ?? 60;+ passwordPolicy = currentSettings.authPasswordPolicy ?? 'strong';- oidcConfigForm.clientId = currentSettings.auth?.oidc?.clientId || '';- oidcConfigForm.scopes = currentSettings.auth?.oidc?.scopes || 'openid email profile';+ // Parse OIDC config from string if it exists+ if (currentSettings.authOidcConfig) {+ try {+ const oidcConfig = JSON.parse(currentSettings.authOidcConfig);+ oidcConfigForm.clientId = oidcConfig.clientId || '';+ oidcConfigForm.scopes = oidcConfig.scopes || 'openid email profile';+ oidcConfigForm.issuerUrl = oidcConfig.issuerUrl || '';+ } catch (e) {+ console.warn('Failed to parse OIDC config:', e);+ }+ }oidcConfigForm.clientSecret = '';});async function updateSettingsConfig(updatedSettings: Partial<Settings>) {- currentSettings = await settingsAPI.updateSettings({- ...currentSettings,- ...updatedSettings- });- settingsStore.reload();+ try {+ currentSettings = await settingsAPI.updateSettings({+ ...currentSettings,+ ...updatedSettings+ });+ settingsStore.reload();+ } catch (error) {+ console.error('Error updating settings:', error);+ throw error;+ }}function handleSecuritySettingUpdates() {isLoading.saving = true;++ // Prepare OIDC config if needed+ let oidcConfigString = currentSettings.authOidcConfig;+ if (oidcEnabled && !data.oidcStatus.envForced) {+ oidcConfigString = JSON.stringify({+ clientId: oidcConfigForm.clientId,+ clientSecret: oidcConfigForm.clientSecret || '',+ issuerUrl: oidcConfigForm.issuerUrl,+ scopes: oidcConfigForm.scopes+ });+ }+updateSettingsConfig({- auth: {- ...currentSettings.auth,- localAuthEnabled: localAuthEnabled,- oidcEnabled: oidcEnabled,- sessionTimeout: sessionTimeout,- passwordPolicy: passwordPolicy,- ...(oidcEnabled && !data.oidcStatus.envForced- ? {- oidc: {- clientId: oidcConfigForm.clientId,- clientSecret: oidcConfigForm.clientSecret || '',- issuerUrl: oidcConfigForm.issuerUrl,- scopes: oidcConfigForm.scopes- }- }- : {})- }+ authLocalEnabled: localAuthEnabled,+ authOidcEnabled: oidcEnabled,+ authSessionTimeout: sessionTimeout,+ authPasswordPolicy: passwordPolicy,+ authOidcConfig: oidcConfigString}).then(async () => {toast.success(`Settings Saved Successfully`);await invalidateAll();})+ .catch((error) => {+ toast.error('Failed to save settings');+ console.error('Settings save error:', error);+ }).finally(() => {isLoading.saving = false;});@@ -93,10 +111,18 @@function openOidcDialog() {if (!isOidcViewMode) {- oidcConfigForm.clientId = currentSettings.auth?.oidc?.clientId || '';+ // Parse current config if it exists+ if (currentSettings.authOidcConfig) {+ try {+ const oidcConfig = JSON.parse(currentSettings.authOidcConfig);+ oidcConfigForm.clientId = oidcConfig.clientId || '';+ oidcConfigForm.issuerUrl = oidcConfig.issuerUrl || '';+ oidcConfigForm.scopes = oidcConfig.scopes || 'openid email profile';+ } catch (e) {+ console.warn('Failed to parse OIDC config:', e);+ }+ }oidcConfigForm.clientSecret = '';- oidcConfigForm.issuerUrl = currentSettings.auth?.oidc?.issuerUrl || '';- oidcConfigForm.scopes = currentSettings.auth?.oidc?.scopes || 'openid email profile';}showOidcConfigDialog = true;}@@ -106,20 +132,19 @@isLoading.saving = true;oidcEnabled = true;+ const oidcConfigString = JSON.stringify({+ clientId: oidcConfigForm.clientId,+ clientSecret: oidcConfigForm.clientSecret || '',+ issuerUrl: oidcConfigForm.issuerUrl,+ scopes: oidcConfigForm.scopes+ });+await updateSettingsConfig({- auth: {- ...currentSettings.auth,- localAuthEnabled: localAuthEnabled,- oidcEnabled: true,- sessionTimeout: sessionTimeout,- passwordPolicy: passwordPolicy,- oidc: {- clientId: oidcConfigForm.clientId,- clientSecret: oidcConfigForm.clientSecret || '',- issuerUrl: oidcConfigForm.issuerUrl,- scopes: oidcConfigForm.scopes- }- }+ authLocalEnabled: localAuthEnabled,+ authOidcEnabled: true,+ authSessionTimeout: sessionTimeout,+ authPasswordPolicy: passwordPolicy,+ authOidcConfig: oidcConfigString});toast.success('OIDC configuration saved successfully.');