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.

commercial: let free installs find Plans & Billing and buy Pro

rcourtmane306ce7b4664
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 56c97ef559..319b8ee1c5 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -2924,6 +2924,12 @@ grant an agent scope, authorize a command channel, or replace live agent
readiness and dispatch admission. Any agent-mediated action still crosses the
existing lifecycle identity, authorization, and receipt boundaries.
+Self-hosted purchase start under shared `internal/api/` (the Plans & Billing
+Buy handoff, including its website-finish path for plain-HTTP installs) is an
+adjacent cloud-paid boundary. It changes no agent install command, registration,
+token or lifecycle state, and lifecycle flows must not surface its purchase
+action.
+
First-run security discovery under shared `internal/api/` is likewise an
adjacent API/security boundary, not an agent-lifecycle discovery surface.
Unauthenticated `/api/security/status` responses must stay on the public tier
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5efd96bc41..3e09582e45 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7292,7 +7292,13 @@ return path. Product-originated upgrade handoffs must include a canonical
commercial-owned `portal_handoff_id` that resolves server-side to the bound
checkout intent. Pulse still binds checkout completion to a signed
`purchase_return_token`, but that token must stay inside the Pulse-owned
-activation callback path rather than leaking into the portal arrival URL. The
+activation callback path rather than leaking into the portal arrival URL.
+When the instance has no secure callback address (plain HTTP on a non-loopback
+address, or no public URL), `/auth/license-purchase-start` mints no return
+token at all: the handoff carries a fresh `web`-prefixed `purchase_return_jti`
+and the website's checkout-result (`thanks.html?session_id=...`) and pricing
+pages as success and cancel targets, so checkout completes on the website and
+the activation key is pasted into Plans & Billing. The
portal runtime must resolve the verified portal handoff through the shared
commercial API and use only that owned handoff-derived checkout state when it
starts checkout instead of trusting browser referrer state, raw
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index aff2540f6a..3be2b3749a 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -1457,16 +1457,23 @@ its estate is, and no estate data crosses the bootstrap.
pricing/checkout, upgrade-metrics, or infrastructure-onboarding analytics
fields, controls, routes, stores, or startup DB artifacts to normal product
users.
-17. Keep ordinary self-hosted v6 commercial surfaces explicitly opt-in under
- the 2026-04-25 posture. Default free self-hosted browser surfaces hide
- paid-feature settings navigation, Plans & Billing navigation, upgrade
- calls to action, trial ceremony, hosted handoff prompts, and proactive
- commercial cards. Direct plan, activation, recovery, and feature-gate
- routes remain available for an operator who deliberately enters that
- context. Hosted sessions and installs with an existing paid, activation,
- or recovery context may expose the corresponding navigation.
- `presentationPolicy.hideUpgrade` is the fail-closed navigation and prompt
- contract. Demo mode and white-label runtimes also force
+17. Keep ordinary self-hosted v6 commercial surfaces quiet, but keep buying
+ findable (2026-10-21, revising the 2026-04-25 opt-in posture). Default
+ free self-hosted browser surfaces hide paid-feature settings navigation,
+ upgrade calls to action, trial ceremony, hosted handoff prompts,
+ proactive commercial cards, and Pro badges on monitoring surfaces. Plans
+ & Billing navigation is listed for every install that does not hide
+ commercial surfaces, and the plan page shows a free install the Pro
+ comparison and its purchase action without requiring an upgrade-prompt
+ arrival; the plan-selection prompt itself stays intent-only. Plan-locked
+ lines inside Settings name the plan and link to Plans & Billing. Before
+ 2026-10-21 free installs had no in-product path to buy at all: Plans &
+ Billing was unlisted, the plan page offered nothing, and the only
+ purchase handoff failed. Direct activation and recovery routes remain
+ available. Hosted sessions and installs with an existing paid,
+ activation, or recovery context may expose the rest of the commercial
+ navigation. `presentationPolicy.hideUpgrade` remains the fail-closed
+ prompt contract for proactive surfaces. Demo mode and white-label runtimes also force
`hideCommercial`, which keeps all commercial surfaces suppressed for demos,
kiosks, and MSP tenant containers. The authenticated app shell must still
skip background `/api/license/commercial-posture` bootstrap while the
@@ -2186,6 +2193,14 @@ selection and paid extras rather than monitored-system-cap expansion. Shared
helpers and route-owned browser symbols should name that commercial state as
plan selection as well; the monitored-system alias belongs only to
backward-compatible handoff normalization and non-commercial usage review.
+When the instance has no secure address to return to (plain HTTP on a LAN
+address, or no public URL), Pulse must not mint or send the purchase return
+token. The start route still creates the handoff, with a fresh
+`web`-prefixed `purchase_return_jti` and the website's checkout-result and
+pricing pages as success and cancel targets, so checkout finishes on the
+website, which shows and emails the activation key for pasting into Plans &
+Billing. Before 2026-10-21 this case failed with the unavailable page, which
+blocked buying from most plain-HTTP homelab installs.
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
@@ -2282,9 +2297,9 @@ Browser and shell coverage now guard that retired boundary:
`tests/integration/scripts/retired-trial-acquisition-contract.sh` must expect `404` from the
retired route and prove entitlements remain unchanged. The paid-prompt browser
proof in `tests/integration/tests/58-self-hosted-trial-rate-limit-ui.spec.ts`
-must keep trial CTAs, hosted handoff prompts, paid-feature navigation, and
-Plans & Billing navigation out of the default free self-hosted UI while keeping
-explicit direct routes available for activation and recovery.
+must keep trial CTAs, hosted handoff prompts and paid-feature navigation out
+of the default free self-hosted UI, while proving Plans & Billing is listed
+and its plan page offers Pro with a purchase action.
`scripts/tests/test-retired-trial-acquisition-docs.sh` guards the same documentation posture
so active operator docs and eval metadata describe the retired route instead of
the old hosted-signup acquisition contract.
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 710512d884..d570a3c51c 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -1796,9 +1796,11 @@ The settings panel registry supplies organisation overview, access and sharing w
Settings navigation discoverability is part of the shared settings-shell
boundary. A settings route that is available in normal commercial presentation
must be reachable through the sidebar unless it is explicitly a hidden
-deep-link flow. Ordinary free self-hosted sessions use the explicit opt-in
-boundary: `system-billing` is hidden from navigation while
-`presentationPolicy.hideUpgrade` is true, and paid-feature items including
+deep-link flow. `system-billing` (Plans & Billing) is listed for every
+session that does not hide commercial surfaces, including ordinary free
+self-hosted sessions, so an operator can find the plan and buy; only demo and
+white-label runtimes hide it. Ordinary free sessions keep the quiet boundary
+for everything proactive: paid-feature items including
`system-relay`, `support-reporting`, `security-roles`, `security-users`,
`security-audit`, and `security-webhooks` use `hideWhenUnavailable`. Their
direct routes remain available because the owning panels still handle explicit
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 79b077b9fc..76f664dd79 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -911,6 +911,12 @@ compression diagnostics, and agent warning behavior remain owned by
reinterpret an accepted large inventory report as backup coverage, recovery
freshness, or restore evidence.
+Self-hosted purchase start under shared `internal/api/`, including the
+website-finish handoff used when an install has no secure callback address, is
+cloud-paid state. It carries no backup, restore or recovery evidence, and
+storage and recovery surfaces must not treat a purchase or activation key as
+recovery readiness.
+
Commercial v5-to-v6 migration posture may be carried by `internal/api/`
handlers that storage/recovery references for setup or support-adjacent flows,
but it remains API/cloud-paid state. Storage and recovery surfaces may point
diff --git a/frontend-modern/src/components/Settings/AISettings.tsx b/frontend-modern/src/components/Settings/AISettings.tsx
index 96052ea0a2..e8d8d3f7fd 100644
--- a/frontend-modern/src/components/Settings/AISettings.tsx
+++ b/frontend-modern/src/components/Settings/AISettings.tsx
@@ -26,10 +26,7 @@ import {
} from '@/features/patrol/patrolAutonomyAvailability';
import { getRuntimeCapabilityBlock, hasFeature, runtimeCapabilities } from '@/stores/license';
import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
-import {
- presentationPolicyHidesCommercialSurfaces,
- presentationPolicyHidesUpgradePrompts,
-} from '@/stores/sessionPresentationPolicy';
+import { presentationPolicyHidesCommercialSurfaces } from '@/stores/sessionPresentationPolicy';
import {
getPatrolCostPresentation,
getPatrolIntervalCostHint,
@@ -104,7 +101,10 @@ const PatrolSettingsContent: Component<{ state: ReturnType<typeof useAISettingsS
getPatrolAutonomyAvailabilityPresentation({
autoFixLocked: !hasFeature('ai_autofix'),
commercialSurfacesHidden: presentationPolicyHidesCommercialSurfaces(),
- upgradePromptsHidden: presentationPolicyHidesUpgradePrompts(),
+ // Settings is where an operator goes looking: plan-locked lines here
+ // always link to Plans & Billing. Demo and white-label runtimes hide
+ // commercial surfaces, which wins inside the presentation.
+ upgradePromptsHidden: false,
runtimeCapabilityBlock: getRuntimeCapabilityBlock('ai_autofix'),
runtime: runtimeCapabilities()?.runtime,
planUpgradeDestination: getUpgradeActionDestination('ai_autofix'),
@@ -115,7 +115,7 @@ const PatrolSettingsContent: Component<{ state: ReturnType<typeof useAISettingsS
getPatrolAlertAnalysisAvailabilityPresentation({
alertAnalysisLocked: props.state.alertAnalysisLocked(),
commercialSurfacesHidden: presentationPolicyHidesCommercialSurfaces(),
- upgradePromptsHidden: presentationPolicyHidesUpgradePrompts(),
+ upgradePromptsHidden: false,
runtimeCapabilityBlock: getRuntimeCapabilityBlock(PATROL_ALERT_ANALYSIS_FEATURE_KEY),
runtime: runtimeCapabilities()?.runtime,
planUpgradeDestination: getUpgradeActionDestination(PATROL_ALERT_ANALYSIS_FEATURE_KEY),
diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
index 79fd97bc5c..e98192e4a8 100644
--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
@@ -382,8 +382,10 @@ describe('AISettings model loading error states', () => {
return document.getElementById(describedBy!)!;
};
- it('explains a plan lock without an upgrade link on a free install', async () => {
+ it('links a plan lock to Plans & Billing on a free install', async () => {
hasFeatureMock.mockImplementation((feature: string) => feature !== 'ai_alerts');
+ // Free installs hide proactive upgrade prompts, but a lock the operator
+ // reads in Settings still says where the plan lives.
presentationPolicyHidesUpgradePromptsMock.mockReturnValue(true);
getSettingsMock.mockResolvedValue(lockedPatrolSettings());
@@ -394,8 +396,8 @@ describe('AISettings model loading error states', () => {
expect(lockExplanation()).toHaveTextContent(
"Higher license plan required. This install's plan does not include container update risk.",
);
- expect(within(lockExplanation()).queryByRole('link')).toBeNull();
- expect(screen.queryByRole('link', { name: 'Plans & Billing' })).toBeNull();
+ const link = within(lockExplanation()).getByRole('link', { name: 'Plans & Billing' });
+ expect(link).toHaveAttribute('href', 'https://example.com/upgrade');
});
it('links Plans & Billing when upgrade prompts are allowed', async () => {
diff --git a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
index 3121bc9ebe..fb1c9987d3 100644
--- a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
@@ -258,7 +258,7 @@ describe('ProLicensePanel', () => {
).not.toBeInTheDocument();
});
- it('keeps the self-hosted billing page non-promotional by default', async () => {
+ it('shows a free install what Pro adds and how to buy it without an upgrade prompt', async () => {
renderPanel();
await waitFor(() => {
@@ -267,11 +267,12 @@ describe('ProLicensePanel', () => {
expect(screen.getByText('Current plan: Community')).toBeInTheDocument();
expect(screen.queryByText(/^Expired$/)).not.toBeInTheDocument();
+ // The plan-selection prompt still belongs to an explicit upgrade arrival.
expect(screen.queryByText('Select a plan')).not.toBeInTheDocument();
- expect(screen.queryByText('Available plans')).not.toBeInTheDocument();
+ expect(screen.getByText('Available plans')).toBeInTheDocument();
expect(screen.queryByText('Relay plan')).not.toBeInTheDocument();
- expect(screen.queryByText('Pulse Pro plan')).not.toBeInTheDocument();
- expect(screen.queryByRole('link', { name: 'View plans' })).not.toBeInTheDocument();
+ expect(screen.getByText('Pulse Pro plan')).toBeInTheDocument();
+ expect(screen.getAllByRole('link', { name: 'View plans' }).length).toBeGreaterThan(0);
});
it('opens compare-plan checkout from the explicit self-hosted billing handoff', async () => {
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 1bdeeb76aa..023b9a991f 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -363,12 +363,14 @@ describe('settings architecture guardrails', () => {
);
expect(pulseIntelligenceNavBlock?.[0]).toContain("id: 'system-billing'");
const systemBillingNavBlock = settingsNavCatalogSource.match(
- /id: 'system-billing',[\s\S]*?hideWhenUpgradeHidden: true,\n\s*},/,
+ /id: 'system-billing',[\s\S]*?hideWhenCommercialHidden: true,\n\s*},/,
);
expect(systemBillingNavBlock?.[0]).toContain(
'label: SELF_HOSTED_PRO_BILLING_PRESENTATION.navLabel',
);
- expect(systemBillingNavBlock?.[0]).toContain('hideWhenUpgradeHidden: true');
+ // Listed for free installs so buying is findable; only demo and
+ // white-label runtimes hide it.
+ expect(systemBillingNavBlock?.[0]).not.toContain('hideWhenUpgradeHidden');
expect(systemBillingNavBlock?.[0]).not.toContain('hideFromSidebar');
const systemNavBlock = settingsNavCatalogSource.match(/id: 'system',[\s\S]*?id: 'support',/);
expect(systemNavBlock?.[0]).not.toContain("id: 'system-billing'");
@@ -1442,9 +1444,9 @@ describe('settings architecture guardrails', () => {
expect(aiSettingsSource).toContain(
'commercialSurfacesHidden: presentationPolicyHidesCommercialSurfaces(),',
);
- expect(aiSettingsSource).toContain(
- 'upgradePromptsHidden: presentationPolicyHidesUpgradePrompts(),',
- );
+ // Plan-locked lines in Settings always say where the plan lives.
+ expect(aiSettingsSource).toContain('upgradePromptsHidden: false,');
+ expect(aiSettingsSource).not.toContain('presentationPolicyHidesUpgradePrompts');
expect(aiSettingsSource).toContain(
'runtimeCapabilityBlock: getRuntimeCapabilityBlock(PATROL_ALERT_ANALYSIS_FEATURE_KEY),',
);
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx b/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
index 4fe7bab100..416dcf8ee8 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
@@ -113,12 +113,12 @@ describe('settingsNavigation integration scaffold', () => {
).toBe(true);
});
- it('keeps self-hosted billing direct-routeable while hiding free default navigation', () => {
+ it('lists self-hosted Plans & Billing for free installs so buying is findable', () => {
expect(deriveTabFromPath('/settings/pulse-intelligence/billing/plan')).toBe('system-billing');
expect(deriveTabFromPath('/settings/system/billing/plan')).toBe('system-billing');
expect(settingsTabPath('system-billing')).toBe('/settings/pulse-intelligence/billing/plan');
expect(getSettingsNavItem('system-billing')?.hideFromSidebar).not.toBe(true);
- expect(getSettingsNavItem('system-billing')?.hideWhenUpgradeHidden).toBe(true);
+ expect(getSettingsNavItem('system-billing')?.hideWhenUpgradeHidden).not.toBe(true);
const freeContext = {
hasFeature: hasFeatures([]),
runtimeCapabilitiesLoaded: () => true,
@@ -126,14 +126,15 @@ describe('settingsNavigation integration scaffold', () => {
presentationPolicyHidesUpgrade: true,
hostedModeEnabled: false,
};
- expect(shouldHideSettingsNavItem('system-billing', freeContext)).toBe(true);
+ expect(shouldHideSettingsNavItem('system-billing', freeContext)).toBe(false);
expect(shouldBlockSettingsRouteItem('system-billing', freeContext)).toBe(false);
+ // Demo and white-label runtimes still hide every commercial surface.
expect(
shouldHideSettingsNavItem('system-billing', {
...freeContext,
- presentationPolicyHidesUpgrade: false,
+ presentationPolicyHidesCommercial: true,
}),
- ).toBe(false);
+ ).toBe(true);
});
it('keeps resource privacy route-backed but out of the normal sidebar', () => {
diff --git a/frontend-modern/src/components/Settings/settingsNavCatalog.ts b/frontend-modern/src/components/Settings/settingsNavCatalog.ts
index a09bb793af..5ec5b106cb 100644
--- a/frontend-modern/src/components/Settings/settingsNavCatalog.ts
+++ b/frontend-modern/src/components/Settings/settingsNavCatalog.ts
@@ -82,8 +82,9 @@ export const SETTINGS_NAV_GROUPS: SettingsNavGroup[] = [
id: 'system-billing',
label: SELF_HOSTED_PRO_BILLING_PRESENTATION.navLabel,
icon: PulseLogoIcon,
+ // Listed for free installs too: it is the one place to see the plan
+ // and buy. Demo and white-label runtimes still hide it.
hideWhenCommercialHidden: true,
- hideWhenUpgradeHidden: true,
},
{
id: 'system-ai-assistant',
diff --git a/frontend-modern/src/components/Settings/useProLicensePanelState.ts b/frontend-modern/src/components/Settings/useProLicensePanelState.ts
index 96120a3f47..95add420d2 100644
--- a/frontend-modern/src/components/Settings/useProLicensePanelState.ts
+++ b/frontend-modern/src/components/Settings/useProLicensePanelState.ts
@@ -394,8 +394,15 @@ export function useProLicensePanelState() {
};
});
const planStatus = createMemo(() => getSelfHostedPlanStatusPresentation(entitlements()));
+ // A free install sees what Pro adds and how to buy it whenever it opens the
+ // plan page, not only when an upgrade prompt sent it here. Paid tiers get no
+ // comparison cards, and nothing renders until the plan state has loaded.
const planComparisonSummary = createMemo(() => {
- if (!showPlanSelectionPrompt()) {
+ if (
+ activeSection() !== 'plan' ||
+ purchaseActivationResult().trim().length > 0 ||
+ !entitlements()
+ ) {
return { cards: [], action: null };
}
const comparison = getSelfHostedPlanComparisonPresentation({
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 6089c12fec..c805cd4efd 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -9905,6 +9905,47 @@ func TestContract_ReleaseDemoFixtureRuntimeGuardrailsRemainCanonical(t *testing.
}
}
+// A plain-HTTP LAN install has no secure callback, so its handoff request is
+// pinned to the website finish: website success and cancel pages and a fresh
+// web-prefixed JTI, with no return token anywhere.
+func TestContract_SelfHostedPurchaseHandoffWebsiteFinishJSON(t *testing.T) {
+ handler := createTestHandler(t)
+ var raw map[string]any
+ 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)
+ }
+ if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {
+ t.Fatalf("decode checkout portal handoff request: %v", err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"portal_handoff_id": "cph_web_finish"})
+ }))
+ defer server.Close()
+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
+
+ req := httptest.NewRequest(http.MethodGet, "http://10.0.0.7:7655"+licensePurchaseStartPath+"?feature=self_hosted_plan", nil)
+ req.Host = "10.0.0.7:7655"
+ req.RemoteAddr = "10.0.0.20:40000"
+ rec := httptest.NewRecorder()
+
+ handler.HandleCheckoutStart(rec, req)
+
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusSeeOther, rec.Body.String())
+ }
+ jti, _ := raw["purchase_return_jti"].(string)
+ if len(raw) != 4 || raw["feature"] != "self_hosted_plan" ||
+ raw["success_url"] != "https://pulserelay.pro/thanks.html?session_id={CHECKOUT_SESSION_ID}" ||
+ raw["cancel_url"] != "https://pulserelay.pro/pricing" ||
+ !strings.HasPrefix(jti, "web") || len(jti) != 35 {
+ t.Fatalf("website-finish handoff request = %#v", raw)
+ }
+ if strings.Contains(rec.Header().Get("Location"), licensePurchaseReturnTokenField) {
+ t.Fatalf("redirect %q must not carry a return token", rec.Header().Get("Location"))
+ }
+}
+
func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {
handler := createTestHandler(t)
handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})
@@ -10153,45 +10194,6 @@ func TestContract_SelfHostedPurchaseActivationBridgeCopyStaysPlanOwned(t *testin
assertJSONSnapshot(t, got, want)
}
-func TestContract_SelfHostedPurchaseHandoffRejectsInsecureNonLoopbackCallbackURL(t *testing.T) {
- handler := createTestHandler(t)
-
- req := httptest.NewRequest(
- http.MethodGet,
- "http://192.168.1.25:7655"+licensePurchaseStartPath+"?feature=max_monitored_systems",
- nil,
- )
- req.Host = "192.168.1.25:7655"
- req.RemoteAddr = "192.168.1.50:54321"
- rec := httptest.NewRecorder()
-
- handler.HandleCheckoutStart(rec, req)
-
- got, err := json.MarshalIndent(struct {
- StatusCode int `json:"status_code"`
- TitlePresent bool `json:"title_present"`
- SecureFailureMessage bool `json:"secure_failure_message"`
- OwnedRedirectPath bool `json:"owned_redirect_path"`
- }{
- StatusCode: rec.Code,
- TitlePresent: strings.Contains(rec.Body.String(), "Pulse Account unavailable"),
- SecureFailureMessage: strings.Contains(rec.Body.String(), "Pulse could not open Pulse Account from this instance right now"),
- OwnedRedirectPath: strings.Contains(rec.Body.String(), "/settings/system/billing/plan?intent=self_hosted_plan&purchase=unavailable"),
- }, "", "\t")
- if err != nil {
- t.Fatalf("marshal insecure handoff snapshot: %v", err)
- }
-
- const want = `{
- "status_code": 503,
- "title_present": true,
- "secure_failure_message": 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/license_handlers_test.go b/internal/api/license_handlers_test.go
index f8e86eb2eb..9794c042ed 100644
--- a/internal/api/license_handlers_test.go
+++ b/internal/api/license_handlers_test.go
@@ -845,12 +845,33 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *tes
}
}
-func TestHandleCheckoutStart_FailsClosedOnInsecureNonLoopbackCallbackURL(t *testing.T) {
+// A plain-HTTP install on a LAN address has no secure place to receive the
+// signed return token, so the token is never minted for it. Checkout still
+// opens, and finishes on the website, which shows and emails the key.
+func TestHandleCheckoutStart_InsecureNonLoopbackFinishesOnWebsite(t *testing.T) {
handler := createTestHandler(t)
+ var capturedReq struct {
+ 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/portal-handoff" || r.Method != http.MethodPost {
+ t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
+ }
+ if err := json.NewDecoder(r.Body).Decode(&capturedReq); err != nil {
+ t.Fatalf("decode checkout portal handoff request: %v", err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"portal_handoff_id": "cph_lan_http"})
+ }))
+ defer server.Close()
+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
req := httptest.NewRequest(
http.MethodGet,
- "http://192.168.1.25:7655/auth/license-purchase-start?feature=relay",
+ "http://192.168.1.25:7655/auth/license-purchase-start?feature=self_hosted_plan",
nil,
)
req.Host = "192.168.1.25:7655"
@@ -859,11 +880,30 @@ func TestHandleCheckoutStart_FailsClosedOnInsecureNonLoopbackCallbackURL(t *test
handler.HandleCheckoutStart(rec, req)
- if rec.Code != http.StatusServiceUnavailable {
- t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusSeeOther, rec.Body.String())
+ }
+ redirectURL, err := url.Parse(rec.Header().Get("Location"))
+ if err != nil {
+ t.Fatalf("parse redirect location: %v", err)
+ }
+ if redirectURL.Host != "license.pulserelay.pro" || redirectURL.Path != "/buy" ||
+ redirectURL.Query().Get("portal_handoff_id") != "cph_lan_http" {
+ t.Fatalf("redirect location = %q, want licence server purchase page for the handoff", redirectURL)
+ }
+ if capturedReq.SuccessURL != licensePurchaseWebsiteSuccessURL || capturedReq.CancelURL != licensePurchaseWebsiteCancelURL {
+ t.Fatalf("success_url = %q cancel_url = %q, want website finish", capturedReq.SuccessURL, capturedReq.CancelURL)
+ }
+ for _, value := range []string{capturedReq.SuccessURL, capturedReq.CancelURL, rec.Header().Get("Location")} {
+ if strings.Contains(value, licensePurchaseReturnTokenField) || strings.Contains(value, "192.168.1.25") {
+ t.Fatalf("%q must not carry a return token or the plain-HTTP instance address", value)
+ }
+ }
+ if !strings.HasPrefix(capturedReq.PurchaseReturnJTI, "web") || len(capturedReq.PurchaseReturnJTI) != 35 {
+ t.Fatalf("purchase_return_jti = %q, want a fresh website handoff id", capturedReq.PurchaseReturnJTI)
}
- if !strings.Contains(rec.Body.String(), "Pulse could not open Pulse Account from this instance right now") {
- t.Fatalf("body = %q, want secure callback failure message", rec.Body.String())
+ if capturedReq.Feature != "self_hosted_plan" {
+ t.Fatalf("feature = %q, want self_hosted_plan", capturedReq.Feature)
}
}
diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.go
index 861595932b..5202d4a8bd 100644
--- a/internal/api/licensing_handlers.go
+++ b/internal/api/licensing_handlers.go
@@ -2,6 +2,8 @@ package api
import (
"context"
+ cryptorand "crypto/rand"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -42,6 +44,13 @@ const (
purchaseReturnKeyPurpose = "pulse-license-purchase-return"
)
+// Where checkout finishes when this instance has no secure address to return
+// to: the website shows the activation key and emails it.
+const (
+ licensePurchaseWebsiteSuccessURL = "https://pulserelay.pro/thanks.html?session_id={CHECKOUT_SESSION_ID}"
+ licensePurchaseWebsiteCancelURL = "https://pulserelay.pro/pricing"
+)
+
func wantsMockFixturesFromEnv() bool {
return strings.EqualFold(strings.TrimSpace(os.Getenv("PULSE_MOCK_MODE")), "true")
}
@@ -1079,66 +1088,9 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
writeLicensePurchaseStartFailurePage(w, statusCode, feature, message)
}
- expectedHost := purchaseReturnExpectedHost(r, h.cfg)
- returnURL := licensePurchaseCallbackURLForRequest(r, h.cfg)
- if expectedHost == "" || returnURL == "" {
- 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")
- 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
- }
-
- orgID := strings.TrimSpace(GetOrgID(r.Context()))
- if orgID == "" {
- orgID = "default"
- }
- returnToken, err := signPurchaseReturnTokenFromLicensing(signingKey, purchaseReturnClaimsModel{
- OrgID: orgID,
- Feature: feature,
- InstanceHost: expectedHost,
- ReturnURL: returnURL,
- })
- if err != nil {
- log.Error().Err(err).Str("org_id", orgID).Str("feature", feature).Msg("Failed to sign purchase return token")
- 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")
- 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
- }
-
- cancelURL, err := publicAbsoluteURLForPath(
- r,
- h.cfg,
- licensePurchaseActivationRedirectPath(feature, selfHostedBillingPurchaseCancelled),
- )
- if err != nil {
- log.Error().Err(err).Str("feature", feature).Msg("Failed to build Pulse Account cancellation return url")
- 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.",
- )
+ successURL, cancelURL, purchaseReturnJTI, failure := h.purchaseHandoffTargets(r, feature)
+ if failure != "" {
+ writeUnavailable(http.StatusServiceUnavailable, failure)
return
}
@@ -1151,22 +1103,9 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
return
}
- 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")
- 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
- }
-
portalHandoff, err := lsClient.CreateCheckoutPortalHandoff(r.Context(), checkoutPortalHandoffRequestModel{
Feature: feature,
- SuccessURL: activationURLTemplate,
+ SuccessURL: successURL,
CancelURL: cancelURL,
PurchaseReturnJTI: purchaseReturnJTI,
})
@@ -1201,6 +1140,74 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Req
http.Redirect(w, r, destination, http.StatusSeeOther)
}
+// purchaseHandoffTargets returns where checkout sends the buyer afterwards,
+// plus the purchase return JTI bound to the handoff. With a secure address for
+// this instance, success returns here with a signed return token so the plan
+// activates itself. Without one (plain HTTP on a LAN address, or no public
+// URL), the token must not travel over plain HTTP, so checkout finishes on the
+// website instead: it shows and emails the activation key, which the operator
+// pastes into Plans & Billing. A non-empty failure is the operator message.
+func (h *LicenseHandlers) purchaseHandoffTargets(r *http.Request, feature string) (successURL, cancelURL, purchaseReturnJTI, failure string) {
+ const prepareFailure = "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."
+
+ expectedHost := purchaseReturnExpectedHost(r, h.cfg)
+ returnURL := licensePurchaseCallbackURLForRequest(r, h.cfg)
+ if expectedHost == "" || returnURL == "" {
+ nonce := make([]byte, 16)
+ if _, err := cryptorand.Read(nonce); err != nil {
+ log.Error().Err(err).Str("feature", feature).Msg("Failed to create website purchase handoff id")
+ return "", "", "", prepareFailure
+ }
+ return licensePurchaseWebsiteSuccessURL, licensePurchaseWebsiteCancelURL, "web" + hex.EncodeToString(nonce), ""
+ }
+
+ signingKey, err := h.purchaseReturnSigningKey()
+ if err != nil {
+ log.Error().Err(err).Msg("Purchase return signing key unavailable")
+ return "", "", "", prepareFailure
+ }
+
+ orgID := strings.TrimSpace(GetOrgID(r.Context()))
+ if orgID == "" {
+ orgID = "default"
+ }
+ returnToken, err := signPurchaseReturnTokenFromLicensing(signingKey, purchaseReturnClaimsModel{
+ OrgID: orgID,
+ Feature: feature,
+ InstanceHost: expectedHost,
+ ReturnURL: returnURL,
+ })
+ if err != nil {
+ log.Error().Err(err).Str("org_id", orgID).Str("feature", feature).Msg("Failed to sign purchase return token")
+ return "", "", "", prepareFailure
+ }
+
+ successURL, err = licensePurchaseActivationTemplateURL(returnURL, returnToken)
+ if err != nil {
+ log.Error().Err(err).Str("feature", feature).Msg("Failed to build Pulse Account activation template")
+ return "", "", "", prepareFailure
+ }
+
+ cancelURL, err = publicAbsoluteURLForPath(
+ r,
+ h.cfg,
+ licensePurchaseActivationRedirectPath(feature, selfHostedBillingPurchaseCancelled),
+ )
+ if err != nil {
+ log.Error().Err(err).Str("feature", feature).Msg("Failed to build Pulse Account cancellation return url")
+ return "", "", "", prepareFailure
+ }
+
+ 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")
+ return "", "", "", prepareFailure
+ }
+ return successURL, cancelURL, purchaseReturnJTI, ""
+}
+
// HandleCheckoutActivation handles the local checkout return at
// /auth/license-purchase-activate. GET renders the auto-submitting bridge for
// a completed Stripe redirect, while POST redeems the completed session into a
diff --git a/tests/integration/tests/58-self-hosted-trial-rate-limit-ui.spec.ts b/tests/integration/tests/58-self-hosted-trial-rate-limit-ui.spec.ts
index 6fd572972c..dc288f937d 100644
--- a/tests/integration/tests/58-self-hosted-trial-rate-limit-ui.spec.ts
+++ b/tests/integration/tests/58-self-hosted-trial-rate-limit-ui.spec.ts
@@ -90,7 +90,8 @@ test.describe.serial('Self-hosted paid prompt visibility', () => {
await expect(page.getByRole('button', { name: 'Users' })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Audit Log' })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Audit Webhooks' })).toHaveCount(0);
- await expect(page.getByRole('button', { name: 'Plans & Billing' })).toHaveCount(0);
+ // Plans & Billing is listed so a free install can find the plan and buy.
+ await expect(page.getByRole('button', { name: 'Plans & Billing' })).toBeVisible();
await expect(page.getByRole('link', { name: /upgrade to pro/i })).toHaveCount(0);
await expect(page.getByRole('button', { name: /start free trial/i })).toHaveCount(0);
await expect(page.getByRole('button', { name: /start trial/i })).toHaveCount(0);
@@ -102,14 +103,13 @@ test.describe.serial('Self-hosted paid prompt visibility', () => {
});
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.getByRole('heading', { level: 1, name: 'Roles' })).toBeVisible();
- await expect(page.getByRole('button', { name: 'Plans & Billing' })).toHaveCount(0);
await page.screenshot({
path: testInfo.outputPath('free-default-settings-narrow.png'),
fullPage: true,
});
});
- test('keeps the Plans & Billing direct route available as an explicit opt-in surface', async ({
+ test('offers Pro on the Plans & Billing page of a free install', async ({
page,
}, testInfo) => {
test.skip(
@@ -122,7 +122,9 @@ test.describe.serial('Self-hosted paid prompt visibility', () => {
await page.goto('/settings/pulse-intelligence/billing/plan');
await expect(page.getByRole('heading', { name: 'Plans & Billing' }).first()).toBeVisible();
- await expect(page.getByRole('button', { name: 'Plans & Billing' })).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Plans & Billing' })).toBeVisible();
+ await expect(page.getByText('Pulse Pro plan')).toBeVisible();
+ await expect(page.getByRole('link', { name: 'View plans' }).first()).toBeVisible();
await page.screenshot({
path: testInfo.outputPath('free-explicit-billing-route.png'),
fullPage: true,