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
Use opaque Pulse Account handoffs for self-hosted upgrades
rcourtman1649faa75d51
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex c8e5134808..5e76ed7b04 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -5074,22 +5074,23 @@ func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {handler := createTestHandler(t)handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})var capturedReq struct {- Feature string `json:"feature"`- SuccessURL string `json:"success_url"`- CancelURL string `json:"cancel_url"`+ Feature string `json:"feature"`+ SuccessURL string `json:"success_url"`+ CancelURL string `json:"cancel_url"`+ PurchaseReturnJTI string `json:"purchase_return_jti"`}server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/v1/checkout/intent" {+ if r.URL.Path != "/v1/checkout/portal-handoff" {t.Fatalf("unexpected path %q", r.URL.Path)}if err := json.NewDecoder(r.Body).Decode(&capturedReq); err != nil {- t.Fatalf("decode checkout intent request: %v", err)+ t.Fatalf("decode checkout portal handoff request: %v", err)}w.Header().Set("Content-Type", "application/json")_ = json.NewEncoder(w).Encode(map[string]any{- "checkout_intent_id": "cki_placeholder",- "feature": capturedReq.Feature,+ "portal_handoff_id": "cph_placeholder",+ "feature": capturedReq.Feature,})}))defer server.Close()@@ -5129,8 +5130,8 @@ func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {if got := redirectURL.Query().Get("purchase_handoff_url"); got != "" {t.Fatalf("purchase_handoff_url=%q, want omitted portal query", got)}- if got := redirectURL.Query().Get("checkout_intent_id"); got != "cki_placeholder" {- t.Fatalf("checkout_intent_id=%q, want cki_placeholder", got)+ if got := redirectURL.Query().Get("portal_handoff_id"); got != "cph_placeholder" {+ t.Fatalf("portal_handoff_id=%q, want cph_placeholder", got)}activationURL, err := url.Parse(capturedReq.SuccessURL)@@ -5155,22 +5156,25 @@ func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {if claims.OrgID != "default" {t.Fatalf("claims.OrgID=%q, want default", claims.OrgID)}+ if capturedReq.PurchaseReturnJTI != claims.ID {+ t.Fatalf("purchase_return_jti=%q, want %q", capturedReq.PurchaseReturnJTI, claims.ID)+ }activationQuery := activationURL.Query()activationQuery.Set(licensePurchaseReturnTokenField, "placeholder")activationURL.RawQuery = activationQuery.Encode()got, err := json.Marshal(struct {- PortalService string `json:"portal_service"`PortalUtmContent string `json:"portal_utm_content"`- CheckoutIntentID string `json:"checkout_intent_id"`+ PortalHandoffID string `json:"portal_handoff_id"`IntentFeature string `json:"intent_feature"`+ PurchaseReturnJTI string `json:"purchase_return_jti"`SuccessURLTemplate string `json:"success_url_template"`CancelURL string `json:"cancel_url"`}{- PortalService: redirectURL.Query().Get("service"),PortalUtmContent: redirectURL.Query().Get("utm_content"),- CheckoutIntentID: redirectURL.Query().Get("checkout_intent_id"),+ PortalHandoffID: redirectURL.Query().Get("portal_handoff_id"),IntentFeature: capturedReq.Feature,+ PurchaseReturnJTI: "placeholder",SuccessURLTemplate: activationURL.String(),CancelURL: capturedReq.CancelURL,})@@ -5179,10 +5183,10 @@ func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {}const want = `{- "portal_service":"upgrade","portal_utm_content":"legacy-bookmark",- "checkout_intent_id":"cki_placeholder",+ "portal_handoff_id":"cph_placeholder","intent_feature":"max_monitored_systems",+ "purchase_return_jti":"placeholder","success_url_template":"https://pulse.example.com/auth/license-purchase-activate?purchase_return_token=placeholder\u0026session_id=%7BCHECKOUT_SESSION_ID%7D","cancel_url":"https://pulse.example.com/settings/system/billing/plan?intent=max_monitored_systems\u0026purchase=cancelled"}`diff --git a/internal/api/license_handlers_test.go b/internal/api/license_handlers_test.goindex 7fd109b974..b6bfdf0a8c 100644--- a/internal/api/license_handlers_test.go+++ b/internal/api/license_handlers_test.go@@ -697,13 +697,14 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *teshandler := createTestHandler(t)handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})var capturedReq struct {- Feature string `json:"feature"`- SuccessURL string `json:"success_url"`- CancelURL string `json:"cancel_url"`+ Feature string `json:"feature"`+ SuccessURL string `json:"success_url"`+ CancelURL string `json:"cancel_url"`+ PurchaseReturnJTI string `json:"purchase_return_jti"`}server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/v1/checkout/intent" {+ if r.URL.Path != "/v1/checkout/portal-handoff" {t.Fatalf("unexpected path %q", r.URL.Path)}if r.Method != http.MethodPost {@@ -714,8 +715,8 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *tes}w.Header().Set("Content-Type", "application/json")_ = json.NewEncoder(w).Encode(map[string]any{- "checkout_intent_id": "cki_test_upgrade",- "feature": capturedReq.Feature,+ "portal_handoff_id": "cph_test_upgrade",+ "feature": capturedReq.Feature,})}))defer server.Close()@@ -747,14 +748,14 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *tesif got := redirectURL.Query().Get("feature"); got != "" {t.Fatalf("feature = %q, want omitted portal query", got)}- if got := redirectURL.Query().Get("service"); got != "upgrade" {- t.Fatalf("service = %q, want upgrade", got)+ if got := redirectURL.Query().Get("service"); got != "" {+ t.Fatalf("service = %q, want omitted portal query", got)}if got := redirectURL.Query().Get("return_url"); got != "" {t.Fatalf("return_url = %q, want omitted portal query", got)}- if got := redirectURL.Query().Get("checkout_intent_id"); got != "cki_test_upgrade" {- t.Fatalf("checkout_intent_id = %q, want cki_test_upgrade", got)+ if got := redirectURL.Query().Get("portal_handoff_id"); got != "cph_test_upgrade" {+ t.Fatalf("portal_handoff_id = %q, want cph_test_upgrade", got)}if got := redirectURL.Query().Get("purchase_handoff_url"); got != "" {t.Fatalf("purchase_handoff_url = %q, want omitted portal query", got)@@ -795,6 +796,9 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *tesif claims.Feature != "relay" {t.Fatalf("claims.Feature = %q, want relay", claims.Feature)}+ if capturedReq.PurchaseReturnJTI != claims.ID {+ t.Fatalf("purchase_return_jti = %q, want %q", capturedReq.PurchaseReturnJTI, claims.ID)+ }if capturedReq.CancelURL != "https://pulse.example.com/settings/system/billing/plan?purchase=cancelled" {t.Fatalf("cancel_url = %q", capturedReq.CancelURL)}@@ -1076,6 +1080,40 @@ func TestHandleCheckoutActivation_RendersFailurePageWhenCheckoutIsNotFulfilled(t}}+func TestHandleCheckoutActivation_RejectsPurchaseReturnBindingMismatch(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/v1/checkout/session" {+ t.Fatalf("unexpected path %q", r.URL.Path)+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"status":"fulfilled","purchase_return_jti":"wrong_purchase_return_jti","activation_key":"ppk_live_should_not_activate"}`))+ }))+ defer server.Close()+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)++ handler := createTestHandler(t)+ returnToken := issuePurchaseReturnToken(t, handler, "default", "max_monitored_systems")+ req := httptest.NewRequest(+ http.MethodPost,+ "https://pulse.example.com"+licensePurchaseActivationPath,+ strings.NewReader("session_id=cs_success&purchase_return_token="+url.QueryEscape(returnToken)),+ )+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ rec := httptest.NewRecorder()++ handler.HandleCheckoutActivation(rec, req)++ if rec.Code != http.StatusConflict {+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusConflict, rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), "did not match the completed upgrade flow") {+ t.Fatalf("body = %q, want binding mismatch message", rec.Body.String())+ }+ if handler.Service(context.Background()).IsActivated() {+ t.Fatal("expected mismatched checkout return to leave the local license inactive")+ }+}+// ========================================// userFriendlyActivationError tests// ========================================diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.goindex 4f0172badc..7990823bbc 100644--- a/internal/api/licensing_bridge.go+++ b/internal/api/licensing_bridge.go@@ -60,6 +60,8 @@ type entitlementLeaseClaimsModel = pkglicensing.EntitlementLeaseClaimstype licenseTier = pkglicensing.Tiertype checkoutIntentRequestModel = pkglicensing.CheckoutIntentRequesttype checkoutIntentResponseModel = pkglicensing.CheckoutIntentResponse+type checkoutPortalHandoffRequestModel = pkglicensing.CheckoutPortalHandoffRequest+type checkoutPortalHandoffResponseModel = pkglicensing.CheckoutPortalHandoffResponseconst (featureMultiTenantKey = pkglicensing.FeatureMultiTenantdiff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.goindex d4d453f6fc..70fbc2d0e3 100644--- a/internal/api/licensing_handlers.go+++ b/internal/api/licensing_handlers.go@@ -32,8 +32,8 @@ const (licensePurchaseSessionIDField = "session_id"licensePurchaseReturnTokenField = "purchase_return_token"pulseAccountUpgradeService = "upgrade"- pulseAccountPortalCheckoutIntentField = "checkout_intent_id"pulseAccountPortalFeatureQueryParam = "feature"+ pulseAccountPortalHandoffIDField = "portal_handoff_id"pulseAccountPortalHandoffURLQueryParam = "purchase_handoff_url"pulseAccountPortalServiceQueryParam = "service"pulseAccountPortalReturnTokenQueryParam = "purchase_return_token"@@ -291,7 +291,7 @@ func (h *LicenseHandlers) purchaseCheckoutHandoffStore() *purchaseCheckoutHandofreturn h.purchaseHandoffs}-func pulseAccountUpgradeURLForRequest(checkoutIntentID string, query url.Values) (string, error) {+func pulseAccountUpgradeURLForRequest(portalHandoffID string, query url.Values) (string, error) {portalURL := strings.TrimSpace(pulseAccountPortalURLFromLicensing(""))if portalURL == "" {return "", fmt.Errorf("pulse account portal url is unavailable")@@ -306,7 +306,7 @@ func pulseAccountUpgradeURLForRequest(checkoutIntentID string, query url.Values)for key, values := range query {switch key {case pulseAccountPortalFeatureQueryParam,- pulseAccountPortalCheckoutIntentField,+ pulseAccountPortalHandoffIDField,pulseAccountPortalHandoffURLQueryParam,pulseAccountPortalServiceQueryParam,pulseAccountPortalReturnTokenQueryParam,@@ -324,8 +324,7 @@ func pulseAccountUpgradeURLForRequest(checkoutIntentID string, query url.Values)}}- params.Set(pulseAccountPortalServiceQueryParam, pulseAccountUpgradeService)- params.Set(pulseAccountPortalCheckoutIntentField, strings.TrimSpace(checkoutIntentID))+ params.Set(pulseAccountPortalHandoffIDField, strings.TrimSpace(portalHandoffID))parsed.RawQuery = params.Encode()return parsed.String(), nil}@@ -1505,24 +1504,35 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Reqreturn}- checkoutIntent, err := lsClient.CreateCheckoutIntent(r.Context(), checkoutIntentRequestModel{- Feature: feature,- SuccessURL: activationURLTemplate,- CancelURL: cancelURL,+ purchaseReturnJTI := ""+ if claims, verifyErr := h.verifiedPurchaseReturnClaims(r, returnToken); verifyErr == nil && claims != nil {+ purchaseReturnJTI = strings.TrimSpace(claims.ID)+ }+ if purchaseReturnJTI == "" {+ log.Error().Str("feature", feature).Msg("Pulse Account purchase return token omitted jti")+ http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)+ return+ }++ portalHandoff, err := lsClient.CreateCheckoutPortalHandoff(r.Context(), checkoutPortalHandoffRequestModel{+ Feature: feature,+ SuccessURL: activationURLTemplate,+ CancelURL: cancelURL,+ PurchaseReturnJTI: purchaseReturnJTI,})if err != nil {- log.Error().Err(err).Str("feature", feature).Msg("Failed to create Pulse Account checkout intent")+ log.Error().Err(err).Str("feature", feature).Msg("Failed to create Pulse Account checkout portal handoff")http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)return}- checkoutIntentID := strings.TrimSpace(checkoutIntent.CheckoutIntentID)- if checkoutIntentID == "" {- log.Error().Str("feature", feature).Msg("Pulse Account checkout intent response omitted id")+ portalHandoffID := strings.TrimSpace(portalHandoff.PortalHandoffID)+ if portalHandoffID == "" {+ log.Error().Str("feature", feature).Msg("Pulse Account checkout portal handoff response omitted id")http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)return}- destination, err := pulseAccountUpgradeURLForRequest(checkoutIntentID, r.URL.Query())+ destination, err := pulseAccountUpgradeURLForRequest(portalHandoffID, r.URL.Query())if err != nil {log.Error().Err(err).Str("feature", feature).Msg("Failed to build Pulse Account upgrade destination")http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)@@ -1730,6 +1740,24 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httwriteLicensePurchaseActivationFailurePage(w, http.StatusConflict, feature, selfHostedBillingPurchaseFailed, message)return}+ expectedPurchaseReturnJTI := ""+ if claims != nil {+ expectedPurchaseReturnJTI = strings.TrimSpace(claims.ID)+ }+ resolvedPurchaseReturnJTI := ""+ if checkoutResult != nil {+ resolvedPurchaseReturnJTI = strings.TrimSpace(checkoutResult.PurchaseReturnJTI)+ }+ if expectedPurchaseReturnJTI == "" || resolvedPurchaseReturnJTI == "" || expectedPurchaseReturnJTI != resolvedPurchaseReturnJTI {+ clearReplay("purchase_return_jti_mismatch", nil)+ log.Warn().+ Str("checkout_session_id", sessionID).+ Str("expected_purchase_return_jti", expectedPurchaseReturnJTI).+ Str("resolved_purchase_return_jti", resolvedPurchaseReturnJTI).+ Msg("Rejected checkout activation due to purchase return binding mismatch")+ writeLicensePurchaseActivationFailurePage(w, http.StatusConflict, feature, selfHostedBillingPurchaseExpired, "Purchase activation state did not match the completed upgrade flow. Reopen the upgrade flow from Pulse Pro billing.")+ return+ }activationKey := strings.TrimSpace(checkoutResult.ActivationKey)if activationKey == "" {diff --git a/internal/cloudcp/portal/frontend/src/app.test.ts b/internal/cloudcp/portal/frontend/src/app.test.tsindex 69ef20306f..b4318ca4d8 100644--- a/internal/cloudcp/portal/frontend/src/app.test.ts+++ b/internal/cloudcp/portal/frontend/src/app.test.ts@@ -150,6 +150,7 @@ describe('portal app', function() {{email: '[email protected]',openBillingPanelID: 'retrieve-billing-panel',+ upgradePortalHandoffID: '',upgradeCheckoutIntentID: '',upgradeFeatureKey: '',}diff --git a/internal/cloudcp/portal/frontend/src/billing.ts b/internal/cloudcp/portal/frontend/src/billing.tsindex 228c063e8c..6a094b9efa 100644--- a/internal/cloudcp/portal/frontend/src/billing.ts+++ b/internal/cloudcp/portal/frontend/src/billing.ts@@ -42,6 +42,7 @@ import type {PortalBillingState,PortalCheckoutSessionCreateResponse,PortalUpgradeCheckoutIntentModel,+ PortalUpgradePortalHandoffModel,PortalUpgradePricingModel,VerificationFlowState,} from './types';@@ -88,6 +89,8 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {var nextState = createPortalBillingState();billingState.openBillingPanelID = nextState.openBillingPanelID;billingState.upgradeFeatureKey = nextState.upgradeFeatureKey;+ billingState.upgradePortalHandoffID = nextState.upgradePortalHandoffID;+ billingState.upgradePortalHandoff = nextState.upgradePortalHandoff;billingState.upgradeCheckoutIntentID = nextState.upgradeCheckoutIntentID;billingState.upgradeCheckoutIntent = nextState.upgradeCheckoutIntent;billingState.upgradePricing = nextState.upgradePricing;@@ -192,34 +195,64 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {async function resolveUpgradeCheckoutIntent(force: boolean) {var billingState = getBillingState();+ var portalHandoffID = String(billingState.upgradePortalHandoffID || '').trim();var checkoutIntentID = String(billingState.upgradeCheckoutIntentID || '').trim();- if (!checkoutIntentID) return;+ if (!portalHandoffID && !checkoutIntentID) return;if (!force && (billingState.upgradeCheckoutIntent.status === 'loading' || billingState.upgradeCheckoutIntent.status === 'ready')) {return;}updateBillingState(function(nextBillingState) {+ if (portalHandoffID) {+ beginQueryState(nextBillingState.upgradePortalHandoff, null);+ }beginQueryState(nextBillingState.upgradeCheckoutIntent, null);});try {- var result = await api.getCommercialJSON<PortalUpgradeCheckoutIntentModel>(- '/v1/checkout/intent?checkout_intent_id=' + encodeURIComponent(checkoutIntentID),- );- var resolvedCheckoutIntentID = String(result.checkout_intent_id || '').trim();+ var resolvedCheckoutIntentID = checkoutIntentID;+ var resolvedFeature = '';+ if (portalHandoffID) {+ var handoff = await api.getCommercialJSON<PortalUpgradePortalHandoffModel>(+ '/v1/checkout/portal-handoff?portal_handoff_id=' + encodeURIComponent(portalHandoffID),+ );+ resolvedCheckoutIntentID = String(handoff.checkout_intent_id || '').trim();+ resolvedFeature = String(handoff.feature || '').trim();+ updateBillingState(function(nextBillingState) {+ resolveQueryState(nextBillingState.upgradePortalHandoff, handoff);+ }, false);+ } else {+ var legacyResult = await api.getCommercialJSON<PortalUpgradeCheckoutIntentModel>(+ '/v1/checkout/intent?checkout_intent_id=' + encodeURIComponent(checkoutIntentID),+ );+ resolvedCheckoutIntentID = String(legacyResult.checkout_intent_id || '').trim();+ resolvedFeature = String(legacyResult.feature || '').trim();+ updateBillingState(function(nextBillingState) {+ resolveQueryState(nextBillingState.upgradeCheckoutIntent, legacyResult);+ }, false);+ }if (!resolvedCheckoutIntentID) {- throw new Error('Pulse Account could not verify the secure Pulse Pro checkout intent.');+ throw new Error('Pulse Account could not verify the secure Pulse Pro upgrade handoff.');}- var resolvedFeature = String(result.feature || '').trim();updateBillingState(function(nextBillingState) {- resolveQueryState(nextBillingState.upgradeCheckoutIntent, result);+ resolveQueryState(nextBillingState.upgradeCheckoutIntent, {+ checkout_intent_id: resolvedCheckoutIntentID,+ feature: resolvedFeature,+ });nextBillingState.upgradeCheckoutIntentID = resolvedCheckoutIntentID;nextBillingState.upgradeFeatureKey = resolvedFeature;});} catch (err) {updateBillingState(function(nextBillingState) {+ if (portalHandoffID) {+ failQueryState(+ nextBillingState.upgradePortalHandoff,+ null,+ err instanceof Error ? err.message : 'Failed to verify the secure Pulse Pro upgrade handoff.',+ );+ }failQueryState(nextBillingState.upgradeCheckoutIntent,null,- err instanceof Error ? err.message : 'Failed to verify the secure Pulse Pro checkout intent.',+ err instanceof Error ? err.message : 'Failed to verify the secure Pulse Pro upgrade handoff.',);});}@@ -232,7 +265,7 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {updateBillingState(function(nextBillingState) {failMutationState(nextBillingState.upgradeCheckout,- 'Pulse Account could not verify the secure checkout intent. Reopen the upgrade flow from Pulse Pro billing.',+ 'Pulse Account could not verify the secure upgrade handoff. Reopen the upgrade flow from Pulse Pro billing.',);});return;@@ -552,6 +585,7 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {if (billingState.openBillingPanelID === 'upgrade-billing-panel' ||!!billingState.upgradeFeatureKey ||+ !!billingState.upgradePortalHandoffID ||!!billingState.upgradeCheckoutIntentID) {void loadUpgradePricing(false);diff --git a/internal/cloudcp/portal/frontend/src/billing_view.test.ts b/internal/cloudcp/portal/frontend/src/billing_view.test.tsindex 2ef45ca156..7be025d683 100644--- a/internal/cloudcp/portal/frontend/src/billing_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/billing_view.test.ts@@ -228,6 +228,7 @@ describe('services view', function() {var billingState = createPortalBillingState();billingState.upgradeFeatureKey = 'max_monitored_systems';+ billingState.upgradePortalHandoffID = 'cph_signed';billingState.upgradeCheckoutIntentID = 'cki_signed';billingState.upgradeCheckoutIntent.status = 'ready';billingState.upgradeCheckoutIntent.data = {@@ -278,9 +279,9 @@ describe('services view', function() {document.body.innerHTML = '<div id="upgrade-billing-root"></div>';var billingState = createPortalBillingState();- billingState.upgradeCheckoutIntentID = 'cki_signed';+ billingState.upgradePortalHandoffID = 'cph_signed';billingState.upgradeCheckoutIntent.status = 'error';- billingState.upgradeCheckoutIntent.error = 'Pulse Account could not verify the secure checkout intent.';+ billingState.upgradeCheckoutIntent.error = 'Pulse Account could not verify the secure upgrade handoff.';billingState.upgradePricing.status = 'ready';billingState.upgradePricing.data = {title: 'Pricing',@@ -310,7 +311,7 @@ describe('services view', function() {renderUpgradePanel(billingState, createBootstrap());expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain(- 'Pulse Account could not verify the secure checkout intent.',+ 'Pulse Account could not verify the secure upgrade handoff.',);expect((document.querySelector('[data-account-billing-action="upgrade-start-checkout"]') as HTMLButtonElement).disabled,diff --git a/internal/cloudcp/portal/frontend/src/billing_view.ts b/internal/cloudcp/portal/frontend/src/billing_view.tsindex 64dd621060..8854ca7e29 100644--- a/internal/cloudcp/portal/frontend/src/billing_view.ts+++ b/internal/cloudcp/portal/frontend/src/billing_view.ts@@ -139,6 +139,7 @@ export function renderUpgradePanel(billingState: PortalBillingState, _bootstrap:if (!root) return;var featureKey = String(billingState.upgradeFeatureKey || '').trim();+ var portalHandoffID = String(billingState.upgradePortalHandoffID || '').trim();var pricingState = billingState.upgradePricing;var checkoutIntentState = billingState.upgradeCheckoutIntent;var checkoutIntentID = String(billingState.upgradeCheckoutIntentID || '').trim();@@ -151,14 +152,14 @@ export function renderUpgradePanel(billingState: PortalBillingState, _bootstrap:if (billingState.upgradeCheckout.error) {summaryItems.push('<div class="billing-status visible error">' + escapeText(billingState.upgradeCheckout.error) + '</div>');}- if (!checkoutIntentID) {+ if (!portalHandoffID && !checkoutIntentID) {summaryItems.push(- '<div class="billing-status visible error">Open this upgrade from Pulse Pro billing so Pulse Account can verify the secure checkout intent before checkout.</div>',+ '<div class="billing-status visible error">Open this upgrade from Pulse Pro billing so Pulse Account can verify the secure upgrade handoff before checkout.</div>',);} else if (checkoutIntentState.status === 'loading') {- summaryItems.push('<div class="billing-status visible">Verifying the secure Pulse Pro checkout intent...</div>');+ summaryItems.push('<div class="billing-status visible">Verifying the secure Pulse Pro upgrade handoff...</div>');} else if (checkoutIntentState.status === 'error') {- summaryItems.push('<div class="billing-status visible error">' + escapeText(checkoutIntentState.error || 'Failed to verify the secure Pulse Pro checkout intent.') + '</div>');+ summaryItems.push('<div class="billing-status visible error">' + escapeText(checkoutIntentState.error || 'Failed to verify the secure Pulse Pro upgrade handoff.') + '</div>');} else if (checkoutIntentState.status === 'ready') {summaryItems.push('<div class="billing-status visible success">Pulse Account will return completed checkout directly to Pulse Pro billing.</div>');}diff --git a/internal/cloudcp/portal/frontend/src/runtime.test.ts b/internal/cloudcp/portal/frontend/src/runtime.test.tsindex 4c83d43841..d92496bf0f 100644--- a/internal/cloudcp/portal/frontend/src/runtime.test.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.test.ts@@ -64,12 +64,13 @@ describe('portal runtime', function() {it('derives canonical email and billing handoff from the portal URL', function() {var handoff = readPortalRuntimeHandoff(- 'https://cloud.pulserelay.pro/portal?email=buyer%40example.com&service=upgrade&checkout_intent_id=cki_signed',+ 'https://cloud.pulserelay.pro/portal?email=buyer%40example.com&portal_handoff_id=cph_signed',);expect(handoff.email).toBe('[email protected]');expect(handoff.openBillingPanelID).toBe('upgrade-billing-panel');- expect(handoff.upgradeCheckoutIntentID).toBe('cki_signed');+ expect(handoff.upgradePortalHandoffID).toBe('cph_signed');+ expect(handoff.upgradeCheckoutIntentID).toBe('');expect(handoff.upgradeFeatureKey).toBe('');});@@ -84,6 +85,7 @@ describe('portal runtime', function() {{email: '[email protected]',openBillingPanelID: 'refund-billing-panel',+ upgradePortalHandoffID: '',upgradeCheckoutIntentID: '',upgradeFeatureKey: '',}@@ -106,14 +108,16 @@ describe('portal runtime', function() {{email: '',openBillingPanelID: 'upgrade-billing-panel',- upgradeCheckoutIntentID: 'cki_signed',+ upgradePortalHandoffID: 'cph_signed',+ upgradeCheckoutIntentID: '',upgradeFeatureKey: '',});expect(runtime.store.getShellState().activeSection).toBe('billing');expect(runtime.store.getBillingState().openBillingPanelID).toBe('upgrade-billing-panel');- expect(runtime.store.getBillingState().upgradeCheckoutIntentID).toBe('cki_signed');+ expect(runtime.store.getBillingState().upgradePortalHandoffID).toBe('cph_signed');+ expect(runtime.store.getBillingState().upgradeCheckoutIntentID).toBe('');expect(runtime.store.getBillingState().upgradeFeatureKey).toBe('');});});diff --git a/internal/cloudcp/portal/frontend/src/runtime.ts b/internal/cloudcp/portal/frontend/src/runtime.tsindex 95e9089850..96338c555e 100644--- a/internal/cloudcp/portal/frontend/src/runtime.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.ts@@ -5,6 +5,7 @@ import type { PortalBootstrapData } from './types';export interface PortalRuntimeHandoff {email: string;openBillingPanelID: string;+ upgradePortalHandoffID: string;upgradeCheckoutIntentID: string;upgradeFeatureKey: string;}@@ -40,6 +41,14 @@ function normalizeUpgradeCheckoutIntentID(return /^[A-Za-z0-9_-]+$/.test(trimmed) ? trimmed : '';}+function normalizeUpgradePortalHandoffID(+ value: string | null | undefined,+): string {+ var trimmed = String(value || '').trim();+ if (!trimmed) return '';+ return /^[A-Za-z0-9_-]+$/.test(trimmed) ? trimmed : '';+}+function normalizeHandoffBillingPanel(value: string | null): string {switch (String(value || '').trim()) {case 'upgrade':@@ -66,9 +75,15 @@ export function readPortalRuntimeHandoff(): PortalRuntimeHandoff {try {var params = new URL(locationHref).searchParams;+ var upgradePortalHandoffID = normalizeUpgradePortalHandoffID(params.get('portal_handoff_id'));+ var openBillingPanelID = normalizeHandoffBillingPanel(params.get('service'));+ if (!openBillingPanelID && upgradePortalHandoffID) {+ openBillingPanelID = 'upgrade-billing-panel';+ }return {email: normalizeHandoffEmail(params.get('email')),- openBillingPanelID: normalizeHandoffBillingPanel(params.get('service')),+ openBillingPanelID: openBillingPanelID,+ upgradePortalHandoffID: upgradePortalHandoffID,upgradeCheckoutIntentID: normalizeUpgradeCheckoutIntentID(params.get('checkout_intent_id')),upgradeFeatureKey: normalizeUpgradeFeatureKey(params.get('feature')),};@@ -76,6 +91,7 @@ export function readPortalRuntimeHandoff(return {email: '',openBillingPanelID: '',+ upgradePortalHandoffID: '',upgradeCheckoutIntentID: '',upgradeFeatureKey: '',};@@ -125,12 +141,14 @@ export function createPortalRuntime(store.setActiveShellSection('billing');store.updateBillingState(function(billingState) {billingState.openBillingPanelID = handoff.openBillingPanelID;+ billingState.upgradePortalHandoffID = handoff.upgradePortalHandoffID;billingState.upgradeCheckoutIntentID = handoff.upgradeCheckoutIntentID;billingState.upgradeFeatureKey = handoff.upgradeFeatureKey;}, { notify: false });- } else if (handoff.upgradeFeatureKey || handoff.upgradeCheckoutIntentID) {+ } else if (handoff.upgradeFeatureKey || handoff.upgradePortalHandoffID || handoff.upgradeCheckoutIntentID) {store.setActiveShellSection('billing');store.updateBillingState(function(billingState) {+ billingState.upgradePortalHandoffID = handoff.upgradePortalHandoffID;billingState.upgradeCheckoutIntentID = handoff.upgradeCheckoutIntentID;billingState.upgradeFeatureKey = handoff.upgradeFeatureKey;}, { notify: false });diff --git a/internal/cloudcp/portal/frontend/src/shell_view.ts b/internal/cloudcp/portal/frontend/src/shell_view.tsindex a78bfacf5b..2019f143c3 100644--- a/internal/cloudcp/portal/frontend/src/shell_view.ts+++ b/internal/cloudcp/portal/frontend/src/shell_view.ts@@ -1236,6 +1236,7 @@ export function renderAuthenticatedPortalHTML(context: ShellViewContext): stringvar showSelfHostedUpgradeHandoff =context.billingState.openBillingPanelID === 'upgrade-billing-panel' ||!!normalizeUpgradeFeatureKey(context.billingState.upgradeFeatureKey) ||+ !!String(context.billingState.upgradePortalHandoffID || '').trim() ||!!String(context.billingState.upgradeCheckoutIntentID || '').trim();var showSelfHostedBillingShell = showSelfHostedCommercial || showSelfHostedUpgradeHandoff;var shellSections = visibleShellSections(context.bootstrap);diff --git a/internal/cloudcp/portal/frontend/src/state.test.ts b/internal/cloudcp/portal/frontend/src/state.test.tsindex 330a9be706..b14e3d108f 100644--- a/internal/cloudcp/portal/frontend/src/state.test.ts+++ b/internal/cloudcp/portal/frontend/src/state.test.ts@@ -35,6 +35,8 @@ describe('portal state', function() {expect(billingState.flows.manage.confirm.pending).toBe(false);expect(billingState.refund.submit.pending).toBe(false);expect(billingState.upgradeFeatureKey).toBe('');+ expect(billingState.upgradePortalHandoffID).toBe('');+ expect(billingState.upgradePortalHandoff.status).toBe('idle');expect(billingState.upgradeCheckoutIntentID).toBe('');expect(billingState.upgradeCheckoutIntent.status).toBe('idle');expect(billingState.upgradePricing.status).toBe('idle');diff --git a/internal/cloudcp/portal/frontend/src/state.ts b/internal/cloudcp/portal/frontend/src/state.tsindex 2294f21613..87dbfd3adc 100644--- a/internal/cloudcp/portal/frontend/src/state.ts+++ b/internal/cloudcp/portal/frontend/src/state.ts@@ -118,6 +118,8 @@ export function createPortalBillingState(): PortalBillingState {return {openBillingPanelID: '',upgradeFeatureKey: '',+ upgradePortalHandoffID: '',+ upgradePortalHandoff: createQueryState(null),upgradeCheckoutIntentID: '',upgradeCheckoutIntent: createQueryState(null),upgradePricing: createQueryState(null),diff --git a/internal/cloudcp/portal/frontend/src/types.ts b/internal/cloudcp/portal/frontend/src/types.tsindex eeb088aadf..f90233db7a 100644--- a/internal/cloudcp/portal/frontend/src/types.ts+++ b/internal/cloudcp/portal/frontend/src/types.ts@@ -84,6 +84,12 @@ export interface PortalUpgradeCheckoutIntentModel {feature?: string;}+export interface PortalUpgradePortalHandoffModel {+ portal_handoff_id: string;+ checkout_intent_id: string;+ feature?: string;+}+export interface PortalCheckoutSessionCreateResponse {url?: string;plan_key?: string;@@ -163,6 +169,8 @@ export interface RefundState {export interface PortalBillingState {openBillingPanelID: string;upgradeFeatureKey: string;+ upgradePortalHandoffID: string;+ upgradePortalHandoff: PortalQueryState<PortalUpgradePortalHandoffModel | null>;upgradeCheckoutIntentID: string;upgradeCheckoutIntent: PortalQueryState<PortalUpgradeCheckoutIntentModel | null>;upgradePricing: PortalQueryState<PortalUpgradePricingModel | null>;diff --git a/pkg/licensing/license_server_client.go b/pkg/licensing/license_server_client.goindex 29aa8e71be..ac000a24b5 100644--- a/pkg/licensing/license_server_client.go+++ b/pkg/licensing/license_server_client.go@@ -28,6 +28,8 @@ type CheckoutSessionResult struct {Message string `json:"message,omitempty"`CheckoutStatus string `json:"checkout_status,omitempty"`PaymentStatus string `json:"payment_status,omitempty"`+ CheckoutIntentID string `json:"checkout_intent_id,omitempty"`+ PurchaseReturnJTI string `json:"purchase_return_jti,omitempty"`LicenseID string `json:"license_id,omitempty"`ActivationKey string `json:"activation_key,omitempty"`ActivationKeyPrefix string `json:"activation_key_prefix,omitempty"`@@ -44,7 +46,7 @@ type CheckoutIntentRequest struct {CancelURL string `json:"cancel_url"`}-// CheckoutIntentResponse is the canonical opaque checkout handoff returned by+// CheckoutIntentResponse is the canonical checkout-intent record returned by// the license server.type CheckoutIntentResponse struct {CheckoutIntentID string `json:"checkout_intent_id"`@@ -52,6 +54,25 @@ type CheckoutIntentResponse struct {ExpiresAt int64 `json:"expires_at,omitempty"`}+// CheckoutPortalHandoffRequest is the canonical server-owned request for a+// Pulse Account portal bootstrap record that hides commercial flow state from+// the browser.+type CheckoutPortalHandoffRequest struct {+ Feature string `json:"feature,omitempty"`+ SuccessURL string `json:"success_url"`+ CancelURL string `json:"cancel_url"`+ PurchaseReturnJTI string `json:"purchase_return_jti"`+}++// CheckoutPortalHandoffResponse is the canonical opaque portal handoff used to+// bootstrap the hosted Pulse Account billing flow.+type CheckoutPortalHandoffResponse struct {+ PortalHandoffID string `json:"portal_handoff_id"`+ CheckoutIntentID string `json:"checkout_intent_id,omitempty"`+ Feature string `json:"feature,omitempty"`+ ExpiresAt int64 `json:"expires_at,omitempty"`+}+// NewLicenseServerClient creates a client for the license server.// The base URL defaults to DefaultLicenseServerURL. The PULSE_LICENSE_SERVER_URL// env var override is only allowed in non-release builds.@@ -208,8 +229,8 @@ func (c *LicenseServerClient) GetCheckoutSessionResult(ctx context.Context, sessreturn &result, nil}-// CreateCheckoutIntent stores a server-owned self-hosted checkout handoff and-// returns an opaque checkout_intent_id for Pulse Account browser flows.+// CreateCheckoutIntent stores a server-owned self-hosted checkout intent and+// returns its commercial checkout_intent_id.func (c *LicenseServerClient) CreateCheckoutIntent(ctx context.Context, req CheckoutIntentRequest) (*CheckoutIntentResponse, error) {body, err := json.Marshal(req)if err != nil {@@ -240,6 +261,38 @@ func (c *LicenseServerClient) CreateCheckoutIntent(ctx context.Context, req Checreturn &result, nil}+// CreateCheckoutPortalHandoff stores a server-owned Pulse Account bootstrap+// record and returns an opaque portal_handoff_id for browser navigation.+func (c *LicenseServerClient) CreateCheckoutPortalHandoff(ctx context.Context, req CheckoutPortalHandoffRequest) (*CheckoutPortalHandoffResponse, error) {+ body, err := json.Marshal(req)+ if err != nil {+ return nil, fmt.Errorf("marshal checkout portal handoff request: %w", err)+ }++ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/v1/checkout/portal-handoff", bytes.NewReader(body))+ if err != nil {+ return nil, fmt.Errorf("create checkout portal handoff request: %w", err)+ }+ httpReq.Header.Set("Content-Type", "application/json")+ httpReq.Header.Set("Accept", "application/json")++ resp, err := c.httpClient.Do(httpReq)+ if err != nil {+ return nil, fmt.Errorf("checkout portal handoff request failed: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {+ return nil, c.parseError(resp)+ }++ var result CheckoutPortalHandoffResponse+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil {+ return nil, fmt.Errorf("decode checkout portal handoff response: %w", err)+ }+ return &result, nil+}+// BootstrapQuickstart exchanges a runtime identity for a short-lived// quickstart token and the current authoritative quickstart inventory.// Callers must pass a server-verified quickstart authority token asdiff --git a/pkg/licensing/license_server_client_test.go b/pkg/licensing/license_server_client_test.goindex 35a2d55592..f48afdc2d1 100644--- a/pkg/licensing/license_server_client_test.go+++ b/pkg/licensing/license_server_client_test.go@@ -291,6 +291,8 @@ func TestClientGetCheckoutSessionResult(t *testing.T) {Status: "fulfilled",CheckoutStatus: "complete",PaymentStatus: "paid",+ CheckoutIntentID: "cki_test_123",+ PurchaseReturnJTI: "purchase_return_jti_123",ActivationKeyPrefix: "ppk_live_",Tier: "pro",})@@ -308,6 +310,9 @@ func TestClientGetCheckoutSessionResult(t *testing.T) {if result.CheckoutStatus != "complete" {t.Fatalf("CheckoutStatus = %q, want complete", result.CheckoutStatus)}+ if result.PurchaseReturnJTI != "purchase_return_jti_123" {+ t.Fatalf("PurchaseReturnJTI = %q, want purchase_return_jti_123", result.PurchaseReturnJTI)+ }})t.Run("empty session id fails before transport", func(t *testing.T) {@@ -377,6 +382,59 @@ func TestClientCreateCheckoutIntent(t *testing.T) {}}+func TestClientCreateCheckoutPortalHandoff(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Errorf("Method = %q, want POST", r.Method)+ }+ if r.URL.Path != "/v1/checkout/portal-handoff" {+ t.Errorf("Path = %q, want /v1/checkout/portal-handoff", r.URL.Path)+ }+ if r.Header.Get("Content-Type") != "application/json" {+ t.Errorf("Content-Type = %q, want application/json", r.Header.Get("Content-Type"))+ }+ if r.Header.Get("Accept") != "application/json" {+ t.Errorf("Accept = %q, want application/json", r.Header.Get("Accept"))+ }++ var req CheckoutPortalHandoffRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ t.Fatalf("decode request: %v", err)+ }+ if req.Feature != "max_monitored_systems" {+ t.Fatalf("Feature = %q, want max_monitored_systems", req.Feature)+ }+ if req.PurchaseReturnJTI != "purchase_return_jti_123" {+ t.Fatalf("PurchaseReturnJTI = %q, want purchase_return_jti_123", req.PurchaseReturnJTI)+ }++ w.WriteHeader(http.StatusOK)+ _ = json.NewEncoder(w).Encode(CheckoutPortalHandoffResponse{+ PortalHandoffID: "cph_test_123",+ Feature: "max_monitored_systems",+ ExpiresAt: 1_775_000_000,+ })+ }))+ defer server.Close()++ client := NewLicenseServerClient(server.URL)+ result, err := client.CreateCheckoutPortalHandoff(context.Background(), CheckoutPortalHandoffRequest{+ Feature: "max_monitored_systems",+ SuccessURL: "https://pulse.example.com/auth/license-purchase-activate?purchase_return_token=prt_signed&session_id={CHECKOUT_SESSION_ID}",+ CancelURL: "https://pulse.example.com/settings/system/billing/plan?intent=max_monitored_systems&purchase=cancelled",+ PurchaseReturnJTI: "purchase_return_jti_123",+ })+ if err != nil {+ t.Fatalf("CreateCheckoutPortalHandoff failed: %v", err)+ }+ if result.PortalHandoffID != "cph_test_123" {+ t.Fatalf("PortalHandoffID = %q, want cph_test_123", result.PortalHandoffID)+ }+ if result.Feature != "max_monitored_systems" {+ t.Fatalf("Feature = %q, want max_monitored_systems", result.Feature)+ }+}+func TestClientRefreshGrant(t *testing.T) {t.Run("successful refresh", func(t *testing.T) {newGrantJWT := makeTestGrantJWT(t, &GrantClaims{diff --git a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts b/tests/integration/tests/55-self-hosted-upgrade-return.spec.tsindex 28f44a72c2..43494bb956 100644--- a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts+++ b/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts@@ -11,7 +11,7 @@ const PURCHASE_START_PATH = "/auth/license-purchase-start";const PURCHASE_START_URL = `${DEV_SERVER_URL}${PURCHASE_START_PATH}`;const PULSE_ACCOUNT_PORTAL_URL = "https://cloud.pulserelay.pro/portal";const PURCHASE_RETURN_URL = `${DEV_SERVER_URL}/auth/license-purchase-activate`;-const CHECKOUT_INTENT_ID = "cki_checkout_return";+const PORTAL_HANDOFF_ID = "cph_checkout_return";const ACTIVATED_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems&purchase=activated`;const FINAL_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems`;const PURCHASE_RETURN_TOKEN = "prt_signed_checkout_return";@@ -194,7 +194,7 @@ test.describe("Self-hosted upgrade return flow", () => {await route.fulfill({status: 303,headers: {- location: `${PULSE_ACCOUNT_PORTAL_URL}?service=upgrade&checkout_intent_id=${CHECKOUT_INTENT_ID}`,+ location: `${PULSE_ACCOUNT_PORTAL_URL}?portal_handoff_id=${PORTAL_HANDOFF_ID}`,},body: "",});@@ -202,13 +202,14 @@ test.describe("Self-hosted upgrade return flow", () => {await context.route(`${PULSE_ACCOUNT_PORTAL_URL}**`, async (route) => {const requestUrl = new URL(route.request().url());- expect(requestUrl.searchParams.get("service")).toBe("upgrade");+ expect(requestUrl.searchParams.get("service")).toBeNull();expect(requestUrl.searchParams.get("feature")).toBeNull();expect(requestUrl.searchParams.get("return_url")).toBeNull();expect(requestUrl.searchParams.get("purchase_handoff_url")).toBeNull();- expect(requestUrl.searchParams.get("checkout_intent_id")).toBe(- CHECKOUT_INTENT_ID,+ expect(requestUrl.searchParams.get("portal_handoff_id")).toBe(+ PORTAL_HANDOFF_ID,);+ expect(requestUrl.searchParams.get("checkout_intent_id")).toBeNull();await route.fulfill({status: 200,@@ -280,7 +281,7 @@ test.describe("Self-hosted upgrade return flow", () => {.toBe(`${PURCHASE_START_URL}?feature=max_monitored_systems`);await page.goto(- `${PULSE_ACCOUNT_PORTAL_URL}?service=upgrade&checkout_intent_id=${CHECKOUT_INTENT_ID}`,+ `${PULSE_ACCOUNT_PORTAL_URL}?portal_handoff_id=${PORTAL_HANDOFF_ID}`,{waitUntil: "domcontentloaded",},