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
Centralize demo commercial boundary policy
rcourtman0c1fafa80093
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 3f41d36356..1cdd46dde4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -312,6 +312,11 @@ lifecycle-owned install or reporting flows. Browser-facing lifecycle surfacesmust also treat `/api/security/status.sessionCapabilities.demoMode` as thecanonical public-demo bootstrap signal instead of inferring demo posture fromheaders, `/api/health`, or hostname heuristics.+That same shared API boundary now owns the hidden-versus-redacted split as+well: lifecycle-adjacent flows may inherit redacted `/api/license/entitlements`+capability reads when demo-visible product behavior needs them, but they must+not rely on licensed identity, plan labels, upgrade reasons, or observed+usage counts surviving that public-demo contract.Lifecycle-adjacent storage and fleet surfaces now also depend on one governedphysical-disk history transport. When agent-backed disk telemetry is renderedthrough shared drawers or lifecycle-adjacent resource context, those readsdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex b3f7e754c5..49f04fea46 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -76,6 +76,7 @@ Own canonical runtime payload shapes between backend and frontend.52. `internal/api/config_setup_handlers.go`53. `internal/api/demo_mode_commercial.go`54. `internal/api/security_status_capabilities.go`+55. `internal/api/demo_middleware.go`## Shared Boundaries@@ -213,6 +214,16 @@ Own canonical runtime payload shapes between backend and frontend.browser bootstrap signal for public demo posture instead of askingfrontend callers to infer demo state from response headers, `/api/health`probes, or hostname heuristics.+33. Keep public demo commercial posture middleware-owned on that same shared+ API contract. `internal/api/demo_middleware.go`,+ `internal/api/demo_mode_commercial.go`,+ `internal/api/subscription_entitlements.go`, and+ `internal/api/contract_test.go` must classify commercial routes centrally+ as either hidden (`404`) or redacted, and `/api/license/entitlements`+ must preserve runtime capability fields while clearing licensed identity,+ upgrade prompts, trial nudges, usage counts, and plan metadata for public+ demo browsers instead of relying on scattered handler-local demo checks or+ frontend-only suppression.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 186545363f..93e6015d87 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -121,12 +121,14 @@ agreement, and cloud-specific enforcement rules.billing surface. `Learn more` links must land on the monitored-systemusage-focused billing state, while `Upgrade to add more` links must land onthe plan-focused billing state. The owned billing shell must express those- states explicitly through its section selector and rendered content, not- merely through nearby hash anchors that still present the same visible- destination. `frontend-modern/src/components/Settings/ProLicensePanel.tsx`+ states explicitly through canonical route-owned destinations+ (`/settings/system/billing/plan` and `/settings/system/billing/usage`) and+ their rendered content, not through nearby fragments that still present the+ same visible destination. `frontend-modern/src/components/Settings/ProLicensePanel.tsx`and `frontend-modern/src/components/Settings/useProLicensePanelState.ts`therefore own a canonical two-state billing focus model (`plan` vs- `usage`) that survives direct links and in-product CTA navigation.+ `usage`) that survives direct links, compatibility redirects, and+ in-product CTA navigation.## Forbidden Paths@@ -164,6 +166,18 @@ real licensing model. That includes settings billing tabs, public-demo bannerand monitored-system/trial nudges, dashboard relay paywalls, Patrol upgradeCTAs, and history-lock upsells. Demo readiness therefore means presentationisolation, not a license exemption.+That same public-demo boundary now also owns route-level commercial+classification. `internal/api/demo_middleware.go` and+`internal/api/demo_mode_commercial.go` must decide centrally which commercial+endpoints are fully hidden (`404`) and which remain available only as a+redacted public contract. `/api/license/entitlements` is the canonical+redacted exception: it may continue to carry capability and history-retention+fields needed for demo-visible product behavior, but it must not expose+licensed identity, plan labels, upgrade reasons, trial urgency, or observed+usage counts to public browsers. The governed browser proof for that posture+lives in `tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts`+and is expected to stay runnable through+`tests/integration/scripts/run-tests.sh demo-contract`.Legacy Cloud plan aliases are now expected to canonicalize to the `cloud_*`contract not only when Stripe metadata is parsed, but also when persisted planversions are consumed at hosted entitlement and workspace-limit enforcement@@ -562,6 +576,11 @@ and context, but `CommercialBillingSections.tsx` andcommercial information architecture. Future billing work must extend thatshared shell/model first instead of letting self-hosted Pulse Pro and hostedorganization billing drift back into parallel local layouts or vocabularies.+For self-hosted Pulse Pro specifically, the plan/usage split is now also a+router contract: `/settings/system/billing/plan` is the canonical plan state,+`/settings/system/billing/usage` is the canonical monitored-system usage state,+and `/settings/system/billing` remains a compatibility handoff rather than the+primary owned destination.That same ownership split is explicit in the governed registry as well:`CommercialBillingSections.tsx` is part of the shared commercial shell/modelsurface, while `SelfHostedCommercialActivationSection.tsx` stays on thediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 1fc3c0038a..220120194f 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -326,6 +326,11 @@ Browser-facing storage/recovery surfaces must also treat`/api/security/status.sessionCapabilities.demoMode` as the canonicalpublic-demo bootstrap signal instead of inferring demo posture from headers,`/api/health`, or hostname heuristics.+That same shared boundary now also owns the one redacted commercial exception:+storage and recovery may inherit demo-safe `/api/license/entitlements`+capability and history-retention reads, but they must not expect licensed+identity, upgrade prompts, trial urgency, or observed usage counts to remain+present once the public-demo contract is applied.Physical-disk live I/O drawers now also sit on the canonical storage surface.Storage disk drawers may show read, write, busy, and SMART history, but everychart must route through the shared `HistoryChart` API contract using the diskdiff --git a/internal/api/billing_state_handlers_test.go b/internal/api/billing_state_handlers_test.goindex ccebfe4c08..604daf4b1e 100644--- a/internal/api/billing_state_handlers_test.go+++ b/internal/api/billing_state_handlers_test.go@@ -359,7 +359,7 @@ func doBillingStateRequest(router *Router, method, path, body string) *httptest.}req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:Password!1")))rec := httptest.NewRecorder()- router.mux.ServeHTTP(rec, req)+ DemoModeMiddleware(router.config, router.mux).ServeHTTP(rec, req)return rec}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 4838e5021d..88e695389e 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -4811,41 +4811,83 @@ func TestContract_HostedBillingStateFallbackJSONSnapshot(t *testing.T) {assertJSONSnapshot(t, rec.Body.Bytes(), want)}-func TestContract_DemoModeCommercialReadSurfaceReturnsNotFound(t *testing.T) {- t.Run("license status", func(t *testing.T) {- handlers := NewLicenseHandlers(nil, false, &config.Config{DemoMode: true})- req := httptest.NewRequest(http.MethodGet, "/api/license/status", nil)- rec := httptest.NewRecorder()+func TestContract_DemoModeCommercialSurfacePolicy(t *testing.T) {+ t.Run("hidden routes return not found", func(t *testing.T) {+ next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatalf("hidden commercial route should not reach downstream handler: %s %s", r.Method, r.URL.Path)+ })+ handler := DemoModeMiddleware(&config.Config{DemoMode: true}, next)- handlers.HandleLicenseStatus(rec, req)+ testCases := []struct {+ method string+ path string+ }{+ {method: http.MethodGet, path: "/api/license/status"},+ {method: http.MethodGet, path: "/api/license/features"},+ {method: http.MethodPost, path: "/api/license/activate"},+ {method: http.MethodPost, path: "/api/license/clear"},+ {method: http.MethodPost, path: "/api/license/trial/start"},+ {method: http.MethodGet, path: "/api/license/monitored-system-ledger"},+ {method: http.MethodGet, path: "/api/admin/orgs/t-tenant/billing-state"},+ {method: http.MethodPut, path: "/api/admin/orgs/t-tenant/billing-state"},+ {method: http.MethodGet, path: "/api/upgrade-metrics/stats"},+ {method: http.MethodPost, path: "/api/upgrade-metrics/events"},+ {method: http.MethodGet, path: "/auth/trial-activate"},+ }- if rec.Code != http.StatusNotFound {- t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusNotFound, rec.Body.String())+ for _, tc := range testCases {+ req := httptest.NewRequest(tc.method, tc.path, nil)+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)+ if rec.Code != http.StatusNotFound {+ t.Fatalf("%s %s status=%d, want %d: %s", tc.method, tc.path, rec.Code, http.StatusNotFound, rec.Body.String())+ }}})- t.Run("monitored system ledger", func(t *testing.T) {- router := &Router{config: &config.Config{DemoMode: true}}- req := httptest.NewRequest(http.MethodGet, "/api/license/monitored-system-ledger", nil)- rec := httptest.NewRecorder()-- router.handleMonitoredSystemLedger(rec, req)+ t.Run("entitlements are redacted instead of hidden", func(t *testing.T) {+ t.Setenv("PULSE_LICENSE_DEV_MODE", "true")- if rec.Code != http.StatusNotFound {- t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusNotFound, rec.Body.String())+ handlers := createTestHandler(t)+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", pkglicensing.TierPro, 24*time.Hour)+ if err != nil {+ t.Fatalf("GenerateLicenseForTesting: %v", err)+ }+ if _, err := handlers.Service(context.Background()).Activate(licenseKey); err != nil {+ t.Fatalf("Activate() error = %v", err)}- })- t.Run("hosted billing state", func(t *testing.T) {- handlers := NewBillingStateHandlers(config.NewFileBillingStore(t.TempDir()), true, true)- req := httptest.NewRequest(http.MethodGet, "/api/admin/orgs/t-tenant/billing-state", nil)- req.SetPathValue("id", "t-tenant")+ req := httptest.NewRequest(http.MethodGet, "/api/license/entitlements", nil)+ req = withPublicDemoCommercialContext(req, publicDemoCommercialExposureRedacted)rec := httptest.NewRecorder()+ handlers.HandleEntitlements(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())+ }- handlers.HandleGetBillingState(rec, req)-- if rec.Code != http.StatusNotFound {- t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusNotFound, rec.Body.String())+ var payload EntitlementPayload+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode payload: %v", err)+ }+ if len(payload.Capabilities) == 0 {+ t.Fatalf("expected sanitized entitlements to preserve capabilities, got %+v", payload)+ }+ if payload.LicensedEmail != "" {+ t.Fatalf("licensed_email=%q, want empty", payload.LicensedEmail)+ }+ if payload.Tier != string(pkglicensing.TierFree) {+ t.Fatalf("tier=%q, want %q", payload.Tier, pkglicensing.TierFree)+ }+ if payload.SubscriptionState != string(pkglicensing.SubStateActive) {+ t.Fatalf("subscription_state=%q, want %q", payload.SubscriptionState, pkglicensing.SubStateActive)+ }+ if len(payload.UpgradeReasons) != 0 {+ t.Fatalf("upgrade_reasons=%v, want empty", payload.UpgradeReasons)+ }+ for _, limit := range payload.Limits {+ if limit.Limit != 0 || limit.Current != 0 || limit.State != "ok" {+ t.Fatalf("sanitized limit=%+v, want limit=0 current=0 state=ok", limit)+ }}})}diff --git a/internal/api/demo_middleware.go b/internal/api/demo_middleware.goindex 8b61c66a92..776fd2cb1d 100644--- a/internal/api/demo_middleware.go+++ b/internal/api/demo_middleware.go@@ -12,7 +12,7 @@ import (// DemoModeMiddleware blocks all modification requests in demo modefunc DemoModeMiddleware(cfg *config.Config, next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if !cfg.DemoMode {+ if cfg == nil || !cfg.DemoMode {next.ServeHTTP(w, r)return}@@ -20,6 +20,16 @@ func DemoModeMiddleware(cfg *config.Config, next http.Handler) http.Handler {// Add header so frontend knows we're in demo modew.Header().Set("X-Demo-Mode", "true")+ if exposure, ok := publicDemoCommercialPolicyForRequest(r); ok {+ switch exposure {+ case publicDemoCommercialExposureHidden:+ http.NotFound(w, r)+ return+ case publicDemoCommercialExposureRedacted:+ r = withPublicDemoCommercialContext(r, exposure)+ }+ }+// Allow GET and HEAD requests (read-only)if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions {next.ServeHTTP(w, r)diff --git a/internal/api/demo_middleware_test.go b/internal/api/demo_middleware_test.goindex a801e6a850..0344629420 100644--- a/internal/api/demo_middleware_test.go+++ b/internal/api/demo_middleware_test.go@@ -53,6 +53,11 @@ func TestDemoModeMiddleware(t *testing.T) {{"demo on oidc provider callback", true, http.MethodPost, "/api/oidc/acme/callback", "", true, http.StatusOK, true},{"demo on logout", true, http.MethodPost, "/api/logout", "", true, http.StatusOK, true},+ // Demo mode enabled - commercial surfaces are hidden or redacted centrally+ {"demo on hidden license status", true, http.MethodGet, "/api/license/status", "", false, http.StatusNotFound, true},+ {"demo on hidden license activate", true, http.MethodPost, "/api/license/activate", "", false, http.StatusNotFound, true},+ {"demo on hidden trial activation", true, http.MethodGet, "/auth/trial-activate", "", false, http.StatusNotFound, true},+// Demo mode enabled - modification requests blocked{"demo on POST", true, http.MethodPost, "/api/users", "", false, http.StatusForbidden, true},{"demo on PUT", true, http.MethodPut, "/api/users/1", "", false, http.StatusForbidden, true},@@ -108,6 +113,28 @@ func TestDemoModeMiddleware(t *testing.T) {}}+func TestDemoModeMiddleware_RedactsCommercialEntitlements(t *testing.T) {+ nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !isPublicDemoCommercialRedactedRequest(r) {+ t.Fatal("expected demo middleware to mark entitlements request as redacted")+ }+ w.WriteHeader(http.StatusNoContent)+ })++ middleware := DemoModeMiddleware(&config.Config{DemoMode: true}, nextHandler)++ req := httptest.NewRequest(http.MethodGet, "/api/license/entitlements", nil)+ rr := httptest.NewRecorder()+ middleware.ServeHTTP(rr, req)++ if rr.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d", rr.Code, http.StatusNoContent)+ }+ if rr.Header().Get("X-Demo-Mode") != "true" {+ t.Fatalf("X-Demo-Mode header = %q, want %q", rr.Header().Get("X-Demo-Mode"), "true")+ }+}+func TestDemoModeMiddleware_BlockedResponse(t *testing.T) {// Verify the error response format when a request is blockedcfg := &config.Config{diff --git a/internal/api/demo_mode_commercial.go b/internal/api/demo_mode_commercial.goindex b73c80c936..2229ed382e 100644--- a/internal/api/demo_mode_commercial.go+++ b/internal/api/demo_mode_commercial.go@@ -1,14 +1,244 @@package api-import "net/http"+import (+ "context"+ "net/http"+ "strings"-// hideCommercialReadSurfaceInDemo returns a generic 404 for demo-only public-// runtimes so billing and license detail endpoints are not surfaced to users.-func hideCommercialReadSurfaceInDemo(w http.ResponseWriter, r *http.Request, demoMode bool) bool {- if !demoMode {+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"+)++type publicDemoCommercialExposure string++const (+ publicDemoCommercialExposureHidden publicDemoCommercialExposure = "hidden"+ publicDemoCommercialExposureRedacted publicDemoCommercialExposure = "redacted"+)++type publicDemoCommercialContextKey struct{}++type publicDemoCommercialRoutePolicy struct {+ route string+ exposure publicDemoCommercialExposure+ matches func(*http.Request) bool+}++var publicDemoCommercialPolicies = []publicDemoCommercialRoutePolicy{+ {+ route: "/api/license/status",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialPath("/api/license/status"),+ },+ {+ route: "/api/license/features",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialPath("/api/license/features"),+ },+ {+ route: "/api/license/activate",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialPath("/api/license/activate"),+ },+ {+ route: "/api/license/clear",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialPath("/api/license/clear"),+ },+ {+ route: "GET /api/license/entitlements",+ exposure: publicDemoCommercialExposureRedacted,+ matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/license/entitlements"),+ },+ {+ route: "POST /api/license/trial/start",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodPost, "/api/license/trial/start"),+ },+ {+ route: "GET /api/license/monitored-system-ledger",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/license/monitored-system-ledger"),+ },+ {+ route: "POST /api/upgrade-metrics/events",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodPost, "/api/upgrade-metrics/events"),+ },+ {+ route: "GET /api/upgrade-metrics/stats",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/upgrade-metrics/stats"),+ },+ {+ route: "GET /api/upgrade-metrics/health",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/upgrade-metrics/health"),+ },+ {+ route: "GET /api/upgrade-metrics/config",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/upgrade-metrics/config"),+ },+ {+ route: "PUT /api/upgrade-metrics/config",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodPut, "/api/upgrade-metrics/config"),+ },+ {+ route: "GET /api/admin/upgrade-metrics-funnel",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/admin/upgrade-metrics-funnel"),+ },+ {+ route: "GET /api/admin/orgs/{id}/billing-state",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialOrgBillingStatePath(http.MethodGet),+ },+ {+ route: "PUT /api/admin/orgs/{id}/billing-state",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialOrgBillingStatePath(http.MethodPut),+ },+ {+ route: "/auth/trial-activate",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialPath("/auth/trial-activate"),+ },+}++func publicDemoCommercialPolicyForRequest(+ r *http.Request,+) (publicDemoCommercialExposure, bool) {+ for _, policy := range publicDemoCommercialPolicies {+ if policy.matches != nil && policy.matches(r) {+ return policy.exposure, true+ }+ }+ return "", false+}++func withPublicDemoCommercialContext(+ r *http.Request,+ exposure publicDemoCommercialExposure,+) *http.Request {+ if r == nil || exposure != publicDemoCommercialExposureRedacted {+ return r+ }++ ctx := context.WithValue(+ r.Context(),+ publicDemoCommercialContextKey{},+ exposure,+ )+ return r.WithContext(ctx)+}++func isPublicDemoCommercialRedactedRequest(r *http.Request) bool {+ if r == nil {return false}- http.NotFound(w, r)- return true+ exposure, _ := r.Context().Value(publicDemoCommercialContextKey{}).(publicDemoCommercialExposure)+ return exposure == publicDemoCommercialExposureRedacted+}++func publicDemoCommercialRouteInventory() []string {+ routes := make([]string, 0, len(publicDemoCommercialPolicies))+ for _, policy := range publicDemoCommercialPolicies {+ routes = append(routes, policy.route)+ }+ return routes+}++func sanitizeEntitlementPayloadForPublicDemo(payload EntitlementPayload) EntitlementPayload {+ sanitized := payload+ sanitized.Limits = sanitizeEntitlementLimitsForPublicDemo(payload.Limits)+ sanitized.SubscriptionState = string(pkglicensing.SubStateActive)+ sanitized.UpgradeReasons = []UpgradeReason{}+ sanitized.PlanVersion = ""+ sanitized.Tier = string(pkglicensing.TierFree)+ sanitized.TrialExpiresAt = nil+ sanitized.TrialDaysRemaining = nil+ sanitized.Valid = false+ sanitized.LicensedEmail = ""+ sanitized.ExpiresAt = nil+ sanitized.IsLifetime = false+ sanitized.DaysRemaining = 0+ sanitized.InGracePeriod = false+ sanitized.GracePeriodEnd = nil+ sanitized.TrialEligible = false+ sanitized.TrialEligibilityReason = ""+ sanitized.OverflowDaysRemaining = nil+ sanitized.LegacyConnections = legacyConnectionCountsModel{}+ sanitized.HasMigrationGap = false+ sanitized.CommercialMigration = nil+ if sanitized.Capabilities == nil {+ sanitized.Capabilities = []string{}+ }+ return sanitized+}++func sanitizeEntitlementLimitsForPublicDemo(limits []LimitStatus) []LimitStatus {+ if len(limits) == 0 {+ return []LimitStatus{}+ }++ sanitized := make([]LimitStatus, 0, len(limits))+ for _, limit := range limits {+ sanitized = append(sanitized, LimitStatus{+ Key: limit.Key,+ Limit: 0,+ Current: 0,+ State: "ok",+ })+ }+ return sanitized+}++func exactDemoCommercialPath(path string) func(*http.Request) bool {+ return func(r *http.Request) bool {+ if r == nil || r.URL == nil {+ return false+ }+ return normalizeDemoCommercialPath(r.URL.Path) == path+ }+}++func exactDemoCommercialMethodPath(method, path string) func(*http.Request) bool {+ return func(r *http.Request) bool {+ if r == nil || r.Method != method {+ return false+ }+ return exactDemoCommercialPath(path)(r)+ }+}++func exactDemoCommercialOrgBillingStatePath(method string) func(*http.Request) bool {+ return func(r *http.Request) bool {+ if r == nil || r.Method != method || r.URL == nil {+ return false+ }++ parts := strings.Split(strings.Trim(normalizeDemoCommercialPath(r.URL.Path), "/"), "/")+ if len(parts) != 5 {+ return false+ }++ return parts[0] == "api" &&+ parts[1] == "admin" &&+ parts[2] == "orgs" &&+ strings.TrimSpace(parts[3]) != "" &&+ parts[4] == "billing-state"+ }+}++func normalizeDemoCommercialPath(path string) string {+ path = strings.TrimSpace(path)+ if path == "" {+ return ""+ }+ if path == "/" {+ return path+ }+ return strings.TrimRight(path, "/")}diff --git a/internal/api/demo_mode_commercial_test.go b/internal/api/demo_mode_commercial_test.gonew file mode 100644index 0000000000..268c4d5b75--- /dev/null+++ b/internal/api/demo_mode_commercial_test.go@@ -0,0 +1,153 @@+package api++import (+ "strings"+ "testing"+)++func TestPublicDemoCommercialRouteInventoryCoverage(t *testing.T) {+ literalRoutes, _, _ := parseRouterRoutes(t)++ var actualCommercialRoutes []string+ for _, route := range literalRoutes {+ if routeBelongsToPublicDemoCommercialBoundary(route) {+ actualCommercialRoutes = append(actualCommercialRoutes, route)+ }+ }++ actualSet := sliceToSet(t, actualCommercialRoutes, "public demo commercial boundary routes")+ expectedSet := sliceToSet(t, publicDemoCommercialRouteInventory(), "public demo commercial route inventory")++ if missing := setDifference(actualSet, expectedSet); len(missing) > 0 {+ t.Fatalf(+ "commercial routes missing demo policy coverage: %s",+ strings.Join(sortedKeys(missing), ", "),+ )+ }+ if stale := setDifference(expectedSet, actualSet); len(stale) > 0 {+ t.Fatalf(+ "demo commercial route inventory contains routes outside the boundary family: %s",+ strings.Join(sortedKeys(stale), ", "),+ )+ }+}++func TestSanitizeEntitlementPayloadForPublicDemo(t *testing.T) {+ trialExpiresAt := int64(1_746_892_800)+ trialDaysRemaining := 7+ expiresAt := "2026-05-05T00:00:00Z"+ gracePeriodEnd := "2026-05-12T00:00:00Z"+ overflowDaysRemaining := 11++ sanitized := sanitizeEntitlementPayloadForPublicDemo(EntitlementPayload{+ Capabilities: []string{"relay", "ai_patrol"},+ Limits: []LimitStatus{+ {+ Key: maxMonitoredSystemsLicenseGateKey,+ Limit: 5,+ Current: 16,+ State: "enforced",+ },+ },+ SubscriptionState: string(subscriptionStateTrialValue),+ UpgradeReasons: []UpgradeReason{{Key: "relay", Reason: "Upgrade", ActionURL: "/pricing"}},+ PlanVersion: "pro_monthly",+ Tier: "pro",+ TrialExpiresAt: &trialExpiresAt,+ TrialDaysRemaining: &trialDaysRemaining,+ HostedMode: true,+ Valid: true,+ LicensedEmail: "[email protected]",+ ExpiresAt: &expiresAt,+ IsLifetime: true,+ DaysRemaining: 30,+ InGracePeriod: true,+ GracePeriodEnd: &gracePeriodEnd,+ TrialEligible: true,+ TrialEligibilityReason: "eligible",+ MaxHistoryDays: 90,+ OverflowDaysRemaining: &overflowDaysRemaining,+ LegacyConnections: legacyConnectionCountsModel{+ ProxmoxNodes: 1,+ DockerHosts: 2,+ KubernetesClusters: 3,+ },+ HasMigrationGap: true,+ CommercialMigration: &commercialMigrationStatusModel{+ State: "failed",+ },+ })++ if len(sanitized.Capabilities) != 2 {+ t.Fatalf("capabilities=%v, want original capabilities preserved", sanitized.Capabilities)+ }+ if len(sanitized.Limits) != 1 {+ t.Fatalf("limits=%v, want one sanitized limit", sanitized.Limits)+ }+ if sanitized.Limits[0].Limit != 0 || sanitized.Limits[0].Current != 0 || sanitized.Limits[0].State != "ok" {+ t.Fatalf("sanitized limit=%+v, want limit=0 current=0 state=ok", sanitized.Limits[0])+ }+ if sanitized.SubscriptionState != string(subscriptionStateActiveValue) {+ t.Fatalf("subscription_state=%q, want %q", sanitized.SubscriptionState, subscriptionStateActiveValue)+ }+ if len(sanitized.UpgradeReasons) != 0 {+ t.Fatalf("upgrade_reasons=%v, want empty", sanitized.UpgradeReasons)+ }+ if sanitized.PlanVersion != "" || sanitized.Tier != "free" {+ t.Fatalf("plan/tier=(%q,%q), want empty/free", sanitized.PlanVersion, sanitized.Tier)+ }+ if sanitized.TrialExpiresAt != nil || sanitized.TrialDaysRemaining != nil {+ t.Fatalf("trial fields should be cleared, got expires=%v days=%v", sanitized.TrialExpiresAt, sanitized.TrialDaysRemaining)+ }+ if sanitized.Valid {+ t.Fatal("valid should be false in sanitized public demo entitlements")+ }+ if sanitized.LicensedEmail != "" || sanitized.ExpiresAt != nil || sanitized.GracePeriodEnd != nil {+ t.Fatalf("commercial identity should be cleared, got email=%q expires=%v grace_end=%v", sanitized.LicensedEmail, sanitized.ExpiresAt, sanitized.GracePeriodEnd)+ }+ if sanitized.IsLifetime || sanitized.DaysRemaining != 0 || sanitized.InGracePeriod {+ t.Fatalf("lifecycle display should be cleared, got %+v", sanitized)+ }+ if sanitized.TrialEligible || sanitized.TrialEligibilityReason != "" {+ t.Fatalf("trial prompt should be cleared, got eligible=%v reason=%q", sanitized.TrialEligible, sanitized.TrialEligibilityReason)+ }+ if sanitized.MaxHistoryDays != 90 || !sanitized.HostedMode {+ t.Fatalf("non-commercial runtime capability fields should be preserved, got max_history_days=%d hosted_mode=%v", sanitized.MaxHistoryDays, sanitized.HostedMode)+ }+ if sanitized.OverflowDaysRemaining != nil {+ t.Fatalf("overflow days should be cleared, got %v", sanitized.OverflowDaysRemaining)+ }+ if sanitized.LegacyConnections.Total() != 0 {+ t.Fatalf("legacy connections should be cleared, got %+v", sanitized.LegacyConnections)+ }+ if sanitized.HasMigrationGap || sanitized.CommercialMigration != nil {+ t.Fatalf("migration state should be cleared, got has_gap=%v migration=%+v", sanitized.HasMigrationGap, sanitized.CommercialMigration)+ }+}++func routeBelongsToPublicDemoCommercialBoundary(route string) bool {+ switch {+ case route == "/auth/trial-activate":+ return true+ case strings.HasPrefix(route, "/api/license/"):+ return true+ case strings.HasPrefix(route, "GET /api/license/"):+ return true+ case strings.HasPrefix(route, "POST /api/license/"):+ return true+ case strings.HasPrefix(route, "GET /api/upgrade-metrics/"):+ return true+ case strings.HasPrefix(route, "POST /api/upgrade-metrics/"):+ return true+ case strings.HasPrefix(route, "PUT /api/upgrade-metrics/"):+ return true+ case route == "GET /api/admin/upgrade-metrics-funnel":+ return true+ case route == "GET /api/admin/orgs/{id}/billing-state":+ return true+ case route == "PUT /api/admin/orgs/{id}/billing-state":+ return true+ default:+ return false+ }+}diff --git a/internal/api/license_handlers_test.go b/internal/api/license_handlers_test.goindex b3d3f56463..b0ecb3f281 100644--- a/internal/api/license_handlers_test.go+++ b/internal/api/license_handlers_test.go@@ -187,20 +187,6 @@ func TestHandleLicenseStatus_NoLicense(t *testing.T) {}}-func TestHandleLicenseStatus_DemoModeReturnsNotFound(t *testing.T) {- handler := createTestHandler(t)- handler.SetConfig(&config.Config{DemoMode: true})-- req := httptest.NewRequest(http.MethodGet, "/api/license/status", nil)- rec := httptest.NewRecorder()-- handler.HandleLicenseStatus(rec, req)-- if rec.Code != http.StatusNotFound {- t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)- }-}-func TestHandleLicenseStatus_WithActiveLicense(t *testing.T) {t.Setenv("PULSE_LICENSE_DEV_MODE", "true")diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.goindex afb7e98bc9..919e743081 100644--- a/internal/api/licensing_handlers.go+++ b/internal/api/licensing_handlers.go@@ -918,9 +918,6 @@ func (h *LicenseHandlers) HandleLicenseStatus(w http.ResponseWriter, r *http.Reqhttp.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- if hideCommercialReadSurfaceInDemo(w, r, h != nil && h.cfg != nil && h.cfg.DemoMode) {- return- }service, _, err := h.getTenantComponents(r.Context())if err != nil {diff --git a/internal/api/monitored_system_ledger.go b/internal/api/monitored_system_ledger.goindex 7be6a84c91..bf491512a5 100644--- a/internal/api/monitored_system_ledger.go+++ b/internal/api/monitored_system_ledger.go@@ -103,10 +103,6 @@ func (e MonitoredSystemLedgerEntry) NormalizeCollections() MonitoredSystemLedger}func (r *Router) handleMonitoredSystemLedger(w http.ResponseWriter, req *http.Request) {- if hideCommercialReadSurfaceInDemo(w, req, r != nil && r.config != nil && r.config.DemoMode) {- return- }-orgID := GetOrgID(req.Context())// Get canonical monitored systems from the unified ReadState surface.diff --git a/internal/api/monitored_system_ledger_test.go b/internal/api/monitored_system_ledger_test.goindex a3ed640522..9006b69743 100644--- a/internal/api/monitored_system_ledger_test.go+++ b/internal/api/monitored_system_ledger_test.go@@ -7,7 +7,6 @@ import ("testing""time"- "github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -327,15 +326,3 @@ func TestHandleMonitoredSystemLedgerHTTP(t *testing.T) {t.Errorf("expected explanation summary, got %+v", decoded.Systems[0].Explanation)}}--func TestHandleMonitoredSystemLedger_DemoModeReturnsNotFound(t *testing.T) {- router := &Router{config: &config.Config{DemoMode: true}}- req := httptest.NewRequest(http.MethodGet, "/api/license/monitored-system-ledger", nil)- rec := httptest.NewRecorder()-- router.handleMonitoredSystemLedger(rec, req)-- if rec.Code != http.StatusNotFound {- t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)- }-}diff --git a/internal/api/router_routes_cloud.go b/internal/api/router_routes_cloud.goindex e40c71f2e0..6152ef531d 100644--- a/internal/api/router_routes_cloud.go+++ b/internal/api/router_routes_cloud.go@@ -22,7 +22,6 @@ func (r *Router) registerHostedRoutes(hostedSignupHandlers *HostedSignupHandlersbillingHandlers := NewBillingStateHandlers(config.NewFileBillingStore(routerConfig.DataPath),r.hostedMode,- routerConfig.DemoMode,)lifecycleHandlers := NewOrgLifecycleHandlers(r.multiTenant, r.hostedMode)hostedOrgAdminHandlers := NewHostedOrgAdminHandlers(r.multiTenant, r.hostedMode)diff --git a/internal/api/subscription_entitlements.go b/internal/api/subscription_entitlements.goindex 96b4eca37b..a878b463ba 100644--- a/internal/api/subscription_entitlements.go+++ b/internal/api/subscription_entitlements.go@@ -64,6 +64,9 @@ func (h *LicenseHandlers) HandleEntitlements(w http.ResponseWriter, r *http.Requ}payload.TrialEligible, payload.TrialEligibilityReason = h.trialStartEligibility(r.Context(), svc, existing)payload.HostedMode = h != nil && h.hostedMode+ if isPublicDemoCommercialRedactedRequest(r) {+ payload = sanitizeEntitlementPayloadForPublicDemo(payload)+ }w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(payload)diff --git a/internal/api/subscription_state_handlers.go b/internal/api/subscription_state_handlers.goindex 459f4737ef..2c5d8cfc1f 100644--- a/internal/api/subscription_state_handlers.go+++ b/internal/api/subscription_state_handlers.go@@ -11,19 +11,12 @@ import (type BillingStateHandlers struct {store *config.FileBillingStore- demoMode boolhostedMode bool}-func NewBillingStateHandlers(store *config.FileBillingStore, hostedMode bool, demoModes ...bool) *BillingStateHandlers {- demoMode := false- if len(demoModes) > 0 {- demoMode = demoModes[0]- }-+func NewBillingStateHandlers(store *config.FileBillingStore, hostedMode bool) *BillingStateHandlers {return &BillingStateHandlers{store: store,- demoMode: demoMode,hostedMode: hostedMode,}}@@ -37,9 +30,6 @@ func (h *BillingStateHandlers) HandleGetBillingState(w http.ResponseWriter, r *hhttp.NotFound(w, r)return}- if hideCommercialReadSurfaceInDemo(w, r, h.demoMode) {- return- }if h.store == nil {writeErrorResponse(w, http.StatusServiceUnavailable, "billing_store_unavailable", "Billing persistence is not configured", nil)return@@ -93,9 +83,6 @@ func (h *BillingStateHandlers) HandlePutBillingState(w http.ResponseWriter, r *hhttp.NotFound(w, r)return}- if hideCommercialReadSurfaceInDemo(w, r, h.demoMode) {- return- }if h.store == nil {writeErrorResponse(w, http.StatusServiceUnavailable, "billing_store_unavailable", "Billing persistence is not configured", nil)returndiff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex 424be7b15f..a41be7910b 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -3709,8 +3709,8 @@ class SubsystemLookupTest(unittest.TestCase):{"heading": "## Shared Boundaries","path": "internal/api/access_control_handlers.go",- "line": 112,- "heading_line": 80,+ "line": 113,+ "heading_line": 81,}],)diff --git a/tests/integration/scripts/run-tests.sh b/tests/integration/scripts/run-tests.shindex 7a7b06f10a..ab12c25ef5 100755--- a/tests/integration/scripts/run-tests.sh+++ b/tests/integration/scripts/run-tests.sh@@ -2,7 +2,7 @@## Run Pulse integration tests with different suites# Usage: ./run-tests.sh [suite]-# suite: all, core, diagnostic, perf, visual, multi-tenant, trial, cloud-hosting, cloud-lifecycle, evals, updates-api+# suite: all, core, diagnostic, perf, visual, multi-tenant, trial, cloud-hosting, cloud-lifecycle, demo-contract, evals, updates-api#set -e@@ -143,6 +143,9 @@ run_suite() {cloud-lifecycle)npx playwright test "tests/09-cloud-billing-lifecycle.spec.ts" --project=chromium --reporter=list;;+ demo-contract)+ npx playwright test "tests/53-demo-mode-commercial-boundary.spec.ts" --project=chromium --project=mobile-chrome --reporter=list+ ;;evals)node ./scripts/run-evals.mjs --mode deterministic;;@@ -188,6 +191,7 @@ case "$SUITE" inrun_suite "Trial Signup E2E" "trial" || FAILED_TESTS+=("Trial Signup E2E")run_suite "Cloud Hosting E2E" "cloud-hosting" || FAILED_TESTS+=("Cloud Hosting E2E")run_suite "Cloud Billing Lifecycle E2E" "cloud-lifecycle" || FAILED_TESTS+=("Cloud Billing Lifecycle E2E")+ run_suite "Public Demo Contract" "demo-contract" || FAILED_TESTS+=("Public Demo Contract")run_suite "Navigation Performance" "perf" || FAILED_TESTS+=("Navigation Performance")run_suite "Theme Visual Regression" "visual" || FAILED_TESTS+=("Theme Visual Regression")run_suite "Update API Integration" "updates-api" || FAILED_TESTS+=("Update API Integration")@@ -225,6 +229,10 @@ case "$SUITE" inrun_suite "Cloud Billing Lifecycle E2E" "cloud-lifecycle" || FAILED_TESTS+=("Cloud Billing Lifecycle E2E");;+ demo-contract)+ run_suite "Public Demo Contract" "demo-contract" || FAILED_TESTS+=("Public Demo Contract")+ ;;+evals)run_suite "Agentic Eval Pack (Deterministic)" "evals" || FAILED_TESTS+=("Agentic Eval Pack (Deterministic)");;@@ -235,7 +243,7 @@ case "$SUITE" in*)echo "Unknown suite: $SUITE"- echo "Available suites: all, diagnostic, core, perf, visual, multi-tenant, trial, cloud-hosting, cloud-lifecycle, evals, updates-api"+ echo "Available suites: all, diagnostic, core, perf, visual, multi-tenant, trial, cloud-hosting, cloud-lifecycle, demo-contract, evals, updates-api"exit 1;;esacdiff --git a/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts b/tests/integration/tests/53-demo-mode-commercial-boundary.spec.tsindex c564ed5713..4be63a0791 100644--- a/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts+++ b/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts@@ -19,33 +19,23 @@ const SECURITY_STATUS_DEMO_PAYLOAD = {},};-const DEMO_COMMERCIAL_ENTITLEMENTS = {+const DEMO_PUBLIC_ENTITLEMENTS = {capabilities: ['ai_patrol', 'relay'],limits: [{key: 'max_monitored_systems',- limit: 5,- current: 16,- state: 'enforced',+ limit: 0,+ current: 0,+ state: 'ok',},],- subscription_state: 'trial',- upgrade_reasons: [- {- key: 'max_monitored_systems',- reason: 'Upgrade to monitor more systems.',- action_url: '/settings/system/billing#plan',- },- {- key: 'trial_banner',- reason: 'Upgrade to keep Pro features active.',- action_url: '/settings/system/billing#plan',- },- ],- tier: 'pro',+ subscription_state: 'active',+ upgrade_reasons: [],+ tier: 'free',hosted_mode: false,- trial_days_remaining: 7,+ valid: false,trial_eligible: false,+ max_history_days: 90,legacy_connections: {proxmox_nodes: 0,docker_hosts: 0,@@ -144,7 +134,7 @@ base.describe('Demo mode commercial boundary', () => {await route.fulfill({status: 200,contentType: 'application/json',- body: JSON.stringify(DEMO_COMMERCIAL_ENTITLEMENTS),+ body: JSON.stringify(DEMO_PUBLIC_ENTITLEMENTS),});});@@ -218,4 +208,111 @@ base.describe('Demo mode commercial boundary', () => {await page.screenshot({ path: screenshotPath, fullPage: true });},);++ authenticatedTest(+ 'exposes only the redacted commercial contract in the browser',+ async ({ page }) => {+ await page.route('**/api/security/status', async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(SECURITY_STATUS_DEMO_PAYLOAD),+ });+ });++ await page.route('**/api/license/entitlements', async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(DEMO_PUBLIC_ENTITLEMENTS),+ });+ });++ const hiddenNotFound = async (route: string) => {+ await page.route(route, async (innerRoute) => {+ await innerRoute.fulfill({+ status: 404,+ contentType: 'application/json',+ body: JSON.stringify({ error: 'not found' }),+ });+ });+ };++ await hiddenNotFound('**/api/license/status');+ await hiddenNotFound('**/api/license/features');+ await hiddenNotFound('**/api/license/activate');+ await hiddenNotFound('**/api/license/clear');+ await hiddenNotFound('**/api/license/trial/start');+ await hiddenNotFound('**/api/license/monitored-system-ledger');+ await hiddenNotFound('**/api/admin/orgs/**/billing-state');+ await hiddenNotFound('**/api/upgrade-metrics/**');+ await hiddenNotFound('**/auth/trial-activate');++ await page.goto('/settings/infrastructure/install', { waitUntil: 'domcontentloaded' });++ const responses = await page.evaluate(async () => {+ const probe = async (input: string, init?: RequestInit) => {+ const res = await fetch(input, {+ credentials: 'include',+ ...init,+ });+ let body: unknown = null;+ try {+ body = await res.json();+ } catch {+ body = null;+ }+ return { status: res.status, body };+ };++ return {+ entitlements: await probe('/api/license/entitlements'),+ status: await probe('/api/license/status'),+ features: await probe('/api/license/features'),+ activate: await probe('/api/license/activate', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ license_key: 'demo' }),+ }),+ clear: await probe('/api/license/clear', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({}),+ }),+ trialStart: await probe('/api/license/trial/start', { method: 'POST' }),+ ledger: await probe('/api/license/monitored-system-ledger'),+ billingState: await probe('/api/admin/orgs/default/billing-state'),+ upgradeMetrics: await probe('/api/upgrade-metrics/stats'),+ trialActivate: await probe('/auth/trial-activate'),+ };+ });++ expect(responses.entitlements.status).toBe(200);+ expect(responses.entitlements.body).toMatchObject({+ capabilities: ['ai_patrol', 'relay'],+ subscription_state: 'active',+ upgrade_reasons: [],+ tier: 'free',+ valid: false,+ trial_eligible: false,+ max_history_days: 90,+ });+ expect(responses.entitlements.body).not.toHaveProperty('licensed_email');+ expect(responses.entitlements.body).not.toHaveProperty('trial_days_remaining');+ expect(responses.entitlements.body).not.toHaveProperty('trial_expires_at');+ expect((responses.entitlements.body as { limits?: Array<{ key: string; current: number; limit: number; state: string }> }).limits).toEqual([+ { key: 'max_monitored_systems', limit: 0, current: 0, state: 'ok' },+ ]);++ expect(responses.status.status).toBe(404);+ expect(responses.features.status).toBe(404);+ expect(responses.activate.status).toBe(404);+ expect(responses.clear.status).toBe(404);+ expect(responses.trialStart.status).toBe(404);+ expect(responses.ledger.status).toBe(404);+ expect(responses.billingState.status).toBe(404);+ expect(responses.upgradeMetrics.status).toBe(404);+ expect(responses.trialActivate.status).toBe(404);+ },+ );});