Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Recover unavailable Pulse Account handoffs

rcourtman429f12decd76
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index fd52f877c8..4cb1fae307 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -253,6 +253,12 @@ an add-only capacity posture.
activation-bridge form state, owned billing purchase-arrival states, or
demo-hidden commercial route policy as installer credentials,
registration state, or fleet enrollment authority. The same adjacent
+ commercial boundary also owns purchase-start unavailability recovery:
+ lifecycle-adjacent surfaces may coexist with that shared browser route, but
+ they must not strand install or fleet flows on a raw Pulse Account error
+ tab, reinterpret `purchase=unavailable` as lifecycle repair state, or
+ bypass the owned billing retry/recovery path.
+ The same adjacent
commercial boundary now also owns migrated-v5 monitored-system
grandfathering: lifecycle surfaces may react to the resulting license or
entitlements payloads, but they must not cache their own pre-activation
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index a54226b863..903d1a1393 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -752,7 +752,11 @@ license/commercial API before returning the browser to the owned billing plan
route. Stripe cancel must return directly to owned billing with
`purchase=cancelled`; activation success, expiry, and failure must return to
owned billing with explicit arrival states so the billing runtime can surface
-those results in-product. When the upgrade flow was opened in a secondary tab,
+those results in-product. If Pulse cannot create the initial Pulse Account
+portal handoff, `GET /auth/license-purchase-start` must still return the
+browser to owned billing with `purchase=unavailable` so the runtime can
+surface the failure in-product instead of leaving the operator on a raw
+service error. When the upgrade flow was opened in a secondary tab,
the callback may refresh the originating billing tab and close itself; when no
opener is available, the callback must still return the current tab to the
owned billing route automatically instead of leaving the operator on a dead
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index ef94ac38a8..88b61446c3 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -602,6 +602,11 @@ as `portal_handoff_id`, feature, handoff lifecycle state, resolve timestamp,
and expiry; it must not disclose the bound `checkout_intent_id`, and browser
checkout creation must post only `portal_handoff_id` so Pulse Account
resolves the private checkout intent server-side before contacting Stripe.
+If Pulse cannot create or resolve that portal handoff locally, the Pulse-owned
+start route must still return the operator to the owned billing plan surface
+with an explicit `purchase=unavailable` arrival instead of leaving the browser
+on a raw error page, so the runtime can explain that Pulse Account is
+temporarily unavailable and offer a retry from the same instance.
That portal handoff is now intentionally narrowly stateful rather than a bare
lookup row: lookup must stamp a first `resolved_at`, and the reported handoff
lifecycle must stay derived from the owned portal handoff plus the bound
@@ -636,8 +641,8 @@ directly to the owned Pulse billing plan route rather than back into the
portal. The owned activation callback must accept the signed state, redeem the
completed checkout, and return the operator to the canonical billing plan
route with an explicit owned purchase arrival state (`purchase=activated`,
-`purchase=expired`, or `purchase=failed`) whether checkout completed in a
-secondary tab or in the current-tab fallback path.
+`purchase=expired`, `purchase=failed`, or `purchase=unavailable`) whether
+checkout completed in a secondary tab or in the current-tab fallback path.
That destination split is canonical commercial truth, but navigation semantics
are not owned here. `frontend-modern/src/utils/pricingHandoff.ts` and
`frontend-modern/src/stores/license.ts` decide which href each commercial
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index aa020ef62d..e161d9f8fa 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -555,7 +555,11 @@ lookup. Storage and recovery may coexist with the shared purchase return routes
in the app shell, but they must not cache, derive, or replay the
server-resolved portal checkout state or owned billing purchase-arrival state
as recovery route state, restore evidence, or storage-local navigation
-context.
+context. The same rule now also covers purchase-start failures: storage and
+recovery surfaces may coexist with the shared `/auth/license-purchase-start`
+route, but they must not absorb `purchase=unavailable` as recovery-local state
+or replace the owned billing retry/recovery notice with storage-specific error
+chrome.
That same adjacent licensing boundary now also owns internal demo-fixture
runtime gating for storage- and recovery-adjacent surfaces. Release builds may
authorize mock fixture rewiring only through the backend-owned
diff --git a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
index 46a7ad7db1..fd783e9280 100644
--- a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
@@ -17,6 +17,7 @@ import {
SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED,
SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED,
SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED,
+ SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE,
SELF_HOSTED_PRO_BILLING_RECOVERY_DETAIL,
SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID,
SELF_HOSTED_PRO_BILLING_USAGE_HREF,
@@ -572,6 +573,12 @@ describe('ProLicensePanel', () => {
detail: SELF_HOSTED_PRO_BILLING_RECOVERY_DETAIL,
}),
},
+ {
+ purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE,
+ title: 'Pulse Account unavailable',
+ actionLabel: 'Try again',
+ actionHref: getSelfHostedPurchaseStartUrl(),
+ },
])('shows the purchase arrival notice for $purchase', async ({ purchase, title, actionLabel, actionHref, redirectedHref = SELF_HOSTED_PRO_BILLING_PLAN_HREF }) => {
useLocationMock.mockReturnValue({
search: `?purchase=${purchase}`,
diff --git a/frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts b/frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts
index e8aaddd61b..6a8455be3f 100644
--- a/frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts
+++ b/frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts
@@ -23,6 +23,7 @@ export interface SelfHostedProBillingPresentation {
purchaseCancelledActionLabel: string;
purchaseExpiredActionLabel: string;
purchaseFailedActionLabel: string;
+ purchaseUnavailableActionLabel: string;
trialStartTitle: string;
trialStartBody: string;
trialStartIdleActionLabel: string;
@@ -61,6 +62,7 @@ export const SELF_HOSTED_PRO_BILLING_PRESENTATION: SelfHostedProBillingPresentat
purchaseCancelledActionLabel: 'Compare plans',
purchaseExpiredActionLabel: 'Restart upgrade',
purchaseFailedActionLabel: 'Open recovery',
+ purchaseUnavailableActionLabel: 'Try again',
trialStartTitle: 'Try Pro for free',
trialStartBody: 'Start a 14-day Pro trial for this organization.',
trialStartIdleActionLabel: 'Start 14-day Pro Trial',
diff --git a/frontend-modern/src/components/Settings/useProLicensePanelState.ts b/frontend-modern/src/components/Settings/useProLicensePanelState.ts
index a788923260..432705cee7 100644
--- a/frontend-modern/src/components/Settings/useProLicensePanelState.ts
+++ b/frontend-modern/src/components/Settings/useProLicensePanelState.ts
@@ -38,6 +38,7 @@ import {
SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED,
SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED,
SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED,
+ SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE,
SELF_HOSTED_PRO_BILLING_PLAN_DETAILS_QUERY_PARAM,
SELF_HOSTED_PRO_BILLING_PLAN_ROUTE,
SELF_HOSTED_PRO_BILLING_PURCHASE_QUERY_PARAM,
@@ -320,6 +321,11 @@ export function useProLicensePanelState() {
}),
),
};
+ case SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE:
+ return {
+ label: SELF_HOSTED_PRO_BILLING_PRESENTATION.purchaseUnavailableActionLabel,
+ destination: resolveSelfHostedPurchaseStartDestination(intent),
+ };
default:
return null;
}
diff --git a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts b/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
index e422c49e61..1797d81fb3 100644
--- a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
@@ -93,6 +93,7 @@ describe('licensePresentation', () => {
purchaseCancelledActionLabel: 'Compare plans',
purchaseExpiredActionLabel: 'Restart upgrade',
purchaseFailedActionLabel: 'Open recovery',
+ purchaseUnavailableActionLabel: 'Try again',
trialStartTitle: 'Try Pro for free',
trialStartBody: 'Start a 14-day Pro trial for this organization.',
trialStartIdleActionLabel: 'Start 14-day Pro Trial',
@@ -270,6 +271,11 @@ describe('licensePresentation', () => {
body: expect.stringContaining('open recovery'),
tone: expect.stringContaining('red'),
});
+ expect(getPurchaseActivationNotice('unavailable')).toMatchObject({
+ title: 'Pulse Account unavailable',
+ body: expect.stringContaining('Retry from this instance'),
+ tone: expect.stringContaining('amber'),
+ });
expect(getPurchaseActivationNotice('')).toBeNull();
});
diff --git a/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts b/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts
index 6a9a45bbcd..d556cf0be7 100644
--- a/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts
+++ b/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts
@@ -20,6 +20,7 @@ import {
SELF_HOSTED_PRO_BILLING_PLAN_MONITORED_SYSTEM_UPGRADE_HREF,
SELF_HOSTED_PRO_BILLING_PLAN_RECOVERY_HREF,
SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,
+ SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE,
SELF_HOSTED_PRO_BILLING_RECOVERY_DETAIL,
SELF_HOSTED_PRO_BILLING_ROUTE,
SELF_HOSTED_PRO_BILLING_USAGE_COUNTING_RULES_HREF,
@@ -115,6 +116,11 @@ describe('pricingHandoff', () => {
'?purchase=' + SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,
),
).toBe(SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED);
+ expect(
+ getSelfHostedBillingPurchaseArrival(
+ '?purchase=' + SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE,
+ ),
+ ).toBe(SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE);
});
it('scopes in-product billing destinations to canonical routes and leaves external ones alone', () => {
diff --git a/frontend-modern/src/utils/licensePresentation.ts b/frontend-modern/src/utils/licensePresentation.ts
index 72679c73d4..125ff714dc 100644
--- a/frontend-modern/src/utils/licensePresentation.ts
+++ b/frontend-modern/src/utils/licensePresentation.ts
@@ -347,6 +347,12 @@ export const getPurchaseActivationNotice = (result?: string | null): LicenseInli
title: 'Activation needs attention',
body: 'Checkout completed, but Pulse could not finish local activation automatically. Review the plan state below, then open recovery if you already have a key from this purchase.',
};
+ case 'unavailable':
+ return {
+ tone: 'border-amber-200 dark:border-amber-900 bg-amber-50 dark:bg-amber-900 text-amber-900 dark:text-amber-100',
+ title: 'Pulse Account unavailable',
+ body: 'Pulse could not open the Pulse Account upgrade flow right now. The current plan state below is unchanged. Retry from this instance in a moment, or use recovery below if you already have a key.',
+ };
default:
return null;
}
diff --git a/frontend-modern/src/utils/pricingHandoff.ts b/frontend-modern/src/utils/pricingHandoff.ts
index d5cc3dee53..0b133dfc82 100644
--- a/frontend-modern/src/utils/pricingHandoff.ts
+++ b/frontend-modern/src/utils/pricingHandoff.ts
@@ -28,6 +28,7 @@ export const SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED = 'activated';
export const SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED = 'cancelled';
export const SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED = 'expired';
export const SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED = 'failed';
+export const SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE = 'unavailable';
export type SelfHostedBillingSection = 'plan' | 'usage';
export type SelfHostedBillingUsageDetail = typeof SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL;
@@ -38,7 +39,8 @@ export type SelfHostedBillingPurchaseArrival =
| typeof SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED
| typeof SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED
| typeof SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED
- | typeof SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED;
+ | typeof SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED
+ | typeof SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE;
export const SELF_HOSTED_PRO_BILLING_PLAN_HREF = SELF_HOSTED_PRO_BILLING_PLAN_ROUTE;
export const SELF_HOSTED_PRO_BILLING_USAGE_HREF = SELF_HOSTED_PRO_BILLING_USAGE_ROUTE;
@@ -172,6 +174,7 @@ export function getSelfHostedBillingPurchaseArrival(
case SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED:
case SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED:
case SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED:
+ case SELF_HOSTED_PRO_BILLING_PURCHASE_UNAVAILABLE:
return purchase;
default:
return null;
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 9754dc6b2d..dd703055ff 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -6460,6 +6460,53 @@ func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_SelfHostedPurchaseHandoffUnavailableJSONSnapshot(t *testing.T) {
+ handler := createTestHandler(t)
+ handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/checkout/portal-handoff" {
+ t.Fatalf("unexpected path %q", r.URL.Path)
+ }
+ http.Error(w, "portal handoff unavailable", http.StatusBadGateway)
+ }))
+ defer server.Close()
+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
+
+ req := httptest.NewRequest(
+ http.MethodGet,
+ "https://pulse.example.com"+licensePurchaseStartPath+"?feature=max_monitored_systems",
+ nil,
+ )
+ rec := httptest.NewRecorder()
+
+ handler.HandleCheckoutStart(rec, req)
+
+ got, err := json.MarshalIndent(struct {
+ StatusCode int `json:"status_code"`
+ TitlePresent bool `json:"title_present"`
+ RetryMessagePresent bool `json:"retry_message_present"`
+ OwnedRedirectPath bool `json:"owned_redirect_path"`
+ }{
+ StatusCode: rec.Code,
+ TitlePresent: strings.Contains(rec.Body.String(), "Pulse Account unavailable"),
+ RetryMessagePresent: strings.Contains(rec.Body.String(), "Retry from this instance in a moment"),
+ OwnedRedirectPath: strings.Contains(rec.Body.String(), "/settings/system/billing/plan?intent=max_monitored_systems&purchase=unavailable"),
+ }, "", "\t")
+ if err != nil {
+ t.Fatalf("marshal unavailable handoff snapshot: %v", err)
+ }
+
+ const want = `{
+ "status_code": 503,
+ "title_present": true,
+ "retry_message_present": true,
+ "owned_redirect_path": true
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_HandoffExchangeJSONSnapshot(t *testing.T) {
key := []byte("test-handoff-key")
configDir := t.TempDir()
diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.go
index e426fcae2a..e86b21e469 100644
--- a/internal/api/licensing_handlers.go
+++ b/internal/api/licensing_handlers.go
@@ -41,6 +41,7 @@ const (
selfHostedBillingPurchaseCancelled = "cancelled"
selfHostedBillingPurchaseExpired = "expired"
selfHostedBillingPurchaseFailed = "failed"
+ selfHostedBillingPurchaseUnavailable = "unavailable"
purchaseReturnKeyPurpose = "pulse-license-purchase-return"
)
@@ -385,7 +386,8 @@ func licensePurchaseActivationRedirectPath(feature, purchaseResult string) strin
case selfHostedBillingPurchaseActivated,
selfHostedBillingPurchaseCancelled,
selfHostedBillingPurchaseExpired,
- selfHostedBillingPurchaseFailed:
+ selfHostedBillingPurchaseFailed,
+ selfHostedBillingPurchaseUnavailable:
query.Set(selfHostedBillingPurchaseQueryParam, strings.TrimSpace(purchaseResult))
}
encoded := query.Encode()
@@ -423,6 +425,33 @@ func writeLicensePurchaseActivationFailurePage(
)
}
+func writeLicensePurchaseStartFailurePage(
+ w http.ResponseWriter,
+ statusCode int,
+ feature string,
+ message string,
+) {
+ if statusCode < http.StatusBadRequest {
+ statusCode = http.StatusBadRequest
+ }
+ redirectPath := licensePurchaseActivationRedirectPath(feature, selfHostedBillingPurchaseUnavailable)
+ escapedMessage := html.EscapeString(strings.TrimSpace(message))
+ if escapedMessage == "" {
+ escapedMessage = "Pulse could not open Pulse Account right now."
+ }
+ escapedLink := html.EscapeString(redirectPath)
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.WriteHeader(statusCode)
+ _, _ = fmt.Fprintf(
+ w,
+ "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Pulse Account unavailable</title></head><body><main style=\"max-width:32rem;margin:3rem auto;padding:0 1rem;font:16px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif\"><h1 style=\"margin-bottom:0.5rem\">Pulse Account unavailable</h1><p id=\"purchase-start-status\" style=\"margin-bottom:1rem\">%s</p><p><a href=\"%s\">Return to Pulse Pro billing</a></p></main><script>(function(){var redirectPath=%q;var statusEl=document.getElementById('purchase-start-status');var redirectedOriginalTab=false;try{if(window.opener&&!window.opener.closed){redirectedOriginalTab=true;window.opener.postMessage({type:'pulse-license-purchase-start-unavailable',redirectPath:redirectPath,result:%q},window.location.origin);window.opener.location.assign(redirectPath);}}catch(_){redirectedOriginalTab=false;}if(redirectedOriginalTab){setTimeout(function(){try{window.close();}catch(_){ }if(statusEl){statusEl.textContent='Pulse Pro billing has been reopened in the original tab. You can close this window if it stays open.';}},75);return;}if(statusEl){statusEl.textContent='Returning to Pulse Pro billing.';}setTimeout(function(){window.location.replace(redirectPath);},150);}());</script></body></html>",
+ escapedMessage,
+ escapedLink,
+ redirectPath,
+ selfHostedBillingPurchaseUnavailable,
+ )
+}
+
func writeLicensePurchaseActivationSuccessPage(w http.ResponseWriter, feature string) {
redirectPath := licensePurchaseActivationRedirectPath(feature, selfHostedBillingPurchaseActivated)
escapedLink := html.EscapeString(redirectPath)
@@ -1486,17 +1515,28 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
return
}
+ feature := strings.TrimSpace(r.URL.Query().Get(pulseAccountPortalFeatureQueryParam))
+ writeUnavailable := func(statusCode int, message string) {
+ writeLicensePurchaseStartFailurePage(w, statusCode, feature, message)
+ }
+
expectedHost := purchaseReturnExpectedHost(r, h.cfg)
returnURL := licensePurchaseCallbackURLForRequest(r, h.cfg)
if expectedHost == "" || returnURL == "" {
- http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not open Pulse Account from this instance right now. Retry from this instance in a moment, or use recovery below if you already have a key.",
+ )
return
}
signingKey, err := h.purchaseReturnSigningKey()
if err != nil {
log.Error().Err(err).Msg("Purchase return signing key unavailable")
- http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not prepare the secure Pulse Account handoff for this instance. Retry in a moment, or use recovery below if you already have a key.",
+ )
return
}
@@ -1504,7 +1544,6 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
if orgID == "" {
orgID = "default"
}
- feature := strings.TrimSpace(r.URL.Query().Get(pulseAccountPortalFeatureQueryParam))
returnToken, err := signPurchaseReturnTokenFromLicensing(signingKey, purchaseReturnClaimsModel{
OrgID: orgID,
Feature: feature,
@@ -1513,14 +1552,20 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
})
if err != nil {
log.Error().Err(err).Str("org_id", orgID).Str("feature", feature).Msg("Failed to sign purchase return token")
- http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not prepare the secure Pulse Account handoff for this instance. Retry in a moment, or use recovery below if you already have a key.",
+ )
return
}
activationURLTemplate, err := licensePurchaseActivationTemplateURL(returnURL, returnToken)
if err != nil {
log.Error().Err(err).Str("feature", feature).Msg("Failed to build Pulse Account activation template")
- http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not prepare the secure Pulse Account handoff for this instance. Retry in a moment, or use recovery below if you already have a key.",
+ )
return
}
@@ -1531,13 +1576,19 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
)
if err != nil {
log.Error().Err(err).Str("feature", feature).Msg("Failed to build Pulse Account cancellation return url")
- http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not prepare the secure Pulse Account handoff for this instance. Retry in a moment, or use recovery below if you already have a key.",
+ )
return
}
lsClient := newLicenseServerClientFromLicensing("")
if lsClient == nil {
- http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not contact the commercial service needed to open Pulse Account. Retry in a moment, or use recovery below if you already have a key.",
+ )
return
}
@@ -1547,7 +1598,10 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
}
if purchaseReturnJTI == "" {
log.Error().Str("feature", feature).Msg("Pulse Account purchase return token omitted jti")
- http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not prepare the secure Pulse Account handoff for this instance. Retry in a moment, or use recovery below if you already have a key.",
+ )
return
}
@@ -1559,20 +1613,29 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
})
if err != nil {
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)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not open Pulse Account right now. Retry from this instance in a moment, or use recovery below if you already have a key.",
+ )
return
}
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)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not open Pulse Account right now. Retry from this instance in a moment, or use recovery below if you already have a key.",
+ )
return
}
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)
+ writeUnavailable(
+ http.StatusServiceUnavailable,
+ "Pulse could not open Pulse Account right now. Retry from this instance in a moment, or use recovery below if you already have a key.",
+ )
return
}
diff --git a/internal/api/licensing_handlers_self_hosted_fallback_test.go b/internal/api/licensing_handlers_self_hosted_fallback_test.go
index c99149298f..049a07f73d 100644
--- a/internal/api/licensing_handlers_self_hosted_fallback_test.go
+++ b/internal/api/licensing_handlers_self_hosted_fallback_test.go
@@ -1,117 +1,53 @@
package api
import (
- "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
-func TestLicenseHandlersService_SelfHostedNonDefaultFallbackToDefaultBillingState(t *testing.T) {
- baseDir := t.TempDir()
- mtp := config.NewMultiTenantPersistence(baseDir)
+func TestHandleCheckoutStart_ReopensOwnedBillingWhenPulseAccountHandoffIsUnavailable(t *testing.T) {
+ handler := createTestHandler(t)
+ handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})
- // Ensure persistence roots exist so billing store can read/write cleanly.
- if _, err := mtp.GetPersistence("default"); err != nil {
- t.Fatalf("init default persistence: %v", err)
- }
- if _, err := mtp.GetPersistence("acme"); err != nil {
- t.Fatalf("init acme persistence: %v", err)
- }
-
- store := config.NewFileBillingStore(baseDir)
- err := store.SaveBillingState("default", &pkglicensing.BillingState{
- Capabilities: []string{pkglicensing.FeatureMultiTenant},
- PlanVersion: string(pkglicensing.TierEnterprise),
- SubscriptionState: pkglicensing.SubStateActive,
- })
- if err != nil {
- t.Fatalf("save default billing state: %v", err)
- }
-
- handlers := NewLicenseHandlers(mtp, false)
- ctx := context.WithValue(context.Background(), OrgIDContextKey, "acme")
- service := handlers.Service(ctx)
- if service == nil {
- t.Fatalf("service is nil")
- }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/checkout/portal-handoff" {
+ t.Fatalf("unexpected path %q", r.URL.Path)
+ }
+ http.Error(w, "portal handoff unavailable", http.StatusBadGateway)
+ }))
+ defer server.Close()
+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
- if !service.HasFeature(pkglicensing.FeatureMultiTenant) {
- t.Fatalf("expected non-default org to inherit default org multi_tenant entitlement in self-hosted mode")
- }
-}
+ req := httptest.NewRequest(
+ http.MethodGet,
+ "https://pulse.example.com/auth/license-purchase-start?feature=max_monitored_systems",
+ nil,
+ )
+ rec := httptest.NewRecorder()
-func TestLicenseHandlersService_SelfHostedNonDefaultBillingStateOverridesDefaultFallback(t *testing.T) {
- baseDir := t.TempDir()
- mtp := config.NewMultiTenantPersistence(baseDir)
+ handler.HandleCheckoutStart(rec, req)
- if _, err := mtp.GetPersistence("default"); err != nil {
- t.Fatalf("init default persistence: %v", err)
- }
- if _, err := mtp.GetPersistence("acme"); err != nil {
- t.Fatalf("init acme persistence: %v", err)
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
}
-
- store := config.NewFileBillingStore(baseDir)
- if err := store.SaveBillingState("default", &pkglicensing.BillingState{
- Capabilities: []string{pkglicensing.FeatureMultiTenant},
- PlanVersion: string(pkglicensing.TierEnterprise),
- SubscriptionState: pkglicensing.SubStateActive,
- }); err != nil {
- t.Fatalf("save default billing state: %v", err)
+ body := rec.Body.String()
+ if !strings.Contains(body, "Pulse Account unavailable") {
+ t.Fatalf("body = %q, want unavailable title", body)
}
- if err := store.SaveBillingState("acme", &pkglicensing.BillingState{
- Capabilities: []string{},
- PlanVersion: string(pkglicensing.TierFree),
- SubscriptionState: pkglicensing.SubStateExpired,
- }); err != nil {
- t.Fatalf("save acme billing state: %v", err)
+ if !strings.Contains(body, "window.opener.location.assign") {
+ t.Fatalf("body = %q, want opener billing redirect", body)
}
-
- handlers := NewLicenseHandlers(mtp, false)
- ctx := context.WithValue(context.Background(), OrgIDContextKey, "acme")
- service := handlers.Service(ctx)
- if service == nil {
- t.Fatalf("service is nil")
+ if !strings.Contains(body, "window.location.replace(redirectPath)") {
+ t.Fatalf("body = %q, want same-tab billing fallback", body)
}
-
- if service.HasFeature(pkglicensing.FeatureMultiTenant) {
- t.Fatalf("expected explicit non-default billing state to take precedence over default fallback")
- }
-}
-
-func TestLicenseHandlersService_HostedNonDefaultFallbackToDefaultBillingState(t *testing.T) {
- baseDir := t.TempDir()
- mtp := config.NewMultiTenantPersistence(baseDir)
-
- if _, err := mtp.GetPersistence("default"); err != nil {
- t.Fatalf("init default persistence: %v", err)
- }
- if _, err := mtp.GetPersistence("t-tenant"); err != nil {
- t.Fatalf("init tenant persistence: %v", err)
- }
-
- store := config.NewFileBillingStore(baseDir)
- if err := store.SaveBillingState("default", &pkglicensing.BillingState{
- Capabilities: []string{pkglicensing.FeatureRBAC, pkglicensing.FeatureRelay},
- PlanVersion: "msp_starter",
- SubscriptionState: pkglicensing.SubStateActive,
- }); err != nil {
- t.Fatalf("save default billing state: %v", err)
- }
-
- handlers := NewLicenseHandlers(mtp, true)
- ctx := context.WithValue(context.Background(), OrgIDContextKey, "t-tenant")
- service := handlers.Service(ctx)
- if service == nil {
- t.Fatalf("service is nil")
- }
-
- if service.SubscriptionState() != string(pkglicensing.SubStateActive) {
- t.Fatalf("subscription_state = %q, want %q", service.SubscriptionState(), pkglicensing.SubStateActive)
+ if !strings.Contains(body, "window.close()") {
+ t.Fatalf("body = %q, want popup close bridge", body)
}
- if !service.HasFeature(pkglicensing.FeatureRBAC) {
- t.Fatalf("expected hosted tenant org to inherit default hosted billing state")
+ if !strings.Contains(body, "/settings/system/billing/plan?intent=max_monitored_systems&purchase=unavailable") {
+ t.Fatalf("body = %q, want owned billing unavailable route", body)
}
}
diff --git a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts b/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts
index fedb981885..b3a6b28837 100644
--- a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts
+++ b/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts
@@ -16,6 +16,7 @@ const ACTIVATED_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?in
const CANCELLED_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems&purchase=cancelled`;
const EXPIRED_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems&purchase=expired`;
const FAILED_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems&purchase=failed`;
+const UNAVAILABLE_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems&purchase=unavailable`;
const FINAL_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems`;
const USAGE_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/usage`;
const RECOVERY_BILLING_HREF =
@@ -186,6 +187,16 @@ function renderActivationCompletionPage(title: string, redirectUrl: string): str
);
}
+function renderPurchaseStartFailurePage(message: string, redirectUrl: string): string {
+ return (
+ "<!doctype html><html><body>" +
+ "<h1>Pulse Account unavailable</h1>" +
+ `<p id="purchase-start-status">${message}</p>` +
+ `<script>(function(){var redirectPath=${JSON.stringify(redirectUrl)};var statusEl=document.getElementById('purchase-start-status');var redirectedOriginalTab=false;try{if(window.opener&&!window.opener.closed){redirectedOriginalTab=true;window.opener.location.assign(redirectPath);}}catch(_){redirectedOriginalTab=false;}if(redirectedOriginalTab){setTimeout(function(){try{window.close();}catch(_){ }if(statusEl){statusEl.textContent='Pulse Pro billing has been reopened in the original tab. You can close this window if it stays open.';}},75);return;}if(statusEl){statusEl.textContent='Returning to Pulse Pro billing.';}setTimeout(function(){window.location.replace(redirectPath);},150);}());</script>` +
+ "</body></html>"
+ );
+}
+
async function configurePurchaseStartRoute(
context: BrowserContext,
onRequest?: (requestUrl: URL) => void,
@@ -570,4 +581,64 @@ test.describe("Self-hosted upgrade return flow", () => {
await expect(page).toHaveURL(RECOVERY_BILLING_URL);
await expect(page.locator("#pulse-pro-recovery")).toBeVisible();
});
+
+ test("reopens owned billing when Pulse Account handoff is unavailable", async ({
+ page,
+ }, testInfo) => {
+ test.skip(
+ testInfo.project.name.startsWith("mobile-"),
+ "Desktop-only billing continuity",
+ );
+
+ const context = page.context();
+ await configureBillingFixtures(context, page);
+
+ await context.route(`${PURCHASE_START_URL}**`, async (route) => {
+ const requestUrl = new URL(route.request().url());
+ expect(requestUrl.searchParams.get("feature")).toBe(MONITORED_SYSTEM_FEATURE);
+ await route.fulfill({
+ status: 503,
+ contentType: "text/html",
+ body: renderPurchaseStartFailurePage(
+ "Pulse could not open the Pulse Account upgrade flow right now.",
+ UNAVAILABLE_BILLING_URL,
+ ),
+ });
+ });
+
+ await openMonitoredSystemUpgradeArrival(page);
+
+ const popupPromise = page.waitForEvent("popup");
+ await page.getByRole("link", { name: "Compare plans" }).click();
+ const popup = await popupPromise;
+
+ await expect
+ .poll(async () => {
+ if ((await page.getByText("Pulse Account unavailable", { exact: true }).count()) > 0) {
+ return "page";
+ }
+ if (
+ !popup.isClosed() &&
+ (await popup.getByText("Pulse Account unavailable", { exact: true }).count()) > 0
+ ) {
+ return "popup";
+ }
+ return "none";
+ })
+ .toMatch(/page|popup/);
+
+ const billingSurface =
+ (await page.getByText("Pulse Account unavailable", { exact: true }).count()) > 0
+ ? page
+ : popup;
+
+ await expect(billingSurface).toHaveURL(FINAL_BILLING_URL);
+ await expect(
+ billingSurface.getByText("Pulse Account unavailable", { exact: true }),
+ ).toBeVisible();
+ await expect(billingSurface.getByRole("link", { name: "Try again" })).toHaveAttribute(
+ "href",
+ `${PURCHASE_START_PATH}?feature=max_monitored_systems`,
+ );
+ });
});