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.

Fix setup-script teardown symmetry

rcourtman2b618c8eaa4e
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index cf2b3b82e8..569a088104 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -127,6 +127,12 @@ an add-only capacity posture.
the one-time `authToken` only and must not also send the long-lived
`X-API-Token` header. The header-backed `agent:report` fallback exists only
for update-only re-registration when setup-token fetch is unavailable.
+ That same lifecycle-owned setup path also owns script teardown behavior:
+ rerunning the governed setup script in remove mode must call canonical
+ `/api/auto-unregister` with `source:"script"` before local credentials are
+ deleted, and the short recent-setup-token grace window must remain valid for
+ that follow-up uninstall so operators can immediately back out a reviewed
+ script-managed Proxmox setup without leaving a stale node record in Pulse.
That same shared `internal/api/` adjacency does not transfer ownership of
Patrol quickstart bootstrap or mobile Patrol-provider bridging:
`internal/api/ai_handlers.go` and `internal/api/chat_service_adapter.go`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index fc54b30b44..f884e4e5b3 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -131,6 +131,7 @@ Own canonical runtime payload shapes between backend and frontend.
That same shared boundary also owns reachable-host selection truth for canonical Proxmox registration: runtime callers may propose ordered `candidateHosts`, but the API contract must persist and echo the first candidate Pulse can actually reach instead of freezing the caller's rejected first preference into the stored node endpoint.
That same canonical payload contract also owns strict-TLS truth for that selected host: `/api/auto-register` may only persist `VerifySSL=true` when Pulse actually captured a certificate fingerprint for the selected candidate, and it must not pretend public-CA verification is safe after every candidate fingerprint probe failed.
That same contract now owns stale-marker verification as well: setup-token-authenticated `checkRegistration` requests may omit token completion fields and must answer `{registered:boolean}` from canonical candidate-host matching so runtime repair can distinguish real registrations from stale local marker files without rotating tokens first.
+ That same shared setup contract also owns teardown symmetry for script-managed Proxmox nodes: `/api/auto-unregister` must accept the canonical `type`, normalized `host`, explicit `serverName`, optional canonical `tokenId`, request-body `authToken`, and `source:"script"` payload, and it must answer the same canonical success envelope on both real removals and idempotent no-op reruns so browser/runtime callers do not invent a second uninstall vocabulary.
37. `internal/api/enterprise_extension_rbac_admin.go` shared with `organization-settings`: RBAC admin extension endpoints are both an organization settings control surface and a canonical API payload contract boundary.
38. `internal/api/licensing_bridge.go` shared with `cloud-paid`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.
39. `internal/api/licensing_handlers.go` shared with `cloud-paid`: commercial licensing handlers carry both API payload contract and cloud-paid entitlement boundary ownership.
@@ -235,6 +236,7 @@ the canonical monitored-system blocked payload.
That same shared token contract also owns audit scope separation: audit event, verification, summary, export, and unified action/export audit reads must require the dedicated `audit:read` scope instead of reusing broader monitoring or settings-read token grants.
11. Add or change infrastructure operations token generation, lookup, assignment, the pure unified-agent inventory/install model, the split infrastructure install state owner, the split direct-node/discovery infrastructure settings owners, the shared infrastructure-operations state provider/context shell, and install presentation through `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, and `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`. Phase 9 retired the InfrastructureOperationsController shell and the useInfrastructureReportingState reporting path; they must not be reintroduced, and aggregator-backed reporting reads are owned by `frontend-modern/src/components/Settings/useConnectionsLedger.ts` under the frontend-primitives contract.
That same governed infrastructure-operations API boundary also owns discovery polling activation: the shared discovery runtime may only poll `/api/discover` while the settings shell has the `infrastructure-connections` route active, so route-level IA changes cannot silently keep discovery traffic alive on unrelated systems or install screens.
+ That same governed setup/install boundary also owns uninstall convergence: when a script-managed Proxmox node removes its local Pulse credentials, the canonical `/api/auto-unregister` API must remove the matching stored node immediately and emit the same discovery/node-deleted refresh semantics as manual deletion, so the infrastructure sources table does not keep a stale active row until the next failed poll.
12. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.
13. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.
14. Keep Patrol status transport semantics explicit in that same AI handler layer: the Patrol status endpoint must carry machine-readable runtime availability such as blocked, running, disabled, active, or unavailable rather than asking frontend consumers to infer operator state from stale summaries or run history.
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 7fd8f8b908..be40f12ddc 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -150,6 +150,11 @@ regression protection.
2. Add query-plan guardrails for DB-backed hot paths
3. Optimize hot paths only when backed by benchmarks or proven query issues
4. Keep shared auth gating in `internal/api/router.go` cheap and local: pre-auth quick-setup and recovery routing may short-circuit on loopback/session/token checks, but they must not trigger chart, metrics, or broad persistence fan-out on the protected request hot path.
+ The same rule applies to public setup-script lifecycle routes: `/api/auto-register`
+ and `/api/auto-unregister` may bypass the global auth wall so their handlers can
+ validate request-body setup tokens, but the router-level public-path check must
+ stay O(1) and must not front-run persistence loads, monitor refresh, or other
+ teardown/register side effects before the canonical handler owns the request.
5. Extend dashboard hot-path filter, sort, grouping, and stats math through `frontend-modern/src/components/Dashboard/workloadSelectors.ts`, and extend workload identity, discovery routing, and node-topology helpers through `frontend-modern/src/components/Dashboard/workloadTopology.ts`, rather than duplicating selector or topology logic in `frontend-modern/src/components/Dashboard/Dashboard.tsx`
6. Normalize dashboard workload view-mode aliases through `frontend-modern/src/utils/workloads.ts` instead of keeping local URL/storage parsing in `frontend-modern/src/components/Dashboard/Dashboard.tsx`
7. Deduplicate dashboard workload rows by canonical workload ID from `frontend-modern/src/utils/workloads.ts` rather than via local pass-through wrappers in `frontend-modern/src/components/Dashboard/Dashboard.tsx`
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 9201e16847..8c293ed28a 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -168,6 +168,12 @@ querying, and the operator-facing storage health presentation layer.
surfaces may reflect zero-delta or removal-only monitored-system previews
for disabled TrueNAS and VMware connections, but they must not reinterpret
those responses as active counted storage capacity.
+ That same shared helper boundary also owns script teardown symmetry:
+ `/api/auto-unregister` must remove the matching script-managed PVE/PBS node
+ immediately, return the canonical success/noop envelope, and trigger the
+ same discovery-refresh plus node-deleted websocket side effects as a manual
+ delete so adjacent recovery/storage surfaces do not retain stale provider
+ context after Pulse credentials have been removed from the host.
14. Preserve canonical /api/auto-register DHCP continuity in those shared helpers so a PVE or PBS node that reruns registration from a new IP with the same canonical node name and deterministic Pulse-managed token identity updates in place instead of duplicating the inventory record.
That same shared helper boundary now also owns runtime-side Proxmox
`candidateHosts` selection from Pulse's network view: storage and
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.go
index d4cb1339f4..7a45c9053f 100644
--- a/internal/api/config_handlers.go
+++ b/internal/api/config_handlers.go
@@ -181,6 +181,15 @@ type SetupTokenRecord struct {
OrgID string // Organization ID creating this code
}
+// RecentSetupTokenRecord preserves minimal identity metadata for the short
+// follow-up grace window after a setup token has been consumed.
+type RecentSetupTokenRecord struct {
+ ExpiresAt time.Time
+ NodeType string
+ Host string
+ OrgID string
+}
+
// ConfigHandlers handles configuration-related API endpoints
type ConfigHandlers struct {
stateMu sync.RWMutex
@@ -196,9 +205,9 @@ type ConfigHandlers struct {
mockModeChanged func(bool)
wsHub *websocket.Hub
guestMetadataHandler *GuestMetadataHandler
- setupTokens map[string]*SetupTokenRecord // Map of token hash -> setup token details
- recentSetupTokens map[string]time.Time // Temporary map for recently used setup tokens (grace period)
- codeMutex sync.RWMutex // Mutex for thread-safe code access
+ setupTokens map[string]*SetupTokenRecord // Map of token hash -> setup token details
+ recentSetupTokens map[string]RecentSetupTokenRecord // Temporary map for recently used setup tokens (grace period)
+ codeMutex sync.RWMutex // Mutex for thread-safe code access
clusterDetectMutex sync.Mutex
lastClusterDetection map[string]time.Time
recentAutoRegistered map[string]time.Time
@@ -237,7 +246,7 @@ func NewConfigHandlers(mtp *config.MultiTenantPersistence, mtm *monitoring.Multi
wsHub: wsHub,
guestMetadataHandler: guestMetadataHandler,
setupTokens: make(map[string]*SetupTokenRecord),
- recentSetupTokens: make(map[string]time.Time),
+ recentSetupTokens: make(map[string]RecentSetupTokenRecord),
lastClusterDetection: make(map[string]time.Time),
recentAutoRegistered: make(map[string]time.Time),
}
@@ -372,8 +381,8 @@ func (h *ConfigHandlers) cleanupExpiredSetupTokens() {
log.Debug().Bool("was_used", tokenRecord.Used).Msg("Cleaned up setup token")
}
}
- for tokenHash, expiresAt := range h.recentSetupTokens {
- if now.After(expiresAt) {
+ for tokenHash, recentRecord := range h.recentSetupTokens {
+ if now.After(recentRecord.ExpiresAt) {
delete(h.recentSetupTokens, tokenHash)
}
}
@@ -381,6 +390,35 @@ func (h *ConfigHandlers) cleanupExpiredSetupTokens() {
}
}
+func recentSetupTokenGraceExpiry(record *SetupTokenRecord, now time.Time) time.Time {
+ graceExpiry := now.Add(1 * time.Minute)
+ if record != nil && !record.ExpiresAt.IsZero() && record.ExpiresAt.Before(graceExpiry) {
+ graceExpiry = record.ExpiresAt
+ }
+ return graceExpiry
+}
+
+func buildRecentSetupTokenRecord(record *SetupTokenRecord, expiresAt time.Time) RecentSetupTokenRecord {
+ recentRecord := RecentSetupTokenRecord{
+ ExpiresAt: expiresAt,
+ }
+ if record == nil {
+ return recentRecord
+ }
+ recentRecord.NodeType = strings.TrimSpace(record.NodeType)
+ recentRecord.Host = strings.TrimSpace(record.Host)
+ recentRecord.OrgID = strings.TrimSpace(record.OrgID)
+ return recentRecord
+}
+
+func normalizeSetupTokenOrgID(orgID string) string {
+ trimmed := strings.TrimSpace(orgID)
+ if trimmed == "" {
+ return "default"
+ }
+ return trimmed
+}
+
// ValidateSetupToken checks whether the provided temporary setup token is still valid.
func (h *ConfigHandlers) ValidateSetupToken(token string) bool {
if token == "" {
@@ -399,7 +437,7 @@ func (h *ConfigHandlers) ValidateSetupToken(token string) bool {
}
}
- if expiresAt, ok := h.recentSetupTokens[tokenHash]; ok && now.Before(expiresAt) {
+ if recentRecord, ok := h.recentSetupTokens[tokenHash]; ok && now.Before(recentRecord.ExpiresAt) {
return true
}
@@ -414,10 +452,7 @@ func (h *ConfigHandlers) ValidateSetupTokenForOrg(token, orgID string) bool {
return false
}
- requestOrgID := strings.TrimSpace(orgID)
- if requestOrgID == "" {
- requestOrgID = "default"
- }
+ requestOrgID := normalizeSetupTokenOrgID(orgID)
tokenHash := internalauth.HashAPIToken(token)
now := time.Now()
@@ -426,18 +461,23 @@ func (h *ConfigHandlers) ValidateSetupTokenForOrg(token, orgID string) bool {
defer h.codeMutex.RUnlock()
if tokenRecord, exists := h.setupTokens[tokenHash]; exists {
- if tokenRecord.Used || !now.Before(tokenRecord.ExpiresAt) {
+ tokenOrgID := normalizeSetupTokenOrgID(tokenRecord.OrgID)
+ if tokenRecord.Used {
+ if recentRecord, ok := h.recentSetupTokens[tokenHash]; ok && now.Before(recentRecord.ExpiresAt) {
+ return normalizeSetupTokenOrgID(recentRecord.OrgID) == requestOrgID
+ }
return false
}
- tokenOrgID := strings.TrimSpace(tokenRecord.OrgID)
- if tokenOrgID == "" {
- tokenOrgID = "default"
+ if !now.Before(tokenRecord.ExpiresAt) {
+ return false
}
return tokenOrgID == requestOrgID
}
- // Recent setup token grace entries are intentionally not accepted here
- // because they do not carry org binding information.
+ if recentRecord, ok := h.recentSetupTokens[tokenHash]; ok && now.Before(recentRecord.ExpiresAt) {
+ return normalizeSetupTokenOrgID(recentRecord.OrgID) == requestOrgID
+ }
+
return false
}
@@ -1730,6 +1770,11 @@ func (h *ConfigHandlers) HandleAutoRegister(w http.ResponseWriter, r *http.Reque
h.handleAutoRegister(w, r)
}
+// HandleAutoUnregister receives teardown requests from the setup script and removes matching nodes.
+func (h *ConfigHandlers) HandleAutoUnregister(w http.ResponseWriter, r *http.Request) {
+ h.handleAutoUnregister(w, r)
+}
+
// HandleAgentInstallCommand generates an API token and install command for agent-based Proxmox setup.
func (h *ConfigHandlers) HandleAgentInstallCommand(w http.ResponseWriter, r *http.Request) {
h.handleAgentInstallCommand(w, r)
diff --git a/internal/api/config_handlers_auto_register_test.go b/internal/api/config_handlers_auto_register_test.go
index 9858be9769..288448ada2 100644
--- a/internal/api/config_handlers_auto_register_test.go
+++ b/internal/api/config_handlers_auto_register_test.go
@@ -73,6 +73,43 @@ func TestHandleAutoRegisterRejectsWithoutAuth(t *testing.T) {
}
}
+func TestHandleAutoUnregisterRejectsWithoutAuth(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+
+ reqBody := AutoUnregisterRequest{
+ Type: "pve",
+ Host: "https://pve.local:8006",
+ TokenID: "pulse-monitor@pve!pulse-pve-local",
+ ServerName: "pve.local",
+ Source: "script",
+ }
+
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("failed to marshal request: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-unregister", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+
+ handler.HandleAutoUnregister(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("expected status 401, got %d, body=%s", rec.Code, rec.Body.String())
+ }
+ if body := rec.Body.String(); body != "Pulse setup token required\n" {
+ t.Fatalf("body = %q, want missing-auth guidance", body)
+ }
+}
+
func TestHandleAutoRegisterRejectsInvalidSetupToken(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", tempDir)
@@ -166,6 +203,133 @@ func TestHandleAutoRegisterAcceptsWithSetupToken(t *testing.T) {
}
}
+func TestHandleAutoUnregisterAcceptsRecentSetupTokenAndRemovesMatchingPVEInstance(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ PVEInstances: []config.PVEInstance{{
+ Name: "pve.local",
+ Host: "https://pve.local:8006",
+ TokenName: "pulse-monitor@pve!pulse-pve-local",
+ Source: "script",
+ }},
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+
+ const tokenValue = "TEMP-TOKEN-REMOVE"
+ tokenHash := internalauth.HashAPIToken(tokenValue)
+ handler.codeMutex.Lock()
+ handler.setupTokens[tokenHash] = &SetupTokenRecord{
+ ExpiresAt: time.Now().Add(5 * time.Minute),
+ Used: true,
+ NodeType: "pve",
+ OrgID: "default",
+ }
+ handler.recentSetupTokens[tokenHash] = RecentSetupTokenRecord{
+ ExpiresAt: time.Now().Add(1 * time.Minute),
+ NodeType: "pve",
+ OrgID: "default",
+ }
+ handler.codeMutex.Unlock()
+
+ reqBody := AutoUnregisterRequest{
+ Type: "pve",
+ Host: "https://pve.local:8006",
+ TokenID: "pulse-monitor@pve!pulse-pve-local",
+ ServerName: "pve.local",
+ AuthToken: tokenValue,
+ Source: "script",
+ }
+
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("failed to marshal request: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-unregister", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+
+ handler.HandleAutoUnregister(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status 200, got %d, body=%s", rec.Code, rec.Body.String())
+ }
+ if len(cfg.PVEInstances) != 0 {
+ t.Fatalf("expected PVE instance to be removed, got %d remaining", len(cfg.PVEInstances))
+ }
+
+ var resp AutoUnregisterResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to decode response: %v", err)
+ }
+ if !resp.Removed {
+ t.Fatalf("removed = false, want true")
+ }
+ if resp.Action != "remove_connection" {
+ t.Fatalf("action = %q, want remove_connection", resp.Action)
+ }
+}
+
+func TestHandleAutoUnregisterIsIdempotentWhenNodeAlreadyMissing(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+
+ const tokenValue = "TEMP-TOKEN-NOOP"
+ tokenHash := internalauth.HashAPIToken(tokenValue)
+ handler.codeMutex.Lock()
+ handler.setupTokens[tokenHash] = &SetupTokenRecord{
+ ExpiresAt: time.Now().Add(5 * time.Minute),
+ NodeType: "pve",
+ OrgID: "default",
+ }
+ handler.codeMutex.Unlock()
+
+ reqBody := AutoUnregisterRequest{
+ Type: "pve",
+ Host: "https://pve.local:8006",
+ TokenID: "pulse-monitor@pve!pulse-pve-local",
+ ServerName: "pve.local",
+ AuthToken: tokenValue,
+ Source: "script",
+ }
+
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("failed to marshal request: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-unregister", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+
+ handler.HandleAutoUnregister(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status 200, got %d, body=%s", rec.Code, rec.Body.String())
+ }
+
+ var resp AutoUnregisterResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to decode response: %v", err)
+ }
+ if resp.Removed {
+ t.Fatalf("removed = true, want false")
+ }
+ if resp.Action != "noop" {
+ t.Fatalf("action = %q, want noop", resp.Action)
+ }
+}
+
func TestHandleAutoRegisterCheckRegistrationUsesCanonicalCandidateHosts(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", tempDir)
diff --git a/internal/api/config_handlers_pve_user_test.go b/internal/api/config_handlers_pve_user_test.go
index 4fc14af816..c2613242c6 100644
--- a/internal/api/config_handlers_pve_user_test.go
+++ b/internal/api/config_handlers_pve_user_test.go
@@ -620,7 +620,7 @@ func TestValidateSetupToken(t *testing.T) {
t.Run("empty token returns false", func(t *testing.T) {
h := &ConfigHandlers{
setupTokens: make(map[string]*SetupTokenRecord),
- recentSetupTokens: make(map[string]time.Time),
+ recentSetupTokens: make(map[string]RecentSetupTokenRecord),
}
if h.ValidateSetupToken("") {
@@ -639,7 +639,7 @@ func TestValidateSetupToken(t *testing.T) {
Used: false,
},
},
- recentSetupTokens: make(map[string]time.Time),
+ recentSetupTokens: make(map[string]RecentSetupTokenRecord),
}
if !h.ValidateSetupToken(token) {
@@ -658,7 +658,7 @@ func TestValidateSetupToken(t *testing.T) {
Used: false,
},
},
- recentSetupTokens: make(map[string]time.Time),
+ recentSetupTokens: make(map[string]RecentSetupTokenRecord),
}
if h.ValidateSetupToken(token) {
@@ -677,7 +677,7 @@ func TestValidateSetupToken(t *testing.T) {
Used: true, // Already used
},
},
- recentSetupTokens: make(map[string]time.Time),
+ recentSetupTokens: make(map[string]RecentSetupTokenRecord),
}
if h.ValidateSetupToken(token) {
@@ -691,8 +691,8 @@ func TestValidateSetupToken(t *testing.T) {
h := &ConfigHandlers{
setupTokens: make(map[string]*SetupTokenRecord),
- recentSetupTokens: map[string]time.Time{
- tokenHash: time.Now().Add(1 * time.Hour), // Valid for another hour
+ recentSetupTokens: map[string]RecentSetupTokenRecord{
+ tokenHash: {ExpiresAt: time.Now().Add(1 * time.Hour)}, // Valid for another hour
},
}
@@ -707,8 +707,8 @@ func TestValidateSetupToken(t *testing.T) {
h := &ConfigHandlers{
setupTokens: make(map[string]*SetupTokenRecord),
- recentSetupTokens: map[string]time.Time{
- tokenHash: time.Now().Add(-1 * time.Hour), // Expired
+ recentSetupTokens: map[string]RecentSetupTokenRecord{
+ tokenHash: {ExpiresAt: time.Now().Add(-1 * time.Hour)}, // Expired
},
}
@@ -720,7 +720,7 @@ func TestValidateSetupToken(t *testing.T) {
t.Run("non-existent token returns false", func(t *testing.T) {
h := &ConfigHandlers{
setupTokens: make(map[string]*SetupTokenRecord),
- recentSetupTokens: make(map[string]time.Time),
+ recentSetupTokens: make(map[string]RecentSetupTokenRecord),
}
if h.ValidateSetupToken("non-existent-token") {
@@ -739,8 +739,8 @@ func TestValidateSetupToken(t *testing.T) {
Used: false,
},
},
- recentSetupTokens: map[string]time.Time{
- tokenHash: time.Now().Add(1 * time.Hour),
+ recentSetupTokens: map[string]RecentSetupTokenRecord{
+ tokenHash: {ExpiresAt: time.Now().Add(1 * time.Hour)},
},
}
@@ -763,7 +763,7 @@ func TestValidateSetupTokenForOrg(t *testing.T) {
OrgID: "org-a",
},
},
- recentSetupTokens: make(map[string]time.Time),
+ recentSetupTokens: make(map[string]RecentSetupTokenRecord),
}
if !h.ValidateSetupTokenForOrg(token, "org-a") {
@@ -773,3 +773,26 @@ func TestValidateSetupTokenForOrg(t *testing.T) {
t.Fatal("expected org-bound token to fail for different org")
}
}
+
+func TestValidateSetupTokenForOrg_AllowsRecentTokenForMatchingOrg(t *testing.T) {
+ token := "recent-org-bound-token-12345"
+ tokenHash := auth.HashAPIToken(token)
+
+ h := &ConfigHandlers{
+ setupTokens: make(map[string]*SetupTokenRecord),
+ recentSetupTokens: map[string]RecentSetupTokenRecord{
+ tokenHash: {
+ ExpiresAt: time.Now().Add(1 * time.Hour),
+ OrgID: "org-a",
+ NodeType: "pve",
+ },
+ },
+ }
+
+ if !h.ValidateSetupTokenForOrg(token, "org-a") {
+ t.Fatal("expected recent org-bound token to validate for matching org")
+ }
+ if h.ValidateSetupTokenForOrg(token, "org-b") {
+ t.Fatal("expected recent org-bound token to fail for different org")
+ }
+}
diff --git a/internal/api/config_handlers_setup_script_test.go b/internal/api/config_handlers_setup_script_test.go
index 67716bc244..d3bce38e9c 100644
--- a/internal/api/config_handlers_setup_script_test.go
+++ b/internal/api/config_handlers_setup_script_test.go
@@ -363,6 +363,39 @@ func TestPVESetupScript_RemovesDiscoveredOldTokensFromBothUsers(t *testing.T) {
}
}
+func TestPVESetupScript_RemovesMatchingPulseConnectionBeforeLocalCleanup(t *testing.T) {
+ tempDir := t.TempDir()
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ }
+
+ handlers := newTestConfigHandlers(t, cfg)
+
+ req := httptest.NewRequest(http.MethodGet,
+ "/api/setup-script?type=pve&host=https://node.example.internal:8006&pulse_url=https://pulse.example.com:7655&setup_token=deadbeefdeadbeefdeadbeefdeadbeef",
+ nil,
+ )
+ rr := httptest.NewRecorder()
+
+ handlers.HandleSetupScript(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected 200 OK, got %d (%s)", rr.Code, rr.Body.String())
+ }
+
+ script := rr.Body.String()
+ if !containsString(script, `echo " • Removing Pulse connection from server..."`) {
+ t.Fatalf("expected teardown script to announce Pulse-side removal, got: %s", truncate(script, 900))
+ }
+ if !containsString(script, `curl -fsS -X POST "$PULSE_URL/api/auto-unregister"`) {
+ t.Fatalf("expected teardown script to use canonical /api/auto-unregister endpoint, got: %s", truncate(script, 900))
+ }
+ if !containsString(script, `"tokenId":"'"$PULSE_TOKEN_ID"'"`) {
+ t.Fatalf("expected teardown payload to bind the canonical token id, got: %s", truncate(script, 900))
+ }
+}
+
func TestPVESetupScript_UsesCanonicalTokenPrefixForCleanupDiscovery(t *testing.T) {
tempDir := t.TempDir()
cfg := &config.Config{
diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.go
index 3e41a77262..69a349bc75 100644
--- a/internal/api/config_setup_handlers.go
+++ b/internal/api/config_setup_handlers.go
@@ -286,6 +286,30 @@ type AutoRegisterResponse struct {
TokenValue string `json:"tokenValue,omitempty"`
}
+// AutoUnregisterRequest represents a request from the setup script to tear down
+// a script-managed node connection after local credentials have been removed.
+type AutoUnregisterRequest struct {
+ Type string `json:"type"` // "pve" or "pbs"
+ Host string `json:"host"` // The canonical node host URL
+ TokenID string `json:"tokenId,omitempty"` // Full token ID like pulse-monitor@pve!pulse-token
+ ServerName string `json:"serverName,omitempty"` // Hostname or IP
+ AuthToken string `json:"authToken,omitempty"` // One-time setup token from the setup flow
+ Source string `json:"source,omitempty"` // Must be "script"
+}
+
+// AutoUnregisterResponse is the canonical success shape for /api/auto-unregister.
+type AutoUnregisterResponse struct {
+ Status string `json:"status"`
+ Message string `json:"message"`
+ Action string `json:"action"`
+ Type string `json:"type"`
+ Source string `json:"source"`
+ Host string `json:"host"`
+ NodeID string `json:"nodeId,omitempty"`
+ NodeName string `json:"nodeName,omitempty"`
+ Removed bool `json:"removed"`
+}
+
func isCanonicalAutoRegisterType(nodeType string) bool {
switch strings.TrimSpace(nodeType) {
case "pve", "pbs":
@@ -453,6 +477,202 @@ func canonicalAutoRegisterSuccessMessage(nodeName string, host string) string {
return fmt.Sprintf("Node %s registered successfully at %s", trimmedNodeName, trimmedHost)
}
+func canonicalAutoUnregisterMissingFieldsMessage(typeValue string, host string, serverName string) string {
+ missing := make([]string, 0, 3)
+ if strings.TrimSpace(typeValue) == "" {
+ missing = append(missing, "type")
+ }
+ if strings.TrimSpace(host) == "" {
+ missing = append(missing, "host")
+ }
+ if strings.TrimSpace(serverName) == "" {
+ missing = append(missing, "serverName")
+ }
+ if len(missing) == 0 {
+ return "Missing required canonical auto-unregister fields"
+ }
+ return "Missing required canonical auto-unregister fields: " + strings.Join(missing, ", ")
+}
+
+func canonicalAutoUnregisterSuccessMessage(nodeName string, host string, removed bool) string {
+ if !removed {
+ return fmt.Sprintf("No matching node is currently configured for %s", strings.TrimSpace(host))
+ }
+ trimmedNodeName := strings.TrimSpace(nodeName)
+ trimmedHost := strings.TrimSpace(host)
+ if trimmedNodeName == "" {
+ return fmt.Sprintf("Node removed successfully from %s", trimmedHost)
+ }
+ if trimmedHost == "" {
+ return fmt.Sprintf("Node %s removed successfully", trimmedNodeName)
+ }
+ return fmt.Sprintf("Node %s removed successfully from %s", trimmedNodeName, trimmedHost)
+}
+
+func buildCanonicalAutoUnregisterResponse(req *AutoUnregisterRequest, host string, actualName string, removed bool) AutoUnregisterResponse {
+ action := "noop"
+ if removed {
+ action = "remove_connection"
+ }
+ return AutoUnregisterResponse{
+ Status: "success",
+ Message: canonicalAutoUnregisterSuccessMessage(actualName, host, removed),
+ Action: action,
+ Type: strings.TrimSpace(req.Type),
+ Source: strings.TrimSpace(req.Source),
+ Host: strings.TrimSpace(host),
+ NodeID: strings.TrimSpace(actualName),
+ NodeName: strings.TrimSpace(actualName),
+ Removed: removed,
+ }
+}
+
+func (h *ConfigHandlers) authenticateSetupScriptTeardownRequest(r *http.Request, nodeType string, authToken string) (*http.Request, bool) {
+ setupToken := strings.TrimSpace(authToken)
+ if setupToken == "" {
+ return r, false
+ }
+
+ requestOrgID := GetOrgID(r.Context())
+ if !h.ValidateSetupTokenForOrg(setupToken, requestOrgID) {
+ return r, false
+ }
+
+ tokenHash := internalauth.HashAPIToken(setupToken)
+ now := time.Now()
+
+ h.codeMutex.Lock()
+ defer h.codeMutex.Unlock()
+
+ record, exists := h.setupTokens[tokenHash]
+ if exists {
+ if strings.TrimSpace(record.NodeType) != "" && strings.TrimSpace(record.NodeType) != strings.TrimSpace(nodeType) {
+ return r, false
+ }
+ if !record.Used && now.Before(record.ExpiresAt) {
+ record.Used = true
+ graceExpiry := recentSetupTokenGraceExpiry(record, now)
+ h.recentSetupTokens[tokenHash] = buildRecentSetupTokenRecord(record, graceExpiry)
+ }
+ if record.OrgID != "" {
+ r = r.WithContext(context.WithValue(r.Context(), OrgIDContextKey, record.OrgID))
+ }
+ return r, true
+ }
+
+ recentRecord, exists := h.recentSetupTokens[tokenHash]
+ if !exists || !now.Before(recentRecord.ExpiresAt) {
+ return r, false
+ }
+ if recentRecord.NodeType != "" && recentRecord.NodeType != strings.TrimSpace(nodeType) {
+ return r, false
+ }
+ if recentRecord.OrgID != "" {
+ r = r.WithContext(context.WithValue(r.Context(), OrgIDContextKey, recentRecord.OrgID))
+ }
+
+ return r, true
+}
+
+func autoUnregisterNodeMatch(nodeHost string, candidateHosts []string, nodeTokenID string, requestedTokenID string) bool {
+ if !autoRegisterHostMatchesCandidates(nodeHost, candidateHosts) {
+ return false
+ }
+ trimmedRequestedTokenID := strings.TrimSpace(requestedTokenID)
+ if trimmedRequestedTokenID == "" {
+ return true
+ }
+ return strings.TrimSpace(nodeTokenID) == trimmedRequestedTokenID
+}
+
+func (h *ConfigHandlers) removeAutoRegisteredNode(ctx context.Context, req *AutoUnregisterRequest, candidateHosts []string) (removed bool, actualName string, removedHost string) {
+ cfg := h.getConfig(ctx)
+ if cfg == nil {
+ return false, "", ""
+ }
+
+ switch strings.TrimSpace(req.Type) {
+ case "pve":
+ hostOnlyFallback := -1
+ for i, node := range cfg.PVEInstances {
+ if autoUnregisterNodeMatch(node.Host, candidateHosts, node.TokenName, req.TokenID) {
+ actualName = node.Name
+ removedHost = node.Host
+ cfg.PVEInstances = append(cfg.PVEInstances[:i], cfg.PVEInstances[i+1:]...)
+ h.normalizePVEConfigState(ctx)
+ return true, actualName, removedHost
+ }
+ if hostOnlyFallback == -1 && autoRegisterHostMatchesCandidates(node.Host, candidateHosts) && node.Source == "script" {
+ hostOnlyFallback = i
+ }
+ }
+ if hostOnlyFallback >= 0 {
+ node := cfg.PVEInstances[hostOnlyFallback]
+ actualName = node.Name
+ removedHost = node.Host
+ cfg.PVEInstances = append(cfg.PVEInstances[:hostOnlyFallback], cfg.PVEInstances[hostOnlyFallback+1:]...)
+ h.normalizePVEConfigState(ctx)
+ return true, actualName, removedHost
+ }
+ case "pbs":
+ hostOnlyFallback := -1
+ for i, node := range cfg.PBSInstances {
+ if autoUnregisterNodeMatch(node.Host, candidateHosts, node.TokenName, req.TokenID) {
+ actualName = node.Name
+ removedHost = node.Host
+ cfg.PBSInstances = append(cfg.PBSInstances[:i], cfg.PBSInstances[i+1:]...)
+ return true, actualName, removedHost
+ }
+ if hostOnlyFallback == -1 && autoRegisterHostMatchesCandidates(node.Host, candidateHosts) && node.Source == "script" {
+ hostOnlyFallback = i
+ }
+ }
+ if hostOnlyFallback >= 0 {
+ node := cfg.PBSInstances[hostOnlyFallback]
+ actualName = node.Name
+ removedHost = node.Host
+ cfg.PBSInstances = append(cfg.PBSInstances[:hostOnlyFallback], cfg.PBSInstances[hostOnlyFallback+1:]...)
+ return true, actualName, removedHost
+ }
+ }
+
+ return false, "", ""
+}
+
+func (h *ConfigHandlers) notifyAutoUnregisterSuccess(ctx context.Context, req *AutoUnregisterRequest) {
+ if h.getMonitor(ctx) != nil && h.getMonitor(ctx).GetDiscoveryService() != nil {
+ log.Info().Msg("Triggering discovery refresh after auto-unregister")
+ h.getMonitor(ctx).GetDiscoveryService().ForceRefresh()
+ }
+
+ if h.wsHub == nil {
+ return
+ }
+
+ h.wsHub.BroadcastMessage(websocket.Message{
+ Type: "node_deleted",
+ Data: map[string]interface{}{
+ "nodeType": strings.TrimSpace(req.Type),
+ },
+ Timestamp: time.Now().Format(time.RFC3339),
+ })
+
+ if h.getMonitor(ctx) != nil && h.getMonitor(ctx).GetDiscoveryService() != nil {
+ if result, _ := h.getMonitor(ctx).GetDiscoveryService().GetCachedResult(); result != nil {
+ h.wsHub.BroadcastMessage(websocket.Message{
+ Type: "discovery_update",
+ Data: map[string]interface{}{
+ "servers": result.Servers,
+ "errors": result.LegacyErrors(),
+ "structured_errors": result.StructuredErrors,
+ "timestamp": time.Now().Unix(),
+ },
+ Timestamp: time.Now().Format(time.RFC3339),
+ })
+ }
+ }
+}
+
type autoRegisterCheckResponse struct {
Registered bool `json:"registered"`
}
@@ -619,6 +839,107 @@ func (h *ConfigHandlers) notifyAutoRegistrationSuccess(ctx context.Context, req
Msg("Broadcasted auto-registration success via WebSocket")
}
+// HandleAutoUnregister removes a script-managed node connection after the host
+// has removed the Pulse-created credentials locally.
+func (h *ConfigHandlers) handleAutoUnregister(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ var req AutoUnregisterRequest
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ log.Error().Err(err).Msg("Failed to read auto-unregister request body")
+ http.Error(w, "Failed to read request body", http.StatusBadRequest)
+ return
+ }
+
+ if err := json.Unmarshal(body, &req); err != nil {
+ log.Error().Err(err).Str("body", string(body)).Msg("Failed to parse auto-unregister request")
+ http.Error(w, "Invalid request format", http.StatusBadRequest)
+ return
+ }
+
+ req.Type = strings.TrimSpace(req.Type)
+ req.Host = strings.TrimSpace(req.Host)
+ req.TokenID = strings.TrimSpace(req.TokenID)
+ req.ServerName = strings.TrimSpace(req.ServerName)
+ req.AuthToken = strings.TrimSpace(req.AuthToken)
+ req.Source = strings.TrimSpace(req.Source)
+
+ if req.Source == "" {
+ http.Error(w, "source is required", http.StatusBadRequest)
+ return
+ }
+ if req.Source != "script" {
+ http.Error(w, "source must be 'script'", http.StatusBadRequest)
+ return
+ }
+ if !isCanonicalAutoRegisterType(req.Type) {
+ http.Error(w, "type must be 'pve' or 'pbs'", http.StatusBadRequest)
+ return
+ }
+ if req.Type == "" || req.Host == "" || req.ServerName == "" {
+ http.Error(w, canonicalAutoUnregisterMissingFieldsMessage(req.Type, req.Host, req.ServerName), http.StatusBadRequest)
+ return
+ }
+
+ if req.TokenID != "" && !isCanonicalAutoRegisterTokenID(req.Type, req.TokenID) {
+ http.Error(w, "tokenId must be a canonical Pulse-managed token id", http.StatusBadRequest)
+ return
+ }
+
+ normalizedCandidates, err := normalizeAutoRegisterHostCandidates(req.Type, req.Host, nil)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ req.Host = normalizedCandidates[0]
+
+ updatedRequest, authenticated := h.authenticateSetupScriptTeardownRequest(r, req.Type, req.AuthToken)
+ if !authenticated {
+ if req.AuthToken == "" {
+ http.Error(w, "Pulse setup token required", http.StatusUnauthorized)
+ } else {
+ http.Error(w, "Invalid or expired setup token", http.StatusUnauthorized)
+ }
+ return
+ }
+ r = updatedRequest
+
+ removed, actualName, removedHost := h.removeAutoRegisteredNode(r.Context(), &req, normalizedCandidates)
+ if removed {
+ if err := h.getPersistence(r.Context()).SaveNodesConfigAllowEmpty(
+ h.getConfig(r.Context()).PVEInstances,
+ h.getConfig(r.Context()).PBSInstances,
+ h.getConfig(r.Context()).PMGInstances,
+ ); err != nil {
+ log.Error().Err(err).Msg("Failed to save auto-unregistered node configuration")
+ http.Error(w, "Failed to save configuration", http.StatusInternalServerError)
+ return
+ }
+
+ if h.reloadFunc != nil {
+ if err := h.reloadFunc(); err != nil {
+ log.Error().Err(err).Msg("Failed to reload monitor after auto-unregister")
+ http.Error(w, "Configuration saved but failed to apply changes", http.StatusInternalServerError)
+ return
+ }
+ }
+
+ h.notifyAutoUnregisterSuccess(r.Context(), &req)
+ } else {
+ removedHost = req.Host
+ actualName = req.ServerName
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(buildCanonicalAutoUnregisterResponse(&req, removedHost, actualName, removed)); err != nil {
+ log.Error().Err(err).Msg("Failed to encode auto-unregister response")
+ }
+}
+
// HandleAutoRegister receives token details from the setup script and auto-configures the node
func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -676,11 +997,8 @@ func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Reque
r = r.WithContext(ctx)
}
// Allow a short grace period for follow-up actions without keeping tokens alive too long.
- graceExpiry := time.Now().Add(1 * time.Minute)
- if setupTokenRecord.ExpiresAt.Before(graceExpiry) {
- graceExpiry = setupTokenRecord.ExpiresAt
- }
- h.recentSetupTokens[tokenHash] = graceExpiry
+ graceExpiry := recentSetupTokenGraceExpiry(setupTokenRecord, time.Now())
+ h.recentSetupTokens[tokenHash] = buildRecentSetupTokenRecord(setupTokenRecord, graceExpiry)
authenticated = true
log.Info().
Str("type", req.Type).
@@ -981,6 +1299,7 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
MonitorSyncJobs: true,
MonitorVerifyJobs: true,
MonitorPruneJobs: true,
+ Source: registrationSource,
}
// Deduplicate by host to keep canonical auto-registration idempotent on reruns.
existingIndex := -1
@@ -1022,6 +1341,9 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
instance.Password = ""
instance.TokenName = pbsNode.TokenName
instance.TokenValue = pbsNode.TokenValue
+ if pbsNode.Source != "" {
+ instance.Source = pbsNode.Source
+ }
// Update TLS fingerprint only when one was captured; a failed
// FetchFingerprint must not erase a previously valid pin.
if pbsNode.Fingerprint != "" {
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 6790e9c42a..2e45244a0a 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -4688,9 +4688,15 @@ func TestContract_SetupScriptEmbedsFailFastGuidance(t *testing.T) {
if !strings.Contains(script, `curl -fsS -X POST "$PULSE_URL/api/auto-register"`) {
t.Fatalf("setup script missing fail-fast auto-register transport: %s", script)
}
+ if !strings.Contains(script, `curl -fsS -X POST "$PULSE_URL/api/auto-unregister"`) {
+ t.Fatalf("setup script missing fail-fast auto-unregister transport: %s", script)
+ }
if !strings.Contains(script, `"source":"script"`) {
t.Fatalf("setup script missing canonical /api/auto-register source marker: %s", script)
}
+ if !strings.Contains(script, `echo " • Removing Pulse connection from server..."`) {
+ t.Fatalf("setup script missing canonical server-side teardown guidance: %s", script)
+ }
if !strings.Contains(script, `REGISTER_RC=$?`) {
t.Fatalf("setup script missing explicit auto-register curl exit-code handling: %s", script)
}
@@ -8189,6 +8195,33 @@ func TestContract_AutoRegisterCheckRequestJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_AutoUnregisterRequestJSONSnapshot(t *testing.T) {
+ payload := AutoUnregisterRequest{
+ Type: "pve",
+ Host: "https://pve.local:8006",
+ TokenID: "pulse-monitor@pve!pulse-homelab",
+ ServerName: "pve-node-1",
+ AuthToken: "setup-token-123",
+ Source: "script",
+ }
+
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal auto-unregister request: %v", err)
+ }
+
+ const want = `{
+ "type":"pve",
+ "host":"https://pve.local:8006",
+ "tokenId":"pulse-monitor@pve!pulse-homelab",
+ "serverName":"pve-node-1",
+ "authToken":"setup-token-123",
+ "source":"script"
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_AutoRegisterScriptRequestRequiresExplicitSourceMarker(t *testing.T) {
payload := AutoRegisterRequest{
Type: "pve",
@@ -8889,6 +8922,15 @@ func TestContract_CanonicalAutoRegisterMissingFieldsMessageContract(t *testing.T
}
}
+func TestContract_CanonicalAutoUnregisterMissingFieldsMessageContract(t *testing.T) {
+ if got := canonicalAutoUnregisterMissingFieldsMessage("", "", ""); got != "Missing required canonical auto-unregister fields: type, host, serverName" {
+ t.Fatalf("all-missing auto-unregister message = %q", got)
+ }
+ if got := canonicalAutoUnregisterMissingFieldsMessage("pve", "https://pve.local:8006", ""); got != "Missing required canonical auto-unregister fields: serverName" {
+ t.Fatalf("serverName-only auto-unregister message = %q", got)
+ }
+}
+
func TestContract_CanonicalAutoRegisterDirectValidationContract(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", tempDir)
@@ -8970,6 +9012,72 @@ func TestContract_AutoRegisterResponseJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_AutoUnregisterResponseJSONSnapshot(t *testing.T) {
+ payload := map[string]any{
+ "status": "success",
+ "message": "Node pve-node-1 removed successfully from https://pve.local:8006",
+ "action": "remove_connection",
+ "type": "pve",
+ "source": "script",
+ "host": "https://pve.local:8006",
+ "nodeId": "pve-node-1",
+ "nodeName": "pve-node-1",
+ "removed": true,
+ }
+
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal auto-unregister response: %v", err)
+ }
+
+ const want = `{
+ "action":"remove_connection",
+ "host":"https://pve.local:8006",
+ "message":"Node pve-node-1 removed successfully from https://pve.local:8006",
+ "nodeId":"pve-node-1",
+ "nodeName":"pve-node-1",
+ "removed":true,
+ "source":"script",
+ "status":"success",
+ "type":"pve"
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
+func TestContract_AutoUnregisterNoopResponseJSONSnapshot(t *testing.T) {
+ payload := map[string]any{
+ "status": "success",
+ "message": "No matching node is currently configured for https://pve.local:8006",
+ "action": "noop",
+ "type": "pve",
+ "source": "script",
+ "host": "https://pve.local:8006",
+ "nodeId": "pve-node-1",
+ "nodeName": "pve-node-1",
+ "removed": false,
+ }
+
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal auto-unregister noop response: %v", err)
+ }
+
+ const want = `{
+ "action":"noop",
+ "host":"https://pve.local:8006",
+ "message":"No matching node is currently configured for https://pve.local:8006",
+ "nodeId":"pve-node-1",
+ "nodeName":"pve-node-1",
+ "removed":false,
+ "source":"script",
+ "status":"success",
+ "type":"pve"
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_AutoRegisterWebSocketEventJSONSnapshot(t *testing.T) {
payload := map[string]any{
"type": "pve",
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index ce1443067d..c471784fc0 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -277,6 +277,7 @@ var publicRouteAllowlist = []string{
"/api/system/verify-temperature-ssh",
"/api/system/ssh-config",
"/api/auto-register",
+ "/api/auto-unregister",
"/auth/cloud-handoff",
"/auth/trial-activate",
licensePurchaseActivationPath,
@@ -292,6 +293,7 @@ var bareRouteAllowlist = []string{
"/api/agent/ws",
"/api/ai/oauth/callback",
"/api/auto-register",
+ "/api/auto-unregister",
"/api/webhooks/stripe",
"/api/config/export",
"/api/config/import",
@@ -545,6 +547,7 @@ var allRouteAllowlist = []string{
"/api/setup-script-url",
"/api/agent-install-command",
"/api/auto-register",
+ "/api/auto-unregister",
"/api/discover",
"/api/test-notification",
"/api/alerts/",
diff --git a/internal/api/router.go b/internal/api/router.go
index 367269d12d..58fe49b49c 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -3561,6 +3561,9 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if normalizedPath == "/api/auto-register" {
isPublic = true
}
+ if normalizedPath == "/api/auto-unregister" {
+ isPublic = true
+ }
// Dev mode bypass for admin endpoints (disabled by default)
if adminBypassEnabled() {
diff --git a/internal/api/router_auth_bypass_inventory_test.go b/internal/api/router_auth_bypass_inventory_test.go
index 5fcc32b8a2..c4e3e00bc1 100644
--- a/internal/api/router_auth_bypass_inventory_test.go
+++ b/internal/api/router_auth_bypass_inventory_test.go
@@ -74,6 +74,7 @@ func parseAuthBypassPaths(t *testing.T) []string {
var authBypassAllowlist = []string{
"/api/auto-register",
+ "/api/auto-unregister",
"/api/setup-script",
"/api/system/ssh-config",
"/api/system/verify-temperature-ssh",
diff --git a/internal/api/router_routes_registration.go b/internal/api/router_routes_registration.go
index 7f2a58f97b..f8b64ffa17 100644
--- a/internal/api/router_routes_registration.go
+++ b/internal/api/router_routes_registration.go
@@ -631,6 +631,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {
// 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
diff --git a/internal/api/setup_script_render.go b/internal/api/setup_script_render.go
index 3a89dd597e..1a558bf291 100644
--- a/internal/api/setup_script_render.go
+++ b/internal/api/setup_script_render.go
@@ -208,6 +208,35 @@ if [[ $MAIN_ACTION =~ ^[2Rr]$ ]]; then
echo "Removing Pulse monitoring components..."
echo ""
+ SERVER_HOSTNAME=$(hostname -s 2>/dev/null || hostname)
+
+ if [ -n "$PULSE_SETUP_TOKEN" ]; then
+ echo " • Removing Pulse connection from server..."
+ UNREGISTER_JSON='{"type":"pve","host":"'"$HOST_URL"'","serverName":"'"$SERVER_HOSTNAME"'","tokenId":"'"$PULSE_TOKEN_ID"'","authToken":"'"$PULSE_SETUP_TOKEN"'","source":"script"}'
+ UNREGISTER_RESPONSE=$(echo "$UNREGISTER_JSON" | curl -fsS -X POST "$PULSE_URL/api/auto-unregister" \
+ -H "Content-Type: application/json" \
+ -d @- 2>&1)
+ UNREGISTER_RC=$?
+ if [ "$UNREGISTER_RC" -ne 0 ]; then
+ echo " ⚠️ Pulse server teardown request failed."
+ echo " Response: $UNREGISTER_RESPONSE"
+ echo " Remove the node from Pulse manually if it remains listed."
+ elif echo "$UNREGISTER_RESPONSE" | grep -Eq '"status"[[:space:]]*:[[:space:]]*"success"'; then
+ if echo "$UNREGISTER_RESPONSE" | grep -Eq '"removed"[[:space:]]*:[[:space:]]*true'; then
+ echo " ✓ Removed matching Proxmox VE connection from Pulse"
+ else
+ echo " ✓ Pulse confirmed there is no matching Proxmox VE connection to remove"
+ fi
+ else
+ echo " ⚠️ Pulse server teardown did not confirm success."
+ echo " Response: $UNREGISTER_RESPONSE"
+ echo " Remove the node from Pulse manually if it remains listed."
+ fi
+ else
+ echo " • No Pulse setup token available for server-side teardown"
+ echo " Remove the node from Pulse manually if it remains listed."
+ fi
+
# Always run manual removal for local services and files
if true; then