Skip to content

Modern Docker Management, Designed for Everyone

refactor: remote environments with access tokens (#401)

Kyle Mendell5e319ff7ca58
diff --git a/.github/workflows/build-1.0-preview-image.yml b/.github/workflows/build-1.0-preview-image.yml
index 83ae78440..12446b21c 100644
--- a/.github/workflows/build-1.0-preview-image.yml
+++ b/.github/workflows/build-1.0-preview-image.yml
@@ -79,8 +79,8 @@ jobs:
id: build-push
uses: docker/build-push-action@v6
with:
- context: .
- file: Dockerfile-static
+ context: ./
+ file: docker/Dockerfile-static
platforms: linux/amd64,linux/arm64
push: true
tags: |
diff --git a/.github/workflows/build-agent-next.yml b/.github/workflows/build-agent-next.yml
new file mode 100644
index 000000000..6133da9af
--- /dev/null
+++ b/.github/workflows/build-agent-next.yml
@@ -0,0 +1,59 @@
+name: Build Agent Image
+
+on:
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+concurrency:
+ group: build-agent-next
+ cancel-in-progress: true
+
+jobs:
+ build-agent:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ packages: write
+ id-token: write
+ attestations: write
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v5
+
+ - name: Set up QEMU
+ uses: docker/setup-qemu-action@v3
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Set DOCKER_IMAGE_NAME
+ run: |
+ REPO_OWNER=${{ github.repository_owner }}
+ DOCKER_IMAGE_NAME="ghcr.io/${REPO_OWNER,,}/arcane-headless"
+ echo "DOCKER_IMAGE_NAME=${DOCKER_IMAGE_NAME}" >>${GITHUB_ENV}
+
+ - name: Login to GHCR
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.repository_owner }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build and push agent image
+ id: build-push-image
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: docker/Dockerfile-agent
+ platforms: linux/amd64,linux/arm64
+ push: true
+ tags: ${{ env.DOCKER_IMAGE_NAME }}:next
+
+ - name: Attest build provenance
+ uses: actions/attest-build-provenance@v2
+ with:
+ subject-name: '${{ env.DOCKER_IMAGE_NAME }}'
+ subject-digest: ${{ steps.build-push-image.outputs.digest }}
+ push-to-registry: true
diff --git a/.github/workflows/build-next.yml b/.github/workflows/build-next.yml
index a149e4eed..d7eafbb54 100644
--- a/.github/workflows/build-next.yml
+++ b/.github/workflows/build-next.yml
@@ -70,7 +70,7 @@ jobs:
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ env.DOCKER_IMAGE_NAME }}:next
- file: Dockerfile-static
+ file: docker/Dockerfile-static
- name: Container image attestation
uses: actions/attest-build-provenance@v2
with:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 55f2a32b1..fd2a1d399 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -77,7 +77,7 @@ jobs:
uses: docker/build-push-action@v6
with:
context: .
- file: Dockerfile
+ file: docker/Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 64ee97abf..f26caa386 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -8,5 +8,8 @@
},
"typescript.tsdk": "frontend/node_modules/typescript/lib",
"go.buildTags": "playwright",
- "prettier.documentSelectors": ["**/*.svelte"]
+ "prettier.documentSelectors": [
+ "**/*.svelte"
+ ],
+ "kiroAgent.configureMCP": "Disabled"
}
diff --git a/Dockerfile-static b/Dockerfile-static
deleted file mode 100644
index 266d1f38c..000000000
--- a/Dockerfile-static
+++ /dev/null
@@ -1,17 +0,0 @@
-FROM alpine:3
-
-ARG TARGETARCH
-WORKDIR /app
-
-RUN apk upgrade && apk --no-cache add ca-certificates tzdata curl shadow su-exec docker docker-compose
-
-RUN delgroup ping && apk del iputils
-
-COPY ./backend/.bin/arcane-linux-${TARGETARCH} ./arcane
-COPY --chmod=755 scripts/docker/entrypoint.sh /usr/local/bin/entrypoint.sh
-
-EXPOSE 3552
-ENV APP_ENV=production
-
-ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
-CMD ["./arcane"]
\ No newline at end of file
diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.go
index 83186c0a4..f2033d48e 100644
--- a/backend/internal/api/environment_handler.go
+++ b/backend/internal/api/environment_handler.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/gin-gonic/gin"
+ "github.com/ofkm/arcane-backend/internal/config"
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/middleware"
"github.com/ofkm/arcane-backend/internal/models"
@@ -25,11 +26,39 @@ type EnvironmentHandler struct {
networkService *services.NetworkService
volumeService *services.VolumeService
stackService *services.StackService
-}
-
-func NewEnvironmentHandler(group *gin.RouterGroup, environmentService *services.EnvironmentService, containerService *services.ContainerService, imageService *services.ImageService, networkService *services.NetworkService, volumeService *services.VolumeService, stackService *services.StackService, authMiddleware *middleware.AuthMiddleware) {
-
- handler := &EnvironmentHandler{environmentService: environmentService, containerService: containerService, imageService: imageService, networkService: networkService, volumeService: volumeService, stackService: stackService}
+ settingsService *services.SettingsService
+ imageUpdateService *services.ImageUpdateService
+ updaterService *services.UpdaterService
+ cfg *config.Config
+}
+
+func NewEnvironmentHandler(
+ group *gin.RouterGroup,
+ environmentService *services.EnvironmentService,
+ containerService *services.ContainerService,
+ imageService *services.ImageService,
+ imageUpdateService *services.ImageUpdateService,
+ updaterService *services.UpdaterService,
+ networkService *services.NetworkService,
+ volumeService *services.VolumeService,
+ stackService *services.StackService,
+ settingsService *services.SettingsService,
+ authMiddleware *middleware.AuthMiddleware,
+ cfg *config.Config,
+) {
+
+ handler := &EnvironmentHandler{
+ environmentService: environmentService,
+ containerService: containerService,
+ imageService: imageService,
+ imageUpdateService: imageUpdateService,
+ updaterService: updaterService,
+ networkService: networkService,
+ volumeService: volumeService,
+ stackService: stackService,
+ settingsService: settingsService,
+ cfg: cfg,
+ }
apiGroup := group.Group("/environments")
apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
@@ -90,7 +119,52 @@ func NewEnvironmentHandler(group *gin.RouterGroup, environmentService *services.
apiGroup.DELETE("/:id/stacks/:stackId/destroy", handler.DestroyStack)
apiGroup.GET("/:id/stacks/:stackId/logs/stream", handler.GetStackLogsStream)
apiGroup.POST("/:id/stacks/convert", handler.ConvertDockerRun)
+
+ // Image update endpoints
+ apiGroup.GET("/:id/image-updates/check", handler.CheckImageUpdate)
+ apiGroup.GET("/:id/image-updates/check/:imageId", handler.CheckImageUpdateByID)
+ apiGroup.POST("/:id/image-updates/check-batch", handler.CheckMultipleImages)
+ apiGroup.GET("/:id/image-updates/check-all", handler.CheckAllImages)
+ apiGroup.GET("/:id/image-updates/summary", handler.GetUpdateSummary)
+ apiGroup.GET("/:id/image-updates/versions", handler.GetImageVersions)
+ apiGroup.POST("/:id/image-updates/compare", handler.CompareVersions)
+
+ // Updater endpoints
+ apiGroup.POST("/:id/updater/run", handler.UpdaterRun)
+ apiGroup.GET("/:id/updater/status", handler.UpdaterStatus)
+ apiGroup.GET("/:id/updater/history", handler.UpdaterHistory)
+
+ apiGroup.POST("/:id/agent/pair", handler.PairAgent)
+ }
+}
+
+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"}})
+ return
+ }
+ type pairReq struct {
+ Rotate *bool `json:"rotate,omitempty"`
+ }
+ var req pairReq
+ _ = c.ShouldBindJSON(&req)
+
+ if h.cfg.AgentToken == "" || (req.Rotate != nil && *req.Rotate) {
+ h.cfg.AgentToken = utils.GenerateRandomString(48)
+ }
+
+ // Persist token on the agent so it survives restarts
+ if err := h.settingsService.SetStringSetting(c.Request.Context(), "agentToken", h.cfg.AgentToken); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to persist agent token"}})
+ return
}
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "token": h.cfg.AgentToken,
+ },
+ })
}
func (h *EnvironmentHandler) routeRequest(c *gin.Context, endpoint string) {
@@ -111,6 +185,9 @@ func (h *EnvironmentHandler) handleLocalRequest(c *gin.Context, endpoint string)
if h.handleImageEndpoints(c, endpoint) {
return
}
+ if h.handleImageUpdateEndpoints(c, endpoint) {
+ return
+ }
if h.handleNetworkEndpoints(c, endpoint) {
return
}
@@ -120,6 +197,9 @@ func (h *EnvironmentHandler) handleLocalRequest(c *gin.Context, endpoint string)
if h.handleStackEndpoints(c, endpoint) {
return
}
+ if h.handleUpdaterEndpoints(c, endpoint) {
+ return
+ }
c.JSON(http.StatusNotFound, gin.H{
"success": false,
@@ -127,6 +207,94 @@ func (h *EnvironmentHandler) handleLocalRequest(c *gin.Context, endpoint string)
})
}
+func (h *EnvironmentHandler) handleUpdaterEndpoints(c *gin.Context, endpoint string) bool {
+ updaterHandler := &UpdaterHandler{
+ updaterService: h.updaterService,
+ }
+ switch {
+ case endpoint == "/updater/run" && c.Request.Method == http.MethodPost:
+ updaterHandler.Run(c)
+ return true
+ case endpoint == "/updater/status" && c.Request.Method == http.MethodGet:
+ updaterHandler.Status(c)
+ return true
+ case endpoint == "/updater/history" && c.Request.Method == http.MethodGet:
+ updaterHandler.History(c)
+ return true
+ }
+ return false
+}
+
+func (h *EnvironmentHandler) UpdaterRun(c *gin.Context) {
+ h.routeRequest(c, "/updater/run")
+}
+func (h *EnvironmentHandler) UpdaterStatus(c *gin.Context) {
+ h.routeRequest(c, "/updater/status")
+}
+func (h *EnvironmentHandler) UpdaterHistory(c *gin.Context) {
+ h.routeRequest(c, "/updater/history")
+}
+
+func (h *EnvironmentHandler) handleImageUpdateEndpoints(c *gin.Context, endpoint string) bool {
+ imageUpdateHandler := &ImageUpdateHandler{
+ imageUpdateService: h.imageUpdateService,
+ }
+
+ switch {
+ case endpoint == "/image-updates/check" && c.Request.Method == http.MethodGet:
+ imageUpdateHandler.CheckImageUpdate(c)
+ return true
+ case strings.HasPrefix(endpoint, "/image-updates/check/") && c.Request.Method == http.MethodGet:
+ imageUpdateHandler.CheckImageUpdateByID(c)
+ return true
+ case endpoint == "/image-updates/check-batch" && c.Request.Method == http.MethodPost:
+ imageUpdateHandler.CheckMultipleImages(c)
+ return true
+ case endpoint == "/image-updates/check-all" && c.Request.Method == http.MethodGet:
+ imageUpdateHandler.CheckAllImages(c)
+ return true
+ case endpoint == "/image-updates/summary" && c.Request.Method == http.MethodGet:
+ imageUpdateHandler.GetUpdateSummary(c)
+ return true
+ case endpoint == "/image-updates/versions" && c.Request.Method == http.MethodGet:
+ imageUpdateHandler.GetImageVersions(c)
+ return true
+ case endpoint == "/image-updates/compare" && c.Request.Method == http.MethodPost:
+ imageUpdateHandler.CompareVersions(c)
+ return true
+ }
+ return false
+}
+
+func (h *EnvironmentHandler) CheckImageUpdate(c *gin.Context) {
+ h.routeRequest(c, "/image-updates/check")
+}
+
+func (h *EnvironmentHandler) CheckImageUpdateByID(c *gin.Context) {
+ imageID := c.Param("imageId")
+ h.routeRequest(c, "/image-updates/check/"+imageID)
+}
+
+func (h *EnvironmentHandler) CheckMultipleImages(c *gin.Context) {
+ h.routeRequest(c, "/image-updates/check-batch")
+}
+
+func (h *EnvironmentHandler) CheckAllImages(c *gin.Context) {
+ h.routeRequest(c, "/image-updates/check-all")
+}
+
+func (h *EnvironmentHandler) GetUpdateSummary(c *gin.Context) {
+ h.routeRequest(c, "/image-updates/summary")
+}
+
+func (h *EnvironmentHandler) GetImageVersions(c *gin.Context) {
+ h.routeRequest(c, "/image-updates/versions")
+}
+
+func (h *EnvironmentHandler) CompareVersions(c *gin.Context) {
+ h.routeRequest(c, "/image-updates/compare")
+}
+
func (h *EnvironmentHandler) handleContainerEndpoints(c *gin.Context, endpoint string) bool {
containerHandler := &ContainerHandler{
containerService: h.containerService,
@@ -310,109 +478,123 @@ func (h *EnvironmentHandler) handleStackEndpoints(c *gin.Context, endpoint strin
func (h *EnvironmentHandler) handleRemoteRequest(c *gin.Context, environmentID string, endpoint string) {
environment, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), environmentID)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": "Environment not found"},
- })
+ if err != nil || environment == nil {
+ c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found"}})
return
}
-
if !environment.Enabled {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": "Environment is disabled"},
- })
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Environment is disabled"}})
return
}
- client := &http.Client{Timeout: 30 * time.Second}
- url := environment.ApiUrl + "/api" + endpoint
+ target := strings.TrimRight(environment.ApiUrl, "/") +
+ "/api/environments/" + LOCAL_DOCKER_ENVIRONMENT_ID + endpoint
+ if qs := c.Request.URL.RawQuery; qs != "" {
+ target += "?" + qs
+ }
var reqBody io.Reader
if c.Request.Body != nil {
- bodyBytes, err := io.ReadAll(c.Request.Body)
- if err == nil && len(bodyBytes) > 0 {
- reqBody = bytes.NewBuffer(bodyBytes)
- }
+ buf, _ := io.ReadAll(c.Request.Body)
+ // reset original body in case other middlewares need it later
+ c.Request.Body = io.NopCloser(bytes.NewBuffer(buf))
+ reqBody = bytes.NewReader(buf)
}
- req, err := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, url, reqBody)
+ req, err := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, target, reqBody)
if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to create request",
- })
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to create proxy request"}})
return
}
- skipHeaders := map[string]struct{}{
- "Host": {},
- "Content-Length": {},
- "Connection": {},
- }
-
- for key, values := range c.Request.Header {
- upperKey := http.CanonicalHeaderKey(key)
- if _, skip := skipHeaders[upperKey]; skip {
- continue
- }
- if strings.HasPrefix(upperKey, "X-Forwarded-") {
+ // Copy headers except hop-by-hop and Authorization (we’ll set explicitly)
+ skip := map[string]struct{}{
+ "Host": {},
+ "Connection": {},
+ "Keep-Alive": {},
+ "Proxy-Authenticate": {},
+ "Proxy-Authorization": {},
+ "Te": {},
+ "Trailer": {},
+ "Transfer-Encoding": {},
+ "Upgrade": {},
+ "Content-Length": {},
+ "Origin": {},
+ "Referer": {},
+ "Access-Control-Request-Method": {},
+ "Access-Control-Request-Headers": {},
+ "Cookie": {},
+ }
+ for k, vs := range c.Request.Header {
+ ck := http.CanonicalHeaderKey(k)
+ if _, ok := skip[ck]; ok || ck == "Authorization" {
continue
}
- if upperKey == "Authorization" {
- if auth := c.GetHeader("Authorization"); auth != "" {
- req.Header.Set("Authorization", auth)
- }
- continue
- }
- for _, value := range values {
- req.Header.Add(key, value)
+ for _, v := range vs {
+ req.Header.Add(k, v)
}
}
- req.Header.Set("X-Forwarded-For", c.ClientIP())
- req.Header.Set("X-Forwarded-Host", c.Request.Host)
- req.Header.Set("X-Forwarded-Proto", c.Request.URL.Scheme)
+ // Forward Authorization (or promote cookie)
+ if auth := c.GetHeader("Authorization"); auth != "" {
+ req.Header.Set("Authorization", auth)
+ } else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {
+ req.Header.Set("Authorization", "Bearer "+cookieToken)
+ }
- q := req.URL.Query()
- for key, values := range c.Request.URL.Query() {
- for _, value := range values {
- q.Add(key, value)
- }
+ // Forward agent token if stored
+ if environment.AccessToken != nil && *environment.AccessToken != "" {
+ req.Header.Set("X-Arcane-Agent-Token", *environment.AccessToken)
}
- req.URL.RawQuery = q.Encode()
+ req.Header.Set("X-Forwarded-For", c.ClientIP())
+ req.Header.Set("X-Forwarded-Host", c.Request.Host)
+
+ client := &http.Client{Timeout: 60 * time.Second}
resp, err := client.Do(req)
if err != nil {
- _ = h.environmentService.UpdateEnvironmentStatus(c.Request.Context(), environmentID, "offline")
- c.JSON(http.StatusServiceUnavailable, gin.H{
- "success": false,
- "error": fmt.Sprintf("Failed to connect to environment: %v", err),
- })
+ c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": fmt.Sprintf("Proxy request failed: %v", err)}})
return
}
defer resp.Body.Close()
- _ = h.environmentService.UpdateEnvironmentHeartbeat(c.Request.Context(), environmentID)
-
- responseBody, err := io.ReadAll(resp.Body)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to read response",
- })
- return
+ // Skip hop-by-hop headers and any named in the Connection header (RFC 7230)
+ hop := map[string]struct{}{
+ http.CanonicalHeaderKey("Connection"): {},
+ http.CanonicalHeaderKey("Keep-Alive"): {},
+ http.CanonicalHeaderKey("Proxy-Authenticate"): {},
+ http.CanonicalHeaderKey("Proxy-Authorization"): {},
+ http.CanonicalHeaderKey("TE"): {},
+ http.CanonicalHeaderKey("Trailers"): {},
+ http.CanonicalHeaderKey("Trailer"): {},
+ http.CanonicalHeaderKey("Transfer-Encoding"): {},
+ http.CanonicalHeaderKey("Upgrade"): {},
+ }
+
+ for _, connVal := range resp.Header.Values("Connection") {
+ for _, token := range strings.Split(connVal, ",") {
+ if t := strings.TrimSpace(token); t != "" {
+ hop[http.CanonicalHeaderKey(t)] = struct{}{}
+ }
+ }
}
- for key, values := range resp.Header {
- for _, value := range values {
- c.Header(key, value)
+ // Copy response headers except hop-by-hop
+ for k, vs := range resp.Header {
+ ck := http.CanonicalHeaderKey(k)
+ if _, ok := hop[ck]; ok {
+ continue
+ }
+ for _, v := range vs {
+ c.Writer.Header().Add(k, v)
}
}
c.Status(resp.StatusCode)
- _, _ = c.Writer.Write(responseBody)
+
+ if c.Request.Method != http.MethodHead {
+ _, _ = io.Copy(c.Writer, resp.Body)
+ }
}
// Create
@@ -423,35 +605,44 @@ func (h *EnvironmentHandler) CreateEnvironment(c *gin.Context) {
return
}
- environment := &models.Environment{
- Hostname: req.Hostname,
- ApiUrl: req.ApiUrl,
- Description: req.Description,
- Enabled: true,
+ env := &models.Environment{
+ ApiUrl: req.ApiUrl,
+ Enabled: true,
+ }
+ if req.Name != nil {
+ env.Name = *req.Name
}
if req.Enabled != nil {
- environment.Enabled = *req.Enabled
+ env.Enabled = *req.Enabled
}
- createdEnvironment, err := h.environmentService.CreateEnvironment(c.Request.Context(), environment)
+ // Auto-pair with agent if bootstrap token is provided
+ if (req.AccessToken == nil || *req.AccessToken == "") && req.BootstrapToken != nil && *req.BootstrapToken != "" {
+ if token, err := h.environmentService.PairAgentWithBootstrap(c.Request.Context(), req.ApiUrl, *req.BootstrapToken); err == nil && token != "" {
+ env.AccessToken = &token
+ } else if err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": "Agent pairing failed: " + err.Error()}})
+ return
+ }
+ } else if req.AccessToken != nil && *req.AccessToken != "" {
+ env.AccessToken = req.AccessToken
+ }
+
+ created, err := h.environmentService.CreateEnvironment(c.Request.Context(), env)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to create environment: " + err.Error()}})
return
}
- out, mapErr := dto.MapOne[*models.Environment, dto.EnvironmentDto](createdEnvironment)
+ out, mapErr := dto.MapOne[*models.Environment, dto.EnvironmentDto](created)
if mapErr != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to map environment"}})
return
}
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": out,
- })
+ c.JSON(http.StatusCreated, gin.H{"success": true, "data": out})
}
-// List (paginated)
func (h *EnvironmentHandler) ListEnvironments(c *gin.Context) {
var req utils.SortedPaginationRequest
if err := c.ShouldBindQuery(&req); err != nil {
@@ -506,45 +697,54 @@ func (h *EnvironmentHandler) UpdateEnvironment(c *gin.Context) {
var req dto.UpdateEnvironmentDto
if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Invalid request format: " + err.Error()}})
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Invalid request body"}})
return
}
- updates := make(map[string]interface{})
- if req.Hostname != nil {
- updates["hostname"] = *req.Hostname
- }
+ updates := map[string]interface{}{}
if req.ApiUrl != nil {
updates["api_url"] = *req.ApiUrl
}
- if req.Description != nil {
- updates["description"] = *req.Description
+ if req.Name != nil {
+ updates["name"] = *req.Name
}
if req.Enabled != nil {
updates["enabled"] = *req.Enabled
}
- if len(updates) == 0 {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "No fields to update"}})
- return
+ // If caller asked to pair (bootstrapToken present) and no accessToken provided in the request,
+ // resolve apiUrl (current or updated) and let the service pair and persist the token.
+ if (req.AccessToken == nil) && req.BootstrapToken != nil && *req.BootstrapToken != "" {
+ current, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), environmentID)
+ if err != nil || current == nil {
+ c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found"}})
+ return
+ }
+ apiUrl := current.ApiUrl
+ if req.ApiUrl != nil && *req.ApiUrl != "" {
+ apiUrl = *req.ApiUrl
+ }
+ if _, err := h.environmentService.PairAndPersistAgentToken(c.Request.Context(), environmentID, apiUrl, *req.BootstrapToken); err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": "Agent pairing failed: " + err.Error()}})
+ return
+ }
+ } else if req.AccessToken != nil {
+ updates["access_token"] = *req.AccessToken
}
- updatedEnvironment, err := h.environmentService.UpdateEnvironment(c.Request.Context(), environmentID, updates)
+ updated, err := h.environmentService.UpdateEnvironment(c.Request.Context(), environmentID, updates)
if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to update environment: " + err.Error()}})
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to update environment"}})
return
}
- out, mapErr := dto.MapOne[*models.Environment, dto.EnvironmentDto](updatedEnvironment)
+ out, mapErr := dto.MapOne[*models.Environment, dto.EnvironmentDto](updated)
if mapErr != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to map environment"}})
return
}
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
}
// Delete
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 396fd7ded..622211bf0 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -34,7 +34,7 @@ func InitializeApp() (*App, error) {
ctx := context.Background()
loadErr := godotenv.Load()
cfg := config.Load()
- utils.InitEncryption(cfg)
+
SetupLogger(cfg)
ConfigureGormLogger(cfg)
@@ -57,6 +57,24 @@ func InitializeApp() (*App, error) {
return nil, fmt.Errorf("services initialization failed: %w", err)
}
+ if cfg.AgentMode && cfg.AgentToken == "" {
+ if tok := appServices.Settings.GetStringSetting(appCtx, "agentToken", ""); tok != "" {
+ cfg.AgentToken = tok
+ slog.InfoContext(appCtx, "Loaded agent token from database")
+ }
+ }
+
+ if cfg.AgentMode || cfg.Environment != "production" {
+ if key, err := appServices.Settings.EnsureEncryptionKey(appCtx); err != nil {
+ slog.WarnContext(appCtx, "Failed to ensure encryption key; falling back to derived behavior",
+ slog.String("error", err.Error()))
+ } else {
+ cfg.EncryptionKey = key
+ }
+ }
+ utils.InitEncryption(cfg)
+
+ // Ensure default settings but skip user bootstrap in agent mode
slog.InfoContext(appCtx, "Ensuring default settings are initialized")
if err := appServices.Settings.EnsureDefaultSettings(appCtx); err != nil {
slog.WarnContext(appCtx, "Failed to initialize default settings",
@@ -89,16 +107,18 @@ func InitializeApp() (*App, error) {
slog.InfoContext(appCtx, "Initial Docker image synchronization complete")
}
- if err := appServices.User.CreateDefaultAdmin(); err != nil {
- slog.WarnContext(appCtx, "Failed to create default admin user",
- slog.String("error", err.Error()))
- }
-
- if cfg.OidcEnabled {
- if _, err := appServices.Settings.SyncOidcEnvToDatabase(appCtx); err != nil {
- slog.WarnContext(appCtx, "Failed to sync OIDC environment variables to database",
+ if !cfg.AgentMode {
+ if err := appServices.User.CreateDefaultAdmin(); err != nil {
+ slog.WarnContext(appCtx, "Failed to create default admin user",
slog.String("error", err.Error()))
}
+
+ if cfg.OidcEnabled {
+ if _, err := appServices.Settings.SyncOidcEnvToDatabase(appCtx); err != nil {
+ slog.WarnContext(appCtx, "Failed to sync OIDC environment variables to database",
+ slog.String("error", err.Error()))
+ }
+ }
}
return &App{
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index cbaa9860d..7cb8f5e94 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -58,19 +58,27 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {
},
}))
- authMiddleware := middleware.NewAuthMiddleware(appServices.Auth)
- router.Use(middleware.SetupCORS(cfg))
+ authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg)
+ corsMiddleware := middleware.NewCORSMiddleware(cfg).Add()
+ router.Use(corsMiddleware)
+ // TODO :- Refactor to a api endpoint
router.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "UP"})
})
apiGroup := router.Group("/api")
+
+ if cfg.AgentMode {
+ api.NewEnvironmentHandler(apiGroup, appServices.Environment, appServices.Container, appServices.Image, appServices.ImageUpdate, appServices.Updater, appServices.Network, appServices.Volume, appServices.Stack, appServices.Settings, authMiddleware, cfg)
+ return router
+ }
+
api.NewAuthHandler(apiGroup, appServices.User, appServices.Auth, appServices.Oidc, authMiddleware)
api.NewContainerHandler(apiGroup, appServices.Container, appServices.Image, authMiddleware)
api.NewContainerRegistryHandler(apiGroup, appServices.ContainerRegistry, authMiddleware)
api.NewConverterHandler(apiGroup, appServices.Converter, authMiddleware)
- api.NewEnvironmentHandler(apiGroup, appServices.Environment, appServices.Container, appServices.Image, appServices.Network, appServices.Volume, appServices.Stack, authMiddleware)
+ api.NewEnvironmentHandler(apiGroup, appServices.Environment, appServices.Container, appServices.Image, appServices.ImageUpdate, appServices.Updater, appServices.Network, appServices.Volume, appServices.Stack, appServices.Settings, authMiddleware, cfg)
api.NewEventHandler(apiGroup, appServices.Event, authMiddleware)
api.NewImageHandler(apiGroup, appServices.Image, appServices.ImageUpdate, authMiddleware)
api.NewImageUpdateHandler(apiGroup, appServices.ImageUpdate, authMiddleware)
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index c87a57af8..4af50ef1e 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -26,8 +26,11 @@ type Config struct {
OidcAdminClaim string
OidcAdminValue string
- LogJson bool
- LogLevel string
+ LogJson bool
+ LogLevel string
+ AgentMode bool
+ AgentToken string
+ AgentBootstrapToken string
}
func Load() *Config {
@@ -47,8 +50,11 @@ func Load() *Config {
OidcAdminClaim: getEnvOrDefault("OIDC_ADMIN_CLAIM", ""),
OidcAdminValue: getEnvOrDefault("OIDC_ADMIN_VALUE", ""),
- LogJson: getBoolEnvOrDefault("LOG_JSON", false),
- LogLevel: strings.ToLower(getEnvOrDefault("LOG_LEVEL", "info")),
+ LogJson: getBoolEnvOrDefault("LOG_JSON", false),
+ LogLevel: strings.ToLower(getEnvOrDefault("LOG_LEVEL", "info")),
+ AgentMode: getBoolEnvOrDefault("AGENT_MODE", false),
+ AgentToken: os.Getenv("AGENT_TOKEN"),
+ AgentBootstrapToken: os.Getenv("AGENT_BOOTSTRAP_TOKEN"),
}
}
diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go
index 594b2d201..8a2c67f11 100644
--- a/backend/internal/database/database.go
+++ b/backend/internal/database/database.go
@@ -5,6 +5,8 @@ import (
"fmt"
"log/slog"
"net/url"
+ "os"
+ "path/filepath"
"strings"
"time"
@@ -93,6 +95,9 @@ func connectDatabase(databaseURL string, environment string) (*DB, error) {
if err != nil {
return nil, fmt.Errorf("failed to parse SQLite connection string: %w", err)
}
+ if err := ensureSQLiteDirectory(connString); err != nil {
+ return nil, fmt.Errorf("failed to prepare SQLite directory: %w", err)
+ }
dialector = glsqlite.Open(connString)
case strings.HasPrefix(databaseURL, "postgres"):
dialector = postgres.Open(databaseURL)
@@ -197,3 +202,31 @@ func (db *DB) Close() error {
}
return sqlDB.Close()
}
+
+// Create parent directory for file-based SQLite if needed
+func ensureSQLiteDirectory(connString string) error {
+ if !strings.HasPrefix(connString, "file:") {
+ return nil
+ }
+ u, err := url.Parse(connString)
+ if err != nil {
+ return fmt.Errorf("failed to parse SQLite DSN: %w", err)
+ }
+
+ // For "file:data/arcane.db?...", path is in Opaque; for "file:/abs/path.db", it's in Path
+ pathPart := u.Opaque
+ if pathPart == "" {
+ pathPart = u.Path
+ }
+ // Trim leading slash to handle file:/relative.db
+ pathPart = strings.TrimPrefix(pathPart, "/")
+ if pathPart == "" || strings.HasPrefix(pathPart, ":memory:") {
+ return nil
+ }
+
+ dir := filepath.Dir(pathPart)
+ if dir == "" || dir == "." {
+ return nil
+ }
+ return os.MkdirAll(dir, 0o755)
+}
diff --git a/backend/internal/dto/environment_dto.go b/backend/internal/dto/environment_dto.go
index dcc813f6b..8e9b3ca6c 100644
--- a/backend/internal/dto/environment_dto.go
+++ b/backend/internal/dto/environment_dto.go
@@ -1,17 +1,19 @@
package dto
type CreateEnvironmentDto struct {
- Hostname string `json:"hostname" binding:"required"`
- ApiUrl string `json:"apiUrl" binding:"required,url"`
- Description *string `json:"description"`
- Enabled *bool `json:"enabled"`
+ ApiUrl string `json:"apiUrl" binding:"required,url"`
+ Name *string `json:"name,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+ AccessToken *string `json:"accessToken,omitempty"`
+ BootstrapToken *string `json:"bootstrapToken,omitempty"`
}
type UpdateEnvironmentDto struct {
- Hostname *string `json:"hostname"`
- ApiUrl *string `json:"apiUrl"`
- Description *string `json:"description"`
- Enabled *bool `json:"enabled"`
+ ApiUrl *string `json:"apiUrl,omitempty" binding:"omitempty,url"`
+ Name *string `json:"name,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+ AccessToken *string `json:"accessToken,omitempty"`
+ BootstrapToken *string `json:"bootstrapToken,omitempty"`
}
type TestConnectionDto struct {
@@ -20,13 +22,11 @@ type TestConnectionDto struct {
}
type EnvironmentDto struct {
- ID string `json:"id"`
- Hostname string `json:"hostname"`
- ApiUrl string `json:"apiUrl"`
- Description *string `json:"description,omitempty"`
- Status string `json:"status"`
- Enabled bool `json:"enabled"`
- LastSeen *string `json:"lastSeen,omitempty"`
- CreatedAt string `json:"createdAt"`
- UpdatedAt *string `json:"updatedAt,omitempty"`
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ ApiUrl string `json:"apiUrl"`
+ Status string `json:"status"`
+ Enabled bool `json:"enabled"`
+ CreatedAt string `json:"createdAt"`
+ UpdatedAt *string `json:"updatedAt,omitempty"`
}
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index 4dbdf1775..91b94ce56 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -1,10 +1,12 @@
package middleware
import (
+ "log/slog"
"net/http"
"strings"
"github.com/gin-gonic/gin"
+ "github.com/ofkm/arcane-backend/internal/config"
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/services"
)
@@ -16,16 +18,15 @@ type AuthOptions struct {
type AuthMiddleware struct {
authService *services.AuthService
+ cfg *config.Config
options AuthOptions
}
-func NewAuthMiddleware(authService *services.AuthService) *AuthMiddleware {
+func NewAuthMiddleware(authService *services.AuthService, cfg *config.Config) *AuthMiddleware {
return &AuthMiddleware{
authService: authService,
- options: AuthOptions{
- AdminRequired: false,
- SuccessOptional: false,
- },
+ cfg: cfg,
+ options: AuthOptions{},
}
}
@@ -34,13 +35,11 @@ func (m *AuthMiddleware) WithAdminRequired() *AuthMiddleware {
clone.options.AdminRequired = true
return &clone
}
-
func (m *AuthMiddleware) WithAdminNotRequired() *AuthMiddleware {
clone := *m
clone.options.AdminRequired = false
return &clone
}
-
func (m *AuthMiddleware) WithSuccessOptional() *AuthMiddleware {
clone := *m
clone.options.SuccessOptional = true
@@ -49,6 +48,45 @@ func (m *AuthMiddleware) WithSuccessOptional() *AuthMiddleware {
func (m *AuthMiddleware) Add() gin.HandlerFunc {
return func(c *gin.Context) {
+ if m.cfg != nil && m.cfg.AgentMode {
+ // Allow OPTIONS preflight to pass through in agent mode
+ if c.Request.Method == http.MethodOptions {
+ c.Next()
+ return
+ }
+
+ // Allow pairing with bootstrap token
+ if strings.HasPrefix(c.Request.URL.Path, "/api/environments/0/agent/pair") &&
+ m.cfg.AgentBootstrapToken != "" &&
+ c.GetHeader("X-Arcane-Agent-Bootstrap") == m.cfg.AgentBootstrapToken {
+ slog.Info("Agent auth: bootstrap pairing accepted", "path", c.Request.URL.Path, "method", c.Request.Method)
+ agentSudo(c)
+ return
+ }
+
+ // Require X-Arcane-Agent-Token
+ if tok := c.GetHeader("X-Arcane-Agent-Token"); tok != "" && m.cfg.AgentToken != "" && tok == m.cfg.AgentToken {
+ slog.Info("Agent auth: agent token accepted", "path", c.Request.URL.Path, "method", c.Request.Method)
+ agentSudo(c)
+ return
+ }
+
+ slog.Warn("Agent auth forbidden",
+ "path", c.Request.URL.Path,
+ "method", c.Request.Method,
+ "has_agent_token_hdr", c.GetHeader("X-Arcane-Agent-Token") != "",
+ "agent_token_config_set", m.cfg.AgentToken != "",
+ "has_bearer", c.GetHeader("Authorization") != "")
+
+ c.JSON(http.StatusForbidden, models.APIError{
+ Code: "FORBIDDEN",
+ Message: "Invalid or missing agent token",
+ })
+ c.Abort()
+ return
+ }
+
+ // Manager (normal) JWT mode
token := extractBearerOrCookieToken(c)
if token == "" {
if m.options.SuccessOptional {
@@ -79,10 +117,6 @@ func (m *AuthMiddleware) Add() gin.HandlerFunc {
isAdmin := userHasRole(user, "admin")
if m.options.AdminRequired && !isAdmin {
- if m.options.SuccessOptional {
- c.Next()
- return
- }
c.JSON(http.StatusForbidden, models.APIError{
Code: "FORBIDDEN",
Message: "You don't have permission to access this resource",
@@ -90,7 +124,6 @@ func (m *AuthMiddleware) Add() gin.HandlerFunc {
c.Abort()
return
}
-
c.Set("userID", user.ID)
c.Set("currentUser", user)
c.Set("userIsAdmin", isAdmin)
@@ -98,9 +131,22 @@ func (m *AuthMiddleware) Add() gin.HandlerFunc {
}
}
+func agentSudo(c *gin.Context) {
+ email := "[email protected]"
+ agentUser := &models.User{
+ BaseModel: models.BaseModel{ID: "agent"},
+ Email: &email,
+ Roles: []string{"admin"},
+ }
+ c.Set("userID", agentUser.ID)
+ c.Set("currentUser", agentUser)
+ c.Set("userIsAdmin", true)
+ c.Next()
+}
+
func extractBearerOrCookieToken(c *gin.Context) string {
authHeader := c.GetHeader("Authorization")
- if authHeader != "" && strings.HasPrefix(authHeader, "Bearer ") {
+ if strings.HasPrefix(authHeader, "Bearer ") {
return strings.TrimPrefix(authHeader, "Bearer ")
}
if tokenCookie, err := c.Cookie("token"); err == nil && tokenCookie != "" {
diff --git a/backend/internal/middleware/cors_middleware.go b/backend/internal/middleware/cors_middleware.go
index 787d179c4..dba2b137c 100644
--- a/backend/internal/middleware/cors_middleware.go
+++ b/backend/internal/middleware/cors_middleware.go
@@ -9,148 +9,96 @@ import (
"github.com/ofkm/arcane-backend/internal/config"
)
-func SetupCORS(cfg *config.Config) gin.HandlerFunc {
- corsConfig := cors.DefaultConfig()
-
- allowedOrigins := []string{}
-
- if cfg.AppUrl != "" {
- if parsedURL, err := url.Parse(cfg.AppUrl); err == nil {
- origin := parsedURL.Scheme + "://" + parsedURL.Host
- allowedOrigins = append(allowedOrigins, origin)
- }
- }
+type CORSMiddleware struct {
+ cfg *config.Config
+ customOrigins []string
+}
- if cfg.Environment != "production" {
- devOrigins := []string{
- "http://localhost:3000",
- "http://localhost:3552",
- }
- allowedOrigins = append(allowedOrigins, devOrigins...)
- }
+func NewCORSMiddleware(cfg *config.Config) *CORSMiddleware {
+ return &CORSMiddleware{cfg: cfg}
+}
- if len(allowedOrigins) == 0 {
- if cfg.Environment == "production" {
- slog.Warn("CORS: No origins specified for production - this may cause issues")
- allowedOrigins = []string{"https://localhost"}
- } else {
- allowedOrigins = []string{"*"}
- }
- }
+func (m *CORSMiddleware) WithOrigins(origins []string) *CORSMiddleware {
+ clone := *m
+ clone.customOrigins = append([]string(nil), origins...)
+ return &clone
+}
- corsConfig.AllowOrigins = allowedOrigins
- corsConfig.AllowCredentials = true
- corsConfig.AllowMethods = []string{
- "GET",
- "POST",
- "PUT",
- "DELETE",
- "OPTIONS",
- "PATCH",
- "HEAD",
- }
- corsConfig.AllowHeaders = []string{
+func (m *CORSMiddleware) Add() gin.HandlerFunc {
+ conf := cors.DefaultConfig()
+ conf.AllowOrigins = deriveAllowedOrigins(m.cfg, m.customOrigins)
+ conf.AllowCredentials = true
+ conf.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"}
+ conf.AllowHeaders = []string{
"Authorization",
"Content-Type",
"X-CSRF-Token",
- "Origin",
+ "X-Requested-With",
"Accept",
+ "Accept-Language",
+ "Accept-Encoding",
"User-Agent",
"Cache-Control",
- "X-Requested-With",
- "Accept-Encoding",
- "Accept-Language",
- "Connection",
- "Host",
+ "Origin",
"Referer",
+ "X-Arcane-Agent-Token",
}
- corsConfig.ExposeHeaders = []string{
+ conf.ExposeHeaders = []string{
"Content-Length",
"Content-Type",
"X-Total-Count",
"X-Page",
"X-Per-Page",
}
- corsConfig.MaxAge = 300
+ conf.MaxAge = 300
- return cors.New(corsConfig)
+ return cors.New(conf)
}
-func SetupCORSWithCustomOrigins(cfg *config.Config, customOrigins []string) gin.HandlerFunc {
- corsConfig := cors.DefaultConfig()
-
- if len(customOrigins) > 0 {
- corsConfig.AllowOrigins = customOrigins
- } else {
- return SetupCORS(cfg)
+func deriveAllowedOrigins(cfg *config.Config, custom []string) []string {
+ if len(custom) > 0 {
+ return dedupe(custom)
}
- corsConfig.AllowCredentials = true
- corsConfig.AllowMethods = []string{
- "GET",
- "POST",
- "PUT",
- "DELETE",
- "OPTIONS",
- "PATCH",
- "HEAD",
- }
- corsConfig.AllowHeaders = []string{
- "Authorization",
- "Content-Type",
- "X-CSRF-Token",
- "Origin",
- "Accept",
- "User-Agent",
- "Cache-Control",
- "X-Requested-With",
- "Accept-Encoding",
- "Accept-Language",
- "Connection",
- "Host",
- "Referer",
- }
- corsConfig.ExposeHeaders = []string{
- "Content-Length",
- "Content-Type",
- "X-Total-Count",
- "X-Page",
- "X-Per-Page",
+ var origins []string
+ // App URL if set
+ if cfg != nil && cfg.AppUrl != "" {
+ if u, err := url.Parse(cfg.AppUrl); err == nil {
+ origins = append(origins, u.Scheme+"://"+u.Host)
+ }
}
- corsConfig.MaxAge = 300
- return cors.New(corsConfig)
-}
+ // Dev defaults
+ if cfg == nil || cfg.Environment != "production" {
+ origins = append(origins,
+ "http://localhost:3000", "http://127.0.0.1:3000",
+ "http://localhost:3552", "http://127.0.0.1:3552",
+ )
+ }
-func GetAllowedOrigins(cfg *config.Config) []string {
- allowedOrigins := []string{}
+ origins = dedupe(origins)
- if cfg.AppUrl != "" {
- if parsedURL, err := url.Parse(cfg.AppUrl); err == nil {
- origin := parsedURL.Scheme + "://" + parsedURL.Host
- allowedOrigins = append(allowedOrigins, origin)
+ if len(origins) == 0 {
+ if cfg != nil && cfg.Environment == "production" {
+ slog.Warn("CORS: No origins specified for production - defaulting to https://localhost")
+ return []string{"https://localhost"}
}
+ // Fallback in dev (avoid "*" with credentials=true)
+ return []string{"http://localhost:3000"}
}
- if cfg.Environment != "production" {
- devOrigins := []string{
- "http://localhost:5173",
- "http://127.0.0.1:5173",
- "http://localhost:3000",
- "http://127.0.0.1:3000",
- "http://localhost:4173",
- "http://127.0.0.1:4173",
- }
- allowedOrigins = append(allowedOrigins, devOrigins...)
- }
+ return origins
+}
- if len(allowedOrigins) == 0 {
- if cfg.Environment == "production" {
- allowedOrigins = []string{"https://localhost"}
- } else {
- allowedOrigins = []string{"*"}
+func dedupe(in []string) []string {
+ seen := make(map[string]struct{}, len(in))
+ out := make([]string, 0, len(in))
+ for _, v := range in {
+ if _, ok := seen[v]; ok {
+ continue
}
+ seen[v] = struct{}{}
+ out = append(out, v)
}
-
- return allowedOrigins
+ return out
}
diff --git a/backend/internal/models/environment.go b/backend/internal/models/environment.go
index e4f72ce92..a1c4de0c4 100644
--- a/backend/internal/models/environment.go
+++ b/backend/internal/models/environment.go
@@ -1,25 +1,20 @@
package models
-import (
- "time"
-)
+import "time"
type Environment struct {
- ID string `json:"id" gorm:"primaryKey"`
- Hostname string `json:"hostname" gorm:"not null" sortable:"true"`
+ Name string `json:"name" sortable:"true"`
ApiUrl string `json:"apiUrl" gorm:"column:api_url;not null" sortable:"true"`
- Description *string `json:"description" sortable:"true"`
Status string `json:"status" gorm:"default:offline" sortable:"true"`
Enabled bool `json:"enabled" gorm:"default:true" sortable:"true"`
- LastSeen *time.Time `json:"lastSeen" gorm:"column:last_seen" sortable:"true"`
- CreatedAt time.Time `json:"createdAt" gorm:"column:created_at" sortable:"true"`
- UpdatedAt *time.Time `json:"updatedAt" gorm:"column:updated_at" sortable:"true"`
-}
+ LastSeen *time.Time `json:"lastSeen" gorm:"column:last_seen"`
+ AccessToken *string `json:"-" gorm:"column:access_token"`
-func (Environment) TableName() string {
- return "environments"
+ BaseModel
}
+func (Environment) TableName() string { return "environments" }
+
type EnvironmentStatus string
const (
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index ba6609949..f86350120 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -2,9 +2,12 @@ package services
import (
"context"
+ "encoding/json"
"errors"
"fmt"
+ "io"
"net/http"
+ "strings"
"time"
"github.com/google/uuid"
@@ -62,11 +65,7 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, req
if req.Search != "" {
like := "%" + req.Search + "%"
- q = q.Where(
- s.db.Or("hostname ILIKE ?", like).
- Or("api_url ILIKE ?", like).
- Or("description ILIKE ?", like),
- )
+ q = q.Where("api_url ILIKE ?", like)
}
if req.Filters != nil {
@@ -218,3 +217,53 @@ func (s *EnvironmentService) IsEnvironmentOnline(environment *models.Environment
timeoutDuration := time.Duration(timeoutMinutes) * time.Minute
return time.Since(*environment.LastSeen) < timeoutDuration
}
+
+func (s *EnvironmentService) PairAgentWithBootstrap(ctx context.Context, apiUrl, bootstrapToken string) (string, error) {
+ client := &http.Client{Timeout: 10 * time.Second}
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(apiUrl, "/")+"/api/environments/0/agent/pair", nil)
+ if err != nil {
+ return "", fmt.Errorf("create request: %w", err)
+ }
+ req.Header.Set("X-Arcane-Agent-Bootstrap", bootstrapToken)
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return "", fmt.Errorf("unexpected status %d: %s", resp.StatusCode, string(body))
+ }
+
+ var parsed struct {
+ Success bool `json:"success"`
+ Data struct {
+ Token string `json:"token"`
+ } `json:"data"`
+ Message string `json:"message"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {
+ return "", fmt.Errorf("decode response: %w", err)
+ }
+ if !parsed.Success || parsed.Data.Token == "" {
+ return "", fmt.Errorf("pairing unsuccessful")
+ }
+
+ return parsed.Data.Token, nil
+}
+
+func (s *EnvironmentService) PairAndPersistAgentToken(ctx context.Context, environmentID, apiUrl, bootstrapToken string) (string, error) {
+ token, err := s.PairAgentWithBootstrap(ctx, apiUrl, bootstrapToken)
+ if err != nil {
+ return "", err
+ }
+ if err := s.db.WithContext(ctx).
+ Model(&models.Environment{}).
+ Where("id = ?", environmentID).
+ Update("access_token", token).Error; err != nil {
+ return "", fmt.Errorf("failed to persist agent token: %w", err)
+ }
+ return token, nil
+}
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 796b2aa05..a98cf3d99 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -2,12 +2,15 @@ package services
import (
"context"
+ "crypto/sha256"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
+ "github.com/google/uuid"
"gorm.io/gorm"
"github.com/ofkm/arcane-backend/internal/config"
@@ -327,3 +330,42 @@ func (s *SettingsService) SetIntSetting(ctx context.Context, key string, value i
func (s *SettingsService) SetStringSetting(ctx context.Context, key, value string) error {
return s.UpdateSetting(ctx, key, value)
}
+
+func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, error) {
+ const keyName = "encryptionKey"
+
+ var sv models.SettingVariable
+ err := s.db.WithContext(ctx).
+ Where("key = ?", keyName).
+ First(&sv).Error
+
+ if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return "", fmt.Errorf("failed to load encryption key: %w", err)
+ }
+
+ if sv.Value != "" {
+ return sv.Value, nil
+ }
+
+ // Generate uuid -> sha256 -> base64 key (32 bytes)
+ u := uuid.New().String()
+ sum := sha256.Sum256([]byte(u))
+ key := base64.StdEncoding.EncodeToString(sum[:])
+
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ if createErr := s.db.WithContext(ctx).
+ Create(&models.SettingVariable{Key: keyName, Value: key}).Error; createErr != nil {
+ return "", fmt.Errorf("failed to persist encryption key: %w", createErr)
+ }
+ return key, nil
+ }
+
+ if updErr := s.db.WithContext(ctx).
+ Model(&models.SettingVariable{}).
+ Where("key = ?", keyName).
+ Update("value", key).Error; updErr != nil {
+ return "", fmt.Errorf("failed to update encryption key: %w", updErr)
+ }
+
+ return key, nil
+}
diff --git a/backend/internal/utils/encryption.go b/backend/internal/utils/encryption.go
index 83f937333..29f75c19b 100644
--- a/backend/internal/utils/encryption.go
+++ b/backend/internal/utils/encryption.go
@@ -3,13 +3,15 @@ package utils
import (
"crypto/aes"
"crypto/cipher"
- "crypto/rand"
+ crand "crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"log/slog"
+ "os"
+ "path/filepath"
"strings"
"github.com/ofkm/arcane-backend/internal/config"
@@ -20,37 +22,130 @@ var encryptionKey []byte
func InitEncryption(cfg *config.Config) {
keyString := strings.TrimSpace(cfg.EncryptionKey)
- if keyString == "" {
- if cfg.Environment == "production" {
- panic("ENCRYPTION_KEY is required in production environment")
+ // If an explicit key was provided, try to accept it (raw/base64/hex)
+ if keyString != "" {
+ clean := strings.TrimSpace(keyString)
+
+ if len(clean) == 32 {
+ encryptionKey = []byte(clean)
+ } else {
+ if b, err := base64.StdEncoding.DecodeString(clean); err == nil && len(b) == 32 {
+ encryptionKey = b
+ } else if b, err := base64.RawStdEncoding.DecodeString(clean); err == nil && len(b) == 32 {
+ encryptionKey = b
+ } else if b, err := hex.DecodeString(clean); err == nil && len(b) == 32 {
+ encryptionKey = b
+ } else {
+ panic(fmt.Sprintf("ENCRYPTION_KEY must be 32 bytes (raw/base64/hex). Provided=%d chars", len(clean)))
+ }
}
- slog.Warn("No ENCRYPTION_KEY provided; deriving development key")
- sum := sha256.Sum256([]byte("arcane-dev-key"))
- encryptionKey = sum[:]
+
if cfg.Environment != "production" {
- slog.Info("Encryption initialized", "env", cfg.Environment, "key_length_bytes", len(encryptionKey), "mode", "derived-dev")
+ slog.Info("Encryption initialized from explicit ENCRYPTION_KEY", "env", cfg.Environment, "key_length_bytes", len(encryptionKey))
}
return
}
- clean := strings.TrimSpace(keyString)
-
- if len(clean) == 32 {
- encryptionKey = []byte(clean)
- } else {
- if b, err := base64.StdEncoding.DecodeString(clean); err == nil && len(b) == 32 {
- encryptionKey = b
- } else if b, err := base64.RawStdEncoding.DecodeString(clean); err == nil && len(b) == 32 {
- encryptionKey = b
- } else if b, err := hex.DecodeString(clean); err == nil && len(b) == 32 {
- encryptionKey = b
+ // No explicit key provided
+ if cfg.AgentMode {
+ // For agent mode, persist a unique per-node key to local secure storage so each agent has its own key.
+ // Prefer user config dir but fall back to current working dir.
+ var dir string
+ if d, err := os.UserConfigDir(); err == nil && d != "" {
+ dir = filepath.Join(d, "arcane")
} else {
- panic(fmt.Sprintf("ENCRYPTION_KEY must be 32 bytes (raw/base64/hex). Provided=%d chars", len(clean)))
+ wd, err := os.Getwd()
+ if err != nil {
+ slog.Warn("Failed to get working directory for agent key storage; using temp dir", "err", err)
+ dir = os.TempDir()
+ } else {
+ dir = filepath.Join(wd, ".arcane")
+ }
+ }
+
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ // If we can't create the directory, log and continue using in-memory generated key
+ slog.Warn("Failed to create directory for agent encryption key; key may not persist", "dir", dir, "err", err)
+ }
+
+ keyPath := filepath.Join(dir, "agent_encryption_key")
+
+ // Try to read existing key
+ if data, err := os.ReadFile(keyPath); err == nil {
+ s := strings.TrimSpace(string(data))
+ if b, err := hex.DecodeString(s); err == nil && len(b) == 32 {
+ encryptionKey = b
+ slog.Info("Loaded agent encryption key from disk", "path", keyPath)
+ return
+ }
+ slog.Warn("Existing agent key found but invalid; will generate a new key", "path", keyPath, "err", err)
+ // fallthrough to generate new key and attempt to overwrite
+ } else if !os.IsNotExist(err) {
+ // if read failed for other reasons, log and continue to generate a new key (may not persist)
+ slog.Warn("Failed to read agent encryption key; will generate a new key", "path", keyPath, "err", err)
+ }
+
+ // Generate a new random 32-byte key
+ newKey := make([]byte, 32)
+ if _, err := crand.Read(newKey); err != nil {
+ // If we cannot get secure randomness, fallback to deterministic derivation as last resort
+ slog.Warn("crypto/rand failed; falling back to deterministic key derivation (not ideal)", "err", err)
+ sum := sha256.Sum256([]byte("arcane-agent-key"))
+ encryptionKey = sum[:]
+ return
+ }
+ encryptionKey = newKey
+
+ // Attempt atomic write: write to temp file in same dir then rename
+ tmpFile, err := os.CreateTemp(dir, "agent_key_")
+ if err != nil {
+ slog.Warn("Failed to create temp file to persist agent key; key will not persist", "path", keyPath, "err", err)
+ return
+ }
+ tmpPath := tmpFile.Name()
+ hexEncoded := hex.EncodeToString(encryptionKey)
+ if _, err := tmpFile.WriteString(hexEncoded + "\n"); err != nil {
+ slog.Warn("Failed to write agent key to temp file; key will not persist", "tmp", tmpPath, "err", err)
+ tmpFile.Close()
+ _ = os.Remove(tmpPath)
+ return
+ }
+ if err := tmpFile.Sync(); err != nil {
+ slog.Warn("Failed to sync agent key temp file; key may not be persisted", "tmp", tmpPath, "err", err)
+ // continue with close/rename attempts
+ }
+ if err := tmpFile.Close(); err != nil {
+ slog.Warn("Failed to close agent key temp file; key may not persist", "tmp", tmpPath, "err", err)
+ _ = os.Remove(tmpPath)
+ return
+ }
+
+ // Ensure file mode 0600 after rename
+ if err := os.Rename(tmpPath, keyPath); err != nil {
+ slog.Warn("Failed to rename agent key temp file into place; key will not persist", "tmp", tmpPath, "dest", keyPath, "err", err)
+ _ = os.Remove(tmpPath)
+ return
+ }
+ if err := os.Chmod(keyPath, 0600); err != nil {
+ slog.Warn("Failed to set permissions on agent key file; permissions may be too permissive", "path", keyPath, "err", err)
}
+ slog.Info("Generated and persisted new agent encryption key", "path", keyPath)
+ return
+ }
+
+ // Non-agent mode and no explicit key provided
+ if cfg.Environment == "production" {
+ // In production non-agent mode a key is required
+ panic("ENCRYPTION_KEY is required in production environment")
}
- if cfg.Environment != "production" {
- slog.Info("Encryption initialized", "env", cfg.Environment, "key_length_bytes", len(encryptionKey))
+ // Development fallback: derive deterministic key to avoid forcing env setup
+ {
+ slog.Warn("No ENCRYPTION_KEY provided; deriving development key")
+ sum := sha256.Sum256([]byte("arcane-dev-key"))
+ encryptionKey = sum[:]
+ slog.Info("Encryption initialized (derived development key)", "env", cfg.Environment, "key_length_bytes", len(encryptionKey))
+ return
}
}
@@ -74,7 +169,7 @@ func Encrypt(plaintext string) (string, error) {
}
nonce := make([]byte, gcm.NonceSize())
- if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
+ if _, err = io.ReadFull(crand.Reader, nonce); err != nil {
return "", fmt.Errorf("failed to generate nonce: %w", err)
}
diff --git a/backend/resources/migrations/postgres/010_rework_environments.down.sql b/backend/resources/migrations/postgres/010_rework_environments.down.sql
new file mode 100644
index 000000000..477a73c51
--- /dev/null
+++ b/backend/resources/migrations/postgres/010_rework_environments.down.sql
@@ -0,0 +1,4 @@
+ALTER TABLE environments DROP COLUMN IF EXISTS access_token;
+ALTER TABLE environments ADD COLUMN IF NOT EXISTS hostname TEXT NOT NULL DEFAULT '';
+ALTER TABLE environments ADD COLUMN IF NOT EXISTS description TEXT;
+DROP INDEX IF EXISTS idx_environments_api_url;
\ No newline at end of file
diff --git a/backend/resources/migrations/postgres/010_rework_environments.up.sql b/backend/resources/migrations/postgres/010_rework_environments.up.sql
new file mode 100644
index 000000000..74785014c
--- /dev/null
+++ b/backend/resources/migrations/postgres/010_rework_environments.up.sql
@@ -0,0 +1,4 @@
+ALTER TABLE environments DROP COLUMN IF EXISTS hostname;
+ALTER TABLE environments DROP COLUMN IF EXISTS description;
+ALTER TABLE environments ADD COLUMN IF NOT EXISTS access_token TEXT;
+CREATE INDEX IF NOT EXISTS idx_environments_api_url ON environments (api_url);
\ No newline at end of file
diff --git a/backend/resources/migrations/postgres/011_add_environment_name.down.sql b/backend/resources/migrations/postgres/011_add_environment_name.down.sql
new file mode 100644
index 000000000..f544be331
--- /dev/null
+++ b/backend/resources/migrations/postgres/011_add_environment_name.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE environments DROP COLUMN IF EXISTS name;
+DROP INDEX IF EXISTS idx_environments_name;
\ No newline at end of file
diff --git a/backend/resources/migrations/postgres/011_add_environment_name.up.sql b/backend/resources/migrations/postgres/011_add_environment_name.up.sql
new file mode 100644
index 000000000..f9adbff9c
--- /dev/null
+++ b/backend/resources/migrations/postgres/011_add_environment_name.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE environments ADD COLUMN IF NOT EXISTS name TEXT;
+CREATE INDEX IF NOT EXISTS idx_environments_name ON environments (name);
\ No newline at end of file
diff --git a/backend/resources/migrations/sqlite/010_rework_environments.down.sql b/backend/resources/migrations/sqlite/010_rework_environments.down.sql
new file mode 100644
index 000000000..68df67aca
--- /dev/null
+++ b/backend/resources/migrations/sqlite/010_rework_environments.down.sql
@@ -0,0 +1,4 @@
+ALTER TABLE environments DROP COLUMN access_token;
+ALTER TABLE environments ADD COLUMN hostname TEXT NOT NULL DEFAULT '';
+ALTER TABLE environments ADD COLUMN description TEXT;
+DROP INDEX IF EXISTS idx_environments_api_url;
\ No newline at end of file
diff --git a/backend/resources/migrations/sqlite/010_rework_environments.up.sql b/backend/resources/migrations/sqlite/010_rework_environments.up.sql
new file mode 100644
index 000000000..6b7c2de60
--- /dev/null
+++ b/backend/resources/migrations/sqlite/010_rework_environments.up.sql
@@ -0,0 +1,4 @@
+ALTER TABLE environments DROP COLUMN hostname;
+ALTER TABLE environments DROP COLUMN description;
+ALTER TABLE environments ADD COLUMN access_token TEXT;
+CREATE INDEX IF NOT EXISTS idx_environments_api_url ON environments(api_url);
\ No newline at end of file
diff --git a/backend/resources/migrations/sqlite/011_add_environment_name.down.sql b/backend/resources/migrations/sqlite/011_add_environment_name.down.sql
new file mode 100644
index 000000000..7bdbdc63b
--- /dev/null
+++ b/backend/resources/migrations/sqlite/011_add_environment_name.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE environments DROP COLUMN name;
+DROP INDEX IF EXISTS idx_environments_name;
\ No newline at end of file
diff --git a/backend/resources/migrations/sqlite/011_add_environment_name.up.sql b/backend/resources/migrations/sqlite/011_add_environment_name.up.sql
new file mode 100644
index 000000000..05c0970a5
--- /dev/null
+++ b/backend/resources/migrations/sqlite/011_add_environment_name.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE environments ADD COLUMN name TEXT DEFAULT '';
+CREATE INDEX IF NOT EXISTS idx_environments_name ON environments(name);
\ No newline at end of file
diff --git a/docker-compose.agent.yml b/docker-compose.agent.yml
new file mode 100644
index 000000000..58ad8caf7
--- /dev/null
+++ b/docker-compose.agent.yml
@@ -0,0 +1,22 @@
+services:
+ arcane-agent:
+ build:
+ context: .
+ dockerfile: docker/Dockerfile-agent
+ target: agent
+ args:
+ BUILD_TAGS: exclude_frontend
+ image: arcane-agent:dev
+ container_name: arcane-agent
+ ports:
+ - '3553:3553'
+ environment:
+ - AGENT_MODE=true
+ - AGENT_BOOTSTRAP_TOKEN=this-is-my-test-bs-token
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ - agent-data:/app/data
+ restart: unless-stopped
+
+volumes:
+ agent-data: {}
diff --git a/Dockerfile b/docker/Dockerfile
similarity index 76%
rename from Dockerfile
rename to docker/Dockerfile
index 5a6c8185c..68a9f61de 100644
--- a/Dockerfile
+++ b/docker/Dockerfile
@@ -4,17 +4,12 @@ ARG BUILD_TAGS=""
# Stage 1: Build Frontend
FROM node:24 AS frontend-builder
RUN corepack enable && corepack prepare [email protected] --activate
-
WORKDIR /build
-
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
COPY frontend/package.json ./frontend/package.json
-
COPY frontend ./frontend
-
ENV NODE_OPTIONS="--max-old-space-size=3072"
RUN pnpm -C frontend install --frozen-lockfile
-
ENV BUILD_PATH=dist
RUN pnpm -C frontend build
@@ -22,17 +17,12 @@ RUN pnpm -C frontend build
FROM golang:1.25-alpine AS backend-builder
ARG BUILD_TAGS
WORKDIR /build
-
-RUN apk add --no-cache git ca-certificates tzdata
-
+RUN apk add --no-cache git ca-certificates tzdata curl
COPY ./backend/go.mod ./backend/go.sum ./
RUN go mod download
-
COPY ./backend ./
-# Copy built frontend assets into backend expected path
COPY --from=frontend-builder /build/frontend/dist ./frontend/dist
-# Build backend binary
RUN CGO_ENABLED=0 \
GOOS=linux \
go build \
@@ -42,31 +32,34 @@ RUN CGO_ENABLED=0 \
-o /build/arcane \
./cmd/main.go
+ARG COMPOSE_VERSION=2.39.2
+ARG TARGETARCH
+COPY ../scripts/development/download-compose.sh /tmp/download-compose.sh
+RUN set -eux; install -d /out; chmod +x /tmp/download-compose.sh; \
+ /tmp/download-compose.sh "${COMPOSE_VERSION}" "/out/docker-compose" "${TARGETARCH}"
+
# Stage 3: Production Image
FROM alpine:3 AS runner
-
-RUN apk upgrade && apk --no-cache add ca-certificates tzdata curl shadow su-exec docker docker-compose
-
-RUN delgroup ping && apk del iputils
+RUN apk upgrade && apk --no-cache add ca-certificates tzdata curl shadow su-exec
+RUN delgroup ping && apk del iputils || true
ENV DOCKER_GID=998 PUID=2000 PGID=2000
ENV GIN_MODE=release
ENV PORT=3552
+ENV ENVIRONMENT=production
WORKDIR /app
-
RUN mkdir -p /app/data && chmod 755 /app/data
COPY --from=backend-builder /build/arcane .
-
-COPY --chmod=755 scripts/docker/entrypoint.sh /usr/local/bin/entrypoint.sh
+COPY --from=backend-builder /out/docker-compose /usr/local/bin/docker-compose
+COPY --chmod=755 ../scripts/docker/entrypoint.sh /usr/local/bin/entrypoint.sh
EXPOSE 3552
VOLUME ["/app/data"]
ARG VERSION="0.15.1"
ARG REVISION="c052902"
-
LABEL org.opencontainers.image.authors="OFKM Technologies"
LABEL org.opencontainers.image.url="https://github.com/ofkm/arcane"
LABEL org.opencontainers.image.documentation="https://github.com/ofkm/arcane/blob/main/README.md"
diff --git a/docker/Dockerfile-agent b/docker/Dockerfile-agent
new file mode 100644
index 000000000..b62bb8dbd
--- /dev/null
+++ b/docker/Dockerfile-agent
@@ -0,0 +1,49 @@
+# Build agent binary
+FROM golang:1.25-alpine AS agent-builder
+ARG BUILD_TAGS="exclude_frontend"
+WORKDIR /build
+
+RUN apk add --no-cache git ca-certificates tzdata curl
+
+COPY ./backend/go.mod ./backend/go.sum ./
+RUN go mod download
+
+COPY ./backend ./backend
+
+WORKDIR /build/backend
+RUN CGO_ENABLED=0 \
+ GOOS=linux \
+ go build \
+ -tags "${BUILD_TAGS}" \
+ -ldflags='-w -s' \
+ -trimpath \
+ -o /out/arcane-agent \
+ ./cmd/main.go
+
+ARG COMPOSE_VERSION=2.39.2
+ARG TARGETARCH
+COPY ../scripts/development/download-compose.sh /tmp/download-compose.sh
+RUN set -eux; chmod +x /tmp/download-compose.sh; \
+ /tmp/download-compose.sh "${COMPOSE_VERSION}" "/out/docker-compose" "${TARGETARCH}"
+
+FROM alpine:3 AS agent
+RUN apk upgrade && apk --no-cache add ca-certificates tzdata curl su-exec
+
+WORKDIR /app
+RUN mkdir -p /app/data && chmod 755 /app/data
+
+COPY --from=agent-builder /out/arcane-agent /usr/local/bin/arcane-agent
+COPY --from=agent-builder /out/docker-compose /usr/local/bin/docker-compose
+
+COPY --chmod=755 ../scripts/docker/entrypoint.sh /usr/local/bin/entrypoint.sh
+ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
+
+ENV GIN_MODE=release \
+ PORT=3553 \
+ AGENT_MODE=true \
+ ENVIRONMENT=production
+
+EXPOSE 3553
+VOLUME ["/app/data"]
+
+CMD ["/usr/local/bin/arcane-agent"]
\ No newline at end of file
diff --git a/docker/Dockerfile-static b/docker/Dockerfile-static
new file mode 100644
index 000000000..df1b379bd
--- /dev/null
+++ b/docker/Dockerfile-static
@@ -0,0 +1,22 @@
+FROM alpine:3
+
+ARG TARGETARCH
+ARG COMPOSE_VERSION=2.39.2
+
+WORKDIR /app
+RUN apk upgrade && apk --no-cache add ca-certificates tzdata curl su-exec \
+ && (delgroup ping || true) && (apk del iputils || true)
+
+COPY ../scripts/development/download-compose.sh /tmp/download-compose.sh
+RUN set -eux; chmod +x /tmp/download-compose.sh; \
+ /tmp/download-compose.sh "${COMPOSE_VERSION}" "/usr/local/bin/docker-compose" "${TARGETARCH}"
+
+COPY ./backend/.bin/arcane-linux-${TARGETARCH} ./arcane
+
+COPY --chmod=755 ../scripts/docker/entrypoint.sh /usr/local/bin/entrypoint.sh
+
+EXPOSE 3552
+ENV ENVIRONMENT=production
+
+ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
+CMD ["./arcane"]
\ No newline at end of file
diff --git a/frontend/src/lib/components/error.svelte b/frontend/src/lib/components/error.svelte
index 58dfbb5e2..bafc8bdbd 100644
--- a/frontend/src/lib/components/error.svelte
+++ b/frontend/src/lib/components/error.svelte
@@ -38,7 +38,7 @@
{#if showButton}
<div class="mt-5 flex items-center justify-center gap-2">
- <Button size="sm" href={actionHref}>{actionLabel}</Button>
+ <Button href={actionHref}>{actionLabel}</Button>
</div>
{/if}
</div>
diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.svelte
index 324620d21..940b17e43 100644
--- a/frontend/src/lib/components/image-update-item.svelte
+++ b/frontend/src/lib/components/image-update-item.svelte
@@ -9,9 +9,9 @@
import ArrowRightIcon from '@lucide/svelte/icons/arrow-right';
import PackageIcon from '@lucide/svelte/icons/package';
import KeyRoundIcon from '@lucide/svelte/icons/key-round';
- import { imageUpdateAPI } from '$lib/services/api';
+ import { environmentAPI } from '$lib/services/api';
import { toast } from 'svelte-sonner';
- import type { ImageUpdateData } from '$lib/services/api/image-update-api-service';
+ import type { ImageUpdateData } from '$lib/types/image.type';
interface Props {
updateInfo?: ImageUpdateData | undefined;
@@ -89,7 +89,7 @@
isChecking = true;
try {
- const result = await imageUpdateAPI.checkImageUpdateByID(imageId);
+ const result = await environmentAPI.checkImageUpdateByID(imageId);
if (result) {
if (result.error) {
localUpdateInfo = result;
diff --git a/frontend/src/lib/components/sheets/new-environment-sheet.svelte b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
index f9e456f26..77d1b49ef 100644
--- a/frontend/src/lib/components/sheets/new-environment-sheet.svelte
+++ b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
@@ -1,16 +1,12 @@
<script lang="ts">
- import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
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 LoaderCircleIcon from '@lucide/svelte/icons/loader-circle';
import ServerIcon from '@lucide/svelte/icons/server';
- import Trash2Icon from '@lucide/svelte/icons/trash-2';
- import TestTubeIcon from '@lucide/svelte/icons/test-tube';
import * as Card from '$lib/components/ui/card';
import { environmentManagementAPI } from '$lib/services/api';
- import type { Environment } from '$lib/stores/environment.store';
import type { CreateEnvironmentDTO } from '$lib/types/environment.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
@@ -22,32 +18,22 @@
let { open = $bindable(false), onEnvironmentCreated }: NewEnvironmentSheetProps = $props();
- let environments = $state<Environment[]>([]);
- let loading = $state(false);
let isSubmitting = $state(false);
const formSchema = z.object({
- apiUrl: z.string().url('Must be a valid URL').min(1, 'Server URL is required')
+ name: z.string().min(1, 'Name is required').max(25, 'Name too long'),
+ apiUrl: z.url('Must be a valid URL').min(1, 'Server URL is required'),
+ bootstrapToken: z.string()
});
let formData = $state({
- apiUrl: ''
+ name: '',
+ apiUrl: '',
+ bootstrapToken: ''
});
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
- async function loadEnvironments() {
- try {
- loading = true;
- environments = await environmentManagementAPI.list();
- } catch (error) {
- toast.error('Failed to load environments');
- console.error(error);
- } finally {
- loading = false;
- }
- }
-
async function handleSubmit() {
const data = form.validate();
if (!data) return;
@@ -55,26 +41,29 @@
try {
isSubmitting = true;
- // Derive a hostname from the URL (for backend compatibility)
- let derivedHostname = '';
- try {
- const u = new URL(data.apiUrl);
- derivedHostname = u.hostname || u.host || data.apiUrl;
- } catch {
- derivedHostname = data.apiUrl;
- }
-
const dto: CreateEnvironmentDTO = {
- hostname: derivedHostname,
- apiUrl: data.apiUrl
- // description omitted; enabled defaults server-side
+ name: data.name,
+ apiUrl: data.apiUrl,
+ bootstrapToken: data.bootstrapToken
};
- await environmentManagementAPI.create(dto);
+ const created = await environmentManagementAPI.create(dto);
+
+ try {
+ const result = await environmentManagementAPI.testConnection(created.id);
+ if (result.status === 'online') {
+ toast.success('Environment is online');
+ } else {
+ toast.warning('Environment appears offline');
+ }
+ } catch (e) {
+ console.error(e);
+ toast.error('Environment test failed');
+ }
+
toast.success('Environment created successfully');
form.reset();
- await loadEnvironments();
onEnvironmentCreated?.();
} catch (error) {
toast.error('Failed to create environment');
@@ -83,45 +72,9 @@
isSubmitting = false;
}
}
-
- async function deleteEnvironment(environmentId: string) {
- if (!confirm('Are you sure you want to delete this environment?')) {
- return;
- }
-
- try {
- await environmentManagementAPI.delete(environmentId);
- toast.success('Environment deleted successfully');
- await loadEnvironments();
- } catch (error) {
- toast.error('Failed to delete environment');
- console.error(error);
- }
- }
-
- async function testConnection(environmentId: string) {
- try {
- const result = await environmentManagementAPI.testConnection(environmentId);
- if (result.status === 'online') {
- toast.success('Connection successful');
- } else {
- toast.error(`Connection failed: ${result.message || 'Unknown error'}`);
- }
- } catch (error) {
- toast.error('Failed to test connection');
- console.error(error);
- }
- }
-
- function handleOpenChange(newOpenState: boolean) {
- open = newOpenState;
- if (!newOpenState) {
- form.reset();
- }
- }
</script>
-<Sheet.Root bind:open onOpenChange={handleOpenChange}>
+<Sheet.Root bind:open>
<Sheet.Content class="w-full p-6 sm:max-w-lg">
<Sheet.Header class="space-y-3 border-b pb-6">
<div class="flex items-center gap-3">
@@ -131,7 +84,7 @@
<div>
<Sheet.Title class="text-xl font-semibold">Manage Environments</Sheet.Title>
<Sheet.Description class="text-muted-foreground mt-1 text-sm"
- >Add and manage remote Arcane servers (headless backend, no frontend). Provide the server endpoint.</Sheet.Description
+ >Add and manage remote Arcane servers in Agent Mode.</Sheet.Description
>
</div>
</div>
@@ -144,14 +97,24 @@
</Card.Header>
<Card.Content>
<form onsubmit={preventDefault(handleSubmit)} class="space-y-4">
+ <FormInput label="Name" placeholder="My Lab Server" bind:input={$inputs.name} />
+
<FormInput
label="Server URL *"
type="text"
- placeholder="http://192.168.1.100:3552"
+ placeholder="http://192.168.1.100:3553"
description="Full URL to the Arcane server endpoint"
bind:input={$inputs.apiUrl}
/>
+ <FormInput
+ label="Bootstrap Token"
+ type="password"
+ placeholder="AGENT_BOOTSTRAP_TOKEN from the agent"
+ description="If provided, manager will auto‑pair with the agent and store the generated token"
+ bind:input={$inputs.bootstrapToken}
+ />
+
<Button type="submit" class="w-full" disabled={isSubmitting}>
{#if isSubmitting}
<LoaderCircleIcon class="mr-2 size-4 animate-spin" />
diff --git a/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte b/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
index 8396242df..5e5b259eb 100644
--- a/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
@@ -7,7 +7,8 @@
import PlusIcon from '@lucide/svelte/icons/plus';
import GlobeIcon from '@lucide/svelte/icons/globe';
import ServerIcon from '@lucide/svelte/icons/server';
- import { environmentStore, type Environment } from '$lib/stores/environment.store';
+ import { environmentStore } from '$lib/stores/environment.store';
+ import type { Environment } from '$lib/types/environment.type';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
@@ -43,6 +44,14 @@
toast.error('Failed to Connect to Environment');
}
}
+
+ function getEnvLabel(env: Environment): string {
+ if (env.isLocal) {
+ return 'Local Docker';
+ } else {
+ return env.name;
+ }
+ }
</script>
<Sidebar.Menu>
@@ -70,7 +79,7 @@
</div>
<div class="grid flex-1 text-left text-sm leading-tight">
<span class="truncate font-medium">
- {currentSelectedEnvironment.hostname}
+ {getEnvLabel(currentSelectedEnvironment)}
</span>
<span class="truncate text-xs">
{currentSelectedEnvironment.isLocal ? 'unix:///var/run/docker.sock' : currentSelectedEnvironment.apiUrl}
@@ -116,7 +125,7 @@
{/if}
</div>
<div class="flex flex-col">
- <span>{env.hostname}</span>
+ <span>{getEnvLabel(env)}</span>
{#if env.isLocal}
<span class="text-muted-foreground text-xs">unix:///var/run/docker.sock</span>
{:else}
@@ -126,8 +135,8 @@
</DropdownMenu.Item>
{/each}
{/if}
- <DropdownMenu.Separator />
{#if isAdmin}
+ <DropdownMenu.Separator />
<DropdownMenu.Item class="gap-2 p-2" onSelect={() => goto('/environments')}>
<div class="flex size-6 items-center justify-center rounded-md border bg-transparent">
<PlusIcon class="size-4" />
diff --git a/frontend/src/lib/services/api/autoupdate-api-service.ts b/frontend/src/lib/services/api/autoupdate-api-service.ts
deleted file mode 100644
index 01eea6003..000000000
--- a/frontend/src/lib/services/api/autoupdate-api-service.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import BaseAPIService from './api-service';
-import type { AutoUpdateCheck, AutoUpdateResult, AutoUpdateRecord, AutoUpdateStatus } from '$lib/types/auto-update.type';
-
-export default class AutoUpdateAPIService extends BaseAPIService {
- async checkForUpdates(options?: AutoUpdateCheck): Promise<AutoUpdateResult> {
- const response = await this.api.post('/updater/run', options || {});
- return response.data.data;
- }
-
- async getStatus(): Promise<AutoUpdateStatus> {
- const response = await this.api.get('/updater/status');
- return response.data.data;
- }
-
- async getUpdateHistory(limit?: number): Promise<AutoUpdateRecord[]> {
- const params = limit ? { limit } : {};
- const response = await this.api.get('/updater/history', { params });
- return response.data.data;
- }
-}
diff --git a/frontend/src/lib/services/api/environment-api-service.ts b/frontend/src/lib/services/api/environment-api-service.ts
index 1f4d37c0f..2c615a1a9 100644
--- a/frontend/src/lib/services/api/environment-api-service.ts
+++ b/frontend/src/lib/services/api/environment-api-service.ts
@@ -3,18 +3,14 @@ import { get } from 'svelte/store';
import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '$lib/stores/environment.store';
import type { ContainerCreateOptions, NetworkCreateOptions, VolumeCreateOptions, ContainerStats } from 'dockerode';
import type { Project } from '$lib/types/project.type';
-import type {
- PaginationRequest,
- SortRequest,
- PaginatedApiResponse,
- SearchPaginationSortRequest,
- Paginated
-} from '$lib/types/pagination.type';
+import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
import { browser } from '$app/environment';
import type { ContainerSummaryDto } from '$lib/types/container.type';
-import type { ImageSummaryDto } from '$lib/types/image.type';
+import type { ImageSummaryDto, ImageUpdateInfoDto } from '$lib/types/image.type';
import type { NetworkSummaryDto } from '$lib/types/network.type';
import type { VolumeSummaryDto, VolumeDetailDto, VolumeUsageDto } from '$lib/types/volume.type';
+import type { ImageUpdateSummary, ImageVersions, VersionComparison, CompareVersionRequest } from '$lib/types/image.type';
+import type { AutoUpdateCheck, AutoUpdateResult, AutoUpdateRecord, AutoUpdateStatus } from '$lib/types/auto-update.type';
export class EnvironmentAPIService extends BaseAPIService {
private async getCurrentEnvironmentId(): Promise<string> {
@@ -321,6 +317,62 @@ export class EnvironmentAPIService extends BaseAPIService {
})
);
}
+
+ async checkImageUpdate(imageRef: string): Promise<ImageUpdateInfoDto> {
+ const envId = await this.getCurrentEnvironmentId();
+ const res = await this.api.get(`/environments/${envId}/image-updates/check`, { params: { imageRef } });
+ return this.handleResponse(res.data);
+ }
+
+ async checkImageUpdateByID(imageId: string): Promise<ImageUpdateInfoDto> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/check/${imageId}`));
+ }
+
+ async checkMultipleImages(imageRefs: string[]): Promise<Record<string, ImageUpdateInfoDto>> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/check-batch`, { imageRefs }));
+ }
+
+ async checkAllImages(limit = 50): Promise<Record<string, ImageUpdateInfoDto>> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/check-all`, { params: { limit } }));
+ }
+
+ async getUpdateSummary(): Promise<ImageUpdateSummary> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/summary`));
+ }
+
+ async getImageVersions(imageRef: string, limit = 20): Promise<ImageVersions> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(
+ this.api.get(`/environments/${envId}/image-updates/versions`, {
+ params: { imageRef, limit }
+ })
+ );
+ }
+
+ async compareVersions(request: CompareVersionRequest): Promise<VersionComparison> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/compare`, request));
+ }
+
+ async runAutoUpdate(options?: AutoUpdateCheck): Promise<AutoUpdateResult> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/updater/run`, options));
+ }
+
+ async getAutoUpdateStatus(): Promise<AutoUpdateStatus> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/updater/status`));
+ }
+
+ async getAutoUpdateHistory(limit?: number): Promise<AutoUpdateRecord[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ const params = limit ? { limit } : undefined;
+ return this.handleResponse(this.api.get(`/environments/${envId}/updater/history`, { params }));
+ }
}
export const environmentAPI = new EnvironmentAPIService();
diff --git a/frontend/src/lib/services/api/environment-management-api-service.ts b/frontend/src/lib/services/api/environment-management-api-service.ts
index 4f295d85d..b982130d8 100644
--- a/frontend/src/lib/services/api/environment-management-api-service.ts
+++ b/frontend/src/lib/services/api/environment-management-api-service.ts
@@ -1,5 +1,5 @@
import BaseAPIService from './api-service';
-import type { Environment } from '$lib/stores/environment.store';
+import type { Environment } from '$lib/types/environment.type';
import type { CreateEnvironmentDTO, UpdateEnvironmentDTO } from '$lib/types/environment.type';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
@@ -14,12 +14,6 @@ export default class EnvironmentManagementAPIService extends BaseAPIService {
return res.data;
}
- // Back-compat helper used by layout/env switcher
- async list(): Promise<Environment[]> {
- const res = await this.api.get('/environments', { params: { 'pagination.page': 1, 'pagination.limit': 1000 } });
- return (res.data?.data as Environment[]) ?? [];
- }
-
async get(environmentId: string): Promise<Environment> {
const res = await this.api.get(`/environments/${environmentId}`);
return res.data.data as Environment;
diff --git a/frontend/src/lib/services/api/image-api-service.ts b/frontend/src/lib/services/api/image-api-service.ts
index f8f0c5843..52b0369d9 100644
--- a/frontend/src/lib/services/api/image-api-service.ts
+++ b/frontend/src/lib/services/api/image-api-service.ts
@@ -6,28 +6,6 @@ export default class ImageAPIService extends BaseAPIService {
return this.handleResponse(this.api.get('/images', { params: { filters } }));
}
- async listPaginated(
- pagination: PaginationRequest,
- sort?: SortRequest,
- filters?: Record<string, string>
- ): Promise<PaginatedApiResponse<any>> {
- const params: any = {
- page: pagination.page,
- limit: pagination.limit
- };
-
- if (sort) {
- params.column = sort.column;
- params.direction = sort.direction;
- }
-
- if (filters) {
- params.filters = filters;
- }
-
- return this.handleResponse(this.api.get('/images', { params }));
- }
-
async getTotalSize() {
return this.handleResponse(this.api.get(`/images/total-size`));
}
diff --git a/frontend/src/lib/services/api/image-update-api-service.ts b/frontend/src/lib/services/api/image-update-api-service.ts
deleted file mode 100644
index 653103f09..000000000
--- a/frontend/src/lib/services/api/image-update-api-service.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import BaseAPIService from './api-service';
-import type { ImageUpdateInfoDto } from '$lib/types/image.type';
-
-export type ImageUpdateData = ImageUpdateInfoDto;
-
-export interface ImageUpdateSummary {
- totalImages: number;
- imagesWithUpdates: number;
- digestUpdates: number;
- tagUpdates: number;
- errorsCount: number;
-}
-
-export interface ImageVersions {
- imageRef: string;
- current: string;
- versions: string[];
- latest?: string;
-}
-
-export interface VersionComparison {
- currentVersion: string;
- targetVersion: string;
- isNewer: boolean;
- updateType: string;
- changeLevel: string;
-}
-
-export interface BatchImageUpdateRequest {
- imageRefs: string[];
-}
-
-export interface CompareVersionRequest {
- currentVersion: string;
- targetVersion: string;
- imageRef: string;
-}
-
-export default class ImageUpdateAPIService extends BaseAPIService {
- async checkImageUpdate(imageRef: string): Promise<ImageUpdateData> {
- const res = await this.api.get(`/image-updates/check?imageRef=${encodeURIComponent(imageRef)}`);
- return this.handleResponse(res.data);
- }
-
- async checkImageUpdateByID(imageId: string): Promise<ImageUpdateData> {
- const res = await this.api.get(`/image-updates/check/${imageId}`);
- return this.handleResponse(res.data);
- }
-
- async checkMultipleImages(imageRefs: string[]): Promise<Record<string, ImageUpdateData>> {
- const res = await this.api.post('/image-updates/check-batch', { imageRefs });
- return this.handleResponse(res.data);
- }
-
- async checkAllImages(limit: number = 50): Promise<Record<string, ImageUpdateData>> {
- const res = await this.api.get(`/image-updates/check-all?limit=${limit}`);
- return this.handleResponse(res.data);
- }
-
- async getUpdateSummary(): Promise<ImageUpdateSummary> {
- const res = await this.api.get('/image-updates/summary');
- return this.handleResponse(res.data);
- }
-
- async getImageVersions(imageRef: string, limit: number = 20): Promise<ImageVersions> {
- const res = await this.api.get(`/image-updates/versions?imageRef=${encodeURIComponent(imageRef)}&limit=${limit}`);
- return this.handleResponse(res.data);
- }
-
- async compareVersions(request: CompareVersionRequest): Promise<VersionComparison> {
- const res = await this.api.post('/image-updates/compare', request);
- return this.handleResponse(res.data);
- }
-}
diff --git a/frontend/src/lib/services/api/index.ts b/frontend/src/lib/services/api/index.ts
index a02adccae..4b41505d8 100644
--- a/frontend/src/lib/services/api/index.ts
+++ b/frontend/src/lib/services/api/index.ts
@@ -1,12 +1,10 @@
import ImageAPIService from './image-api-service';
-import ImageUpdateAPIService from './image-update-api-service';
import SystemAPIService from './system-api-service';
import TemplateAPIService from './template-api-service';
import UserAPIService from './user-api-service';
import SettingsAPIService from './settings-api-service';
import TemplateRegistryAPIService from './template-registry-api-service';
import OidcAPIService from './oidc-api-service';
-import AutoUpdateAPIService from './autoupdate-api-service';
import ConverterAPIService from './converter-api-service';
import ContainerRegistryAPIService from './container-registry-api-service';
import { EnvironmentAPIService } from './environment-api-service';
@@ -14,7 +12,6 @@ import EnvironmentManagementAPIService from './environment-management-api-servic
import EventAPIService from './event-api-service';
export const imageAPI = new ImageAPIService();
-export const imageUpdateAPI = new ImageUpdateAPIService();
export const systemAPI = new SystemAPIService();
export const templateAPI = new TemplateAPIService();
export const userAPI = new UserAPIService();
@@ -23,14 +20,12 @@ export const templateRegistryAPI = new TemplateRegistryAPIService();
export const oidcAPI = new OidcAPIService();
export const converterAPI = new ConverterAPIService();
export const containerRegistryAPI = new ContainerRegistryAPIService();
-export const autoUpdateAPI = new AutoUpdateAPIService();
export const environmentAPI = new EnvironmentAPIService();
export const environmentManagementAPI = new EnvironmentManagementAPIService();
export const eventAPI = new EventAPIService();
interface APIServices {
image: ImageAPIService;
- imageUpdate: ImageUpdateAPIService;
system: SystemAPIService;
template: TemplateAPIService;
user: UserAPIService;
@@ -39,7 +34,6 @@ interface APIServices {
oidc: OidcAPIService;
converter: ConverterAPIService;
containerRegistry: ContainerRegistryAPIService;
- autoUpdate: AutoUpdateAPIService;
environment: EnvironmentAPIService;
environmentManagement: EnvironmentManagementAPIService;
event: EventAPIService;
@@ -47,7 +41,6 @@ interface APIServices {
const apiServices: APIServices = {
image: imageAPI,
- imageUpdate: imageUpdateAPI,
system: systemAPI,
template: templateAPI,
user: userAPI,
@@ -56,7 +49,6 @@ const apiServices: APIServices = {
oidc: oidcAPI,
converter: converterAPI,
containerRegistry: containerRegistryAPI,
- autoUpdate: autoUpdateAPI,
environment: environmentAPI,
environmentManagement: environmentManagementAPI,
event: eventAPI
diff --git a/frontend/src/lib/stores/environment.store.ts b/frontend/src/lib/stores/environment.store.ts
index f66c12717..9265c2ef3 100644
--- a/frontend/src/lib/stores/environment.store.ts
+++ b/frontend/src/lib/stores/environment.store.ts
@@ -1,25 +1,13 @@
import { writable, get } from 'svelte/store';
import { browser } from '$app/environment';
-import { invalidateAll } from '$app/navigation';
-
-export type Environment = {
- id: string;
- hostname: string;
- apiUrl: string;
- description?: string;
- status: 'online' | 'offline' | 'error';
- enabled: boolean;
- lastSeen?: string;
- createdAt: string;
- updatedAt?: string;
- isLocal?: boolean;
-};
+import { goto } from '$app/navigation';
+import type { Environment } from '$lib/types/environment.type';
export const LOCAL_DOCKER_ENVIRONMENT_ID = '0';
export const localDockerEnvironment: Environment = {
id: LOCAL_DOCKER_ENVIRONMENT_ID,
- hostname: 'Local Docker',
+ name: 'Local Docker',
apiUrl: 'http://localhost',
status: 'online',
enabled: true,
@@ -116,7 +104,10 @@ function createEnvironmentManagementStore() {
}
if (browser) {
- await invalidateAll();
+ await goto(window.location.pathname + window.location.search, {
+ replaceState: true,
+ invalidateAll: true
+ });
}
}
},
diff --git a/frontend/src/lib/types/environment.type.ts b/frontend/src/lib/types/environment.type.ts
index 79ca97e51..3befc04f8 100644
--- a/frontend/src/lib/types/environment.type.ts
+++ b/frontend/src/lib/types/environment.type.ts
@@ -1,30 +1,30 @@
-import type { Environment } from '$lib/stores/environment.store';
+export type EnvironmentStatus = 'online' | 'offline' | 'error';
+
+export interface Environment {
+ id: string;
+ name: string;
+ apiUrl: string;
+ status: EnvironmentStatus;
+ enabled: boolean;
+ lastSeen?: string;
+ createdAt: string;
+ updatedAt?: string;
+ isLocal?: boolean;
+}
export interface CreateEnvironmentDTO {
- hostname: string;
apiUrl: string;
- description?: string;
+ name: string;
+ bootstrapToken?: string;
}
export interface UpdateEnvironmentDTO {
- hostname?: string;
apiUrl?: string;
- description?: string;
+ name?: string;
+ enabled?: boolean;
+ bootstrapToken?: string;
}
export interface EnvironmentResponse {
data: Environment;
- success: boolean;
- message?: string;
-}
-
-export interface EnvironmentsListResponse<T = Environment> {
- data: T[];
- success: boolean;
- pagination?: {
- totalPages: number;
- totalItems: number;
- currentPage: number;
- itemsPerPage: number;
- };
}
diff --git a/frontend/src/lib/types/image.type.ts b/frontend/src/lib/types/image.type.ts
index 55fd4a54f..9a8ed6920 100644
--- a/frontend/src/lib/types/image.type.ts
+++ b/frontend/src/lib/types/image.type.ts
@@ -65,3 +65,38 @@ export interface ImageDetailSummaryDto {
size: number;
};
}
+
+export type ImageUpdateData = ImageUpdateInfoDto;
+
+export interface ImageUpdateSummary {
+ totalImages: number;
+ imagesWithUpdates: number;
+ digestUpdates: number;
+ tagUpdates: number;
+ errorsCount: number;
+}
+
+export interface ImageVersions {
+ imageRef: string;
+ current: string;
+ versions: string[];
+ latest?: string;
+}
+
+export interface VersionComparison {
+ currentVersion: string;
+ targetVersion: string;
+ isNewer: boolean;
+ updateType: string;
+ changeLevel: string;
+}
+
+export interface BatchImageUpdateRequest {
+ imageRefs: string[];
+}
+
+export interface CompareVersionRequest {
+ currentVersion: string;
+ targetVersion: string;
+ imageRef: string;
+}
diff --git a/frontend/src/lib/utils/redirect.util.ts b/frontend/src/lib/utils/redirect.util.ts
index 915d94670..e7fb92084 100644
--- a/frontend/src/lib/utils/redirect.util.ts
+++ b/frontend/src/lib/utils/redirect.util.ts
@@ -19,16 +19,12 @@ const PROTECTED_RE = new RegExp(`^/(?:${PROTECTED_PREFIXES.map(escapeRe).join('|
const isProtectedPath = (path: string) => {
const result = PROTECTED_RE.test(path);
- console.log(`Testing path: "${path}" against regex | Result: ${result}`);
- console.log(`Regex pattern: ${PROTECTED_RE.source}`);
return result;
};
export function getAuthRedirectPath(path: string, user: User | null, settings: Settings | null) {
const isSignedIn = !!user;
- console.log(`Path: ${path}, isProtected: ${isProtectedPath(path)}, isSignedIn: ${isSignedIn}`);
-
const isUnauthenticatedOnlyPath =
path === '/auth/login' ||
path.startsWith('/auth/login/') ||
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index 710c8077e..81d980d1e 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -33,10 +33,7 @@
String(page.url.pathname).includes('/callback')
);
- // const isLoginPage = $derived(page.url.pathname.startsWith('/auth/login'));
-
const redirectPath = getAuthRedirectPath(page.url.pathname, user, settings);
- console.log(page.url.pathname);
if (redirectPath) {
goto(redirectPath);
}
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index eda72dba2..2bb03ea30 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -5,6 +5,7 @@ import { versionService } from '$lib/services/app-version-service';
import { tryCatch } from '$lib/utils/try-catch';
import userStore from '$lib/stores/user-store';
import settingsStore from '$lib/stores/config-store';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
export const ssr = false;
@@ -17,11 +18,18 @@ export const load = async () => {
return settingsAPI.getPublicSettings().catch(() => null);
});
+ const environmentRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 1000
+ }
+ };
+
const environmentsPromise = userPromise.then(async (user) => {
if (!environmentStore.isInitialized() && user) {
- const environments = await tryCatch(environmentManagementAPI.list());
+ const environments = await tryCatch(environmentManagementAPI.getEnvironments(environmentRequestOptions));
if (!environments.error) {
- await environmentStore.initialize(environments.data || [], true);
+ await environmentStore.initialize(environments.data.data, true);
}
}
return null;
diff --git a/frontend/src/routes/compose/+page.svelte b/frontend/src/routes/compose/+page.svelte
index 3217ea6a1..15134beff 100644
--- a/frontend/src/routes/compose/+page.svelte
+++ b/frontend/src/routes/compose/+page.svelte
@@ -6,7 +6,7 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { autoUpdateAPI, environmentAPI } from '$lib/services/api';
+ import { environmentAPI } from '$lib/services/api';
import StatCard from '$lib/components/stat-card.svelte';
import ProjectsTable from './compose-table.svelte';
import { goto } from '$app/navigation';
@@ -29,7 +29,7 @@
async function handleCheckForUpdates() {
isLoading.updating = true;
handleApiResultWithCallbacks({
- result: await tryCatch(autoUpdateAPI.checkForUpdates()),
+ result: await tryCatch(environmentAPI.runAutoUpdate()),
message: 'Failed to Check Compose Projects for Updates',
setLoadingState: (value) => (isLoading.updating = value),
async onSuccess() {
diff --git a/frontend/src/routes/compose/new/+page.ts b/frontend/src/routes/compose/new/+page.ts
index dc344aa67..2f15fbd26 100644
--- a/frontend/src/routes/compose/new/+page.ts
+++ b/frontend/src/routes/compose/new/+page.ts
@@ -1,17 +1,8 @@
-import { templateAPI, environmentManagementAPI } from '$lib/services/api';
+import { templateAPI } from '$lib/services/api';
import { defaultComposeTemplate } from '$lib/constants';
-import type { Template } from '$lib/types/template.type';
-import type { Environment } from '$lib/stores/environment.store';
-export interface PageProps {
- composeTemplates: Template[];
- envTemplate: string;
- defaultTemplate: string;
- environments: Environment[];
-}
-
-export const load = async (): Promise<PageProps> => {
- const [allTemplates, envTemplate, environments] = await Promise.all([
+export const load = async () => {
+ const [allTemplates, envTemplate] = await Promise.all([
templateAPI.loadAll().catch((err) => {
console.warn('Failed to load templates:', err);
return [];
@@ -19,17 +10,12 @@ export const load = async (): Promise<PageProps> => {
templateAPI.getEnvTemplate().catch((err) => {
console.warn('Failed to load env template:', err);
return '';
- }),
- environmentManagementAPI.list().catch((err) => {
- console.warn('Failed to load environments:', err);
- return [];
})
]);
return {
composeTemplates: allTemplates,
envTemplate,
- defaultTemplate: defaultComposeTemplate,
- environments
+ defaultTemplate: defaultComposeTemplate
};
};
diff --git a/frontend/src/routes/containers/+page.svelte b/frontend/src/routes/containers/+page.svelte
index 20e892004..6a815ba40 100644
--- a/frontend/src/routes/containers/+page.svelte
+++ b/frontend/src/routes/containers/+page.svelte
@@ -5,7 +5,7 @@
import { tryCatch } from '$lib/utils/try-catch';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import StatCard from '$lib/components/stat-card.svelte';
- import { autoUpdateAPI, environmentAPI } from '$lib/services/api';
+ import { environmentAPI } from '$lib/services/api';
import ContainerTable from './container-table.svelte';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
@@ -25,7 +25,7 @@
async function handleCheckForUpdates() {
isLoading.checking = true;
handleApiResultWithCallbacks({
- result: await tryCatch(autoUpdateAPI.checkForUpdates()),
+ result: await tryCatch(environmentAPI.runAutoUpdate()),
message: 'Failed to Check Containers for Updates',
setLoadingState: (value) => (isLoading.checking = value),
async onSuccess() {
diff --git a/frontend/src/routes/environments/+page.svelte b/frontend/src/routes/environments/+page.svelte
index 3516d2cfb..211d1a684 100644
--- a/frontend/src/routes/environments/+page.svelte
+++ b/frontend/src/routes/environments/+page.svelte
@@ -1,7 +1,6 @@
<script lang="ts">
import ServerIcon from '@lucide/svelte/icons/server';
import { toast } from 'svelte-sonner';
- import * as Card from '$lib/components/ui/card/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import NewEnvironmentSheet from '$lib/components/sheets/new-environment-sheet.svelte';
import EnvironmentTable from './environment-table.svelte';
@@ -76,8 +75,9 @@
});
}
- function onEnvironmentCreated() {
+ async function onEnvironmentCreated() {
showEnvironmentSheet = false;
+ environments = await environmentManagementAPI.getEnvironments(requestOptions);
toast.success('Environment added successfully');
refresh();
}
@@ -115,11 +115,7 @@
</div>
</div>
- <Card.Root class="border shadow-sm">
- <Card.Content>
- <EnvironmentTable bind:environments bind:selectedIds bind:requestOptions />
- </Card.Content>
- </Card.Root>
+ <EnvironmentTable bind:environments bind:selectedIds bind:requestOptions />
</div>
<NewEnvironmentSheet bind:open={showEnvironmentSheet} {onEnvironmentCreated} />
diff --git a/frontend/src/routes/environments/[id]/+page.svelte b/frontend/src/routes/environments/[id]/+page.svelte
index 94c137f17..14cd75c79 100644
--- a/frontend/src/routes/environments/[id]/+page.svelte
+++ b/frontend/src/routes/environments/[id]/+page.svelte
@@ -7,15 +7,11 @@
import MonitorIcon from '@lucide/svelte/icons/monitor';
import TerminalIcon from '@lucide/svelte/icons/terminal';
import SettingsIcon from '@lucide/svelte/icons/settings';
- import ActivityIcon from '@lucide/svelte/icons/activity';
import GlobeIcon from '@lucide/svelte/icons/globe';
- import DatabaseIcon from '@lucide/svelte/icons/database';
import { goto, invalidateAll } from '$app/navigation';
- import { format } from 'date-fns';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { environmentManagementAPI } from '$lib/services/api';
import { toast } from 'svelte-sonner';
- import { onMount } from 'svelte';
import Label from '$lib/components/ui/label/label.svelte';
let { data }: { data: PageData } = $props();
@@ -23,22 +19,19 @@
let isRefreshing = $state(false);
let isTestingConnection = $state(false);
+ let isPairing = $state(false);
+ let bootstrapToken = $state('');
+
let activeSection = $state<string>('overview');
const sections = [
{ id: 'overview', Label: 'Overview', icon: MonitorIcon },
{ id: 'connection', Label: 'Connection', icon: GlobeIcon },
- { id: 'activity', Label: 'Activity', icon: ActivityIcon }
+ { id: 'pairing', Label: 'Pair/Rotate', icon: SettingsIcon }
];
- onMount(() => {
- const interval = setInterval(refreshEnvironment, 30000);
- return () => clearInterval(interval);
- });
-
async function refreshEnvironment() {
if (isRefreshing) return;
-
try {
isRefreshing = true;
await invalidateAll();
@@ -52,17 +45,14 @@
async function testConnection() {
if (isTestingConnection) return;
-
try {
isTestingConnection = true;
const result = await environmentManagementAPI.testConnection(environment.id);
-
if (result.status === 'online') {
toast.success('Connection successful');
} else {
toast.error(`Connection failed: ${result.message || 'Unknown error'}`);
}
-
await refreshEnvironment();
} catch (error) {
toast.error('Failed to test connection');
@@ -72,14 +62,33 @@
}
}
- const environmentDisplayName = $derived(environment?.hostname || 'Environment Details');
+ async function pairOrRotate() {
+ if (!bootstrapToken) {
+ toast.error('Bootstrap token is required');
+ return;
+ }
+ try {
+ isPairing = true;
+ await environmentManagementAPI.update(environment.id, { bootstrapToken });
+ toast.success('Agent paired successfully');
+ bootstrapToken = '';
+ await refreshEnvironment();
+ } catch (e) {
+ console.error(e);
+ toast.error('Failed to pair/rotate agent token');
+ } finally {
+ isPairing = false;
+ }
+ }
+
+ const environmentDisplayName = $derived(environment.name);
</script>
<div class="space-y-6 pb-16">
<div class="flex items-center justify-between">
<div class="flex items-center gap-4">
<Button variant="ghost" size="icon" onclick={() => goto('/environments')}>
- <ArrowLeftIcon class="h-4 w-4" />
+ <ArrowLeftIcon class="size-4" />
</Button>
<div>
<h1 class="text-3xl font-bold tracking-tight">{environmentDisplayName}</h1>
@@ -89,17 +98,17 @@
<div class="flex items-center gap-2">
<Button variant="outline" onclick={testConnection} disabled={isTestingConnection}>
{#if isTestingConnection}
- <RefreshCwIcon class="mr-2 h-4 w-4 animate-spin" />
+ <RefreshCwIcon class="mr-2 size-4 animate-spin" />
{:else}
- <TerminalIcon class="mr-2 h-4 w-4" />
+ <TerminalIcon class="mr-2 size-4" />
{/if}
Test Connection
</Button>
<Button onclick={refreshEnvironment} disabled={isRefreshing}>
{#if isRefreshing}
- <RefreshCwIcon class="mr-2 h-4 w-4 animate-spin" />
+ <RefreshCwIcon class="mr-2 size-4 animate-spin" />
{:else}
- <RefreshCwIcon class="mr-2 h-4 w-4" />
+ <RefreshCwIcon class="mr-2 size-4" />
{/if}
Refresh
</Button>
@@ -146,8 +155,8 @@
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
<div class="space-y-4">
<div>
- <Label class="text-muted-foreground text-sm font-medium">Hostname</Label>
- <div class="mt-1 text-lg font-semibold">{environment.hostname}</div>
+ <Label class="text-muted-foreground text-sm font-medium">Name</Label>
+ <div class="mt-1 text-lg font-semibold">{environmentDisplayName}</div>
</div>
<div>
<Label class="text-muted-foreground text-sm font-medium">Status</Label>
@@ -173,24 +182,8 @@
<Label class="text-muted-foreground text-sm font-medium">Environment ID</Label>
<div class="bg-muted mt-1 rounded px-2 py-1 font-mono text-sm">{environment.id}</div>
</div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">Created</Label>
- <div class="mt-1 text-sm">{format(new Date(environment.createdAt), 'PP p')}</div>
- </div>
- {#if environment.updatedAt}
- <div>
- <Label class="text-muted-foreground text-sm font-medium">Last Updated</Label>
- <div class="mt-1 text-sm">{format(new Date(environment.updatedAt), 'PP p')}</div>
- </div>
- {/if}
</div>
</div>
- {#if environment.description}
- <div>
- <Label class="text-muted-foreground text-sm font-medium">Description</Label>
- <div class="mt-1 text-sm">{environment.description}</div>
- </div>
- {/if}
</Card.Content>
</Card.Root>
</div>
@@ -204,21 +197,14 @@
</Card.Title>
</Card.Header>
<Card.Content class="space-y-4">
+ <div>
+ <Label class="text-muted-foreground text-sm font-medium">Name</Label>
+ <div class="mt-1 text-sm">{environmentDisplayName}</div>
+ </div>
<div>
<Label class="text-muted-foreground text-sm font-medium">API URL</Label>
- <div class="bg-muted mt-1 rounded-md px-3 py-2 font-mono text-sm break-all">{environment.apiUrl}</div>
+ <div class="bg-muted mt-1 break-all rounded-md px-3 py-2 font-mono text-sm">{environment.apiUrl}</div>
</div>
- {#if environment.lastSeen}
- <div>
- <Label class="text-muted-foreground text-sm font-medium">Last Seen</Label>
- <div class="mt-1 text-sm">{format(new Date(environment.lastSeen), 'PP p')}</div>
- </div>
- {:else}
- <div>
- <Label class="text-muted-foreground text-sm font-medium">Last Seen</Label>
- <div class="text-muted-foreground mt-1 text-sm">Never</div>
- </div>
- {/if}
<div class="pt-4">
<Button onclick={testConnection} disabled={isTestingConnection} class="w-full">
{#if isTestingConnection}
@@ -232,45 +218,39 @@
</div>
</Card.Content>
</Card.Root>
-
- <Card.Root>
- <Card.Header>
- <Card.Title class="flex items-center gap-2">
- <SettingsIcon class="h-5 w-5" />
- Connection Health
- </Card.Title>
- </Card.Header>
- <Card.Content>
- <div class="space-y-3">
- <div class="flex items-center justify-between">
- <span class="text-sm">Connection Status</span>
- <StatusBadge
- text={environment.status === 'online' ? 'Connected' : 'Disconnected'}
- variant={environment.status === 'online' ? 'green' : 'red'}
- />
- </div>
- <div class="flex items-center justify-between">
- <span class="text-sm">Environment Enabled</span>
- <StatusBadge text={environment.enabled ? 'Yes' : 'No'} variant={environment.enabled ? 'green' : 'gray'} />
- </div>
- </div>
- </Card.Content>
- </Card.Root>
</div>
- {:else if activeSection === 'activity'}
+ {:else if activeSection === 'pairing'}
<div class="space-y-6">
<Card.Root>
<Card.Header>
<Card.Title class="flex items-center gap-2">
- <ActivityIcon class="h-5 w-5" />
- Activity Log
+ <SettingsIcon class="h-5 w-5" />
+ Pair / Rotate Agent Token
</Card.Title>
+ <Card.Description>
+ The token is stored securely on the server and not displayed. Use a Bootstrap Token to pair or rotate.
+ </Card.Description>
</Card.Header>
- <Card.Content>
- <div class="text-muted-foreground py-8 text-center">
- <DatabaseIcon class="mx-auto mb-3 h-12 w-12 opacity-50" />
- <p>Activity logging coming soon</p>
- <p class="text-sm">Environment activity and logs will be displayed here</p>
+ <Card.Content class="space-y-4">
+ <div>
+ <Label class="text-muted-foreground text-sm font-medium">Bootstrap Token</Label>
+ <input
+ class="bg-background focus:ring-primary mt-1 w-full rounded-md border px-3 py-2 text-sm outline-none focus:ring-2"
+ type="password"
+ placeholder="Enter AGENT_BOOTSTRAP_TOKEN"
+ bind:value={bootstrapToken}
+ />
+ </div>
+ <div class="flex gap-2">
+ <Button onclick={pairOrRotate} disabled={isPairing || !bootstrapToken}>
+ {#if isPairing}
+ <RefreshCwIcon class="mr-2 h-4 w-4 animate-spin" />
+ {:else}
+ <SettingsIcon class="mr-2 h-4 w-4" />
+ {/if}
+ Pair / Rotate
+ </Button>
+ <Button variant="outline" onclick={() => (bootstrapToken = '')} disabled={isPairing}>Clear</Button>
</div>
</Card.Content>
</Card.Root>
@@ -280,7 +260,7 @@
</div>
{#if isRefreshing}
- <div class="fixed right-4 bottom-4 flex items-center gap-2 rounded-lg bg-blue-600 px-3 py-2 text-white shadow-lg">
+ <div class="fixed bottom-4 right-4 flex items-center gap-2 rounded-lg bg-blue-600 px-3 py-2 text-white shadow-lg">
<RefreshCwIcon class="h-4 w-4 animate-spin" />
<span class="text-sm">Refreshing...</span>
</div>
diff --git a/frontend/src/routes/environments/[id]/+page.ts b/frontend/src/routes/environments/[id]/+page.ts
index 3a0741f3a..6cee22fa2 100644
--- a/frontend/src/routes/environments/[id]/+page.ts
+++ b/frontend/src/routes/environments/[id]/+page.ts
@@ -1,23 +1,10 @@
import type { PageLoad } from './$types';
import { environmentManagementAPI } from '$lib/services/api';
-import { error } from '@sveltejs/kit';
export const load: PageLoad = async ({ params }) => {
- try {
- const environment = await environmentManagementAPI.get(params.id);
+ const environment = await environmentManagementAPI.get(params.id);
- return {
- environment
- };
- } catch (err) {
- console.error('Failed to load environment:', err);
-
- if (err && typeof err === 'object' && 'status' in err) {
- throw err;
- }
-
- throw error(404, {
- message: err instanceof Error ? err.message : 'Environment not found'
- });
- }
+ return {
+ environment
+ };
};
diff --git a/frontend/src/routes/environments/environment-table.svelte b/frontend/src/routes/environments/environment-table.svelte
index c0e1899f5..11894e257 100644
--- a/frontend/src/routes/environments/environment-table.svelte
+++ b/frontend/src/routes/environments/environment-table.svelte
@@ -9,17 +9,15 @@
import MonitorIcon from '@lucide/svelte/icons/monitor';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import * as Card from '$lib/components/ui/card/index.js';
- import * as Table from '$lib/components/ui/table/index.js';
import { goto } from '$app/navigation';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import { toast } from 'svelte-sonner';
- import { formatDistanceToNow } from 'date-fns';
import { environmentManagementAPI } from '$lib/services/api';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { ColumnSpec } from '$lib/components/arcane-table';
- import type { Environment } from '$lib/stores/environment.store';
+ import type { Environment } from '$lib/types/environment.type';
let {
environments = $bindable(),
@@ -117,18 +115,13 @@
isLoading.testing = false;
}
- function formatLastSeen(lastSeen?: string | null) {
- if (!lastSeen) return 'Never';
- return `${formatDistanceToNow(new Date(lastSeen))} ago`;
- }
-
const columns = [
{ accessorKey: 'id', title: 'ID', hidden: true },
{
- id: 'environment',
- title: 'Environment',
+ id: 'name',
+ title: 'Friendly Name',
sortable: true,
- accessorFn: (row) => row.hostname,
+ accessorFn: (row) => row.name,
cell: EnvironmentCell
},
{
@@ -147,12 +140,6 @@
title: 'Enabled',
sortable: true,
cell: EnabledCell
- },
- {
- accessorKey: 'lastSeen',
- title: 'Last Seen',
- sortable: true,
- cell: LastSeenCell
}
] satisfies ColumnSpec<Environment>[];
</script>
@@ -164,13 +151,13 @@
<MonitorIcon class="text-muted-foreground size-4" />
</div>
<div
- class="border-background absolute -top-1 -right-1 size-3 rounded-full border-2 {item.status === 'online'
+ class="border-background absolute -right-1 -top-1 size-3 rounded-full border-2 {item.status === 'online'
? 'bg-green-500'
: 'bg-red-500'}"
></div>
</div>
<div>
- <div class="font-medium">{item.hostname}</div>
+ <div class="font-medium">{item.name}</div>
<div class="text-muted-foreground font-mono text-xs">{item.id}</div>
</div>
</div>
@@ -188,10 +175,6 @@
<StatusBadge text={Boolean(value) ? 'Enabled' : 'Disabled'} variant={Boolean(value) ? 'green' : 'gray'} />
{/snippet}
-{#snippet LastSeenCell({ value }: { value: unknown })}
- <span class="text-sm">{formatLastSeen((value as string) ?? '')}</span>
-{/snippet}
-
{#snippet RowActions({ item }: { item: Environment })}
<DropdownMenu.Root>
<DropdownMenu.Trigger>
@@ -214,8 +197,8 @@
</DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item
- class="text-red-500 focus:text-red-700!"
- onclick={() => handleDeleteOne(item.id, item.hostname)}
+ variant="destructive"
+ onclick={() => handleDeleteOne(item.id, item.name)}
disabled={isLoading.removing}
>
<Trash2Icon class="size-4" />
diff --git a/frontend/src/routes/images/+page.svelte b/frontend/src/routes/images/+page.svelte
index c499d13d1..321f4e7cf 100644
--- a/frontend/src/routes/images/+page.svelte
+++ b/frontend/src/routes/images/+page.svelte
@@ -10,7 +10,7 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { environmentAPI, imageUpdateAPI } from '$lib/services/api';
+ import { environmentAPI } from '$lib/services/api';
import StatCard from '$lib/components/stat-card.svelte';
import ImageTableNew from './image-table.svelte';
@@ -49,7 +49,7 @@
isLoading.checking = true;
try {
const imageRefs = images.data.map((img) => img.repoTags?.[0] || `image:${img.id}`);
- await imageUpdateAPI.checkMultipleImages(imageRefs);
+ await environmentAPI.checkMultipleImages(imageRefs);
toast.success('Update check completed');
images = await environmentAPI.getImages(requestOptions);
} catch (error) {
diff --git a/frontend/src/routes/images/+page.ts b/frontend/src/routes/images/+page.ts
index 8950d9580..a0adbd390 100644
--- a/frontend/src/routes/images/+page.ts
+++ b/frontend/src/routes/images/+page.ts
@@ -1,4 +1,4 @@
-import { environmentAPI, settingsAPI, systemAPI } from '$lib/services/api';
+import { environmentAPI, settingsAPI } from '$lib/services/api';
import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { PageLoad } from './$types';
diff --git a/scripts/development/create-release.sh b/scripts/development/create-release.sh
index 2f2374411..82da1a001 100755
--- a/scripts/development/create-release.sh
+++ b/scripts/development/create-release.sh
@@ -82,13 +82,13 @@ git add .revision
# Update default ARG VERSION in Dockerfile
echo "Updating Dockerfile ARG VERSION..."
-sed -i.bak "s/^ARG VERSION=.*$/ARG VERSION=\"$NEW_VERSION\"/" Dockerfile && rm Dockerfile.bak
-git add Dockerfile
+sed -i.bak "s/^ARG VERSION=.*$/ARG VERSION=\"$NEW_VERSION\"/" docker/Dockerfile && rm docker/Dockerfile.bak
+git add docker/Dockerfile
# Update default ARG REVISION in Dockerfile
echo "Updating Dockerfile ARG REVISION..."
-sed -i.bak "s/^ARG REVISION=.*$/ARG REVISION=\"$LATEST_REVISION\"/" Dockerfile && rm Dockerfile.bak
-git add Dockerfile
+sed -i.bak "s/^ARG REVISION=.*$/ARG REVISION=\"$LATEST_REVISION\"/" docker/Dockerfile && rm docker/Dockerfile.bak
+git add docker/Dockerfile
# Check if conventional-changelog is installed, if not install it
if ! command -v conventional-changelog &>/dev/null; then
diff --git a/scripts/development/download-compose.sh b/scripts/development/download-compose.sh
new file mode 100644
index 000000000..f9d579a5f
--- /dev/null
+++ b/scripts/development/download-compose.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env sh
+set -eu
+
+# Usage: download-compose.sh <version> <dest-path> [target-arch]
+# version: e.g. 2.39.2
+# dest-path: absolute path where the binary will be written
+# target-arch: buildx TARGETARCH (amd64|arm64). If omitted, inferred.
+
+VERSION="${1:-${COMPOSE_VERSION:-2.39.2}}"
+DEST="${2:-/usr/local/bin/docker-compose}"
+TARGETARCH_IN="${3:-${TARGETARCH:-}}"
+
+# Normalize architecture
+ARCH_GH=""
+case "${TARGETARCH_IN}" in
+ amd64|"") ARCH_GH="x86_64" ;;
+ arm64) ARCH_GH="aarch64" ;;
+ *)
+ # Try uname -m as last resort
+ UNAME_ARCH="$(uname -m 2>/dev/null || echo x86_64)"
+ case "${UNAME_ARCH}" in
+ x86_64|amd64) ARCH_GH="x86_64" ;;
+ aarch64|arm64) ARCH_GH="aarch64" ;;
+ *) ARCH_GH="x86_64" ;;
+ esac
+ ;;
+esac
+
+URL="https://github.com/docker/compose/releases/download/v${VERSION}/docker-compose-linux-${ARCH_GH}"
+
+echo "Downloading docker-compose v${VERSION} (${ARCH_GH}) -> ${DEST}"
+mkdir -p "$(dirname "${DEST}")"
+curl -fsSL --retry 3 --retry-delay 2 -o "${DEST}" "${URL}"
+chmod +x "${DEST}"
+echo "docker-compose installed at ${DEST}"
\ No newline at end of file