Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: add api key authentication (#1046)
Kyle Mendellecaa3e07a9e2
diff --git a/.github/workflows/svelte-check.yml b/.github/workflows/svelte-check.ymlindex 0aabc947d..b6dfed1b8 100644--- a/.github/workflows/svelte-check.yml+++ b/.github/workflows/svelte-check.yml@@ -26,7 +26,7 @@ on:jobs:type-check:name: Run Svelte Check- runs-on: depot-ubuntu-latest+ runs-on: depot-ubuntu-24.04-8permissions:contents: readchecks: writediff --git a/backend/internal/cli/root.go b/backend/cli/root.gosimilarity index 94%rename from backend/internal/cli/root.gorename to backend/cli/root.goindex ec37a5ad5..b638770dc 100644--- a/backend/internal/cli/root.go+++ b/backend/cli/root.go@@ -7,8 +7,8 @@ import ("github.com/spf13/cobra"+ "github.com/getarcaneapp/arcane/backend/cli/upgrade""github.com/getarcaneapp/arcane/backend/internal/bootstrap"- "github.com/getarcaneapp/arcane/backend/internal/cli/upgrade""github.com/getarcaneapp/arcane/backend/internal/config""github.com/getarcaneapp/arcane/backend/internal/utils/signals""go.getarcane.app/cli/pkg/generate"diff --git a/backend/internal/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.gosimilarity index 100%rename from backend/internal/cli/upgrade/upgrade.gorename to backend/cli/upgrade/upgrade.godiff --git a/backend/internal/cli/version.go b/backend/cli/version.gosimilarity index 100%rename from backend/internal/cli/version.gorename to backend/cli/version.godiff --git a/backend/cmd/main.go b/backend/cmd/main.goindex fe03c1081..ae8274fad 100644--- a/backend/cmd/main.go+++ b/backend/cmd/main.go@@ -1,9 +1,13 @@package mainimport (- "github.com/getarcaneapp/arcane/backend/internal/cli"+ "github.com/getarcaneapp/arcane/backend/cli")+// @title Arcane API+// @version 1.0+// @description.markdown+func main() {cli.Execute()}diff --git a/backend/go.mod b/backend/go.modindex 1d373b8cd..c5b522b9f 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -44,6 +44,7 @@ require (golang.org/x/oauth2 v0.33.0golang.org/x/sync v0.18.0golang.org/x/text v0.31.0+ gopkg.in/yaml.v3 v3.0.1gorm.io/driver/postgres v1.6.0gorm.io/gorm v1.31.1)diff --git a/backend/internal/api/api_key_handler.go b/backend/internal/api/api_key_handler.gonew file mode 100644index 000000000..2b42ce2b6--- /dev/null+++ b/backend/internal/api/api_key_handler.go@@ -0,0 +1,226 @@+package api++import (+ "errors"+ "net/http"++ "github.com/getarcaneapp/arcane/backend/internal/common"+ "github.com/getarcaneapp/arcane/backend/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"+ "github.com/gin-gonic/gin"+ "go.getarcane.app/types/apikey"+)++type ApiKeyHandler struct {+ apiKeyService *services.ApiKeyService+}++func NewApiKeyHandler(group *gin.RouterGroup, apiKeyService *services.ApiKeyService, authMiddleware *middleware.AuthMiddleware) {+ handler := &ApiKeyHandler{apiKeyService: apiKeyService}++ apiGroup := group.Group("/api-keys")+ apiGroup.Use(authMiddleware.WithAdminRequired().Add())+ {+ apiGroup.GET("", handler.ListApiKeys)+ apiGroup.POST("", handler.CreateApiKey)+ apiGroup.GET("/:id", handler.GetApiKey)+ apiGroup.PUT("/:id", handler.UpdateApiKey)+ apiGroup.DELETE("/:id", handler.DeleteApiKey)+ }+}++// ListApiKeys godoc+//+// @Summary List API keys+// @Description Get a paginated list of API keys+// @Tags API Keys+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param search query string false "Search query for filtering by name or description"+// @Param sort query string false "Column to sort by"+// @Param order query string false "Sort direction (asc or desc)" default("asc")+// @Param start query int false "Start index for pagination" default(0)+// @Param limit query int false "Number of items per page" default(20)+// @Success 200 {object} base.Paginated[apikey.ApiKey]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/api-keys [get]+func (h *ApiKeyHandler) ListApiKeys(c *gin.Context) {+ params := pagination.ExtractListModifiersQueryParams(c)++ apiKeys, paginationResp, err := h.apiKeyService.ListApiKeys(c.Request.Context(), params)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.ApiKeyListError{Err: err}).Error()},+ })+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": apiKeys,+ "pagination": paginationResp,+ })+}++// CreateApiKey godoc+//+// @Summary Create an API key+// @Description Create a new API key for programmatic access+// @Tags API Keys+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param request body apikey.Create true "API key creation request"+// @Success 201 {object} base.ApiResponse[apikey.ApiKeyCreatedDto]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 401 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/api-keys [post]+func (h *ApiKeyHandler) CreateApiKey(c *gin.Context) {+ user, ok := middleware.RequireAuthentication(c)+ if !ok {+ return+ }++ var req apikey.Create+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},+ })+ return+ }++ apiKey, err := h.apiKeyService.CreateApiKey(c.Request.Context(), user.ID, req)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.ApiKeyCreationError{Err: err}).Error()},+ })+ return+ }++ c.JSON(http.StatusCreated, gin.H{+ "success": true,+ "data": apiKey,+ })+}++// GetApiKey godoc+//+// @Summary Get an API key+// @Description Get details of a specific API key by ID+// @Tags API Keys+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "API key ID"+// @Success 200 {object} base.ApiResponse[apikey.ApiKey]+// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/api-keys/{id} [get]+func (h *ApiKeyHandler) GetApiKey(c *gin.Context) {+ id := c.Param("id")++ apiKey, err := h.apiKeyService.GetApiKey(c.Request.Context(), id)+ if err != nil {+ c.JSON(http.StatusNotFound, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.ApiKeyNotFoundError{}).Error()},+ })+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": apiKey,+ })+}++// UpdateApiKey godoc+//+// @Summary Update an API key+// @Description Update an existing API key's details+// @Tags API Keys+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param id path string true "API key ID"+// @Param request body apikey.Update true "API key update request"+// @Success 200 {object} base.ApiResponse[apikey.ApiKey]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/api-keys/{id} [put]+func (h *ApiKeyHandler) UpdateApiKey(c *gin.Context) {+ id := c.Param("id")++ var req apikey.Update+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},+ })+ return+ }++ apiKey, err := h.apiKeyService.UpdateApiKey(c.Request.Context(), id, req)+ if err != nil {+ if errors.Is(err, services.ErrApiKeyNotFound) {+ c.JSON(http.StatusNotFound, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.ApiKeyNotFoundError{}).Error()},+ })+ return+ }+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.ApiKeyUpdateError{Err: err}).Error()},+ })+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": apiKey,+ })+}++// DeleteApiKey godoc+//+// @Summary Delete an API key+// @Description Delete an API key by ID+// @Tags API Keys+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "API key ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/api-keys/{id} [delete]+func (h *ApiKeyHandler) DeleteApiKey(c *gin.Context) {+ id := c.Param("id")++ if err := h.apiKeyService.DeleteApiKey(c.Request.Context(), id); err != nil {+ if errors.Is(err, services.ErrApiKeyNotFound) {+ c.JSON(http.StatusNotFound, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.ApiKeyNotFoundError{}).Error()},+ })+ return+ }+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "data": gin.H{"error": (&common.ApiKeyDeletionError{Err: err}).Error()},+ })+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": gin.H{"message": "API key deleted successfully"},+ })+}diff --git a/backend/internal/api/app_images_handler.go b/backend/internal/api/app_images_handler.goindex c5af68bb6..6da0ff3ea 100644--- a/backend/internal/api/app_images_handler.go+++ b/backend/internal/api/app_images_handler.go@@ -23,6 +23,15 @@ func NewApplicationImagesHandler(group *gin.RouterGroup, appImagesService *servigroup.GET("/app-images/profile", appImageHandler.getDefaultProfile)}+// getLogo godoc+//+// @Summary Get application logo+// @Description Get the application logo image+// @Tags Application Images+// @Param full query bool false "Return full logo" default(false)+// @Produce image/png,image/jpeg+// @Success 200 {file} binary+// @Router /api/app-images/logo [get]func (c *ApplicationImagesHandler) getLogo(ctx *gin.Context) {name := "logo"@@ -35,10 +44,26 @@ func (c *ApplicationImagesHandler) getLogo(ctx *gin.Context) {c.getImage(ctx, name)}+// getFavicon godoc+//+// @Summary Get application favicon+// @Description Get the application favicon image+// @Tags Application Images+// @Produce image/png,image/jpeg+// @Success 200 {file} binary+// @Router /api/app-images/favicon [get]func (c *ApplicationImagesHandler) getFavicon(ctx *gin.Context) {c.getImage(ctx, "favicon")}+// getDefaultProfile godoc+//+// @Summary Get default profile image+// @Description Get the default user profile image+// @Tags Application Images+// @Produce image/png,image/jpeg+// @Success 200 {file} binary+// @Router /api/app-images/profile [get]func (c *ApplicationImagesHandler) getDefaultProfile(ctx *gin.Context) {c.getImage(ctx, "profile")}diff --git a/backend/internal/api/auth_handler.go b/backend/internal/api/auth_handler.goindex 410d12544..5c676f74d 100644--- a/backend/internal/api/auth_handler.go+++ b/backend/internal/api/auth_handler.go@@ -102,6 +102,16 @@ func (h *AuthHandler) Logout(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"message": "Logged out successfully"}})}+// GetCurrentUser godoc+//+// @Summary Get current user+// @Description Get the currently authenticated user's information+// @Tags Auth+// @Security BearerAuth+// @Security ApiKeyAuth+// @Success 200 {object} base.ApiResponse[user.Response]+// @Failure 401 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/auth/me [get]func (h *AuthHandler) GetCurrentUser(c *gin.Context) {userID, exists := middleware.GetCurrentUserID(c)if !exists {diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.goindex c2946713c..71cd87ba4 100644--- a/backend/internal/api/container_handler.go+++ b/backend/internal/api/container_handler.go@@ -148,6 +148,21 @@ func (h *ContainerHandler) getOrStartContainerLogHub(containerID, format string,return ls.hub}+// GetLogsWS godoc+//+// @Summary Get container logs via WebSocket+// @Description Stream container logs over WebSocket connection+// @Tags Containers+// @Param id path string true "Environment ID"+// @Param containerId path string true "Container ID"+// @Param follow query bool false "Follow log output" default(true)+// @Param tail query string false "Number of lines to show from the end" default(100)+// @Param since query string false "Show logs since timestamp"+// @Param timestamps query bool false "Show timestamps" default(true)+// @Param format query string false "Output format (text or json)" default(text)+// @Param batched query bool false "Batch log messages" default(false)+// @Router /api/environments/{id}/containers/{containerId}/logs/ws [get]+//// GET /api/containers/:id/logs/ws// /api/environments/:envId/containers/:containerId/logs/wsfunc (h *ContainerHandler) GetLogsWS(c *gin.Context) {@@ -180,6 +195,16 @@ func (h *ContainerHandler) GetLogsWS(c *gin.Context) {slog.Debug("websocket connection closed", "containerID", containerID)}+// GetExecWS godoc+//+// @Summary Execute command in container via WebSocket+// @Description Open an interactive shell session in a container over WebSocket+// @Tags Containers+// @Param id path string true "Environment ID"+// @Param containerId path string true "Container ID"+// @Param shell query string false "Shell to use" default(/bin/sh)+// @Router /api/environments/{id}/containers/{containerId}/exec/ws [get]+//// GET /api/environments/:id/containers/:containerId/exec/wsfunc (h *ContainerHandler) GetExecWS(c *gin.Context) {containerID := c.Param("containerId")@@ -298,6 +323,18 @@ func (h *ContainerHandler) waitForExecCompletion(conn *websocket.Conn, done chan}}+// List godoc+//+// @Summary List containers+// @Description Get a paginated list of Docker containers+// @Tags Containers+// @Param id path string true "Environment ID"+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[container.Summary]+// @Router /api/environments/{id}/containers [get]func (h *ContainerHandler) List(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -329,6 +366,15 @@ func (h *ContainerHandler) List(c *gin.Context) {})}+// GetByID godoc+//+// @Summary Get container by ID+// @Description Get detailed information about a Docker container+// @Tags Containers+// @Param id path string true "Environment ID"+// @Param containerId path string true "Container ID"+// @Success 200 {object} base.ApiResponse[container.Details]+// @Router /api/environments/{id}/containers/{containerId} [get]func (h *ContainerHandler) GetByID(c *gin.Context) {id := c.Param("containerId")@@ -349,6 +395,18 @@ func (h *ContainerHandler) GetByID(c *gin.Context) {})}+// Start godoc+//+// @Summary Start a container+// @Description Start a stopped Docker container+// @Tags Containers+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param containerId path string true "Container ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/containers/{containerId}/start [post]func (h *ContainerHandler) Start(c *gin.Context) {id := c.Param("containerId")@@ -370,6 +428,18 @@ func (h *ContainerHandler) Start(c *gin.Context) {})}+// Stop godoc+//+// @Summary Stop a container+// @Description Stop a running Docker container+// @Tags Containers+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param containerId path string true "Container ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/containers/{containerId}/stop [post]func (h *ContainerHandler) Stop(c *gin.Context) {id := c.Param("containerId")@@ -391,6 +461,18 @@ func (h *ContainerHandler) Stop(c *gin.Context) {})}+// Restart godoc+//+// @Summary Restart a container+// @Description Restart a Docker container+// @Tags Containers+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param containerId path string true "Container ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/containers/{containerId}/restart [post]func (h *ContainerHandler) Restart(c *gin.Context) {id := c.Param("containerId")@@ -412,6 +494,20 @@ func (h *ContainerHandler) Restart(c *gin.Context) {})}+// Delete godoc+//+// @Summary Delete a container+// @Description Delete a Docker container+// @Tags Containers+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param containerId path string true "Container ID"+// @Param force query bool false "Force removal of running container"+// @Param volumes query bool false "Remove associated volumes"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/containers/{containerId} [delete]func (h *ContainerHandler) Delete(c *gin.Context) {id := c.Param("containerId")force := c.Query("force") == "true"@@ -435,6 +531,14 @@ func (h *ContainerHandler) Delete(c *gin.Context) {})}+// GetContainerStatusCounts godoc+//+// @Summary Get container status counts+// @Description Get counts of running, stopped, and total containers+// @Tags Containers+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[container.StatusCounts]+// @Router /api/environments/{id}/containers/counts [get]func (h *ContainerHandler) GetContainerStatusCounts(c *gin.Context) {_, running, stopped, total, err := h.dockerService.GetAllContainers(c.Request.Context())if err != nil {@@ -457,6 +561,17 @@ func (h *ContainerHandler) GetContainerStatusCounts(c *gin.Context) {})}+// Create godoc+//+// @Summary Create a container+// @Description Create a new Docker container+// @Tags Containers+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param container body container.Create true "Container creation data"+// @Success 201 {object} base.ApiResponse[container.Created]+// @Router /api/environments/{id}/containers [post]func (h *ContainerHandler) Create(c *gin.Context) {var req containertypes.Createif err := c.ShouldBindJSON(&req); err != nil {@@ -619,6 +734,14 @@ func (h *ContainerHandler) getOrStartContainerStatsHub(containerID string) *ws.Hreturn ss.hub}+// GetStatsWS godoc+//+// @Summary Get container stats via WebSocket+// @Description Stream container resource statistics over WebSocket connection+// @Tags Containers+// @Param id path string true "Environment ID"+// @Param containerId path string true "Container ID"+// @Router /api/environments/{id}/containers/{containerId}/stats/ws [get]func (h *ContainerHandler) GetStatsWS(c *gin.Context) {containerID := c.Param("containerId")if containerID == "" {diff --git a/backend/internal/api/container_registry_handler.go b/backend/internal/api/container_registry_handler.goindex eefffded1..8e33517d2 100644--- a/backend/internal/api/container_registry_handler.go+++ b/backend/internal/api/container_registry_handler.go@@ -38,6 +38,17 @@ func NewContainerRegistryHandler(group *gin.RouterGroup, registryService *servic}}+// GetRegistries godoc+//+// @Summary List container registries+// @Description Get a paginated list of container registries+// @Tags Container Registries+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[containerregistry.Response]+// @Router /api/container-registries [get]func (h *ContainerRegistryHandler) GetRegistries(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -57,6 +68,14 @@ func (h *ContainerRegistryHandler) GetRegistries(c *gin.Context) {})}+// GetRegistry godoc+//+// @Summary Get a container registry+// @Description Get a container registry by ID+// @Tags Container Registries+// @Param id path string true "Registry ID"+// @Success 200 {object} base.ApiResponse[containerregistry.Response]+// @Router /api/container-registries/{id} [get]func (h *ContainerRegistryHandler) GetRegistry(c *gin.Context) {id := c.Param("id")@@ -85,6 +104,16 @@ func (h *ContainerRegistryHandler) GetRegistry(c *gin.Context) {})}+// CreateRegistry godoc+//+// @Summary Create a container registry+// @Description Create a new container registry+// @Tags Container Registries+// @Accept json+// @Produce json+// @Param registry body models.CreateContainerRegistryRequest true "Registry creation data"+// @Success 201 {object} base.ApiResponse[containerregistry.Response]+// @Router /api/container-registries [post]func (h *ContainerRegistryHandler) CreateRegistry(c *gin.Context) {var req models.CreateContainerRegistryRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -120,6 +149,17 @@ func (h *ContainerRegistryHandler) CreateRegistry(c *gin.Context) {})}+// UpdateRegistry godoc+//+// @Summary Update a container registry+// @Description Update an existing container registry+// @Tags Container Registries+// @Accept json+// @Produce json+// @Param id path string true "Registry ID"+// @Param registry body models.UpdateContainerRegistryRequest true "Registry update data"+// @Success 200 {object} base.ApiResponse[containerregistry.Response]+// @Router /api/container-registries/{id} [put]func (h *ContainerRegistryHandler) UpdateRegistry(c *gin.Context) {id := c.Param("id")@@ -157,6 +197,17 @@ func (h *ContainerRegistryHandler) UpdateRegistry(c *gin.Context) {})}+// DeleteRegistry godoc+//+// @Summary Delete a container registry+// @Description Delete a container registry by ID+// @Tags Container Registries+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Registry ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/container-registries/{id} [delete]func (h *ContainerRegistryHandler) DeleteRegistry(c *gin.Context) {id := c.Param("id")@@ -175,6 +226,17 @@ func (h *ContainerRegistryHandler) DeleteRegistry(c *gin.Context) {})}+// TestRegistry godoc+//+// @Summary Test a container registry+// @Description Test connectivity and authentication to a container registry+// @Tags Container Registries+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Registry ID"+// @Success 200 {object} base.ApiResponse[containerregistry.TestResult]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/container-registries/{id}/test [post]func (h *ContainerRegistryHandler) TestRegistry(c *gin.Context) {id := c.Param("id")@@ -212,6 +274,20 @@ func (h *ContainerRegistryHandler) TestRegistry(c *gin.Context) {})}+// SyncRegistries godoc+//+// @Summary Sync container registries+// @Description Sync container registries from a remote source+// @Tags Container Registries+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param request body containerregistry.SyncRequest true "Registries to sync"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/container-registries/sync [post]func (h *ContainerRegistryHandler) SyncRegistries(c *gin.Context) {var req containerregistry.SyncRequestif err := c.ShouldBindJSON(&req); err != nil {diff --git a/backend/internal/api/customize_handler.go b/backend/internal/api/customize_handler.goindex 923c7f09c..b8de80b6f 100644--- a/backend/internal/api/customize_handler.go+++ b/backend/internal/api/customize_handler.go@@ -26,6 +26,17 @@ func NewCustomizeHandler(group *gin.RouterGroup, customizeSearchService *serviceapiGroup.GET("/categories", authMiddleware.WithAdminNotRequired().Add(), handler.GetCategories)}+// Search godoc+//+// @Summary Search customization options+// @Description Search customization categories and options by query+// @Tags Customize+// @Accept json+// @Produce json+// @Param request body search.Request true "Search query"+// @Success 200 {object} search.Response+// @Router /api/customize/search [post]+//// Search delegates to the customize search service and returns relevance-scored resultsfunc (h *CustomizeHandler) Search(c *gin.Context) {var req search.Request@@ -49,6 +60,14 @@ func (h *CustomizeHandler) Search(c *gin.Context) {c.JSON(http.StatusOK, results)}+// GetCategories godoc+//+// @Summary Get customization categories+// @Description Get all available customization categories with metadata+// @Tags Customize+// @Success 200 {array} search.Category+// @Router /api/customize/categories [get]+//// GetCategories returns all available customization categories with metadatafunc (h *CustomizeHandler) GetCategories(c *gin.Context) {categories := h.customizeSearchService.GetCustomizeCategories()diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.goindex 67c8f7857..4c8668116 100644--- a/backend/internal/api/environment_handler.go+++ b/backend/internal/api/environment_handler.go@@ -58,6 +58,21 @@ func NewEnvironmentHandler(}}+// PairAgent godoc+//+// @Summary Pair with local agent+// @Description Generate or rotate the local agent pairing token+// @Tags Environments+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param id path string true "Environment ID (must be 0 for local)"+// @Param request body environment.AgentPairRequest false "Pair request with optional rotate flag"+// @Success 200 {object} base.ApiResponse[environment.AgentPairResponse]+// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/agent/pair [post]func (h *EnvironmentHandler) PairAgent(c *gin.Context) {if c.Param("id") != LOCAL_DOCKER_ENVIRONMENT_ID {c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Not found"}})@@ -87,6 +102,17 @@ func (h *EnvironmentHandler) PairAgent(c *gin.Context) {})}+// CreateEnvironment godoc+//+// @Summary Create an environment+// @Description Create a new Docker environment+// @Tags Environments+// @Accept json+// @Produce json+// @Param environment body environment.Create true "Environment creation data"+// @Success 201 {object} base.ApiResponse[environment.Response]+// @Router /api/environments [post]+//// Createfunc (h *EnvironmentHandler) CreateEnvironment(c *gin.Context) {var req environment.Create@@ -162,6 +188,17 @@ func (h *EnvironmentHandler) CreateEnvironment(c *gin.Context) {c.JSON(http.StatusCreated, gin.H{"success": true, "data": out})}+// ListEnvironments godoc+//+// @Summary List environments+// @Description Get a paginated list of Docker environments+// @Tags Environments+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[environment.Response]+// @Router /api/environments [get]func (h *EnvironmentHandler) ListEnvironments(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -178,6 +215,15 @@ func (h *EnvironmentHandler) ListEnvironments(c *gin.Context) {})}+// GetEnvironment godoc+//+// @Summary Get an environment+// @Description Get a Docker environment by ID+// @Tags Environments+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[environment.Response]+// @Router /api/environments/{id} [get]+//// Get by IDfunc (h *EnvironmentHandler) GetEnvironment(c *gin.Context) {environmentID := c.Param("id")@@ -200,6 +246,18 @@ func (h *EnvironmentHandler) GetEnvironment(c *gin.Context) {})}+// UpdateEnvironment godoc+//+// @Summary Update an environment+// @Description Update a Docker environment+// @Tags Environments+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param environment body environment.Update true "Environment update data"+// @Success 200 {object} base.ApiResponse[environment.Response]+// @Router /api/environments/{id} [put]+//// Updatefunc (h *EnvironmentHandler) UpdateEnvironment(c *gin.Context) {environmentID := c.Param("id")@@ -335,6 +393,19 @@ func (h *EnvironmentHandler) triggerPostUpdateTasksInternal(environmentID string}}+// DeleteEnvironment godoc+//+// @Summary Delete an environment+// @Description Delete a Docker environment+// @Tags Environments+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id} [delete]+//// Deletefunc (h *EnvironmentHandler) DeleteEnvironment(c *gin.Context) {environmentID := c.Param("id")@@ -357,6 +428,18 @@ func (h *EnvironmentHandler) DeleteEnvironment(c *gin.Context) {})}+// TestConnection godoc+//+// @Summary Test environment connection+// @Description Test connectivity to a Docker environment+// @Tags Environments+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param request body object false "Optional API URL to test"+// @Success 200 {object} base.ApiResponse[environment.Test]+// @Router /api/environments/{id}/test [post]+//// TestConnectionfunc (h *EnvironmentHandler) TestConnection(c *gin.Context) {environmentID := c.Param("id")@@ -385,6 +468,17 @@ func (h *EnvironmentHandler) TestConnection(c *gin.Context) {})}+// UpdateHeartbeat godoc+//+// @Summary Update environment heartbeat+// @Description Update the heartbeat timestamp for an environment+// @Tags Environments+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/heartbeat [post]func (h *EnvironmentHandler) UpdateHeartbeat(c *gin.Context) {environmentID := c.Param("id")@@ -403,6 +497,17 @@ func (h *EnvironmentHandler) UpdateHeartbeat(c *gin.Context) {})}+// SyncRegistries godoc+//+// @Summary Sync container registries+// @Description Sync container registries to a remote environment+// @Tags Environments+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/sync-registries [post]func (h *EnvironmentHandler) SyncRegistries(c *gin.Context) {environmentID := c.Param("id")diff --git a/backend/internal/api/event_handler.go b/backend/internal/api/event_handler.goindex 675f76d6d..5f3fe418f 100644--- a/backend/internal/api/event_handler.go+++ b/backend/internal/api/event_handler.go@@ -28,6 +28,17 @@ func NewEventHandler(group *gin.RouterGroup, eventService *services.EventService}}+// ListEvents godoc+//+// @Summary List events+// @Description Get a paginated list of system events+// @Tags Events+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[event.Event]+// @Router /api/events [get]func (h *EventHandler) ListEvents(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -47,6 +58,18 @@ func (h *EventHandler) ListEvents(c *gin.Context) {})}+// GetEventsByEnvironment godoc+//+// @Summary Get events by environment+// @Description Get a paginated list of events for a specific environment+// @Tags Events+// @Param environmentId path string true "Environment ID"+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[event.Event]+// @Router /api/events/environment/{environmentId} [get]func (h *EventHandler) GetEventsByEnvironment(c *gin.Context) {environmentID := c.Param("environmentId")if environmentID == "" {@@ -75,6 +98,16 @@ func (h *EventHandler) GetEventsByEnvironment(c *gin.Context) {})}+// CreateEvent godoc+//+// @Summary Create an event+// @Description Create a new system event+// @Tags Events+// @Accept json+// @Produce json+// @Param event body event.Create true "Event creation data"+// @Success 201 {object} base.ApiResponse[event.Event]+// @Router /api/events [post]func (h *EventHandler) CreateEvent(c *gin.Context) {var req event.Createif err := c.ShouldBindJSON(&req); err != nil {@@ -100,6 +133,18 @@ func (h *EventHandler) CreateEvent(c *gin.Context) {})}+// DeleteEvent godoc+//+// @Summary Delete an event+// @Description Delete a system event by ID+// @Tags Events+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param eventId path string true "Event ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/events/{eventId} [delete]func (h *EventHandler) DeleteEvent(c *gin.Context) {eventID := c.Param("eventId")if eventID == "" {diff --git a/backend/internal/api/image_handler.go b/backend/internal/api/image_handler.goindex 08404c8dc..66b25c5d3 100644--- a/backend/internal/api/image_handler.go+++ b/backend/internal/api/image_handler.go@@ -41,6 +41,18 @@ func NewImageHandler(group *gin.RouterGroup, dockerService *services.DockerClien}}+// List godoc+//+// @Summary List images+// @Description Get a paginated list of Docker images+// @Tags Images+// @Param id path string true "Environment ID"+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[image.Summary]+// @Router /api/environments/{id}/images [get]func (h *ImageHandler) List(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -70,6 +82,15 @@ func (h *ImageHandler) List(c *gin.Context) {})}+// GetByID godoc+//+// @Summary Get image by ID+// @Description Get a Docker image by its ID+// @Tags Images+// @Param id path string true "Environment ID"+// @Param imageId path string true "Image ID"+// @Success 200 {object} base.ApiResponse[image.DetailSummary]+// @Router /api/environments/{id}/images/{imageId} [get]func (h *ImageHandler) GetByID(c *gin.Context) {id := c.Param("imageId")@@ -87,6 +108,19 @@ func (h *ImageHandler) GetByID(c *gin.Context) {})}+// Remove godoc+//+// @Summary Remove an image+// @Description Remove a Docker image by ID+// @Tags Images+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param imageId path string true "Image ID"+// @Param force query bool false "Force removal"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/images/{imageId} [delete]func (h *ImageHandler) Remove(c *gin.Context) {id := c.Param("imageId")force := c.Query("force") == "true"@@ -109,6 +143,21 @@ func (h *ImageHandler) Remove(c *gin.Context) {})}+// Pull godoc+//+// @Summary Pull an image+// @Description Pull a Docker image from a registry+// @Tags Images+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce application/x-json-stream+// @Param id path string true "Environment ID"+// @Param request body image.PullOptions true "Image pull request"+// @Success 200 {string} string "Streaming JSON response"+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/images/pull [post]func (h *ImageHandler) Pull(c *gin.Context) {ctx := c.Request.Context()var req image.PullOptions@@ -141,6 +190,17 @@ func (h *ImageHandler) Pull(c *gin.Context) {slog.String("imageName", req.ImageName))}+// Prune godoc+//+// @Summary Prune unused images+// @Description Remove unused Docker images+// @Tags Images+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param dangling query bool false "Only remove dangling images"+// @Success 200 {object} base.ApiResponse[image.PruneReport]+// @Router /api/environments/{id}/images/prune [post]func (h *ImageHandler) Prune(c *gin.Context) {dangling := c.Query("dangling") == "true"@@ -183,6 +243,14 @@ func (h *ImageHandler) Prune(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"success": true, "data": out})}+// GetImageUsageCounts godoc+//+// @Summary Get image usage counts+// @Description Get counts of images in use, unused, total, and total size+// @Tags Images+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[image.UsageCounts]+// @Router /api/environments/{id}/images/counts [get]func (h *ImageHandler) GetImageUsageCounts(c *gin.Context) {ctx := c.Request.Context()@@ -227,6 +295,22 @@ func (h *ImageHandler) GetImageUsageCounts(c *gin.Context) {})}+// Upload godoc+//+// @Summary Upload an image+// @Description Upload a Docker image from a tar archive+// @Tags Images+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept multipart/form-data+// @Produce json+// @Param id path string true "Environment ID"+// @Param file formData file true "Docker image tar archive"+// @Success 200 {object} base.ApiResponse[image.LoadResult]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 413 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/images/upload [post]func (h *ImageHandler) Upload(c *gin.Context) {ctx := context.Background()diff --git a/backend/internal/api/image_update_handler.go b/backend/internal/api/image_update_handler.goindex dbd6fa14e..ca2dae11f 100644--- a/backend/internal/api/image_update_handler.go+++ b/backend/internal/api/image_update_handler.go@@ -29,6 +29,19 @@ func NewImageUpdateHandler(group *gin.RouterGroup, imageUpdateService *services.}}+// CheckImageUpdate godoc+//+// @Summary Check image update by reference+// @Description Check if an image has an update available by image reference+// @Tags Image Updates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param imageRef query string true "Image reference (e.g., nginx:latest)"+// @Success 200 {object} base.ApiResponse[imageupdate.Response]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/image-updates/check [get]func (h *ImageUpdateHandler) CheckImageUpdate(c *gin.Context) {imageRef := c.Query("imageRef")if imageRef == "" {@@ -54,6 +67,19 @@ func (h *ImageUpdateHandler) CheckImageUpdate(c *gin.Context) {})}+// CheckImageUpdateByID godoc+//+// @Summary Check image update by ID+// @Description Check if an image has an update available by image ID+// @Tags Image Updates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param imageId path string true "Image ID"+// @Success 200 {object} base.ApiResponse[imageupdate.Response]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/image-updates/check/{imageId} [get]func (h *ImageUpdateHandler) CheckImageUpdateByID(c *gin.Context) {imageID := c.Param("imageId")if imageID == "" {@@ -79,6 +105,17 @@ func (h *ImageUpdateHandler) CheckImageUpdateByID(c *gin.Context) {})}+// CheckMultipleImages godoc+//+// @Summary Check multiple images for updates+// @Description Check multiple images for available updates+// @Tags Image Updates+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param request body imageupdate.BatchImageUpdateRequest true "Batch image update request"+// @Success 200 {object} base.ApiResponse[imageupdate.BatchResponse]+// @Router /api/environments/{id}/image-updates/check-batch [post]func (h *ImageUpdateHandler) CheckMultipleImages(c *gin.Context) {var req imageupdate.BatchImageUpdateRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -114,6 +151,17 @@ func (h *ImageUpdateHandler) CheckMultipleImages(c *gin.Context) {})}+// CheckAllImages godoc+//+// @Summary Check all images for updates+// @Description Check all local images for available updates+// @Tags Image Updates+// @Accept json+// @Produce json+// @Param id path string false "Environment ID"+// @Param request body imageupdate.BatchImageUpdateRequest false "Optional credentials"+// @Success 200 {object} base.ApiResponse[imageupdate.BatchResponse]+// @Router /api/environments/{id}/image-updates/check-all [post]func (h *ImageUpdateHandler) CheckAllImages(c *gin.Context) {var req imageupdate.BatchImageUpdateRequest_ = c.ShouldBindJSON(&req)@@ -135,6 +183,17 @@ func (h *ImageUpdateHandler) CheckAllImages(c *gin.Context) {})}+// GetUpdateSummary godoc+//+// @Summary Get image update summary+// @Description Get a summary of images with available updates+// @Tags Image Updates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[imageupdate.Summary]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/image-updates/summary [get]func (h *ImageUpdateHandler) GetUpdateSummary(c *gin.Context) {summary, err := h.imageUpdateService.GetUpdateSummary(c.Request.Context())if err != nil {diff --git a/backend/internal/api/network_handler.go b/backend/internal/api/network_handler.goindex c33f7c3ef..aafb17b76 100644--- a/backend/internal/api/network_handler.go+++ b/backend/internal/api/network_handler.go@@ -33,6 +33,18 @@ func NewNetworkHandler(group *gin.RouterGroup, dockerService *services.DockerCli}}+// List godoc+//+// @Summary List networks+// @Description Get a paginated list of Docker networks+// @Tags Networks+// @Param id path string true "Environment ID"+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[network.Summary]+// @Router /api/environments/{id}/networks [get]func (h *NetworkHandler) List(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -62,6 +74,15 @@ func (h *NetworkHandler) List(c *gin.Context) {})}+// GetByID godoc+//+// @Summary Get network by ID+// @Description Get a Docker network by its ID+// @Tags Networks+// @Param id path string true "Environment ID"+// @Param networkId path string true "Network ID"+// @Success 200 {object} base.ApiResponse[network.Inspect]+// @Router /api/environments/{id}/networks/{networkId} [get]func (h *NetworkHandler) GetByID(c *gin.Context) {id := c.Param("networkId")@@ -86,6 +107,17 @@ func (h *NetworkHandler) GetByID(c *gin.Context) {})}+// Create godoc+//+// @Summary Create a network+// @Description Create a new Docker network+// @Tags Networks+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param network body object true "Network creation data"+// @Success 201 {object} base.ApiResponse[network.CreateResponse]+// @Router /api/environments/{id}/networks [post]func (h *NetworkHandler) Create(c *gin.Context) {var req struct {Name string `json:"name" binding:"required"`@@ -126,6 +158,18 @@ func (h *NetworkHandler) Create(c *gin.Context) {})}+// Remove godoc+//+// @Summary Remove a network+// @Description Remove a Docker network by ID+// @Tags Networks+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param networkId path string true "Network ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/networks/{networkId} [delete]func (h *NetworkHandler) Remove(c *gin.Context) {id := c.Param("networkId")@@ -148,6 +192,14 @@ func (h *NetworkHandler) Remove(c *gin.Context) {})}+// GetNetworkUsageCounts godoc+//+// @Summary Get network usage counts+// @Description Get counts of networks in use, unused, and total+// @Tags Networks+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[network.UsageCounts]+// @Router /api/environments/{id}/networks/counts [get]func (h *NetworkHandler) GetNetworkUsageCounts(c *gin.Context) {_, inuse, unused, total, err := h.dockerService.GetAllNetworks(c.Request.Context())if err != nil {@@ -170,6 +222,14 @@ func (h *NetworkHandler) GetNetworkUsageCounts(c *gin.Context) {})}+// Prune godoc+//+// @Summary Prune unused networks+// @Description Remove all unused Docker networks+// @Tags Networks+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[network.PruneReport]+// @Router /api/environments/{id}/networks/prune [post]func (h *NetworkHandler) Prune(c *gin.Context) {report, err := h.networkService.PruneNetworks(c.Request.Context())if err != nil {diff --git a/backend/internal/api/notification_handler.go b/backend/internal/api/notification_handler.goindex a3ce5f68e..46e3aa6a7 100644--- a/backend/internal/api/notification_handler.go+++ b/backend/internal/api/notification_handler.go@@ -38,6 +38,14 @@ func NewNotificationHandler(group *gin.RouterGroup, notificationService *service}}+// GetAllSettings godoc+//+// @Summary Get all notification settings+// @Description Get all notification provider settings+// @Tags Notifications+// @Param id path string true "Environment ID"+// @Success 200 {array} notification.Response+// @Router /api/environments/{id}/notifications/settings [get]func (h *NotificationHandler) GetAllSettings(c *gin.Context) {settings, err := h.notificationService.GetAllSettings(c.Request.Context())if err != nil {@@ -59,6 +67,15 @@ func (h *NotificationHandler) GetAllSettings(c *gin.Context) {c.JSON(http.StatusOK, responses)}+// GetSettings godoc+//+// @Summary Get notification settings by provider+// @Description Get notification settings for a specific provider+// @Tags Notifications+// @Param id path string true "Environment ID"+// @Param provider path string true "Notification provider (discord, email)"+// @Success 200 {object} notification.Response+// @Router /api/environments/{id}/notifications/settings/{provider} [get]func (h *NotificationHandler) GetSettings(c *gin.Context) {providerStr := c.Param("provider")provider := models.NotificationProvider(providerStr)@@ -86,6 +103,17 @@ func (h *NotificationHandler) GetSettings(c *gin.Context) {c.JSON(http.StatusOK, response)}+// CreateOrUpdateSettings godoc+//+// @Summary Create or update notification settings+// @Description Create or update notification settings for a provider+// @Tags Notifications+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param settings body notification.Update true "Notification settings"+// @Success 200 {object} notification.Response+// @Router /api/environments/{id}/notifications/settings [post]func (h *NotificationHandler) CreateOrUpdateSettings(c *gin.Context) {var req notification.Updateif err := c.ShouldBindJSON(&req); err != nil {@@ -114,6 +142,19 @@ func (h *NotificationHandler) CreateOrUpdateSettings(c *gin.Context) {c.JSON(http.StatusOK, response)}+// DeleteSettings godoc+//+// @Summary Delete notification settings+// @Description Delete notification settings for a provider+// @Tags Notifications+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param provider path string true "Notification provider (discord, email)"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/notifications/settings/{provider} [delete]func (h *NotificationHandler) DeleteSettings(c *gin.Context) {providerStr := c.Param("provider")provider := models.NotificationProvider(providerStr)@@ -133,6 +174,20 @@ func (h *NotificationHandler) DeleteSettings(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"message": "Settings deleted successfully"})}+// TestNotification godoc+//+// @Summary Test notification+// @Description Send a test notification for a provider+// @Tags Notifications+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param provider path string true "Notification provider (discord, email)"+// @Param type query string false "Test type (simple or image-update)" default(simple)+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/notifications/test/{provider} [post]func (h *NotificationHandler) TestNotification(c *gin.Context) {providerStr := c.Param("provider")provider := models.NotificationProvider(providerStr)@@ -154,6 +209,14 @@ func (h *NotificationHandler) TestNotification(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"message": "Test notification sent successfully"})}+// GetAppriseSettings godoc+//+// @Summary Get Apprise settings+// @Description Get Apprise notification settings+// @Tags Notifications+// @Param id path string true "Environment ID"+// @Success 200 {object} notification.AppriseResponse+// @Router /api/environments/{id}/notifications/apprise [get]func (h *NotificationHandler) GetAppriseSettings(c *gin.Context) {settings, err := h.appriseService.GetSettings(c.Request.Context())if err != nil {@@ -172,6 +235,17 @@ func (h *NotificationHandler) GetAppriseSettings(c *gin.Context) {c.JSON(http.StatusOK, response)}+// CreateOrUpdateAppriseSettings godoc+//+// @Summary Create or update Apprise settings+// @Description Create or update Apprise notification settings+// @Tags Notifications+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param settings body notification.AppriseUpdate true "Apprise settings"+// @Success 200 {object} notification.AppriseResponse+// @Router /api/environments/{id}/notifications/apprise [post]func (h *NotificationHandler) CreateOrUpdateAppriseSettings(c *gin.Context) {var req notification.AppriseUpdateif err := c.ShouldBindJSON(&req); err != nil {@@ -207,6 +281,17 @@ func (h *NotificationHandler) CreateOrUpdateAppriseSettings(c *gin.Context) {c.JSON(http.StatusOK, response)}+// TestAppriseNotification godoc+//+// @Summary Test Apprise notification+// @Description Send a test notification via Apprise+// @Tags Notifications+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/notifications/apprise/test [post]func (h *NotificationHandler) TestAppriseNotification(c *gin.Context) {if err := h.appriseService.TestNotification(c.Request.Context()); err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": (&common.AppriseTestError{Err: err}).Error()})diff --git a/backend/internal/api/playwright_handler.go b/backend/internal/api/playwright_handler.goindex 3d60c61f6..eb941cd97 100644--- a/backend/internal/api/playwright_handler.go+++ b/backend/internal/api/playwright_handler.go@@ -25,6 +25,8 @@ func SetupPlaywrightRoutes(api *gin.RouterGroup, playwrightService *services.Plaplaywright.POST("/skip-onboarding", playwrightHandler.SkipOnboardingHandler)playwright.POST("/reset-onboarding", playwrightHandler.ResetOnboardingHandler)+ playwright.POST("/create-test-api-keys", playwrightHandler.CreateTestApiKeysHandler)+ playwright.POST("/delete-test-api-keys", playwrightHandler.DeleteTestApiKeysHandler)}func (ph *PlaywrightHandler) SkipOnboardingHandler(c *gin.Context) {@@ -44,3 +46,36 @@ func (ph *PlaywrightHandler) ResetOnboardingHandler(c *gin.Context) {c.Status(http.StatusNoContent)}++type CreateTestApiKeysRequest struct {+ Count int `json:"count"`+}++func (ph *PlaywrightHandler) CreateTestApiKeysHandler(c *gin.Context) {+ var req CreateTestApiKeysRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ // Default to 2 if no count provided+ req.Count = 2+ }++ if req.Count <= 0 {+ req.Count = 2+ }++ apiKeys, err := ph.PlaywrightService.CreateTestApiKeys(c.Request.Context(), req.Count)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ c.JSON(http.StatusCreated, gin.H{"apiKeys": apiKeys})+}++func (ph *PlaywrightHandler) DeleteTestApiKeysHandler(c *gin.Context) {+ if err := ph.PlaywrightService.DeleteAllTestApiKeys(c.Request.Context()); err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ c.Status(http.StatusNoContent)+}diff --git a/backend/internal/api/project_handler.go b/backend/internal/api/project_handler.goindex 6b4923fe4..9303ed928 100644--- a/backend/internal/api/project_handler.go+++ b/backend/internal/api/project_handler.go@@ -69,6 +69,18 @@ func NewProjectHandler(group *gin.RouterGroup, projectService *services.ProjectS}}+// ListProjects godoc+//+// @Summary List projects+// @Description Get a paginated list of Docker Compose projects+// @Tags Projects+// @Param id path string true "Environment ID"+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[project.Details]+// @Router /api/environments/{id}/projects [get]func (h *ProjectHandler) ListProjects(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -98,6 +110,18 @@ func (h *ProjectHandler) ListProjects(c *gin.Context) {})}+// DeployProject godoc+//+// @Summary Deploy a project+// @Description Deploy a Docker Compose project (docker-compose up)+// @Tags Projects+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/projects/{projectId}/up [post]func (h *ProjectHandler) DeployProject(c *gin.Context) {projectID := c.Param("projectId")@@ -124,6 +148,18 @@ func (h *ProjectHandler) DeployProject(c *gin.Context) {})}+// DownProject godoc+//+// @Summary Bring down a project+// @Description Bring down a Docker Compose project (docker-compose down)+// @Tags Projects+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/projects/{projectId}/down [post]func (h *ProjectHandler) DownProject(c *gin.Context) {projectID := c.Param("projectId")@@ -142,6 +178,17 @@ func (h *ProjectHandler) DownProject(c *gin.Context) {})}+// CreateProject godoc+//+// @Summary Create a project+// @Description Create a new Docker Compose project+// @Tags Projects+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param project body project.Create true "Project creation data"+// @Success 201 {object} base.ApiResponse[project.CreateReponse]+// @Router /api/environments/{id}/projects [post]func (h *ProjectHandler) CreateProject(c *gin.Context) {var req project.Createif err := c.ShouldBindJSON(&req); err != nil {@@ -173,6 +220,15 @@ func (h *ProjectHandler) CreateProject(c *gin.Context) {})}+// GetProject godoc+//+// @Summary Get a project+// @Description Get a Docker Compose project by ID+// @Tags Projects+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Success 200 {object} base.ApiResponse[project.Details]+// @Router /api/environments/{id}/projects/{projectId} [get]func (h *ProjectHandler) GetProject(c *gin.Context) {projectID := c.Param("projectId")if projectID == "" {@@ -192,6 +248,18 @@ func (h *ProjectHandler) GetProject(c *gin.Context) {})}+// RedeployProject godoc+//+// @Summary Redeploy a project+// @Description Redeploy a Docker Compose project (down + up)+// @Tags Projects+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/projects/{projectId}/redeploy [post]func (h *ProjectHandler) RedeployProject(c *gin.Context) {projectID := c.Param("projectId")@@ -218,6 +286,22 @@ func (h *ProjectHandler) RedeployProject(c *gin.Context) {})}+// DestroyProject godoc+//+// @Summary Destroy a project+// @Description Destroy a Docker Compose project and optionally remove files/volumes+// @Tags Projects+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Param request body project.Destroy false "Destroy options"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/projects/{projectId}/destroy [delete]func (h *ProjectHandler) DestroyProject(c *gin.Context) {projectID := c.Param("projectId")@@ -244,6 +328,21 @@ func (h *ProjectHandler) DestroyProject(c *gin.Context) {})}+// PullProjectImages godoc+//+// @Summary Pull project images+// @Description Pull all images for a Docker Compose project+// @Tags Projects+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce application/x-json-stream+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Param request body project.ImagePullRequest false "Pull options with optional credentials"+// @Success 200 {string} string "Streaming JSON response"+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/projects/{projectId}/pull [post]func (h *ProjectHandler) PullProjectImages(c *gin.Context) {projectID := c.Param("projectId")if projectID == "" {@@ -274,6 +373,18 @@ func (h *ProjectHandler) PullProjectImages(c *gin.Context) {_, _ = fmt.Fprintln(c.Writer, `{"status":"complete"}`)}+// UpdateProject godoc+//+// @Summary Update a project+// @Description Update a Docker Compose project configuration+// @Tags Projects+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Param project body project.Update true "Project update data"+// @Success 200 {object} base.ApiResponse[project.Details]+// @Router /api/environments/{id}/projects/{projectId} [put]func (h *ProjectHandler) UpdateProject(c *gin.Context) {projectID := c.Param("projectId")if projectID == "" {@@ -304,6 +415,18 @@ func (h *ProjectHandler) UpdateProject(c *gin.Context) {})}+// UpdateProjectInclude godoc+//+// @Summary Update project include file+// @Description Update an include file within a Docker Compose project+// @Tags Projects+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Param include body project.UpdateIncludeFile true "Include file update data"+// @Success 200 {object} base.ApiResponse[project.Details]+// @Router /api/environments/{id}/projects/{projectId}/includes [put]func (h *ProjectHandler) UpdateProjectInclude(c *gin.Context) {projectID := c.Param("projectId")if projectID == "" {@@ -334,6 +457,18 @@ func (h *ProjectHandler) UpdateProjectInclude(c *gin.Context) {})}+// RestartProject godoc+//+// @Summary Restart a project+// @Description Restart all containers in a Docker Compose project+// @Tags Projects+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/projects/{projectId}/restart [post]func (h *ProjectHandler) RestartProject(c *gin.Context) {projectID := c.Param("projectId")if projectID == "" {@@ -416,6 +551,20 @@ func (h *ProjectHandler) getOrStartProjectLogHub(projectID, format string, batchreturn ls.hub}+// GetProjectLogsWS godoc+//+// @Summary Get project logs via WebSocket+// @Description Stream project logs over WebSocket connection+// @Tags Projects+// @Param id path string true "Environment ID"+// @Param projectId path string true "Project ID"+// @Param follow query bool false "Follow log output" default(true)+// @Param tail query string false "Number of lines to show from the end" default(100)+// @Param since query string false "Show logs since timestamp"+// @Param timestamps query bool false "Show timestamps" default(false)+// @Param format query string false "Output format (text or json)" default(text)+// @Param batched query bool false "Batch log messages" default(false)+// @Router /api/environments/{id}/projects/{projectId}/logs/ws [get]func (h *ProjectHandler) GetProjectLogsWS(c *gin.Context) {projectID := c.Param("projectId")if strings.TrimSpace(projectID) == "" {@@ -438,6 +587,14 @@ func (h *ProjectHandler) GetProjectLogsWS(c *gin.Context) {ws.ServeClient(context.Background(), hub, conn)}+// GetProjectStatusCounts godoc+//+// @Summary Get project status counts+// @Description Get counts of running, stopped, and total projects+// @Tags Projects+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[project.StatusCounts]+// @Router /api/environments/{id}/projects/counts [get]func (h *ProjectHandler) GetProjectStatusCounts(c *gin.Context) {_, running, stopped, total, err := h.projectService.GetProjectStatusCounts(c.Request.Context())if err != nil {diff --git a/backend/internal/api/settings_handler.go b/backend/internal/api/settings_handler.goindex 221165f7a..ff77b5459 100644--- a/backend/internal/api/settings_handler.go+++ b/backend/internal/api/settings_handler.go@@ -38,6 +38,17 @@ func NewSettingsHandler(group *gin.RouterGroup, settingsService *services.Settintop.GET("/categories", authMiddleware.WithAdminNotRequired().Add(), handler.GetCategories)}+// Search godoc+//+// @Summary Search settings+// @Description Search settings categories and individual settings by query+// @Tags Settings+// @Accept json+// @Produce json+// @Param request body search.Request true "Search query"+// @Success 200 {object} search.Response+// @Router /api/settings/search [post]+//// Search delegates to the settings search service and returns relevance-scored resultsfunc (h *SettingsHandler) Search(c *gin.Context) {var req search.Request@@ -61,12 +72,28 @@ func (h *SettingsHandler) Search(c *gin.Context) {c.JSON(http.StatusOK, results)}+// GetCategories godoc+//+// @Summary Get settings categories+// @Description Get all available settings categories with metadata+// @Tags Settings+// @Success 200 {array} settings.Category+// @Router /api/settings/categories [get]+//// GetCategories returns all available settings categories with metadatafunc (h *SettingsHandler) GetCategories(c *gin.Context) {categories := h.settingsSearchService.GetSettingsCategories()c.JSON(http.StatusOK, categories)}+// GetSettings godoc+//+// @Summary Get settings+// @Description Get all settings for an environment+// @Tags Settings+// @Param id path string true "Environment ID"+// @Success 200 {array} settings.PublicSetting+// @Router /api/environments/{id}/settings [get]func (h *SettingsHandler) GetSettings(c *gin.Context) {environmentID := c.Param("id")@@ -92,6 +119,14 @@ func (h *SettingsHandler) GetSettings(c *gin.Context) {c.JSON(http.StatusOK, settingsDto)}+// GetPublicSettings godoc+//+// @Summary Get public settings+// @Description Get all public settings for an environment+// @Tags Settings+// @Param id path string true "Environment ID"+// @Success 200 {array} settings.PublicSetting+// @Router /api/environments/{id}/settings/public [get]func (h *SettingsHandler) GetPublicSettings(c *gin.Context) {settingsList := h.settingsService.ListSettings(false)@@ -114,6 +149,22 @@ func (h *SettingsHandler) GetPublicSettings(c *gin.Context) {c.JSON(http.StatusOK, settingsDto)}+// UpdateSettings godoc+//+// @Summary Update settings+// @Description Update settings for an environment+// @Tags Settings+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param settings body settings.Update true "Settings update data"+// @Success 200 {object} base.ApiResponse[[]settings.SettingDto]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 403 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/settings [put]func (h *SettingsHandler) UpdateSettings(c *gin.Context) {environmentID := c.Param("id")diff --git a/backend/internal/api/system_handler.go b/backend/internal/api/system_handler.goindex 824f14472..a5f36b61f 100644--- a/backend/internal/api/system_handler.go+++ b/backend/internal/api/system_handler.go@@ -119,6 +119,14 @@ type SystemStats struct {GPUs []GPUStats `json:"gpus,omitempty"`}+// Health godoc+//+// @Summary Check system health+// @Description Check if the Docker daemon is responsive+// @Tags System+// @Param id path string true "Environment ID"+// @Success 200+// @Router /api/environments/{id}/system/health [head]func (h *SystemHandler) Health(c *gin.Context) {ctx := c.Request.Context()@@ -138,6 +146,14 @@ func (h *SystemHandler) Health(c *gin.Context) {c.Status(http.StatusOK)}+// GetDockerInfo godoc+//+// @Summary Get Docker info+// @Description Get Docker daemon version and system information+// @Tags System+// @Param id path string true "Environment ID"+// @Success 200 {object} dockerinfo.Info+// @Router /api/environments/{id}/system/docker/info [get]func (h *SystemHandler) GetDockerInfo(c *gin.Context) {ctx := c.Request.Context()@@ -205,6 +221,21 @@ func (h *SystemHandler) GetDockerInfo(c *gin.Context) {c.JSON(http.StatusOK, dockerInfo)}+// PruneAll godoc+//+// @Summary Prune Docker resources+// @Description Remove unused Docker resources (containers, images, volumes, networks)+// @Tags System+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param request body system.PruneAllRequest true "Prune options"+// @Success 200 {object} base.ApiResponse[system.PruneResult]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/system/prune [post]func (h *SystemHandler) PruneAll(c *gin.Context) {ctx := c.Request.Context()slog.InfoContext(ctx, "System prune operation initiated")@@ -253,6 +284,17 @@ func (h *SystemHandler) PruneAll(c *gin.Context) {})}+// StartAllContainers godoc+//+// @Summary Start all containers+// @Description Start all Docker containers+// @Tags System+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[system.ContainerBulkActionResult]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/system/containers/start-all [post]func (h *SystemHandler) StartAllContainers(c *gin.Context) {result, err := h.systemService.StartAllContainers(c.Request.Context())if err != nil {@@ -270,6 +312,17 @@ func (h *SystemHandler) StartAllContainers(c *gin.Context) {})}+// StartAllStoppedContainers godoc+//+// @Summary Start all stopped containers+// @Description Start all stopped Docker containers+// @Tags System+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[system.ContainerBulkActionResult]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/system/containers/start-stopped [post]func (h *SystemHandler) StartAllStoppedContainers(c *gin.Context) {result, err := h.systemService.StartAllStoppedContainers(c.Request.Context())if err != nil {@@ -309,6 +362,17 @@ func (h *SystemHandler) getDiskUsagePath(ctx context.Context) string {return diskUsagePath}+// StopAllContainers godoc+//+// @Summary Stop all containers+// @Description Stop all running Docker containers+// @Tags System+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[system.ContainerBulkActionResult]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/system/containers/stop-all [post]func (h *SystemHandler) StopAllContainers(c *gin.Context) {result, err := h.systemService.StopAllContainers(c.Request.Context())if err != nil {@@ -326,6 +390,14 @@ func (h *SystemHandler) StopAllContainers(c *gin.Context) {})}+// Stats godoc+//+// @Summary Get system stats via WebSocket+// @Description Stream system resource statistics over WebSocket connection+// @Tags System+// @Param id path string true "Environment ID"+// @Router /api/environments/{id}/system/stats/ws [get]+////nolint:gocognitfunc (h *SystemHandler) Stats(c *gin.Context) {clientIP := c.ClientIP()@@ -494,6 +566,17 @@ func (h *SystemHandler) Stats(c *gin.Context) {}}+// ConvertDockerRun godoc+//+// @Summary Convert docker run command+// @Description Convert a docker run command to docker-compose format+// @Tags System+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param request body models.ConvertDockerRunRequest true "Docker run command"+// @Success 200 {object} models.ConvertDockerRunResponse+// @Router /api/environments/{id}/system/convert [post]func (h *SystemHandler) ConvertDockerRun(c *gin.Context) {var req models.ConvertDockerRunRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -532,6 +615,17 @@ func (h *SystemHandler) ConvertDockerRun(c *gin.Context) {})}+// CheckUpgradeAvailable godoc+//+// @Summary Check for system upgrade+// @Description Check if a system upgrade is available+// @Tags System+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[system.UpgradeCheckResult]+// @Router /api/environments/{id}/system/upgrade/check [get]+//// CheckUpgradeAvailable checks if the local system can be upgraded// Remote environments are handled by the proxy middlewarefunc (h *SystemHandler) CheckUpgradeAvailable(c *gin.Context) {@@ -554,6 +648,18 @@ func (h *SystemHandler) CheckUpgradeAvailable(c *gin.Context) {})}+// TriggerUpgrade godoc+//+// @Summary Trigger system upgrade+// @Description Trigger a system upgrade+// @Tags System+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 202 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/system/upgrade [post]+//// TriggerUpgrade triggers a system upgrade by spawning the upgrade CLI command// This runs the upgrade from outside the current container to avoid self-termination issuesfunc (h *SystemHandler) TriggerUpgrade(c *gin.Context) {diff --git a/backend/internal/api/template_handler.go b/backend/internal/api/template_handler.goindex dc3ee187f..15c7575e7 100644--- a/backend/internal/api/template_handler.go+++ b/backend/internal/api/template_handler.go@@ -48,6 +48,17 @@ func NewTemplateHandler(group *gin.RouterGroup, templateService *services.Templa}}+// GetAllTemplatesPaginated godoc+//+// @Summary List templates (paginated)+// @Description Get a paginated list of compose templates+// @Tags Templates+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[template.Template]+// @Router /api/templates [get]func (h *TemplateHandler) GetAllTemplatesPaginated(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -77,6 +88,13 @@ func (h *TemplateHandler) GetAllTemplatesPaginated(c *gin.Context) {})}+// GetAllTemplates godoc+//+// @Summary List all templates+// @Description Get all compose templates without pagination+// @Tags Templates+// @Success 200 {array} template.Template+// @Router /api/templates/all [get]func (h *TemplateHandler) GetAllTemplates(c *gin.Context) {templates, err := h.templateService.GetAllTemplates(c.Request.Context())if err != nil {@@ -104,6 +122,14 @@ func (h *TemplateHandler) GetAllTemplates(c *gin.Context) {})}+// GetTemplate godoc+//+// @Summary Get a template+// @Description Get a compose template by ID+// @Tags Templates+// @Param id path string true "Template ID"+// @Success 200 {object} base.ApiResponse[template.Template]+// @Router /api/templates/{id} [get]func (h *TemplateHandler) GetTemplate(c *gin.Context) {id := c.Param("id")if id == "" {@@ -146,6 +172,18 @@ func (h *TemplateHandler) GetTemplate(c *gin.Context) {})}+// GetTemplateContent godoc+//+// @Summary Get template content+// @Description Get the compose content for a template with parsed data+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Template ID"+// @Success 200 {object} base.ApiResponse[template.Content]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/templates/{id}/content [get]func (h *TemplateHandler) GetTemplateContent(c *gin.Context) {id := c.Param("id")if id == "" {@@ -171,6 +209,16 @@ func (h *TemplateHandler) GetTemplateContent(c *gin.Context) {})}+// CreateTemplate godoc+//+// @Summary Create a template+// @Description Create a new compose template+// @Tags Templates+// @Accept json+// @Produce json+// @Param template body object true "Template creation data"+// @Success 201 {object} base.ApiResponse[template.Template]+// @Router /api/templates [post]func (h *TemplateHandler) CreateTemplate(c *gin.Context) {var req struct {Name string `json:"name" binding:"required"`@@ -221,6 +269,17 @@ func (h *TemplateHandler) CreateTemplate(c *gin.Context) {})}+// UpdateTemplate godoc+//+// @Summary Update a template+// @Description Update an existing compose template+// @Tags Templates+// @Accept json+// @Produce json+// @Param id path string true "Template ID"+// @Param template body object true "Template update data"+// @Success 200 {object} base.ApiResponse[template.Template]+// @Router /api/templates/{id} [put]func (h *TemplateHandler) UpdateTemplate(c *gin.Context) {id := c.Param("id")if id == "" {@@ -296,6 +355,19 @@ func (h *TemplateHandler) UpdateTemplate(c *gin.Context) {})}+// DeleteTemplate godoc+//+// @Summary Delete a template+// @Description Delete a compose template+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Template ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/templates/{id} [delete]func (h *TemplateHandler) DeleteTemplate(c *gin.Context) {id := c.Param("id")if id == "" {@@ -328,6 +400,15 @@ func (h *TemplateHandler) DeleteTemplate(c *gin.Context) {})}+// GetDefaultTemplates godoc+//+// @Summary Get default templates+// @Description Get the default compose and env templates+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Success 200 {object} base.ApiResponse[template.DefaultTemplates]+// @Router /api/templates/default [get]func (h *TemplateHandler) GetDefaultTemplates(c *gin.Context) {composeTemplate := h.templateService.GetComposeTemplate()envTemplate := h.templateService.GetEnvTemplate()@@ -341,6 +422,20 @@ func (h *TemplateHandler) GetDefaultTemplates(c *gin.Context) {})}+// SaveDefaultTemplates godoc+//+// @Summary Save default templates+// @Description Save the default compose and env templates+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param templates body template.SaveDefault true "Default templates data"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/templates/default [post]func (h *TemplateHandler) SaveDefaultTemplates(c *gin.Context) {var req struct {ComposeContent string `json:"composeContent" binding:"required"`@@ -376,6 +471,13 @@ func (h *TemplateHandler) SaveDefaultTemplates(c *gin.Context) {})}+// GetRegistries godoc+//+// @Summary List template registries+// @Description Get all template registries+// @Tags Templates+// @Success 200 {array} template.Registry+// @Router /api/templates/registries [get]func (h *TemplateHandler) GetRegistries(c *gin.Context) {registries, err := h.templateService.GetRegistries(c.Request.Context())if err != nil {@@ -401,6 +503,16 @@ func (h *TemplateHandler) GetRegistries(c *gin.Context) {})}+// CreateRegistry godoc+//+// @Summary Create a template registry+// @Description Create a new template registry+// @Tags Templates+// @Accept json+// @Produce json+// @Param registry body object true "Registry creation data"+// @Success 201 {object} base.ApiResponse[template.Registry]+// @Router /api/templates/registries [post]func (h *TemplateHandler) CreateRegistry(c *gin.Context) {var req struct {Name string `json:"name" binding:"required"`@@ -445,6 +557,22 @@ func (h *TemplateHandler) CreateRegistry(c *gin.Context) {})}+// UpdateRegistry godoc+//+// @Summary Update a template registry+// @Description Update an existing template registry+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param id path string true "Registry ID"+// @Param registry body template.UpdateRegistry true "Registry update data"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/templates/registries/{id} [put]func (h *TemplateHandler) UpdateRegistry(c *gin.Context) {id := c.Param("id")if id == "" {@@ -497,6 +625,19 @@ func (h *TemplateHandler) UpdateRegistry(c *gin.Context) {})}+// DeleteRegistry godoc+//+// @Summary Delete a template registry+// @Description Delete a template registry+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Registry ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/templates/registries/{id} [delete]func (h *TemplateHandler) DeleteRegistry(c *gin.Context) {id := c.Param("id")if id == "" {@@ -529,6 +670,18 @@ func (h *TemplateHandler) DeleteRegistry(c *gin.Context) {})}+// FetchRegistry godoc+//+// @Summary Fetch remote registry+// @Description Fetch templates from a remote registry URL+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param url query string true "Registry URL"+// @Success 200 {object} map[string]any+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 502 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/templates/fetch [get]func (h *TemplateHandler) FetchRegistry(c *gin.Context) {url := c.Query("url")if url == "" {@@ -557,6 +710,14 @@ func (h *TemplateHandler) FetchRegistry(c *gin.Context) {})}+// DownloadTemplate godoc+//+// @Summary Download a template+// @Description Download a remote template to local storage+// @Tags Templates+// @Param id path string true "Template ID"+// @Success 200 {object} base.ApiResponse[template.Template]+// @Router /api/templates/{id}/download [post]func (h *TemplateHandler) DownloadTemplate(c *gin.Context) {id := c.Param("id")if id == "" {@@ -592,6 +753,16 @@ func (h *TemplateHandler) DownloadTemplate(c *gin.Context) {})}+// GetGlobalVariables godoc+//+// @Summary Get global variables+// @Description Get global template variables+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Success 200 {object} base.ApiResponse[[]env.Variable]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/templates/variables [get]func (h *TemplateHandler) GetGlobalVariables(c *gin.Context) {vars, err := h.templateService.GetGlobalVariables(c.Request.Context())if err != nil {@@ -608,6 +779,20 @@ func (h *TemplateHandler) GetGlobalVariables(c *gin.Context) {})}+// UpdateGlobalVariables godoc+//+// @Summary Update global variables+// @Description Update global template variables+// @Tags Templates+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param variables body env.Summary true "Variables update data"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/templates/variables [put]func (h *TemplateHandler) UpdateGlobalVariables(c *gin.Context) {var req env.Summaryif err := c.ShouldBindJSON(&req); err != nil {diff --git a/backend/internal/api/updater_handler.go b/backend/internal/api/updater_handler.goindex bb7ce222f..5024182f8 100644--- a/backend/internal/api/updater_handler.go+++ b/backend/internal/api/updater_handler.go@@ -27,6 +27,20 @@ func NewUpdaterHandler(group *gin.RouterGroup, updaterService *services.UpdaterS}}+// Run godoc+//+// @Summary Run updater+// @Description Apply pending container updates+// @Tags Updater+// @Security BearerAuth+// @Security ApiKeyAuth+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param request body updater.Options false "Updater run options"+// @Success 200 {object} base.ApiResponse[updater.Result]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/updater/run [post]func (h *UpdaterHandler) Run(c *gin.Context) {var req updater.Options_ = c.ShouldBindJSON(&req)@@ -40,11 +54,33 @@ func (h *UpdaterHandler) Run(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"success": true, "data": out})}+// Status godoc+//+// @Summary Get updater status+// @Description Get the current status of the updater+// @Tags Updater+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[updater.Status]+// @Router /api/environments/{id}/updater/status [get]func (h *UpdaterHandler) Status(c *gin.Context) {status := h.updaterService.GetStatus()c.JSON(http.StatusOK, gin.H{"success": true, "data": status})}+// History godoc+//+// @Summary Get updater history+// @Description Get the history of update operations+// @Tags Updater+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param limit query int false "Number of history entries to return" default(50)+// @Success 200 {object} base.ApiResponse[[]updater.HistoryEntry]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/updater/history [get]func (h *UpdaterHandler) History(c *gin.Context) {limit := 50if ls := c.Query("limit"); ls != "" {diff --git a/backend/internal/api/user_handler.go b/backend/internal/api/user_handler.goindex 8989850d1..fd1b4ca9b 100644--- a/backend/internal/api/user_handler.go+++ b/backend/internal/api/user_handler.go@@ -33,6 +33,17 @@ func NewUserHandler(group *gin.RouterGroup, userService *services.UserService, a}}+// ListUsers godoc+//+// @Summary List users+// @Description Get a paginated list of all users+// @Tags Users+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[user.Response]+// @Router /api/users [get]func (h *UserHandler) ListUsers(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -52,6 +63,16 @@ func (h *UserHandler) ListUsers(c *gin.Context) {})}+// CreateUser godoc+//+// @Summary Create a user+// @Description Create a new user account+// @Tags Users+// @Accept json+// @Produce json+// @Param user body user.Create true "User creation data"+// @Success 201 {object} base.ApiResponse[user.Response]+// @Router /api/users [post]func (h *UserHandler) CreateUser(c *gin.Context) {var req user.Createif err := c.ShouldBindJSON(&req); err != nil {@@ -111,6 +132,14 @@ func (h *UserHandler) CreateUser(c *gin.Context) {})}+// GetUser godoc+//+// @Summary Get a user+// @Description Get a user by ID+// @Tags Users+// @Param id path string true "User ID"+// @Success 200 {object} base.ApiResponse[user.Response]+// @Router /api/users/{id} [get]func (h *UserHandler) GetUser(c *gin.Context) {userID := c.Param("id")@@ -138,6 +167,17 @@ func (h *UserHandler) GetUser(c *gin.Context) {})}+// UpdateUser godoc+//+// @Summary Update a user+// @Description Update an existing user's information+// @Tags Users+// @Accept json+// @Produce json+// @Param id path string true "User ID"+// @Param user body user.Update true "User update data"+// @Success 200 {object} base.ApiResponse[user.Response]+// @Router /api/users/{id} [put]func (h *UserHandler) UpdateUser(c *gin.Context) {userID := c.Param("id")@@ -211,6 +251,17 @@ func (h *UserHandler) UpdateUser(c *gin.Context) {})}+// DeleteUser godoc+//+// @Summary Delete a user+// @Description Delete a user by ID+// @Tags Users+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "User ID"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/users/{id} [delete]func (h *UserHandler) DeleteUser(c *gin.Context) {userID := c.Param("id")diff --git a/backend/internal/api/version_handler.go b/backend/internal/api/version_handler.goindex 5616caaf3..58ca16877 100644--- a/backend/internal/api/version_handler.go+++ b/backend/internal/api/version_handler.go@@ -20,6 +20,14 @@ func NewVersionHandler(api *gin.RouterGroup, version *services.VersionService) *return h}+// Get godoc+//+// @Summary Get version information+// @Description Get application version information and check for updates+// @Tags Version+// @Param current query string false "Current version to compare against"+// @Success 200 {object} version.Info+// @Router /api/version [get]func (h *VersionHandler) Get(c *gin.Context) {current := strings.TrimSpace(c.Query("current"))@@ -30,6 +38,13 @@ func (h *VersionHandler) Get(c *gin.Context) {c.JSON(http.StatusOK, info)}+// GetAppVersion godoc+//+// @Summary Get app version+// @Description Get the current application version+// @Tags Version+// @Success 200 {object} version.Info+// @Router /api/app-version [get]func (h *VersionHandler) GetAppVersion(c *gin.Context) {info := h.version.GetAppVersionInfo(c.Request.Context())c.JSON(http.StatusOK, info)diff --git a/backend/internal/api/volume_handler.go b/backend/internal/api/volume_handler.goindex d00dd59b5..6f639239d 100644--- a/backend/internal/api/volume_handler.go+++ b/backend/internal/api/volume_handler.go@@ -33,6 +33,18 @@ func NewVolumeHandler(group *gin.RouterGroup, dockerService *services.DockerClie}}+// List godoc+//+// @Summary List volumes+// @Description Get a paginated list of Docker volumes+// @Tags Volumes+// @Param id path string true "Environment ID"+// @Param pagination[page] query int false "Page number for pagination" default(1)+// @Param pagination[limit] query int false "Number of items per page" default(20)+// @Param sort[column] query string false "Column to sort by"+// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")+// @Success 200 {object} base.Paginated[volume.Volume]+// @Router /api/environments/{id}/volumes [get]func (h *VolumeHandler) List(c *gin.Context) {params := pagination.ExtractListModifiersQueryParams(c)@@ -63,6 +75,15 @@ func (h *VolumeHandler) List(c *gin.Context) {})}+// GetByName godoc+//+// @Summary Get volume by name+// @Description Get a Docker volume by its name+// @Tags Volumes+// @Param id path string true "Environment ID"+// @Param volumeName path string true "Volume name"+// @Success 200 {object} base.ApiResponse[volume.Volume]+// @Router /api/environments/{id}/volumes/{volumeName} [get]func (h *VolumeHandler) GetByName(c *gin.Context) {name := c.Param("volumeName")@@ -81,6 +102,17 @@ func (h *VolumeHandler) GetByName(c *gin.Context) {})}+// Create godoc+//+// @Summary Create a volume+// @Description Create a new Docker volume+// @Tags Volumes+// @Accept json+// @Produce json+// @Param id path string true "Environment ID"+// @Param volume body volume.Create true "Volume creation data"+// @Success 201 {object} base.ApiResponse[volume.Volume]+// @Router /api/environments/{id}/volumes [post]func (h *VolumeHandler) Create(c *gin.Context) {var req volumetypes.Createif err := c.ShouldBindJSON(&req); err != nil {@@ -118,6 +150,19 @@ func (h *VolumeHandler) Create(c *gin.Context) {})}+// Remove godoc+//+// @Summary Remove a volume+// @Description Remove a Docker volume by name+// @Tags Volumes+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param volumeName path string true "Volume name"+// @Param force query bool false "Force removal"+// @Success 200 {object} base.ApiResponse[base.MessageResponse]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/volumes/{volumeName} [delete]func (h *VolumeHandler) Remove(c *gin.Context) {name := c.Param("volumeName")force := c.Query("force") == "true"@@ -141,6 +186,17 @@ func (h *VolumeHandler) Remove(c *gin.Context) {})}+// Prune godoc+//+// @Summary Prune unused volumes+// @Description Remove all unused Docker volumes+// @Tags Volumes+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[volume.PruneReport]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/volumes/prune [post]func (h *VolumeHandler) Prune(c *gin.Context) {report, err := h.volumeService.PruneVolumes(c.Request.Context())if err != nil {@@ -157,6 +213,18 @@ func (h *VolumeHandler) Prune(c *gin.Context) {})}+// GetUsage godoc+//+// @Summary Get volume usage+// @Description Get containers using a specific volume+// @Tags Volumes+// @Security BearerAuth+// @Security ApiKeyAuth+// @Param id path string true "Environment ID"+// @Param volumeName path string true "Volume name"+// @Success 200 {object} base.ApiResponse[volume.Usage]+// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]+// @Router /api/environments/{id}/volumes/{volumeName}/usage [get]func (h *VolumeHandler) GetUsage(c *gin.Context) {name := c.Param("volumeName")@@ -178,6 +246,14 @@ func (h *VolumeHandler) GetUsage(c *gin.Context) {})}+// GetVolumeUsageCounts godoc+//+// @Summary Get volume usage counts+// @Description Get counts of volumes in use, unused, and total+// @Tags Volumes+// @Param id path string true "Environment ID"+// @Success 200 {object} base.ApiResponse[volume.UsageCounts]+// @Router /api/environments/{id}/volumes/counts [get]func (h *VolumeHandler) GetVolumeUsageCounts(c *gin.Context) {_, running, stopped, total, err := h.dockerService.GetAllVolumes(c.Request.Context())if err != nil {diff --git a/backend/internal/bootstrap/playwright_router_bootstrap.go b/backend/internal/bootstrap/playwright_router_bootstrap.goindex f2c73d7d7..8964bd0c2 100644--- a/backend/internal/bootstrap/playwright_router_bootstrap.go+++ b/backend/internal/bootstrap/playwright_router_bootstrap.go@@ -13,7 +13,7 @@ import (func init() {registerPlaywrightRoutes = []func(apiGroup *gin.RouterGroup, services *Services){func(apiGroup *gin.RouterGroup, svc *Services) {- playwrightService := services.NewPlaywrightService(svc.Settings)+ playwrightService := services.NewPlaywrightService(svc.Settings, svc.ApiKey, svc.User)if playwrightService == nil {slog.Warn("Playwright service not available, skipping playwright routes")returndiff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex 8417936a9..5ffa69434 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -66,7 +66,7 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {},}))- authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg)+ authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).WithApiKeyValidator(appServices.ApiKey)corsMiddleware := middleware.NewCORSMiddleware(cfg).Add()router.Use(corsMiddleware)@@ -81,6 +81,7 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {api.NewEnvironmentHandler(apiGroup, appServices.Environment, appServices.Settings, authMiddleware, cfg)api.NewContainerRegistryHandler(apiGroup, appServices.ContainerRegistry, authMiddleware)api.NewTemplateHandler(apiGroup, appServices.Template, authMiddleware)+ api.NewApiKeyHandler(apiGroup, appServices.ApiKey, authMiddleware)envMiddleware := middleware.NewEnvProxyMiddlewareWithParam(api.LOCAL_DOCKER_ENVIRONMENT_ID,diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex 3949ae744..a965d6cf8 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -36,6 +36,7 @@ type Services struct {Version *services.VersionServiceNotification *services.NotificationServiceApprise *services.AppriseService+ ApiKey *services.ApiKeyService}func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config, httpClient *http.Client) (svcs *Services, dockerSrvice *services.DockerClientService, err error) {@@ -65,6 +66,7 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Configsvcs.Template = services.NewTemplateService(ctx, db, httpClient, svcs.Settings)svcs.Auth = services.NewAuthService(svcs.User, svcs.Settings, svcs.Event, cfg.JWTSecret, cfg)svcs.Oidc = services.NewOidcService(svcs.Auth, cfg, httpClient)+ svcs.ApiKey = services.NewApiKeyService(db, svcs.User)svcs.Updater = services.NewUpdaterService(db, svcs.Settings, svcs.Docker, svcs.Project, svcs.ImageUpdate, svcs.ContainerRegistry, svcs.Event, svcs.Image, svcs.Notification)svcs.System = services.NewSystemService(db, svcs.Docker, svcs.Container, svcs.Image, svcs.Volume, svcs.Network, svcs.Settings)svcs.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, svcs.ContainerRegistry, svcs.Docker)diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 243eec70d..e111a4eb8 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -1202,3 +1202,41 @@ type VolumeCountsError struct {func (e *VolumeCountsError) Error() string {return fmt.Sprintf("Failed to get volume counts: %v", e.Err)}++type ApiKeyListError struct {+ Err error+}++func (e *ApiKeyListError) Error() string {+ return fmt.Sprintf("Failed to list API keys: %v", e.Err)+}++type ApiKeyCreationError struct {+ Err error+}++func (e *ApiKeyCreationError) Error() string {+ return "Failed to create API key"+}++type ApiKeyNotFoundError struct{}++func (e *ApiKeyNotFoundError) Error() string {+ return "API key not found"+}++type ApiKeyUpdateError struct {+ Err error+}++func (e *ApiKeyUpdateError) Error() string {+ return "Failed to update API key"+}++type ApiKeyDeletionError struct {+ Err error+}++func (e *ApiKeyDeletionError) Error() string {+ return "Failed to delete API key"+}diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.goindex 664685862..066750e85 100644--- a/backend/internal/middleware/auth_middleware.go+++ b/backend/internal/middleware/auth_middleware.go@@ -1,6 +1,7 @@package middlewareimport (+ "context""errors""log/slog""net/http"@@ -16,6 +17,7 @@ import (const (headerAgentBootstrap = "X-Arcane-Agent-Bootstrap"headerAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential+ headerApiToken = "X-API-TOKEN" // #nosec G101: header name, not a credentialagentPairingPrefix = "/api/environments/0/agent/pair")@@ -24,10 +26,15 @@ type AuthOptions struct {SuccessOptional bool}+type ApiKeyValidator interface {+ ValidateApiKey(ctx context.Context, rawKey string) (*models.User, error)+}+type AuthMiddleware struct {- authService *services.AuthService- cfg *config.Config- options AuthOptions+ authService *services.AuthService+ apiKeyValidator ApiKeyValidator+ cfg *config.Config+ options AuthOptions}func NewAuthMiddleware(authService *services.AuthService, cfg *config.Config) *AuthMiddleware {@@ -38,6 +45,12 @@ func NewAuthMiddleware(authService *services.AuthService, cfg *config.Config) *A}}+func (m *AuthMiddleware) WithApiKeyValidator(validator ApiKeyValidator) *AuthMiddleware {+ clone := *m+ clone.apiKeyValidator = validator+ return &clone+}+func (m *AuthMiddleware) WithAdminRequired() *AuthMiddleware {clone := *mclone.options.AdminRequired = true@@ -97,6 +110,35 @@ func (m *AuthMiddleware) agentAuth(c *gin.Context) {}func (m *AuthMiddleware) managerAuth(c *gin.Context) {+ // First, check for API token in X-API-TOKEN header+ if apiToken := c.GetHeader(headerApiToken); apiToken != "" && m.apiKeyValidator != nil {+ user, err := m.apiKeyValidator.ValidateApiKey(c.Request.Context(), apiToken)+ if err == nil && user != nil {+ isAdmin := userHasRole(user, "admin")+ if m.options.AdminRequired && !isAdmin {+ c.JSON(http.StatusForbidden, models.APIError{+ Code: "FORBIDDEN",+ Message: "You don't have permission to access this resource",+ })+ c.Abort()+ return+ }+ c.Set("userID", user.ID)+ c.Set("currentUser", user)+ c.Set("userIsAdmin", isAdmin)+ c.Set("authMethod", "api_key")+ c.Next()+ return+ }+ // If API key validation fails, return unauthorized+ c.JSON(http.StatusUnauthorized, models.APIError{+ Code: models.APIErrorCodeUnauthorized,+ Message: "Invalid or expired API key",+ })+ c.Abort()+ return+ }+token := extractBearerOrCookieToken(c)if token == "" {if m.options.SuccessOptional {diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex 95cb3c562..b4dca0a00 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -135,13 +135,18 @@ func (m *EnvironmentMiddleware) convertToWebSocketURL(target string) string {func (m *EnvironmentMiddleware) buildWebSocketHeaders(c *gin.Context, accessToken *string) http.Header {hdr := http.Header{}+ // Forward API key header if present+ if apiKey := c.GetHeader("X-Api-Token"); apiKey != "" {+ hdr.Set("X-Api-Token", apiKey)+ }+if auth := c.GetHeader("Authorization"); auth != "" {hdr.Set("Authorization", auth)} else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {hdr.Set("Authorization", "Bearer "+cookieToken)}- if hdr.Get("Authorization") == "" {+ if hdr.Get("Authorization") == "" && hdr.Get("X-Api-Token") == "" {if cookieHeader := c.Request.Header.Get("Cookie"); cookieHeader != "" {hdr.Set("Cookie", cookieHeader)}diff --git a/backend/internal/models/api_key.go b/backend/internal/models/api_key.gonew file mode 100644index 000000000..ac527fb10--- /dev/null+++ b/backend/internal/models/api_key.go@@ -0,0 +1,20 @@+package models++import (+ "time"+)++type ApiKey struct {+ Name string `json:"name" gorm:"column:name;not null" sortable:"true"`+ Description *string `json:"description,omitempty" gorm:"column:description"`+ KeyHash string `json:"-" gorm:"column:key_hash;not null"`+ KeyPrefix string `json:"keyPrefix" gorm:"column:key_prefix;not null"`+ UserID string `json:"userId" gorm:"column:user_id;not null"`+ ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`+ LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"column:last_used_at" sortable:"true"`+ BaseModel+}++func (ApiKey) TableName() string {+ return "api_keys"+}diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex f6238a754..7304cabca 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -96,6 +96,12 @@ type Settings struct {AgentToken SettingVariable `key:"agentToken,internal,sensitive"`InstanceID SettingVariable `key:"instanceId,internal"`++ // Users category (admin management page - no actual settings)+ UsersCategoryPlaceholder SettingVariable `key:"usersCategory,internal" meta:"label=Users;type=internal;keywords=users,accounts,management,admin,access,permissions,roles;category=users;description=Manage user accounts and permissions" catmeta:"id=users;title=Users;icon=user;url=/settings/users;description=Manage user accounts and access control"`++ // API Keys category (admin management page - no actual settings)+ ApiKeysCategoryPlaceholder SettingVariable `key:"apiKeysCategory,internal" meta:"label=API Keys;type=internal;keywords=api,keys,tokens,authentication,access,programmatic,integration;category=apikeys;description=Manage API keys for programmatic access" catmeta:"id=apikeys;title=API Keys;icon=key;url=/settings/api-keys;description=Create and manage API keys for programmatic access to Arcane"`}func (SettingVariable) TableName() string {diff --git a/backend/internal/services/api_key_service.go b/backend/internal/services/api_key_service.gonew file mode 100644index 000000000..e6ba7d38d--- /dev/null+++ b/backend/internal/services/api_key_service.go@@ -0,0 +1,242 @@+package services++import (+ "context"+ "crypto/rand"+ "encoding/hex"+ "errors"+ "fmt"+ "strings"+ "time"++ "github.com/getarcaneapp/arcane/backend/internal/database"+ "github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"+ "go.getarcane.app/types/apikey"+ "gorm.io/gorm"+)++var (+ ErrApiKeyNotFound = errors.New("API key not found")+ ErrApiKeyExpired = errors.New("API key has expired")+ ErrApiKeyInvalid = errors.New("invalid API key")+)++const (+ apiKeyPrefix = "arc_"+ apiKeyLength = 32+ apiKeyPrefixLen = 8+)++type ApiKeyService struct {+ db *database.DB+ userService *UserService+ argon2Params *Argon2Params+}++func NewApiKeyService(db *database.DB, userService *UserService) *ApiKeyService {+ return &ApiKeyService{+ db: db,+ userService: userService,+ argon2Params: DefaultArgon2Params(),+ }+}++func (s *ApiKeyService) generateApiKey() (string, error) {+ bytes := make([]byte, apiKeyLength)+ if _, err := rand.Read(bytes); err != nil {+ return "", fmt.Errorf("failed to generate API key: %w", err)+ }+ return apiKeyPrefix + hex.EncodeToString(bytes), nil+}++func (s *ApiKeyService) hashApiKey(key string) (string, error) {+ return s.userService.HashPassword(key)+}++func (s *ApiKeyService) validateApiKeyHash(hash, key string) error {+ return s.userService.ValidatePassword(hash, key)+}++func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req apikey.Create) (*apikey.ApiKeyCreatedDto, error) {+ rawKey, err := s.generateApiKey()+ if err != nil {+ return nil, err+ }++ keyHash, err := s.hashApiKey(rawKey)+ if err != nil {+ return nil, fmt.Errorf("failed to hash API key: %w", err)+ }++ keyPrefix := rawKey[:len(apiKeyPrefix)+apiKeyPrefixLen]++ ak := &models.ApiKey{+ Name: req.Name,+ Description: req.Description,+ KeyHash: keyHash,+ KeyPrefix: keyPrefix,+ UserID: userID,+ ExpiresAt: req.ExpiresAt,+ }++ if err := s.db.WithContext(ctx).Create(ak).Error; err != nil {+ return nil, fmt.Errorf("failed to create API key: %w", err)+ }++ return &apikey.ApiKeyCreatedDto{+ ApiKey: apikey.ApiKey{+ ID: ak.ID,+ Name: ak.Name,+ Description: ak.Description,+ KeyPrefix: ak.KeyPrefix,+ UserID: ak.UserID,+ ExpiresAt: ak.ExpiresAt,+ LastUsedAt: ak.LastUsedAt,+ CreatedAt: ak.CreatedAt,+ UpdatedAt: ak.UpdatedAt,+ },+ Key: rawKey,+ }, nil+}++func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKey, error) {+ var ak models.ApiKey+ if err := s.db.WithContext(ctx).Where("id = ?", id).First(&ak).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, ErrApiKeyNotFound+ }+ return nil, fmt.Errorf("failed to get API key: %w", err)+ }++ return &apikey.ApiKey{+ ID: ak.ID,+ Name: ak.Name,+ Description: ak.Description,+ KeyPrefix: ak.KeyPrefix,+ UserID: ak.UserID,+ ExpiresAt: ak.ExpiresAt,+ LastUsedAt: ak.LastUsedAt,+ CreatedAt: ak.CreatedAt,+ UpdatedAt: ak.UpdatedAt,+ }, nil+}++func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.QueryParams) ([]apikey.ApiKey, pagination.Response, error) {+ var apiKeys []models.ApiKey+ query := s.db.WithContext(ctx).Model(&models.ApiKey{})++ if term := strings.TrimSpace(params.Search); term != "" {+ searchPattern := "%" + term + "%"+ query = query.Where(+ "name LIKE ? OR COALESCE(description, '') LIKE ?",+ searchPattern, searchPattern,+ )+ }++ paginationResp, err := pagination.PaginateAndSortDB(params, query, &apiKeys)+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate API keys: %w", err)+ }++ result := make([]apikey.ApiKey, len(apiKeys))+ for i, ak := range apiKeys {+ result[i] = apikey.ApiKey{+ ID: ak.ID,+ Name: ak.Name,+ Description: ak.Description,+ KeyPrefix: ak.KeyPrefix,+ UserID: ak.UserID,+ ExpiresAt: ak.ExpiresAt,+ LastUsedAt: ak.LastUsedAt,+ CreatedAt: ak.CreatedAt,+ UpdatedAt: ak.UpdatedAt,+ }+ }++ return result, paginationResp, nil+}++func (s *ApiKeyService) UpdateApiKey(ctx context.Context, id string, req apikey.Update) (*apikey.ApiKey, error) {+ var ak models.ApiKey+ if err := s.db.WithContext(ctx).Where("id = ?", id).First(&ak).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, ErrApiKeyNotFound+ }+ return nil, fmt.Errorf("failed to get API key: %w", err)+ }++ if req.Name != nil {+ ak.Name = *req.Name+ }+ if req.Description != nil {+ ak.Description = req.Description+ }+ if req.ExpiresAt != nil {+ ak.ExpiresAt = req.ExpiresAt+ }++ if err := s.db.WithContext(ctx).Save(&ak).Error; err != nil {+ return nil, fmt.Errorf("failed to update API key: %w", err)+ }++ return &apikey.ApiKey{+ ID: ak.ID,+ Name: ak.Name,+ Description: ak.Description,+ KeyPrefix: ak.KeyPrefix,+ UserID: ak.UserID,+ ExpiresAt: ak.ExpiresAt,+ LastUsedAt: ak.LastUsedAt,+ CreatedAt: ak.CreatedAt,+ UpdatedAt: ak.UpdatedAt,+ }, nil+}++func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {+ result := s.db.WithContext(ctx).Delete(&models.ApiKey{}, "id = ?", id)+ if result.Error != nil {+ return fmt.Errorf("failed to delete API key: %w", result.Error)+ }+ if result.RowsAffected == 0 {+ return ErrApiKeyNotFound+ }+ return nil+}++func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*models.User, error) {+ if !strings.HasPrefix(rawKey, apiKeyPrefix) {+ return nil, ErrApiKeyInvalid+ }++ keyPrefix := rawKey[:len(apiKeyPrefix)+apiKeyPrefixLen]++ var apiKeys []models.ApiKey+ if err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {+ return nil, fmt.Errorf("failed to find API keys: %w", err)+ }++ for _, apiKey := range apiKeys {+ if err := s.validateApiKeyHash(apiKey.KeyHash, rawKey); err == nil {+ if apiKey.ExpiresAt != nil && apiKey.ExpiresAt.Before(time.Now()) {+ return nil, ErrApiKeyExpired+ }++ // Update last_used_at asynchronously to avoid blocking auth flow+ go func(keyID string) {+ bgCtx := context.WithoutCancel(ctx)+ now := time.Now()+ s.db.WithContext(bgCtx).Model(&models.ApiKey{}).Where("id = ?", keyID).Update("last_used_at", now)+ }(apiKey.ID)++ user, err := s.userService.GetUserByID(ctx, apiKey.UserID)+ if err != nil {+ return nil, fmt.Errorf("failed to get user for API key: %w", err)+ }++ return user, nil+ }+ }++ return nil, ErrApiKeyInvalid+}diff --git a/backend/internal/services/playwright_service.go b/backend/internal/services/playwright_service.goindex 3be6cca51..ad4ad6c54 100644--- a/backend/internal/services/playwright_service.go+++ b/backend/internal/services/playwright_service.go@@ -6,15 +6,22 @@ import ("context""fmt""log/slog"++ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"+ "go.getarcane.app/types/apikey")type PlaywrightService struct {settingsService *SettingsService+ apiKeyService *ApiKeyService+ userService *UserService}-func NewPlaywrightService(settingsService *SettingsService) *PlaywrightService {+func NewPlaywrightService(settingsService *SettingsService, apiKeyService *ApiKeyService, userService *UserService) *PlaywrightService {return &PlaywrightService{settingsService: settingsService,+ apiKeyService: apiKeyService,+ userService: userService,}}@@ -41,3 +48,64 @@ func (ps *PlaywrightService) ResetOnboarding(ctx context.Context) error {slog.Info("Playwright: Onboarding reset successfully")return nil}++func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) ([]*apikey.ApiKeyCreatedDto, error) {+ slog.Info("Playwright: Creating test API keys", "count", count)++ // Get the arcane user to associate the API keys with+ user, err := ps.userService.GetUserByUsername(ctx, "arcane")+ if err != nil {+ return nil, fmt.Errorf("failed to get arcane user: %w", err)+ }++ var createdKeys []*apikey.ApiKeyCreatedDto+ for i := 0; i < count; i++ {+ req := apikey.Create{+ Name: fmt.Sprintf("test-api-key-%d", i+1),+ Description: stringPtr(fmt.Sprintf("Test API key %d for Playwright tests", i+1)),+ }++ apiKey, err := ps.apiKeyService.CreateApiKey(ctx, user.ID, req)+ if err != nil {+ return nil, fmt.Errorf("failed to create test API key %d: %w", i+1, err)+ }++ createdKeys = append(createdKeys, apiKey)+ }++ slog.Info("Playwright: Test API keys created successfully", "count", len(createdKeys))+ return createdKeys, nil+}++func (ps *PlaywrightService) DeleteAllTestApiKeys(ctx context.Context) error {+ slog.Info("Playwright: Deleting all test API keys")++ // Get all API keys with test prefix+ params := pagination.QueryParams{+ SearchQuery: pagination.SearchQuery{+ Search: "test-api-key",+ },+ PaginationParams: pagination.PaginationParams{+ Start: 0,+ Limit: 1000,+ },+ }++ apiKeys, _, err := ps.apiKeyService.ListApiKeys(ctx, params)+ if err != nil {+ return fmt.Errorf("failed to list API keys: %w", err)+ }++ for _, apiKey := range apiKeys {+ if err := ps.apiKeyService.DeleteApiKey(ctx, apiKey.ID); err != nil {+ slog.Warn("Failed to delete test API key", "id", apiKey.ID, "error", err)+ }+ }++ slog.Info("Playwright: Test API keys deleted", "count", len(apiKeys))+ return nil+}++func stringPtr(s string) *string {+ return &s+}diff --git a/backend/internal/utils/remenv/remenv.go b/backend/internal/utils/remenv/remenv.goindex 4cc543471..b1f9c1e3d 100644--- a/backend/internal/utils/remenv/remenv.go+++ b/backend/internal/utils/remenv/remenv.go@@ -7,10 +7,12 @@ import ("github.com/gin-gonic/gin")+const headerApiToken = "X-Api-Token" // #nosec G101: header name, not a credential+func CopyRequestHeaders(from http.Header, to http.Header, skip map[string]struct{}) {for k, vs := range from {ck := http.CanonicalHeaderKey(k)- if _, ok := skip[ck]; ok || ck == "Authorization" {+ if _, ok := skip[ck]; ok || ck == "Authorization" || ck == http.CanonicalHeaderKey(headerApiToken) {continue}for _, v := range vs {@@ -20,6 +22,12 @@ func CopyRequestHeaders(from http.Header, to http.Header, skip map[string]struct}func SetAuthHeader(req *http.Request, c *gin.Context) {+ // Forward API key header if present+ if apiKey := c.GetHeader(headerApiToken); apiKey != "" {+ req.Header.Set(headerApiToken, apiKey)+ }++ // Forward Authorization header or cookie tokenif auth := c.GetHeader("Authorization"); auth != "" {req.Header.Set("Authorization", auth)} else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {diff --git a/backend/resources/migrations/postgres/024_add_api_keys.down.sql b/backend/resources/migrations/postgres/024_add_api_keys.down.sqlnew file mode 100644index 000000000..42af8e148--- /dev/null+++ b/backend/resources/migrations/postgres/024_add_api_keys.down.sql@@ -0,0 +1,4 @@+DROP INDEX IF EXISTS idx_api_keys_key_prefix;+DROP INDEX IF EXISTS idx_api_keys_key_hash;+DROP INDEX IF EXISTS idx_api_keys_user_id;+DROP TABLE IF EXISTS api_keys;diff --git a/backend/resources/migrations/postgres/024_add_api_keys.up.sql b/backend/resources/migrations/postgres/024_add_api_keys.up.sqlnew file mode 100644index 000000000..fcbc143ec--- /dev/null+++ b/backend/resources/migrations/postgres/024_add_api_keys.up.sql@@ -0,0 +1,17 @@+CREATE TABLE IF NOT EXISTS api_keys (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ key_hash TEXT NOT NULL,+ key_prefix TEXT NOT NULL,+ user_id TEXT NOT NULL,+ expires_at TIMESTAMPTZ,+ last_used_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ,+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE+);++CREATE INDEX IF NOT EXISTS idx_api_keys_user_id ON api_keys(user_id);+CREATE INDEX IF NOT EXISTS idx_api_keys_key_hash ON api_keys(key_hash);+CREATE INDEX IF NOT EXISTS idx_api_keys_key_prefix ON api_keys(key_prefix);diff --git a/backend/resources/migrations/sqlite/024_add_api_keys.down.sql b/backend/resources/migrations/sqlite/024_add_api_keys.down.sqlnew file mode 100644index 000000000..42af8e148--- /dev/null+++ b/backend/resources/migrations/sqlite/024_add_api_keys.down.sql@@ -0,0 +1,4 @@+DROP INDEX IF EXISTS idx_api_keys_key_prefix;+DROP INDEX IF EXISTS idx_api_keys_key_hash;+DROP INDEX IF EXISTS idx_api_keys_user_id;+DROP TABLE IF EXISTS api_keys;diff --git a/backend/resources/migrations/sqlite/024_add_api_keys.up.sql b/backend/resources/migrations/sqlite/024_add_api_keys.up.sqlnew file mode 100644index 000000000..db413040f--- /dev/null+++ b/backend/resources/migrations/sqlite/024_add_api_keys.up.sql@@ -0,0 +1,17 @@+CREATE TABLE IF NOT EXISTS api_keys (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ key_hash TEXT NOT NULL,+ key_prefix TEXT NOT NULL,+ user_id TEXT NOT NULL,+ expires_at DATETIME,+ last_used_at DATETIME,+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME,+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE+);++CREATE INDEX IF NOT EXISTS idx_api_keys_user_id ON api_keys(user_id);+CREATE INDEX IF NOT EXISTS idx_api_keys_key_hash ON api_keys(key_hash);+CREATE INDEX IF NOT EXISTS idx_api_keys_key_prefix ON api_keys(key_prefix);diff --git a/cli/go.mod b/cli/go.modindex 48a8f523d..76fc7dd94 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -23,6 +23,7 @@ require (github.com/docker/go-connections v0.6.0 // indirectgithub.com/docker/go-units v0.5.0 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirect+ github.com/kr/pretty v0.3.1 // indirectgithub.com/mattn/go-colorable v0.1.14 // indirectgithub.com/mattn/go-isatty v0.0.20 // indirectgithub.com/mattn/go-runewidth v0.0.19 // indirect@@ -31,7 +32,9 @@ require (github.com/opencontainers/go-digest v1.0.0 // indirectgithub.com/opencontainers/image-spec v1.1.1 // indirectgithub.com/rivo/uniseg v0.4.7 // indirect+ github.com/rogpeppe/go-internal v1.14.1 // indirectgithub.com/spf13/pflag v1.0.10 // indirectgolang.org/x/sys v0.38.0 // indirectgolang.org/x/term v0.37.0 // indirect+ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect)diff --git a/cli/go.sum b/cli/go.sumindex b4a06a368..bdb6e6e86 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -21,9 +21,9 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=-github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=-github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=-github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=@@ -44,6 +44,7 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=github.com/schollz/progressbar/v3 v3.18.0 h1:uXdoHABRFmNIjUfte/Ex7WtuyVslrw2wVPQmCN62HpA=github.com/schollz/progressbar/v3 v3.18.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=@@ -61,14 +62,12 @@ github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sDgo.withmatt.com/size v0.0.0-20250220224316-11aee5773e67 h1:nHPqmzoLZv+9OqER7S2oXnIBDAbIaIKKrVtNtDvJzjc=go.withmatt.com/size v0.0.0-20250220224316-11aee5773e67/go.mod h1:WFmSrzphcXaSV4LG3YfIw42bPHDK8A6WsAYZCxyys/c=golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=-golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=-golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=+golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 5e07a98a2..a307d4810 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -202,6 +202,9 @@"common_add_button": "Add {resource}","_comment_common_validation": "=== COMMON - VALIDATION ===","common_username_required": "Username is required",+ "common_field_required": "{field} is required",+ "common_copied": "Copied to clipboard",+ "common_copy_failed": "Failed to copy to clipboard","_comment_resources": "=== RESOURCE NAMES ===","resource_volume": "volume","resource_volume_cap": "Volume",@@ -1371,5 +1374,49 @@"upgrade_status_checking": "Checking for new version...","upgrade_status_detected": "New version detected!","upgrade_wait_info": "This may take 30-60 seconds. The page will reload automatically when ready.",- "auto_start": "Auto-start"+ "auto_start": "Auto-start",++ "_comment_api_keys": "=== API KEYS ===",+ "api_key_name": "Name",+ "api_key_name_placeholder": "Enter a name for this API key",+ "api_key_name_description": "A friendly name to identify this API key",+ "api_key_description_label": "Description",+ "api_key_description_placeholder": "Optional description",+ "api_key_description_help": "Additional details about what this API key is used for",+ "api_key_expires_at": "Expires",+ "api_key_expires_at_placeholder": "Optional expiration date",+ "api_key_expires_at_description": "When this API key will expire. Leave empty for a non-expiring key",+ "api_key_last_used": "Last Used",+ "api_key_key_prefix": "Key Prefix",+ "api_key_status_active": "Active",+ "api_key_status_expired": "Expired",+ "api_key_expires_never": "Never",+ "api_key_create_title": "Create API Key",+ "api_key_edit_title": "Edit API Key",+ "api_key_create_description": "Create a new API key for programmatic access",+ "api_key_edit_description": "Update the details of the API key \"{name}\"",+ "api_key_save_changes": "Save Changes",+ "api_key_create_button": "Create API Key",+ "api_key_created_title": "API Key Created",+ "api_key_created_description": "Copy your API key now. You won't be able to see it again!",+ "api_key_your_key": "Your API Key",+ "api_key_important_warning": "This is the only time you will see this key. Make sure to copy it and store it securely.",+ "api_key_copied_success": "API key copied to clipboard",+ "api_key_page_title": "API Keys",+ "api_key_page_description": "Manage API keys for programmatic access to Arcane",+ "api_key_updated_success": "API key \"{name}\" updated successfully",+ "api_key_update_failed": "Failed to update API key \"{name}\"",+ "api_key_created_success": "API key \"{name}\" created successfully",+ "api_key_create_failed": "Failed to create API key \"{name}\"",+ "api_key_delete_title": "Delete API Key \"{name}\"?",+ "api_key_delete_message": "Are you sure you want to delete the API key \"{name}\"? This action cannot be undone.",+ "api_key_delete_selected_title": "Delete {count} API Key(s)?",+ "api_key_delete_selected_message": "Are you sure you want to delete {count} API key(s)? This action cannot be undone.",+ "api_key_delete_failed": "Failed to delete API key \"{name}\"",+ "api_key_delete_success": "API key \"{name}\" deleted successfully",+ "api_key_bulk_delete_success": "Successfully deleted {count} API key(s)",+ "api_key_bulk_delete_failed": "Failed to delete {count} API key(s)",+ "common_done": "Done",+ "common_important": "Important",+ "select_a_date": "Select a date"}diff --git a/frontend/src/lib/components/form/date-picker.svelte b/frontend/src/lib/components/form/date-picker.sveltenew file mode 100644index 000000000..eac049f9a--- /dev/null+++ b/frontend/src/lib/components/form/date-picker.svelte@@ -0,0 +1,98 @@+<script lang="ts">+ import { Button } from '$lib/components/ui/button';+ import { Calendar } from '$lib/components/ui/calendar';+ import * as Popover from '$lib/components/ui/popover';+ import { m } from '$lib/paraglide/messages';+ import { getLocale } from '$lib/paraglide/runtime';+ import { cn } from '$lib/utils';+ import {+ CalendarDate,+ DateFormatter,+ getLocalTimeZone,+ type DateValue+ } from '@internationalized/date';+ import CalendarIcon from '@lucide/svelte/icons/calendar';+ import type { HTMLAttributes } from 'svelte/elements';++ type Props = {+ value?: Date;+ id?: string;+ } & HTMLAttributes<HTMLDivElement>;++ let { value = $bindable(undefined), id, ...restProps }: Props = $props();++ let calendarDisplayDate: CalendarDate | undefined = $state(+ value ? dateToCalendarDate(value) : undefined+ );++ let open = $state(false);++ function dateToCalendarDate(d: Date): CalendarDate {+ return new CalendarDate(d.getFullYear(), d.getMonth() + 1, d.getDate());+ }++ $effect(() => {+ if (calendarDisplayDate) {+ const newExternalDate = calendarDisplayDate.toDate(getLocalTimeZone());+ if (!value || value.getTime() !== newExternalDate.getTime()) {+ value = newExternalDate;+ }+ } else {+ if (value !== undefined) {+ value = undefined;+ }+ }+ });++ $effect(() => {+ if (value) {+ const newInternalCalendarDate = dateToCalendarDate(value);+ if (!calendarDisplayDate || calendarDisplayDate.compare(newInternalCalendarDate) !== 0) {+ calendarDisplayDate = newInternalCalendarDate;+ }+ } else {+ if (calendarDisplayDate !== undefined) {+ calendarDisplayDate = undefined;+ }+ }+ });++ function handleCalendarInteraction(newDateValue?: DateValue) {+ open = false;+ }++ const df = new DateFormatter(getLocale(), {+ dateStyle: 'long'+ });+</script>++<div class="w-full" {...restProps}>+ <Popover.Root bind:open>+ <Popover.Trigger {id} class="w-full">+ {#snippet child({ props })}+ <Button+ {...props}+ variant="outline"+ class={cn(+ 'w-full justify-start text-left font-normal',+ !value && 'text-muted-foreground'+ )}+ aria-label={m.select_a_date()}+ >+ <CalendarIcon class="mr-2 size-4" />+ {calendarDisplayDate+ ? df.format(calendarDisplayDate.toDate(getLocalTimeZone()))+ : m.select_a_date()}+ </Button>+ {/snippet}+ </Popover.Trigger>+ <Popover.Content class="w-auto p-0" align="start">+ <Calendar+ type="single"+ bind:value={calendarDisplayDate}+ onValueChange={handleCalendarInteraction}+ initialFocus+ />+ </Popover.Content>+ </Popover.Root>+</div>\ No newline at end of filediff --git a/frontend/src/lib/components/form/form-input.svelte b/frontend/src/lib/components/form/form-input.svelteindex be0123c5f..a705f3430 100644--- a/frontend/src/lib/components/form/form-input.svelte+++ b/frontend/src/lib/components/form/form-input.svelte@@ -1,6 +1,7 @@<!-- Originally From https://github.com/pocket-id/pocket-id/blob/main/frontend/src/lib/components/form/form-input.svelte --><script lang="ts">import { Input } from '$lib/components/ui/input';+ import DatePicker from '$lib/components/form/date-picker.svelte';import { Textarea } from '$lib/components/ui/textarea';import { Switch } from '$lib/components/ui/switch';import { Label } from '$lib/components/ui/label';@@ -53,6 +54,8 @@<Switch {id} bind:checked={input.value as boolean} {disabled} />{:else if type === 'textarea'}<Textarea {id} {placeholder} {rows} bind:value={input.value as string} {disabled} />+ {:else if type === 'date'}+ <DatePicker {id} bind:value={input.value as Date} />{:else}<Input {id} {placeholder} {type} bind:value={input.value} {disabled} {autocomplete} />{/if}diff --git a/frontend/src/lib/components/sheets/api-key-form-sheet.svelte b/frontend/src/lib/components/sheets/api-key-form-sheet.sveltenew file mode 100644index 000000000..217ecfa7f--- /dev/null+++ b/frontend/src/lib/components/sheets/api-key-form-sheet.svelte@@ -0,0 +1,122 @@+<script lang="ts">+ import * as Sheet from '$lib/components/ui/sheet/index.js';+ import { Button } from '$lib/components/ui/button/index.js';+ import FormInput from '$lib/components/form/form-input.svelte';+ import { Spinner } from '$lib/components/ui/spinner/index.js';+ import KeyIcon from '@lucide/svelte/icons/key';+ import SaveIcon from '@lucide/svelte/icons/save';+ import type { ApiKey } from '$lib/types/api-key.type';+ import { z } from 'zod/v4';+ import { createForm, preventDefault } from '$lib/utils/form.utils';+ import * as m from '$lib/paraglide/messages.js';++ type ApiKeyFormProps = {+ open: boolean;+ apiKeyToEdit: ApiKey | null;+ onSubmit: (data: {+ apiKey: { name: string; description?: string; expiresAt?: string };+ isEditMode: boolean;+ apiKeyId?: string;+ }) => void;+ isLoading: boolean;+ };++ let { open = $bindable(false), apiKeyToEdit = $bindable(), onSubmit, isLoading }: ApiKeyFormProps = $props();++ let isEditMode = $derived(!!apiKeyToEdit);+ let SubmitIcon = $derived(isEditMode ? SaveIcon : KeyIcon);++ const formSchema = z.object({+ name: z.string().min(1, m.common_field_required({ field: m.api_key_name() })),+ description: z.string().optional(),+ expiresAt: z.date().optional()+ });++ let formData = $derived({+ name: apiKeyToEdit?.name || '',+ description: apiKeyToEdit?.description || '',+ expiresAt: apiKeyToEdit?.expiresAt ? new Date(apiKeyToEdit.expiresAt) : undefined+ });++ let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));++ function handleSubmit() {+ const data = form.validate();+ if (!data) return;++ const apiKeyData = {+ name: data.name,+ description: data.description || undefined,+ expiresAt: data.expiresAt ? data.expiresAt.toISOString() : undefined+ };++ onSubmit({ apiKey: apiKeyData, isEditMode, apiKeyId: apiKeyToEdit?.id });+ }++ function handleOpenChange(newOpenState: boolean) {+ open = newOpenState;+ if (!newOpenState) {+ apiKeyToEdit = null;+ }+ }+</script>++<Sheet.Root bind:open onOpenChange={handleOpenChange}>+ <Sheet.Content class="p-6">+ <Sheet.Header class="space-y-3 border-b pb-6">+ <div class="flex items-center gap-3">+ <div class="bg-primary/10 flex size-10 shrink-0 items-center justify-center rounded-lg">+ <SubmitIcon class="text-primary size-5" />+ </div>+ <div>+ <Sheet.Title class="text-xl font-semibold">+ {isEditMode ? m.api_key_edit_title() : m.api_key_create_title()}+ </Sheet.Title>+ <Sheet.Description class="text-muted-foreground mt-1 text-sm">+ {#if isEditMode}+ {m.api_key_edit_description({ name: apiKeyToEdit?.name ?? m.common_unknown() })}+ {:else}+ {m.api_key_create_description()}+ {/if}+ </Sheet.Description>+ </div>+ </div>+ </Sheet.Header>++ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">+ <FormInput+ label={m.api_key_name()}+ type="text"+ placeholder={m.api_key_name_placeholder()}+ description={m.api_key_name_description()}+ bind:input={$inputs.name}+ />+ <FormInput+ label={m.api_key_description_label()}+ type="text"+ placeholder={m.api_key_description_placeholder()}+ description={m.api_key_description_help()}+ bind:input={$inputs.description}+ />+ <FormInput+ label={m.api_key_expires_at()}+ type="date"+ description={m.api_key_expires_at_description()}+ bind:input={$inputs.expiresAt}+ />++ <Sheet.Footer class="flex flex-row gap-2">+ <Button type="button" class="arcane-button-cancel flex-1" variant="outline" onclick={() => (open = false)} disabled={isLoading}+ >{m.common_cancel()}</Button+ >+ <Button type="submit" class="arcane-button-create flex-1" disabled={isLoading}>+ {#if isLoading}+ <Spinner class="mr-2 size-4" />+ {/if}+ <SubmitIcon class="mr-2 size-4" />+ {isEditMode ? m.api_key_save_changes() : m.api_key_create_button()}+ </Button>+ </Sheet.Footer>+ </form>+ </Sheet.Content>+</Sheet.Root>diff --git a/frontend/src/lib/components/ui/calendar/calendar-caption.svelte b/frontend/src/lib/components/ui/calendar/calendar-caption.sveltenew file mode 100644index 000000000..5c9303701--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-caption.svelte@@ -0,0 +1,76 @@+<script lang="ts">+ import type { ComponentProps } from "svelte";+ import type Calendar from "./calendar.svelte";+ import CalendarMonthSelect from "./calendar-month-select.svelte";+ import CalendarYearSelect from "./calendar-year-select.svelte";+ import { DateFormatter, getLocalTimeZone, type DateValue } from "@internationalized/date";++ let {+ captionLayout,+ months,+ monthFormat,+ years,+ yearFormat,+ month,+ locale,+ placeholder = $bindable(),+ monthIndex = 0,+ }: {+ captionLayout: ComponentProps<typeof Calendar>["captionLayout"];+ months: ComponentProps<typeof CalendarMonthSelect>["months"];+ monthFormat: ComponentProps<typeof CalendarMonthSelect>["monthFormat"];+ years: ComponentProps<typeof CalendarYearSelect>["years"];+ yearFormat: ComponentProps<typeof CalendarYearSelect>["yearFormat"];+ month: DateValue;+ placeholder: DateValue | undefined;+ locale: string;+ monthIndex: number;+ } = $props();++ function formatYear(date: DateValue) {+ const dateObj = date.toDate(getLocalTimeZone());+ if (typeof yearFormat === "function") return yearFormat(dateObj.getFullYear());+ return new DateFormatter(locale, { year: yearFormat }).format(dateObj);+ }++ function formatMonth(date: DateValue) {+ const dateObj = date.toDate(getLocalTimeZone());+ if (typeof monthFormat === "function") return monthFormat(dateObj.getMonth() + 1);+ return new DateFormatter(locale, { month: monthFormat }).format(dateObj);+ }+</script>++{#snippet MonthSelect()}+ <CalendarMonthSelect+ {months}+ {monthFormat}+ value={month.month}+ onchange={(e) => {+ if (!placeholder) return;+ const v = Number.parseInt(e.currentTarget.value);+ const newPlaceholder = placeholder.set({ month: v });+ placeholder = newPlaceholder.subtract({ months: monthIndex });+ }}+ />+{/snippet}++{#snippet YearSelect()}+ <CalendarYearSelect {years} {yearFormat} value={month.year} />+{/snippet}++{#if captionLayout === "dropdown"}+ {@render MonthSelect()}+ {@render YearSelect()}+{:else if captionLayout === "dropdown-months"}+ {@render MonthSelect()}+ {#if placeholder}+ {formatYear(placeholder)}+ {/if}+{:else if captionLayout === "dropdown-years"}+ {#if placeholder}+ {formatMonth(placeholder)}+ {/if}+ {@render YearSelect()}+{:else}+ {formatMonth(month)} {formatYear(month)}+{/if}diff --git a/frontend/src/lib/components/ui/calendar/calendar-cell.svelte b/frontend/src/lib/components/ui/calendar/calendar-cell.sveltenew file mode 100644index 000000000..fad6c3670--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-cell.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.CellProps = $props();+</script>++<CalendarPrimitive.Cell+ bind:ref+ class={cn(+ "size-(--cell-size) relative p-0 text-center text-sm focus-within:z-20 [&:first-child[data-selected]_[data-bits-day]]:rounded-s-md [&:last-child[data-selected]_[data-bits-day]]:rounded-e-md",+ className+ )}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-day.svelte b/frontend/src/lib/components/ui/calendar/calendar-day.sveltenew file mode 100644index 000000000..32e9c8345--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-day.svelte@@ -0,0 +1,35 @@+<script lang="ts">+ import { buttonVariants } from "$lib/components/ui/button/index.js";+ import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from "bits-ui";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.DayProps = $props();+</script>++<CalendarPrimitive.Day+ bind:ref+ class={cn(+ buttonVariants({ variant: "ghost" }),+ "size-(--cell-size) flex select-none flex-col items-center justify-center gap-1 whitespace-nowrap p-0 font-normal leading-none",+ "[&[data-today]:not([data-selected])]:bg-accent [&[data-today]:not([data-selected])]:text-accent-foreground [&[data-today][data-disabled]]:text-muted-foreground",+ "data-[selected]:bg-primary dark:data-[selected]:hover:bg-accent/50 data-[selected]:text-primary-foreground",+ // Outside months+ "[&[data-outside-month]:not([data-selected])]:text-muted-foreground [&[data-outside-month]:not([data-selected])]:hover:text-accent-foreground",+ // Disabled+ "data-[disabled]:text-muted-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ // Unavailable+ "data-[unavailable]:text-muted-foreground data-[unavailable]:line-through",+ // hover+ "dark:hover:text-accent-foreground",+ // focus+ "focus:border-ring focus:ring-ring/50 focus:relative",+ // inner spans+ "[&>span]:text-xs [&>span]:opacity-70",+ className+ )}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-body.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-body.sveltenew file mode 100644index 000000000..8cd86decd--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-body.svelte@@ -0,0 +1,12 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.GridBodyProps = $props();+</script>++<CalendarPrimitive.GridBody bind:ref class={cn(className)} {...restProps} />diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-head.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-head.sveltenew file mode 100644index 000000000..333edc47e--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-head.svelte@@ -0,0 +1,12 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.GridHeadProps = $props();+</script>++<CalendarPrimitive.GridHead bind:ref class={cn(className)} {...restProps} />diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-row.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-row.sveltenew file mode 100644index 000000000..903223698--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-row.svelte@@ -0,0 +1,12 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.GridRowProps = $props();+</script>++<CalendarPrimitive.GridRow bind:ref class={cn("flex", className)} {...restProps} />diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid.sveltenew file mode 100644index 000000000..e0c8627f3--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-grid.svelte@@ -0,0 +1,16 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.GridProps = $props();+</script>++<CalendarPrimitive.Grid+ bind:ref+ class={cn("mt-4 flex w-full border-collapse flex-col gap-1", className)}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-head-cell.svelte b/frontend/src/lib/components/ui/calendar/calendar-head-cell.sveltenew file mode 100644index 000000000..131807e2d--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-head-cell.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.HeadCellProps = $props();+</script>++<CalendarPrimitive.HeadCell+ bind:ref+ class={cn(+ "text-muted-foreground w-(--cell-size) rounded-md text-[0.8rem] font-normal",+ className+ )}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-header.svelte b/frontend/src/lib/components/ui/calendar/calendar-header.sveltenew file mode 100644index 000000000..5b7e3972f--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-header.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.HeaderProps = $props();+</script>++<CalendarPrimitive.Header+ bind:ref+ class={cn(+ "h-(--cell-size) flex w-full items-center justify-center gap-1.5 text-sm font-medium",+ className+ )}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-heading.svelte b/frontend/src/lib/components/ui/calendar/calendar-heading.sveltenew file mode 100644index 000000000..a9b9810c6--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-heading.svelte@@ -0,0 +1,16 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.HeadingProps = $props();+</script>++<CalendarPrimitive.Heading+ bind:ref+ class={cn("px-(--cell-size) text-sm font-medium", className)}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-month-select.svelte b/frontend/src/lib/components/ui/calendar/calendar-month-select.sveltenew file mode 100644index 000000000..c17c59d1f--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-month-select.svelte@@ -0,0 +1,44 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";++ let {+ ref = $bindable(null),+ class: className,+ value,+ onchange,+ ...restProps+ }: WithoutChildrenOrChild<CalendarPrimitive.MonthSelectProps> = $props();+</script>++<span+ class={cn(+ "has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative flex rounded-md border",+ className+ )}+>+ <CalendarPrimitive.MonthSelect bind:ref class="absolute inset-0 opacity-0" {...restProps}>+ {#snippet child({ props, monthItems, selectedMonthItem })}+ <select {...props} {value} {onchange}>+ {#each monthItems as monthItem (monthItem.value)}+ <option+ value={monthItem.value}+ selected={value !== undefined+ ? monthItem.value === value+ : monthItem.value === selectedMonthItem.value}+ >+ {monthItem.label}+ </option>+ {/each}+ </select>+ <span+ class="[&>svg]:text-muted-foreground flex h-8 select-none items-center gap-1 rounded-md pe-1 ps-2 text-sm font-medium [&>svg]:size-3.5"+ aria-hidden="true"+ >+ {monthItems.find((item) => item.value === value)?.label || selectedMonthItem.label}+ <ChevronDownIcon class="size-4" />+ </span>+ {/snippet}+ </CalendarPrimitive.MonthSelect>+</span>diff --git a/frontend/src/lib/components/ui/calendar/calendar-month.svelte b/frontend/src/lib/components/ui/calendar/calendar-month.sveltenew file mode 100644index 000000000..e747fae74--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-month.svelte@@ -0,0 +1,15 @@+<script lang="ts">+ import { type WithElementRef, cn } from "$lib/utils.js";+ import type { HTMLAttributes } from "svelte/elements";++ let {+ ref = $bindable(null),+ class: className,+ children,+ ...restProps+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();+</script>++<div {...restProps} bind:this={ref} class={cn("flex flex-col", className)}>+ {@render children?.()}+</div>diff --git a/frontend/src/lib/components/ui/calendar/calendar-months.svelte b/frontend/src/lib/components/ui/calendar/calendar-months.sveltenew file mode 100644index 000000000..f717a9d9a--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-months.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ children,+ ...restProps+ }: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();+</script>++<div+ bind:this={ref}+ class={cn("relative flex flex-col gap-4 md:flex-row", className)}+ {...restProps}+>+ {@render children?.()}+</div>diff --git a/frontend/src/lib/components/ui/calendar/calendar-nav.svelte b/frontend/src/lib/components/ui/calendar/calendar-nav.sveltenew file mode 100644index 000000000..27f33d797--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-nav.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from "svelte/elements";++ let {+ ref = $bindable(null),+ class: className,+ children,+ ...restProps+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();+</script>++<nav+ {...restProps}+ bind:this={ref}+ class={cn("absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", className)}+>+ {@render children?.()}+</nav>diff --git a/frontend/src/lib/components/ui/calendar/calendar-next-button.svelte b/frontend/src/lib/components/ui/calendar/calendar-next-button.sveltenew file mode 100644index 000000000..d8eb4efa0--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-next-button.svelte@@ -0,0 +1,31 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import ChevronRightIcon from "@lucide/svelte/icons/chevron-right";+ import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ children,+ variant = "ghost",+ ...restProps+ }: CalendarPrimitive.NextButtonProps & {+ variant?: ButtonVariant;+ } = $props();+</script>++{#snippet Fallback()}+ <ChevronRightIcon class="size-4" />+{/snippet}++<CalendarPrimitive.NextButton+ bind:ref+ class={cn(+ buttonVariants({ variant }),+ "size-(--cell-size) select-none bg-transparent p-0 disabled:opacity-50 rtl:rotate-180",+ className+ )}+ children={children || Fallback}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-prev-button.svelte b/frontend/src/lib/components/ui/calendar/calendar-prev-button.sveltenew file mode 100644index 000000000..3e4471a20--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-prev-button.svelte@@ -0,0 +1,31 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import ChevronLeftIcon from "@lucide/svelte/icons/chevron-left";+ import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ children,+ variant = "ghost",+ ...restProps+ }: CalendarPrimitive.PrevButtonProps & {+ variant?: ButtonVariant;+ } = $props();+</script>++{#snippet Fallback()}+ <ChevronLeftIcon class="size-4" />+{/snippet}++<CalendarPrimitive.PrevButton+ bind:ref+ class={cn(+ buttonVariants({ variant }),+ "size-(--cell-size) select-none bg-transparent p-0 disabled:opacity-50 rtl:rotate-180",+ className+ )}+ children={children || Fallback}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-year-select.svelte b/frontend/src/lib/components/ui/calendar/calendar-year-select.sveltenew file mode 100644index 000000000..3ac691edc--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-year-select.svelte@@ -0,0 +1,43 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";++ let {+ ref = $bindable(null),+ class: className,+ value,+ ...restProps+ }: WithoutChildrenOrChild<CalendarPrimitive.YearSelectProps> = $props();+</script>++<span+ class={cn(+ "has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative flex rounded-md border",+ className+ )}+>+ <CalendarPrimitive.YearSelect bind:ref class="absolute inset-0 opacity-0" {...restProps}>+ {#snippet child({ props, yearItems, selectedYearItem })}+ <select {...props} {value}>+ {#each yearItems as yearItem (yearItem.value)}+ <option+ value={yearItem.value}+ selected={value !== undefined+ ? yearItem.value === value+ : yearItem.value === selectedYearItem.value}+ >+ {yearItem.label}+ </option>+ {/each}+ </select>+ <span+ class="[&>svg]:text-muted-foreground flex h-8 select-none items-center gap-1 rounded-md pe-1 ps-2 text-sm font-medium [&>svg]:size-3.5"+ aria-hidden="true"+ >+ {yearItems.find((item) => item.value === value)?.label || selectedYearItem.label}+ <ChevronDownIcon class="size-4" />+ </span>+ {/snippet}+ </CalendarPrimitive.YearSelect>+</span>diff --git a/frontend/src/lib/components/ui/calendar/calendar.svelte b/frontend/src/lib/components/ui/calendar/calendar.sveltenew file mode 100644index 000000000..29b6fff9a--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar.svelte@@ -0,0 +1,115 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import * as Calendar from "./index.js";+ import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import type { ButtonVariant } from "../button/button.svelte";+ import { isEqualMonth, type DateValue } from "@internationalized/date";+ import type { Snippet } from "svelte";++ let {+ ref = $bindable(null),+ value = $bindable(),+ placeholder = $bindable(),+ class: className,+ weekdayFormat = "short",+ buttonVariant = "ghost",+ captionLayout = "label",+ locale = "en-US",+ months: monthsProp,+ years,+ monthFormat: monthFormatProp,+ yearFormat = "numeric",+ day,+ disableDaysOutsideMonth = false,+ ...restProps+ }: WithoutChildrenOrChild<CalendarPrimitive.RootProps> & {+ buttonVariant?: ButtonVariant;+ captionLayout?: "dropdown" | "dropdown-months" | "dropdown-years" | "label";+ months?: CalendarPrimitive.MonthSelectProps["months"];+ years?: CalendarPrimitive.YearSelectProps["years"];+ monthFormat?: CalendarPrimitive.MonthSelectProps["monthFormat"];+ yearFormat?: CalendarPrimitive.YearSelectProps["yearFormat"];+ day?: Snippet<[{ day: DateValue; outsideMonth: boolean }]>;+ } = $props();++ const monthFormat = $derived.by(() => {+ if (monthFormatProp) return monthFormatProp;+ if (captionLayout.startsWith("dropdown")) return "short";+ return "long";+ });+</script>++<!--+Discriminated Unions + Destructing (required for bindable) do not+get along, so we shut typescript up by casting `value` to `never`.+-->+<CalendarPrimitive.Root+ bind:value={value as never}+ bind:ref+ bind:placeholder+ {weekdayFormat}+ {disableDaysOutsideMonth}+ class={cn(+ "bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",+ className+ )}+ {locale}+ {monthFormat}+ {yearFormat}+ {...restProps}+>+ {#snippet children({ months, weekdays })}+ <Calendar.Months>+ <Calendar.Nav>+ <Calendar.PrevButton variant={buttonVariant} />+ <Calendar.NextButton variant={buttonVariant} />+ </Calendar.Nav>+ {#each months as month, monthIndex (month)}+ <Calendar.Month>+ <Calendar.Header>+ <Calendar.Caption+ {captionLayout}+ months={monthsProp}+ {monthFormat}+ {years}+ {yearFormat}+ month={month.value}+ bind:placeholder+ {locale}+ {monthIndex}+ />+ </Calendar.Header>+ <Calendar.Grid>+ <Calendar.GridHead>+ <Calendar.GridRow class="select-none">+ {#each weekdays as weekday (weekday)}+ <Calendar.HeadCell>+ {weekday.slice(0, 2)}+ </Calendar.HeadCell>+ {/each}+ </Calendar.GridRow>+ </Calendar.GridHead>+ <Calendar.GridBody>+ {#each month.weeks as weekDates (weekDates)}+ <Calendar.GridRow class="mt-2 w-full">+ {#each weekDates as date (date)}+ <Calendar.Cell {date} month={month.value}>+ {#if day}+ {@render day({+ day: date,+ outsideMonth: !isEqualMonth(date, month.value),+ })}+ {:else}+ <Calendar.Day />+ {/if}+ </Calendar.Cell>+ {/each}+ </Calendar.GridRow>+ {/each}+ </Calendar.GridBody>+ </Calendar.Grid>+ </Calendar.Month>+ {/each}+ </Calendar.Months>+ {/snippet}+</CalendarPrimitive.Root>diff --git a/frontend/src/lib/components/ui/calendar/index.ts b/frontend/src/lib/components/ui/calendar/index.tsnew file mode 100644index 000000000..f3a16d2d5--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/index.ts@@ -0,0 +1,40 @@+import Root from "./calendar.svelte";+import Cell from "./calendar-cell.svelte";+import Day from "./calendar-day.svelte";+import Grid from "./calendar-grid.svelte";+import Header from "./calendar-header.svelte";+import Months from "./calendar-months.svelte";+import GridRow from "./calendar-grid-row.svelte";+import Heading from "./calendar-heading.svelte";+import GridBody from "./calendar-grid-body.svelte";+import GridHead from "./calendar-grid-head.svelte";+import HeadCell from "./calendar-head-cell.svelte";+import NextButton from "./calendar-next-button.svelte";+import PrevButton from "./calendar-prev-button.svelte";+import MonthSelect from "./calendar-month-select.svelte";+import YearSelect from "./calendar-year-select.svelte";+import Month from "./calendar-month.svelte";+import Nav from "./calendar-nav.svelte";+import Caption from "./calendar-caption.svelte";++export {+ Day,+ Cell,+ Grid,+ Header,+ Months,+ GridRow,+ Heading,+ GridBody,+ GridHead,+ HeadCell,+ NextButton,+ PrevButton,+ Nav,+ Month,+ YearSelect,+ MonthSelect,+ Caption,+ //+ Root as Calendar,+};diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.tsindex a8b752769..68cf0d767 100644--- a/frontend/src/lib/config/navigation-config.ts+++ b/frontend/src/lib/config/navigation-config.ts@@ -1,4 +1,4 @@-import type { Icon as IconType } from '@lucide/svelte';+import { KeyIcon, type Icon as IconType } from '@lucide/svelte';import PaletteIcon from '@lucide/svelte/icons/palette';import FileStackIcon from '@lucide/svelte/icons/file-stack';import HardDriveIcon from '@lucide/svelte/icons/hard-drive';@@ -70,7 +70,8 @@ export const navigationItems: Record<string, NavigationItem[]> = {{ title: m.security_title(), url: '/settings/security', icon: ShieldIcon },{ title: m.navigation_title(), url: '/settings/navigation', icon: NavigationIcon },{ title: m.users_title(), url: '/settings/users', icon: UserIcon },- { title: m.notifications_title(), url: '/settings/notifications', icon: BellIcon }+ { title: m.notifications_title(), url: '/settings/notifications', icon: BellIcon },+ { title: m.api_key_page_title(), url: '/settings/api-keys', icon: KeyIcon },]}]diff --git a/frontend/src/lib/services/api-key-service.ts b/frontend/src/lib/services/api-key-service.tsnew file mode 100644index 000000000..69ce758e6--- /dev/null+++ b/frontend/src/lib/services/api-key-service.ts@@ -0,0 +1,30 @@+import BaseAPIService from './api-service';+import type { ApiKey, ApiKeyCreated, CreateApiKey, UpdateApiKey } from '$lib/types/api-key.type';+import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { transformPaginationParams } from '$lib/utils/params.util';++export default class ApiKeyAPIService extends BaseAPIService {+ async getApiKeys(options?: SearchPaginationSortRequest): Promise<Paginated<ApiKey>> {+ const params = transformPaginationParams(options);+ const res = await this.api.get('/api-keys', { params });+ return res.data;+ }++ async get(id: string): Promise<ApiKey> {+ return this.handleResponse(this.api.get(`/api-keys/${id}`)) as Promise<ApiKey>;+ }++ async create(apiKey: CreateApiKey): Promise<ApiKeyCreated> {+ return this.handleResponse(this.api.post('/api-keys', apiKey)) as Promise<ApiKeyCreated>;+ }++ async update(id: string, apiKey: UpdateApiKey): Promise<ApiKey> {+ return this.handleResponse(this.api.put(`/api-keys/${id}`, apiKey)) as Promise<ApiKey>;+ }++ async delete(id: string): Promise<void> {+ return this.handleResponse(this.api.delete(`/api-keys/${id}`)) as Promise<void>;+ }+}++export const apiKeyService = new ApiKeyAPIService();diff --git a/frontend/src/lib/types/api-key.type.ts b/frontend/src/lib/types/api-key.type.tsnew file mode 100644index 000000000..5e5c90957--- /dev/null+++ b/frontend/src/lib/types/api-key.type.ts@@ -0,0 +1,27 @@+export type ApiKey = {+ id: string;+ name: string;+ description?: string;+ keyPrefix: string;+ userId: string;+ expiresAt?: string;+ lastUsedAt?: string;+ createdAt: string;+ updatedAt?: string;+};++export type ApiKeyCreated = ApiKey & {+ key: string;+};++export type CreateApiKey = {+ name: string;+ description?: string;+ expiresAt?: string;+};++export type UpdateApiKey = {+ name?: string;+ description?: string;+ expiresAt?: string;+};diff --git a/frontend/src/routes/(app)/networks/network-table.svelte b/frontend/src/routes/(app)/networks/network-table.svelteindex 97996a586..3ccc65922 100644--- a/frontend/src/routes/(app)/networks/network-table.svelte+++ b/frontend/src/routes/(app)/networks/network-table.svelte@@ -23,6 +23,8 @@import RouteIcon from '@lucide/svelte/icons/route';import GlobeIcon from '@lucide/svelte/icons/globe';+ type FieldVisibility = Record<string, boolean>;+let {networks = $bindable(),selectedIds = $bindable(),@@ -215,7 +217,7 @@}: {row: any;item: NetworkSummaryDto;- mobileFieldVisibility: Record<string, boolean>;+ mobileFieldVisibility: FieldVisibility;})}<UniversalMobileCard{item}diff --git a/frontend/src/routes/(app)/settings/api-keys/+page.svelte b/frontend/src/routes/(app)/settings/api-keys/+page.sveltenew file mode 100644index 000000000..7d04b2190--- /dev/null+++ b/frontend/src/routes/(app)/settings/api-keys/+page.svelte@@ -0,0 +1,175 @@+<script lang="ts">+ import KeyIcon from '@lucide/svelte/icons/key';+ import { toast } from 'svelte-sonner';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import ApiKeyTable from './api-key-table.svelte';+ import ApiKeyFormSheet from '$lib/components/sheets/api-key-form-sheet.svelte';+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+ import type { ApiKey, ApiKeyCreated } from '$lib/types/api-key.type';+ import { apiKeyService } from '$lib/services/api-key-service';+ import { SettingsPageLayout, type SettingsActionButton } from '$lib/layouts/index.js';+ import * as Dialog from '$lib/components/ui/dialog/index.js';+ import { Button } from '$lib/components/ui/button/index.js';+ import { Snippet } from '$lib/components/ui/snippet/index.js';+ import * as m from '$lib/paraglide/messages.js';+ import { untrack } from 'svelte';++ let { data } = $props();++ let apiKeys = $state(untrack(() => data.apiKeys));+ let selectedIds = $state<string[]>([]);+ let requestOptions = $state<SearchPaginationSortRequest>(untrack(() => data.apiKeyRequestOptions));++ let isDialogOpen = $state({+ create: false,+ edit: false,+ showKey: false+ });++ let apiKeyToEdit = $state<ApiKey | null>(null);+ let newlyCreatedKey = $state<ApiKeyCreated | null>(null);++ let isLoading = $state({+ creating: false,+ editing: false,+ refresh: false+ });++ function openCreateDialog() {+ apiKeyToEdit = null;+ isDialogOpen.create = true;+ }++ function openEditDialog(apiKey: ApiKey) {+ apiKeyToEdit = apiKey;+ isDialogOpen.edit = true;+ }++ async function handleApiKeySubmit({+ apiKey,+ isEditMode,+ apiKeyId+ }: {+ apiKey: { name: string; description?: string; expiresAt?: string };+ isEditMode: boolean;+ apiKeyId?: string;+ }) {+ const loading = isEditMode ? 'editing' : 'creating';+ isLoading[loading] = true;++ try {+ if (isEditMode && apiKeyId) {+ const safeName = apiKey.name?.trim() || 'Unknown';+ const result = await tryCatch(apiKeyService.update(apiKeyId, apiKey));+ handleApiResultWithCallbacks({+ result,+ message: m.api_key_update_failed({ name: safeName }),+ setLoadingState: (value) => (isLoading[loading] = value),+ onSuccess: async () => {+ toast.success(m.api_key_updated_success({ name: safeName }));+ apiKeys = await apiKeyService.getApiKeys(requestOptions);+ isDialogOpen.edit = false;+ apiKeyToEdit = null;+ }+ });+ } else {+ const safeName = apiKey.name?.trim() || 'Unknown';+ const result = await tryCatch(apiKeyService.create(apiKey));+ handleApiResultWithCallbacks({+ result,+ message: m.api_key_create_failed({ name: safeName }),+ setLoadingState: (value) => (isLoading[loading] = value),+ onSuccess: async (createdKey) => {+ toast.success(m.api_key_created_success({ name: safeName }));+ apiKeys = await apiKeyService.getApiKeys(requestOptions);+ isDialogOpen.create = false;+ newlyCreatedKey = createdKey as ApiKeyCreated;+ isDialogOpen.showKey = true;+ }+ });+ }+ } catch (error) {+ console.error('Failed to submit API key:', error);+ }+ }++ const actionButtons: SettingsActionButton[] = $derived.by(() => [+ {+ id: 'create',+ action: 'create',+ label: m.api_key_create_button(),+ onclick: openCreateDialog,+ loading: isLoading.creating,+ disabled: isLoading.creating+ }+ ]);+</script>++<SettingsPageLayout+ title={m.api_key_page_title()}+ description={m.api_key_page_description()}+ icon={KeyIcon}+ pageType="management"+ {actionButtons}+ statCardsColumns={3}+>+ {#snippet mainContent()}+ <ApiKeyTable+ bind:apiKeys+ bind:selectedIds+ bind:requestOptions+ onApiKeysChanged={async () => {+ apiKeys = await apiKeyService.getApiKeys(requestOptions);+ }}+ onEditApiKey={openEditDialog}+ />+ {/snippet}++ {#snippet additionalContent()}+ <ApiKeyFormSheet+ bind:open={isDialogOpen.create}+ apiKeyToEdit={null}+ onSubmit={handleApiKeySubmit}+ isLoading={isLoading.creating}+ />++ <ApiKeyFormSheet bind:open={isDialogOpen.edit} {apiKeyToEdit} onSubmit={handleApiKeySubmit} isLoading={isLoading.editing} />++ <Dialog.Root bind:open={isDialogOpen.showKey}>+ <Dialog.Content class="!max-w-fit">+ <Dialog.Header>+ <Dialog.Title class="flex items-center gap-2">+ <KeyIcon class="size-5" />+ {m.api_key_created_title()}+ </Dialog.Title>+ <Dialog.Description>+ {m.api_key_created_description()}+ </Dialog.Description>+ </Dialog.Header>+ <div class="space-y-4 py-4">+ <div class="bg-muted rounded-lg p-4">+ <p class="text-muted-foreground mb-2 text-sm font-medium">{m.api_key_your_key()}</p>+ <Snippet+ text={newlyCreatedKey?.key || ''}+ onCopy={(status) => {+ if (status === 'success') {+ toast.success(m.api_key_copied_success());+ }+ }}+ />+ </div>+ <div class="rounded-lg border border-yellow-200 bg-yellow-50 p-4 dark:border-yellow-800 dark:bg-yellow-900/20">+ <p class="text-sm text-yellow-800 dark:text-yellow-200">+ <strong>{m.common_important()}:</strong>+ {m.api_key_important_warning()}+ </p>+ </div>+ </div>+ <Dialog.Footer>+ <Button onclick={() => (isDialogOpen.showKey = false)}>{m.common_done()}</Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog.Root>+ {/snippet}+</SettingsPageLayout>diff --git a/frontend/src/routes/(app)/settings/api-keys/+page.ts b/frontend/src/routes/(app)/settings/api-keys/+page.tsnew file mode 100644index 000000000..50a81455c--- /dev/null+++ b/frontend/src/routes/(app)/settings/api-keys/+page.ts@@ -0,0 +1,23 @@+import { apiKeyService } from '$lib/services/api-key-service';+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';++export const load = async () => {+ const apiKeyRequestOptions = resolveInitialTableRequest('arcane-api-keys-table', {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'createdAt',+ direction: 'desc'+ }+ } satisfies SearchPaginationSortRequest);++ const apiKeys = await apiKeyService.getApiKeys(apiKeyRequestOptions);++ return {+ apiKeys,+ apiKeyRequestOptions+ };+};diff --git a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte b/frontend/src/routes/(app)/settings/api-keys/api-key-table.sveltenew file mode 100644index 000000000..1ed6ec1ea--- /dev/null+++ b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte@@ -0,0 +1,278 @@+<script lang="ts">+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';+ import { Button } from '$lib/components/ui/button/index.js';+ import Trash2Icon from '@lucide/svelte/icons/trash-2';+ import EllipsisIcon from '@lucide/svelte/icons/ellipsis';+ import EditIcon from '@lucide/svelte/icons/edit';+ import CopyIcon from '@lucide/svelte/icons/copy';+ import { toast } from 'svelte-sonner';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';+ import type { ApiKey } from '$lib/types/api-key.type';+ import type { ColumnSpec } from '$lib/components/arcane-table';+ import { UniversalMobileCard } from '$lib/components/arcane-table';+ import { apiKeyService } from '$lib/services/api-key-service';+ import KeyIcon from '@lucide/svelte/icons/key';+ import * as m from '$lib/paraglide/messages.js';++ let {+ apiKeys = $bindable(),+ selectedIds = $bindable(),+ requestOptions = $bindable(),+ onApiKeysChanged,+ onEditApiKey+ }: {+ apiKeys: Paginated<ApiKey>;+ selectedIds: string[];+ requestOptions: SearchPaginationSortRequest;+ onApiKeysChanged: () => Promise<void>;+ onEditApiKey: (apiKey: ApiKey) => void;+ } = $props();++ let isLoading = $state({+ removing: false+ });++ function formatDate(dateString?: string): string {+ if (!dateString) return '-';+ return new Date(dateString).toLocaleString();+ }++ function isExpired(expiresAt?: string): boolean {+ if (!expiresAt) return false;+ return new Date(expiresAt) < new Date();+ }++ function getStatusText(apiKey: ApiKey): string {+ if (isExpired(apiKey.expiresAt)) return m.api_key_status_expired();+ return m.api_key_status_active();+ }++ function getStatusVariant(apiKey: ApiKey): 'red' | 'green' {+ if (isExpired(apiKey.expiresAt)) return 'red';+ return 'green';+ }++ async function copyToClipboard(text: string) {+ try {+ await navigator.clipboard.writeText(text);+ toast.success(m.common_copied());+ } catch {+ toast.error(m.common_copy_failed());+ }+ }++ async function handleDeleteSelected() {+ if (selectedIds.length === 0) return;++ openConfirmDialog({+ title: m.api_key_delete_selected_title({ count: selectedIds.length }),+ message: m.api_key_delete_selected_message({ count: selectedIds.length }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ isLoading.removing = true;+ let successCount = 0;+ let failureCount = 0;++ for (const apiKeyId of selectedIds) {+ const result = await tryCatch(apiKeyService.delete(apiKeyId));+ handleApiResultWithCallbacks({+ result,+ message: m.api_key_delete_failed({ name: apiKeyId }),+ setLoadingState: () => {},+ onSuccess: () => {+ successCount++;+ }+ });++ if (result.error) {+ failureCount++;+ }+ }++ isLoading.removing = false;++ if (successCount > 0) {+ toast.success(m.api_key_bulk_delete_success({ count: successCount }));+ await onApiKeysChanged();+ }++ if (failureCount > 0) {+ toast.error(m.api_key_bulk_delete_failed({ count: failureCount }));+ }++ selectedIds = [];+ }+ }+ });+ }++ async function handleDeleteApiKey(apiKeyId: string, name: string) {+ const safeName = name?.trim() || m.common_unknown();+ openConfirmDialog({+ title: m.api_key_delete_title({ name: safeName }),+ message: m.api_key_delete_message({ name: safeName }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ isLoading.removing = true;+ handleApiResultWithCallbacks({+ result: await tryCatch(apiKeyService.delete(apiKeyId)),+ message: m.api_key_delete_failed({ name: safeName }),+ setLoadingState: (value) => (isLoading.removing = value),+ onSuccess: async () => {+ toast.success(m.api_key_delete_success({ name: safeName }));+ await onApiKeysChanged();+ }+ });+ }+ }+ });+ }++ const columns = [+ { accessorKey: 'name', title: m.api_key_name(), sortable: true, cell: NameCell },+ { accessorKey: 'description', title: m.api_key_description_label(), sortable: false, cell: DescriptionCell },+ { accessorKey: 'keyPrefix', title: m.api_key_key_prefix(), sortable: false, cell: KeyPrefixCell },+ { accessorKey: 'expiresAt', title: m.api_key_expires_at(), sortable: true, cell: ExpiresCell },+ { accessorKey: 'lastUsedAt', title: m.api_key_last_used(), sortable: true, cell: LastUsedCell }+ ] satisfies ColumnSpec<ApiKey>[];++ const mobileFields = [+ { id: 'description', label: m.api_key_description_label(), defaultVisible: true },+ { id: 'keyPrefix', label: m.api_key_key_prefix(), defaultVisible: true },+ { id: 'expiresAt', label: m.api_key_expires_at(), defaultVisible: true },+ { id: 'lastUsedAt', label: m.api_key_last_used(), defaultVisible: true }+ ];++ let mobileFieldVisibility = $state<Record<string, boolean>>({});+</script>++{#snippet NameCell({ item }: { item: ApiKey })}+ <span class="font-medium">{item.name}</span>+{/snippet}++{#snippet DescriptionCell({ item }: { item: ApiKey })}+ <span class="text-muted-foreground">{item.description || '-'}</span>+{/snippet}++{#snippet KeyPrefixCell({ item }: { item: ApiKey })}+ <div class="flex items-center gap-2">+ <code class="bg-muted rounded px-2 py-1 text-xs">{item.keyPrefix}...</code>+ <Button variant="ghost" size="icon" class="size-6" onclick={() => copyToClipboard(item.keyPrefix)}>+ <CopyIcon class="size-3" />+ </Button>+ </div>+{/snippet}++{#snippet ExpiresCell({ item }: { item: ApiKey })}+ <div class="flex items-center gap-2">+ {#if item.expiresAt}+ <span class={isExpired(item.expiresAt) ? 'text-red-500' : ''}>{formatDate(item.expiresAt)}</span>+ {:else}+ <span class="text-muted-foreground">{m.api_key_expires_never()}</span>+ {/if}+ <StatusBadge text={getStatusText(item)} variant={getStatusVariant(item)} />+ </div>+{/snippet}++{#snippet LastUsedCell({ item }: { item: ApiKey })}+ {formatDate(item.lastUsedAt)}+{/snippet}++{#snippet ApiKeyMobileCardSnippet({+ row,+ item,+ mobileFieldVisibility+}: {+ row: any;+ item: ApiKey;+ mobileFieldVisibility: Record<string, boolean>;+})}+ <UniversalMobileCard+ {item}+ icon={{ component: KeyIcon, variant: 'blue' }}+ title={(item: ApiKey) => item.name}+ subtitle={(item: ApiKey) => ((mobileFieldVisibility.keyPrefix ?? true) ? `${item.keyPrefix}...` : null)}+ badges={[+ (item: ApiKey) => ({+ variant: getStatusVariant(item),+ text: getStatusText(item)+ })+ ]}+ fields={[+ {+ label: m.api_key_description_label(),+ getValue: (item: ApiKey) => item.description || '-',+ icon: KeyIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.description ?? true+ },+ {+ label: m.api_key_expires_at(),+ getValue: (item: ApiKey) => (item.expiresAt ? formatDate(item.expiresAt) : m.api_key_expires_never()),+ icon: KeyIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.expiresAt ?? true+ },+ {+ label: m.api_key_last_used(),+ getValue: (item: ApiKey) => formatDate(item.lastUsedAt),+ icon: KeyIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.lastUsedAt ?? true+ }+ ]}+ rowActions={RowActions}+ />+{/snippet}++{#snippet RowActions({ item }: { item: ApiKey })}+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ {#snippet child({ props })}+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">+ <span class="sr-only">{m.common_open_menu()}</span>+ <EllipsisIcon />+ </Button>+ {/snippet}+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Group>+ <DropdownMenu.Item onclick={() => onEditApiKey(item)}>+ <EditIcon class="size-4" />+ {m.common_edit()}+ </DropdownMenu.Item>+ <DropdownMenu.Item variant="destructive" onclick={() => handleDeleteApiKey(item.id, item.name)}>+ <Trash2Icon class="size-4" />+ {m.common_delete()}+ </DropdownMenu.Item>+ </DropdownMenu.Group>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+{/snippet}++<ArcaneTable+ persistKey="arcane-api-keys-table"+ items={apiKeys}+ bind:requestOptions+ bind:selectedIds+ bind:mobileFieldVisibility+ onRemoveSelected={(ids) => handleDeleteSelected()}+ onRefresh={async (options) => {+ requestOptions = options;+ await onApiKeysChanged();+ return apiKeys;+ }}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={ApiKeyMobileCardSnippet}+/>diff --git a/tests/spec/api-keys.spec.ts b/tests/spec/api-keys.spec.tsnew file mode 100644index 000000000..c5b8bac1c--- /dev/null+++ b/tests/spec/api-keys.spec.ts@@ -0,0 +1,199 @@+import { test, expect, type Page } from '@playwright/test';+import { createTestApiKeys, deleteTestApiKeys } from '../utils/onboarding.util';++const API_KEYS_ROUTE = '/settings/api-keys';++async function navigateToApiKeys(page: Page) {+ await page.goto(API_KEYS_ROUTE);+ await page.waitForLoadState('networkidle');+}++test.describe('API Keys Page', () => {+ // Create test API keys before tests that need existing data+ test.beforeAll(async () => {+ await createTestApiKeys(3);+ });++ // Clean up test API keys after all tests+ test.afterAll(async () => {+ await deleteTestApiKeys();+ });++ test('should display the API keys page title and description', async ({ page }) => {+ await navigateToApiKeys(page);+ await expect(page.getByRole('heading', { name: 'API Keys', level: 1 })).toBeVisible();+ await expect(page.getByText('Manage API keys for programmatic access to Arcane').first()).toBeVisible();+ });++ test('should open Create API Key sheet', async ({ page }) => {+ await navigateToApiKeys(page);++ await page.getByRole('button', { name: 'Create API Key' }).click();+ await expect(page.getByRole('dialog')).toBeVisible();+ await expect(page.getByText('Create API Key').first()).toBeVisible();+ });++ test('should validate required fields when creating API key', async ({ page }) => {+ await navigateToApiKeys(page);++ await page.getByRole('button', { name: 'Create API Key' }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();++ // Try to submit without filling required name field+ await dialog.getByRole('button', { name: /Create API Key/i }).click();++ // Should show validation error for name field+ await expect(dialog.getByText(/is required/i)).toBeVisible();+ });++ test('should create a new API key and show the key dialog', async ({ page }) => {+ await navigateToApiKeys(page);++ await page.getByRole('button', { name: 'Create API Key' }).click();+ const createDialog = page.getByRole('dialog');+ await expect(createDialog).toBeVisible();++ const apiKeyName = `test-key-${Date.now()}`;++ // Fill in the name field+ await createDialog.getByLabel(/Name/i).fill(apiKeyName);++ // Optionally fill description+ const descInput = createDialog.getByLabel(/Description/i);+ if (await descInput.count()) {+ await descInput.fill('E2E test API key');+ }++ // Submit the form+ await createDialog.getByRole('button', { name: /Create API Key/i }).click();++ // Should show success toast+ await expect(page.locator('li[data-sonner-toast][data-type="success"]').first()).toBeVisible({ timeout: 10000 });++ // Should show the API key reveal dialog+ await expect(page.getByText('API Key Created')).toBeVisible();+ await expect(page.getByText(/Copy your API key now/i)).toBeVisible();++ // The key should be visible in a code/snippet element+ await expect(page.locator('code, [data-snippet]').first()).toBeVisible();++ // Close the dialog+ await page.getByRole('button', { name: 'Done' }).click();++ // The new key should appear in the table+ await expect(page.locator(`tr:has-text("${apiKeyName}")`)).toBeVisible();+ });++ test('should open edit dialog from row actions', async ({ page }) => {+ await navigateToApiKeys(page);++ const firstRow = page.locator('tbody tr').first();+ await expect(firstRow).toBeVisible();++ await firstRow.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Edit' }).click();++ await expect(page.getByRole('dialog')).toBeVisible();+ await expect(page.getByText('Edit API Key')).toBeVisible();++ // Close the dialog+ await page.keyboard.press('Escape');+ });++ test('should open delete confirmation dialog from row actions', async ({ page }) => {+ await navigateToApiKeys(page);++ const firstRow = page.locator('tbody tr').first();+ await expect(firstRow).toBeVisible();++ await firstRow.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Delete' }).click();++ // Should show confirmation dialog+ await expect(page.getByText(/Delete API Key/i)).toBeVisible();+ await expect(page.getByText(/Are you sure/i)).toBeVisible();++ // Cancel the deletion+ await page.getByRole('button', { name: 'Cancel' }).click();+ });++ test('should delete an API key', async ({ page }) => {+ // First create a key to delete+ await navigateToApiKeys(page);++ await page.getByRole('button', { name: 'Create API Key' }).click();+ const createDialog = page.getByRole('dialog');++ const apiKeyName = `delete-test-${Date.now()}`;+ await createDialog.getByLabel(/Name/i).fill(apiKeyName);+ await createDialog.getByRole('button', { name: /Create API Key/i }).click();++ // Wait for creation success and close reveal dialog+ await expect(page.getByText('API Key Created')).toBeVisible({ timeout: 10000 });+ await page.getByRole('button', { name: 'Done' }).click();++ // Wait for toasts to clear+ await page.waitForTimeout(1000);++ // Now delete the key+ const keyRow = page.locator(`tr:has-text("${apiKeyName}")`);+ await expect(keyRow).toBeVisible();++ await keyRow.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Delete' }).click();++ // Confirm deletion+ await expect(page.getByText(/Delete API Key/i)).toBeVisible();+ await page.getByRole('button', { name: 'Delete' }).click();++ // Should show success toast for deletion+ await expect(page.getByText(/deleted successfully/i)).toBeVisible({ timeout: 10000 });++ // Key should no longer be in the table+ await expect(keyRow).toBeHidden();+ });++ test('should select multiple API keys and show bulk delete option', async ({ page }) => {+ await navigateToApiKeys(page);++ // Select first two checkboxes+ const checkboxes = page.locator('tbody tr input[type="checkbox"]');+ const checkboxCount = await checkboxes.count();++ if (checkboxCount < 2) {+ test.skip(true, 'Need at least 2 API keys for bulk selection test');+ return;+ }++ await checkboxes.nth(0).check();+ await checkboxes.nth(1).check();++ // Remove Selected button should appear+ const removeSelectedBtn = page.getByRole('button', { name: /Remove Selected/i });+ await expect(removeSelectedBtn).toBeVisible();++ // Click it to open confirmation+ await removeSelectedBtn.click();++ // Should show bulk delete confirmation+ await expect(page.getByText(/Delete.*API Key/i)).toBeVisible();++ // Cancel+ await page.getByRole('button', { name: 'Cancel' }).click();+ });++ test('should display correct status badges for active keys', async ({ page }) => {+ await navigateToApiKeys(page);++ // Check if Active badge is visible+ await expect(page.locator('text="Active"').first()).toBeVisible();+ });++ test('should display "Never" for keys without expiration', async ({ page }) => {+ await navigateToApiKeys(page);++ // Test keys created without expiration should show "Never"+ await expect(page.locator('text="Never"').first()).toBeVisible();+ });+});diff --git a/tests/types/api-key.type.ts b/tests/types/api-key.type.tsnew file mode 100644index 000000000..33795539f--- /dev/null+++ b/tests/types/api-key.type.ts@@ -0,0 +1,11 @@+export type ApiKey = {+ id: string;+ name: string;+ description?: string;+ keyPrefix: string;+ userId: string;+ expiresAt?: string;+ lastUsedAt?: string;+ createdAt: string;+ updatedAt?: string;+};diff --git a/tests/utils/fetch.util.ts b/tests/utils/fetch.util.tsindex c4def99b2..2c1b429d2 100644--- a/tests/utils/fetch.util.ts+++ b/tests/utils/fetch.util.ts@@ -4,6 +4,7 @@ import { ImageUsageCounts } from 'types/image.type';import { NetworkSummary, NetworkUsageCounts } from 'types/networks.type';import { Project, ProjectStatusCounts } from 'types/project.type';import { VolumeUsageCounts } from 'types/volumes.type';+import { ApiKey } from 'types/api-key.type';export type Paginated<T> = { data: T[]; pagination?: { totalItems?: number } };@@ -124,3 +125,14 @@ export async function fetchContainersWithRetry(page: Page, maxRetries = 3): Promreturn { data, pagination };}, maxRetries);}++export async function fetchApiKeysWithRetry(page: Page, maxRetries = 3): Promise<Paginated<ApiKey>> {+ return retry(async () => {+ const res = await page.request.get('/api/api-keys');+ if (!res.ok()) throw new Error(`HTTP ${res.status()}`);+ const body = await res.json().catch(() => null as any);+ const data = Array.isArray(body?.data) ? (body.data as ApiKey[]) : [];+ const pagination = body?.pagination || { totalItems: data.length };+ return { data, pagination };+ }, maxRetries);+}diff --git a/tests/utils/onboarding.util.ts b/tests/utils/onboarding.util.tsindex 66a6fb2d4..3721ff346 100644--- a/tests/utils/onboarding.util.ts+++ b/tests/utils/onboarding.util.ts@@ -11,3 +11,33 @@ export async function skipOnboarding() {throw new Error(`Failed to skip onboarding: ${response.status} ${response.statusText}`);}}++export async function createTestApiKeys(count: number = 2) {+ const url = new URL('/api/playwright/create-test-api-keys', playwrightConfig.use!.baseURL);++ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ count }),+ });++ if (!response.ok) {+ throw new Error(`Failed to create test API keys: ${response.status} ${response.statusText}`);+ }++ return response.json();+}++export async function deleteTestApiKeys() {+ const url = new URL('/api/playwright/delete-test-api-keys', playwrightConfig.use!.baseURL);++ const response = await fetch(url, {+ method: 'POST',+ });++ if (!response.ok) {+ throw new Error(`Failed to delete test API keys: ${response.status} ${response.statusText}`);+ }+}diff --git a/types/apikey/apikey.go b/types/apikey/apikey.gonew file mode 100644index 000000000..4d9e1731d--- /dev/null+++ b/types/apikey/apikey.go@@ -0,0 +1,32 @@+package apikey++import "time"++type Create struct {+ Name string `json:"name" binding:"required"`+ Description *string `json:"description,omitempty"`+ ExpiresAt *time.Time `json:"expiresAt,omitempty"`+}++type ApiKey struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description *string `json:"description,omitempty"`+ KeyPrefix string `json:"keyPrefix"`+ UserID string `json:"userId"`+ ExpiresAt *time.Time `json:"expiresAt,omitempty"`+ LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt *time.Time `json:"updatedAt,omitempty"`+}++type ApiKeyCreatedDto struct {+ ApiKey+ Key string `json:"key"`+}++type Update struct {+ Name *string `json:"name,omitempty"`+ Description *string `json:"description,omitempty"`+ ExpiresAt *time.Time `json:"expiresAt,omitempty"`+}diff --git a/types/base/response.go b/types/base/response.gonew file mode 100644index 000000000..af6f369cc--- /dev/null+++ b/types/base/response.go@@ -0,0 +1,43 @@+package base++// ErrorResponse represents an error response.+//+// @Description Error response with error message+type ErrorResponse struct {+ Error string `json:"error"`+}++// MessageResponse represents a simple message response.+//+// @Description Simple message response+type MessageResponse struct {+ Message string `json:"message"`+}++// PaginationResponse contains pagination metadata.+//+// @Description Pagination metadata+type PaginationResponse struct {+ TotalPages int64 `json:"totalPages"`+ TotalItems int64 `json:"totalItems"`+ CurrentPage int `json:"currentPage"`+ ItemsPerPage int `json:"itemsPerPage"`+ GrandTotalItems int64 `json:"grandTotalItems,omitempty"`+}++// ApiResponse is a generic wrapper for API responses.+//+// @Description Generic API response wrapper+type ApiResponse[T any] struct {+ Success bool `json:"success"`+ Data T `json:"data"`+}++// Paginated is a generic wrapper for paginated responses.+//+// @Description Generic paginated response wrapper+type Paginated[T any] struct {+ Success bool `json:"success"`+ Data []T `json:"data"`+ Pagination PaginationResponse `json:"pagination"`+}