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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
fix(cloudcp): unify portal magic link identity
Richard Courtman066ba8136bcd
diff --git a/internal/cloudcp/auth/handlers.go b/internal/cloudcp/auth/handlers.goindex 69d7cde3f1..5b76561543 100644--- a/internal/cloudcp/auth/handlers.go+++ b/internal/cloudcp/auth/handlers.go@@ -18,7 +18,6 @@ import ()const handoffTTL = 60 * time.Second-const portalRedirectPath = "/portal"type adminGenerateMagicLinkRequest struct {Email string `json:"email"`@@ -41,7 +40,7 @@ type errorResponse struct {// HandleMagicLinkVerify returns an http.HandlerFunc that validates a control-plane// magic link token, generates a short-lived handoff token, and redirects the user// to the tenant container.-func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDir, baseDomain string) http.HandlerFunc {+func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDir, baseDomain, portalPath string) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed")@@ -65,7 +64,7 @@ func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDiMsg("Magic link verification failed")// Browser redirect on failure.if !strings.Contains(r.Header.Get("Accept"), "application/json") {- http.Redirect(w, r, "/login?error=magic_link_invalid", http.StatusTemporaryRedirect)+ http.Redirect(w, r, strings.TrimSpace(portalPath), http.StatusTemporaryRedirect)return}writeError(w, http.StatusBadRequest, "invalid_token", "Invalid or expired magic link")@@ -73,34 +72,56 @@ func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDi}if token.Target == MagicLinkTargetPortal {- userID, err := ensureAccountUser(reg, token.Email)+ redirectPath := strings.TrimSpace(portalPath)+ if redirectPath == "" {+ redirectPath = "/portal"+ }+ userID, err := ensurePortalUserAndMembership(reg, token.TenantID, token.Email)if err != nil {auditEvent(r, "cp_magic_link_verify", "failure").Err(err).- Str("email", token.Email).- Str("target", token.Target).- Str("reason", "user_resolution_failed").+ Str("tenant_id", token.TenantID).+ Str("reason", "portal_session_identity_failed").Msg("Magic link verification failed")writeError(w, http.StatusInternalServerError, "session_error", "Unable to establish portal session")return}- if err := setSessionCookie(w, svc, reg, userID, token.Email); err != nil {+ sessionVersion, err := reg.GetUserSessionVersion(userID)+ if err != nil {+ auditEvent(r, "cp_magic_link_verify", "failure").+ Err(err).+ Str("reason", "session_version_lookup_failed").+ Msg("Magic link verification failed")+ writeError(w, http.StatusInternalServerError, "session_error", "Unable to establish portal session")+ return+ }+ sessionToken, err := svc.GenerateSessionTokenWithVersion(userID, token.Email, sessionVersion, SessionTTL)+ if err != nil {auditEvent(r, "cp_magic_link_verify", "failure").Err(err).- Str("email", token.Email).- Str("target", token.Target).Str("reason", "session_issue_failed").Msg("Magic link verification failed")writeError(w, http.StatusInternalServerError, "session_error", "Unable to establish portal session")return}+ http.SetCookie(w, &http.Cookie{+ Name: SessionCookieName,+ Value: sessionToken,+ Path: "/",+ HttpOnly: true,+ Secure: true,+ SameSite: http.SameSiteLaxMode,+ MaxAge: int(SessionTTL.Seconds()),+ })+auditEvent(r, "cp_magic_link_verify", "success").+ Str("tenant_id", token.TenantID).Str("email", token.Email).- Str("target", token.Target).- Msg("Magic link verified, redirecting to Pulse Account")+ Str("target", string(token.Target)).+ Msg("Magic link verified, redirecting to portal")- http.Redirect(w, r, portalRedirectPath, http.StatusTemporaryRedirect)+ http.Redirect(w, r, redirectPath, http.StatusTemporaryRedirect)return}@@ -130,25 +151,25 @@ func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDireturn}- handoffClaims := cloudauth.Claims{- Email: token.Email,- TenantID: tenant.ID,- }- userID, membershipRole, membershipErr := ensureAccountUserAndMembership(reg, tenant, token.Email)- if membershipErr != nil {+ userID, identityErr := ensureAccountUserAndMembership(reg, tenant, token.Email)+ if identityErr != nil {log.Warn().- Err(membershipErr).+ Err(identityErr).Str("tenant_id", tenant.ID).Str("email", token.Email).- Msg("Failed to resolve account membership for cloud handoff token")- } else {- handoffClaims.UserID = userID- handoffClaims.AccountID = tenant.AccountID- handoffClaims.Role = string(membershipRole)+ Msg("Failed to establish control-plane session identity")+ }++ claims := cloudauth.Claims{+ Email: token.Email,+ TenantID: tenant.ID,+ AccountID: strings.TrimSpace(tenant.AccountID),+ UserID: strings.TrimSpace(userID),+ Role: string(registry.MemberRoleOwner),}// Sign a short-lived handoff token.- handoffToken, err := cloudauth.SignWithClaims(handoffKey, handoffClaims, handoffTTL)+ handoffToken, err := cloudauth.SignWithClaims(handoffKey, claims, handoffTTL)if err != nil {auditEvent(r, "cp_magic_link_verify", "failure").Err(err).@@ -163,24 +184,36 @@ func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDiredirectURL := fmt.Sprintf("https://%s.%s/auth/cloud-handoff?token=%s",tenant.ID, baseDomain, handoffToken)- if membershipErr != nil {- log.Warn().- Err(membershipErr).- Str("tenant_id", tenant.ID).- Str("email", token.Email).- Msg("Failed to establish control-plane session identity")- } else if err := setSessionCookie(w, svc, reg, userID, token.Email); err != nil {- log.Warn().- Err(err).- Str("tenant_id", tenant.ID).- Str("email", token.Email).- Msg("Failed to issue control-plane session")+ if identityErr == nil {+ if sessionVersion, err := reg.GetUserSessionVersion(userID); err != nil {+ log.Warn().+ Err(err).+ Str("tenant_id", tenant.ID).+ Str("email", token.Email).+ Str("user_id", userID).+ Msg("Failed to read user session version")+ } else if sessionToken, err := svc.GenerateSessionTokenWithVersion(userID, token.Email, sessionVersion, SessionTTL); err != nil {+ log.Warn().+ Err(err).+ Str("tenant_id", tenant.ID).+ Str("email", token.Email).+ Msg("Failed to issue control-plane session")+ } else {+ http.SetCookie(w, &http.Cookie{+ Name: SessionCookieName,+ Value: sessionToken,+ Path: "/",+ HttpOnly: true,+ Secure: true,+ SameSite: http.SameSiteLaxMode,+ MaxAge: int(SessionTTL.Seconds()),+ })+ }}auditEvent(r, "cp_magic_link_verify", "success").Str("tenant_id", tenant.ID).Str("email", token.Email).- Str("target", token.Target).Msg("Magic link verified, redirecting to tenant handoff")http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)@@ -362,28 +395,25 @@ func clearSessionCookie(w http.ResponseWriter) {})}-func setSessionCookie(w http.ResponseWriter, svc *Service, reg *registry.TenantRegistry, userID, email string) error {- sessionVersion, err := reg.GetUserSessionVersion(userID)- if err != nil {- return fmt.Errorf("read user session version: %w", err)+func ensurePortalUserAndMembership(reg *registry.TenantRegistry, tenantID, email string) (string, error) {+ if reg == nil {+ return "", fmt.Errorf("registry unavailable")}- sessionToken, err := svc.GenerateSessionTokenWithVersion(userID, email, sessionVersion, SessionTTL)- if err != nil {- return fmt.Errorf("issue session token: %w", err)+ email = strings.ToLower(strings.TrimSpace(email))+ tenantID = strings.TrimSpace(tenantID)+ if tenantID != "" {+ tenant, err := reg.Get(tenantID)+ if err != nil {+ return "", fmt.Errorf("lookup tenant: %w", err)+ }+ if tenant != nil {+ return ensureAccountUserAndMembership(reg, tenant, email)+ }}- http.SetCookie(w, &http.Cookie{- Name: SessionCookieName,- Value: sessionToken,- Path: "/",- HttpOnly: true,- Secure: true,- SameSite: http.SameSiteLaxMode,- MaxAge: int(SessionTTL.Seconds()),- })- return nil+ return ensurePortalUser(reg, email)}-func ensureAccountUser(reg *registry.TenantRegistry, email string) (string, error) {+func ensurePortalUser(reg *registry.TenantRegistry, email string) (string, error) {if reg == nil {return "", fmt.Errorf("registry unavailable")}@@ -418,52 +448,49 @@ func ensureAccountUser(reg *registry.TenantRegistry, email string) (string, erroif user == nil || strings.TrimSpace(user.ID) == "" {return "", fmt.Errorf("user resolution failed")}-_ = reg.UpdateUserLastLogin(user.ID)return user.ID, nil}-func ensureAccountUserAndMembership(reg *registry.TenantRegistry, tenant *registry.Tenant, email string) (string, registry.MemberRole, error) {+func ensureAccountUserAndMembership(reg *registry.TenantRegistry, tenant *registry.Tenant, email string) (string, error) {if reg == nil {- return "", "", fmt.Errorf("registry unavailable")+ return "", fmt.Errorf("registry unavailable")}if tenant == nil {- return "", "", fmt.Errorf("tenant is required")+ return "", fmt.Errorf("tenant is required")}accountID := strings.TrimSpace(tenant.AccountID)if accountID == "" {- return "", "", fmt.Errorf("tenant has no account id")+ return "", fmt.Errorf("tenant has no account id")}email = strings.ToLower(strings.TrimSpace(email))if email == "" {- return "", "", fmt.Errorf("email is required")+ return "", fmt.Errorf("email is required")}- userID, err := ensureAccountUser(reg, email)+ userID, err := ensurePortalUser(reg, email)if err != nil {- return "", "", err+ return "", err}+ user := ®istry.User{ID: userID}- m, err := reg.GetMembership(accountID, userID)+ m, err := reg.GetMembership(accountID, user.ID)if err != nil {- return "", "", fmt.Errorf("lookup membership: %w", err)+ return "", fmt.Errorf("lookup membership: %w", err)}if m == nil {newMembership := ®istry.AccountMembership{AccountID: accountID,- UserID: userID,+ UserID: user.ID,Role: registry.MemberRoleOwner,}if createErr := reg.CreateMembership(newMembership); createErr != nil {- reloaded, reloadErr := reg.GetMembership(accountID, userID)+ reloaded, reloadErr := reg.GetMembership(accountID, user.ID)if reloadErr != nil || reloaded == nil {- return "", "", fmt.Errorf("create membership: %w", createErr)+ return "", fmt.Errorf("create membership: %w", createErr)}- m = reloaded- } else {- m = newMembership}}- return userID, m.Role, nil+ return user.ID, nil}diff --git a/internal/cloudcp/auth/handlers_magiclink_test.go b/internal/cloudcp/auth/handlers_magiclink_test.goindex e97d45ea1c..ba90c8044b 100644--- a/internal/cloudcp/auth/handlers_magiclink_test.go+++ b/internal/cloudcp/auth/handlers_magiclink_test.go@@ -27,7 +27,7 @@ func TestHandleMagicLinkVerifyPortalTargetCreatesPortalSession(t *testing.T) {}t.Cleanup(svc.Close)- token, err := svc.GeneratePortalToken("[email protected]")+ token, err := svc.GeneratePortalToken("[email protected]", "")if err != nil {t.Fatalf("GeneratePortalToken: %v", err)}@@ -35,7 +35,7 @@ func TestHandleMagicLinkVerifyPortalTargetCreatesPortalSession(t *testing.T) {req := httptest.NewRequest(http.MethodGet, "/auth/magic-link/verify?token="+token, nil)rec := httptest.NewRecorder()- HandleMagicLinkVerify(svc, reg, filepath.Join(dir, "tenants"), "cloud.example.com")(rec, req)+ HandleMagicLinkVerify(svc, reg, filepath.Join(dir, "tenants"), "cloud.example.com", "/portal")(rec, req)if rec.Code != http.StatusTemporaryRedirect {t.Fatalf("status=%d body=%q", rec.Code, rec.Body.String())@@ -120,7 +120,7 @@ func TestHandleMagicLinkVerifyTenantTargetStillRedirectsToTenantHandoff(t *testireq := httptest.NewRequest(http.MethodGet, "/auth/magic-link/verify?token="+token, nil)rec := httptest.NewRecorder()- HandleMagicLinkVerify(svc, reg, tenantsDir, "cloud.example.com")(rec, req)+ HandleMagicLinkVerify(svc, reg, tenantsDir, "cloud.example.com", "/portal")(rec, req)if rec.Code != http.StatusTemporaryRedirect {t.Fatalf("status=%d body=%q", rec.Code, rec.Body.String())diff --git a/internal/cloudcp/auth/handlers_test.go b/internal/cloudcp/auth/handlers_test.gonew file mode 100644index 0000000000..fd11c4d80b--- /dev/null+++ b/internal/cloudcp/auth/handlers_test.go@@ -0,0 +1,86 @@+package auth++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"+)++func TestHandleMagicLinkVerifyPortalTargetCreatesSessionAndRedirectsToPortal(t *testing.T) {+ dir := t.TempDir()+ reg, err := registry.NewTenantRegistry(dir)+ if err != nil {+ t.Fatalf("NewTenantRegistry: %v", err)+ }+ t.Cleanup(func() { _ = reg.Close() })++ svc, err := NewService(dir)+ if err != nil {+ t.Fatalf("NewService: %v", err)+ }+ t.Cleanup(svc.Close)++ token, err := svc.GeneratePortalToken("[email protected]", "")+ if err != nil {+ t.Fatalf("GeneratePortalToken: %v", err)+ }++ req := httptest.NewRequest(http.MethodGet, "/auth/magic-link/verify?token="+token, nil)+ rec := httptest.NewRecorder()++ HandleMagicLinkVerify(svc, reg, dir, "cloud.example.com", "/portal")(rec, req)++ if rec.Code != http.StatusTemporaryRedirect {+ t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusTemporaryRedirect, rec.Body.String())+ }+ if got := rec.Header().Get("Location"); got != "/portal" {+ t.Fatalf("location=%q, want /portal", got)+ }+ foundSessionCookie := false+ for _, cookie := range rec.Result().Cookies() {+ if cookie.Name == SessionCookieName && cookie.Value != "" {+ foundSessionCookie = true+ break+ }+ }+ if !foundSessionCookie {+ t.Fatalf("expected %s cookie to be set", SessionCookieName)+ }++ user, err := reg.GetUserByEmail("[email protected]")+ if err != nil {+ t.Fatalf("GetUserByEmail: %v", err)+ }+ if user == nil {+ t.Fatal("expected control-plane user to be created")+ }+}++func TestHandleMagicLinkVerifyInvalidBrowserRedirectsToPortal(t *testing.T) {+ dir := t.TempDir()+ reg, err := registry.NewTenantRegistry(dir)+ if err != nil {+ t.Fatalf("NewTenantRegistry: %v", err)+ }+ t.Cleanup(func() { _ = reg.Close() })++ svc, err := NewService(dir)+ if err != nil {+ t.Fatalf("NewService: %v", err)+ }+ t.Cleanup(svc.Close)++ req := httptest.NewRequest(http.MethodGet, "/auth/magic-link/verify?token=ml1_invalid", nil)+ rec := httptest.NewRecorder()++ HandleMagicLinkVerify(svc, reg, dir, "cloud.example.com", "/portal")(rec, req)++ if rec.Code != http.StatusTemporaryRedirect {+ t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusTemporaryRedirect, rec.Body.String())+ }+ if got := rec.Header().Get("Location"); got != "/portal" {+ t.Fatalf("location=%q, want /portal", got)+ }+}diff --git a/internal/cloudcp/auth/magiclink.go b/internal/cloudcp/auth/magiclink.goindex 089035cfa2..1d46f9662c 100644--- a/internal/cloudcp/auth/magiclink.go+++ b/internal/cloudcp/auth/magiclink.go@@ -21,16 +21,20 @@ const (magicLinkPrefix = "ml1_"hmacKeyFile = ".cp_magic_link_key"hmacKeySize = 32+)++type MagicLinkTarget string- MagicLinkTargetTenantHandoff = "tenant_handoff"- MagicLinkTargetPortal = "portal"+const (+ MagicLinkTargetTenant MagicLinkTarget = "tenant"+ MagicLinkTargetPortal MagicLinkTarget = "portal")// Token holds the validated data from a consumed magic link token.type Token struct {Email stringTenantID string- Target string+ Target MagicLinkTargetExpiresAt time.Time}@@ -71,33 +75,34 @@ func NewService(cpDataDir string) (*Service, error) {// GenerateToken creates a new magic link token for the given email and tenant.// Returns a string in the format "ml1_<random>" that can be included in a URL.func (s *Service) GenerateToken(email, tenantID string) (string, error) {- return s.generateToken(email, tenantID, MagicLinkTargetTenantHandoff)+ return s.generateTokenForTarget(email, tenantID, MagicLinkTargetTenant)}-// GeneratePortalToken creates a new magic link token that signs the user into-// the Pulse Account portal without requiring a tenant handoff target.-func (s *Service) GeneratePortalToken(email string) (string, error) {- return s.generateToken(email, "", MagicLinkTargetPortal)+// GeneratePortalToken creates a new portal-targeted magic link token. tenantID+// is optional and, when present, is used during verification to ensure the+// control-plane membership exists before the session is established.+func (s *Service) GeneratePortalToken(email, tenantID string) (string, error) {+ return s.generateTokenForTarget(email, tenantID, MagicLinkTargetPortal)}-func (s *Service) generateToken(email, tenantID, target string) (string, error) {+func (s *Service) generateTokenForTarget(email, tenantID string, target MagicLinkTarget) (string, error) {if s == nil {return "", fmt.Errorf("magic link service not configured")}email = strings.ToLower(strings.TrimSpace(email))tenantID = strings.TrimSpace(tenantID)- target = strings.TrimSpace(target)if email == "" {return "", fmt.Errorf("email is required")}- if target == "" {- target = MagicLinkTargetTenantHandoff- }- if target == MagicLinkTargetTenantHandoff && tenantID == "" {- return "", fmt.Errorf("tenantID is required")- }- if target != MagicLinkTargetTenantHandoff && target != MagicLinkTargetPortal {- return "", fmt.Errorf("target is invalid")+ switch target {+ case MagicLinkTargetTenant:+ if tenantID == "" {+ return "", fmt.Errorf("tenantID is required")+ }+ case MagicLinkTargetPortal:+ // tenantID is optional for portal-targeted sign-in.+ default:+ return "", fmt.Errorf("unsupported magic link target %q", target)}expiresAt := s.now().UTC().Add(s.ttl)@@ -112,7 +117,7 @@ func (s *Service) generateToken(email, tenantID, target string) (string, error)if err := s.store.Put(tokenHash, &TokenRecord{Email: email,TenantID: tenantID,- Target: target,+ Target: string(target),ExpiresAt: expiresAt,}); err != nil {return "", err@@ -140,7 +145,7 @@ func (s *Service) ValidateToken(token string) (*Token, error) {return &Token{Email: rec.Email,TenantID: rec.TenantID,- Target: rec.Target,+ Target: MagicLinkTarget(rec.Target),ExpiresAt: rec.ExpiresAt,}, nil}diff --git a/internal/cloudcp/auth/magiclink_store.go b/internal/cloudcp/auth/magiclink_store.goindex 22608cbf53..8062bb5730 100644--- a/internal/cloudcp/auth/magiclink_store.go+++ b/internal/cloudcp/auth/magiclink_store.go@@ -96,8 +96,8 @@ func (s *Store) initSchema() error {CREATE TABLE IF NOT EXISTS magic_link_tokens (token_hash TEXT PRIMARY KEY,email TEXT NOT NULL,- tenant_id TEXT NOT NULL,- target TEXT NOT NULL DEFAULT '` + MagicLinkTargetTenantHandoff + `',+ tenant_id TEXT NOT NULL DEFAULT '',+ target TEXT NOT NULL DEFAULT 'tenant',expires_at INTEGER NOT NULL,used INTEGER NOT NULL DEFAULT 0,created_at INTEGER NOT NULL,@@ -109,41 +109,42 @@ func (s *Store) initSchema() error {if _, err := s.db.Exec(schema); err != nil {return fmt.Errorf("init magic link schema: %w", err)}- if err := ensureMagicLinkTargetColumn(s.db); err != nil {- return fmt.Errorf("ensure magic link target column: %w", err)+ if err := ensureMagicLinkColumn(s.db, "target", "ALTER TABLE magic_link_tokens ADD COLUMN target TEXT NOT NULL DEFAULT 'tenant'"); err != nil {+ return err+ }+ if err := ensureMagicLinkColumn(s.db, "tenant_id", "ALTER TABLE magic_link_tokens ADD COLUMN tenant_id TEXT NOT NULL DEFAULT ''"); err != nil {+ return err}return nil}-func ensureMagicLinkTargetColumn(db *sql.DB) error {+func ensureMagicLinkColumn(db *sql.DB, columnName, alterStmt string) error {rows, err := db.Query(`PRAGMA table_info(magic_link_tokens)`)if err != nil {- return err+ return fmt.Errorf("inspect magic link schema: %w", err)}defer rows.Close()for rows.Next() {- var (- cid int- name string- columnType string- notNull int- defaultVal sql.NullString- primaryKey int- )- if err := rows.Scan(&cid, &name, &columnType, ¬Null, &defaultVal, &primaryKey); err != nil {- return err+ var cid int+ var name, columnType string+ var notNull int+ var defaultValue sql.NullString+ var pk int+ if err := rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &pk); err != nil {+ return fmt.Errorf("scan magic link schema: %w", err)}- if name == "target" {+ if strings.EqualFold(name, columnName) {return nil}}if err := rows.Err(); err != nil {- return err+ return fmt.Errorf("iterate magic link schema: %w", err)}-- _, err = db.Exec(`ALTER TABLE magic_link_tokens ADD COLUMN target TEXT NOT NULL DEFAULT '` + MagicLinkTargetTenantHandoff + `'`)- return err+ if _, err := db.Exec(alterStmt); err != nil {+ return fmt.Errorf("add magic link column %s: %w", columnName, err)+ }+ return nil}func (s *Store) cleanupLoop() {@@ -172,15 +173,8 @@ func (s *Store) Put(tokenHash []byte, rec *TokenRecord) error {if rec == nil || rec.Email == "" || rec.ExpiresAt.IsZero() {return fmt.Errorf("token record is required")}- target := strings.TrimSpace(rec.Target)- if target == "" {- target = MagicLinkTargetTenantHandoff- }- if target == MagicLinkTargetTenantHandoff && strings.TrimSpace(rec.TenantID) == "" {- return fmt.Errorf("tenant-target tokens require tenantID")- }- if target != MagicLinkTargetTenantHandoff && target != MagicLinkTargetPortal {- return fmt.Errorf("target is invalid")+ if strings.TrimSpace(rec.Target) == "" {+ rec.Target = string(MagicLinkTargetTenant)}key := hex.EncodeToString(tokenHash)@@ -196,7 +190,7 @@ func (s *Store) Put(tokenHash []byte, rec *TokenRecord) error {_, err := db.Exec(`INSERT OR REPLACE INTO magic_link_tokens (token_hash, email, tenant_id, target, expires_at, used, created_at, used_at)VALUES (?, ?, ?, ?, ?, 0, ?, NULL)`,- key, rec.Email, rec.TenantID, target, rec.ExpiresAt.UTC().Unix(), now,+ key, rec.Email, rec.TenantID, rec.Target, rec.ExpiresAt.UTC().Unix(), now,)if err != nil {return fmt.Errorf("put magic link token: %w", err)diff --git a/internal/cloudcp/auth/magiclink_store_migration_test.go b/internal/cloudcp/auth/magiclink_store_migration_test.gonew file mode 100644index 0000000000..d101a86036--- /dev/null+++ b/internal/cloudcp/auth/magiclink_store_migration_test.go@@ -0,0 +1,62 @@+package auth++import (+ "database/sql"+ "path/filepath"+ "testing"+ "time"++ _ "modernc.org/sqlite"+)++func TestNewStoreMigratesLegacySchemaWithNoTargetColumn(t *testing.T) {+ dir := t.TempDir()+ dbPath := filepath.Join(dir, "cp_magic_links.db")++ db, err := sql.Open("sqlite", dbPath)+ if err != nil {+ t.Fatalf("sql.Open: %v", err)+ }+ defer db.Close()++ if _, err := db.Exec(`+ CREATE TABLE magic_link_tokens (+ token_hash TEXT PRIMARY KEY,+ email TEXT NOT NULL,+ tenant_id TEXT NOT NULL,+ expires_at INTEGER NOT NULL,+ used INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ used_at INTEGER+ );+ `); err != nil {+ t.Fatalf("create legacy schema: %v", err)+ }++ store, err := NewStore(dir)+ if err != nil {+ t.Fatalf("NewStore: %v", err)+ }+ t.Cleanup(store.Close)++ tokenHash := signHMAC([]byte("legacy-key"), "portal")+ if err := store.Put(tokenHash, &TokenRecord{+ Email: "[email protected]",+ TenantID: "",+ Target: string(MagicLinkTargetPortal),+ ExpiresAt: time.Now().UTC().Add(10 * time.Minute),+ }); err != nil {+ t.Fatalf("Put: %v", err)+ }++ rec, err := store.Consume(tokenHash, time.Now().UTC())+ if err != nil {+ t.Fatalf("Consume: %v", err)+ }+ if rec.Target != string(MagicLinkTargetPortal) {+ t.Fatalf("target=%q, want %q", rec.Target, MagicLinkTargetPortal)+ }+ if rec.TenantID != "" {+ t.Fatalf("tenantID=%q, want empty", rec.TenantID)+ }+}diff --git a/internal/cloudcp/auth/magiclink_store_queryplan_test.go b/internal/cloudcp/auth/magiclink_store_queryplan_test.goindex cd1bf0dc2c..5ec8c3f6ca 100644--- a/internal/cloudcp/auth/magiclink_store_queryplan_test.go+++ b/internal/cloudcp/auth/magiclink_store_queryplan_test.go@@ -70,7 +70,6 @@ func newMagicLinkPlanTestStore(t *testing.T) (*Store, []byte, time.Time) {rec := &TokenRecord{Email: fmt.Sprintf("user%[email protected]", i),TenantID: fmt.Sprintf("tenant-%02d", i%12),- Target: MagicLinkTargetTenantHandoff,ExpiresAt: base.Add(time.Duration(i-64) * time.Minute),}if err := store.Put(tokenHash, rec); err != nil {diff --git a/internal/cloudcp/auth/magiclink_test.go b/internal/cloudcp/auth/magiclink_test.goindex 2b4e5f788a..eb2fdaf4dc 100644--- a/internal/cloudcp/auth/magiclink_test.go+++ b/internal/cloudcp/auth/magiclink_test.go@@ -67,12 +67,12 @@ func TestValidateToken_Valid(t *testing.T) {if result.TenantID != "t-xyz" {t.Errorf("tenantID = %q, want t-xyz", result.TenantID)}- if result.Target != MagicLinkTargetTenantHandoff {- t.Errorf("target = %q, want %q", result.Target, MagicLinkTargetTenantHandoff)+ if result.Target != MagicLinkTargetTenant {+ t.Errorf("target = %q, want %q", result.Target, MagicLinkTargetTenant)}}-func TestGeneratePortalToken_Valid(t *testing.T) {+func TestValidateToken_PortalTargetAllowsEmptyTenant(t *testing.T) {dir := t.TempDir()svc, err := NewService(dir)if err != nil {@@ -80,7 +80,7 @@ func TestGeneratePortalToken_Valid(t *testing.T) {}defer svc.Close()- token, err := svc.GeneratePortalToken("[email protected]")+ token, err := svc.GeneratePortalToken("[email protected]", "")if err != nil {t.Fatalf("GeneratePortalToken: %v", err)}@@ -89,8 +89,8 @@ func TestGeneratePortalToken_Valid(t *testing.T) {if err != nil {t.Fatalf("ValidateToken: %v", err)}- if result.Email != "[email protected]" {- t.Errorf("email = %q, want [email protected]", result.Email)+ if result.Email != "[email protected]" {+ t.Errorf("email = %q, want [email protected]", result.Email)}if result.TenantID != "" {t.Errorf("tenantID = %q, want empty", result.TenantID)diff --git a/internal/cloudcp/commercial_identity.go b/internal/cloudcp/commercial_identity.goindex 9f4c2aae4c..3b7df23c1e 100644--- a/internal/cloudcp/commercial_identity.go+++ b/internal/cloudcp/commercial_identity.go@@ -4,16 +4,15 @@ import ("context""encoding/json""fmt"- "io""net/http""net/url""strings""time")-const defaultLicenseServerURL = "https://license.pulserelay.pro"+const commercialIdentityLookupTimeout = 10 * time.Second-type CommercialIdentityLookupResult struct {+type commercialIdentity struct {Email string `json:"email"`HasCommercialIdentity bool `json:"has_commercial_identity"`Sources []string `json:"sources,omitempty"`@@ -22,66 +21,55 @@ type CommercialIdentityLookupResult struct {StripeCustomerID string `json:"stripe_customer_id,omitempty"`}-type commercialIdentityLookup interface {- LookupCommercialIdentity(ctx context.Context, email string) (*CommercialIdentityLookupResult, error)-}--type commercialIdentityClient struct {- baseURL string- adminToken string- httpClient *http.Client-}+type commercialIdentityLookupFunc func(ctx context.Context, email string) (*commercialIdentity, error)-func newCommercialIdentityClient(cfg *CPConfig) commercialIdentityLookup {+func newCommercialIdentityLookup(cfg *CPConfig) commercialIdentityLookupFunc {if cfg == nil {return nil}+ baseURL := strings.TrimSpace(cfg.LicenseServerURL)adminToken := strings.TrimSpace(cfg.LicenseAdminToken)- if adminToken == "" {+ if baseURL == "" || adminToken == "" {return nil}- baseURL := strings.TrimRight(strings.TrimSpace(cfg.LicenseServerURL), "/")- if baseURL == "" {- baseURL = defaultLicenseServerURL- }- return &commercialIdentityClient{- baseURL: baseURL,- adminToken: adminToken,- httpClient: &http.Client{Timeout: 10 * time.Second},- }-}-func (c *commercialIdentityClient) LookupCommercialIdentity(ctx context.Context, email string) (*CommercialIdentityLookupResult, error) {- if c == nil {- return nil, nil- }- email = strings.TrimSpace(email)- if email == "" {- return nil, fmt.Errorf("email is required")- }+ client := &http.Client{Timeout: commercialIdentityLookupTimeout}+ return func(ctx context.Context, email string) (*commercialIdentity, error) {+ email = strings.TrimSpace(email)+ if email == "" {+ return nil, fmt.Errorf("email is required")+ }- endpoint := c.baseURL + "/v1/admin/commercial/lookup?email=" + url.QueryEscape(email)- req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)- if err != nil {- return nil, fmt.Errorf("create commercial identity request: %w", err)- }- req.Header.Set("Accept", "application/json")- req.Header.Set("X-API-Token", c.adminToken)+ endpoint, err := url.Parse(baseURL)+ if err != nil {+ return nil, fmt.Errorf("parse license server url: %w", err)+ }+ endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/v1/admin/commercial/lookup"+ query := endpoint.Query()+ query.Set("email", email)+ endpoint.RawQuery = query.Encode()- resp, err := c.httpClient.Do(req)- if err != nil {- return nil, fmt.Errorf("commercial identity request failed: %w", err)- }- defer resp.Body.Close()+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)+ if err != nil {+ return nil, fmt.Errorf("build commercial lookup request: %w", err)+ }+ req.Header.Set("X-Admin-Key", adminToken)+ req.Header.Set("Accept", "application/json")- if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<16))- return nil, fmt.Errorf("commercial identity lookup returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))- }+ resp, err := client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("perform commercial lookup request: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("commercial lookup returned status %d", resp.StatusCode)+ }- var result CommercialIdentityLookupResult- if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil {- return nil, fmt.Errorf("decode commercial identity response: %w", err)+ var result commercialIdentity+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ return nil, fmt.Errorf("decode commercial lookup response: %w", err)+ }+ return &result, nil}- return &result, nil}diff --git a/internal/cloudcp/config.go b/internal/cloudcp/config.goindex 7f41d42fa9..84b186678d 100644--- a/internal/cloudcp/config.go+++ b/internal/cloudcp/config.go@@ -1,6 +1,8 @@package cloudcpimport (+ "crypto/ed25519"+ "encoding/base64""fmt""net/url""os"@@ -9,6 +11,7 @@ import ("strings""github.com/joho/godotenv"+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing")// CPConfig holds all configuration for the control plane.@@ -29,6 +32,7 @@ type CPConfig struct {PortalAPIRateLimitPerMinute intPulseImage stringDockerNetwork string+ TrustedProxyCIDRs []stringTenantMemoryLimit int64 // bytesTenantCPUShares int64AllowDockerlessProvisioning bool@@ -37,12 +41,13 @@ type CPConfig struct {TrialSignupPriceID string // Cloud Starter (default tier) price IDCloudPowerPriceID string // Cloud Power tier price ID (optional)CloudMaxPriceID string // Cloud Max tier price ID (optional)+ LicenseServerURL string+ LicenseAdminToken stringTrialActivationPrivateKey string+ TrialActivationPublicKey stringRequireEmailProvider boolResendAPIKey string // Resend API key (optional — if empty, emails are logged)EmailFrom string // Sender email address (e.g. "[email protected]")- LicenseServerURL string- LicenseAdminToken string}// TenantsDir returns the directory where per-tenant data is stored.@@ -115,6 +120,7 @@ func LoadConfig() (*CPConfig, error) {PortalAPIRateLimitPerMinute: portalRPS,PulseImage: envOrDefault("CP_PULSE_IMAGE", "ghcr.io/rcourtman/pulse:latest"),DockerNetwork: envOrDefault("CP_DOCKER_NETWORK", "pulse-cloud"),+ TrustedProxyCIDRs: parseTrustedProxyCIDRValues("CP_TRUSTED_PROXY_CIDRS", "PULSE_TRUSTED_PROXY_CIDRS"),TenantMemoryLimit: tenantMemoryLimit,TenantCPUShares: tenantCPUShares,AllowDockerlessProvisioning: envOrDefaultBool("CP_ALLOW_DOCKERLESS_PROVISIONING", false),@@ -123,12 +129,19 @@ func LoadConfig() (*CPConfig, error) {TrialSignupPriceID: strings.TrimSpace(os.Getenv("CP_TRIAL_SIGNUP_PRICE_ID")),CloudPowerPriceID: strings.TrimSpace(os.Getenv("CP_CLOUD_POWER_PRICE_ID")),CloudMaxPriceID: strings.TrimSpace(os.Getenv("CP_CLOUD_MAX_PRICE_ID")),+ LicenseServerURL: envOrDefault("PULSE_LICENSE_SERVER_URL", "https://license.pulserelay.pro"),+ LicenseAdminToken: strings.TrimSpace(os.Getenv("PULSE_LICENSE_ADMIN_TOKEN")),TrialActivationPrivateKey: strings.TrimSpace(os.Getenv("CP_TRIAL_ACTIVATION_PRIVATE_KEY")),RequireEmailProvider: envOrDefaultBool("CP_REQUIRE_EMAIL_PROVIDER", true),ResendAPIKey: strings.TrimSpace(os.Getenv("RESEND_API_KEY")),EmailFrom: envOrDefault("PULSE_EMAIL_FROM", "[email protected]"),- LicenseServerURL: strings.TrimSpace(envOrDefault("PULSE_LICENSE_SERVER_URL", defaultLicenseServerURL)),- LicenseAdminToken: strings.TrimSpace(os.Getenv("PULSE_LICENSE_ADMIN_TOKEN")),+ }+ if strings.TrimSpace(cfg.TrialActivationPrivateKey) != "" {+ publicKey, err := deriveTrialActivationPublicKey(cfg.TrialActivationPrivateKey)+ if err != nil {+ return nil, fmt.Errorf("derive trial activation public key: %w", err)+ }+ cfg.TrialActivationPublicKey = publicKey}if err := cfg.validate(); err != nil {@@ -137,6 +150,18 @@ func LoadConfig() (*CPConfig, error) {return cfg, nil}+func deriveTrialActivationPublicKey(encodedPrivateKey string) (string, error) {+ privateKey, err := pkglicensing.DecodeEd25519PrivateKey(strings.TrimSpace(encodedPrivateKey))+ if err != nil {+ return "", err+ }+ publicKey, ok := privateKey.Public().(ed25519.PublicKey)+ if !ok || len(publicKey) != ed25519.PublicKeySize {+ return "", fmt.Errorf("invalid derived trial activation public key")+ }+ return base64.StdEncoding.EncodeToString(publicKey), nil+}+func (c *CPConfig) validate() error {var missing []stringif c.AdminKey == "" {@@ -199,6 +224,9 @@ func (c *CPConfig) validate() error {if strings.TrimSpace(c.StripeAPIKey) != "" && strings.TrimSpace(c.TrialActivationPrivateKey) == "" {return fmt.Errorf("CP_TRIAL_ACTIVATION_PRIVATE_KEY is required when STRIPE_API_KEY is configured")}+ if strings.TrimSpace(c.LicenseServerURL) == "" && strings.TrimSpace(c.LicenseAdminToken) != "" {+ return fmt.Errorf("PULSE_LICENSE_SERVER_URL is required when PULSE_LICENSE_ADMIN_TOKEN is configured")+ }if strings.TrimSpace(c.StripeAPIKey) != "" {stripeMode := stripeSecretKeyMode(c.StripeAPIKey)switch c.Environment {@@ -223,18 +251,6 @@ func (c *CPConfig) validate() error {if parsedBaseURL.Host == "" {return fmt.Errorf("CP_BASE_URL must include a host")}- if c.LicenseServerURL != "" {- parsedLicenseURL, err := url.Parse(c.LicenseServerURL)- if err != nil {- return fmt.Errorf("PULSE_LICENSE_SERVER_URL must be a valid URL: %w", err)- }- if parsedLicenseURL.Scheme != "http" && parsedLicenseURL.Scheme != "https" {- return fmt.Errorf("PULSE_LICENSE_SERVER_URL must use http or https scheme")- }- if parsedLicenseURL.Host == "" {- return fmt.Errorf("PULSE_LICENSE_SERVER_URL must include a host")- }- }return nil}@@ -301,3 +317,26 @@ func envOrDefaultBool(key string, fallback bool) bool {return fallback}}++func parseTrustedProxyCIDRValues(keys ...string) []string {+ values := make([]string, 0)+ seen := make(map[string]struct{})+ for _, key := range keys {+ raw := strings.TrimSpace(os.Getenv(key))+ if raw == "" {+ continue+ }+ for _, entry := range strings.Split(raw, ",") {+ entry = strings.TrimSpace(entry)+ if entry == "" {+ continue+ }+ if _, ok := seen[entry]; ok {+ continue+ }+ seen[entry] = struct{}{}+ values = append(values, entry)+ }+ }+ return values+}diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.jsonindex 61bdcd2344..ae9d5c941b 100644--- a/internal/cloudcp/portal/dist/build_manifest.json+++ b/internal/cloudcp/portal/dist/build_manifest.json@@ -1,5 +1,5 @@{- "source_hash": "918ada89ef87e6fc50df48b964eb2ebce6fc24b6d151c2823c062761fa33748f",+ "source_hash": "7505a9b901c8b7ebb92ddf00680e261dd82a88758f8aea0e9bf9cc0ba2a17ae5","build_inputs": ["package.json","tsconfig.json",diff --git a/internal/cloudcp/portal/dist/portal_app.js b/internal/cloudcp/portal/dist/portal_app.jsindex 887b42211c..0a8c3597cd 100644--- a/internal/cloudcp/portal/dist/portal_app.js+++ b/internal/cloudcp/portal/dist/portal_app.js@@ -10,6 +10,64 @@var input = getElement(id);if (input) input.focus();}+ function workspaceActionLabel(workspace) {+ return workspace.state === "active" ? "Suspend workspace" : "Delete workspace";+ }+ function workspaceSummary(workspace) {+ if (workspace.health_status === "healthy") return "Live updates and health checks are currently good.";+ if (workspace.health_status === "unhealthy") return "This workspace needs attention before it is trustworthy.";+ return "This workspace is still waiting on a completed health check.";+ }+ function workspaceMeta(workspace) {+ var parts = [workspace.state];+ if (workspace.health_status) parts.push(workspace.health_status);+ if (workspace.created_at) {+ var date = new Date(workspace.created_at);+ if (!Number.isNaN(date.getTime())) {+ parts.push("Created " + date.toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" }));+ }+ }+ return parts.join(" \xB7 ");+ }+ function findWorkspace(account, workspaceID) {+ for (var i = 0; i < account.workspaces.length; i += 1) {+ if (account.workspaces[i].id === workspaceID) return account.workspaces[i];+ }+ return null;+ }+ function renderWorkspaceManagement(account, entry) {+ var panel = getElement("workspace-management-" + account.id);+ if (!panel) return;+ var empty = getElement("workspace-management-empty-" + account.id);+ var content = getElement("workspace-management-content-" + account.id);+ var title = getElement("workspace-management-title-" + account.id);+ var meta = getElement("workspace-management-meta-" + account.id);+ var summary = getElement("workspace-management-summary-" + account.id);+ var actionButton = getElement("workspace-management-action-" + account.id);+ var closeButton = getElement("workspace-management-close-" + account.id);+ if (!empty || !content || !title || !meta || !summary || !actionButton || !closeButton) return;+ var workspace = entry.selectedWorkspaceID ? findWorkspace(account, entry.selectedWorkspaceID) : null;+ var hasSelection = !!workspace;+ panel.classList.toggle("visible", hasSelection);+ empty.hidden = hasSelection;+ content.hidden = !hasSelection;+ if (!workspace) {+ actionButton.disabled = false;+ actionButton.removeAttribute("data-workspace-id");+ actionButton.removeAttribute("data-workspace-name");+ actionButton.removeAttribute("data-workspace-action");+ return;+ }+ title.textContent = workspace.display_name;+ meta.textContent = workspaceMeta(workspace);+ summary.textContent = workspaceSummary(workspace);+ actionButton.textContent = workspaceActionLabel(workspace);+ actionButton.disabled = entry.manageWorkspace.pending;+ actionButton.setAttribute("data-workspace-id", workspace.id);+ actionButton.setAttribute("data-workspace-name", workspace.display_name);+ actionButton.setAttribute("data-workspace-action", workspace.state === "active" ? "suspend" : "delete");+ closeButton.disabled = entry.manageWorkspace.pending;+ }function setTbodyMessage(tbody, msg, isError) {tbody.textContent = "";var tr = document.createElement("tr");@@ -20,6 +78,31 @@tr.appendChild(td);tbody.appendChild(tr);}+ function countMembersByRole(members, role) {+ var count = 0;+ for (var i = 0; i < members.length; i += 1) {+ if (members[i].role === role) count += 1;+ }+ return count;+ }+ function renderTeamStats(accountID, entry) {+ var stats = getElement("team-stats-" + accountID);+ if (!stats) return;+ if (!entry.teamVisible) {+ stats.innerHTML = "";+ return;+ }+ if (entry.teamQuery.status === "loading") {+ stats.innerHTML = '<div class="team-stat-card"><span class="team-stat-label">Roster</span><span class="team-stat-value">Loading\u2026</span></div>';+ return;+ }+ if (entry.teamQuery.status === "error") {+ stats.innerHTML = '<div class="team-stat-card"><span class="team-stat-label">Roster</span><span class="team-stat-value team-stat-error">Needs attention</span></div>';+ return;+ }+ var members = entry.teamQuery.data;+ stats.innerHTML = '<div class="team-stat-card"><span class="team-stat-label">Members</span><span class="team-stat-value">' + String(members.length) + '</span></div><div class="team-stat-card"><span class="team-stat-label">Owners</span><span class="team-stat-value">' + String(countMembersByRole(members, "owner")) + '</span></div><div class="team-stat-card"><span class="team-stat-label">Admins</span><span class="team-stat-value">' + String(countMembersByRole(members, "admin")) + '</span></div><div class="team-stat-card"><span class="team-stat-label">Operators</span><span class="team-stat-value">' + String(countMembersByRole(members, "tech") + countMembersByRole(members, "read_only")) + "</span></div>";+ }function renderTeamMemberRoleCell(accountID, member, isOwner) {var tdRole = document.createElement("td");if (member.role === "owner" && !isOwner) {@@ -73,6 +156,7 @@var actorRole = section.getAttribute("data-actor-role") || "";var isOwner = actorRole === "owner";section.classList.toggle("visible", entry.teamVisible);+ renderTeamStats(accountID, entry);if (!entry.teamVisible) {return;}@@ -100,12 +184,20 @@tbody.appendChild(tr);}}- function renderAccountUI(accountState) {+ function renderAccountUI(accountState, accounts) {var accountIDs = Object.keys(accountState.byAccountID);for (var i = 0; i < accountIDs.length; i += 1) {var accountID = accountIDs[i];var entry = accountState.byAccountID[accountID];+ var account = null;+ for (var j = 0; j < accounts.length; j += 1) {+ if (accounts[j].id === accountID) {+ account = accounts[j];+ break;+ }+ }renderAddWorkspaceSection(accountID, entry);+ if (account) renderWorkspaceManagement(account, entry);renderTeamSection(accountID, entry);}}@@ -113,7 +205,9 @@// src/account_controller.tsfunction installAccountController(deps) {document.addEventListener("click", function(event) {- var actionEl = asHTMLElement(event.target)?.closest("[data-action]");+ var target = asHTMLElement(event.target);+ if (!target) return;+ var actionEl = target.closest("[data-action]");if (!actionEl) return;var action = actionEl.getAttribute("data-action") || "";var accountID = actionEl.getAttribute("data-account-id") || "";@@ -138,13 +232,23 @@event.preventDefault();void deps.runtime.createWorkspace(accountID);return;- case "workspace-manage":+ case "select-workspace":+ event.preventDefault();+ deps.runtime.selectWorkspace(+ accountID,+ actionEl.getAttribute("data-workspace-id") || ""+ );+ return;+ case "clear-workspace-selection":+ event.preventDefault();+ deps.runtime.clearWorkspaceSelection(accountID);+ return;+ case "workspace-action":event.preventDefault();- void deps.runtime.manageWorkspace(- event,+ void deps.runtime.manageWorkspaceAction(accountID,actionEl.getAttribute("data-workspace-id") || "",- actionEl.getAttribute("data-workspace-state") || "",+ actionEl.getAttribute("data-workspace-action") || "",actionEl.getAttribute("data-workspace-name") || "");return;@@ -293,7 +397,7 @@}, "Failed to sign out.");},postCommercialJSON: function(path, body) {- return request(bootstrap().commercial_api_base_path + path, {+ return request(bootstrap().commercial_api_base_url + path, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(body)@@ -400,6 +504,8 @@accountState.byAccountID[accountID] = {addWorkspaceOpen: false,createWorkspace: createMutationState(),+ selectedWorkspaceID: "",+ manageWorkspace: createMutationState(),teamVisible: false,teamQuery: createQueryState([])};@@ -513,7 +619,7 @@return true;};var renderAccountRuntime = function() {- renderAccountUI(deps.store.getAccountState());+ renderAccountUI(deps.store.getAccountState(), deps.store.getBootstrap().accounts || []);};var loadTeam = async function(accountID) {var section = getElement("team-section-" + accountID);@@ -562,6 +668,18 @@focusElement("ws-name-" + accountID);}};+ var selectWorkspace = function(accountID, workspaceID) {+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ entry.selectedWorkspaceID = entry.selectedWorkspaceID === workspaceID ? "" : workspaceID;+ });+ };+ var clearWorkspaceSelection = function(accountID) {+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ entry.selectedWorkspaceID = "";+ });+ };var createWorkspace = async function(accountID) {var nameEl = getElement("ws-name-" + accountID);if (!nameEl) return;@@ -598,22 +716,39 @@deps.showToast(message, true);}};- var manageWorkspace = async function(evt, accountID, tenantID, state, name) {- evt.stopPropagation();- var action = state === "active" ? "Suspend" : "Delete";- if (!window.confirm(action + ' workspace "' + name + '"?')) return;+ var manageWorkspaceAction = async function(accountID, tenantID, action, name) {+ var verb = action === "suspend" ? "Suspend" : action === "delete" ? "Delete" : "";+ if (!verb) return;+ if (!window.confirm(verb + ' workspace "' + name + '"?')) return;+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ beginMutationState(entry.manageWorkspace);+ });try {- if (state === "active") {+ if (action === "suspend") {await deps.api.suspendWorkspace(accountID, tenantID);} else {await deps.api.deleteWorkspace(accountID, tenantID);}if (!await refreshOrRedirect()) {+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ resetMutationState(entry.manageWorkspace);+ }, { notify: false });return;}- deps.showToast(action + "d workspace.");+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ entry.selectedWorkspaceID = "";+ succeedMutationState(entry.manageWorkspace);+ });+ deps.showToast(verb + "ed workspace.");} catch (error) {- deps.showToast(error instanceof Error ? error.message : "Failed to " + action.toLowerCase() + " workspace.", true);+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ failMutationState(entry.manageWorkspace, error instanceof Error ? error.message : "Failed to " + verb.toLowerCase() + " workspace.");+ }, { notify: false });+ deps.showToast(error instanceof Error ? error.message : "Failed to " + verb.toLowerCase() + " workspace.", true);}};var openBilling = async function(accountID) {@@ -700,18 +835,19 @@deps.store.subscribeBootstrap(renderAccountRuntime);return {toggleAddWorkspace,+ selectWorkspace,+ clearWorkspaceSelection,openBilling,toggleTeam,inviteMember,createWorkspace,- manageWorkspace,+ manageWorkspaceAction,removeMember,changeRole};}// src/auth_controller.ts- var GENERIC_MAGIC_LINK_MESSAGE = "If that email is registered, you'll receive a magic link shortly.";function asHTMLElement2(target) {return target instanceof HTMLElement ? target : null;}@@ -741,7 +877,7 @@deps.store.updateLoginState(function(nextState) {succeedMutationState(nextState.request);nextState.success = true;- nextState.successMessage = String(response && response.message || "").trim() || GENERIC_MAGIC_LINK_MESSAGE;+ nextState.successMessage = String(response?.message || "").trim();});return;} catch (error) {@@ -749,7 +885,7 @@deps.store.updateLoginState(function(nextState) {succeedMutationState(nextState.request);nextState.success = true;- nextState.successMessage = GENERIC_MAGIC_LINK_MESSAGE;+ nextState.successMessage = "";});return;}@@ -1367,12 +1503,6 @@}// src/shell_view.ts- function hasHostedAccounts(bootstrap) {- return Array.isArray(bootstrap.accounts) && bootstrap.accounts.length > 0;- }- function listAccounts(bootstrap) {- return Array.isArray(bootstrap.accounts) ? bootstrap.accounts : [];- }function escapeHTML(value) {return String(value || "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");}@@ -1391,41 +1521,73 @@if (role === "tech") return '<span class="badge badge-role">Tech</span>';return "";}- function formatRoleLabel(role) {- if (role === "owner") return "Owner";- if (role === "admin") return "Admin";- if (role === "tech") return "Tech";- if (role === "read_only") return "Read-only";- return "Member";- }- function formatAccountAccessLabel(accounts) {- if (accounts.length === 1) {- if (accounts[0].kind === "msp") return "MSP operator";- if (accounts[0].kind === "cloud" || accounts[0].kind === "individual") return "Pulse Cloud";- }- return "Hosted access";- }- function totalWorkspaceCount(accounts) {- return accounts.reduce(function(total, account) {- return total + (Array.isArray(account.workspaces) ? account.workspaces.length : 0);- }, 0);- }- function totalActiveWorkspaceCount(accounts) {- return accounts.reduce(function(total, account) {- return total + (Array.isArray(account.workspaces) ? account.workspaces.filter(function(workspace) {- return workspace.state === "active";- }).length : 0);- }, 0);- }- function formatAccountSummary(account) {- var workspaceCount = Array.isArray(account.workspaces) ? account.workspaces.length : 0;- var workspaceLabel = workspaceCount === 1 ? "1 workspace" : String(workspaceCount) + " workspaces";- return account.kind_label + " account \xB7 " + formatRoleLabel(account.role) + " \xB7 " + workspaceLabel;+ function healthBadgeHTML(workspace) {+ if (workspace.health_status === "healthy") {+ return '<span class="badge badge-healthy">Healthy</span>';+ }+ if (workspace.health_status === "unhealthy") {+ return '<span class="badge badge-unhealthy">Unhealthy</span>';+ }+ return '<span class="badge badge-checking">Checking</span>';+ }+ function workspaceCountLabel(count) {+ return count === 1 ? "1 workspace" : String(count) + " workspaces";+ }+ function accountKindLabel(account) {+ if (account.kind === "msp") return "MSP account";+ if (account.kind === "cloud") return "Cloud account";+ if (account.kind === "individual") return "Hosted account";+ return account.kind_label ? account.kind_label + " account" : "Account";+ }+ function titleCase(value) {+ if (!value) return "";+ return value.charAt(0).toUpperCase() + value.slice(1);+ }+ function countWorkspaces(accounts) {+ var total = 0;+ for (var i = 0; i < accounts.length; i += 1) {+ total += Array.isArray(accounts[i].workspaces) ? accounts[i].workspaces.length : 0;+ }+ return total;+ }+ function hasHostedAccounts(accounts) {+ return accounts.length > 0;+ }+ function countWorkspacesByHealth(workspaces, status) {+ var count = 0;+ for (var i = 0; i < workspaces.length; i += 1) {+ if (String(workspaces[i].health_status || "") === status) count += 1;+ }+ return count;+ }+ function countWorkspacesByState(workspaces, state) {+ var count = 0;+ for (var i = 0; i < workspaces.length; i += 1) {+ if (String(workspaces[i].state || "") === state) count += 1;+ }+ return count;+ }+ function renderOverviewBand(context, accounts) {+ var hosted = hasHostedAccounts(accounts);+ var workspaceTotal = countWorkspaces(accounts);+ var title = hosted ? "Pulse Account" : "Self-hosted Pulse Account";+ var summary = hosted ? "Open hosted workspaces, manage account access, and handle commercial account services from one place." : "This account currently has no hosted workspaces. Self-hosted licenses, billing, refunds, and data requests stay available below.";+ var hostedStateLabel = hosted ? "Active" : "Not attached";+ var hostedStateClass = hosted ? "overview-stat-positive" : "overview-stat-muted";+ var accountsLabel = accounts.length === 1 ? "1 account" : String(accounts.length) + " accounts";+ return '<section class="overview-band"><div class="overview-copy"><div class="overview-kicker">' + (hosted ? "Hosted access is active on this account." : "No hosted workspace access is attached to this account yet.") + "</div><h1>" + title + "</h1><p>" + summary + '</p></div><div class="overview-stats"><div class="overview-stat-card"><span class="overview-stat-label">Hosted access</span><span class="overview-stat-value ' + hostedStateClass + '">' + hostedStateLabel + '</span></div><div class="overview-stat-card"><span class="overview-stat-label">Accounts</span><span class="overview-stat-value">' + accountsLabel + '</span></div><div class="overview-stat-card"><span class="overview-stat-label">Workspaces</span><span class="overview-stat-value">' + String(workspaceTotal) + "</span></div></div></section>";+ }+ function renderShellNavigation(accounts, supportEmail) {+ var hosted = hasHostedAccounts(accounts);+ var hostedLabel = hosted ? "Hosted operations" : "Hosted access";+ var hostedCopy = hosted ? "Workspaces, teams, and hosted billing" : "No hosted workspaces are attached yet";+ return '<nav class="portal-section-nav" aria-label="Pulse Account sections"><a class="portal-section-link" href="#hosted-operations-section"><span class="portal-section-link-label">' + hostedLabel + '</span><span class="portal-section-link-copy">' + hostedCopy + '</span></a><a class="portal-section-link" href="#account-services-section"><span class="portal-section-link-label">Account services</span><span class="portal-section-link-copy">Licenses, billing, refunds, and privacy</span></a><a class="portal-section-link" href="mailto:' + escapeAttr(supportEmail || "") + '"><span class="portal-section-link-label">Support</span><span class="portal-section-link-copy">' + escapeHTML(supportEmail || "") + "</span></a></nav>";}function renderWorkspaceCard(account, workspace, accountAPIBasePath) {var state = String(workspace.state || "");var safeState = escapeHTML(state);var createdLabel = formatWorkspaceDate(workspace.created_at);+ var healthSummary = workspace.health_status === "healthy" ? "Live updates and health checks are currently good." : workspace.health_status === "unhealthy" ? "This workspace needs attention before it is trustworthy." : "This workspace is still waiting on a completed health check.";var openAction = "";if (state === "active") {openAction = '<form method="POST" action="' + escapeAttr(accountAPIBasePath + "/" + account.id + "/tenants/" + workspace.id + "/handoff") + '"><button type="submit" class="btn-primary">Open workspace</button></form>';@@ -1434,16 +1596,22 @@}var manageAction = "";if (account.can_manage && (state === "active" || state === "suspended" || state === "failed")) {- manageAction = '<button type="button" class="btn-secondary btn-secondary-quiet" data-action="workspace-manage" data-account-id="' + escapeAttr(account.id) + '" data-workspace-id="' + escapeAttr(workspace.id) + '" data-workspace-state="' + escapeAttr(state) + '" data-workspace-name="' + escapeAttr(workspace.display_name) + '">Manage</button>';+ manageAction = '<button type="button" class="btn-secondary btn-workspace-manage" data-action="select-workspace" data-account-id="' + escapeAttr(account.id) + '" data-workspace-id="' + escapeAttr(workspace.id) + '">Manage</button>';}var createdMeta = createdLabel ? '<span class="ws-created">Created ' + escapeHTML(createdLabel) + "</span>" : "";- return '<div class="workspace-card"><div class="ws-info"><span class="ws-name">' + escapeHTML(workspace.display_name) + '</span><div class="ws-meta">' + (workspace.healthy ? '<span class="badge badge-healthy">Healthy</span>' : '<span class="badge badge-unhealthy">Checking</span>') + '<span class="badge badge-' + safeState + '">' + safeState + "</span>" + createdMeta + '</div></div><div class="ws-actions">' + openAction + manageAction + "</div></div>";+ return '<div class="workspace-card"><div class="ws-info"><div class="ws-title-row"><span class="ws-name">' + escapeHTML(workspace.display_name) + '</span></div><div class="ws-meta">' + healthBadgeHTML(workspace) + '<span class="badge badge-' + safeState + '">' + safeState + "</span>" + createdMeta + '</div><div class="ws-summary">' + escapeHTML(healthSummary) + '</div></div><div class="ws-actions">' + openAction + manageAction + "</div></div>";}function renderAccountSection(account, accountAPIBasePath) {var workspaces = Array.isArray(account.workspaces) ? account.workspaces : [];+ var summaryText = accountKindLabel(account) + " \xB7 " + titleCase(account.role) + " \xB7 " + workspaceCountLabel(workspaces.length);+ var healthyCount = countWorkspacesByHealth(workspaces, "healthy");+ var checkingCount = countWorkspacesByHealth(workspaces, "checking");+ var unhealthyCount = countWorkspacesByHealth(workspaces, "unhealthy");+ var activeCount = countWorkspacesByState(workspaces, "active");+ var operationsCopy = account.kind === "msp" ? "Manage the client fleet from this account surface. Workspace creation, billing, and team actions belong here." : "Use this account surface to open hosted workspaces, manage billing, and control access for this hosted account.";var workspaceHTML = "";if (workspaces.length === 0) {- workspaceHTML = '<div class="empty-state empty-state-account"><p class="empty-state-title">' + (account.kind === "msp" ? "No client workspaces yet" : "No hosted workspaces yet") + "</p><p>" + (account.kind === "msp" ? "Create a workspace when you are ready to onboard a customer environment." : "This account is ready for hosted access, but no workspace has been provisioned yet.") + "</p></div>";+ workspaceHTML = '<div class="empty-state"><p>No hosted workspaces yet. Create one to get started.</p></div>';} else {workspaceHTML = '<div class="workspace-list">' + workspaces.map(function(workspace) {return renderWorkspaceCard(account, workspace, accountAPIBasePath);@@ -1452,14 +1620,16 @@var actions = "";var teamSection = "";var addWorkspaceForm = "";+ var workspaceManagement = "";if (account.can_manage) {- actions = '<div class="account-actions">' + (account.kind === "msp" ? '<button type="button" class="btn-secondary" id="add-ws-btn-' + escapeAttr(account.id) + '" data-action="toggle-add-workspace" data-account-id="' + escapeAttr(account.id) + '">+ Add workspace</button>' : "") + (account.has_billing ? '<button type="button" class="btn-secondary" data-action="open-billing" data-account-id="' + escapeAttr(account.id) + '">Manage billing</button>' : "") + '<button type="button" class="btn-secondary" id="team-btn-' + escapeAttr(account.id) + '" data-action="toggle-team" data-account-id="' + escapeAttr(account.id) + '">Manage team</button></div>';- teamSection = '<div class="team-section" id="team-section-' + escapeAttr(account.id) + '" data-actor-role="' + escapeAttr(account.role) + '"><h3>Team members</h3><table class="team-table"><thead><tr><th>Email</th><th>Role</th><th></th></tr></thead><tbody id="team-list-' + escapeAttr(account.id) + '"><tr><td colspan="3" class="team-message-cell">Loading\u2026</td></tr></tbody></table><div class="team-invite"><div><label for="invite-email-' + escapeAttr(account.id) + '">Email</label><input type="email" id="invite-email-' + escapeAttr(account.id) + '" placeholder="[email protected]" autocomplete="off"></div><div><label for="invite-role-' + escapeAttr(account.id) + '">Role</label><select id="invite-role-' + escapeAttr(account.id) + '"><option value="admin">Admin</option><option value="tech">Tech</option><option value="read_only">Read-only</option></select></div><button type="button" class="btn-primary btn-compact" data-action="invite-member" data-account-id="' + escapeAttr(account.id) + '">Invite</button></div></div>';+ actions = '<div class="account-operations-panel"><div class="account-operations-copy"><h3>Account operations</h3><p>' + escapeHTML(operationsCopy) + '</p></div><div class="account-actions">' + (account.kind === "msp" ? '<button type="button" class="btn-secondary" id="add-ws-btn-' + escapeAttr(account.id) + '" data-action="toggle-add-workspace" data-account-id="' + escapeAttr(account.id) + '">Add workspace</button>' : "") + (account.has_billing ? '<button type="button" class="btn-secondary" data-action="open-billing" data-account-id="' + escapeAttr(account.id) + '">Manage billing</button>' : "") + '<button type="button" class="btn-secondary" id="team-btn-' + escapeAttr(account.id) + '" data-action="toggle-team" data-account-id="' + escapeAttr(account.id) + '">Manage team</button></div></div>';+ teamSection = '<div class="team-management-panel team-section" id="team-section-' + escapeAttr(account.id) + '" data-actor-role="' + escapeAttr(account.role) + '"><div class="team-management-header"><div><h3>Team management</h3><p>Control who can operate this account, what role they hold, and who should be invited next.</p></div><button type="button" class="btn-secondary btn-compact" data-action="toggle-team" data-account-id="' + escapeAttr(account.id) + '">Done</button></div><div class="team-management-stats" id="team-stats-' + escapeAttr(account.id) + '"></div><div class="team-management-grid"><div class="team-roster"><div class="team-panel-heading"><h4>People on this account</h4><p>Owners can manage billing and account access. Admins and techs keep the hosted fleet running day to day.</p></div><table class="team-table"><thead><tr><th>Email</th><th>Role</th><th></th></tr></thead><tbody id="team-list-' + escapeAttr(account.id) + '"><tr><td colspan="3" class="team-message-cell">Loading\u2026</td></tr></tbody></table></div><div class="team-invite-panel"><div class="team-panel-heading"><h4>Invite someone new</h4><p>Add another operator with the minimum role they need for this account.</p></div><div class="team-invite"><div><label for="invite-email-' + escapeAttr(account.id) + '">Email</label><input type="email" id="invite-email-' + escapeAttr(account.id) + '" placeholder="[email protected]" autocomplete="off"></div><div><label for="invite-role-' + escapeAttr(account.id) + '">Role</label><select id="invite-role-' + escapeAttr(account.id) + '"><option value="admin">Admin</option><option value="tech">Tech</option><option value="read_only">Read-only</option></select></div><button type="button" class="btn-primary btn-compact" data-action="invite-member" data-account-id="' + escapeAttr(account.id) + '">Invite</button></div></div></div></div>';+ workspaceManagement = '<div class="workspace-management-panel" id="workspace-management-' + escapeAttr(account.id) + '"><div class="workspace-management-header"><div><h3>Workspace management</h3><p>Select a workspace from the fleet to review its lifecycle state and run explicit management actions.</p></div><button type="button" class="btn-secondary btn-compact" id="workspace-management-close-' + escapeAttr(account.id) + '" data-action="clear-workspace-selection" data-account-id="' + escapeAttr(account.id) + '">Done</button></div><div class="workspace-management-empty" id="workspace-management-empty-' + escapeAttr(account.id) + '">Choose a workspace to manage from the fleet above.</div><div class="workspace-management-content" id="workspace-management-content-' + escapeAttr(account.id) + '" hidden><div class="workspace-management-meta" id="workspace-management-meta-' + escapeAttr(account.id) + '"></div><h4 id="workspace-management-title-' + escapeAttr(account.id) + '"></h4><p class="workspace-management-summary" id="workspace-management-summary-' + escapeAttr(account.id) + '"></p><div class="workspace-management-actions"><button type="button" class="btn-danger" id="workspace-management-action-' + escapeAttr(account.id) + '" data-action="workspace-action" data-account-id="' + escapeAttr(account.id) + '">Manage workspace</button></div></div></div>';if (account.kind === "msp") {addWorkspaceForm = '<div class="add-workspace-form" id="add-ws-form-' + escapeAttr(account.id) + '"><label for="ws-name-' + escapeAttr(account.id) + '">Workspace name (e.g. client name)</label><input type="text" id="ws-name-' + escapeAttr(account.id) + '" placeholder="Acme Corp" maxlength="80" autocomplete="off"><div class="form-actions"><button type="button" class="btn-primary" data-action="create-workspace" data-account-id="' + escapeAttr(account.id) + '">Create workspace</button><button type="button" class="btn-secondary" data-action="toggle-add-workspace" data-account-id="' + escapeAttr(account.id) + '">Cancel</button><div class="spinner" id="ws-spinner-' + escapeAttr(account.id) + '" hidden></div></div></div>';}}- return '<section class="account-section"><div class="account-header"><div class="account-heading"><div class="account-heading-row"><h2>' + escapeHTML(account.name) + '</h2><span class="badge badge-' + escapeHTML(account.kind) + '">' + escapeHTML(account.kind_label) + "</span>" + roleBadgeHTML(account.role) + '</div><p class="account-summary">' + escapeHTML(formatAccountSummary(account)) + "</p></div></div>" + workspaceHTML + actions + teamSection + addWorkspaceForm + "</section>";+ return '<section class="account-section"><div class="account-header"><div class="account-heading"><div class="account-eyebrow">' + escapeHTML(accountKindLabel(account)) + "</div><h2>" + escapeHTML(account.name) + '</h2><div class="account-summary">' + escapeHTML(summaryText) + '</div></div><div class="account-badges"><span class="badge badge-' + escapeHTML(account.kind) + '">' + escapeHTML(account.kind_label) + "</span>" + roleBadgeHTML(account.role) + '</div></div><div class="account-status-grid"><div class="account-stat-card"><span class="account-stat-label">Active workspaces</span><span class="account-stat-value">' + String(activeCount) + '</span></div><div class="account-stat-card"><span class="account-stat-label">Healthy</span><span class="account-stat-value account-stat-healthy">' + String(healthyCount) + '</span></div><div class="account-stat-card"><span class="account-stat-label">Checking</span><span class="account-stat-value account-stat-checking">' + String(checkingCount) + '</span></div><div class="account-stat-card"><span class="account-stat-label">Needs attention</span><span class="account-stat-value account-stat-unhealthy">' + String(unhealthyCount) + "</span></div></div>" + actions + '<div class="account-subsection-header"><h3>Workspace fleet</h3><p>Open hosted Pulse workspaces, review fleet health, and manage lifecycle actions for this account.</p></div>' + workspaceHTML + workspaceManagement + teamSection + addWorkspaceForm + "</section>";}function renderHeaderHTML(context) {if (context.bootstrap.authenticated) {@@ -1470,32 +1640,25 @@function renderAccountsHTML(context) {var safeAccounts = Array.isArray(context.bootstrap.accounts) ? context.bootstrap.accounts : [];if (safeAccounts.length === 0) {- return '<div class="empty-state empty-state-spaced empty-state-self-hosted"><p class="empty-state-title">No hosted workspaces on this account</p><p>This Pulse Account is still valid for self-hosted billing, license recovery, refunds, and privacy requests. Hosted Cloud or MSP workspaces will appear here when this account owns them.</p><p class="support-copy">Need help? Contact <a href="mailto:' + escapeAttr(context.bootstrap.support_email || "") + '" class="support-link">' + escapeHTML(context.bootstrap.support_email || "") + "</a></p></div>";+ return '<div class="empty-state empty-state-spaced"><p>No hosted workspaces are attached to this account.</p><p class="support-copy">You can still use the self-hosted licensing and billing tools below.</p><p class="support-copy">Need help? Contact <a href="mailto:' + escapeAttr(context.bootstrap.support_email || "") + '" class="support-link">' + escapeHTML(context.bootstrap.support_email || "") + "</a></p></div>";}return safeAccounts.map(function(account) {return renderAccountSection(account, context.accountAPIBasePath);}).join("");}- function renderAuthenticatedIntroHTML(context) {- var accounts = listAccounts(context.bootstrap);- if (!hasHostedAccounts(context.bootstrap)) {- return '<section class="intro-card intro-card-self-hosted"><h1>Pulse Account</h1><p>This account currently uses Pulse Account for self-hosted commercial services. When you own hosted Cloud workspaces or MSP access, they will appear here in the same account shell.</p><div class="overview-grid"><div class="overview-stat"><span class="overview-label">Signed in as</span><strong>' + escapeHTML(context.bootstrap.email || "") + '</strong></div><div class="overview-stat"><span class="overview-label">Hosted access</span><strong>None on this account</strong></div><div class="overview-stat"><span class="overview-label">Self-hosted services</span><strong>Available below</strong></div></div></section>';- }- var totalWorkspaces = totalWorkspaceCount(accounts);- var activeWorkspaces = totalActiveWorkspaceCount(accounts);- var accessLabel = formatAccountAccessLabel(accounts);- return '<section class="intro-card"><h1>Pulse Account</h1><p>Hosted access is active on this account. Open workspaces here, manage team and billing at the account level, and keep self-hosted commercial tools in the same account surface instead of splitting them across public utility pages.</p><div class="overview-grid"><div class="overview-stat"><span class="overview-label">Signed in as</span><strong>' + escapeHTML(context.bootstrap.email || "") + '</strong></div><div class="overview-stat"><span class="overview-label">Account access</span><strong>' + escapeHTML(accessLabel) + '</strong></div><div class="overview-stat"><span class="overview-label">Hosted workspaces</span><strong>' + escapeHTML(String(totalWorkspaces)) + '</strong></div><div class="overview-stat"><span class="overview-label">Active now</span><strong>' + escapeHTML(String(activeWorkspaces)) + '</strong></div></div><div class="intro-guidance">Use <strong>Open workspace</strong> to enter a hosted Pulse runtime. Team, workspace lifecycle, and billing controls stay with each account card below.</div></section>';- }function renderAuthenticatedPortalHTML(context) {- var hostedAccounts = hasHostedAccounts(context.bootstrap);- return renderAuthenticatedIntroHTML(context) + '<div id="accounts-root">' + renderAccountsHTML(context) + '</div><section class="service-section"><div class="service-header"><h2>' + (hostedAccounts ? "Self-hosted licenses and billing" : "Self-hosted account services") + '</h2><div class="service-note">' + (hostedAccounts ? "These tools stay available on the same account for self-hosted subscriptions, license recovery, refunds, and privacy actions. Hosted workspace administration stays above." : "Use these tools for subscription, license, refund, and privacy actions on self-hosted commercial accounts. The public utility pages remain as compatibility entry points only.") + '</div></div><div class="service-grid"><button class="service-card service-card-button" type="button" id="open-manage-service" data-account-service-action="open-service-panel" data-account-service-panel="manage-service-panel" data-account-service-focus="manage-inline-email"><h3>Manage subscriptions</h3><p>Open Stripe billing access for existing self-hosted subscriptions without leaving the Pulse Account shell.</p></button><button class="service-card service-card-button" type="button" id="open-retrieve-service" data-account-service-action="open-service-panel" data-account-service-panel="retrieve-service-panel" data-account-service-focus="retrieve-inline-email"><h3>Retrieve licenses</h3><p>Recover the latest active self-hosted license and invoice link for a commercial email address.</p></button><button class="service-card service-card-button" type="button" id="open-refund-service" data-account-service-action="open-service-panel" data-account-service-panel="refund-service-panel" data-account-service-focus="refund-inline-email"><h3>Refund requests</h3><p>Request an immediate self-serve refund for eligible self-hosted purchases with explicit revocation confirmation.</p></button><button class="service-card service-card-button" type="button" id="open-data-service" data-account-service-action="open-service-panel" data-account-service-panel="data-service-panel" data-account-service-focus="data-export-email"><h3>Data and privacy</h3><p>Request commercial data export or deletion without leaving the account shell.</p></button></div><div class="service-panel" id="manage-service-panel"><div id="manage-service-root"></div></div><div class="service-panel" id="retrieve-service-panel"><div id="retrieve-service-root"></div></div><div class="service-panel" id="refund-service-panel"><div id="refund-service-root"></div></div><div class="service-panel" id="data-service-panel"><h3>Data and privacy</h3><p>Request export or deletion of the commercial data tied to an email address. Payment data held directly by Stripe still requires support handling.</p><div class="subsection"><div id="data-export-root"></div></div><div class="subsection"><div id="data-delete-root"></div></div><div class="helper-text">Payment-card data stays with Stripe. For Stripe deletion support, contact <a href="mailto:' + escapeAttr(context.bootstrap.support_email || "") + '">' + escapeHTML(context.bootstrap.support_email || "") + "</a>.</div></div></section>";+ var accounts = Array.isArray(context.bootstrap.accounts) ? context.bootstrap.accounts : [];+ var serviceHeading = hasHostedAccounts(accounts) ? "Self-hosted licenses and billing" : "Account services";+ var serviceNote = hasHostedAccounts(accounts) ? "Hosted access lives above. The self-hosted commercial tools remain available here for licenses, billing, refunds, and privacy actions." : "Use these account tools for self-hosted licenses, billing, refunds, and privacy actions.";+ return renderOverviewBand(context, accounts) + renderShellNavigation(accounts, context.bootstrap.support_email || "") + '<section class="portal-top-section" id="hosted-operations-section"><div class="portal-top-section-header"><h2>' + (hasHostedAccounts(accounts) ? "Hosted operations" : "Hosted access") + "</h2><p>" + (hasHostedAccounts(accounts) ? "Use this area for workspace access, fleet operations, hosted billing, and team management." : "This account does not currently have hosted workspace access. If that is unexpected, contact support while using the commercial tools below.") + '</p></div><div id="accounts-root">' + renderAccountsHTML(context) + '</div></section><section class="service-section" id="account-services-section"><div class="service-header"><h2>' + serviceHeading + '</h2><div class="service-note">' + serviceNote + '</div></div><div class="service-grid"><button class="service-card service-card-button" type="button" id="open-manage-service" data-account-service-action="open-service-panel" data-account-service-panel="manage-service-panel" data-account-service-focus="manage-inline-email"><h3>Manage subscriptions</h3><p>Open Stripe billing access for existing self-hosted subscriptions without leaving the Pulse Account shell.</p></button><button class="service-card service-card-button" type="button" id="open-retrieve-service" data-account-service-action="open-service-panel" data-account-service-panel="retrieve-service-panel" data-account-service-focus="retrieve-inline-email"><h3>Retrieve licenses</h3><p>Recover the latest active self-hosted license and invoice link for a commercial email address.</p></button><button class="service-card service-card-button" type="button" id="open-refund-service" data-account-service-action="open-service-panel" data-account-service-panel="refund-service-panel" data-account-service-focus="refund-inline-email"><h3>Refund requests</h3><p>Request an immediate self-serve refund for eligible self-hosted purchases with explicit revocation confirmation.</p></button><button class="service-card service-card-button" type="button" id="open-data-service" data-account-service-action="open-service-panel" data-account-service-panel="data-service-panel" data-account-service-focus="data-export-email"><h3>Data and privacy</h3><p>Request commercial data export or deletion without leaving the account shell.</p></button></div><div class="service-panel" id="manage-service-panel"><div id="manage-service-root"></div></div><div class="service-panel" id="retrieve-service-panel"><div id="retrieve-service-root"></div></div><div class="service-panel" id="refund-service-panel"><div id="refund-service-root"></div></div><div class="service-panel" id="data-service-panel"><h3>Data and privacy</h3><p>Request export or deletion of the commercial data tied to an email address. Payment data held directly by Stripe still requires support handling.</p><div class="subsection"><div id="data-export-root"></div></div><div class="subsection"><div id="data-delete-root"></div></div><div class="helper-text">Payment-card data stays with Stripe. For Stripe deletion support, contact <a href="mailto:' + escapeAttr(context.bootstrap.support_email || "") + '">' + escapeHTML(context.bootstrap.support_email || "") + "</a>.</div></div></section>";}function renderSignedOutPortalHTML(context) {var statusHTML = "";if (context.loginState.request.error) {statusHTML = '<div class="service-status visible error">' + escapeHTML(context.loginState.request.error) + "</div>";} else if (context.loginState.success) {- statusHTML = '<div class="service-status visible success">' + escapeHTML(context.loginState.successMessage || "If that email is registered, you'll receive a magic link shortly.") + `<br><br><strong>Don't see it?</strong> <a href="#" data-portal-action="resend-magic-link">Send a new link</a>.</div>`;+ var successMessage = context.loginState.successMessage || "If that email is registered, a magic link is on the way.";+ statusHTML = '<div class="service-status visible success">' + escapeHTML(successMessage) + `<br><br><strong>Don't see it?</strong> <a href="#" data-portal-action="resend-magic-link">Send a new link</a>.</div>`;}return '<section class="intro-card"><h1>Pulse Account</h1><p>Sign in to manage Cloud workspaces, MSP access, and commercial account services from one account surface.</p></section><section class="service-section"><div class="service-panel visible"><h3>Sign in</h3><p>Enter the commercial email address for your Pulse account. I will send a magic link so you can open Pulse Account without managing a password.</p><div class="form-group"><label for="portal-login-email">Email address</label><input id="portal-login-email" type="email" autocomplete="email" placeholder="[email protected]" value="' + escapeAttr(context.loginState.emailValue || "") + '" data-portal-input="login-email"></div><div class="form-actions"><button class="btn-primary" id="portal-login-send" type="button" data-portal-action="send-magic-link">' + (context.loginState.request.pending ? "Sending\u2026" : "Send magic link") + '</button><a class="btn-secondary link-button" href="' + escapeAttr(context.signupPath) + '">Create an account</a></div>' + statusHTML + "</div></section>";}@@ -1682,7 +1845,7 @@return {public_site_url: embeddedBootstrap.public_site_url || "https://pulserelay.pro",support_email: embeddedBootstrap.support_email || "[email protected]",- commercial_api_base_path: embeddedBootstrap.commercial_api_base_path || "/api/portal/commercial",+ commercial_api_base_url: embeddedBootstrap.commercial_api_base_url || "",portal_path: embeddedBootstrap.portal_path || "/portal",bootstrap_path: embeddedBootstrap.bootstrap_path || "/api/portal/bootstrap",magic_link_request_path: embeddedBootstrap.magic_link_request_path || "/api/public/magic-link/request",diff --git a/internal/cloudcp/portal/frontend/src/account_controller.test.ts b/internal/cloudcp/portal/frontend/src/account_controller.test.tsindex 050e147b55..a2e8aaa2d5 100644--- a/internal/cloudcp/portal/frontend/src/account_controller.test.ts+++ b/internal/cloudcp/portal/frontend/src/account_controller.test.ts@@ -11,11 +11,13 @@ describe('account controller', function() {it('routes account actions to the matching runtime handlers', function() {var runtime = {toggleAddWorkspace: vi.fn(),+ selectWorkspace: vi.fn(),+ clearWorkspaceSelection: vi.fn(),openBilling: vi.fn(),toggleTeam: vi.fn(),inviteMember: vi.fn(),createWorkspace: vi.fn(),- manageWorkspace: vi.fn(),+ manageWorkspaceAction: vi.fn(),removeMember: vi.fn(),changeRole: vi.fn(),};@@ -28,7 +30,9 @@ describe('account controller', function() {'<button id="team" data-action="toggle-team" data-account-id="acct_1">Team</button>' +'<button id="invite" data-action="invite-member" data-account-id="acct_1">Invite</button>' +'<button id="create" data-action="create-workspace" data-account-id="acct_1">Create</button>' +- '<button id="manage" data-action="workspace-manage" data-account-id="acct_1" data-workspace-id="ws_1" data-workspace-state="active" data-workspace-name="Alpha">Manage</button>' ++ '<button id="select" data-action="select-workspace" data-account-id="acct_1" data-workspace-id="ws_1">Manage</button>' ++ '<button id="close" data-action="clear-workspace-selection" data-account-id="acct_1">Done</button>' ++ '<button id="manage" data-action="workspace-action" data-account-id="acct_1" data-workspace-id="ws_1" data-workspace-action="suspend" data-workspace-name="Alpha">Suspend</button>' +'<button id="remove" data-action="remove-member" data-account-id="acct_1" data-user-id="u1" data-member-email="[email protected]">Remove</button>' +'<select id="role" data-action="change-role" data-account-id="acct_1" data-user-id="u1"><option value="admin">Admin</option></select>';@@ -47,8 +51,14 @@ describe('account controller', function() {document.getElementById('create')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));expect(runtime.createWorkspace).toHaveBeenCalledWith('acct_1');+ document.getElementById('select')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ expect(runtime.selectWorkspace).toHaveBeenCalledWith('acct_1', 'ws_1');++ document.getElementById('close')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ expect(runtime.clearWorkspaceSelection).toHaveBeenCalledWith('acct_1');+document.getElementById('manage')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));- expect(runtime.manageWorkspace).toHaveBeenCalledWith(expect.any(MouseEvent), 'acct_1', 'ws_1', 'active', 'Alpha');+ expect(runtime.manageWorkspaceAction).toHaveBeenCalledWith('acct_1', 'ws_1', 'suspend', 'Alpha');document.getElementById('remove')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));expect(runtime.removeMember).toHaveBeenCalledWith('acct_1', 'u1', '[email protected]');diff --git a/internal/cloudcp/portal/frontend/src/account_controller.ts b/internal/cloudcp/portal/frontend/src/account_controller.tsindex 1db1331fc0..3ae0f5b819 100644--- a/internal/cloudcp/portal/frontend/src/account_controller.ts+++ b/internal/cloudcp/portal/frontend/src/account_controller.ts@@ -7,7 +7,9 @@ export interface AccountControllerDeps {export function installAccountController(deps: AccountControllerDeps): void {document.addEventListener('click', function(event) {- var actionEl = asHTMLElement(event.target)?.closest('[data-action]');+ var target = asHTMLElement(event.target);+ if (!target) return;+ var actionEl = target.closest('[data-action]');if (!actionEl) return;var action = actionEl.getAttribute('data-action') || '';var accountID = actionEl.getAttribute('data-account-id') || '';@@ -33,13 +35,23 @@ export function installAccountController(deps: AccountControllerDeps): void {event.preventDefault();void deps.runtime.createWorkspace(accountID);return;- case 'workspace-manage':+ case 'select-workspace':event.preventDefault();- void deps.runtime.manageWorkspace(- event,+ deps.runtime.selectWorkspace(accountID,actionEl.getAttribute('data-workspace-id') || '',- actionEl.getAttribute('data-workspace-state') || '',+ );+ return;+ case 'clear-workspace-selection':+ event.preventDefault();+ deps.runtime.clearWorkspaceSelection(accountID);+ return;+ case 'workspace-action':+ event.preventDefault();+ void deps.runtime.manageWorkspaceAction(+ accountID,+ actionEl.getAttribute('data-workspace-id') || '',+ actionEl.getAttribute('data-workspace-action') || '',actionEl.getAttribute('data-workspace-name') || '',);return;diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.test.ts b/internal/cloudcp/portal/frontend/src/account_runtime.test.tsindex a14866013a..5f310d70b2 100644--- a/internal/cloudcp/portal/frontend/src/account_runtime.test.ts+++ b/internal/cloudcp/portal/frontend/src/account_runtime.test.ts@@ -28,7 +28,7 @@ async function flushAsync() {const bootstrapDefaults: Omit<PortalBootstrapData, 'authenticated' | 'email' | 'accounts'> = {public_site_url: 'https://pulserelay.pro',support_email: '[email protected]',- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',portal_path: '/portal',bootstrap_path: '/api/portal/bootstrap',magic_link_request_path: '/api/public/magic-link/request',@@ -81,6 +81,7 @@ describe('account runtime', function() {'<div id="add-ws-form-acct_1" class="add-workspace-form">' +'<input id="ws-name-acct_1" value="Acme Corp">' +'<div id="ws-spinner-acct_1" hidden></div>' ++ '<div id="workspace-management-acct_1" class="workspace-management-panel"><button id="workspace-management-close-acct_1"></button><div id="workspace-management-empty-acct_1"></div><div id="workspace-management-content-acct_1" hidden><div id="workspace-management-meta-acct_1"></div><h4 id="workspace-management-title-acct_1"></h4><p id="workspace-management-summary-acct_1"></p><button id="workspace-management-action-acct_1"></button></div></div>' +'</div>';runtime.toggleAddWorkspace('acct_1');@@ -106,6 +107,63 @@ describe('account runtime', function() {expect((document.getElementById('ws-spinner-acct_1') as HTMLElement).hidden).toBe(true);});+ it('selects a workspace and routes explicit workspace actions through the management panel', async function() {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({})));+ var confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);+ deps.store.setBootstrap({+ authenticated: true,+ email: '[email protected]',+ accounts: [{+ id: 'acct_1',+ name: 'Acme MSP',+ kind: 'msp',+ kind_label: 'MSP',+ role: 'owner',+ can_manage: true,+ has_billing: true,+ workspaces: [{+ id: 'ws_2',+ display_name: 'Alpha Workspace',+ state: 'active',+ healthy: true,+ health_status: 'healthy',+ }],+ }],+ });++ document.body.innerHTML =+ '<div id="workspace-management-acct_1" class="workspace-management-panel">' ++ '<button id="workspace-management-close-acct_1"></button>' ++ '<div id="workspace-management-empty-acct_1"></div>' ++ '<div id="workspace-management-content-acct_1" hidden>' ++ '<div id="workspace-management-meta-acct_1"></div>' ++ '<h4 id="workspace-management-title-acct_1"></h4>' ++ '<p id="workspace-management-summary-acct_1"></p>' ++ '<button id="workspace-management-action-acct_1"></button>' ++ '</div>' ++ '</div>';++ runtime.selectWorkspace('acct_1', 'ws_2');+ expect(deps.store.getAccountState().byAccountID.acct_1.selectedWorkspaceID).toBe('ws_2');+ expect(document.getElementById('workspace-management-title-acct_1')?.textContent).toContain('Alpha Workspace');+ expect(document.getElementById('workspace-management-action-acct_1')?.textContent).toContain('Suspend workspace');++ await runtime.manageWorkspaceAction('acct_1', 'ws_2', 'suspend', 'Alpha Workspace');+ await flushAsync();++ expect(confirmSpy).toHaveBeenCalledWith('Suspend workspace "Alpha Workspace"?');+ expect(fetch).toHaveBeenCalledWith(+ '/api/accounts/acct_1/tenants/ws_2',+ expect.objectContaining({+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ state: 'suspended' }),+ })+ );+ expect(deps.showToast).toHaveBeenCalledWith('Suspended workspace.');+ expect(deps.store.getAccountState().byAccountID.acct_1.selectedWorkspaceID).toBe('');+ });+it('loads and updates team membership from runtime actions', async function() {vi.stubGlobal('fetch',@@ -116,7 +174,9 @@ describe('account runtime', function() {);document.body.innerHTML =+ '<div id="workspace-management-acct_1" class="workspace-management-panel"><button id="workspace-management-close-acct_1"></button><div id="workspace-management-empty-acct_1"></div><div id="workspace-management-content-acct_1" hidden><div id="workspace-management-meta-acct_1"></div><h4 id="workspace-management-title-acct_1"></h4><p id="workspace-management-summary-acct_1"></p><button id="workspace-management-action-acct_1"></button></div></div>' +'<div id="team-section-acct_1" class="team-section" data-actor-role="owner">' ++ '<div id="team-stats-acct_1"></div>' +'<table><tbody id="team-list-acct_1"></tbody></table>' +'<input id="invite-email-acct_1">' +'<select id="invite-role-acct_1"><option value="admin">Admin</option></select>' +@@ -128,6 +188,7 @@ describe('account runtime', function() {expect(deps.store.getAccountState().byAccountID.acct_1.teamVisible).toBe(true);expect(deps.store.getAccountState().byAccountID.acct_1.teamQuery.status).toBe('ready');expect(deps.store.getAccountState().byAccountID.acct_1.teamQuery.data).toHaveLength(1);+ expect(document.getElementById('team-stats-acct_1')?.textContent).toContain('Members');var roleSelect = document.querySelector('[data-action="change-role"]') as HTMLSelectElement | null;expect(roleSelect).not.toBeNull();expect(roleSelect?.value).toBe('owner');diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.ts b/internal/cloudcp/portal/frontend/src/account_runtime.tsindex 7fe3146657..3a455061bb 100644--- a/internal/cloudcp/portal/frontend/src/account_runtime.ts+++ b/internal/cloudcp/portal/frontend/src/account_runtime.ts@@ -15,11 +15,13 @@ export interface AccountRuntimeDeps {export interface AccountRuntime {toggleAddWorkspace(accountID: string): void;+ selectWorkspace(accountID: string, workspaceID: string): void;+ clearWorkspaceSelection(accountID: string): void;openBilling(accountID: string): Promise<void>;toggleTeam(accountID: string): void;inviteMember(accountID: string): Promise<void>;createWorkspace(accountID: string): Promise<void>;- manageWorkspace(event: Event, accountID: string, tenantID: string, state: string, name: string): Promise<void>;+ manageWorkspaceAction(accountID: string, tenantID: string, action: string, name: string): Promise<void>;removeMember(accountID: string, userID: string, email: string): Promise<void>;changeRole(accountID: string, userID: string, newRole: string): Promise<void>;}@@ -38,7 +40,7 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime};var renderAccountRuntime = function(): void {- renderAccountUIState(deps.store.getAccountState());+ renderAccountUIState(deps.store.getAccountState(), deps.store.getBootstrap().accounts || []);};var loadTeam = async function(accountID: string): Promise<void> {@@ -91,6 +93,20 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime}};+ var selectWorkspace = function(accountID: string, workspaceID: string): void {+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ entry.selectedWorkspaceID = entry.selectedWorkspaceID === workspaceID ? '' : workspaceID;+ });+ };++ var clearWorkspaceSelection = function(accountID: string): void {+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ entry.selectedWorkspaceID = '';+ });+ };+var createWorkspace = async function(accountID: string): Promise<void> {var nameEl = getElement<HTMLInputElement>('ws-name-' + accountID);if (!nameEl) return;@@ -128,22 +144,39 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime}};- var manageWorkspace = async function(evt: Event, accountID: string, tenantID: string, state: string, name: string): Promise<void> {- evt.stopPropagation();- var action = state === 'active' ? 'Suspend' : 'Delete';- if (!window.confirm(action + ' workspace "' + name + '"?')) return;+ var manageWorkspaceAction = async function(accountID: string, tenantID: string, action: string, name: string): Promise<void> {+ var verb = action === 'suspend' ? 'Suspend' : action === 'delete' ? 'Delete' : '';+ if (!verb) return;+ if (!window.confirm(verb + ' workspace "' + name + '"?')) return;+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ beginMutationState(entry.manageWorkspace);+ });try {- if (state === 'active') {+ if (action === 'suspend') {await deps.api.suspendWorkspace(accountID, tenantID);} else {await deps.api.deleteWorkspace(accountID, tenantID);}if (!await refreshOrRedirect()) {+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ resetMutationState(entry.manageWorkspace);+ }, { notify: false });return;}- deps.showToast(action + 'd workspace.');+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ entry.selectedWorkspaceID = '';+ succeedMutationState(entry.manageWorkspace);+ });+ deps.showToast(verb + 'ed workspace.');} catch (error) {- deps.showToast(error instanceof Error ? error.message : 'Failed to ' + action.toLowerCase() + ' workspace.', true);+ deps.store.updateAccountState(function(accountState) {+ var entry = ensurePortalAccountUIEntry(accountState, accountID);+ failMutationState(entry.manageWorkspace, error instanceof Error ? error.message : 'Failed to ' + verb.toLowerCase() + ' workspace.');+ }, { notify: false });+ deps.showToast(error instanceof Error ? error.message : 'Failed to ' + verb.toLowerCase() + ' workspace.', true);}};@@ -237,11 +270,13 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntimereturn {toggleAddWorkspace: toggleAddWorkspace,+ selectWorkspace: selectWorkspace,+ clearWorkspaceSelection: clearWorkspaceSelection,openBilling: openBilling,toggleTeam: toggleTeam,inviteMember: inviteMember,createWorkspace: createWorkspace,- manageWorkspace: manageWorkspace,+ manageWorkspaceAction: manageWorkspaceAction,removeMember: removeMember,changeRole: changeRole,};diff --git a/internal/cloudcp/portal/frontend/src/account_view.test.ts b/internal/cloudcp/portal/frontend/src/account_view.test.tsindex 44b086d832..f06b9d5217 100644--- a/internal/cloudcp/portal/frontend/src/account_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/account_view.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it } from 'vitest';-import { renderAccountUI, renderAddWorkspaceSection, renderTeamSection } from './account_view';-import type { PortalAccountState, PortalAccountUIEntry } from './types';+import { renderAccountUI, renderAddWorkspaceSection, renderTeamSection, renderWorkspaceManagement } from './account_view';+import type { PortalAccountState, PortalAccountSummary, PortalAccountUIEntry } from './types';function createEntry(overrides: Partial<PortalAccountUIEntry> = {}): PortalAccountUIEntry {return {@@ -10,6 +10,11 @@ function createEntry(overrides: Partial<PortalAccountUIEntry> = {}): PortalAccoupending: false,error: '',},+ selectedWorkspaceID: '',+ manageWorkspace: {+ pending: false,+ error: '',+ },teamVisible: false,teamQuery: {status: 'idle',@@ -25,6 +30,29 @@ describe('account view', function() {document.body.innerHTML = '';});+ function createAccount(overrides: Partial<PortalAccountSummary> = {}): PortalAccountSummary {+ return {+ id: 'acct_1',+ name: 'Acme MSP',+ kind: 'msp',+ kind_label: 'MSP',+ role: 'owner',+ can_manage: true,+ has_billing: true,+ workspaces: [+ {+ id: 'ws_1',+ display_name: 'Alpha Workspace',+ state: 'active',+ healthy: true,+ health_status: 'healthy',+ created_at: '2026-03-26T10:00:00Z',+ },+ ],+ ...overrides,+ };+ }+it('renders add-workspace visibility from account UI state', function() {document.body.innerHTML ='<div id="add-ws-form-acct_1" class="add-workspace-form"></div>' +@@ -47,6 +75,7 @@ describe('account view', function() {it('renders team loading, error, and populated member states', function() {document.body.innerHTML ='<div id="team-section-acct_1" class="team-section" data-actor-role="owner">' ++ '<div id="team-stats-acct_1"></div>' +'<table><tbody id="team-list-acct_1"></tbody></table>' +'</div>';@@ -69,26 +98,55 @@ describe('account view', function() {teamQuery: {status: 'ready',error: '',- data: [{ email: '[email protected]', role: 'owner', user_id: 'u1' }],+ data: [+ { email: '[email protected]', role: 'owner', user_id: 'u1' },+ { email: '[email protected]', role: 'tech', user_id: 'u2' },+ ],},}));expect(document.querySelector('[data-action="change-role"]')).not.toBeNull();expect(document.querySelector('[data-action="remove-member"]')).not.toBeNull();+ expect(document.getElementById('team-stats-acct_1')?.textContent).toContain('Members');+ expect(document.getElementById('team-stats-acct_1')?.textContent).toContain('2');+ });++ it('renders workspace management selection from account UI state', function() {+ document.body.innerHTML =+ '<div id="workspace-management-acct_1" class="workspace-management-panel">' ++ '<button id="workspace-management-close-acct_1"></button>' ++ '<div id="workspace-management-empty-acct_1"></div>' ++ '<div id="workspace-management-content-acct_1" hidden>' ++ '<div id="workspace-management-meta-acct_1"></div>' ++ '<h4 id="workspace-management-title-acct_1"></h4>' ++ '<p id="workspace-management-summary-acct_1"></p>' ++ '<button id="workspace-management-action-acct_1"></button>' ++ '</div>' ++ '</div>';++ renderWorkspaceManagement(createAccount(), createEntry({ selectedWorkspaceID: 'ws_1' }));+ expect(document.getElementById('workspace-management-acct_1')?.classList.contains('visible')).toBe(true);+ expect((document.getElementById('workspace-management-empty-acct_1') as HTMLElement).hidden).toBe(true);+ expect((document.getElementById('workspace-management-content-acct_1') as HTMLElement).hidden).toBe(false);+ expect(document.getElementById('workspace-management-title-acct_1')?.textContent).toContain('Alpha Workspace');+ expect(document.getElementById('workspace-management-action-acct_1')?.textContent).toContain('Suspend workspace');});it('renders account UI for every tracked account entry', function() {document.body.innerHTML ='<div id="add-ws-form-acct_1" class="add-workspace-form"></div><div id="ws-spinner-acct_1"></div>' +- '<div id="team-section-acct_1" class="team-section" data-actor-role="admin"><table><tbody id="team-list-acct_1"></tbody></table></div>' ++ '<div id="workspace-management-acct_1" class="workspace-management-panel"><button id="workspace-management-close-acct_1"></button><div id="workspace-management-empty-acct_1"></div><div id="workspace-management-content-acct_1" hidden><div id="workspace-management-meta-acct_1"></div><h4 id="workspace-management-title-acct_1"></h4><p id="workspace-management-summary-acct_1"></p><button id="workspace-management-action-acct_1"></button></div></div>' ++ '<div id="team-section-acct_1" class="team-section" data-actor-role="admin"><div id="team-stats-acct_1"></div><table><tbody id="team-list-acct_1"></tbody></table></div>' +'<div id="add-ws-form-acct_2" class="add-workspace-form"></div><div id="ws-spinner-acct_2"></div>' +- '<div id="team-section-acct_2" class="team-section" data-actor-role="owner"><table><tbody id="team-list-acct_2"></tbody></table></div>';+ '<div id="workspace-management-acct_2" class="workspace-management-panel"><button id="workspace-management-close-acct_2"></button><div id="workspace-management-empty-acct_2"></div><div id="workspace-management-content-acct_2" hidden><div id="workspace-management-meta-acct_2"></div><h4 id="workspace-management-title-acct_2"></h4><p id="workspace-management-summary-acct_2"></p><button id="workspace-management-action-acct_2"></button></div></div>' ++ '<div id="team-section-acct_2" class="team-section" data-actor-role="owner"><div id="team-stats-acct_2"></div><table><tbody id="team-list-acct_2"></tbody></table></div>';var state: PortalAccountState = {byAccountID: {acct_1: createEntry({ addWorkspaceOpen: true, teamVisible: true }),acct_2: createEntry({addWorkspaceOpen: false,+ selectedWorkspaceID: 'ws_2',teamVisible: true,teamQuery: {status: 'ready',@@ -99,10 +157,26 @@ describe('account view', function() {},};- renderAccountUI(state);+ renderAccountUI(state, [+ createAccount(),+ createAccount({+ id: 'acct_2',+ name: 'Beta MSP',+ workspaces: [+ {+ id: 'ws_2',+ display_name: 'Beta Workspace',+ state: 'failed',+ healthy: false,+ health_status: 'unhealthy',+ },+ ],+ }),+ ]);expect(document.getElementById('add-ws-form-acct_1')?.classList.contains('visible')).toBe(true);expect(document.getElementById('add-ws-form-acct_2')?.classList.contains('visible')).toBe(false);expect(document.getElementById('team-list-acct_2')?.textContent).toContain('[email protected]');+ expect(document.getElementById('workspace-management-title-acct_2')?.textContent).toContain('Beta Workspace');});});diff --git a/internal/cloudcp/portal/frontend/src/account_view.ts b/internal/cloudcp/portal/frontend/src/account_view.tsindex 4dcebd577f..f4c50c2938 100644--- a/internal/cloudcp/portal/frontend/src/account_view.ts+++ b/internal/cloudcp/portal/frontend/src/account_view.ts@@ -1,4 +1,10 @@-import type { PortalAccountState, PortalAccountUIEntry, PortalTeamMember } from './types';+import type {+ PortalAccountState,+ PortalAccountSummary,+ PortalAccountUIEntry,+ PortalTeamMember,+ PortalWorkspaceSummary,+} from './types';type FormValueElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;@@ -15,6 +21,72 @@ export function focusElement(id: string): void {if (input) input.focus();}+function workspaceActionLabel(workspace: PortalWorkspaceSummary): string {+ return workspace.state === 'active' ? 'Suspend workspace' : 'Delete workspace';+}++function workspaceSummary(workspace: PortalWorkspaceSummary): string {+ if (workspace.health_status === 'healthy') return 'Live updates and health checks are currently good.';+ if (workspace.health_status === 'unhealthy') return 'This workspace needs attention before it is trustworthy.';+ return 'This workspace is still waiting on a completed health check.';+}++function workspaceMeta(workspace: PortalWorkspaceSummary): string {+ var parts = [workspace.state];+ if (workspace.health_status) parts.push(workspace.health_status);+ if (workspace.created_at) {+ var date = new Date(workspace.created_at);+ if (!Number.isNaN(date.getTime())) {+ parts.push('Created ' + date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }));+ }+ }+ return parts.join(' · ');+}++function findWorkspace(account: PortalAccountSummary, workspaceID: string): PortalWorkspaceSummary | null {+ for (var i = 0; i < account.workspaces.length; i += 1) {+ if (account.workspaces[i].id === workspaceID) return account.workspaces[i];+ }+ return null;+}++export function renderWorkspaceManagement(account: PortalAccountSummary, entry: PortalAccountUIEntry): void {+ var panel = getElement<HTMLElement>('workspace-management-' + account.id);+ if (!panel) return;+ var empty = getElement<HTMLElement>('workspace-management-empty-' + account.id);+ var content = getElement<HTMLElement>('workspace-management-content-' + account.id);+ var title = getElement<HTMLElement>('workspace-management-title-' + account.id);+ var meta = getElement<HTMLElement>('workspace-management-meta-' + account.id);+ var summary = getElement<HTMLElement>('workspace-management-summary-' + account.id);+ var actionButton = getElement<HTMLButtonElement>('workspace-management-action-' + account.id);+ var closeButton = getElement<HTMLButtonElement>('workspace-management-close-' + account.id);+ if (!empty || !content || !title || !meta || !summary || !actionButton || !closeButton) return;++ var workspace = entry.selectedWorkspaceID ? findWorkspace(account, entry.selectedWorkspaceID) : null;+ var hasSelection = !!workspace;+ panel.classList.toggle('visible', hasSelection);+ empty.hidden = hasSelection;+ content.hidden = !hasSelection;++ if (!workspace) {+ actionButton.disabled = false;+ actionButton.removeAttribute('data-workspace-id');+ actionButton.removeAttribute('data-workspace-name');+ actionButton.removeAttribute('data-workspace-action');+ return;+ }++ title.textContent = workspace.display_name;+ meta.textContent = workspaceMeta(workspace);+ summary.textContent = workspaceSummary(workspace);+ actionButton.textContent = workspaceActionLabel(workspace);+ actionButton.disabled = entry.manageWorkspace.pending;+ actionButton.setAttribute('data-workspace-id', workspace.id);+ actionButton.setAttribute('data-workspace-name', workspace.display_name);+ actionButton.setAttribute('data-workspace-action', workspace.state === 'active' ? 'suspend' : 'delete');+ closeButton.disabled = entry.manageWorkspace.pending;+}+function setTbodyMessage(tbody: HTMLElement, msg: string, isError: boolean): void {tbody.textContent = '';var tr = document.createElement('tr');@@ -26,6 +98,38 @@ function setTbodyMessage(tbody: HTMLElement, msg: string, isError: boolean): voitbody.appendChild(tr);}+function countMembersByRole(members: PortalTeamMember[], role: string): number {+ var count = 0;+ for (var i = 0; i < members.length; i += 1) {+ if (members[i].role === role) count += 1;+ }+ return count;+}++function renderTeamStats(accountID: string, entry: PortalAccountUIEntry): void {+ var stats = getElement<HTMLElement>('team-stats-' + accountID);+ if (!stats) return;+ if (!entry.teamVisible) {+ stats.innerHTML = '';+ return;+ }+ if (entry.teamQuery.status === 'loading') {+ stats.innerHTML = '<div class="team-stat-card"><span class="team-stat-label">Roster</span><span class="team-stat-value">Loading…</span></div>';+ return;+ }+ if (entry.teamQuery.status === 'error') {+ stats.innerHTML = '<div class="team-stat-card"><span class="team-stat-label">Roster</span><span class="team-stat-value team-stat-error">Needs attention</span></div>';+ return;+ }++ var members = entry.teamQuery.data;+ stats.innerHTML =+ '<div class="team-stat-card"><span class="team-stat-label">Members</span><span class="team-stat-value">' + String(members.length) + '</span></div>' ++ '<div class="team-stat-card"><span class="team-stat-label">Owners</span><span class="team-stat-value">' + String(countMembersByRole(members, 'owner')) + '</span></div>' ++ '<div class="team-stat-card"><span class="team-stat-label">Admins</span><span class="team-stat-value">' + String(countMembersByRole(members, 'admin')) + '</span></div>' ++ '<div class="team-stat-card"><span class="team-stat-label">Operators</span><span class="team-stat-value">' + String(countMembersByRole(members, 'tech') + countMembersByRole(members, 'read_only')) + '</span></div>';+}+function renderTeamMemberRoleCell(accountID: string, member: PortalTeamMember, isOwner: boolean): HTMLTableCellElement {var tdRole = document.createElement('td');if (member.role === 'owner' && !isOwner) {@@ -85,6 +189,7 @@ export function renderTeamSection(accountID: string, entry: PortalAccountUIEntryvar actorRole = section.getAttribute('data-actor-role') || '';var isOwner = actorRole === 'owner';section.classList.toggle('visible', entry.teamVisible);+ renderTeamStats(accountID, entry);if (!entry.teamVisible) {return;@@ -115,12 +220,20 @@ export function renderTeamSection(accountID: string, entry: PortalAccountUIEntry}}-export function renderAccountUI(accountState: PortalAccountState): void {+export function renderAccountUI(accountState: PortalAccountState, accounts: PortalAccountSummary[]): void {var accountIDs = Object.keys(accountState.byAccountID);for (var i = 0; i < accountIDs.length; i += 1) {var accountID = accountIDs[i];var entry = accountState.byAccountID[accountID];+ var account = null as PortalAccountSummary | null;+ for (var j = 0; j < accounts.length; j += 1) {+ if (accounts[j].id === accountID) {+ account = accounts[j];+ break;+ }+ }renderAddWorkspaceSection(accountID, entry);+ if (account) renderWorkspaceManagement(account, entry);renderTeamSection(accountID, entry);}}diff --git a/internal/cloudcp/portal/frontend/src/api.test.ts b/internal/cloudcp/portal/frontend/src/api.test.tsindex 6883c7bf04..3960eabb6d 100644--- a/internal/cloudcp/portal/frontend/src/api.test.ts+++ b/internal/cloudcp/portal/frontend/src/api.test.ts@@ -8,7 +8,7 @@ const bootstrap: PortalBootstrapData = {email: '[email protected]',public_site_url: 'https://pulserelay.pro',support_email: '[email protected]',- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',portal_path: '/portal',bootstrap_path: '/api/portal/bootstrap',magic_link_request_path: '/api/public/magic-link/request',@@ -69,4 +69,32 @@ describe('portal api', function() {message: 'Member already exists.',});});++ it('sends portal-targeted magic-link requests and returns the server message', async function() {+ var fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: new Headers({ 'content-type': 'application/json' }),+ json: async function() {+ return { message: 'If that email is registered, you will receive a magic link shortly.' };+ },+ });+ vi.stubGlobal('fetch', fetchMock);++ var api = createPortalAPI({+ getBootstrap: function() {+ return bootstrap;+ },+ });++ var result = await api.requestMagicLink('[email protected]');+ expect(fetchMock).toHaveBeenCalledWith(+ '/api/public/magic-link/request',+ expect.objectContaining({+ method: 'POST',+ body: JSON.stringify({ email: '[email protected]', target: 'portal' }),+ })+ );+ expect(result.message).toContain('If that email is registered');+ });});diff --git a/internal/cloudcp/portal/frontend/src/api.ts b/internal/cloudcp/portal/frontend/src/api.tsindex ef98e15328..ab1c1d8bec 100644--- a/internal/cloudcp/portal/frontend/src/api.ts+++ b/internal/cloudcp/portal/frontend/src/api.ts@@ -21,7 +21,6 @@ export interface PortalBillingResponse {}export interface PortalMagicLinkResponse {- success?: boolean;message?: string;}@@ -142,7 +141,7 @@ export function createPortalAPI(context: PortalAPIContext): PortalAPI {}, 'Failed to sign out.');},postCommercialJSON: function<T>(path: string, body: Record<string, unknown>) {- return request<T>(bootstrap().commercial_api_base_path + path, {+ return request<T>(bootstrap().commercial_api_base_url + path, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),diff --git a/internal/cloudcp/portal/frontend/src/app.test.ts b/internal/cloudcp/portal/frontend/src/app.test.tsindex 304b4447e0..1615160b9f 100644--- a/internal/cloudcp/portal/frontend/src/app.test.ts+++ b/internal/cloudcp/portal/frontend/src/app.test.ts@@ -27,7 +27,7 @@ async function flushAsync() {const bootstrapDefaults: Omit<PortalBootstrapData, 'authenticated' | 'email' | 'accounts'> = {public_site_url: 'https://pulserelay.pro',support_email: '[email protected]',- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',portal_path: '/portal',bootstrap_path: '/api/portal/bootstrap',magic_link_request_path: '/api/public/magic-link/request',@@ -186,10 +186,7 @@ describe('portal app', function() {email: '',accounts: [],});- var fetchMock = vi.fn().mockResolvedValue(jsonResponse({- success: true,- message: "If that email is registered, you'll receive a magic link shortly.",- }));+ var fetchMock = vi.fn().mockResolvedValue(jsonResponse({}));vi.stubGlobal('fetch', fetchMock);installPortalApp({@@ -212,7 +209,7 @@ describe('portal app', function() {body: JSON.stringify({ email: '[email protected]', target: 'portal' }),}));- expect(document.getElementById('portal-app-root')?.textContent).toContain("If that email is registered, you'll receive a magic link shortly.");+ expect(document.getElementById('portal-app-root')?.textContent).toContain('If that email is registered, a magic link is on the way.');});it('completes the retrieve-license flow through the real authenticated app shell', async function() {@@ -242,10 +239,10 @@ describe('portal app', function() {accounts: accounts,});}- if (url === '/api/portal/commercial/v1/retrieve-license/request') {+ if (url === 'https://license.pulserelay.pro/v1/retrieve-license/request') {return jsonResponse({});}- if (url === '/api/portal/commercial/v1/retrieve-license') {+ if (url === 'https://license.pulserelay.pro/v1/retrieve-license') {return jsonResponse({license: {token: 'pulse_token_123',@@ -284,14 +281,14 @@ describe('portal app', function() {await flushAsync();expect(fetchMock.mock.calls).toContainEqual([- '/api/portal/commercial/v1/retrieve-license/request',+ 'https://license.pulserelay.pro/v1/retrieve-license/request',expect.objectContaining({method: 'POST',body: JSON.stringify({ email: '[email protected]' }),}),]);expect(fetchMock.mock.calls).toContainEqual([- '/api/portal/commercial/v1/retrieve-license',+ 'https://license.pulserelay.pro/v1/retrieve-license',expect.objectContaining({method: 'POST',body: JSON.stringify({ email: '[email protected]', code: '123456' }),diff --git a/internal/cloudcp/portal/frontend/src/auth_controller.test.ts b/internal/cloudcp/portal/frontend/src/auth_controller.test.tsindex 8c0bf9d6fb..6b2334c747 100644--- a/internal/cloudcp/portal/frontend/src/auth_controller.test.ts+++ b/internal/cloudcp/portal/frontend/src/auth_controller.test.ts@@ -17,7 +17,7 @@ async function flushAsync() {const bootstrapDefaults: Omit<PortalBootstrapData, 'authenticated' | 'email' | 'accounts'> = {public_site_url: 'https://pulserelay.pro',support_email: '[email protected]',- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',portal_path: '/portal',bootstrap_path: '/api/portal/bootstrap',magic_link_request_path: '/magic-link',@@ -60,10 +60,10 @@ describe('auth controller', function() {status: 200,headers: new Headers({ 'content-type': 'application/json' }),json: async function() {- return {- success: true,- message: "If that email is registered, you'll receive a magic link shortly.",- };+ return { message: 'If that email is registered, you will receive a magic link shortly.' };+ },+ text: async function() {+ return '';},}));@@ -88,11 +88,12 @@ describe('auth controller', function() {expect(controller.getLoginState().request.pending).toBe(false);expect(controller.getLoginState().request.error).toBe('');expect(controller.getLoginState().success).toBe(true);- expect(controller.getLoginState().successMessage).toBe("If that email is registered, you'll receive a magic link shortly.");+ expect(controller.getLoginState().successMessage).toContain('If that email is registered');expect(fetch).toHaveBeenCalledWith('/magic-link',expect.objectContaining({method: 'POST',+ body: JSON.stringify({ email: '[email protected]', target: 'portal' }),}));});diff --git a/internal/cloudcp/portal/frontend/src/auth_controller.ts b/internal/cloudcp/portal/frontend/src/auth_controller.tsindex 51e87d3871..3bdfd1791a 100644--- a/internal/cloudcp/portal/frontend/src/auth_controller.ts+++ b/internal/cloudcp/portal/frontend/src/auth_controller.ts@@ -16,8 +16,6 @@ export interface AuthController {getLoginState: () => PortalLoginState;}-const GENERIC_MAGIC_LINK_MESSAGE = "If that email is registered, you'll receive a magic link shortly.";-function asHTMLElement(target: EventTarget | null): HTMLElement | null {return target instanceof HTMLElement ? target : null;}@@ -50,7 +48,7 @@ export function installAuthController(deps: AuthControllerDeps): AuthControllerdeps.store.updateLoginState(function(nextState) {succeedMutationState(nextState.request);nextState.success = true;- nextState.successMessage = String(response && response.message || '').trim() || GENERIC_MAGIC_LINK_MESSAGE;+ nextState.successMessage = String(response?.message || '').trim();});return;} catch (error) {@@ -58,7 +56,7 @@ export function installAuthController(deps: AuthControllerDeps): AuthControllerdeps.store.updateLoginState(function(nextState) {succeedMutationState(nextState.request);nextState.success = true;- nextState.successMessage = GENERIC_MAGIC_LINK_MESSAGE;+ nextState.successMessage = '';});return;}diff --git a/internal/cloudcp/portal/frontend/src/runtime.test.ts b/internal/cloudcp/portal/frontend/src/runtime.test.tsindex 258431c1f7..5aeceb1651 100644--- a/internal/cloudcp/portal/frontend/src/runtime.test.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.test.ts@@ -7,7 +7,7 @@ describe('portal runtime', function() {var defaults = createBootstrapDefaults({public_site_url: 'https://cloud.pulserelay.pro',support_email: '[email protected]',- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',portal_path: '/account',bootstrap_path: '/api/account/bootstrap',magic_link_request_path: '/api/public/account/magic-link/request',@@ -28,12 +28,12 @@ describe('portal runtime', function() {authenticated: true,email: '[email protected]',accounts: [],- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',});expect(runtime.store.getBootstrap().authenticated).toBe(true);expect(runtime.store.getBootstrap().email).toBe('[email protected]');- expect(runtime.bootstrapDefaults.commercial_api_base_path).toBe('/api/portal/commercial');+ expect(runtime.bootstrapDefaults.commercial_api_base_url).toBe('https://license.pulserelay.pro');});it('derives canonical email and service handoff from the portal URL', function() {diff --git a/internal/cloudcp/portal/frontend/src/runtime.ts b/internal/cloudcp/portal/frontend/src/runtime.tsindex 3bb82e9672..6c4f47fe31 100644--- a/internal/cloudcp/portal/frontend/src/runtime.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.ts@@ -66,7 +66,7 @@ export function createBootstrapDefaults(return {public_site_url: embeddedBootstrap.public_site_url || 'https://pulserelay.pro',support_email: embeddedBootstrap.support_email || '[email protected]',- commercial_api_base_path: embeddedBootstrap.commercial_api_base_path || '/api/portal/commercial',+ commercial_api_base_url: embeddedBootstrap.commercial_api_base_url || '',portal_path: embeddedBootstrap.portal_path || '/portal',bootstrap_path: embeddedBootstrap.bootstrap_path || '/api/portal/bootstrap',magic_link_request_path: embeddedBootstrap.magic_link_request_path || '/api/public/magic-link/request',diff --git a/internal/cloudcp/portal/frontend/src/services_view.test.ts b/internal/cloudcp/portal/frontend/src/services_view.test.tsindex 7d6b8892bc..5087a20861 100644--- a/internal/cloudcp/portal/frontend/src/services_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/services_view.test.ts@@ -18,7 +18,7 @@ function createBootstrap(overrides: Partial<PortalBootstrapData> = {}): PortalBoemail: '[email protected]',public_site_url: 'https://pulserelay.pro',support_email: '[email protected]',- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',portal_path: '/portal',bootstrap_path: '/api/portal/bootstrap',magic_link_request_path: '/auth/magic-link',diff --git a/internal/cloudcp/portal/frontend/src/shell_view.test.ts b/internal/cloudcp/portal/frontend/src/shell_view.test.tsindex ee6c88ce45..92ece702f5 100644--- a/internal/cloudcp/portal/frontend/src/shell_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/shell_view.test.ts@@ -15,7 +15,7 @@ function createBootstrap(overrides: Partial<PortalBootstrapData> = {}): PortalBoemail: '[email protected]',public_site_url: 'https://pulserelay.pro',support_email: '[email protected]',- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',portal_path: '/portal',bootstrap_path: '/api/portal/bootstrap',magic_link_request_path: '/auth/magic-link',@@ -75,7 +75,8 @@ describe('shell view', function() {it('renders empty accounts state with support contact', function() {var html = renderAccountsHTML(createContext());- expect(html).toContain('No hosted workspaces on this account');+ expect(html).toContain('No hosted workspaces are attached to this account.');+ expect(html).toContain('self-hosted licensing and billing tools below');expect(html).toContain('mailto:[email protected]');expect(html).toContain('[email protected]');});@@ -99,6 +100,8 @@ describe('shell view', function() {display_name: 'Alpha Workspace',state: 'active',healthy: true,+ health_status: 'healthy',+ last_health_check: '2026-03-26T10:10:00Z',created_at: '2026-03-26T10:00:00Z',},{@@ -106,6 +109,14 @@ describe('shell view', function() {display_name: 'Beta Workspace',state: 'failed',healthy: false,+ health_status: 'unhealthy',+ },+ {+ id: 'ws_pending',+ display_name: 'Gamma Workspace',+ state: 'provisioning',+ healthy: false,+ health_status: 'checking',},],},@@ -116,32 +127,60 @@ describe('shell view', function() {expect(html).toContain('<h1>Pulse Account</h1>');expect(html).toContain('Hosted access is active on this account.');- expect(html).toContain('MSP operator');- expect(html).toContain('Hosted workspaces');+ expect(html).toContain('portal-section-nav');+ expect(html).toContain('Hosted operations');+ expect(html).toContain('Account services');+ expect(html).toContain('Support');+ expect(html).toContain('id="hosted-operations-section"');+ expect(html).toContain('id="account-services-section"');+ expect(html).toContain('Self-hosted licenses and billing');expect(html).toContain('id="accounts-root"');+ expect(html).toContain('MSP account');+ expect(html).toContain('MSP account · Owner · 3 workspaces');expect(html).toContain('Acme MSP');- expect(html).toContain('MSP account · Owner · 2 workspaces');+ expect(html).toContain('Account operations');+ expect(html).toContain('Manage the client fleet from this account surface.');+ expect(html).toContain('Workspace fleet');expect(html).toContain('Alpha Workspace');+ expect(html).toContain('Beta Workspace');+ expect(html).toContain('Gamma Workspace');+ expect(html).toContain('Active workspaces');+ expect(html).toContain('Needs attention');+ expect(html).toContain('Healthy</span>');+ expect(html).toContain('Unhealthy</span>');+ expect(html).toContain('Checking</span>');+ expect(html).toContain('Live updates and health checks are currently good.');+ expect(html).toContain('This workspace needs attention before it is trustworthy.');+ expect(html).toContain('This workspace is still waiting on a completed health check.');expect(html).toContain('/api/accounts/acct_1/tenants/ws_active/handoff');expect(html).toContain('Open workspace');- expect(html).toContain('Manage</button>');- expect(html).toContain('data-action="workspace-manage"');+ expect(html).toContain('data-action="select-workspace"');+ expect(html).toContain('Workspace management');+ expect(html).toContain('Choose a workspace to manage from the fleet above.');+ expect(html).toContain('data-action="clear-workspace-selection"');+ expect(html).toContain('Team management');+ expect(html).toContain('Invite someone new');+ expect(html).toContain('People on this account');+ expect(html).toContain('data-action="workspace-action"');expect(html).toContain('service-card-button');- expect(html).toContain('Self-hosted licenses and billing');expect(html).toContain('id="open-retrieve-service"');expect(html).toContain('id="data-service-panel"');});- it('renders a self-hosted overview when the signed-in account has no hosted workspaces', function() {- var html = renderAuthenticatedPortalHTML(createContext());+ it('renders self-hosted overview copy when no hosted accounts are attached', function() {+ var html = renderAuthenticatedPortalHTML(+ createContext({+ bootstrap: createBootstrap({+ accounts: [],+ }),+ })+ );- expect(html).toContain('This account currently uses Pulse Account for self-hosted commercial services.');- expect(html).toContain('Signed in as');- expect(html).toContain('[email protected]');- expect(html).toContain('Hosted access');- expect(html).toContain('None on this account');- expect(html).toContain('Self-hosted account services');- expect(html).not.toContain('Other account services');+ expect(html).toContain('<h1>Self-hosted Pulse Account</h1>');+ expect(html).toContain('No hosted workspace access is attached to this account yet.');+ expect(html).toContain('This account does not currently have hosted workspace access.');+ expect(html).toContain('Account services');+ expect(html).not.toContain('Self-hosted licenses and billing');});it('renders signed-out portal with error and success login states', function() {@@ -163,7 +202,6 @@ describe('shell view', function() {loginState: createLoginState({emailValue: '[email protected]',success: true,- successMessage: "If that email is registered, you'll receive a magic link shortly.",request: {pending: false,error: '',@@ -174,7 +212,7 @@ describe('shell view', function() {expect(errorHTML).toContain('value="[email protected]"');expect(errorHTML).toContain('Invalid email');- expect(successHTML).toContain("If that email is registered, you'll receive a magic link shortly.");+ expect(successHTML).toContain('If that email is registered, a magic link is on the way.');expect(successHTML).toContain('data-portal-action="resend-magic-link"');});});diff --git a/internal/cloudcp/portal/frontend/src/shell_view.ts b/internal/cloudcp/portal/frontend/src/shell_view.tsindex 85aeb2e66e..2c39b20a96 100644--- a/internal/cloudcp/portal/frontend/src/shell_view.ts+++ b/internal/cloudcp/portal/frontend/src/shell_view.ts@@ -12,14 +12,6 @@ export interface ShellViewContext {accountAPIBasePath: string;}-function hasHostedAccounts(bootstrap: PortalBootstrapData): boolean {- return Array.isArray(bootstrap.accounts) && bootstrap.accounts.length > 0;-}--function listAccounts(bootstrap: PortalBootstrapData): PortalAccountSummary[] {- return Array.isArray(bootstrap.accounts) ? bootstrap.accounts : [];-}-function escapeHTML(value: unknown): string {return String(value || '').replace(/&/g, '&')@@ -47,46 +39,130 @@ function roleBadgeHTML(role: string): string {return '';}-function formatRoleLabel(role: string): string {- if (role === 'owner') return 'Owner';- if (role === 'admin') return 'Admin';- if (role === 'tech') return 'Tech';- if (role === 'read_only') return 'Read-only';- return 'Member';+function healthBadgeHTML(workspace: PortalWorkspaceSummary): string {+ if (workspace.health_status === 'healthy') {+ return '<span class="badge badge-healthy">Healthy</span>';+ }+ if (workspace.health_status === 'unhealthy') {+ return '<span class="badge badge-unhealthy">Unhealthy</span>';+ }+ return '<span class="badge badge-checking">Checking</span>';+}++function workspaceCountLabel(count: number): string {+ return count === 1 ? '1 workspace' : String(count) + ' workspaces';+}++function accountKindLabel(account: PortalAccountSummary): string {+ if (account.kind === 'msp') return 'MSP account';+ if (account.kind === 'cloud') return 'Cloud account';+ if (account.kind === 'individual') return 'Hosted account';+ return account.kind_label ? account.kind_label + ' account' : 'Account';+}++function titleCase(value: string): string {+ if (!value) return '';+ return value.charAt(0).toUpperCase() + value.slice(1);+}++function countWorkspaces(accounts: PortalAccountSummary[]): number {+ var total = 0;+ for (var i = 0; i < accounts.length; i += 1) {+ total += Array.isArray(accounts[i].workspaces) ? accounts[i].workspaces.length : 0;+ }+ return total;+}++function hasHostedAccounts(accounts: PortalAccountSummary[]): boolean {+ return accounts.length > 0;}-function formatAccountAccessLabel(accounts: PortalAccountSummary[]): string {- if (accounts.length === 1) {- if (accounts[0].kind === 'msp') return 'MSP operator';- if (accounts[0].kind === 'cloud' || accounts[0].kind === 'individual') return 'Pulse Cloud';+function countWorkspacesByHealth(workspaces: PortalWorkspaceSummary[], status: string): number {+ var count = 0;+ for (var i = 0; i < workspaces.length; i += 1) {+ if (String(workspaces[i].health_status || '') === status) count += 1;}- return 'Hosted access';+ return count;}-function totalWorkspaceCount(accounts: PortalAccountSummary[]): number {- return accounts.reduce(function(total, account) {- return total + (Array.isArray(account.workspaces) ? account.workspaces.length : 0);- }, 0);+function countWorkspacesByState(workspaces: PortalWorkspaceSummary[], state: string): number {+ var count = 0;+ for (var i = 0; i < workspaces.length; i += 1) {+ if (String(workspaces[i].state || '') === state) count += 1;+ }+ return count;}-function totalActiveWorkspaceCount(accounts: PortalAccountSummary[]): number {- return accounts.reduce(function(total, account) {- return total + (Array.isArray(account.workspaces)- ? account.workspaces.filter(function(workspace) { return workspace.state === 'active'; }).length- : 0);- }, 0);+function renderOverviewBand(context: ShellViewContext, accounts: PortalAccountSummary[]): string {+ var hosted = hasHostedAccounts(accounts);+ var workspaceTotal = countWorkspaces(accounts);+ var title = hosted ? 'Pulse Account' : 'Self-hosted Pulse Account';+ var summary = hosted+ ? 'Open hosted workspaces, manage account access, and handle commercial account services from one place.'+ : 'This account currently has no hosted workspaces. Self-hosted licenses, billing, refunds, and data requests stay available below.';+ var hostedStateLabel = hosted ? 'Active' : 'Not attached';+ var hostedStateClass = hosted ? 'overview-stat-positive' : 'overview-stat-muted';+ var accountsLabel = accounts.length === 1 ? '1 account' : String(accounts.length) + ' accounts';++ return (+ '<section class="overview-band">' ++ '<div class="overview-copy">' ++ '<div class="overview-kicker">' + (hosted ? 'Hosted access is active on this account.' : 'No hosted workspace access is attached to this account yet.') + '</div>' ++ '<h1>' + title + '</h1>' ++ '<p>' + summary + '</p>' ++ '</div>' ++ '<div class="overview-stats">' ++ '<div class="overview-stat-card">' ++ '<span class="overview-stat-label">Hosted access</span>' ++ '<span class="overview-stat-value ' + hostedStateClass + '">' + hostedStateLabel + '</span>' ++ '</div>' ++ '<div class="overview-stat-card">' ++ '<span class="overview-stat-label">Accounts</span>' ++ '<span class="overview-stat-value">' + accountsLabel + '</span>' ++ '</div>' ++ '<div class="overview-stat-card">' ++ '<span class="overview-stat-label">Workspaces</span>' ++ '<span class="overview-stat-value">' + String(workspaceTotal) + '</span>' ++ '</div>' ++ '</div>' ++ '</section>'+ );}-function formatAccountSummary(account: PortalAccountSummary): string {- var workspaceCount = Array.isArray(account.workspaces) ? account.workspaces.length : 0;- var workspaceLabel = workspaceCount === 1 ? '1 workspace' : String(workspaceCount) + ' workspaces';- return account.kind_label + ' account · ' + formatRoleLabel(account.role) + ' · ' + workspaceLabel;+function renderShellNavigation(accounts: PortalAccountSummary[], supportEmail: string): string {+ var hosted = hasHostedAccounts(accounts);+ var hostedLabel = hosted ? 'Hosted operations' : 'Hosted access';+ var hostedCopy = hosted+ ? 'Workspaces, teams, and hosted billing'+ : 'No hosted workspaces are attached yet';++ return (+ '<nav class="portal-section-nav" aria-label="Pulse Account sections">' ++ '<a class="portal-section-link" href="#hosted-operations-section">' ++ '<span class="portal-section-link-label">' + hostedLabel + '</span>' ++ '<span class="portal-section-link-copy">' + hostedCopy + '</span>' ++ '</a>' ++ '<a class="portal-section-link" href="#account-services-section">' ++ '<span class="portal-section-link-label">Account services</span>' ++ '<span class="portal-section-link-copy">Licenses, billing, refunds, and privacy</span>' ++ '</a>' ++ '<a class="portal-section-link" href="mailto:' + escapeAttr(supportEmail || '') + '">' ++ '<span class="portal-section-link-label">Support</span>' ++ '<span class="portal-section-link-copy">' + escapeHTML(supportEmail || '') + '</span>' ++ '</a>' ++ '</nav>'+ );}function renderWorkspaceCard(account: PortalAccountSummary, workspace: PortalWorkspaceSummary, accountAPIBasePath: string): string {var state = String(workspace.state || '');var safeState = escapeHTML(state);var createdLabel = formatWorkspaceDate(workspace.created_at);+ var healthSummary = workspace.health_status === 'healthy'+ ? 'Live updates and health checks are currently good.'+ : workspace.health_status === 'unhealthy'+ ? 'This workspace needs attention before it is trustworthy.'+ : 'This workspace is still waiting on a completed health check.';var openAction = '';if (state === 'active') {openAction =@@ -102,29 +178,28 @@ function renderWorkspaceCard(account: PortalAccountSummary, workspace: PortalWorvar manageAction = '';if (account.can_manage && (state === 'active' || state === 'suspended' || state === 'failed')) {manageAction =- '<button type="button" class="btn-secondary btn-secondary-quiet" data-action="workspace-manage" data-account-id="' +- escapeAttr(account.id) +- '" data-workspace-id="' +- escapeAttr(workspace.id) +- '" data-workspace-state="' +- escapeAttr(state) +- '" data-workspace-name="' +- escapeAttr(workspace.display_name) +- '">Manage</button>';+ '<button type="button" class="btn-secondary btn-workspace-manage" data-action="select-workspace" data-account-id="' ++ escapeAttr(account.id) ++ '" data-workspace-id="' ++ escapeAttr(workspace.id) ++ '">' ++ 'Manage' ++ '</button>';}var createdMeta = createdLabel ? '<span class="ws-created">Created ' + escapeHTML(createdLabel) + '</span>' : '';return ('<div class="workspace-card">' +'<div class="ws-info">' +- '<span class="ws-name">' + escapeHTML(workspace.display_name) + '</span>' ++ '<div class="ws-title-row">' ++ '<span class="ws-name">' + escapeHTML(workspace.display_name) + '</span>' ++ '</div>' +'<div class="ws-meta">' +- (workspace.healthy- ? '<span class="badge badge-healthy">Healthy</span>'- : '<span class="badge badge-unhealthy">Checking</span>') ++ healthBadgeHTML(workspace) +'<span class="badge badge-' + safeState + '">' + safeState + '</span>' +createdMeta +'</div>' ++ '<div class="ws-summary">' + escapeHTML(healthSummary) + '</div>' +'</div>' +'<div class="ws-actions">' +openAction +@@ -136,19 +211,17 @@ function renderWorkspaceCard(account: PortalAccountSummary, workspace: PortalWorfunction renderAccountSection(account: PortalAccountSummary, accountAPIBasePath: string): string {var workspaces = Array.isArray(account.workspaces) ? account.workspaces : [];+ var summaryText = accountKindLabel(account) + ' · ' + titleCase(account.role) + ' · ' + workspaceCountLabel(workspaces.length);+ var healthyCount = countWorkspacesByHealth(workspaces, 'healthy');+ var checkingCount = countWorkspacesByHealth(workspaces, 'checking');+ var unhealthyCount = countWorkspacesByHealth(workspaces, 'unhealthy');+ var activeCount = countWorkspacesByState(workspaces, 'active');+ var operationsCopy = account.kind === 'msp'+ ? 'Manage the client fleet from this account surface. Workspace creation, billing, and team actions belong here.'+ : 'Use this account surface to open hosted workspaces, manage billing, and control access for this hosted account.';var workspaceHTML = '';if (workspaces.length === 0) {- workspaceHTML =- '<div class="empty-state empty-state-account">' +- '<p class="empty-state-title">' +- (account.kind === 'msp' ? 'No client workspaces yet' : 'No hosted workspaces yet') +- '</p>' +- '<p>' +- (account.kind === 'msp'- ? 'Create a workspace when you are ready to onboard a customer environment.'- : 'This account is ready for hosted access, but no workspace has been provisioned yet.') +- '</p>' +- '</div>';+ workspaceHTML = '<div class="empty-state"><p>No hosted workspaces yet. Create one to get started.</p></div>';} else {workspaceHTML ='<div class="workspace-list">' +@@ -161,15 +234,21 @@ function renderAccountSection(account: PortalAccountSummary, accountAPIBasePath:var actions = '';var teamSection = '';var addWorkspaceForm = '';+ var workspaceManagement = '';if (account.can_manage) {actions =+ '<div class="account-operations-panel">' ++ '<div class="account-operations-copy">' ++ '<h3>Account operations</h3>' ++ '<p>' + escapeHTML(operationsCopy) + '</p>' ++ '</div>' +'<div class="account-actions">' +(account.kind === 'msp'? '<button type="button" class="btn-secondary" id="add-ws-btn-' +escapeAttr(account.id) +'" data-action="toggle-add-workspace" data-account-id="' +escapeAttr(account.id) +- '">+ Add workspace</button>'+ '">Add workspace</button>': '') +(account.has_billing? '<button type="button" class="btn-secondary" data-action="open-billing" data-account-id="' +@@ -181,15 +260,33 @@ function renderAccountSection(account: PortalAccountSummary, accountAPIBasePath:'" data-action="toggle-team" data-account-id="' +escapeAttr(account.id) +'">Manage team</button>' ++ '</div>' +'</div>';teamSection =- '<div class="team-section" id="team-section-' ++ '<div class="team-management-panel team-section" id="team-section-' +escapeAttr(account.id) +'" data-actor-role="' +escapeAttr(account.role) +'">' +- '<h3>Team members</h3>' ++ '<div class="team-management-header">' ++ '<div>' ++ '<h3>Team management</h3>' ++ '<p>Control who can operate this account, what role they hold, and who should be invited next.</p>' ++ '</div>' ++ '<button type="button" class="btn-secondary btn-compact" data-action="toggle-team" data-account-id="' ++ escapeAttr(account.id) ++ '">Done</button>' ++ '</div>' ++ '<div class="team-management-stats" id="team-stats-' ++ escapeAttr(account.id) ++ '"></div>' ++ '<div class="team-management-grid">' ++ '<div class="team-roster">' ++ '<div class="team-panel-heading">' ++ '<h4>People on this account</h4>' ++ '<p>Owners can manage billing and account access. Admins and techs keep the hosted fleet running day to day.</p>' ++ '</div>' +'<table class="team-table">' +'<thead><tr><th>Email</th><th>Role</th><th></th></tr></thead>' +'<tbody id="team-list-' +@@ -198,6 +295,12 @@ function renderAccountSection(account: PortalAccountSummary, accountAPIBasePath:'<tr><td colspan="3" class="team-message-cell">Loading…</td></tr>' +'</tbody>' +'</table>' ++ '</div>' ++ '<div class="team-invite-panel">' ++ '<div class="team-panel-heading">' ++ '<h4>Invite someone new</h4>' ++ '<p>Add another operator with the minimum role they need for this account.</p>' ++ '</div>' +'<div class="team-invite">' +'<div><label for="invite-email-' +escapeAttr(account.id) +@@ -213,6 +316,48 @@ function renderAccountSection(account: PortalAccountSummary, accountAPIBasePath:escapeAttr(account.id) +'">Invite</button>' +'</div>' ++ '</div>' ++ '</div>' ++ '</div>';++ workspaceManagement =+ '<div class="workspace-management-panel" id="workspace-management-' ++ escapeAttr(account.id) ++ '">' ++ '<div class="workspace-management-header">' ++ '<div>' ++ '<h3>Workspace management</h3>' ++ '<p>Select a workspace from the fleet to review its lifecycle state and run explicit management actions.</p>' ++ '</div>' ++ '<button type="button" class="btn-secondary btn-compact" id="workspace-management-close-' ++ escapeAttr(account.id) ++ '" data-action="clear-workspace-selection" data-account-id="' ++ escapeAttr(account.id) ++ '">Done</button>' ++ '</div>' ++ '<div class="workspace-management-empty" id="workspace-management-empty-' ++ escapeAttr(account.id) ++ '">Choose a workspace to manage from the fleet above.</div>' ++ '<div class="workspace-management-content" id="workspace-management-content-' ++ escapeAttr(account.id) ++ '" hidden>' ++ '<div class="workspace-management-meta" id="workspace-management-meta-' ++ escapeAttr(account.id) ++ '"></div>' ++ '<h4 id="workspace-management-title-' ++ escapeAttr(account.id) ++ '"></h4>' ++ '<p class="workspace-management-summary" id="workspace-management-summary-' ++ escapeAttr(account.id) ++ '"></p>' ++ '<div class="workspace-management-actions">' ++ '<button type="button" class="btn-danger" id="workspace-management-action-' ++ escapeAttr(account.id) ++ '" data-action="workspace-action" data-account-id="' ++ escapeAttr(account.id) ++ '">Manage workspace</button>' ++ '</div>' ++ '</div>' +'</div>';if (account.kind === 'msp') {@@ -245,16 +390,40 @@ function renderAccountSection(account: PortalAccountSummary, accountAPIBasePath:'<section class="account-section">' +'<div class="account-header">' +'<div class="account-heading">' +- '<div class="account-heading-row">' +- '<h2>' + escapeHTML(account.name) + '</h2>' +- '<span class="badge badge-' + escapeHTML(account.kind) + '">' + escapeHTML(account.kind_label) + '</span>' +- roleBadgeHTML(account.role) +- '</div>' +- '<p class="account-summary">' + escapeHTML(formatAccountSummary(account)) + '</p>' ++ '<div class="account-eyebrow">' + escapeHTML(accountKindLabel(account)) + '</div>' ++ '<h2>' + escapeHTML(account.name) + '</h2>' ++ '<div class="account-summary">' + escapeHTML(summaryText) + '</div>' ++ '</div>' ++ '<div class="account-badges">' ++ '<span class="badge badge-' + escapeHTML(account.kind) + '">' + escapeHTML(account.kind_label) + '</span>' ++ roleBadgeHTML(account.role) ++ '</div>' ++ '</div>' ++ '<div class="account-status-grid">' ++ '<div class="account-stat-card">' ++ '<span class="account-stat-label">Active workspaces</span>' ++ '<span class="account-stat-value">' + String(activeCount) + '</span>' ++ '</div>' ++ '<div class="account-stat-card">' ++ '<span class="account-stat-label">Healthy</span>' ++ '<span class="account-stat-value account-stat-healthy">' + String(healthyCount) + '</span>' ++ '</div>' ++ '<div class="account-stat-card">' ++ '<span class="account-stat-label">Checking</span>' ++ '<span class="account-stat-value account-stat-checking">' + String(checkingCount) + '</span>' ++ '</div>' ++ '<div class="account-stat-card">' ++ '<span class="account-stat-label">Needs attention</span>' ++ '<span class="account-stat-value account-stat-unhealthy">' + String(unhealthyCount) + '</span>' +'</div>' +'</div>' +- workspaceHTML +actions ++ '<div class="account-subsection-header">' ++ '<h3>Workspace fleet</h3>' ++ '<p>Open hosted Pulse workspaces, review fleet health, and manage lifecycle actions for this account.</p>' ++ '</div>' ++ workspaceHTML ++ workspaceManagement +teamSection +addWorkspaceForm +'</section>'@@ -275,9 +444,9 @@ export function renderAccountsHTML(context: ShellViewContext): string {var safeAccounts = Array.isArray(context.bootstrap.accounts) ? context.bootstrap.accounts : [];if (safeAccounts.length === 0) {return (- '<div class="empty-state empty-state-spaced empty-state-self-hosted">' +- '<p class="empty-state-title">No hosted workspaces on this account</p>' +- '<p>This Pulse Account is still valid for self-hosted billing, license recovery, refunds, and privacy requests. Hosted Cloud or MSP workspaces will appear here when this account owns them.</p>' ++ '<div class="empty-state empty-state-spaced">' ++ '<p>No hosted workspaces are attached to this account.</p>' ++ '<p class="support-copy">You can still use the self-hosted licensing and billing tools below.</p>' +'<p class="support-copy">Need help? Contact <a href="mailto:' +escapeAttr(context.bootstrap.support_email || '') +'" class="support-link">' +@@ -291,74 +460,28 @@ export function renderAccountsHTML(context: ShellViewContext): string {}).join('');}-function renderAuthenticatedIntroHTML(context: ShellViewContext): string {- var accounts = listAccounts(context.bootstrap);- if (!hasHostedAccounts(context.bootstrap)) {- return (- '<section class="intro-card intro-card-self-hosted">' +- '<h1>Pulse Account</h1>' +- '<p>This account currently uses Pulse Account for self-hosted commercial services. When you own hosted Cloud workspaces or MSP access, they will appear here in the same account shell.</p>' +- '<div class="overview-grid">' +- '<div class="overview-stat">' +- '<span class="overview-label">Signed in as</span>' +- '<strong>' + escapeHTML(context.bootstrap.email || '') + '</strong>' +- '</div>' +- '<div class="overview-stat">' +- '<span class="overview-label">Hosted access</span>' +- '<strong>None on this account</strong>' +- '</div>' +- '<div class="overview-stat">' +- '<span class="overview-label">Self-hosted services</span>' +- '<strong>Available below</strong>' +- '</div>' +- '</div>' +- '</section>'- );- }-- var totalWorkspaces = totalWorkspaceCount(accounts);- var activeWorkspaces = totalActiveWorkspaceCount(accounts);- var accessLabel = formatAccountAccessLabel(accounts);- return (- '<section class="intro-card">' +- '<h1>Pulse Account</h1>' +- '<p>Hosted access is active on this account. Open workspaces here, manage team and billing at the account level, and keep self-hosted commercial tools in the same account surface instead of splitting them across public utility pages.</p>' +- '<div class="overview-grid">' +- '<div class="overview-stat">' +- '<span class="overview-label">Signed in as</span>' +- '<strong>' + escapeHTML(context.bootstrap.email || '') + '</strong>' +- '</div>' +- '<div class="overview-stat">' +- '<span class="overview-label">Account access</span>' +- '<strong>' + escapeHTML(accessLabel) + '</strong>' +- '</div>' +- '<div class="overview-stat">' +- '<span class="overview-label">Hosted workspaces</span>' +- '<strong>' + escapeHTML(String(totalWorkspaces)) + '</strong>' +- '</div>' +- '<div class="overview-stat">' +- '<span class="overview-label">Active now</span>' +- '<strong>' + escapeHTML(String(activeWorkspaces)) + '</strong>' +- '</div>' +- '</div>' +- '<div class="intro-guidance">Use <strong>Open workspace</strong> to enter a hosted Pulse runtime. Team, workspace lifecycle, and billing controls stay with each account card below.</div>' +- '</section>'- );-}-export function renderAuthenticatedPortalHTML(context: ShellViewContext): string {- var hostedAccounts = hasHostedAccounts(context.bootstrap);+ var accounts = Array.isArray(context.bootstrap.accounts) ? context.bootstrap.accounts : [];+ var serviceHeading = hasHostedAccounts(accounts) ? 'Self-hosted licenses and billing' : 'Account services';+ var serviceNote = hasHostedAccounts(accounts)+ ? 'Hosted access lives above. The self-hosted commercial tools remain available here for licenses, billing, refunds, and privacy actions.'+ : 'Use these account tools for self-hosted licenses, billing, refunds, and privacy actions.';return (- renderAuthenticatedIntroHTML(context) +- '<div id="accounts-root">' + renderAccountsHTML(context) + '</div>' +- '<section class="service-section">' ++ renderOverviewBand(context, accounts) ++ renderShellNavigation(accounts, context.bootstrap.support_email || '') ++ '<section class="portal-top-section" id="hosted-operations-section">' ++ '<div class="portal-top-section-header">' ++ '<h2>' + (hasHostedAccounts(accounts) ? 'Hosted operations' : 'Hosted access') + '</h2>' ++ '<p>' + (hasHostedAccounts(accounts)+ ? 'Use this area for workspace access, fleet operations, hosted billing, and team management.'+ : 'This account does not currently have hosted workspace access. If that is unexpected, contact support while using the commercial tools below.') + '</p>' ++ '</div>' ++ '<div id="accounts-root">' + renderAccountsHTML(context) + '</div>' ++ '</section>' ++ '<section class="service-section" id="account-services-section">' +'<div class="service-header">' +- '<h2>' + (hostedAccounts ? 'Self-hosted licenses and billing' : 'Self-hosted account services') + '</h2>' +- '<div class="service-note">' +- (hostedAccounts- ? 'These tools stay available on the same account for self-hosted subscriptions, license recovery, refunds, and privacy actions. Hosted workspace administration stays above.'- : 'Use these tools for subscription, license, refund, and privacy actions on self-hosted commercial accounts. The public utility pages remain as compatibility entry points only.') +- '</div>' ++ '<h2>' + serviceHeading + '</h2>' ++ '<div class="service-note">' + serviceNote + '</div>' +'</div>' +'<div class="service-grid">' +'<button class="service-card service-card-button" type="button" id="open-manage-service" data-account-service-action="open-service-panel" data-account-service-panel="manage-service-panel" data-account-service-focus="manage-inline-email">' +@@ -401,9 +524,10 @@ export function renderSignedOutPortalHTML(context: ShellViewContext): string {if (context.loginState.request.error) {statusHTML = '<div class="service-status visible error">' + escapeHTML(context.loginState.request.error) + '</div>';} else if (context.loginState.success) {+ var successMessage = context.loginState.successMessage || 'If that email is registered, a magic link is on the way.';statusHTML ='<div class="service-status visible success">' +- escapeHTML(context.loginState.successMessage || "If that email is registered, you'll receive a magic link shortly.") ++ escapeHTML(successMessage) +'<br><br><strong>Don\'t see it?</strong> <a href="#" data-portal-action="resend-magic-link">Send a new link</a>.' +'</div>';}diff --git a/internal/cloudcp/portal/frontend/src/state.ts b/internal/cloudcp/portal/frontend/src/state.tsindex 6615c43846..4036adc5a0 100644--- a/internal/cloudcp/portal/frontend/src/state.ts+++ b/internal/cloudcp/portal/frontend/src/state.ts@@ -69,6 +69,8 @@ export function ensurePortalAccountUIEntry(accountState: PortalAccountState, accaccountState.byAccountID[accountID] = {addWorkspaceOpen: false,createWorkspace: createMutationState(),+ selectedWorkspaceID: '',+ manageWorkspace: createMutationState(),teamVisible: false,teamQuery: createQueryState<PortalTeamMember[]>([]),};diff --git a/internal/cloudcp/portal/frontend/src/store.test.ts b/internal/cloudcp/portal/frontend/src/store.test.tsindex a755fba38a..c8c10f2190 100644--- a/internal/cloudcp/portal/frontend/src/store.test.ts+++ b/internal/cloudcp/portal/frontend/src/store.test.ts@@ -6,7 +6,7 @@ import type { PortalBootstrapData } from './types';const bootstrapDefaults: Omit<PortalBootstrapData, 'authenticated' | 'email' | 'accounts'> = {public_site_url: 'https://pulserelay.pro',support_email: '[email protected]',- commercial_api_base_path: '/api/portal/commercial',+ commercial_api_base_url: 'https://license.pulserelay.pro',portal_path: '/portal',bootstrap_path: '/api/portal/bootstrap',magic_link_request_path: '/api/public/magic-link/request',diff --git a/internal/cloudcp/portal/frontend/src/types.ts b/internal/cloudcp/portal/frontend/src/types.tsindex 23933b000d..8bac4f6ad2 100644--- a/internal/cloudcp/portal/frontend/src/types.ts+++ b/internal/cloudcp/portal/frontend/src/types.ts@@ -3,6 +3,8 @@ export interface PortalWorkspaceSummary {display_name: string;state: string;healthy: boolean;+ health_status: 'healthy' | 'checking' | 'unhealthy';+ last_health_check?: string;created_at?: string;}@@ -22,7 +24,7 @@ export interface PortalBootstrapData {email: string;public_site_url: string;support_email: string;- commercial_api_base_path: string;+ commercial_api_base_url: string;portal_path: string;bootstrap_path: string;magic_link_request_path: string;@@ -62,6 +64,8 @@ export interface PortalMutationState {export interface PortalAccountUIEntry {addWorkspaceOpen: boolean;createWorkspace: PortalMutationState;+ selectedWorkspaceID: string;+ manageWorkspace: PortalMutationState;teamVisible: boolean;teamQuery: PortalQueryState<PortalTeamMember[]>;}diff --git a/internal/cloudcp/public_cloud_signup_handlers.go b/internal/cloudcp/public_cloud_signup_handlers.goindex e3b60ef790..e8e92b5d5a 100644--- a/internal/cloudcp/public_cloud_signup_handlers.go+++ b/internal/cloudcp/public_cloud_signup_handlers.go@@ -11,6 +11,7 @@ import ("strings""unicode"+ cpauth "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auth""github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/cpsec"cpemail "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/email""github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"@@ -154,9 +155,9 @@ type PublicCloudSignupHandlers struct {registry *registry.TenantRegistrymagicLinks interface {GenerateToken(email, tenantID string) (string, error)- GeneratePortalToken(email string) (string, error)+ GeneratePortalToken(email, tenantID string) (string, error)}- commercialIdentities commercialIdentityLookup+ commercialLookup commercialIdentityLookupFuncemailSender cpemail.SendercreateCheckoutSession func(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error)}@@ -188,22 +189,15 @@ type publicMagicLinkRequest struct {Target string `json:"target,omitempty"`}-type publicMagicLinkTarget string--const (- publicMagicLinkTargetDefault publicMagicLinkTarget = ""- publicMagicLinkTargetPortal publicMagicLinkTarget = "portal"-)-func NewPublicCloudSignupHandlers(cfg *CPConfig, reg *registry.TenantRegistry, magicLinks interface {GenerateToken(email, tenantID string) (string, error)- GeneratePortalToken(email string) (string, error)+ GeneratePortalToken(email, tenantID string) (string, error)}, emailSender cpemail.Sender) *PublicCloudSignupHandlers {return &PublicCloudSignupHandlers{cfg: cfg,registry: reg,magicLinks: magicLinks,- commercialIdentities: newCommercialIdentityClient(cfg),+ commercialLookup: newCommercialIdentityLookup(cfg),emailSender: emailSender,createCheckoutSession: stripesession.New,}@@ -404,7 +398,7 @@ func (h *PublicCloudSignupHandlers) HandlePublicMagicLinkRequest(w http.Responsetarget := parsePublicMagicLinkTarget(req.Target)const msg = "If that email is registered, you'll receive a magic link shortly."- if h.magicLinks == nil {+ if h.registry == nil || h.magicLinks == nil {writePublicSignupJSON(w, http.StatusOK, map[string]any{"success": true,"message": msg,@@ -412,16 +406,26 @@ func (h *PublicCloudSignupHandlers) HandlePublicMagicLinkRequest(w http.Responsereturn}- token, issued, tenantID, err := h.issueMagicLinkToken(r.Context(), email, target)+ tenantID, ok, err := h.resolveMagicLinkTenantID(r.Context(), email, target)if err != nil {- log.Warn().Err(err).Str("email", email).Str("target", string(target)).Msg("public magic link request: token generation failed")+ log.Warn().Err(err).Str("email", email).Str("target", string(target)).Msg("public magic link request: identity lookup failed")writePublicSignupJSON(w, http.StatusOK, map[string]any{"success": true,"message": msg,})return}- if !issued {+ if !ok {+ writePublicSignupJSON(w, http.StatusOK, map[string]any{+ "success": true,+ "message": msg,+ })+ return+ }++ token, err := h.generateMagicLink(email, tenantID, target)+ if err != nil {+ log.Warn().Err(err).Str("email", email).Str("tenant_id", tenantID).Str("target", string(target)).Msg("public magic link request: token generation failed")writePublicSignupJSON(w, http.StatusOK, map[string]any{"success": true,"message": msg,@@ -445,48 +449,6 @@ func (h *PublicCloudSignupHandlers) HandlePublicMagicLinkRequest(w http.Response})}-func parsePublicMagicLinkTarget(raw string) publicMagicLinkTarget {- switch strings.ToLower(strings.TrimSpace(raw)) {- case string(publicMagicLinkTargetPortal):- return publicMagicLinkTargetPortal- default:- return publicMagicLinkTargetDefault- }-}--func (h *PublicCloudSignupHandlers) issueMagicLinkToken(ctx context.Context, email string, target publicMagicLinkTarget) (token string, issued bool, tenantID string, err error) {- tenantID, hasTenant, err := h.findTenantForEmail(email)- if err != nil {- return "", false, "", err- }-- switch target {- case publicMagicLinkTargetPortal:- if hasTenant {- token, err := h.magicLinks.GeneratePortalToken(email)- return token, err == nil, tenantID, err- }- if h.commercialIdentities == nil {- return "", false, "", nil- }- identity, err := h.commercialIdentities.LookupCommercialIdentity(ctx, email)- if err != nil {- return "", false, "", err- }- if identity == nil || !identity.HasCommercialIdentity {- return "", false, "", nil- }- token, err := h.magicLinks.GeneratePortalToken(email)- return token, err == nil, "", err- default:- if !hasTenant {- return "", false, "", nil- }- token, err := h.magicLinks.GenerateToken(email, tenantID)- return token, err == nil, tenantID, err- }-}-func (h *PublicCloudSignupHandlers) createCheckout(email, orgName string, tier cloudTier) (string, error) {if h.cfg == nil {return "", fmt.Errorf("control plane config is missing")@@ -560,9 +522,6 @@ func (h *PublicCloudSignupHandlers) renderSignupPage(w http.ResponseWriter, r *h}func (h *PublicCloudSignupHandlers) findTenantForEmail(email string) (string, bool, error) {- if h.registry == nil {- return "", false, nil- }tenants, err := h.registry.List()if err != nil {return "", false, err@@ -586,6 +545,52 @@ func (h *PublicCloudSignupHandlers) findTenantForEmail(email string) (string, boreturn "", false, nil}+func parsePublicMagicLinkTarget(raw string) cpauth.MagicLinkTarget {+ switch strings.ToLower(strings.TrimSpace(raw)) {+ case string(cpauth.MagicLinkTargetPortal):+ return cpauth.MagicLinkTargetPortal+ default:+ return cpauth.MagicLinkTargetTenant+ }+}++func (h *PublicCloudSignupHandlers) generateMagicLink(email, tenantID string, target cpauth.MagicLinkTarget) (string, error) {+ switch target {+ case cpauth.MagicLinkTargetPortal:+ return h.magicLinks.GeneratePortalToken(email, tenantID)+ default:+ return h.magicLinks.GenerateToken(email, tenantID)+ }+}++func (h *PublicCloudSignupHandlers) resolveMagicLinkTenantID(ctx context.Context, email string, target cpauth.MagicLinkTarget) (string, bool, error) {+ if target == cpauth.MagicLinkTargetPortal {+ if user, err := h.registry.GetUserByEmail(strings.ToLower(strings.TrimSpace(email))); err != nil {+ return "", false, err+ } else if user != nil {+ return "", true, nil+ }+ }++ tenantID, ok, err := h.findTenantForEmail(email)+ if err != nil || ok {+ return tenantID, ok, err+ }++ if target != cpauth.MagicLinkTargetPortal || h.commercialLookup == nil {+ return "", false, nil+ }++ identity, err := h.commercialLookup(ctx, email)+ if err != nil {+ return "", false, err+ }+ if identity != nil && identity.HasCommercialIdentity {+ return "", true, nil+ }+ return "", false, nil+}+func (h *PublicCloudSignupHandlers) sendMagicLinkEmail(email, verifyURL string) error {if h.emailSender == nil || h.cfg == nil || strings.TrimSpace(h.cfg.EmailFrom) == "" {log.Info().diff --git a/internal/cloudcp/public_cloud_signup_handlers_test.go b/internal/cloudcp/public_cloud_signup_handlers_test.goindex 19a233eedc..d00ff2e728 100644--- a/internal/cloudcp/public_cloud_signup_handlers_test.go+++ b/internal/cloudcp/public_cloud_signup_handlers_test.go@@ -15,16 +15,20 @@ import ()type captureMagicLinkGenerator struct {- tenantCalls int- portalCalls int- email string- tenantID string- token string- err error+ calls int+ email string+ tenantID string+ token string+ err error+ portalCalls int+ portalEmail string+ portalTenant string+ portalToken string+ portalErr error}func (c *captureMagicLinkGenerator) GenerateToken(email, tenantID string) (string, error) {- c.tenantCalls+++ c.calls++c.email = emailc.tenantID = tenantIDif c.err != nil {@@ -33,30 +37,14 @@ func (c *captureMagicLinkGenerator) GenerateToken(email, tenantID string) (strinreturn c.token, nil}-func (c *captureMagicLinkGenerator) GeneratePortalToken(email string) (string, error) {+func (c *captureMagicLinkGenerator) GeneratePortalToken(email, tenantID string) (string, error) {c.portalCalls++- c.email = email- c.tenantID = ""- if c.err != nil {- return "", c.err+ c.portalEmail = email+ c.portalTenant = tenantID+ if c.portalErr != nil {+ return "", c.portalErr}- return c.token, nil-}--type captureCommercialIdentityLookup struct {- calls int- email string- result *CommercialIdentityLookupResult- err error-}--func (c *captureCommercialIdentityLookup) LookupCommercialIdentity(_ context.Context, email string) (*CommercialIdentityLookupResult, error) {- c.calls++- c.email = email- if c.err != nil {- return nil, c.err- }- return c.result, nil+ return c.portalToken, nil}type captureEmailSender struct {@@ -228,7 +216,7 @@ func TestPublicCloudSignupHandlePublicMagicLinkRequestKnownTenantSendsEmail(t *tt.Fatalf("Create tenant: %v", err)}- magic := &captureMagicLinkGenerator{token: "ml_test_123"}+ magic := &captureMagicLinkGenerator{token: "ml_test_123", portalToken: "ml_portal_123"}emailSender := &captureEmailSender{}h := NewPublicCloudSignupHandlers(&CPConfig{BaseURL: "https://cloud.example.com",@@ -244,11 +232,8 @@ func TestPublicCloudSignupHandlePublicMagicLinkRequestKnownTenantSendsEmail(t *tif rec.Code != http.StatusOK {t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())}- if magic.tenantCalls != 1 {- t.Fatalf("magic GenerateToken calls=%d, want 1", magic.tenantCalls)- }- if magic.portalCalls != 0 {- t.Fatalf("magic GeneratePortalToken calls=%d, want 0", magic.portalCalls)+ if magic.calls != 1 {+ t.Fatalf("magic GenerateToken calls=%d, want 1", magic.calls)}if magic.tenantID != "t-test-1" {t.Fatalf("magic tenantID=%q, want %q", magic.tenantID, "t-test-1")@@ -264,7 +249,7 @@ func TestPublicCloudSignupHandlePublicMagicLinkRequestKnownTenantSendsEmail(t *t}}-func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalTargetKnownTenantUsesPortalToken(t *testing.T) {+func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalKnownUserSendsEmail(t *testing.T) {dir := t.TempDir()reg, err := registry.NewTenantRegistry(dir)if err != nil {@@ -272,24 +257,21 @@ func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalTargetKnownTenantUse}t.Cleanup(func() { _ = reg.Close() })- if err := reg.Create(®istry.Tenant{- ID: "t-portal-1",- AccountID: "a-portal-1",- Email: "[email protected]",- DisplayName: "Pulse Labs",- State: registry.TenantStateActive,+ if err := reg.CreateUser(®istry.User{+ ID: "u_test_1",+ Email: "[email protected]",}); err != nil {- t.Fatalf("Create tenant: %v", err)+ t.Fatalf("CreateUser: %v", err)}- magic := &captureMagicLinkGenerator{token: "ml_portal_123"}+ magic := &captureMagicLinkGenerator{token: "ml_test_123", portalToken: "ml_portal_123"}emailSender := &captureEmailSender{}h := NewPublicCloudSignupHandlers(&CPConfig{BaseURL: "https://cloud.example.com",EmailFrom: "[email protected]",}, reg, magic, emailSender)- req := httptest.NewRequest(http.MethodPost, "/api/public/magic-link/request", strings.NewReader(`{"email":"[email protected]","target":"portal"}`))+ req := httptest.NewRequest(http.MethodPost, "/api/public/magic-link/request", strings.NewReader(`{"email":"[email protected]","target":"portal"}`))req.Header.Set("Content-Type", "application/json")rec := httptest.NewRecorder()@@ -298,35 +280,44 @@ func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalTargetKnownTenantUseif rec.Code != http.StatusOK {t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())}+ if magic.calls != 0 {+ t.Fatalf("tenant GenerateToken calls=%d, want 0", magic.calls)+ }if magic.portalCalls != 1 {- t.Fatalf("magic GeneratePortalToken calls=%d, want 1", magic.portalCalls)+ t.Fatalf("portal GeneratePortalToken calls=%d, want 1", magic.portalCalls)}- if magic.tenantCalls != 0 {- t.Fatalf("magic GenerateToken calls=%d, want 0", magic.tenantCalls)+ if magic.portalTenant != "" {+ t.Fatalf("portal tenantID=%q, want empty", magic.portalTenant)}if emailSender.calls != 1 {t.Fatalf("email sender calls=%d, want 1", emailSender.calls)}}-func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalTargetCommercialOnlyUsesPortalToken(t *testing.T) {- magic := &captureMagicLinkGenerator{token: "ml_portal_456"}- emailSender := &captureEmailSender{}- lookup := &captureCommercialIdentityLookup{- result: &CommercialIdentityLookupResult{- Email: "[email protected]",- HasCommercialIdentity: true,- Sources: []string{"v5_license"},- V5LicenseCount: 1,- },+func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalCommercialIdentitySendsEmail(t *testing.T) {+ dir := t.TempDir()+ reg, err := registry.NewTenantRegistry(dir)+ if err != nil {+ t.Fatalf("NewTenantRegistry: %v", err)}+ t.Cleanup(func() { _ = reg.Close() })++ magic := &captureMagicLinkGenerator{portalToken: "ml_portal_123"}+ emailSender := &captureEmailSender{}h := NewPublicCloudSignupHandlers(&CPConfig{BaseURL: "https://cloud.example.com",EmailFrom: "[email protected]",- }, nil, magic, emailSender)- h.commercialIdentities = lookup+ }, reg, magic, emailSender)+ h.commercialLookup = func(_ context.Context, email string) (*commercialIdentity, error) {+ return &commercialIdentity{+ Email: email,+ HasCommercialIdentity: true,+ Sources: []string{"v6_license"},+ V6LicenseCount: 1,+ }, nil+ }- req := httptest.NewRequest(http.MethodPost, "/api/public/magic-link/request", strings.NewReader(`{"email":"[email protected]","target":"portal"}`))+ req := httptest.NewRequest(http.MethodPost, "/api/public/magic-link/request", strings.NewReader(`{"email":"[email protected]","target":"portal"}`))req.Header.Set("Content-Type", "application/json")rec := httptest.NewRecorder()@@ -335,14 +326,11 @@ func TestPublicCloudSignupHandlePublicMagicLinkRequestPortalTargetCommercialOnlyif rec.Code != http.StatusOK {t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())}- if lookup.calls != 1 {- t.Fatalf("commercial lookup calls=%d, want 1", lookup.calls)- }if magic.portalCalls != 1 {- t.Fatalf("magic GeneratePortalToken calls=%d, want 1", magic.portalCalls)+ t.Fatalf("portal GeneratePortalToken calls=%d, want 1", magic.portalCalls)}- if magic.tenantCalls != 0 {- t.Fatalf("magic GenerateToken calls=%d, want 0", magic.tenantCalls)+ if magic.portalTenant != "" {+ t.Fatalf("portal tenantID=%q, want empty", magic.portalTenant)}if emailSender.calls != 1 {t.Fatalf("email sender calls=%d, want 1", emailSender.calls)diff --git a/internal/cloudcp/routes.go b/internal/cloudcp/routes.goindex fc6a632fd8..558df5c8bc 100644--- a/internal/cloudcp/routes.go+++ b/internal/cloudcp/routes.go@@ -112,7 +112,7 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {// Magic link verification (public, token-authenticated)baseDomain := baseDomainFromURL(deps.Config.BaseURL)- mux.Handle("/auth/magic-link/verify", magicLinkVerifyLimiter.Middleware(http.HandlerFunc(cpauth.HandleMagicLinkVerify(deps.MagicLinks, deps.Registry, deps.Config.TenantsDir(), baseDomain))))+ mux.Handle("/auth/magic-link/verify", magicLinkVerifyLimiter.Middleware(http.HandlerFunc(cpauth.HandleMagicLinkVerify(deps.MagicLinks, deps.Registry, deps.Config.TenantsDir(), baseDomain, portal.PortalPagePath))))if deps.MagicLinks != nil {mux.Handle(portal.PortalLogoutPath, sessionAuthLimiter.Middleware(sessionAuth(cpauth.HandleLogout(deps.Registry))))}@@ -120,13 +120,10 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {// Hosted Pulse Pro trial signup: public form + checkout + return completion.trialSignupHandlers := NewTrialSignupHandlers(deps.Config, deps.EmailSender, deps.TrialSignupStore, hostedEntitlements)hostedEntitlementHandlers := NewHostedEntitlementHandlers(hostedEntitlements)- trialSignupRejected := func(w http.ResponseWriter, r *http.Request, retryAfter int) {- trialSignupHandlers.HandleRateLimitedTrialSignup(w, r, retryAfter)- }mux.Handle("/start-pro-trial", trialSignupPageLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleStartProTrial)))- mux.Handle("/api/trial-signup/request-verification", trialSignupVerificationLimiter.MiddlewareWithRejected(http.HandlerFunc(trialSignupHandlers.HandleRequestVerification), trialSignupRejected))+ mux.Handle("/api/trial-signup/request-verification", trialSignupVerificationLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleRequestVerification)))mux.Handle("/trial-signup/verify", trialSignupVerifyLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleVerifyEmail)))- mux.Handle("/api/trial-signup/checkout", trialSignupCheckoutLimiter.MiddlewareWithRejected(http.HandlerFunc(trialSignupHandlers.HandleCheckout), trialSignupRejected))+ mux.Handle("/api/trial-signup/checkout", trialSignupCheckoutLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleCheckout)))mux.Handle("/trial-signup/complete", trialSignupCompleteLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleTrialSignupComplete)))mux.Handle("/api/trial-signup/redeem", trialSignupRedeemLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleTrialSignupRedeem)))mux.Handle("/api/entitlements/refresh", hostedEntitlementRefreshLimiter.Middleware(http.HandlerFunc(hostedEntitlementHandlers.HandleRefresh)))@@ -230,9 +227,6 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {mux.Handle(portal.PortalBootstrapPath, portalAPILimiter.Middleware(sessionAuth(portal.HandlePortalBootstrap(deps.MagicLinks, deps.Registry))))mux.Handle(portal.PortalDashboardPath, portalAPILimiter.Middleware(accountSessionAuth(accountIDFromPortalRequest, portal.HandlePortalDashboard(deps.Registry))))mux.Handle(portal.PortalWorkspacePath, portalAPILimiter.Middleware(accountSessionAuth(accountIDFromPortalRequest, portal.HandlePortalWorkspaceDetail(deps.Registry))))- mux.Handle(portal.PortalCommercialAPIPath, portalAPILimiter.Middleware(sessionAuth(portal.HandleCommercialProxy(portal.CommercialProxyConfig{- BaseURL: deps.Config.LicenseServerURL,- }))))// Stripe Customer Portal redirect (session + account-membership authenticated)billingCfg := portal.BillingPortalConfig{diff --git a/internal/cloudcp/routes_auth_test.go b/internal/cloudcp/routes_auth_test.goindex f755d387ee..1877e57ab9 100644--- a/internal/cloudcp/routes_auth_test.go+++ b/internal/cloudcp/routes_auth_test.go@@ -338,13 +338,6 @@ func TestRegisterRoutes_PortalBootstrapRequiresSession(t *testing.T) {if revokedRec.Code != http.StatusUnauthorized {t.Fatalf("revoked status = %d, want %d (body=%q)", revokedRec.Code, http.StatusUnauthorized, revokedRec.Body.String())}-- commercialReq := httptest.NewRequest(http.MethodPost, portal.PortalCommercialAPIBasePath+"/v1/retrieve-license/request", strings.NewReader(`{"email":"[email protected]"}`))- commercialRec := httptest.NewRecorder()- mux.ServeHTTP(commercialRec, commercialReq)- if commercialRec.Code != http.StatusUnauthorized {- t.Fatalf("portal commercial unauth status = %d, want %d (body=%q)", commercialRec.Code, http.StatusUnauthorized, commercialRec.Body.String())- }}func TestRegisterRoutes_PortalPageSessionModes(t *testing.T) {@@ -440,9 +433,9 @@ func TestRegisterRoutes_PortalPageSessionModes(t *testing.T) {`id="pulse-account-bootstrap"`,`id="portal-app-root"`,`"authenticated":true`,- "Hosted access is active on this account.",+ "Hosted operations",+ "Account services","Self-hosted licenses and billing",- "Hosted workspace administration stays above.",} {if !strings.Contains(authRec.Body.String(), needle) {t.Fatalf("expected authenticated portal page to contain %q, body=%q", needle, authRec.Body.String())