Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

29.6 KB
Raw Blame
package api

import (
	"encoding/json"
	"net/http"
	"strings"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
	"github.com/rcourtman/pulse-go-rewrite/internal/config"
	"github.com/rcourtman/pulse-go-rewrite/internal/websocket"
)

const featureAgentProfilesKey = "agent_profiles"

func (r *Router) registerPublicAndAuthRoutes() {
	r.registerAuthSecurityInstallRoutes()
}

func (r *Router) registerMonitoringRoutes(
	guestMetadataHandler *GuestMetadataHandler,
	dockerMetadataHandler *DockerMetadataHandler,
	hostMetadataHandler *HostMetadataHandler,
	infraUpdateHandlers *UpdateDetectionHandlers,
) {
	r.registerMonitoringResourceRoutes(
		guestMetadataHandler,
		dockerMetadataHandler,
		hostMetadataHandler,
		infraUpdateHandlers,
	)
}

func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {
	wrapLegacyHostAlias := func(aliasPath string, next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, req *http.Request) {
			noteLegacyHostAliasUsage(aliasPath)
			next(w, req)
		}
	}

	// Log management routes
	r.mux.HandleFunc("/api/logs/stream", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.logHandlers.HandleStreamLogs)))
	r.mux.HandleFunc("/api/logs/download", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.logHandlers.HandleDownloadBundle)))
	r.mux.HandleFunc("/api/logs/level", func(w http.ResponseWriter, req *http.Request) {
		switch req.Method {
		case http.MethodGet:
			RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.logHandlers.HandleGetLevel))(w, req)
		case http.MethodPost:
			RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.logHandlers.HandleSetLevel))(w, req)
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})
	// Agent scopes constrain token callers. Browser and proxy identities do not
	// have token scopes, so require organization administration for their
	// telemetry writes and agent command acknowledgements.
	r.mux.HandleFunc("/api/agents/docker/report", RequireOrgAdmin(r.config, RequireScope(config.ScopeDockerReport, r.dockerAgentHandlers.HandleReport)))
	r.mux.HandleFunc("/api/agents/kubernetes/report", RequireOrgAdmin(r.config, RequireScope(config.ScopeKubernetesReport, r.kubernetesAgentHandlers.HandleReport)))
	r.mux.HandleFunc("/api/agents/agent/report", RequireOrgAdmin(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleReport)))
	r.mux.HandleFunc("/api/agents/action-runner/credential", RequireAuth(r.config, actionRunnerCredentialRoute(r.config, r.handleIssueActionRunnerCredential, r.handleActivateActionRunnerCredential, r.handleSelfRevokeActionRunnerCredential)))
	r.mux.HandleFunc("/api/agents/action-runner/credential/activation", RequireAuth(r.config, RequireScope(config.ScopeAgentExec, r.handleCancelPendingActionRunnerCredentialActivation)))
	r.mux.HandleFunc("/api/agents/collector/reduce-authority", RequireAuth(r.config, RequireScope(config.ScopeAgentReport, r.handleReduceCollectorAuthority)))
	r.mux.HandleFunc("/api/agents/host/report", wrapLegacyHostAlias("/api/agents/host/report", RequireOrgAdmin(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleReport))))
	r.mux.HandleFunc("/api/agents/agent/lookup", RequireAuth(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleLookup)))
	r.mux.HandleFunc("/api/agents/host/lookup", wrapLegacyHostAlias("/api/agents/host/lookup", RequireAuth(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleLookup))))
	// Uninstall is a collector's self-removal by token. Anything that is not a
	// token takes the administrative removal path inside the handler, so it must
	// be an administrator, as for the unlink and delete routes below.
	r.mux.HandleFunc("/api/agents/agent/uninstall", RequireOrgAdmin(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleUninstall)))
	r.mux.HandleFunc("/api/agents/host/uninstall", wrapLegacyHostAlias("/api/agents/host/uninstall", RequireOrgAdmin(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleUninstall))))
	// SECURITY: Use settings:write (not just host_manage) to prevent compromised host tokens from manipulating other hosts
	r.mux.HandleFunc("/api/agents/agent/unlink", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleUnlink)))
	r.mux.HandleFunc("/api/agents/host/unlink", wrapLegacyHostAlias("/api/agents/host/unlink", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleUnlink))))
	r.mux.HandleFunc("/api/agents/agent/link", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleLink)))
	r.mux.HandleFunc("/api/agents/host/link", wrapLegacyHostAlias("/api/agents/host/link", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleLink))))
	r.mux.HandleFunc("/api/agents/diagnostics", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.handleAgentFleetDiagnostics)))
	// Unified Agent management routes - config endpoint is accessible by agents (GET) and admins (PATCH)
	unifiedAgentManagementCore := func(w http.ResponseWriter, req *http.Request) {
		// Route /api/agents/agent/{id}/config to HandleConfig
		if strings.HasSuffix(req.URL.Path, "/config") {
			// GET is for agents to fetch config (agent config scope)
			// PATCH is for UI to update config (agent_manage scope, admin only)
			if req.Method == http.MethodPatch {
				RequireOrgAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {
					if !ensureScope(w, req, config.ScopeAgentManage) {
						return
					}
					r.unifiedAgentHandlers.HandleConfig(w, req)
				})(w, req)
				return
			}
			// Agent configuration may contain credentials for assigned probes.
			// Token ownership and scope are checked by HandleConfig; session and
			// proxy callers must also have administrative authority.
			RequireOrgAdmin(r.config, r.unifiedAgentHandlers.HandleConfig)(w, req)
			return
		}
		// Route POST /api/agents/agent/{id}/allow-reenroll to HandleAllowReenroll
		if strings.HasSuffix(req.URL.Path, "/allow-reenroll") {
			if req.Method == http.MethodPost {
				RequireOrgAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {
					if !ensureScope(w, req, config.ScopeSettingsWrite) {
						return
					}
					r.unifiedAgentHandlers.HandleAllowReenroll(w, req)
				})(w, req)
				return
			}
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}
		// Route DELETE /api/agents/agent/{id} to HandleDeleteHost
		// SECURITY: Require settings:write (not just host_manage) to prevent compromised host tokens from deleting other hosts
		if req.Method == http.MethodDelete {
			RequireOrgAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {
				if !ensureScope(w, req, config.ScopeSettingsWrite) {
					return
				}
				r.unifiedAgentHandlers.HandleDeleteHost(w, req)
			})(w, req)
			return
		}
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
	r.mux.HandleFunc("/api/agents/agent/", RequireAuth(r.config, unifiedAgentManagementCore))
	r.mux.HandleFunc("/api/agents/host/", wrapLegacyHostAlias("/api/agents/host/", RequireAuth(r.config, unifiedAgentManagementCore)))
	r.mux.HandleFunc("/api/agents/docker/commands/", RequireOrgAdmin(r.config, RequireScope(config.ScopeDockerReport, r.dockerAgentHandlers.HandleCommandAck)))
	r.mux.HandleFunc("/api/agents/docker/runtimes/", RequireOrgAdmin(r.config, RequireScope(config.ScopeDockerManage, r.dockerAgentHandlers.HandleDockerHostActions)))
	r.mux.HandleFunc("/api/agents/docker/containers/update", RequireAdmin(r.config, RequireScope(config.ScopeDockerManage, r.dockerAgentHandlers.HandleContainerUpdate)))
	r.mux.HandleFunc("/api/agents/kubernetes/clusters/", RequireOrgAdmin(r.config, RequireScope(config.ScopeKubernetesManage, r.kubernetesAgentHandlers.HandleClusterActions)))
	r.mux.HandleFunc("/api/diagnostics", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.handleDiagnostics)))
	r.mux.HandleFunc("/api/diagnostics/docker/prepare-token", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.handleDiagnosticsDockerPrepareToken)))
	r.mux.HandleFunc("/api/config", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleConfig)))
	r.mux.HandleFunc("/api/runtime/branding", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.systemSettingsHandler.HandleGetRuntimeBranding)))
	r.mux.HandleFunc("/api/runtime/display", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.systemSettingsHandler.HandleGetRuntimeDisplay)))
	// Update routes
	r.mux.HandleFunc("/api/updates/check", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, updateHandlers.HandleCheckUpdates)))
	r.mux.HandleFunc("/api/updates/apply", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, updateHandlers.HandleApplyUpdate)))
	r.mux.HandleFunc("/api/updates/rollback", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, updateHandlers.HandleRollbackUpdate)))
	r.mux.HandleFunc("/api/updates/status", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, updateHandlers.HandleUpdateStatus)))
	r.mux.HandleFunc("/api/updates/stream", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead,
		retainTokenStreamAuthority(r.config, config.ScopeSettingsRead, true, updateHandlers.HandleUpdateStream))))
	r.mux.HandleFunc("/api/updates/plan", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, updateHandlers.HandleGetUpdatePlan)))
	r.mux.HandleFunc("/api/updates/pro-runtime", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, updateHandlers.HandleCheckProRuntimeSwitch)))
	r.mux.HandleFunc("/api/updates/pro-runtime/apply", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, updateHandlers.HandleApplyProRuntimeSwitch)))
	// Release notes for the running version are readable by any authenticated
	// user (public GitHub data) so the What's New card works for non-admins.
	r.mux.HandleFunc("/api/updates/release-notes", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, updateHandlers.HandleGetReleaseNotes)))
	r.mux.HandleFunc("/api/updates/release-notes/assets/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, updateHandlers.HandleGetReleaseNoteImage)))
	r.mux.HandleFunc("/api/updates/history", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, updateHandlers.HandleListUpdateHistory)))
	r.mux.HandleFunc("/api/updates/history/entry", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, updateHandlers.HandleGetUpdateHistoryEntry)))
	// Config management routes
	r.mux.HandleFunc("/api/config/nodes", func(w http.ResponseWriter, req *http.Request) {
		switch req.Method {
		case http.MethodGet:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.withExternalAgentCapabilityActivity(
				agentcapabilities.ListNodesCapabilityName,
				r.configHandlers.HandleGetNodes,
			)))(w, req)
		case http.MethodPost:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(
				agentcapabilities.AddNodeCapabilityName,
				r.configHandlers.HandleAddNode,
			)))(w, req)
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})
	// Test node configuration endpoint (for new nodes)
	r.mux.HandleFunc("/api/config/nodes/test-config", func(w http.ResponseWriter, req *http.Request) {
		if req.Method == http.MethodPost {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(
				agentcapabilities.TestNodeCredentialsCapabilityName,
				r.configHandlers.HandleTestNodeConfig,
			)))(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	// Test connection endpoint
	r.mux.HandleFunc("/api/config/nodes/test-connection", func(w http.ResponseWriter, req *http.Request) {
		if req.Method == http.MethodPost {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleTestConnection))(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})
	r.mux.HandleFunc("/api/config/nodes/", func(w http.ResponseWriter, req *http.Request) {
		switch req.Method {
		case http.MethodPut:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(
				agentcapabilities.UpdateNodeCapabilityName,
				r.configHandlers.HandleUpdateNode,
			)))(w, req)
		case http.MethodDelete:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(
				agentcapabilities.RemoveNodeCapabilityName,
				r.configHandlers.HandleDeleteNode,
			)))(w, req)
		case http.MethodPost:
			// Handle test endpoint and refresh-cluster endpoint
			if strings.HasSuffix(req.URL.Path, "/test") {
				RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(
					agentcapabilities.TestNodeConnectionCapabilityName,
					r.configHandlers.HandleTestNode,
				)))(w, req)
			} else if strings.HasSuffix(req.URL.Path, "/refresh-cluster") {
				RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(
					agentcapabilities.RefreshNodeClusterMembershipCapabilityName,
					r.configHandlers.HandleRefreshClusterNodes,
				)))(w, req)
			} else {
				http.Error(w, "Not found", http.StatusNotFound)
			}
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	// Unified connections ledger — aggregates PVE/PBS/PMG/VMware/TrueNAS/agent rows.
	r.mux.HandleFunc("/api/connections", func(w http.ResponseWriter, req *http.Request) {
		if r.connectionsHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "connections_unavailable", "Connections service unavailable", nil)
			return
		}
		if req.Method != http.MethodGet {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}
		RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.connectionsHandlers.HandleList))(w, req)
	})
	// Workloads needs source health at the monitoring tier, but the connection
	// ledger above is intentionally administrative. Authentication and
	// monitoring scope wrap the entire handler so unavailable wiring and every
	// other response remain behind the same fail-closed boundary.
	r.mux.HandleFunc("GET /api/runtime/inventory-sources", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, func(w http.ResponseWriter, req *http.Request) {
		if r.connectionsHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "inventory_sources_unavailable", "Inventory source health unavailable", nil)
			return
		}
		r.connectionsHandlers.HandleRuntimeInventorySources(w, req)
	})))

	// Connection address probe — stateless type detection before credential entry.
	r.mux.HandleFunc("/api/connections/probe", func(w http.ResponseWriter, req *http.Request) {
		if r.connectionsHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "connections_unavailable", "Connections service unavailable", nil)
			return
		}
		if req.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}
		RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.connectionsHandlers.HandleProbe))(w, req)
	})

	// Agentless availability target management
	r.mux.HandleFunc("/api/availability-targets", func(w http.ResponseWriter, req *http.Request) {
		if r.availabilityHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "availability_unavailable", "Availability target service unavailable", nil)
			return
		}
		switch req.Method {
		case http.MethodGet:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.availabilityHandlers.HandleList))(w, req)
		case http.MethodPost:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleAdd))(w, req)
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	r.mux.HandleFunc("/api/availability-targets/test", func(w http.ResponseWriter, req *http.Request) {
		if r.availabilityHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "availability_unavailable", "Availability target service unavailable", nil)
			return
		}
		if req.Method == http.MethodPost {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleTestConnection))(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	r.mux.HandleFunc("/api/availability-targets/", func(w http.ResponseWriter, req *http.Request) {
		if r.availabilityHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "availability_unavailable", "Availability target service unavailable", nil)
			return
		}
		if req.Method == http.MethodPost && strings.HasSuffix(strings.Trim(req.URL.Path, "/"), "/test") {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleTestSavedConnection))(w, req)
		} else if req.Method == http.MethodDelete {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleDelete))(w, req)
		} else if req.Method == http.MethodPut {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleUpdate))(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	// TrueNAS connection management
	r.mux.HandleFunc("/api/truenas/connections", func(w http.ResponseWriter, req *http.Request) {
		if r.trueNASHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "truenas_unavailable", "TrueNAS service unavailable", nil)
			return
		}

		switch req.Method {
		case http.MethodGet:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.trueNASHandlers.HandleList))(w, req)
		case http.MethodPost:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandleAdd))(w, req)
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	r.mux.HandleFunc("/api/truenas/connections/test", func(w http.ResponseWriter, req *http.Request) {
		if r.trueNASHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "truenas_unavailable", "TrueNAS service unavailable", nil)
			return
		}

		if req.Method == http.MethodPost {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandleTestConnection))(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	r.mux.HandleFunc("/api/truenas/connections/preview", func(w http.ResponseWriter, req *http.Request) {
		if r.trueNASHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "truenas_unavailable", "TrueNAS service unavailable", nil)
			return
		}

		if req.Method == http.MethodPost {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandlePreviewConnection))(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	r.mux.HandleFunc("/api/truenas/connections/", r.platformConnectionItemRoute("truenas_unavailable", "TrueNAS service unavailable", func() *platformConnectionItemHandlers {
		if r.trueNASHandlers == nil {
			return nil
		}
		return &platformConnectionItemHandlers{
			test:    r.trueNASHandlers.HandleTestSavedConnection,
			preview: r.trueNASHandlers.HandlePreviewSavedConnection,
			delete:  r.trueNASHandlers.HandleDelete,
			update:  r.trueNASHandlers.HandleUpdate,
		}
	}))

	// VMware vCenter connection management
	r.mux.HandleFunc("/api/vmware/connections", func(w http.ResponseWriter, req *http.Request) {
		if r.vmwareHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "vmware_unavailable", "VMware service unavailable", nil)
			return
		}

		switch req.Method {
		case http.MethodGet:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.vmwareHandlers.HandleList))(w, req)
		case http.MethodPost:
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandleAdd))(w, req)
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	r.mux.HandleFunc("/api/vmware/connections/test", func(w http.ResponseWriter, req *http.Request) {
		if r.vmwareHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "vmware_unavailable", "VMware service unavailable", nil)
			return
		}

		if req.Method == http.MethodPost {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandleTestConnection))(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	r.mux.HandleFunc("/api/vmware/connections/preview", func(w http.ResponseWriter, req *http.Request) {
		if r.vmwareHandlers == nil {
			writeErrorResponse(w, http.StatusServiceUnavailable, "vmware_unavailable", "VMware service unavailable", nil)
			return
		}

		if req.Method == http.MethodPost {
			RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandlePreviewConnection))(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	r.mux.HandleFunc("/api/vmware/connections/", r.platformConnectionItemRoute("vmware_unavailable", "VMware service unavailable", func() *platformConnectionItemHandlers {
		if r.vmwareHandlers == nil {
			return nil
		}
		return &platformConnectionItemHandlers{
			test:    r.vmwareHandlers.HandleTestSavedConnection,
			preview: r.vmwareHandlers.HandlePreviewSavedConnection,
			delete:  r.vmwareHandlers.HandleDelete,
			update:  r.vmwareHandlers.HandleUpdate,
		}
	}))

	// Config Profile Routes - Protected by Admin Auth, Settings Scope, and Pro License
	// SECURITY: Require settings:write scope to prevent low-privilege tokens from modifying agent profiles
	// r.configProfileHandler.ServeHTTP implements http.Handler, so we wrap it
	r.mux.Handle("/api/admin/profiles/", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, RequireLicenseFeature(r.licenseHandlers, featureAgentProfilesKey, func(w http.ResponseWriter, req *http.Request) {
		http.StripPrefix("/api/admin/profiles", r.configProfileHandler).ServeHTTP(w, req)
	}))))

	// System settings routes
	r.mux.HandleFunc("/api/config/system", func(w http.ResponseWriter, req *http.Request) {
		switch req.Method {
		case http.MethodGet:
			handler := r.configHandlers.HandleGetSystemSettings
			if r.systemSettingsHandler != nil {
				handler = r.systemSettingsHandler.HandleGetSystemSettings
			}
			RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, handler))(w, req)
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})

	// Mock mode toggle routes
	r.mux.HandleFunc("/api/system/mock-mode", func(w http.ResponseWriter, req *http.Request) {
		switch req.Method {
		case http.MethodGet:
			RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.configHandlers.HandleGetMockMode))(w, req)
		case http.MethodPost, http.MethodPut:
			RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleUpdateMockMode))(w, req)
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})
	// Config export/import routes. These stay globally public so the deliberate
	// no-auth recovery policy can operate; authorizeConfigTransfer is the single
	// fail-closed boundary for every authenticated, hosted, and tenant mode.
	r.mux.HandleFunc("/api/config/export", r.exportLimiter.Middleware(func(w http.ResponseWriter, req *http.Request) {
		if req.Method == http.MethodPost {
			if !r.authorizeConfigTransfer(w, req, configTransferExport) {
				return
			}
			// Encryption can outlive the admitted credential. Keep the existing
			// transfer/recovery policy, but refuse undisclosed backup bytes after
			// token withdrawal or local logout. Import's apply lifetime is separate.
			retainTokenResponseAuthority(r.config, config.ScopeSettingsRead, false, r.configHandlers.HandleExportConfig)(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	}))

	r.mux.HandleFunc("/api/config/import", r.exportLimiter.Middleware(func(w http.ResponseWriter, req *http.Request) {
		if req.Method == http.MethodPost {
			if !r.authorizeConfigTransfer(w, req, configTransferImport) {
				return
			}
			r.configHandlers.HandleImportConfig(w, req)
		} else {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	}))

	// Discovery route

	// Setup script route
	r.mux.HandleFunc("/api/setup-script", r.configHandlers.HandleSetupScript)

	// Generate setup script URL with temporary token (for authenticated users)
	r.mux.HandleFunc("/api/setup-script-url", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleSetupScriptURL)))

	// Generate agent install command with API token (for authenticated users)
	r.mux.HandleFunc("/api/agent-install-command", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleAgentInstallCommand)))

	// Auto-register route for setup scripts
	r.mux.HandleFunc("/api/auto-register", r.configHandlers.HandleAutoRegister)
	r.mux.HandleFunc("/api/auto-unregister", r.configHandlers.HandleAutoUnregister)
	// Discovery endpoint
	// Test endpoint for WebSocket notifications
	// SECURITY: Require settings:write scope for test notifications to prevent unauthenticated broadcasting.
	// The event reaches only the request organization's clients, so its managers and tokens may send it.
	r.mux.HandleFunc("/api/test-notification", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, func(w http.ResponseWriter, req *http.Request) {
		if req.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		// Send a test auto-registration notification
		r.wsHub.BroadcastMessageToTenant(GetOrgID(req.Context()), websocket.Message{
			Type: "node_auto_registered",
			Data: map[string]interface{}{
				"type":     "pve",
				"host":     "test-node.example.com",
				"name":     "Test Node",
				"tokenId":  "test-token",
				"hasToken": true,
			},
			Timestamp: time.Now().Format(time.RFC3339),
		})

		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(map[string]string{"status": "notification sent"})
	})))
	r.mux.HandleFunc("/api/system/settings", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.systemSettingsHandler.HandleGetSystemSettings)))
	r.mux.HandleFunc("/api/system/settings/telemetry-preview", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.systemSettingsHandler.HandleGetTelemetryPreview)))
	r.mux.HandleFunc("/api/system/settings/update", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.systemSettingsHandler.HandleUpdateSystemSettings)))
	r.mux.HandleFunc("/api/system/settings/telemetry-reset-id", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.systemSettingsHandler.HandleResetTelemetryID)))
	r.mux.HandleFunc("/api/system/ssh-config", r.handleSSHConfig)
	r.mux.HandleFunc("/api/system/verify-temperature-ssh", r.handleVerifyTemperatureSSH)

	// Cluster agent deployment routes
	if r.deployHandlers != nil {
		r.mux.HandleFunc("/api/clusters/", func(w http.ResponseWriter, req *http.Request) {
			path := req.URL.Path
			switch {
			case strings.HasSuffix(path, "/agent-deploy/candidates"):
				RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleCandidates))(w, req)
			case strings.HasSuffix(path, "/agent-deploy/preflights"):
				RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.deployHandlers.HandleCreatePreflight))(w, req)
			case strings.HasSuffix(path, "/agent-deploy/jobs"):
				RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.deployHandlers.HandleCreateJob))(w, req)
			default:
				http.Error(w, "Not found", http.StatusNotFound)
			}
		})
		r.mux.HandleFunc("/api/agents/agent/enroll",
			RequireAuth(r.config, RequireScope(config.ScopeAgentEnroll, r.deployHandlers.HandleEnroll)))
		r.mux.HandleFunc("/api/agents/host/enroll",
			wrapLegacyHostAlias("/api/agents/host/enroll", RequireAuth(r.config, RequireScope(config.ScopeAgentEnroll, r.deployHandlers.HandleEnroll))))

		r.mux.HandleFunc("/api/agent-deploy/preflights/", func(w http.ResponseWriter, req *http.Request) {
			path := req.URL.Path
			switch {
			case strings.HasSuffix(path, "/events"):
				RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead,
					retainTokenStreamAuthority(r.config, config.ScopeSettingsRead, false, r.deployHandlers.HandlePreflightEvents)))(w, req)
			default:
				RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleGetPreflight))(w, req)
			}
		})

		r.mux.HandleFunc("/api/agent-deploy/jobs/", func(w http.ResponseWriter, req *http.Request) {
			path := req.URL.Path
			switch {
			case strings.HasSuffix(path, "/events"):
				RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead,
					retainTokenStreamAuthority(r.config, config.ScopeSettingsRead, false, r.deployHandlers.HandleJobEvents)))(w, req)
			case strings.HasSuffix(path, "/cancel"):
				RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.deployHandlers.HandleCancelJob))(w, req)
			case strings.HasSuffix(path, "/retry"):
				RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.deployHandlers.HandleRetryJob))(w, req)
			default:
				RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleGetJob))(w, req)
			}
		})
	}
}

func (r *Router) registerAIRelayRoutes() {
	r.registerAIRelayRoutesGroup()
}

func (r *Router) registerOrgLicenseRoutes(orgHandlers *OrgHandlers, rbacHandlers *RBACHandlers, auditHandlers *AuditHandlers) {
	r.registerOrgLicenseRoutesGroup(orgHandlers, rbacHandlers, auditHandlers)
}