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.

feat(cloudcp): add Pulse Account bootstrap handler

rcourtman9cc3ff11f8a2
diff --git a/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md b/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md
index 9fb3763ef9..9104657955 100644
--- a/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md
+++ b/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md
@@ -235,6 +235,10 @@ frontend state seam for:
2. hosted account and workspace summaries
3. public/commercial edge URLs needed by the account shell
+The portal package also owns a dedicated bootstrap JSON handler shape for the
+same contract, so route wiring can promote the shell toward a maintained
+frontend/API split without inventing a second state model.
+
New frontend work should extend that contract deliberately instead of adding
one-off data attributes or baking production hostnames into static assets.
diff --git a/internal/cloudcp/portal/handlers.go b/internal/cloudcp/portal/handlers.go
index c4b231172d..5bca38c812 100644
--- a/internal/cloudcp/portal/handlers.go
+++ b/internal/cloudcp/portal/handlers.go
@@ -2,10 +2,12 @@ package portal
import (
"encoding/json"
+ "errors"
"net/http"
"strings"
"time"
+ cpauth "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auth"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
"github.com/rs/zerolog/log"
stripe "github.com/stripe/stripe-go/v82"
@@ -204,6 +206,45 @@ func HandlePortalWorkspaceDetail(reg *registry.TenantRegistry) http.HandlerFunc
}
}
+// HandlePortalBootstrap returns the renderer-owned Pulse Account bootstrap payload.
+// Route: GET /api/portal/bootstrap
+//
+// Auth: control-plane session.
+func HandlePortalBootstrap(sessionSvc *cpauth.Service, reg *registry.TenantRegistry) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if sessionSvc == nil || reg == nil {
+ http.Error(w, "internal error", http.StatusInternalServerError)
+ return
+ }
+
+ claims, err := validatePortalSessionClaims(r, sessionSvc, reg)
+ if err != nil {
+ if errors.Is(err, errPortalAuthRequired) {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ log.Error().Err(err).Msg("cloudcp.portal.bootstrap: validate session")
+ http.Error(w, "internal error", http.StatusInternalServerError)
+ return
+ }
+
+ accounts, err := loadPortalAccountsForUser(reg, claims.UserID)
+ if err != nil {
+ log.Error().Err(err).Str("user_id", claims.UserID).Msg("cloudcp.portal.bootstrap: load accounts")
+ http.Error(w, "internal error", http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ encodeJSON(w, buildPortalBootstrapData(claims.Email, accounts))
+ }
+}
+
// BillingPortalConfig holds the configuration for the billing portal redirect handler.
type BillingPortalConfig struct {
StripeAPIKey string
diff --git a/internal/cloudcp/portal/handlers_test.go b/internal/cloudcp/portal/handlers_test.go
index d44257958b..c02097ceb6 100644
--- a/internal/cloudcp/portal/handlers_test.go
+++ b/internal/cloudcp/portal/handlers_test.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/admin"
+ cpauth "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auth"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
stripe "github.com/stripe/stripe-go/v82"
)
@@ -61,6 +62,46 @@ func renderLoginHTML(t *testing.T, nonce string) string {
return rec.Body.String()
}
+func newPortalSessionFixture(t *testing.T) (*registry.TenantRegistry, *cpauth.Service, string, string, string) {
+ t.Helper()
+
+ reg := newTestRegistry(t)
+ accountID, err := registry.GenerateAccountID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ userID, err := registry.GenerateUserID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.CreateAccount(&registry.Account{ID: accountID, Kind: registry.AccountKindIndividual, DisplayName: "Portal Account"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.CreateUser(&registry.User{ID: userID, Email: "[email protected]"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.CreateMembership(&registry.AccountMembership{
+ AccountID: accountID,
+ UserID: userID,
+ Role: registry.MemberRoleOwner,
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ sessionSvc, err := cpauth.NewService(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewService: %v", err)
+ }
+ t.Cleanup(sessionSvc.Close)
+
+ token, err := sessionSvc.GenerateSessionToken(userID, "[email protected]", cpauth.SessionTTL)
+ if err != nil {
+ t.Fatalf("GenerateSessionToken: %v", err)
+ }
+
+ return reg, sessionSvc, token, accountID, userID
+}
+
type dashboardResp struct {
Account struct {
ID string `json:"id"`
@@ -846,6 +887,77 @@ func TestBuildPortalBootstrapJSON_Contract(t *testing.T) {
}
}
+func TestHandlePortalBootstrap_Success(t *testing.T) {
+ reg, sessionSvc, token, accountID, _ := newPortalSessionFixture(t)
+
+ if err := reg.Create(&registry.Tenant{
+ ID: "t_bootstrap",
+ AccountID: accountID,
+ DisplayName: "Bootstrap Workspace",
+ State: registry.TenantStateActive,
+ CreatedAt: time.Date(2026, 3, 25, 10, 0, 0, 0, time.UTC),
+ HealthCheckOK: true,
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/api/portal/bootstrap", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+ rec := httptest.NewRecorder()
+ HandlePortalBootstrap(sessionSvc, reg).ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusOK, rec.Body.String())
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("unmarshal bootstrap response: %v", err)
+ }
+ if got := payload["email"]; got != "[email protected]" {
+ t.Fatalf("email = %#v", got)
+ }
+ if got := payload["portal_api_base_path"]; got != "/api/portal" {
+ t.Fatalf("portal_api_base_path = %#v", got)
+ }
+ accounts, ok := payload["accounts"].([]any)
+ if !ok || len(accounts) != 1 {
+ t.Fatalf("accounts = %#v", payload["accounts"])
+ }
+ account, ok := accounts[0].(map[string]any)
+ if !ok {
+ t.Fatalf("account = %#v", accounts[0])
+ }
+ workspaces, ok := account["workspaces"].([]any)
+ if !ok || len(workspaces) != 1 {
+ t.Fatalf("workspaces = %#v", account["workspaces"])
+ }
+ workspace, ok := workspaces[0].(map[string]any)
+ if !ok {
+ t.Fatalf("workspace = %#v", workspaces[0])
+ }
+ if got := workspace["display_name"]; got != "Bootstrap Workspace" {
+ t.Fatalf("workspace display_name = %#v", got)
+ }
+}
+
+func TestHandlePortalBootstrap_RequiresAuth(t *testing.T) {
+ reg := newTestRegistry(t)
+ sessionSvc, err := cpauth.NewService(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewService: %v", err)
+ }
+ t.Cleanup(sessionSvc.Close)
+
+ req := httptest.NewRequest(http.MethodGet, "/api/portal/bootstrap", nil)
+ rec := httptest.NewRecorder()
+ HandlePortalBootstrap(sessionSvc, reg).ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
+ }
+}
+
func TestPortalLoginTemplate_UsesPulseAccountBranding(t *testing.T) {
html := renderLoginHTML(t, "test-nonce")
diff --git a/internal/cloudcp/portal/page.go b/internal/cloudcp/portal/page.go
index 4a78eb33ca..3258d4fea4 100644
--- a/internal/cloudcp/portal/page.go
+++ b/internal/cloudcp/portal/page.go
@@ -2,6 +2,7 @@ package portal
import (
"encoding/json"
+ "errors"
"html/template"
"net/http"
"time"
@@ -96,6 +97,8 @@ const (
defaultPortalAPIBasePath = "/api/portal"
)
+var errPortalAuthRequired = errors.New("portal auth required")
+
// HandlePortalPage serves the MSP/Cloud portal dashboard (browser-facing HTML).
// Route: GET /portal
// - No session or invalid session -> shows a magic-link login form
@@ -109,105 +112,121 @@ func HandlePortalPage(sessionSvc *cpauth.Service, reg *registry.TenantRegistry)
nonce := cpsec.NonceFromContext(r.Context())
- // Validate session from cookie or Bearer token.
- token := cpauth.SessionTokenFromRequest(r)
- if token == "" || sessionSvc == nil || reg == nil {
+ claims, err := validatePortalSessionClaims(r, sessionSvc, reg)
+ if err != nil {
renderLoginPage(w, nonce)
return
}
-
- claims, err := sessionSvc.ValidateSessionToken(token)
+ accounts, err := loadPortalAccountsForUser(reg, claims.UserID)
if err != nil {
- renderLoginPage(w, nonce)
+ log.Error().Err(err).Str("user_id", claims.UserID).Msg("cloudcp.portal.page: load accounts")
+ http.Error(w, "internal error", http.StatusInternalServerError)
return
}
- sessionVersion, err := reg.GetUserSessionVersion(claims.UserID)
+
+ renderPortalPage(w, nonce, claims.Email, accounts)
+ }
+}
+
+func validatePortalSessionClaims(r *http.Request, sessionSvc *cpauth.Service, reg *registry.TenantRegistry) (*cpauth.SessionClaims, error) {
+ if r == nil || sessionSvc == nil || reg == nil {
+ return nil, errPortalAuthRequired
+ }
+
+ token := cpauth.SessionTokenFromRequest(r)
+ if token == "" {
+ return nil, errPortalAuthRequired
+ }
+
+ claims, err := sessionSvc.ValidateSessionToken(token)
+ if err != nil {
+ return nil, errPortalAuthRequired
+ }
+
+ sessionVersion, err := reg.GetUserSessionVersion(claims.UserID)
+ if err != nil {
+ return nil, err
+ }
+ if claims.SessionVersion != sessionVersion {
+ return nil, errPortalAuthRequired
+ }
+ return claims, nil
+}
+
+func loadPortalAccountsForUser(reg *registry.TenantRegistry, userID string) ([]portalPageAccount, error) {
+ accountIDs, err := reg.ListAccountsByUser(userID)
+ if err != nil {
+ return nil, err
+ }
+
+ accounts := make([]portalPageAccount, 0, len(accountIDs))
+ for _, accountID := range accountIDs {
+ a, err := reg.GetAccount(accountID)
if err != nil {
- log.Error().Err(err).Str("user_id", claims.UserID).Msg("cloudcp.portal.page: get session version")
- renderLoginPage(w, nonce)
- return
+ log.Error().Err(err).Str("account_id", accountID).Msg("cloudcp.portal.page: get account")
+ continue
}
- if claims.SessionVersion != sessionVersion {
- renderLoginPage(w, nonce)
- return
+ if a == nil {
+ continue
}
- accountIDs, err := reg.ListAccountsByUser(claims.UserID)
+ m, err := reg.GetMembership(accountID, userID)
if err != nil {
- log.Error().Err(err).Str("user_id", claims.UserID).Msg("cloudcp.portal.page: list accounts by user")
- http.Error(w, "internal error", http.StatusInternalServerError)
- return
+ log.Error().Err(err).Str("account_id", accountID).Str("user_id", userID).Msg("cloudcp.portal.page: get membership")
+ continue
+ }
+ if m == nil {
+ continue
}
- accounts := make([]portalPageAccount, 0, len(accountIDs))
- for _, accountID := range accountIDs {
- a, err := reg.GetAccount(accountID)
- if err != nil {
- log.Error().Err(err).Str("account_id", accountID).Msg("cloudcp.portal.page: get account")
- continue
- }
- if a == nil {
- continue
- }
+ tenants, err := reg.ListByAccountID(accountID)
+ if err != nil {
+ log.Error().Err(err).Str("account_id", accountID).Msg("cloudcp.portal.page: list tenants")
+ continue
+ }
- m, err := reg.GetMembership(accountID, claims.UserID)
- if err != nil {
- log.Error().Err(err).Str("account_id", accountID).Str("user_id", claims.UserID).Msg("cloudcp.portal.page: get membership")
- continue
- }
- if m == nil {
+ workspaces := make([]portalPageWorkspace, 0, len(tenants))
+ for _, t := range tenants {
+ if t == nil {
continue
}
-
- tenants, err := reg.ListByAccountID(accountID)
- if err != nil {
- log.Error().Err(err).Str("account_id", accountID).Msg("cloudcp.portal.page: list tenants")
+ if t.State == registry.TenantStateDeleted || t.State == registry.TenantStateDeleting {
continue
}
+ workspaces = append(workspaces, portalPageWorkspace{
+ ID: t.ID,
+ DisplayName: t.DisplayName,
+ State: string(t.State),
+ Healthy: t.HealthCheckOK,
+ CreatedAt: t.CreatedAt,
+ })
+ }
- workspaces := make([]portalPageWorkspace, 0, len(tenants))
- for _, t := range tenants {
- if t == nil {
- continue
- }
- if t.State == registry.TenantStateDeleted || t.State == registry.TenantStateDeleting {
- continue
- }
- workspaces = append(workspaces, portalPageWorkspace{
- ID: t.ID,
- DisplayName: t.DisplayName,
- State: string(t.State),
- Healthy: t.HealthCheckOK,
- CreatedAt: t.CreatedAt,
- })
- }
-
- kindLabel := "Cloud"
- if a.Kind == registry.AccountKindMSP {
- kindLabel = "MSP"
- }
-
- hasBilling := false
- if sa, saErr := reg.GetStripeAccount(accountID); saErr != nil {
- log.Warn().Err(saErr).Str("account_id", accountID).Msg("cloudcp.portal.page: lookup stripe account for billing button")
- } else if sa != nil && sa.StripeCustomerID != "" {
- hasBilling = true
- }
+ kindLabel := "Cloud"
+ if a.Kind == registry.AccountKindMSP {
+ kindLabel = "MSP"
+ }
- accounts = append(accounts, portalPageAccount{
- ID: a.ID,
- Kind: string(a.Kind),
- KindLabel: kindLabel,
- Name: a.DisplayName,
- Role: string(m.Role),
- CanManage: m.Role == registry.MemberRoleOwner || m.Role == registry.MemberRoleAdmin,
- HasBilling: hasBilling,
- Workspaces: workspaces,
- })
+ hasBilling := false
+ if sa, saErr := reg.GetStripeAccount(accountID); saErr != nil {
+ log.Warn().Err(saErr).Str("account_id", accountID).Msg("cloudcp.portal.page: lookup stripe account for billing button")
+ } else if sa != nil && sa.StripeCustomerID != "" {
+ hasBilling = true
}
- renderPortalPage(w, nonce, claims.Email, accounts)
+ accounts = append(accounts, portalPageAccount{
+ ID: a.ID,
+ Kind: string(a.Kind),
+ KindLabel: kindLabel,
+ Name: a.DisplayName,
+ Role: string(m.Role),
+ CanManage: m.Role == registry.MemberRoleOwner || m.Role == registry.MemberRoleAdmin,
+ HasBilling: hasBilling,
+ Workspaces: workspaces,
+ })
}
+
+ return accounts, nil
}
func renderPortalPage(w http.ResponseWriter, nonce, email string, accounts []portalPageAccount) {
@@ -250,6 +269,14 @@ func renderLoginPage(w http.ResponseWriter, nonce string) {
}
func buildPortalBootstrapJSON(email string, accounts []portalPageAccount) (template.JS, error) {
+ payload, err := json.Marshal(buildPortalBootstrapData(email, accounts))
+ if err != nil {
+ return "", err
+ }
+ return template.JS(payload), nil
+}
+
+func buildPortalBootstrapData(email string, accounts []portalPageAccount) portalBootstrapData {
bootstrapAccounts := make([]portalBootstrapAccount, 0, len(accounts))
for _, account := range accounts {
workspaces := make([]portalBootstrapWorkspace, 0, len(account.Workspaces))
@@ -273,7 +300,7 @@ func buildPortalBootstrapJSON(email string, accounts []portalPageAccount) (templ
})
}
- payload, err := json.Marshal(portalBootstrapData{
+ return portalBootstrapData{
Email: email,
PublicSiteURL: defaultPublicSiteURL,
SupportEmail: defaultSupportEmail,
@@ -283,9 +310,5 @@ func buildPortalBootstrapJSON(email string, accounts []portalPageAccount) (templ
AccountAPIBasePath: defaultAccountAPIBasePath,
PortalAPIBasePath: defaultPortalAPIBasePath,
Accounts: bootstrapAccounts,
- })
- if err != nil {
- return "", err
}
- return template.JS(payload), nil
}