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
Split commercial posture from billing entitlements
rcourtmancc5ee2e24c7f
diff --git a/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md b/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.mdindex 4e8eadbcac..48df90f4d6 100644--- a/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md+++ b/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md@@ -464,7 +464,10 @@ Accepted as sufficient for RC and GA:billing, with `Pulse Account` owning self-hosted plan comparison andcheckout for those arrivals4. purchase completion may return directly into Pulse billing activation- instead of requiring manual copy/paste of a newly issued license key+ instead of requiring manual copy/paste of a newly issued license key, with+ Pulse accepting a signed instance-bound return token and returning either+ the originating billing tab or the current tab fallback to the owned+ billing route automatically5. commercial surfaces are functional but still fragmented outside the ownedcheckout-return pathdiff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex b93137f5b7..34baf146a4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -315,9 +315,11 @@ headers, `/api/health`, or hostname heuristics.That same shared API boundary now owns the hidden-versus-runtime-only split aswell: lifecycle-adjacent flows may inherit non-commercial`/api/license/runtime-capabilities` reads when demo-visible product behavior-needs them, but `/api/license/entitlements` stays hidden in public demo mode-and those lifecycle flows must not depend on licensed identity, plan labels,-upgrade reasons, or observed usage counts surviving the public-demo contract.+needs them, but `/api/license/commercial-posture`,+`/api/license/entitlements`, and `/auth/license-purchase-start` stay hidden in+public demo mode and those lifecycle flows must not depend on licensed+identity, plan labels, upgrade reasons, checkout handoff state, or observed+usage counts surviving the public-demo contract.Lifecycle-adjacent storage and fleet surfaces now also depend on one governedphysical-disk history transport. When agent-backed disk telemetry is renderedthrough shared drawers or lifecycle-adjacent resource context, those readsdiff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 2118ca8cbd..4c0838cc8e 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -537,7 +537,7 @@ because alerts surfaces must remain lazy-load safe and must not blank the appbefore auth/bootstrap finishes.Alert commercial handoffs now also follow the runtime-versus-commercial split.`frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx` may resolve-upgrade destinations through the shared commercial store, but alert runtime-availability and chat enablement must stay governed by the non-commercial app-runtime and assistant state instead of reusing the same commercial payload as-feature truth.+upgrade destinations through the shared commercial-posture store, but alert+runtime availability and chat enablement must stay governed by the+non-commercial app runtime and assistant state instead of reusing the same+commercial payload as feature truth.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 89f9a43e00..56471a2755 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -220,10 +220,12 @@ Own canonical runtime payload shapes between backend and frontend.`internal/api/subscription_entitlements.go`, and`internal/api/contract_test.go` must classify commercial routes centrallyas either hidden (`404`) or runtime-safe. Public demo browsers may read the- non-commercial `/api/license/runtime-capabilities` contract, while- `/api/license/entitlements` stays hidden and must not be relied on for- runtime feature truth, upgrade prompts, trial nudges, usage counts, or plan- metadata.+ non-commercial `/api/license/runtime-capabilities` contract for feature+ truth, while `/api/license/commercial-posture`,+ `/api/license/entitlements`, and `/auth/license-purchase-start` stay+ hidden. Upgrade prompts, trial nudges, monitored-system migration guidance,+ usage counts, billing identity, and plan metadata must therefore not depend+ on hidden commercial routes surviving the public demo boundary.## Forbidden Paths@@ -506,9 +508,14 @@ hosted-only account that only arrived through an upgrade CTA.That same commercial contract now also includes the self-hosted purchasereturn path. Product-originated upgrade handoffs must include a canonical`return_url` that points back to Pulse's public `POST /auth/license-purchase-activate`-callback, and that callback must redeem the completed checkout through the-shared license/commercial API before redirecting the browser back to the-owned billing plan route.+callback plus a signed `purchase_return_token` bound to the originating Pulse+instance, and that callback must redeem the completed checkout through the+shared license/commercial API before returning the browser to the owned+billing plan route. 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+success page.That same typed bootstrap/runtime contract must also derive the default signed-in shell section from account shape: hosted accounts open on `Workspaces`,self-hosted-only accounts open on `Billing`, and the signed-in shell keeps@@ -2305,10 +2312,11 @@ provider bridges purely to satisfy Patrol once the Patrol runtime can operatefrom those canonical tenant providers directly.Hosted licensing handlers now also carry a tenant-scoped fallback contract:when hosted auth handoff preserves a non-default tenant org like `t-...`,-`/api/license/status`, `/api/license/entitlements`, and-`/api/license/runtime-capabilities` must still evaluate the instance-level-hosted billing lease from `default` if that tenant org has no org-local-billing state of its own, rather than failing closed into+`/api/license/status`, `/api/license/commercial-posture`,+`/api/license/entitlements`, and `/api/license/runtime-capabilities` must+still evaluate the instance-level hosted billing lease from `default` if that+tenant org has no org-local billing state of its own, rather than failing+closed into`subscription_required` on first entry.That same hosted entitlement contract also owns lease refresh targeting:when a hosted tenant request arrives on a non-default org with no org-localdiff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 8adb959a51..4e77b6034a 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -37,50 +37,51 @@ agreement, and cloud-specific enforcement rules.15. `pkg/licensing/persistence.go`16. `pkg/licensing/activation_store.go`17. `pkg/licensing/trial_activation.go`-18. `pkg/licensing/stripe_subscription.go`-19. `pkg/licensing/monitored_system_limit.go`-20. `internal/cloudcp/account/tenant_handlers.go`-21. `internal/cloudcp/config.go`-22. `internal/cloudcp/entitlements/service.go`-23. `internal/cloudcp/portal/handlers.go`-24. `internal/cloudcp/portal/page.go`-25. `internal/cloudcp/public_cloud_signup_handlers.go`-26. `internal/cloudcp/registry/registry.go`-27. `internal/cloudcp/routes.go`-28. `internal/cloudcp/stripe/provisioner.go`-29. `internal/hosted/provisioner.go`-30. `frontend-modern/src/App.tsx`-31. `frontend-modern/src/AppLayout.tsx`-32. `frontend-modern/src/useAppRuntimeState.ts`-33. `frontend-modern/src/components/Dashboard/RelayOnboardingCard.tsx`-34. `frontend-modern/src/components/Dashboard/useRelayOnboardingCardState.ts`-35. `frontend-modern/src/components/Commercial/MonitoredSystemDefinitionDisclosure.tsx`-36. `frontend-modern/src/components/Settings/BillingAdminPanel.tsx`-37. `frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx`-38. `frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx`-39. `frontend-modern/src/components/Settings/OrganizationBillingLoadingState.tsx`-40. `frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx`-41. `frontend-modern/src/components/Settings/ProLicensePanel.tsx`-42. `frontend-modern/src/components/Settings/ProLicensePlanSection.tsx`-43. `frontend-modern/src/components/Settings/CommercialBillingSections.tsx`-44. `frontend-modern/src/components/Settings/SelfHostedCommercialActivationSection.tsx`-45. `frontend-modern/src/components/Settings/RelaySettingsPanel.tsx`-46. `frontend-modern/src/components/Settings/RelayPairingSection.tsx`-47. `frontend-modern/src/components/Settings/useBillingAdminPanelState.ts`-48. `frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts`-49. `frontend-modern/src/components/Settings/useProLicensePanelState.ts`-50. `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`-51. `frontend-modern/src/pages/CloudPricing.tsx`-52. `frontend-modern/src/pages/HostedSignup.tsx`-53. `frontend-modern/src/pages/PricingHandoff.tsx`-54. `frontend-modern/src/utils/apiClient.ts`-55. `frontend-modern/src/utils/cloudPlans.ts`-56. `frontend-modern/src/utils/commercialBillingModel.ts`-57. `frontend-modern/src/utils/licensePresentation.ts`-58. `frontend-modern/src/utils/monitoredSystemPresentation.ts`-59. `frontend-modern/src/utils/pricingHandoff.ts`-60. `frontend-modern/src/utils/selfHostedPlans.ts`-61. `frontend-modern/src/utils/upgradePresentation.ts`+18. `pkg/licensing/purchase_return.go`+19. `pkg/licensing/stripe_subscription.go`+20. `pkg/licensing/monitored_system_limit.go`+21. `internal/cloudcp/account/tenant_handlers.go`+22. `internal/cloudcp/config.go`+23. `internal/cloudcp/entitlements/service.go`+24. `internal/cloudcp/portal/handlers.go`+25. `internal/cloudcp/portal/page.go`+26. `internal/cloudcp/public_cloud_signup_handlers.go`+27. `internal/cloudcp/registry/registry.go`+28. `internal/cloudcp/routes.go`+29. `internal/cloudcp/stripe/provisioner.go`+30. `internal/hosted/provisioner.go`+31. `frontend-modern/src/App.tsx`+32. `frontend-modern/src/AppLayout.tsx`+33. `frontend-modern/src/useAppRuntimeState.ts`+34. `frontend-modern/src/components/Dashboard/RelayOnboardingCard.tsx`+35. `frontend-modern/src/components/Dashboard/useRelayOnboardingCardState.ts`+36. `frontend-modern/src/components/Commercial/MonitoredSystemDefinitionDisclosure.tsx`+37. `frontend-modern/src/components/Settings/BillingAdminPanel.tsx`+38. `frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx`+39. `frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx`+40. `frontend-modern/src/components/Settings/OrganizationBillingLoadingState.tsx`+41. `frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx`+42. `frontend-modern/src/components/Settings/ProLicensePanel.tsx`+43. `frontend-modern/src/components/Settings/ProLicensePlanSection.tsx`+44. `frontend-modern/src/components/Settings/CommercialBillingSections.tsx`+45. `frontend-modern/src/components/Settings/SelfHostedCommercialActivationSection.tsx`+46. `frontend-modern/src/components/Settings/RelaySettingsPanel.tsx`+47. `frontend-modern/src/components/Settings/RelayPairingSection.tsx`+48. `frontend-modern/src/components/Settings/useBillingAdminPanelState.ts`+49. `frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts`+50. `frontend-modern/src/components/Settings/useProLicensePanelState.ts`+51. `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`+52. `frontend-modern/src/pages/CloudPricing.tsx`+53. `frontend-modern/src/pages/HostedSignup.tsx`+54. `frontend-modern/src/pages/PricingHandoff.tsx`+55. `frontend-modern/src/utils/apiClient.ts`+56. `frontend-modern/src/utils/cloudPlans.ts`+57. `frontend-modern/src/utils/commercialBillingModel.ts`+58. `frontend-modern/src/utils/licensePresentation.ts`+59. `frontend-modern/src/utils/monitoredSystemPresentation.ts`+60. `frontend-modern/src/utils/pricingHandoff.ts`+61. `frontend-modern/src/utils/selfHostedPlans.ts`+62. `frontend-modern/src/utils/upgradePresentation.ts`## Shared Boundaries@@ -101,7 +102,9 @@ agreement, and cloud-specific enforcement rules.8. Add or change activation/grant lifecycle or dev-mode capability widening through `pkg/licensing/dev_mode_features.go`, `pkg/licensing/service.go`, `pkg/licensing/grant_refresh.go`, and `pkg/licensing/revocation_poll.go`9. Add or change license-server transport through `pkg/licensing/license_server_client.go` and `pkg/licensing/quickstart_bootstrap.go`10. Add or change encrypted activation persistence through `pkg/licensing/persistence.go` and `pkg/licensing/activation_store.go`-11. Add or change hosted trial token semantics through `pkg/licensing/trial_activation.go`+11. Add or change hosted trial or self-hosted purchase-return token semantics+ through `pkg/licensing/trial_activation.go` and+ `pkg/licensing/purchase_return.go`12. Add or change hosted signup provisioning through `internal/hosted/provisioner.go`13. Add or change hosted billing-admin presentation through `frontend-modern/src/components/Settings/BillingAdminPanel.tsx`, `frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx`, and `frontend-modern/src/components/Settings/useBillingAdminPanelState.ts`14. Add or change shared commercial plan/usage presentation through `frontend-modern/src/components/Settings/CommercialBillingSections.tsx` and `frontend-modern/src/utils/commercialBillingModel.ts`@@ -174,13 +177,16 @@ classification. `internal/api/demo_middleware.go` and`internal/api/demo_mode_commercial.go` must decide centrally which commercialendpoints are fully hidden (`404`) and which remain available only as anon-commercial public contract. `/api/license/runtime-capabilities` is the-canonical public exception: it may carry capability and history-retention-fields needed for demo-visible product behavior, but-`/api/license/entitlements` must stay hidden and public browsers must not see-licensed identity, plan labels, upgrade reasons, trial urgency, or observed-usage counts. The commercial store must also fail closed locally in demo mode-so hidden routes are not probed from the browser shell. The governed browser-proof for that posture lives in+canonical public exception for feature truth and history retention.+`/api/license/commercial-posture` is the canonical non-billing commercial+contract for upgrade/trial posture in real customer workspaces, while+`/api/license/entitlements` remains billing-only. In public demo mode both+commercial routes, plus `/auth/license-purchase-start`, must stay hidden and+public browsers must not see licensed identity, plan labels, upgrade reasons,+trial urgency, observed usage counts, or checkout handoff state. The+commercial posture store and billing-entitlements store must also fail closed+locally in demo mode so hidden routes are not probed from the browser shell.+The governed browser proof for that posture lives in`tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts` and isexpected to stay runnable through`tests/integration/scripts/run-tests.sh demo-contract`.@@ -417,7 +423,12 @@ checkout-session creation, and the purchase return handoff back into Pulse via`/auth/license-purchase-activate`; Pulse itself must not render a secondpublic pricing surface inside the runtime, and the authenticated portal shellmust not collapse back into a public-site-only waystation for new-purchase-depth.+depth. That handoff now starts through Pulse-owned `GET /auth/license-purchase-start`,+which mints a signed `purchase_return_token` for the local instance before the+browser leaves for `Pulse Account`. The owned activation callback must accept+that signed state, redeem the completed checkout, and return the operator to+the canonical billing plan route automatically whether checkout completed in a+secondary tab or in the current tab fallback path.That destination split is canonical commercial truth, but navigation semanticsare not owned here. `frontend-modern/src/utils/pricingHandoff.ts` and`frontend-modern/src/stores/license.ts` decide which href each commercialdiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex f5f3787624..96ba4cfe35 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -654,8 +654,10 @@ notification flow, or customer-facing system-log copy back into the panelrender shell.Shared trial CTA handling is now part of that same primitive boundary forsettings and shared paywalls. Shared/settings runtime owners must derive trial-eligibility from the canonical entitlements payload, including-`trial_eligible`, and route operator-facing failure copy through+eligibility and upgrade posture from the canonical commercial-posture+contract, including `trial_eligible`, while billing identity and plan detail+stay on the billing-only entitlements contract. Shared/settings runtime owners+must route operator-facing failure copy through`frontend-modern/src/utils/upgradePresentation.ts`. The trial-start runtimehandoff itself is now centralized in`frontend-modern/src/utils/trialStartAction.ts`; settings/shared paywalls anddiff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.mdindex 61d6f4f5c0..398723ba97 100644--- a/docs/release-control/v6/internal/subsystems/organization-settings.md+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md@@ -184,6 +184,7 @@ lane-local `startProTrial()` branch once that shared helper covers the sameruntime contract.That same RBAC paywall surface now also depends on the runtime-versus-commercial license split: RBAC enablement must stay on the runtime capability-store, while free-trial eligibility and upgrade routing stay on the commercial-store. Organization settings must not collapse those two concerns back into-one payload just because the same paywall shell renders both.+store, while free-trial eligibility and upgrade routing stay on the canonical+commercial-posture store backed by `/api/license/commercial-posture`.+Organization settings must not collapse those two concerns back into one+payload just because the same paywall shell renders both.diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex eeb8d8fe09..938fe8596d 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -595,5 +595,5 @@ TrueNAS.Patrol upgrade and trial posture now follows the same runtime-versus-commercial split as the rest of the app. Patrol runtime availability must stayon the non-commercial capability store, while approval/trial CTAs use the-shared commercial store and trial-start helper. Patrol surfaces must not+shared commercial-posture store and trial-start helper. Patrol surfaces must notrecombine those two contracts into one entitlement payload.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 67eab6d36e..eea2f56152 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -705,5 +705,6 @@ create a reverse dependency into the root shell just to read websocket state.The same hot-path discipline now applies to public-demo commercial reads.Shared shells may consume the small `/api/license/runtime-capabilities`contract for feature truth, but commercial demo routes stay hidden and the-browser must not keep retrying `/api/license/entitlements` or other hidden+browser must not keep retrying `/api/license/commercial-posture`,+`/api/license/entitlements`, `/auth/license-purchase-start`, or other hiddencommercial endpoints from performance-sensitive settings or dashboard shells.diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 7640be7c54..144581e5fa 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -1989,6 +1989,19 @@"pkg/licensing/upgrade_test.go"]},+ {+ "id": "purchase-return-handoff",+ "label": "purchase return handoff proof",+ "match_prefixes": [],+ "match_files": [+ "pkg/licensing/purchase_return.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "pkg/licensing/purchase_return_test.go"+ ]+ },{"id": "conversion-telemetry-pipeline","label": "conversion telemetry pipeline proof",diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex c9a7423b24..00b3ae76d6 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -329,9 +329,11 @@ public-demo bootstrap signal instead of inferring demo posture from headers,That same shared boundary now also owns the one runtime-safe exception:storage and recovery may inherit demo-safe `/api/license/runtime-capabilities`reads for capability and history-retention truth, but-`/api/license/entitlements` stays hidden and those surfaces must not expect-licensed identity, upgrade prompts, trial urgency, or observed usage counts-to remain present once the public-demo contract is applied.+`/api/license/commercial-posture`, `/api/license/entitlements`, and+`/auth/license-purchase-start` stay hidden and those surfaces must not expect+licensed identity, upgrade prompts, trial urgency, checkout handoff state, or+observed usage counts to remain present once the public-demo contract is+applied.Physical-disk live I/O drawers now also sit on the canonical storage surface.Storage disk drawers may show read, write, busy, and SMART history, but everychart must route through the shared `HistoryChart` API contract using the diskdiff --git a/frontend-modern/src/AppLayout.tsx b/frontend-modern/src/AppLayout.tsxindex e11d0b3791..0d8e599989 100644--- a/frontend-modern/src/AppLayout.tsx+++ b/frontend-modern/src/AppLayout.tsx@@ -43,7 +43,7 @@ import { demoModeEnabled } from '@/stores/demoMode';import { isMultiTenantEnabled } from '@/stores/license';import {isPro,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import type { AppConnectionStatus } from '@/useAppRuntimeState';@@ -180,7 +180,7 @@ export function AppLayout(props: AppLayoutProps) {onMount(() => {if (!demoModeEnabled()) {- void loadCommercialLicenseStatus();+ void loadCommercialPosture();}});diff --git a/frontend-modern/src/__tests__/App.architecture.test.ts b/frontend-modern/src/__tests__/App.architecture.test.tsindex 8c2648ee32..165e5f026c 100644--- a/frontend-modern/src/__tests__/App.architecture.test.ts+++ b/frontend-modern/src/__tests__/App.architecture.test.ts@@ -55,11 +55,9 @@ describe('App architecture', () => {expect(appLayoutSource).not.toContain('props.connected()');expect(appLayoutSource).toContain('const utilityTabs = createMemo(() =>');expect(appLayoutSource).toContain("import { isMultiTenantEnabled } from '@/stores/license';");- expect(appLayoutSource).toContain(- "loadLicenseStatus as loadCommercialLicenseStatus",- );+ expect(appLayoutSource).toContain("loadCommercialPosture");expect(appLayoutSource).toContain('if (!demoModeEnabled()) {');- expect(appLayoutSource).toContain('void loadCommercialLicenseStatus();');+ expect(appLayoutSource).toContain('void loadCommercialPosture();');expect(appSource).not.toContain("eventBus.on('theme_changed'");expect(appSource).not.toContain("eventBus.on('websocket_reconnected'");expect(appSource).not.toContain("apiFetch('/api/security/status')");diff --git a/frontend-modern/src/api/__tests__/license.test.ts b/frontend-modern/src/api/__tests__/license.test.tsindex 9c29a3ab89..ff881f4578 100644--- a/frontend-modern/src/api/__tests__/license.test.ts+++ b/frontend-modern/src/api/__tests__/license.test.ts@@ -49,6 +49,23 @@ describe('LicenseAPI', () => {});});+ it('reads commercial posture from the public-safe commercial endpoint', async () => {+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({+ tier: 'pro',+ subscription_state: 'active',+ upgrade_reasons: [],+ trial_eligible: false,+ });++ const result = await LicenseAPI.getCommercialPosture();++ expect(apiFetchJSON).toHaveBeenCalledWith('/api/license/commercial-posture');+ expect(result).toMatchObject({+ tier: 'pro',+ subscription_state: 'active',+ });+ });+it('keeps getEntitlements as a compatibility alias for the commercial endpoint', async () => {vi.mocked(apiFetchJSON).mockResolvedValueOnce({tier: 'free',diff --git a/frontend-modern/src/api/license.ts b/frontend-modern/src/api/license.tsindex 9df2f3c149..693e01c417 100644--- a/frontend-modern/src/api/license.ts+++ b/frontend-modern/src/api/license.ts@@ -51,16 +51,26 @@ export interface LicenseRuntimeCapabilities {max_history_days?: number;}-// Mirrors internal/api/subscription_entitlements.go:EntitlementPayload-export interface LicenseCommercialEntitlements {- capabilities: string[];- limits: EntitlementLimitStatus[];+// Mirrors internal/api/subscription_entitlements.go:CommercialPosturePayload+export interface LicenseCommercialPosture {subscription_state: string;upgrade_reasons: EntitlementUpgradeReason[];- plan_version?: string;tier: string;trial_expires_at?: number;trial_days_remaining?: number;+ trial_eligible?: boolean;+ trial_eligibility_reason?: string;+ overflow_days_remaining?: number;+ legacy_connections?: EntitlementLegacyConnections;+ has_migration_gap?: boolean;+ commercial_migration?: CommercialMigrationStatus;+}++// Mirrors internal/api/subscription_entitlements.go:EntitlementPayload+export interface LicenseCommercialEntitlements extends LicenseCommercialPosture {+ capabilities: string[];+ limits: EntitlementLimitStatus[];+ plan_version?: string;hosted_mode?: boolean;valid?: boolean;licensed_email?: string;@@ -69,13 +79,7 @@ export interface LicenseCommercialEntitlements {days_remaining?: number;in_grace_period?: boolean;grace_period_end?: string;- trial_eligible?: boolean;- trial_eligibility_reason?: string;max_history_days?: number;- overflow_days_remaining?: number;- legacy_connections?: EntitlementLegacyConnections;- has_migration_gap?: boolean;- commercial_migration?: CommercialMigrationStatus;}export type LicenseEntitlements = LicenseCommercialEntitlements;@@ -110,6 +114,10 @@ export class LicenseAPI {) as Promise<LicenseRuntimeCapabilities>;}+ static async getCommercialPosture(): Promise<LicenseCommercialPosture> {+ return apiFetchJSON(`${this.baseUrl}/commercial-posture`) as Promise<LicenseCommercialPosture>;+ }+static async getCommercialEntitlements(): Promise<LicenseCommercialEntitlements> {return apiFetchJSON(`${this.baseUrl}/entitlements`) as Promise<LicenseCommercialEntitlements>;}diff --git a/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx b/frontend-modern/src/components/Settings/ProLicensePlanSection.tsxindex aba1e355cd..b1903e6ca2 100644--- a/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx+++ b/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx@@ -1,15 +1,15 @@import { Component, For, Show } from 'solid-js';import RefreshCw from 'lucide-solid/icons/refresh-cw';import { UpgradeLink } from '@/components/shared/UpgradeLink';-import { getUpgradeActionDestination, licenseLoadError } from '@/stores/licenseCommercial';+import { getUpgradeActionDestination } from '@/stores/licenseCommercial';+import { licenseEntitlementsLoadError } from '@/stores/licenseEntitlements';import {getInactiveProUpsellNotice,getLicenseStatusLoadingState,getNoActiveProLicenseState,getTrialEndedProLicenseNotice,} from '@/utils/licensePresentation';-import { getPulseAccountPortalUpgradeUrl } from '@/utils/pricingHandoff';-import { resolveUpgradeDestination } from '@/utils/upgradeNavigation';+import { resolveSelfHostedPurchaseStartDestination } from '@/utils/pricingHandoff';import { CommercialStatGrid } from './CommercialBillingSections';import { SELF_HOSTED_PRO_BILLING_PRESENTATION } from './selfHostedBillingPresentation';@@ -56,7 +56,7 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (proconst inactiveProUpsellNotice =!props.hasPaidFeatures && !props.trialEnded ? getInactiveProUpsellNotice() : null;const monitoredSystemUpgradeDestination = () =>- resolveUpgradeDestination(getPulseAccountPortalUpgradeUrl('max_monitored_systems'));+ resolveSelfHostedPurchaseStartDestination('max_monitored_systems');return (<>@@ -100,7 +100,7 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (pro</div>)}</Show>- <Show when={props.trialEnded && !licenseLoadError() && trialEndedNotice}>+ <Show when={props.trialEnded && !licenseEntitlementsLoadError() && trialEndedNotice}><div class={`mb-4 rounded-md border p-3 text-sm ${trialEndedNotice?.tone ?? ''}`}><p class="font-medium">{trialEndedNotice?.title}</p><p class="text-xs mt-1 opacity-90">{trialEndedNotice?.body}</p>@@ -112,7 +112,7 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (pro</UpgradeLink></div></Show>- <Show when={licenseLoadError()}>+ <Show when={licenseEntitlementsLoadError()}><div class="rounded-md border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900 p-3 text-sm text-amber-800 dark:text-amber-200"><p class="font-medium">Could not load license status</p><p class="text-xs text-amber-700 dark:text-amber-300 mt-1">@@ -129,7 +129,7 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (pro</button></div></Show>- <Show when={!licenseLoadError()}>+ <Show when={!licenseEntitlementsLoadError()}><Showwhen={!props.loading}fallback={<p class="text-sm ">{getLicenseStatusLoadingState().text}</p>}diff --git a/frontend-modern/src/components/Settings/Settings.tsx b/frontend-modern/src/components/Settings/Settings.tsxindex a9ff036c14..8037df7a7f 100644--- a/frontend-modern/src/components/Settings/Settings.tsx+++ b/frontend-modern/src/components/Settings/Settings.tsx@@ -18,7 +18,11 @@ import { useSystemSettingsState } from './useSystemSettingsState';import { useSettingsNavigation } from './useSettingsNavigation';import { getSettingsLoadingState } from '@/utils/settingsShellPresentation';-import { getLimit, isPro, loadLicenseStatus } from '@/stores/licenseCommercial';+import {+ getLimit,+ loadLicenseStatus as loadRuntimeLicenseStatus,+} from '@/stores/license';+import { isPro, loadCommercialPosture } from '@/stores/licenseCommercial';interface SettingsProps {darkMode: () => boolean;@@ -149,7 +153,8 @@ const Settings: Component<SettingsProps> = (props) => {});onMount(() => {- loadLicenseStatus();+ void loadRuntimeLicenseStatus();+ void loadCommercialPosture();});return (diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsxindex a5985af71a..cbd13707b6 100644--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx@@ -22,6 +22,8 @@ const loggerDebugMock = vi.fn();const loggerErrorMock = vi.fn();const hasFeatureMock = vi.fn();const loadLicenseStatusMock = vi.fn();+const loadCommercialPostureMock = vi.fn();+const commercialPostureMock = vi.fn();const entitlementsMock = vi.fn();const trackPaywallViewedMock = vi.fn();const trackUpgradeClickedMock = vi.fn();@@ -73,8 +75,10 @@ vi.mock('@/stores/license', () => ({}));vi.mock('@/stores/licenseCommercial', () => ({+ commercialPosture: (...args: unknown[]) => commercialPostureMock(...args),entitlements: (...args: unknown[]) => entitlementsMock(...args),getUpgradeActionDestination: () => ({ href: 'https://example.com/upgrade', external: true }),+ loadCommercialPosture: (...args: unknown[]) => loadCommercialPostureMock(...args),loadLicenseStatus: (...args: unknown[]) => loadLicenseStatusMock(...args),}));@@ -129,6 +133,8 @@ const resetAllMocks = () => {loggerErrorMock.mockReset();hasFeatureMock.mockReset();loadLicenseStatusMock.mockReset();+ loadCommercialPostureMock.mockReset();+ commercialPostureMock.mockReset();entitlementsMock.mockReset();trackPaywallViewedMock.mockReset();trackUpgradeClickedMock.mockReset();@@ -137,6 +143,8 @@ const resetAllMocks = () => {const setupDefaultMocks = () => {hasFeatureMock.mockReturnValue(true);+ loadCommercialPostureMock.mockResolvedValue(undefined);+ commercialPostureMock.mockReturnValue({ trial_eligible: true });entitlementsMock.mockReturnValue({ trial_eligible: true });getSettingsMock.mockResolvedValue(baseSettings());getModelsMock.mockResolvedValue({ models: [] });diff --git a/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsxindex a98f1686c9..01c52e73b0 100644--- a/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx@@ -39,9 +39,11 @@ vi.mock('@/stores/license', () => ({}));vi.mock('@/stores/licenseCommercial', () => ({+ commercialPosture: () => ({ trial_eligible: true }),entitlements: () => ({ trial_eligible: true }),getUpgradeActionDestination: (...args: unknown[]) => getUpgradeActionDestinationMock(...args),getUpgradeActionUrlOrFallback: (...args: unknown[]) => getUpgradeActionUrlOrFallbackMock(...args),+ loadCommercialPosture: () => Promise.resolve(),loadLicenseStatus: () => Promise.resolve(),startProTrial: vi.fn(),}));diff --git a/frontend-modern/src/components/Settings/__tests__/NodeModal.guardrails.test.ts b/frontend-modern/src/components/Settings/__tests__/NodeModal.guardrails.test.tsindex fbbe213158..774d0545c3 100644--- a/frontend-modern/src/components/Settings/__tests__/NodeModal.guardrails.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/NodeModal.guardrails.test.ts@@ -55,6 +55,8 @@ describe('NodeModal guardrails', () => {expect(nodeModalSource).toContain('useNodeModalState');expect(nodeModalStateSource).toContain("from '@/stores/licenseCommercial';");expect(nodeModalStateSource).not.toContain("from '@/stores/license';\n");+ expect(nodeModalStateSource).toContain('void loadLicenseStatus();');+ expect(nodeModalStateSource).toContain('const ent = licenseStatus();');expect(nodeModalStateSource).toContain('const copyProxmoxAgentInstallCommand = async (');expect(nodeModalStateSource).toContain("const data = await NodesAPI.getAgentInstallCommand({");expect(nodeModalStateSource).toContain('type,');diff --git a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsxindex 48341cecc1..cf465228f4 100644--- a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { Route, Router } from '@solidjs/router';import type { LicenseEntitlements } from '@/api/license';import { ProLicensePanel } from '../ProLicensePanel';@@ -8,8 +9,8 @@ import proLicensePanelStateSource from '../useProLicensePanelState.ts?raw';import proLicensePlanSectionSource from '../ProLicensePlanSection.tsx?raw';import selfHostedCommercialActivationSectionSource from '../SelfHostedCommercialActivationSection.tsx?raw';import {- getPulseAccountPortalUpgradeUrl,getPublicPricingUrl,+ getSelfHostedPurchaseStartUrl,SELF_HOSTED_PRO_BILLING_PLAN_HREF,SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID,SELF_HOSTED_PRO_BILLING_USAGE_HREF,@@ -18,7 +19,10 @@ import {let mockEntitlements: LicenseEntitlements | null = null;-const loadLicenseStatusMock = vi.fn();+const loadRuntimeLicenseStatusMock = vi.fn();+const loadCommercialPostureMock = vi.fn();+const loadLicenseEntitlementsMock = vi.fn();+const licenseEntitlementsLoadErrorMock = vi.fn(() => null);const startProTrialMock = vi.fn();const activateLicenseMock = vi.fn();const clearLicenseMock = vi.fn();@@ -33,24 +37,33 @@ const navigateMock = vi.fn();const getUpgradeActionDestinationMock = vi.hoisted(() => vi.fn());const getUpgradeActionUrlOrFallbackMock = vi.hoisted(() => vi.fn());-vi.mock('@solidjs/router', () => ({- useLocation: () => useLocationMock(),- useNavigate: () => navigateMock,-}));+vi.mock('@solidjs/router', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@solidjs/router')>();+ return {+ ...actual,+ useLocation: () => useLocationMock(),+ useNavigate: () => navigateMock,+ };+});vi.mock('@/stores/license', () => ({isMultiTenantEnabled: () => true,+ loadLicenseStatus: (...args: unknown[]) => loadRuntimeLicenseStatusMock(...args),}));vi.mock('@/stores/licenseCommercial', () => ({getUpgradeActionDestination: (...args: unknown[]) => getUpgradeActionDestinationMock(...args),getUpgradeActionUrlOrFallback: (...args: unknown[]) => getUpgradeActionUrlOrFallbackMock(...args),- licenseLoadError: () => false,- licenseStatus: () => mockEntitlements,- loadLicenseStatus: (...args: unknown[]) => loadLicenseStatusMock(...args),+ loadCommercialPosture: (...args: unknown[]) => loadCommercialPostureMock(...args),startProTrial: (...args: unknown[]) => startProTrialMock(...args),}));+vi.mock('@/stores/licenseEntitlements', () => ({+ licenseEntitlements: () => mockEntitlements,+ licenseEntitlementsLoadError: () => licenseEntitlementsLoadErrorMock(),+ loadLicenseEntitlements: (...args: unknown[]) => loadLicenseEntitlementsMock(...args),+}));+vi.mock('@/api/license', () => ({LicenseAPI: {activateLicense: (...args: unknown[]) => activateLicenseMock(...args),@@ -66,6 +79,12 @@ vi.mock('@/stores/notifications', () => ({}));describe('ProLicensePanel', () => {+ const renderPanel = () => render(() => (+ <Router>+ <Route path="/" component={() => <ProLicensePanel />} />+ </Router>+ ));+beforeEach(() => {mockEntitlements = {capabilities: [],@@ -76,7 +95,10 @@ describe('ProLicensePanel', () => {trial_eligible: true,};- loadLicenseStatusMock.mockReset();+ loadRuntimeLicenseStatusMock.mockReset();+ loadCommercialPostureMock.mockReset();+ loadLicenseEntitlementsMock.mockReset();+ licenseEntitlementsLoadErrorMock.mockReset();startProTrialMock.mockReset();activateLicenseMock.mockReset();clearLicenseMock.mockReset();@@ -86,7 +108,10 @@ describe('ProLicensePanel', () => {navigateMock.mockReset();getUpgradeActionDestinationMock.mockReset();getUpgradeActionUrlOrFallbackMock.mockReset();- loadLicenseStatusMock.mockResolvedValue(undefined);+ loadRuntimeLicenseStatusMock.mockResolvedValue(undefined);+ loadCommercialPostureMock.mockResolvedValue(undefined);+ loadLicenseEntitlementsMock.mockResolvedValue(undefined);+ licenseEntitlementsLoadErrorMock.mockReturnValue(null);startProTrialMock.mockResolvedValue(undefined);activateLicenseMock.mockResolvedValue({ success: true });clearLicenseMock.mockResolvedValue({ success: true });@@ -107,10 +132,10 @@ describe('ProLicensePanel', () => {});it('shows start trial action only when trial_eligible is true', async () => {- render(() => <ProLicensePanel />);+ renderPanel();await waitFor(() => {- expect(loadLicenseStatusMock).toHaveBeenCalled();+ expect(loadLicenseEntitlementsMock).toHaveBeenCalled();});expect(screen.getByText('Pulse Pro')).toBeInTheDocument();@@ -128,7 +153,7 @@ describe('ProLicensePanel', () => {trial_eligibility_reason: 'already_used',};- render(() => <ProLicensePanel />);+ renderPanel();expect(screen.queryByRole('button', { name: /start 14-day pro trial/i }),@@ -148,10 +173,10 @@ describe('ProLicensePanel', () => {trial_eligible: false,};- render(() => <ProLicensePanel />);+ renderPanel();await waitFor(() => {- expect(loadLicenseStatusMock).toHaveBeenCalled();+ expect(loadLicenseEntitlementsMock).toHaveBeenCalled();});await waitFor(() => {expect(screen.getByText('Days Remaining')).toBeInTheDocument();@@ -175,7 +200,7 @@ describe('ProLicensePanel', () => {trial_eligible: false,};- render(() => <ProLicensePanel />);+ renderPanel();await waitFor(() => {expect(screen.getByText('Plan Terms')).toBeInTheDocument();@@ -224,7 +249,7 @@ describe('ProLicensePanel', () => {trial_eligible: false,};- render(() => <ProLicensePanel />);+ renderPanel();await waitFor(() => {expect(screen.getByText('Plan Terms')).toBeInTheDocument();@@ -266,7 +291,7 @@ describe('ProLicensePanel', () => {tier: 'enterprise',};- render(() => <ProLicensePanel />);+ renderPanel();await waitFor(() => {expect(screen.getByText('Basic SSO (OIDC)')).toBeInTheDocument();@@ -294,7 +319,7 @@ describe('ProLicensePanel', () => {});it('starts trial and records conversion metric when user clicks start', async () => {- render(() => <ProLicensePanel />);+ renderPanel();fireEvent.click(screen.getByRole('button', { name: /start 14-day pro trial/i }));@@ -305,7 +330,7 @@ describe('ProLicensePanel', () => {});it('shows migration guidance when the pasted key looks like a legacy v5 license', async () => {- render(() => <ProLicensePanel />);+ renderPanel();fireEvent.input(screen.getByLabelText(/license \/ activation key/i), {target: { value: 'header.payload.signature' },@@ -324,7 +349,7 @@ describe('ProLicensePanel', () => {hash: '',});- render(() => <ProLicensePanel />);+ renderPanel();expect(screen.getByText('Trial activated')).toBeInTheDocument();expect(@@ -343,7 +368,7 @@ describe('ProLicensePanel', () => {hash: '',});- render(() => <ProLicensePanel />);+ renderPanel();expect(screen.getByRole('tab', { name: 'Usage' })).toHaveAttribute('aria-selected', 'true');expect(document.getElementById(SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID)).not.toBeInTheDocument();@@ -359,12 +384,12 @@ describe('ProLicensePanel', () => {hash: '',});- render(() => <ProLicensePanel />);+ renderPanel();expect(screen.getByText('Need a higher monitored-system cap?')).toBeInTheDocument();expect(screen.getByRole('link', { name: 'Compare plans' })).toHaveAttribute('href',- getPulseAccountPortalUpgradeUrl('max_monitored_systems'),+ getSelfHostedPurchaseStartUrl('max_monitored_systems'),);});@@ -375,7 +400,7 @@ describe('ProLicensePanel', () => {hash: '',});- render(() => <ProLicensePanel />);+ renderPanel();fireEvent.click(screen.getByRole('tab', { name: 'Usage' }));@@ -402,7 +427,7 @@ describe('ProLicensePanel', () => {},};- render(() => <ProLicensePanel />);+ renderPanel();expect(screen.getByText('v5 license migration pending')).toBeInTheDocument();expect(screen.getByText(/automatic v6 exchange did not complete yet/i)).toBeInTheDocument();@@ -428,7 +453,7 @@ describe('ProLicensePanel', () => {},};- render(() => <ProLicensePanel />);+ renderPanel();expect(screen.getByText('v5 license migration pending')).toBeInTheDocument();expect(screen.getByText(/rate-limited right now/i)).toBeInTheDocument();@@ -452,7 +477,7 @@ describe('ProLicensePanel', () => {},};- render(() => <ProLicensePanel />);+ renderPanel();expect(screen.getByText('v5 license migration needs attention')).toBeInTheDocument();expect(@@ -477,7 +502,7 @@ describe('ProLicensePanel', () => {),);- render(() => <ProLicensePanel />);+ renderPanel();fireEvent.click(screen.getByRole('button', { name: /start 14-day pro trial/i }));@@ -496,7 +521,7 @@ describe('ProLicensePanel', () => {}),);- render(() => <ProLicensePanel />);+ renderPanel();fireEvent.click(screen.getByRole('button', { name: /start 14-day pro trial/i }));@@ -512,7 +537,7 @@ describe('ProLicensePanel', () => {}),);- render(() => <ProLicensePanel />);+ renderPanel();fireEvent.click(screen.getByRole('button', { name: /start 14-day pro trial/i }));@@ -535,7 +560,9 @@ describe('ProLicensePanel', () => {expect(proLicensePanelStateSource).toContain('getSelfHostedBillingPlanIntent');expect(proLicensePanelStateSource).toContain('getSelfHostedBillingUsageDetail');expect(proLicensePanelStateSource).toContain('const setActiveSection = (section: SelfHostedBillingSection) => {');- expect(proLicensePanelStateSource).toContain('loadLicenseStatus(true)');+ expect(proLicensePanelStateSource).toContain('loadLicenseEntitlements(true)');+ expect(proLicensePanelStateSource).toContain('loadCommercialPosture(true)');+ expect(proLicensePanelStateSource).toContain('loadRuntimeLicenseStatus(true)');expect(proLicensePanelStateSource).toContain('buildSelfHostedCommercialPlanModel');expect(proLicensePanelStateSource).toContain('runStartProTrialAction({');expect(proLicensePanelStateSource).not.toContain('startProTrial()');@@ -559,7 +586,7 @@ describe('ProLicensePanel', () => {'monitoredSystemUpgradeArrivalTitle',);expect(proLicensePlanSectionSource).toContain(- "getPulseAccountPortalUpgradeUrl('max_monitored_systems')",+ "resolveSelfHostedPurchaseStartDestination('max_monitored_systems')",);expect(proLicensePlanSectionSource).not.toContain('Your Pro trial has ended');expect(proLicensePlanSectionSource).not.toContain('Unlock Pulse Patrol, alert analysis, auto-fix, and more.');diff --git a/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx b/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsxindex d63e58d7f2..b0ec8f775c 100644--- a/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx@@ -6,8 +6,9 @@ import { UserAssignmentsPanel } from '../UserAssignmentsPanel';const hasFeatureMock = vi.fn();const loadLicenseStatusMock = vi.fn();-const loadCommercialLicenseStatusMock = vi.fn();+const loadCommercialPostureMock = vi.fn();const startProTrialMock = vi.fn();+const commercialPostureMock = vi.fn();const entitlementsMock = vi.fn();const trackPaywallViewedMock = vi.fn();const trackUpgradeClickedMock = vi.fn();@@ -26,12 +27,14 @@ vi.mock('@/stores/license', () => ({}));vi.mock('@/stores/licenseCommercial', () => ({+ commercialPosture: (...args: unknown[]) => commercialPostureMock(...args),getUpgradeActionDestination: (feature: string) => ({href: `https://example.com/upgrade?feature=${feature}`,external: true,}),getUpgradeActionUrlOrFallback: (feature: string) => `/upgrade?feature=${feature}`,- loadLicenseStatus: (...args: unknown[]) => loadCommercialLicenseStatusMock(...args),+ loadCommercialPosture: (...args: unknown[]) => loadCommercialPostureMock(...args),+ loadLicenseStatus: (...args: unknown[]) => loadCommercialPostureMock(...args),startProTrial: (...args: unknown[]) => startProTrialMock(...args),entitlements: (...args: unknown[]) => entitlementsMock(...args),}));@@ -71,8 +74,9 @@ describe('RBAC paywall settings panels', () => {beforeEach(() => {hasFeatureMock.mockReset();loadLicenseStatusMock.mockReset();- loadCommercialLicenseStatusMock.mockReset();+ loadCommercialPostureMock.mockReset();startProTrialMock.mockReset();+ commercialPostureMock.mockReset();entitlementsMock.mockReset();trackPaywallViewedMock.mockReset();trackUpgradeClickedMock.mockReset();@@ -86,8 +90,9 @@ describe('RBAC paywall settings panels', () => {hasFeatureMock.mockReturnValue(true);loadLicenseStatusMock.mockResolvedValue(undefined);- loadCommercialLicenseStatusMock.mockResolvedValue(undefined);+ loadCommercialPostureMock.mockResolvedValue(undefined);startProTrialMock.mockResolvedValue({ outcome: 'started' });+ commercialPostureMock.mockReturnValue({ trial_eligible: false });entitlementsMock.mockReturnValue({ trial_eligible: false });getRolesMock.mockResolvedValue([{@@ -125,6 +130,7 @@ describe('RBAC paywall settings panels', () => {'href','https://example.com/upgrade?feature=rbac',);+ expect(loadCommercialPostureMock).toHaveBeenCalled();expect(screen.getByRole('button', { name: 'New Role' })).toBeDisabled();expect(getRolesMock).not.toHaveBeenCalled();expect(trackPaywallViewedMock).toHaveBeenCalledWith('rbac', 'settings_roles_panel');@@ -152,6 +158,7 @@ describe('RBAC paywall settings panels', () => {expect(screen.getByText('Centralized Access Control (Pro)')).toBeInTheDocument();});+ expect(loadCommercialPostureMock).toHaveBeenCalled();expect(screen.getByRole('link', { name: 'Upgrade to Pro' })).toHaveAttribute('href','https://example.com/upgrade?feature=rbac',@@ -205,6 +212,7 @@ describe('RBAC paywall settings panels', () => {it('surfaces backend trial-start messages instead of collapsing every conflict into already-used', async () => {hasFeatureMock.mockImplementation((feature: string) => feature !== 'rbac');+ commercialPostureMock.mockReturnValue({ trial_eligible: true });entitlementsMock.mockReturnValue({ trial_eligible: true });startProTrialMock.mockRejectedValueOnce(Object.assign(diff --git a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsxindex b508bf41e7..f01e83e590 100644--- a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx@@ -5,6 +5,7 @@ import relaySettingsPanelSource from '../RelaySettingsPanel.tsx?raw';import relaySettingsPanelStateSource from '../useRelaySettingsPanelState.ts?raw';const loadLicenseStatusMock = vi.fn();+const loadCommercialPostureMock = vi.fn();const hasFeatureMock = vi.fn();const getRelayConfigMock = vi.fn();const getRelayStatusMock = vi.fn();@@ -26,8 +27,10 @@ vi.mock('@/stores/license', () => ({}));vi.mock('@/stores/licenseCommercial', () => ({+ commercialPosture: () => ({ trial_eligible: false }),getUpgradeActionDestination: () => ({ href: 'https://example.com/upgrade', external: true }),entitlements: () => ({ trial_eligible: false }),+ loadCommercialPosture: (...args: unknown[]) => loadCommercialPostureMock(...args),loadLicenseStatus: (...args: unknown[]) => loadLicenseStatusMock(...args),startProTrial: vi.fn(),}));@@ -79,6 +82,7 @@ import { RelaySettingsPanel } from '../RelaySettingsPanel';describe('RelaySettingsPanel runtime', () => {beforeEach(() => {loadLicenseStatusMock.mockReset();+ loadCommercialPostureMock.mockReset();hasFeatureMock.mockReset();getRelayConfigMock.mockReset();getRelayStatusMock.mockReset();@@ -95,6 +99,7 @@ describe('RelaySettingsPanel runtime', () => {hasFeatureMock.mockReturnValue(true);loadLicenseStatusMock.mockResolvedValue(undefined);+ loadCommercialPostureMock.mockResolvedValue(undefined);getRelayConfigMock.mockResolvedValue({enabled: true,server_url: 'wss://relay.example.test/ws/instance',diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex 03fe7c5903..93b973b064 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -579,7 +579,9 @@ describe('Settings architecture guardrails', () => {expect(proLicensePanelSource).toContain('./selfHostedBillingPresentation');expect(proLicensePanelSource).toContain('SELF_HOSTED_PRO_BILLING_PRESENTATION');expect(proLicensePanelStateSource).toContain('buildSelfHostedCommercialPlanModel');- expect(proLicensePanelStateSource).toContain('loadLicenseStatus(true)');+ expect(proLicensePanelStateSource).toContain('loadLicenseEntitlements(true)');+ expect(proLicensePanelStateSource).toContain('loadCommercialPosture(true)');+ expect(proLicensePanelStateSource).toContain('loadRuntimeLicenseStatus(true)');expect(proLicensePanelStateSource).toContain('runStartProTrialAction({');expect(proLicensePanelStateSource).not.toContain('startProTrial()');expect(proLicensePanelSource).not.toContain('title="Pulse Pro"');@@ -1505,11 +1507,11 @@ describe('Settings architecture guardrails', () => {expect(aiSettingsStateSource).toContain("} from '@/stores/license';");expect(aiSettingsStateSource).toContain("} from '@/stores/licenseCommercial';");- expect(aiSettingsStateSource).toContain('loadCommercialLicenseStatus();');+ expect(aiSettingsStateSource).toContain('loadCommercialPosture();');expect(reportingPanelStateSource).toContain("} from '@/stores/license';");expect(reportingPanelStateSource).toContain("} from '@/stores/licenseCommercial';");- expect(reportingPanelStateSource).toContain('loadCommercialLicenseStatus();');+ expect(reportingPanelStateSource).toContain('loadCommercialPosture();');expect(auditLogStateSource).toContain("} from '@/stores/license';");expect(auditLogStateSource).toContain("} from '@/stores/licenseCommercial';");diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.tsindex eef910b7ce..b065be5fd7 100644--- a/frontend-modern/src/components/Settings/useAISettingsState.ts+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts@@ -15,9 +15,9 @@ import {loadLicenseStatus,} from '@/stores/license';import {- entitlements,+ commercialPosture,getUpgradeActionDestination,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { notificationStore } from '@/stores/notifications';import type { AISettings as AISettingsType, AIProvider, AuthMethod } from '@/types/ai';@@ -157,7 +157,7 @@ export const useAISettingsState = () => {const quickstartBlockedReason = createMemo(() =>normalizeQuickstartReason(settings()?.quickstart_blocked_reason),);- const canStartTrial = () => entitlements()?.trial_eligible !== false;+ const canStartTrial = () => commercialPosture()?.trial_eligible !== false;const upgradeAutofixDestination = () => getUpgradeActionDestination('ai_autofix');const hasProviderBackedModels = (data: AISettingsType | null | undefined) =>@@ -831,7 +831,7 @@ export const useAISettingsState = () => {onMount(() => {loadLicenseStatus();- loadCommercialLicenseStatus();+ loadCommercialPosture();if (typeof window !== 'undefined') {const params = new URLSearchParams(window.location.search);diff --git a/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts b/frontend-modern/src/components/Settings/useAgentProfilesPanelState.tsindex b169927880..5f3c40172d 100644--- a/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts+++ b/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts@@ -16,9 +16,9 @@ import {licenseLoading,} from '@/stores/license';import {- entitlements,+ commercialPosture,getUpgradeActionDestination,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { loadLicenseStatus } from '@/stores/license';import type { ConnectedInfrastructureItem } from '@/types/api';@@ -78,7 +78,7 @@ export const useAgentProfilesPanelState = () => {const checkingLicense = () => !licenseLoaded() || licenseLoading();const hasAgentProfiles = () => hasEntitlement('agent_profiles');const [startingTrial, setStartingTrial] = createSignal(false);- const canStartTrial = () => entitlements()?.trial_eligible !== false;+ const canStartTrial = () => commercialPosture()?.trial_eligible !== false;const [aiAvailable, setAiAvailable] = createSignal(false);const [profiles, setProfiles] = createSignal<AgentProfile[]>([]);@@ -238,7 +238,7 @@ export const useAgentProfilesPanelState = () => {onMount(async () => {await loadLicenseStatus();- await loadCommercialLicenseStatus();+ await loadCommercialPosture();try {const aiSettings = await AIAPI.getSettings();diff --git a/frontend-modern/src/components/Settings/useAuditLogPanelState.ts b/frontend-modern/src/components/Settings/useAuditLogPanelState.tsindex 4cef977f9c..ba2ba95568 100644--- a/frontend-modern/src/components/Settings/useAuditLogPanelState.ts+++ b/frontend-modern/src/components/Settings/useAuditLogPanelState.ts@@ -12,9 +12,9 @@ import {licenseLoaded,} from '@/stores/license';import {- entitlements,+ commercialPosture,getUpgradeActionDestination,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { loadLicenseStatus } from '@/stores/license';import { trackPaywallViewed, trackUpgradeClicked } from '@/utils/upgradeMetrics';@@ -120,7 +120,7 @@ export const useAuditLogPanelState = () => {const showUpgradePaywall = createMemo(() => licenseLoaded() && !auditLoggingEnabled() && !loading(),);- const canStartTrial = () => entitlements()?.trial_eligible !== false;+ const canStartTrial = () => commercialPosture()?.trial_eligible !== false;const upgradeDestination = createMemo(() => getUpgradeActionDestination('audit_logging'));const fetchAuditEvents = async (options?: { limit?: number; offset?: number }) => {@@ -545,7 +545,7 @@ export const useAuditLogPanelState = () => {onMount(() => {setIsMounted(true);void loadLicenseStatus();- void loadCommercialLicenseStatus();+ void loadCommercialPosture();});createEffect(() => {diff --git a/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts b/frontend-modern/src/components/Settings/useAuditWebhookPanelState.tsindex 8db1689064..29a452b6d6 100644--- a/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts+++ b/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts@@ -7,9 +7,9 @@ import {licenseLoaded,} from '@/stores/license';import {- entitlements,+ commercialPosture,getUpgradeActionDestination,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { loadLicenseStatus } from '@/stores/license';import { trackPaywallViewed } from '@/utils/upgradeMetrics';@@ -29,7 +29,7 @@ export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {const [startingTrial, setStartingTrial] = createSignal(false);const canManage = () => canManageOverride !== false;- const canStartTrial = () => entitlements()?.trial_eligible !== false;+ const canStartTrial = () => commercialPosture()?.trial_eligible !== false;const isAuditLoggingEnabled = () => hasFeature('audit_logging');const upgradeDestination = () => getUpgradeActionDestination('audit_logging');@@ -102,7 +102,7 @@ export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {onMount(() => {loadLicenseStatus();- loadCommercialLicenseStatus();+ loadCommercialPosture();});createEffect((wasPaywallVisible: boolean) => {diff --git a/frontend-modern/src/components/Settings/useNodeModalState.ts b/frontend-modern/src/components/Settings/useNodeModalState.tsindex b819218c37..2275a2e9e1 100644--- a/frontend-modern/src/components/Settings/useNodeModalState.ts+++ b/frontend-modern/src/components/Settings/useNodeModalState.ts@@ -4,7 +4,7 @@ import type { NodeConfig } from '@/types/nodes';import { notificationStore } from '@/stores/notifications';import { NodesAPI } from '@/api/nodes';import type { ProxmoxSetupCommandResponse } from '@/api/nodes';-import { licenseStatus, loadLicenseStatus } from '@/stores/licenseCommercial';+import { commercialPosture, loadCommercialPosture } from '@/stores/licenseCommercial';import { copyToClipboard } from '@/utils/clipboard';import { logger } from '@/utils/logger';import {@@ -44,7 +44,7 @@ export const useNodeModalState = (props: NodeModalProps) => {const [agentCommandError, setAgentCommandError] = createSignal<string | null>(null);onMount(() => {- void loadLicenseStatus();+ void loadCommercialPosture();});const isAdvancedSetupMode = () =>@@ -60,7 +60,7 @@ export const useNodeModalState = (props: NodeModalProps) => {const [startingTrial, setStartingTrial] = createSignal(false);const hostLimitReached = createMemo(() => false);const canStartTrial = createMemo(() => {- const ent = licenseStatus();+ const ent = commercialPosture();if (!ent) return false;if (ent.subscription_state === 'active' || ent.subscription_state === 'trial') return false;return ent.trial_eligible !== false;diff --git a/frontend-modern/src/components/Settings/useProLicensePanelState.ts b/frontend-modern/src/components/Settings/useProLicensePanelState.tsindex 171b1faf33..31eff26ff7 100644--- a/frontend-modern/src/components/Settings/useProLicensePanelState.ts+++ b/frontend-modern/src/components/Settings/useProLicensePanelState.ts@@ -2,11 +2,15 @@ import { createMemo, createSignal, onMount } from 'solid-js';import { useLocation, useNavigate } from '@solidjs/router';import { notificationStore } from '@/stores/notifications';import {- licenseLoadError,- licenseStatus,- loadLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { isMultiTenantEnabled } from '@/stores/license';+import { loadLicenseStatus as loadRuntimeLicenseStatus } from '@/stores/license';+import {+ licenseEntitlements,+ licenseEntitlementsLoadError,+ loadLicenseEntitlements,+} from '@/stores/licenseEntitlements';import { LicenseAPI } from '@/api/license';import {formatLicensePlanVersion,@@ -55,14 +59,14 @@ export function useProLicensePanelState() {const [startingTrial, setStartingTrial] = createSignal(false);const [trialActivationResult, setTrialActivationResult] = createSignal('');- const entitlements = createMemo(() => licenseStatus());+ const entitlements = createMemo(() => licenseEntitlements());const subscriptionState = createMemo(() => entitlements()?.subscription_state);const trialExpiryUnix = createMemo(() => entitlements()?.trial_expires_at);const trialDaysRemaining = createMemo(() => entitlements()?.trial_days_remaining);const loadPanelData = async () => {setLoading(true);- await loadLicenseStatus(true);+ await loadLicenseEntitlements(true);setLoading(false);};@@ -112,7 +116,7 @@ export function useProLicensePanelState() {return current.trial_eligible;}const state = subscriptionState();- return state !== 'active' && state !== 'trial' && !licenseLoadError();+ return state !== 'active' && state !== 'trial' && !licenseEntitlementsLoadError();});const handleStartTrial = async () => {@@ -266,7 +270,11 @@ export function useProLicensePanelState() {}notificationStore.success(result.message || 'License activated');setLicenseKey('');- await loadPanelData();+ await Promise.all([+ loadPanelData(),+ loadCommercialPosture(true),+ loadRuntimeLicenseStatus(true),+ ]);} catch (error) {notificationStore.error(error instanceof Error ? error.message : 'Failed to activate license');} finally {@@ -282,7 +290,11 @@ export function useProLicensePanelState() {try {const result = await LicenseAPI.clearLicense();notificationStore.success(result.message || 'License cleared');- await loadPanelData();+ await Promise.all([+ loadPanelData(),+ loadCommercialPosture(true),+ loadRuntimeLicenseStatus(true),+ ]);} catch (error) {notificationStore.error(error instanceof Error ? error.message : 'Failed to clear license');} finally {diff --git a/frontend-modern/src/components/Settings/useRBACFeatureGateState.ts b/frontend-modern/src/components/Settings/useRBACFeatureGateState.tsindex 004d4453f0..5441c0bbf7 100644--- a/frontend-modern/src/components/Settings/useRBACFeatureGateState.ts+++ b/frontend-modern/src/components/Settings/useRBACFeatureGateState.ts@@ -4,8 +4,8 @@ import {licenseLoaded,} from '@/stores/license';import {- entitlements,- loadLicenseStatus as loadCommercialLicenseStatus,+ commercialPosture,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { loadLicenseStatus } from '@/stores/license';import { notificationStore } from '@/stores/notifications';@@ -31,7 +31,7 @@ export function useRBACFeatureGateState(options: UseRBACFeatureGateStateOptions)getRBACFeatureGateCopy(options.kind),);const licenseReady = createMemo(() => licenseLoaded());- const canStartTrial = createMemo(() => entitlements()?.trial_eligible !== false);+ const canStartTrial = createMemo(() => commercialPosture()?.trial_eligible !== false);const rbacEnabled = createMemo(() => licenseReady() && hasFeature('rbac'));const paywallVisible = createMemo(() => licenseReady() && !hasFeature('rbac') && !options.loading(),@@ -39,7 +39,7 @@ export function useRBACFeatureGateState(options: UseRBACFeatureGateStateOptions)onMount(() => {void loadLicenseStatus();- void loadCommercialLicenseStatus();+ void loadCommercialPosture();});createEffect((wasPaywallVisible) => {diff --git a/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts b/frontend-modern/src/components/Settings/useRelaySettingsPanelState.tsindex 4b39c6de1c..68f0e76894 100644--- a/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts+++ b/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts@@ -4,9 +4,9 @@ import {licenseLoaded,} from '@/stores/license';import {- entitlements,+ commercialPosture,getUpgradeActionDestination,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { loadLicenseStatus } from '@/stores/license';import { trackPaywallViewed } from '@/utils/upgradeMetrics';@@ -37,7 +37,7 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {const [startingTrial, setStartingTrial] = createSignal(false);const canManage = () => props.canManage !== false;- const canStartTrial = () => entitlements()?.trial_eligible !== false;+ const canStartTrial = () => commercialPosture()?.trial_eligible !== false;const relayEnabled = () => hasFeature('relay');const upgradeDestination = () => getUpgradeActionDestination('relay');const connectionPresentation = createMemo(() =>@@ -134,7 +134,7 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {};onMount(async () => {- await Promise.all([loadLicenseStatus(), loadCommercialLicenseStatus()]);+ await Promise.all([loadLicenseStatus(), loadCommercialPosture()]);if (!relayEnabled()) {setLoading(false);return;diff --git a/frontend-modern/src/components/Settings/useReportingPanelState.ts b/frontend-modern/src/components/Settings/useReportingPanelState.tsindex 3ebd0239a1..8e670746f6 100644--- a/frontend-modern/src/components/Settings/useReportingPanelState.ts+++ b/frontend-modern/src/components/Settings/useReportingPanelState.ts@@ -7,9 +7,9 @@ import {licenseLoaded,} from '@/stores/license';import {- entitlements,+ commercialPosture,getUpgradeActionDestination,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { loadLicenseStatus } from '@/stores/license';import { trackPaywallViewed } from '@/utils/upgradeMetrics';@@ -58,7 +58,7 @@ export const useReportingPanelState = () => {licenseLoaded() &&reportingFeatureId() !== '' &&!hasFeature(reportingFeatureId());- const canStartTrial = () => entitlements()?.trial_eligible !== false;+ const canStartTrial = () => commercialPosture()?.trial_eligible !== false;const isReportingEnabled = () =>licenseLoaded() &&reportingFeatureId() !== '' &&@@ -70,7 +70,7 @@ export const useReportingPanelState = () => {onMount(() => {loadLicenseStatus();- loadCommercialLicenseStatus();+ loadCommercialPosture();});createEffect((wasVisible: boolean) => {diff --git a/frontend-modern/src/components/Settings/useSSOProvidersState.ts b/frontend-modern/src/components/Settings/useSSOProvidersState.tsindex a6fd87b1c6..b34fd43057 100644--- a/frontend-modern/src/components/Settings/useSSOProvidersState.ts+++ b/frontend-modern/src/components/Settings/useSSOProvidersState.ts@@ -7,9 +7,9 @@ import {licenseLoaded,} from '@/stores/license';import {- entitlements,+ commercialPosture,getUpgradeActionDestination,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { loadLicenseStatus } from '@/stores/license';import { trackPaywallViewed, trackUpgradeClicked } from '@/utils/upgradeMetrics';@@ -72,7 +72,7 @@ export const useSSOProvidersState = (props: SSOProvidersPanelProps) => {const hasAdvancedSSO = createMemo(() => hasFeature('advanced_sso'));const canManage = () => props.canManage !== false;- const canStartTrial = () => entitlements()?.trial_eligible !== false;+ const canStartTrial = () => commercialPosture()?.trial_eligible !== false;const handleStartTrial = async () => {if (startingTrial()) {@@ -131,7 +131,7 @@ export const useSSOProvidersState = (props: SSOProvidersPanelProps) => {onMount(() => {loadLicenseStatus();- loadCommercialLicenseStatus();+ loadCommercialPosture();void loadProviders();});diff --git a/frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx b/frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsxindex 442b8991b1..bf5e0dbda1 100644--- a/frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx+++ b/frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx@@ -32,8 +32,8 @@ import {getPreferredResourceHostname,} from '@/utils/resourceIdentity';import {- loadLicenseStatus,- entitlements,+ commercialPosture,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import {RELAY_ONBOARDING_SETUP_LABEL,@@ -132,7 +132,7 @@ export const SetupCompletionPanel: Component<CompleteStepProps> = (props) => {let firstConnectionTracked = false;onMount(() => {- void loadLicenseStatus();+ void loadCommercialPosture();});createEffect(() => {@@ -329,7 +329,7 @@ Keep these credentials secure!});if (outcome === 'activated') {setTrialStarted(true);- await loadLicenseStatus(true);+ await loadCommercialPosture(true);}} finally {setTrialStarting(false);@@ -735,7 +735,7 @@ Keep these credentials secure!Relay.</p><Show- when={!trialStarted() && entitlements()?.subscription_state !== 'trial'}+ when={!trialStarted() && commercialPosture()?.subscription_state !== 'trial'}fallback={<buttontype="button"diff --git a/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.guardrails.test.ts b/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.guardrails.test.tsindex 8c51646b2d..6e50ef8a84 100644--- a/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.guardrails.test.ts+++ b/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.guardrails.test.ts@@ -25,7 +25,7 @@ describe('SetupCompletionPanel guardrails', () => {expect(setupCompletionPanelSource).toContain('Use the Platform connections workspace when:');expect(setupCompletionPanelSource).toContain('configure TLS and custom CA options');expect(setupCompletionPanelSource).toContain('runStartProTrialAction({');- expect(setupCompletionPanelSource).toContain('await loadLicenseStatus(true);');+ expect(setupCompletionPanelSource).toContain('await loadCommercialPosture(true);');expect(setupCompletionPanelSource).not.toContain('getUpgradeActionUrlOrFallback');});diff --git a/frontend-modern/src/components/patrol/ApprovalSection.tsx b/frontend-modern/src/components/patrol/ApprovalSection.tsxindex 46325b0ae3..9eb0749335 100644--- a/frontend-modern/src/components/patrol/ApprovalSection.tsx+++ b/frontend-modern/src/components/patrol/ApprovalSection.tsx@@ -9,7 +9,7 @@ import { Component, Show, createSignal, createResource, createMemo, onMount } frimport { aiIntelligenceStore } from '@/stores/aiIntelligence';import { notificationStore } from '@/stores/notifications';import { aiChatStore } from '@/stores/aiChat';-import { licenseStatus, loadLicenseStatus } from '@/stores/licenseCommercial';+import { commercialPosture, loadCommercialPosture } from '@/stores/licenseCommercial';import { hasFeature } from '@/stores/license';import { AIAPI, type ApprovalRequest, type ApprovalExecutionResult } from '@/api/ai';import { getApprovalRiskPresentation } from '@/utils/approvalRiskPresentation';@@ -30,7 +30,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {const [executionResult, setExecutionResult] = createSignal<ApprovalExecutionResult | null>(null);onMount(() => {- void loadLicenseStatus();+ void loadCommercialPosture();});// Find the pending approval for this finding from the store@@ -48,7 +48,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {const [startingTrial, setStartingTrial] = createSignal(false);const canStartTrial = createMemo(() => {- const ent = licenseStatus();+ const ent = commercialPosture();if (!ent) return false;if (ent.subscription_state === 'active' || ent.subscription_state === 'trial') return false;return ent.trial_eligible !== false;diff --git a/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx b/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsxindex 213442a0b6..40d7e207f0 100644--- a/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx+++ b/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx@@ -22,6 +22,7 @@ const notificationSuccessMock = vi.hoisted(() => vi.fn());const notificationErrorMock = vi.hoisted(() => vi.fn());const openWithPromptMock = vi.hoisted(() => vi.fn());const startProTrialMock = vi.hoisted(() => vi.fn());+const loadCommercialPostureMock = vi.hoisted(() => vi.fn());vi.mock('@/api/ai', () => ({AIAPI: {@@ -58,8 +59,10 @@ vi.mock('@/stores/license', () => ({}));vi.mock('@/stores/licenseCommercial', () => ({+ commercialPosture: () => state.entitlements,licenseStatus: () => state.entitlements,- loadLicenseStatus: vi.fn(),+ loadCommercialPosture: (...args: unknown[]) => loadCommercialPostureMock(...args),+ loadLicenseStatus: (...args: unknown[]) => loadCommercialPostureMock(...args),startProTrial: (...args: unknown[]) => startProTrialMock(...args),}));@@ -86,6 +89,8 @@ describe('ApprovalSection', () => {notificationErrorMock.mockReset();openWithPromptMock.mockReset();startProTrialMock.mockReset();+ loadCommercialPostureMock.mockReset();+ loadCommercialPostureMock.mockResolvedValue(undefined);});afterEach(() => {@@ -106,6 +111,7 @@ describe('ApprovalSection', () => {/>));+ expect(loadCommercialPostureMock).toHaveBeenCalled();expect(await screen.findByText('Fix Pending Approval')).toBeInTheDocument();expect(screen.getAllByText('Fix Pending Approval')).toHaveLength(1);expect(screen.getByText('details unavailable')).toBeInTheDocument();@@ -144,6 +150,7 @@ describe('ApprovalSection', () => {render(() => <ApprovalSection findingId="finding-2" investigationOutcome="fix_queued" />);+ expect(loadCommercialPostureMock).toHaveBeenCalled();expect(await screen.findAllByRole('button', { name: /re-approve & execute/i })).toHaveLength(1);fireEvent.click(screen.getByRole('button', { name: /re-approve & execute/i }));diff --git a/frontend-modern/src/components/shared/UpgradeLink.tsx b/frontend-modern/src/components/shared/UpgradeLink.tsxindex 634473783a..5d85959560 100644--- a/frontend-modern/src/components/shared/UpgradeLink.tsx+++ b/frontend-modern/src/components/shared/UpgradeLink.tsx@@ -8,17 +8,33 @@ type UpgradeLinkProps = Omit<JSX.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'export const UpgradeLink: Component<UpgradeLinkProps> = (props) => {const [local, others] = splitProps(props, ['destination', 'rel', 'target']);+ const newTab = () => local.destination.newTab ?? local.destination.external;+ const hardNavigation = () => local.destination.hardNavigation ?? local.destination.external;+ const useHardLink = () => Boolean(hardNavigation() || newTab());+ const rel = () => {+ if (local.rel) return local.rel;+ if (newTab() && !local.destination.preserveOpener) {+ return 'noopener noreferrer';+ }+ return undefined;+ };+ const target = () => {+ if (newTab()) {+ return local.target ?? '_blank';+ }+ return local.target;+ };return (<Show- when={local.destination.external}+ when={useHardLink()}fallback={<A {...others} href={local.destination.href} />}><a{...others}href={local.destination.href}- target={local.target ?? '_blank'}- rel={local.rel ?? 'noopener noreferrer'}+ target={target()}+ rel={rel()}/></Show>);diff --git a/frontend-modern/src/components/shared/__tests__/MonitoredSystemLimitWarningBanner.test.tsx b/frontend-modern/src/components/shared/__tests__/MonitoredSystemLimitWarningBanner.test.tsxindex 9a34d87a83..dbb6c71d17 100644--- a/frontend-modern/src/components/shared/__tests__/MonitoredSystemLimitWarningBanner.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/MonitoredSystemLimitWarningBanner.test.tsx@@ -30,19 +30,24 @@ const mockLegacyConnections = vi.hoisted(() =>);const mockTrackUpgradeMetricEvent = vi.hoisted(() => vi.fn());const mockTrackUpgradeClicked = vi.hoisted(() => vi.fn());-const mockLoadLicenseStatus = vi.hoisted(() => vi.fn());+const mockLoadRuntimeLicenseStatus = vi.hoisted(() => vi.fn());+const mockLoadCommercialPosture = vi.hoisted(() => vi.fn());const mockDemoModeEnabled = vi.hoisted(() => vi.fn(() => false));const mockGetUpgradeActionDestination = vi.hoisted(() => vi.fn());const mockGetUpgradeActionUrlOrFallback = vi.hoisted(() => vi.fn());+vi.mock('@/stores/license', () => ({+ getLimit: (...args: unknown[]) => mockGetLimit(...args),+ loadLicenseStatus: (...args: unknown[]) => mockLoadRuntimeLicenseStatus(...args),+}));+vi.mock('@/stores/licenseCommercial', () => ({- entitlements: mockEntitlements,- getLimit: mockGetLimit,+ commercialPosture: mockEntitlements,getUpgradeActionDestination: (...args: unknown[]) => mockGetUpgradeActionDestination(...args),getUpgradeActionUrlOrFallback: (...args: unknown[]) => mockGetUpgradeActionUrlOrFallback(...args),hasMigrationGap: mockHasMigrationGap,legacyConnections: mockLegacyConnections,- loadLicenseStatus: (...args: unknown[]) => mockLoadLicenseStatus(...args),+ loadCommercialPosture: (...args: unknown[]) => mockLoadCommercialPosture(...args),}));vi.mock('@/stores/demoMode', () => ({@@ -70,8 +75,10 @@ describe('MonitoredSystemLimitWarningBanner', () => {});mockDemoModeEnabled.mockReset();mockDemoModeEnabled.mockReturnValue(false);- mockLoadLicenseStatus.mockReset();- mockLoadLicenseStatus.mockResolvedValue(undefined);+ mockLoadRuntimeLicenseStatus.mockReset();+ mockLoadRuntimeLicenseStatus.mockResolvedValue(undefined);+ mockLoadCommercialPosture.mockReset();+ mockLoadCommercialPosture.mockResolvedValue(undefined);mockGetUpgradeActionDestination.mockReset();mockGetUpgradeActionUrlOrFallback.mockReset();mockGetUpgradeActionDestination.mockReturnValue({@@ -107,6 +114,7 @@ describe('MonitoredSystemLimitWarningBanner', () => {expect(monitoredSystemLimitWarningBannerStateSource).toContain('createEffect');expect(monitoredSystemLimitWarningBannerStateSource).toContain('createMemo');expect(monitoredSystemLimitWarningBannerStateSource).toContain('loadLicenseStatus');+ expect(monitoredSystemLimitWarningBannerStateSource).toContain('loadCommercialPosture');expect(monitoredSystemLimitWarningBannerStateSource).toContain('demoModeEnabled');expect(monitoredSystemLimitWarningBannerStateSource).toContain('trackUpgradeMetricEvent');expect(monitoredSystemLimitWarningBannerStateSource).toContain('legacyConnections');@@ -143,7 +151,8 @@ describe('MonitoredSystemLimitWarningBanner', () => {</Router>));- expect(mockLoadLicenseStatus).toHaveBeenCalled();+ expect(mockLoadRuntimeLicenseStatus).toHaveBeenCalled();+ expect(mockLoadCommercialPosture).toHaveBeenCalled();expect(screen.queryByText(/Monitored systems:/i)).not.toBeInTheDocument();});diff --git a/frontend-modern/src/components/shared/__tests__/TrialBanner.test.tsx b/frontend-modern/src/components/shared/__tests__/TrialBanner.test.tsxindex 500274ee57..59b395183f 100644--- a/frontend-modern/src/components/shared/__tests__/TrialBanner.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/TrialBanner.test.tsx@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { Route, Router } from '@solidjs/router';import { TrialBanner } from '@/components/shared/TrialBanner';import trialBannerSource from '@/components/shared/TrialBanner.tsx?raw';import trialBannerModelSource from '@/components/shared/trialBannerModel.ts?raw';@@ -11,8 +12,8 @@ const {demoModeEnabledMock,getUpgradeActionDestinationMock,getUpgradeActionUrlOrFallbackMock,- licenseStatusMock,- loadLicenseStatusMock,+ commercialPostureMock,+ loadCommercialPostureMock,isUpsellSnoozedMock,snoozeUpsellMock,} =@@ -20,8 +21,8 @@ const {demoModeEnabledMock: vi.fn(),getUpgradeActionDestinationMock: vi.fn(),getUpgradeActionUrlOrFallbackMock: vi.fn(),- licenseStatusMock: vi.fn(),- loadLicenseStatusMock: vi.fn(),+ commercialPostureMock: vi.fn(),+ loadCommercialPostureMock: vi.fn(),isUpsellSnoozedMock: vi.fn(),snoozeUpsellMock: vi.fn(),}));@@ -29,8 +30,8 @@ const {vi.mock('@/stores/licenseCommercial', () => ({getUpgradeActionDestination: (...args: unknown[]) => getUpgradeActionDestinationMock(...args),getUpgradeActionUrlOrFallback: (...args: unknown[]) => getUpgradeActionUrlOrFallbackMock(...args),- licenseStatus: (...args: unknown[]) => licenseStatusMock(...args),- loadLicenseStatus: (...args: unknown[]) => loadLicenseStatusMock(...args),+ commercialPosture: (...args: unknown[]) => commercialPostureMock(...args),+ loadCommercialPosture: (...args: unknown[]) => loadCommercialPostureMock(...args),}));vi.mock('@/stores/demoMode', () => ({@@ -43,13 +44,19 @@ vi.mock('@/utils/snooze', () => ({}));describe('TrialBanner', () => {+ const renderBanner = () => render(() => (+ <Router>+ <Route path="/" component={() => <TrialBanner />} />+ </Router>+ ));+beforeEach(() => {cleanup();demoModeEnabledMock.mockReset();getUpgradeActionDestinationMock.mockReset();getUpgradeActionUrlOrFallbackMock.mockReset();- licenseStatusMock.mockReset();- loadLicenseStatusMock.mockReset();+ commercialPostureMock.mockReset();+ loadCommercialPostureMock.mockReset();isUpsellSnoozedMock.mockReset();snoozeUpsellMock.mockReset();getUpgradeActionDestinationMock.mockReturnValue({@@ -58,7 +65,7 @@ describe('TrialBanner', () => {});demoModeEnabledMock.mockReturnValue(false);getUpgradeActionUrlOrFallbackMock.mockReturnValue(getPublicPricingUrl('trial_banner'));- loadLicenseStatusMock.mockResolvedValue(undefined);+ loadCommercialPostureMock.mockResolvedValue(undefined);isUpsellSnoozedMock.mockReturnValue(false);});@@ -78,9 +85,9 @@ describe('TrialBanner', () => {expect(trialBannerStateSource).toContain('export function useTrialBannerState');expect(trialBannerStateSource).toContain('createSignal');expect(trialBannerStateSource).toContain('createMemo');- expect(trialBannerStateSource).toContain('loadLicenseStatus');+ expect(trialBannerStateSource).toContain('loadCommercialPosture');expect(trialBannerStateSource).toContain('demoModeEnabled');- expect(trialBannerStateSource).toContain('licenseStatus');+ expect(trialBannerStateSource).toContain('commercialPosture');expect(trialBannerStateSource).toContain('getUpgradeActionDestination');expect(trialBannerStateSource).toContain('snoozeUpsell');@@ -91,16 +98,16 @@ describe('TrialBanner', () => {expect(trialBannerModelSource).toContain('TRIAL_BANNER_UPGRADE_LABEL');});- it('loads license status on mount and renders trial details when active', async () => {- licenseStatusMock.mockReturnValue({+ it('loads commercial posture on mount and renders trial details when active', async () => {+ commercialPostureMock.mockReturnValue({subscription_state: 'trial',trial_days_remaining: 4.8,});- render(() => <TrialBanner />);+ renderBanner();await waitFor(() => {- expect(loadLicenseStatusMock).toHaveBeenCalled();+ expect(loadCommercialPostureMock).toHaveBeenCalled();});expect(screen.getByRole('status')).toBeInTheDocument();expect(screen.getByText('Pro Trial:')).toBeInTheDocument();@@ -112,35 +119,35 @@ describe('TrialBanner', () => {});it('shows active fallback when trial days are unavailable', () => {- licenseStatusMock.mockReturnValue({+ commercialPostureMock.mockReturnValue({subscription_state: 'trial',trial_days_remaining: undefined,});- render(() => <TrialBanner />);+ renderBanner();expect(screen.getByText('Active')).toBeInTheDocument();});it('stays hidden in demo mode even when the workspace is on trial', () => {demoModeEnabledMock.mockReturnValue(true);- licenseStatusMock.mockReturnValue({+ commercialPostureMock.mockReturnValue({subscription_state: 'trial',trial_days_remaining: 2,});- render(() => <TrialBanner />);+ renderBanner();expect(screen.queryByRole('status')).toBeNull();});it('snoozes and hides the action row', async () => {- licenseStatusMock.mockReturnValue({+ commercialPostureMock.mockReturnValue({subscription_state: 'trial',trial_days_remaining: 2,});- render(() => <TrialBanner />);+ renderBanner();fireEvent.click(screen.getByRole('button', { name: 'Snooze 7d' }));diff --git a/frontend-modern/src/components/shared/__tests__/UpgradeLink.test.tsx b/frontend-modern/src/components/shared/__tests__/UpgradeLink.test.tsxindex 70ccbfddc2..91d11ea7dc 100644--- a/frontend-modern/src/components/shared/__tests__/UpgradeLink.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/UpgradeLink.test.tsx@@ -52,4 +52,32 @@ describe('UpgradeLink', () => {expect(link).toHaveAttribute('target', '_blank');expect(link).toHaveAttribute('rel', 'noopener noreferrer');});++ it('preserves opener access for self-hosted purchase-start links', () => {+ render(() => (+ <Router>+ <Route+ path="/"+ component={() => (+ <UpgradeLink+ destination={{+ href: '/auth/license-purchase-start?feature=relay',+ external: false,+ hardNavigation: true,+ newTab: true,+ preserveOpener: true,+ }}+ >+ Compare plans+ </UpgradeLink>+ )}+ />+ </Router>+ ));++ const link = screen.getByRole('link', { name: 'Compare plans' });+ expect(link).toHaveAttribute('href', '/auth/license-purchase-start?feature=relay');+ expect(link).toHaveAttribute('target', '_blank');+ expect(link).not.toHaveAttribute('rel');+ });});diff --git a/frontend-modern/src/components/shared/activeUseTrialNudgeModel.ts b/frontend-modern/src/components/shared/activeUseTrialNudgeModel.tsindex 0de6f48e3e..e26630057c 100644--- a/frontend-modern/src/components/shared/activeUseTrialNudgeModel.ts+++ b/frontend-modern/src/components/shared/activeUseTrialNudgeModel.ts@@ -1,4 +1,4 @@-import type { LicenseEntitlements } from '@/api/license';+import type { LicenseCommercialPosture } from '@/api/license';export const ACTIVE_USE_TRIAL_NUDGE_SNOOZE_KEY = 'pulse_active_use_nudge_snoozed';export const ACTIVE_USE_TRIAL_NUDGE_FIRST_SEEN_KEY = 'pulse_first_seen_ts';@@ -12,7 +12,7 @@ export const ACTIVE_USE_TRIAL_NUDGE_STARTING_LABEL = 'Starting...';export const ACTIVE_USE_TRIAL_NUDGE_SNOOZE_LABEL = 'Snooze 7d';export function isActiveUseTrialNudgeEligible(- entitlements: LicenseEntitlements | null | undefined,+ entitlements: LicenseCommercialPosture | null | undefined,): boolean {if (!entitlements) return false;diff --git a/frontend-modern/src/components/shared/useActiveUseTrialNudgeState.ts b/frontend-modern/src/components/shared/useActiveUseTrialNudgeState.tsindex b84e10291c..ea389df38a 100644--- a/frontend-modern/src/components/shared/useActiveUseTrialNudgeState.ts+++ b/frontend-modern/src/components/shared/useActiveUseTrialNudgeState.ts@@ -1,5 +1,5 @@import { createMemo, createSignal, onCleanup, onMount } from 'solid-js';-import { licenseStatus, loadLicenseStatus } from '@/stores/licenseCommercial';+import { commercialPosture, loadCommercialPosture } from '@/stores/licenseCommercial';import { notificationStore } from '@/stores/notifications';import { isUpsellSnoozed, snoozeUpsell } from '@/utils/snooze';import { runStartProTrialAction } from '@/utils/trialStartAction';@@ -38,7 +38,7 @@ export function useActiveUseTrialNudgeState() {const [startingTrial, setStartingTrial] = createSignal(false);onMount(() => {- void loadLicenseStatus();+ void loadCommercialPosture();setFirstSeen(getActiveUseTrialNudgeFirstSeenTimestamp());const timer = window.setInterval(() => setNow(Date.now()), ACTIVE_USE_TRIAL_NUDGE_REFRESH_MS);onCleanup(() => window.clearInterval(timer));@@ -47,7 +47,7 @@ export function useActiveUseTrialNudgeState() {const shouldShow = createMemo(() => {return (isActiveUseTrialNudgeOldEnough(now(), firstSeen()) &&- isActiveUseTrialNudgeEligible(licenseStatus()) &&+ isActiveUseTrialNudgeEligible(commercialPosture()) &&!snoozed());});diff --git a/frontend-modern/src/components/shared/useHistoryChartState.ts b/frontend-modern/src/components/shared/useHistoryChartState.tsindex 2b5dc68624..cd2e636f9f 100644--- a/frontend-modern/src/components/shared/useHistoryChartState.ts+++ b/frontend-modern/src/components/shared/useHistoryChartState.ts@@ -12,9 +12,9 @@ import {maxHistoryDays,} from '@/stores/license';import {+ commercialPosture,getUpgradeActionDestination,- licenseStatus,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { calculateOptimalPoints } from '@/utils/downsample';import { setupCanvasDPR } from '@/utils/canvasRenderQueue';@@ -55,7 +55,7 @@ export function useHistoryChartState(props: HistoryChartProps, refs: HistoryCharconst [hoveredPoint, setHoveredPoint] = createSignal<HistoryChartHoverPoint | null>(null);const canStartTrial = createMemo(() => {- const ent = licenseStatus();+ const ent = commercialPosture();if (!ent) return false;if (ent.subscription_state === 'active' || ent.subscription_state === 'trial') return false;return ent.trial_eligible !== false;@@ -79,7 +79,7 @@ export function useHistoryChartState(props: HistoryChartProps, refs: HistoryCharonMount(() => {loadLicenseStatus();- loadCommercialLicenseStatus();+ loadCommercialPosture();});createEffect(() => {diff --git a/frontend-modern/src/components/shared/useMonitoredSystemLimitWarningBannerState.ts b/frontend-modern/src/components/shared/useMonitoredSystemLimitWarningBannerState.tsindex f0c6931fce..eb6562e824 100644--- a/frontend-modern/src/components/shared/useMonitoredSystemLimitWarningBannerState.ts+++ b/frontend-modern/src/components/shared/useMonitoredSystemLimitWarningBannerState.ts@@ -1,12 +1,15 @@import { createEffect, createMemo, onMount } from 'solid-js';import { demoModeEnabled } from '@/stores/demoMode';import {- entitlements,getLimit,+ loadLicenseStatus as loadRuntimeLicenseStatus,+} from '@/stores/license';+import {+ commercialPosture,getUpgradeActionDestination,hasMigrationGap,legacyConnections,- loadLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { resolveUpgradeDestination } from '@/utils/upgradeNavigation';import {@@ -33,7 +36,8 @@ import {export function useMonitoredSystemLimitWarningBannerState() {onMount(() => {- void loadLicenseStatus();+ void loadRuntimeLicenseStatus();+ void loadCommercialPosture();});const monitoredSystemLimit = createMemo(() => getLimit(MONITORED_SYSTEM_LIMIT_KEY));@@ -50,7 +54,7 @@ export function useMonitoredSystemLimitWarningBannerState() {getMonitoredSystemMigrationMessage(migrationCounts()),);const overflowSummary = createMemo(() =>- getMonitoredSystemOverflowSummary(entitlements()?.overflow_days_remaining),+ getMonitoredSystemOverflowSummary(commercialPosture()?.overflow_days_remaining),);const toneClass = createMemo(() => getMonitoredSystemBannerToneClass(isUrgent()));const migrationTextClass = createMemo(() =>diff --git a/frontend-modern/src/components/shared/useTrialBannerState.ts b/frontend-modern/src/components/shared/useTrialBannerState.tsindex d6b5157beb..00cc643559 100644--- a/frontend-modern/src/components/shared/useTrialBannerState.ts+++ b/frontend-modern/src/components/shared/useTrialBannerState.ts@@ -1,9 +1,9 @@import { createMemo, createSignal, onMount } from 'solid-js';import { demoModeEnabled } from '@/stores/demoMode';import {+ commercialPosture,getUpgradeActionDestination,- licenseStatus,- loadLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { isUpsellSnoozed, snoozeUpsell } from '@/utils/snooze';import {@@ -17,14 +17,14 @@ export function useTrialBannerState() {const [snoozed, setSnoozed] = createSignal(isUpsellSnoozed(TRIAL_BANNER_SNOOZE_KEY));onMount(() => {- void loadLicenseStatus();+ void loadCommercialPosture();});const isTrial = createMemo(- () => !demoModeEnabled() && licenseStatus()?.subscription_state === 'trial',+ () => !demoModeEnabled() && commercialPosture()?.subscription_state === 'trial',);const daysRemaining = createMemo(() =>- normalizeTrialBannerDaysRemaining(licenseStatus()?.trial_days_remaining),+ normalizeTrialBannerDaysRemaining(commercialPosture()?.trial_days_remaining),);const toneClass = createMemo(() => getTrialBannerToneClass(daysRemaining()));const upgradeDestination = createMemo(() =>diff --git a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.tsindex fa9cff1529..2f76cb22bf 100644--- a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts+++ b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts@@ -27,9 +27,9 @@ import {loadLicenseStatus,} from '@/stores/license';import {+ commercialPosture,getUpgradeActionDestination,- licenseStatus,- loadLicenseStatus as loadCommercialLicenseStatus,+ loadCommercialPosture,} from '@/stores/licenseCommercial';import { getCanonicalScopeResourceIds } from '@/utils/patrolFormat';import { buildPatrolInvestigationContextSummary } from './patrolInvestigationContextModel';@@ -171,7 +171,7 @@ export function usePatrolIntelligenceState() {const autoFixLocked = createMemo(() => !hasFeature('ai_autofix'));const canStartTrial = createMemo(() => {- const entitlements = licenseStatus();+ const entitlements = commercialPosture();if (!entitlements) return false;if (entitlements.subscription_state === 'active' ||@@ -673,7 +673,7 @@ export function usePatrolIntelligenceState() {onMount(async () => {await Promise.all([loadLicenseStatus(),- loadCommercialLicenseStatus(),+ loadCommercialPosture(),loadAllData(),loadAutonomySettings(),loadModels(),diff --git a/frontend-modern/src/pages/PricingHandoff.tsx b/frontend-modern/src/pages/PricingHandoff.tsxindex 28321d2188..2acbc22a00 100644--- a/frontend-modern/src/pages/PricingHandoff.tsx+++ b/frontend-modern/src/pages/PricingHandoff.tsx@@ -5,6 +5,7 @@ import {getPricingRouteDestination,handoffToExternalPricing,isExternalPricingDestination,+ isSelfHostedPurchaseStartDestination,isPulseAccountPortalDestination,} from '@/utils/pricingHandoff';@@ -12,8 +13,11 @@ export default function PricingHandoff() {const location = useLocation();const destination = createMemo(() => getPricingRouteDestination(location.search));const externalDestination = createMemo(() => isExternalPricingDestination(destination()));+ const selfHostedPurchaseStartDestination = createMemo(() =>+ isSelfHostedPurchaseStartDestination(destination()),+ );const pulseAccountDestination = createMemo(() =>- isPulseAccountPortalDestination(destination()),+ isPulseAccountPortalDestination(destination()) || selfHostedPurchaseStartDestination(),);const handoffLabel = createMemo(() =>pulseAccountDestination() ? 'Pulse Account' : 'pricing',@@ -24,13 +28,16 @@ export default function PricingHandoff() {onMount(() => {trackPaywallViewed('pricing', 'pricing_handoff');- if (externalDestination()) {+ if (externalDestination() || selfHostedPurchaseStartDestination()) {handoffToExternalPricing(destination());}});return (- <Show when={externalDestination()} fallback={<Navigate href={destination()} />}>+ <Show+ when={externalDestination() || selfHostedPurchaseStartDestination()}+ fallback={<Navigate href={destination()} />}+ ><div class="flex min-h-[50vh] items-center justify-center"><div class="space-y-2 text-center"><h1 class="text-lg font-semibold text-base-content">diff --git a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsxindex 7fbf36426c..a76a38b3c9 100644--- a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx+++ b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx@@ -102,6 +102,7 @@ const apiFetchJSONMock = vi.fn();const hasFeatureMock = vi.fn();const licenseStatusMock = vi.fn();const loadLicenseStatusMock = vi.fn();+const loadCommercialPostureMock = vi.fn();const startProTrialMock = vi.fn();const getUpgradeActionDestinationMock = vi.fn();const getUpgradeActionUrlOrFallbackMock = vi.fn();@@ -135,7 +136,9 @@ vi.mock('@/stores/license', () => ({vi.mock('@/stores/licenseCommercial', () => ({getUpgradeActionDestination: (...args: unknown[]) => getUpgradeActionDestinationMock(...args),+ commercialPosture: (...args: unknown[]) => licenseStatusMock(...args),licenseStatus: (...args: unknown[]) => licenseStatusMock(...args),+ loadCommercialPosture: (...args: unknown[]) => loadCommercialPostureMock(...args),loadLicenseStatus: (...args: unknown[]) => loadLicenseStatusMock(...args),startProTrial: (...args: unknown[]) => startProTrialMock(...args),getUpgradeActionUrlOrFallback: (...args: unknown[]) => getUpgradeActionUrlOrFallbackMock(...args),@@ -323,6 +326,7 @@ describe('AIIntelligence entitlement gating', () => {hasFeatureMock.mockReset();licenseStatusMock.mockReset();loadLicenseStatusMock.mockReset();+ loadCommercialPostureMock.mockReset();startProTrialMock.mockReset();getUpgradeActionDestinationMock.mockReset();getUpgradeActionUrlOrFallbackMock.mockReset();@@ -371,6 +375,7 @@ describe('AIIntelligence entitlement gating', () => {);licenseStatusMock.mockReturnValue({ subscription_state: 'expired' });loadLicenseStatusMock.mockResolvedValue(undefined);+ loadCommercialPostureMock.mockResolvedValue(undefined);startProTrialMock.mockResolvedValue({ outcome: 'started' });getUpgradeActionDestinationMock.mockImplementation((feature?: string) => ({href: getPublicPricingUrl(feature),diff --git a/frontend-modern/src/pages/__tests__/PricingHandoff.test.tsx b/frontend-modern/src/pages/__tests__/PricingHandoff.test.tsxindex a2f43c0db8..ff62249f2e 100644--- a/frontend-modern/src/pages/__tests__/PricingHandoff.test.tsx+++ b/frontend-modern/src/pages/__tests__/PricingHandoff.test.tsx@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cleanup, render, screen, waitFor } from '@solidjs/testing-library';import { Route, Router } from '@solidjs/router';import PricingHandoff from '@/pages/PricingHandoff';-import { getPulseAccountPortalUpgradeUrl } from '@/utils/pricingHandoff';+import { getSelfHostedPurchaseStartUrl } from '@/utils/pricingHandoff';const trackPaywallViewedMock = vi.fn();const handoffToExternalPricingMock = vi.fn();@@ -35,10 +35,9 @@ describe('PricingHandoff', () => {it('hands self-hosted upgrade requests off to Pulse Account', async () => {window.history.replaceState({}, '', '/pricing?feature=relay');- const expectedDestination = getPulseAccountPortalUpgradeUrl(+ const expectedDestination = getSelfHostedPurchaseStartUrl('relay',- undefined,- 'http://localhost:3000/pricing?feature=relay',+ new URLSearchParams('feature=relay'),);render(() => (diff --git a/frontend-modern/src/stores/__tests__/license.test.ts b/frontend-modern/src/stores/__tests__/license.test.tsindex df6a3292ee..bda22b40f3 100644--- a/frontend-modern/src/stores/__tests__/license.test.ts+++ b/frontend-modern/src/stores/__tests__/license.test.ts@@ -2,10 +2,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import {LicenseAPI,type LicenseCommercialEntitlements,+ type LicenseCommercialPosture,type LicenseRuntimeCapabilities,} from '@/api/license';import { demoModeEnabled } from '@/stores/demoMode';-import { getPulseAccountPortalUpgradeUrl } from '@/utils/pricingHandoff';+import { getUpgradeFallbackDestination } from '@/utils/pricingHandoff';import {getLimit,hasFeature,@@ -19,7 +20,7 @@ import {runtimeCapabilities,} from '@/stores/license';import {- entitlements,+ commercialPosture,getFirstUpgradeActionUrl,getUpgradeActionUrl,getUpgradeActionUrlOrFallback,@@ -27,10 +28,15 @@ import {hasMigrationGap,isPro,legacyConnections,- licenseLoadError as commercialLicenseLoadError,- loadLicenseStatus as loadCommercialLicenseStatus,+ commercialPostureLoadError,+ loadCommercialPosture,startProTrial,} from '@/stores/licenseCommercial';+import {+ licenseEntitlements,+ licenseEntitlementsLoadError,+ loadLicenseEntitlements,+} from '@/stores/licenseEntitlements';vi.mock('@/api/license');vi.mock('@/stores/demoMode', () => ({@@ -48,17 +54,13 @@ describe('license stores', () => {max_history_days: 90,};- const mockCommercialEntitlements: LicenseCommercialEntitlements = {+ const mockCommercialPosture: LicenseCommercialPosture = {tier: 'pro',subscription_state: 'active',- capabilities: mockRuntimeCapabilities.capabilities,- limits: mockRuntimeCapabilities.limits,upgrade_reasons: [{ key: 'reason1', reason: 'Reason 1', action_url: '/upgrade/reason1' },{ key: 'reason2', reason: 'Reason 2', action_url: '/upgrade/reason2' },],- hosted_mode: false,- max_history_days: 90,legacy_connections: {proxmox_nodes: 2,docker_hosts: 1,@@ -66,6 +68,13 @@ describe('license stores', () => {},has_migration_gap: true,};+ const mockCommercialEntitlements: LicenseCommercialEntitlements = {+ ...mockCommercialPosture,+ capabilities: mockRuntimeCapabilities.capabilities,+ limits: mockRuntimeCapabilities.limits,+ hosted_mode: false,+ max_history_days: 90,+ };const mockFreeRuntimeCapabilities: LicenseRuntimeCapabilities = {capabilities: [],@@ -74,12 +83,16 @@ describe('license stores', () => {max_history_days: 7,};- const mockFreeCommercialEntitlements: LicenseCommercialEntitlements = {+ const mockFreeCommercialPosture: LicenseCommercialPosture = {tier: 'free',subscription_state: 'expired',+ upgrade_reasons: [],+ };++ const mockFreeCommercialEntitlements: LicenseCommercialEntitlements = {+ ...mockFreeCommercialPosture,capabilities: [],limits: [],- upgrade_reasons: [],hosted_mode: false,max_history_days: 7,};@@ -237,20 +250,17 @@ describe('license stores', () => {});});- describe('commercial entitlement store', () => {- it('suppresses commercial entitlement reads in demo mode', async () => {+ describe('commercial posture store', () => {+ it('suppresses commercial posture reads in demo mode', async () => {vi.mocked(demoModeEnabled).mockReturnValue(true);- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);- expect(LicenseAPI.getCommercialEntitlements).not.toHaveBeenCalled();- expect(entitlements()).toEqual({- capabilities: ['update_alerts', 'sso', 'ai_patrol'],- limits: [],+ expect(LicenseAPI.getCommercialPosture).not.toHaveBeenCalled();+ expect(commercialPosture()).toEqual({subscription_state: 'expired',upgrade_reasons: [],tier: 'free',- hosted_mode: false,trial_eligible: false,legacy_connections: {proxmox_nodes: 0,@@ -260,30 +270,27 @@ describe('license stores', () => {has_migration_gap: false,commercial_migration: undefined,});- expect(commercialLicenseLoadError()).toBeNull();+ expect(commercialPostureLoadError()).toBeNull();});- it('loads commercial entitlements from API', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);+ it('loads commercial posture from API', async () => {+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockCommercialPosture);- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);- expect(LicenseAPI.getCommercialEntitlements).toHaveBeenCalled();- expect(entitlements()).toEqual(mockCommercialEntitlements);+ expect(LicenseAPI.getCommercialPosture).toHaveBeenCalled();+ expect(commercialPosture()).toEqual(mockCommercialPosture);});- it('sets commercial fallback entitlements on error', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockRejectedValue(new Error('API error'));+ it('sets commercial fallback posture on error', async () => {+ vi.mocked(LicenseAPI.getCommercialPosture).mockRejectedValue(new Error('API error'));- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);- expect(entitlements()).toEqual({- capabilities: ['update_alerts', 'sso', 'ai_patrol'],- limits: [],+ expect(commercialPosture()).toEqual({subscription_state: 'expired',upgrade_reasons: [],tier: 'free',- hosted_mode: false,trial_eligible: false,legacy_connections: {proxmox_nodes: 0,@@ -296,14 +303,12 @@ describe('license stores', () => {});it('sets commercial loadError on API failure', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockRejectedValue(- new Error('Network timeout'),- );+ vi.mocked(LicenseAPI.getCommercialPosture).mockRejectedValue(new Error('Network timeout'));- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);- expect(commercialLicenseLoadError()).toBeInstanceOf(Error);- expect(commercialLicenseLoadError()?.message).toBe('Network timeout');+ expect(commercialPostureLoadError()).toBeInstanceOf(Error);+ expect(commercialPostureLoadError()?.message).toBe('Network timeout');});it('startProTrial throws error if trial start fails', async () => {@@ -366,61 +371,61 @@ describe('license stores', () => {it('startProTrial refreshes commercial and runtime state when local activation succeeds', async () => {vi.mocked(LicenseAPI.startTrial).mockResolvedValue({ ok: true } as Response);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockCommercialPosture);vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);vi.mocked(LicenseAPI.getRuntimeCapabilities).mockResolvedValue(mockRuntimeCapabilities);await expect(startProTrial()).resolves.toEqual({ outcome: 'activated' });+ expect(LicenseAPI.getCommercialPosture).toHaveBeenCalled();expect(LicenseAPI.getCommercialEntitlements).toHaveBeenCalled();expect(LicenseAPI.getRuntimeCapabilities).toHaveBeenCalled();});it('returns true for pro tier', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);- await loadCommercialLicenseStatus(true);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockCommercialPosture);+ await loadCommercialPosture(true);expect(isPro()).toBe(true);});it('returns true for pro_plus tier', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue({- ...mockCommercialEntitlements,+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue({+ ...mockCommercialPosture,tier: 'pro_plus',});- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);expect(isPro()).toBe(true);});it('returns false for relay tier (paid but not Pro)', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue({- ...mockCommercialEntitlements,+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue({+ ...mockCommercialPosture,tier: 'relay',});- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);expect(isPro()).toBe(false);});it('returns false for free tier', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(- mockFreeCommercialEntitlements,- );- await loadCommercialLicenseStatus(true);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockFreeCommercialPosture);+ await loadCommercialPosture(true);expect(isPro()).toBe(false);});it('returns upgrade reason by key', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);- await loadCommercialLicenseStatus(true);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockCommercialPosture);+ await loadCommercialPosture(true);expect(getUpgradeReason('reason2')?.key).toBe('reason2');});it('returns undefined for unknown key', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);- await loadCommercialLicenseStatus(true);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockCommercialPosture);+ await loadCommercialPosture(true);expect(getUpgradeReason('unknown')).toBeUndefined();});- it('returns legacy connection counts from entitlements', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);- await loadCommercialLicenseStatus(true);+ it('returns legacy connection counts from posture', async () => {+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockCommercialPosture);+ await loadCommercialPosture(true);expect(legacyConnections()).toEqual({proxmox_nodes: 2,@@ -431,12 +436,12 @@ describe('license stores', () => {});it('falls back to zero legacy counts when absent', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue({- ...mockFreeCommercialEntitlements,+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue({+ ...mockFreeCommercialPosture,legacy_connections: undefined,has_migration_gap: undefined,});- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);expect(legacyConnections()).toEqual({proxmox_nodes: 0,@@ -447,57 +452,49 @@ describe('license stores', () => {});it('returns action URL for upgrade reason', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);- await loadCommercialLicenseStatus(true);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockCommercialPosture);+ await loadCommercialPosture(true);expect(getUpgradeActionUrl('reason1')).toBe('/upgrade/reason1');});it('returns first upgrade reason URL', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);- await loadCommercialLicenseStatus(true);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockCommercialPosture);+ await loadCommercialPosture(true);expect(getFirstUpgradeActionUrl()).toBe('/upgrade/reason1');});it('routes missing self-hosted upgrades to Pulse Account when no upgrade reasons exist', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(- mockFreeCommercialEntitlements,- );- await loadCommercialLicenseStatus(true);- expect(getUpgradeActionUrlOrFallback('relay')).toBe(getPulseAccountPortalUpgradeUrl('relay'));+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockFreeCommercialPosture);+ await loadCommercialPosture(true);+ expect(getUpgradeActionUrlOrFallback('relay')).toBe(getUpgradeFallbackDestination('relay'));});it('routes monitored-system limit fallbacks to the billing upgrade arrival', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue({- ...mockCommercialEntitlements,+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue({+ ...mockCommercialPosture,upgrade_reasons: [{ key: 'reason1', reason: 'Reason 1', action_url: '/upgrade/reason1' }],});- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);expect(getUpgradeActionUrlOrFallback('max_monitored_systems')).toBe('/settings/system/billing/plan?intent=max_monitored_systems',);});it('routes cloud fallbacks to the in-product cloud plans page', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(- mockFreeCommercialEntitlements,- );- await loadCommercialLicenseStatus(true);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockFreeCommercialPosture);+ await loadCommercialPosture(true);expect(getUpgradeActionUrlOrFallback('cloud')).toBe('/cloud');});it('routes generic upgrade fallbacks to Pulse Account', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(- mockFreeCommercialEntitlements,- );- await loadCommercialLicenseStatus(true);- expect(getUpgradeActionUrlOrFallback('upgrade')).toBe(- getPulseAccountPortalUpgradeUrl('upgrade'),- );+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockFreeCommercialPosture);+ await loadCommercialPosture(true);+ expect(getUpgradeActionUrlOrFallback('upgrade')).toBe(getUpgradeFallbackDestination('upgrade'));});it('prefers a specific monitored-system upgrade action when provided', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue({- ...mockCommercialEntitlements,+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue({+ ...mockCommercialPosture,upgrade_reasons: [{key: 'max_monitored_systems',@@ -506,20 +503,64 @@ describe('license stores', () => {},],});- await loadCommercialLicenseStatus(true);+ await loadCommercialPosture(true);expect(getUpgradeActionUrlOrFallback('max_monitored_systems')).toBe(- '/upgrade/max-monitored-systems',+ getUpgradeFallbackDestination('max_monitored_systems'),);});it('routes unknown keys to Pulse Account as a last resort', async () => {- vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(- mockFreeCommercialEntitlements,- );- await loadCommercialLicenseStatus(true);+ vi.mocked(LicenseAPI.getCommercialPosture).mockResolvedValue(mockFreeCommercialPosture);+ await loadCommercialPosture(true);expect(getUpgradeActionUrlOrFallback('feature1')).toBe(- getPulseAccountPortalUpgradeUrl('feature1'),+ getUpgradeFallbackDestination('feature1'),);});});++ describe('billing entitlements store', () => {+ it('suppresses full entitlements reads in demo mode', async () => {+ vi.mocked(demoModeEnabled).mockReturnValue(true);++ await loadLicenseEntitlements(true);++ expect(LicenseAPI.getCommercialEntitlements).not.toHaveBeenCalled();+ expect(licenseEntitlements()).toEqual({+ capabilities: ['update_alerts', 'sso', 'ai_patrol'],+ limits: [],+ subscription_state: 'expired',+ upgrade_reasons: [],+ tier: 'free',+ trial_eligible: false,+ legacy_connections: {+ proxmox_nodes: 0,+ docker_hosts: 0,+ kubernetes_clusters: 0,+ },+ has_migration_gap: false,+ commercial_migration: undefined,+ });+ expect(licenseEntitlementsLoadError()).toBeNull();+ });++ it('loads full billing entitlements from API', async () => {+ vi.mocked(LicenseAPI.getCommercialEntitlements).mockResolvedValue(mockCommercialEntitlements);++ await loadLicenseEntitlements(true);++ expect(LicenseAPI.getCommercialEntitlements).toHaveBeenCalled();+ expect(licenseEntitlements()).toEqual(mockCommercialEntitlements);+ });++ it('sets billing loadError on API failure', async () => {+ vi.mocked(LicenseAPI.getCommercialEntitlements).mockRejectedValue(+ new Error('billing unavailable'),+ );++ await loadLicenseEntitlements(true);++ expect(licenseEntitlementsLoadError()).toBeInstanceOf(Error);+ expect(licenseEntitlementsLoadError()?.message).toBe('billing unavailable');+ });+ });});diff --git a/frontend-modern/src/stores/licenseCommercial.ts b/frontend-modern/src/stores/licenseCommercial.tsindex c944ed068e..f487cc6acf 100644--- a/frontend-modern/src/stores/licenseCommercial.ts+++ b/frontend-modern/src/stores/licenseCommercial.ts@@ -2,7 +2,7 @@ import { createSignal, createMemo, createRoot } from 'solid-js';import {LicenseAPI,type EntitlementLegacyConnections,- type LicenseCommercialEntitlements,+ type LicenseCommercialPosture,} from '@/api/license';import { demoModeEnabled } from '@/stores/demoMode';import { eventBus } from '@/stores/events';@@ -10,20 +10,19 @@ import { logger } from '@/utils/logger';import {getInProductPricingDestination,getUpgradeFallbackDestination,+ isSelfHostedPurchaseStartDestination,} from '@/utils/pricingHandoff';import {resolveUpgradeDestination,type UpgradeDestination,} from '@/utils/upgradeNavigation';import { loadLicenseStatus as loadRuntimeLicenseStatus } from '@/stores/license';+import { loadLicenseEntitlements } from '@/stores/licenseEntitlements';-const FREE_COMMERCIAL_ENTITLEMENTS_FALLBACK: LicenseCommercialEntitlements = {- capabilities: ['update_alerts', 'sso', 'ai_patrol'],- limits: [],+const FREE_COMMERCIAL_POSTURE_FALLBACK: LicenseCommercialPosture = {subscription_state: 'expired',upgrade_reasons: [],tier: 'free',- hosted_mode: false,trial_eligible: false,legacy_connections: {proxmox_nodes: 0,@@ -34,8 +33,8 @@ const FREE_COMMERCIAL_ENTITLEMENTS_FALLBACK: LicenseCommercialEntitlements = {commercial_migration: undefined,};-const [commercialEntitlements, setCommercialEntitlements] =- createSignal<LicenseCommercialEntitlements | null>(null);+const [commercialPostureState, setCommercialPostureState] =+ createSignal<LicenseCommercialPosture | null>(null);const [loading, setLoading] = createSignal(false);const [loaded, setLoaded] = createSignal(false);const [loadError, setLoadError] = createSignal<Error | null>(null);@@ -75,15 +74,15 @@ function parseRetryAfterSeconds(value: string | null | undefined): number | unde}/**- * Load the commercial entitlement payload used by billing, trial, and upgrade UI.+ * Load the commercial posture payload used by non-billing trial and upgrade UI.*/-export async function loadLicenseStatus(force = false): Promise<void> {+export async function loadCommercialPosture(force = false): Promise<void> {if (demoModeEnabled()) {- setCommercialEntitlements(FREE_COMMERCIAL_ENTITLEMENTS_FALLBACK);+ setCommercialPostureState(FREE_COMMERCIAL_POSTURE_FALLBACK);setLoadError(null);setLoaded(true);setLoading(false);- logger.debug('[licenseCommercialStore] Commercial entitlements suppressed in demo mode');+ logger.debug('[licenseCommercialStore] Commercial posture suppressed in demo mode');return;}@@ -91,18 +90,18 @@ export async function loadLicenseStatus(force = false): Promise<void> {setLoading(true);try {- const next = await LicenseAPI.getCommercialEntitlements();- setCommercialEntitlements(next);+ const next = await LicenseAPI.getCommercialPosture();+ setCommercialPostureState(next);setLoadError(null);setLoaded(true);- logger.debug('[licenseCommercialStore] Commercial entitlements loaded', {+ logger.debug('[licenseCommercialStore] Commercial posture loaded', {tier: next.tier,sub_state: next.subscription_state,});} catch (err) {- logger.error('[licenseCommercialStore] Failed to load commercial entitlements', err);+ logger.error('[licenseCommercialStore] Failed to load commercial posture', err);setLoadError(err instanceof Error ? err : new Error(String(err)));- setCommercialEntitlements(FREE_COMMERCIAL_ENTITLEMENTS_FALLBACK);+ setCommercialPostureState(FREE_COMMERCIAL_POSTURE_FALLBACK);setLoaded(true);} finally {setLoading(false);@@ -149,7 +148,11 @@ export async function startProTrial(): Promise<StartProTrialResult> {err.retryAfterSeconds = retryAfterSeconds;throw err;}- await Promise.all([loadLicenseStatus(true), loadRuntimeLicenseStatus(true)]);+ await Promise.all([+ loadCommercialPosture(true),+ loadRuntimeLicenseStatus(true),+ loadLicenseEntitlements(true),+ ]);return { outcome: 'activated' };}@@ -169,13 +172,13 @@ const PRO_TIERS = new Set([*/export const isPro = createRoot(() =>createMemo(() => {- const current = commercialEntitlements();+ const current = commercialPostureState();return Boolean(current && PRO_TIERS.has(current.tier));}),);export function getUpgradeReason(key: string) {- const current = commercialEntitlements();+ const current = commercialPostureState();if (!current?.upgrade_reasons?.length) return undefined;return current.upgrade_reasons.find((reason) => reason.key === key);}@@ -185,32 +188,33 @@ export function getUpgradeActionUrl(key: string): string | undefined {}export function getFirstUpgradeActionUrl(): string | undefined {- const current = commercialEntitlements();+ const current = commercialPostureState();return current?.upgrade_reasons?.[0]?.action_url;}export function getUpgradeActionDestination(key: string): UpgradeDestination {- return resolveUpgradeDestination(- getUpgradeActionUrl(key) ||- getInProductPricingDestination(key) ||- getFirstUpgradeActionUrl() ||- getUpgradeFallbackDestination(key),- );+ const productOwnedHref = key ? getUpgradeFallbackDestination(key) : undefined;+ const href =+ productOwnedHref || getUpgradeActionUrl(key) || getFirstUpgradeActionUrl() || getUpgradeFallbackDestination(key);++ if (isSelfHostedPurchaseStartDestination(href)) {+ return resolveUpgradeDestination(href, {+ hardNavigation: true,+ newTab: true,+ preserveOpener: true,+ });+ }++ return resolveUpgradeDestination(href);}export function getUpgradeActionUrlOrFallback(key: string): string {return getUpgradeActionDestination(key).href;}-export function getLimit(key: string) {- const current = commercialEntitlements();- if (!current?.limits?.length) return undefined;- return current.limits.find((limit) => limit.key === key);-}-export function legacyConnections(): EntitlementLegacyConnections {return (- commercialEntitlements()?.legacy_connections ?? {+ commercialPostureState()?.legacy_connections ?? {proxmox_nodes: 0,docker_hosts: 0,kubernetes_clusters: 0,@@ -219,22 +223,26 @@ export function legacyConnections(): EntitlementLegacyConnections {}export function hasMigrationGap(): boolean {- return Boolean(commercialEntitlements()?.has_migration_gap);+ return Boolean(commercialPostureState()?.has_migration_gap);}-// Ensure org-scoped commercial entitlements do not leak across tenant switches.+// Ensure org-scoped commercial posture does not leak across tenant switches.eventBus.on('org_switched', () => {- setCommercialEntitlements(null);+ setCommercialPostureState(null);setLoaded(false);setLoadError(null);- void loadLicenseStatus(true);+ void loadCommercialPosture(true);});export {- commercialEntitlements,- commercialEntitlements as entitlements,- commercialEntitlements as licenseStatus,+ commercialPostureState as commercialPosture,+ commercialPostureState as entitlements,+ commercialPostureState as licenseStatus,+ loadCommercialPosture as loadLicenseStatus,+ loading as commercialPostureLoading,loading as licenseLoading,+ loaded as commercialPostureLoaded,loaded as licenseLoaded,+ loadError as commercialPostureLoadError,loadError as licenseLoadError,};diff --git a/frontend-modern/src/stores/licenseEntitlements.ts b/frontend-modern/src/stores/licenseEntitlements.tsnew file mode 100644index 0000000000..c5512be472--- /dev/null+++ b/frontend-modern/src/stores/licenseEntitlements.ts@@ -0,0 +1,77 @@+import { createSignal } from 'solid-js';+import { LicenseAPI, type LicenseCommercialEntitlements } from '@/api/license';+import { demoModeEnabled } from '@/stores/demoMode';+import { eventBus } from '@/stores/events';+import { logger } from '@/utils/logger';++const FREE_LICENSE_ENTITLEMENTS_FALLBACK: LicenseCommercialEntitlements = {+ capabilities: ['update_alerts', 'sso', 'ai_patrol'],+ limits: [],+ subscription_state: 'expired',+ upgrade_reasons: [],+ tier: 'free',+ trial_eligible: false,+ legacy_connections: {+ proxmox_nodes: 0,+ docker_hosts: 0,+ kubernetes_clusters: 0,+ },+ has_migration_gap: false,+ commercial_migration: undefined,+};++const [licenseEntitlementsState, setLicenseEntitlementsState] =+ createSignal<LicenseCommercialEntitlements | null>(null);+const [loading, setLoading] = createSignal(false);+const [loaded, setLoaded] = createSignal(false);+const [loadError, setLoadError] = createSignal<Error | null>(null);++/**+ * Load the full commercial entitlement payload used only by billing/identity surfaces.+ */+export async function loadLicenseEntitlements(force = false): Promise<void> {+ if (demoModeEnabled()) {+ setLicenseEntitlementsState(FREE_LICENSE_ENTITLEMENTS_FALLBACK);+ setLoadError(null);+ setLoaded(true);+ setLoading(false);+ logger.debug('[licenseEntitlementsStore] Full entitlements suppressed in demo mode');+ return;+ }++ if (loaded() && !force) return;++ setLoading(true);+ try {+ const next = await LicenseAPI.getCommercialEntitlements();+ setLicenseEntitlementsState(next);+ setLoadError(null);+ setLoaded(true);+ logger.debug('[licenseEntitlementsStore] Full entitlements loaded', {+ tier: next.tier,+ sub_state: next.subscription_state,+ });+ } catch (err) {+ logger.error('[licenseEntitlementsStore] Failed to load full entitlements', err);+ setLoadError(err instanceof Error ? err : new Error(String(err)));+ setLicenseEntitlementsState(FREE_LICENSE_ENTITLEMENTS_FALLBACK);+ setLoaded(true);+ } finally {+ setLoading(false);+ }+}++// Ensure org-scoped billing entitlements do not leak across tenant switches.+eventBus.on('org_switched', () => {+ setLicenseEntitlementsState(null);+ setLoaded(false);+ setLoadError(null);+ void loadLicenseEntitlements(true);+});++export {+ licenseEntitlementsState as licenseEntitlements,+ loading as licenseEntitlementsLoading,+ loaded as licenseEntitlementsLoaded,+ loadError as licenseEntitlementsLoadError,+};diff --git a/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts b/frontend-modern/src/utils/__tests__/pricingHandoff.test.tsindex 20b6012bd1..fadd44f388 100644--- a/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts+++ b/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import {+ getSelfHostedPurchaseStartUrl,getSelfHostedPurchaseReturnUrl,getSelfHostedBillingHref,getSelfHostedBillingPlanIntent,@@ -9,8 +10,10 @@ import {getPublicPricingUrl,getUpgradeFallbackDestination,isExternalPricingDestination,+ isSelfHostedPurchaseStartDestination,resolveCanonicalSelfHostedBillingHref,resolveSelfHostedBillingSection,+ resolveSelfHostedPurchaseStartDestination,scopeSelfHostedBillingDestination,SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL,SELF_HOSTED_PRO_BILLING_PLAN_HREF,@@ -19,6 +22,7 @@ import {SELF_HOSTED_PRO_BILLING_USAGE_COUNTING_RULES_HREF,SELF_HOSTED_PRO_BILLING_USAGE_HREF,SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT,+ SELF_HOSTED_PURCHASE_START_PATH,SELF_HOSTED_PURCHASE_RETURN_PATH,} from '@/utils/pricingHandoff';@@ -35,7 +39,7 @@ describe('pricingHandoff', () => {it('routes self-hosted upgrades to Pulse Account first', () => {expect(getUpgradeFallbackDestination('relay')).toBe(- getPulseAccountPortalUpgradeUrl('relay'),+ getSelfHostedPurchaseStartUrl('relay'),);});@@ -53,7 +57,7 @@ describe('pricingHandoff', () => {it('preserves extra query parameters when handing off the legacy pricing route', () => {expect(getPricingRouteDestination('?feature=relay&utm_content=legacy-bookmark')).toBe(- getPulseAccountPortalUpgradeUrl(+ getSelfHostedPurchaseStartUrl('relay',new URLSearchParams('feature=relay&utm_content=legacy-bookmark'),),@@ -130,21 +134,35 @@ describe('pricingHandoff', () => {});expect(scopeSelfHostedBillingDestination(- { href: getPulseAccountPortalUpgradeUrl('relay'), external: true },+ resolveSelfHostedPurchaseStartDestination('relay'),'usage',{ detail: SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL },),).toEqual({- href: getPulseAccountPortalUpgradeUrl('relay'),- external: true,+ href: getSelfHostedPurchaseStartUrl('relay'),+ external: false,+ hardNavigation: true,+ newTab: true,+ preserveOpener: true,});});it('detects external pricing destinations', () => {expect(isExternalPricingDestination(getPulseAccountPortalUpgradeUrl('relay'))).toBe(true);+ expect(isExternalPricingDestination(getSelfHostedPurchaseStartUrl('relay'))).toBe(false);expect(isExternalPricingDestination('/cloud')).toBe(false);});+ it('detects the internal self-hosted purchase start destination', () => {+ expect(isSelfHostedPurchaseStartDestination(getSelfHostedPurchaseStartUrl('relay'))).toBe(+ true,+ );+ expect(isSelfHostedPurchaseStartDestination(SELF_HOSTED_PURCHASE_START_PATH)).toBe(true);+ expect(isSelfHostedPurchaseStartDestination(getPulseAccountPortalUpgradeUrl('relay'))).toBe(+ false,+ );+ });+it('adds the product return URL to Pulse Account upgrade links when the app origin is known', () => {const withOrigin = getPulseAccountPortalUpgradeUrl('relay',diff --git a/frontend-modern/src/utils/__tests__/upgradeNavigation.test.ts b/frontend-modern/src/utils/__tests__/upgradeNavigation.test.tsindex 749ba52222..5c9750a553 100644--- a/frontend-modern/src/utils/__tests__/upgradeNavigation.test.ts+++ b/frontend-modern/src/utils/__tests__/upgradeNavigation.test.ts@@ -20,10 +20,16 @@ describe('upgradeNavigation', () => {expect(resolveUpgradeDestination(' /cloud ')).toEqual({href: '/cloud',external: false,+ hardNavigation: false,+ newTab: false,+ preserveOpener: false,});expect(resolveUpgradeDestination(' https://pulserelay.pro/pricing ')).toEqual({href: 'https://pulserelay.pro/pricing',external: true,+ hardNavigation: true,+ newTab: true,+ preserveOpener: false,});});@@ -31,7 +37,11 @@ describe('upgradeNavigation', () => {const navigate = vi.fn();const openExternal = vi.fn();- navigateToUpgradeDestination({ href: '/settings/system/billing', external: false }, navigate, openExternal);+ navigateToUpgradeDestination(+ { href: '/settings/system/billing', external: false },+ navigate,+ openExternal,+ );expect(navigate).toHaveBeenCalledWith('/settings/system/billing');expect(openExternal).not.toHaveBeenCalled();@@ -49,6 +59,7 @@ describe('upgradeNavigation', () => {expect(openExternal).toHaveBeenCalledWith('https://pulserelay.pro/pricing?feature=relay',+ false,);expect(navigate).not.toHaveBeenCalled();});@@ -75,4 +86,16 @@ describe('upgradeNavigation', () => {'noopener,noreferrer',);});++ it('opens preserve-opener destinations without noopener so the return bridge can refresh the opener', () => {+ const windowOpen = vi.fn();+ vi.stubGlobal('window', { open: windowOpen });++ openExternalUpgradeDestination('/auth/license-purchase-start?feature=relay', true);++ expect(windowOpen).toHaveBeenCalledWith(+ '/auth/license-purchase-start?feature=relay',+ '_blank',+ );+ });});diff --git a/frontend-modern/src/utils/pricingHandoff.ts b/frontend-modern/src/utils/pricingHandoff.tsindex a59acadb19..5009d84974 100644--- a/frontend-modern/src/utils/pricingHandoff.ts+++ b/frontend-modern/src/utils/pricingHandoff.ts@@ -1,5 +1,6 @@import {isExternalUpgradeHref,+ resolveUpgradeDestination,type UpgradeDestination,} from '@/utils/upgradeNavigation';@@ -7,8 +8,10 @@ const DEFAULT_PUBLIC_PRICING_URL ='https://pulserelay.pro/pricing?utm_source=pulse&utm_medium=app&utm_campaign=upgrade';const DEFAULT_PULSE_ACCOUNT_PORTAL_URL = 'https://cloud.pulserelay.pro/portal';const PULSE_ACCOUNT_PORTAL_UPGRADE_SERVICE = 'upgrade';+export const SELF_HOSTED_PURCHASE_START_PATH = '/auth/license-purchase-start';export const SELF_HOSTED_PURCHASE_RETURN_PATH = '/auth/license-purchase-activate';export const PULSE_ACCOUNT_PORTAL_RETURN_URL_QUERY_PARAM = 'return_url';+export const PULSE_ACCOUNT_PORTAL_RETURN_TOKEN_QUERY_PARAM = 'purchase_return_token';export const SELF_HOSTED_PRO_BILLING_ROUTE = '/settings/system/billing';export const SELF_HOSTED_PRO_BILLING_PLAN_ROUTE = `${SELF_HOSTED_PRO_BILLING_ROUTE}/plan`;@@ -103,6 +106,38 @@ export function getSelfHostedPurchaseReturnUrl(locationHref?: string): string |}}+export function getSelfHostedPurchaseStartUrl(+ feature?: string | null,+ searchParams?: URLSearchParams,+): string {+ const url = new URL(SELF_HOSTED_PURCHASE_START_PATH, INTERNAL_HREF_BASE);+ if (searchParams) {+ for (const [key, value] of searchParams.entries()) {+ const normalizedValue = value.trim();+ if (normalizedValue) {+ url.searchParams.set(key, normalizedValue);+ }+ }+ }++ const normalizedFeature = normalizeFeatureKey(feature);+ if (normalizedFeature) {+ url.searchParams.set('feature', normalizedFeature);+ }+ return `${url.pathname}${url.search}`;+}++export function resolveSelfHostedPurchaseStartDestination(+ feature?: string | null,+ searchParams?: URLSearchParams,+): UpgradeDestination {+ return resolveUpgradeDestination(getSelfHostedPurchaseStartUrl(feature, searchParams), {+ hardNavigation: true,+ newTab: true,+ preserveOpener: true,+ });+}+export function getInProductPricingDestination(feature: string | null | undefined,): string | undefined {@@ -175,7 +210,7 @@ export function getPulseAccountPortalUpgradeUrl(}export function getUpgradeFallbackDestination(feature?: string | null): string {- return getInProductPricingDestination(feature) || getPulseAccountPortalUpgradeUrl(feature);+ return getInProductPricingDestination(feature) || getSelfHostedPurchaseStartUrl(feature);}export function getSelfHostedBillingUsageDetail(@@ -312,7 +347,7 @@ export function getPricingRouteDestination(search: string): string {}if (normalizeFeatureKey(feature)) {- return getPulseAccountPortalUpgradeUrl(feature, params);+ return getSelfHostedPurchaseStartUrl(feature, params);}const url = new URL(DEFAULT_PUBLIC_PRICING_URL);@@ -329,6 +364,18 @@ export function isExternalPricingDestination(destination: string): boolean {return isExternalUpgradeHref(destination);}+export function isSelfHostedPurchaseStartDestination(destination: string): boolean {+ if (isExternalUpgradeHref(destination)) {+ return false;+ }++ try {+ return new URL(destination, INTERNAL_HREF_BASE).pathname === SELF_HOSTED_PURCHASE_START_PATH;+ } catch {+ return false;+ }+}+export function isPulseAccountPortalDestination(destination: string): boolean {if (!isExternalUpgradeHref(destination)) {return false;diff --git a/frontend-modern/src/utils/upgradeNavigation.ts b/frontend-modern/src/utils/upgradeNavigation.tsindex 112d7f8883..0730b27162 100644--- a/frontend-modern/src/utils/upgradeNavigation.ts+++ b/frontend-modern/src/utils/upgradeNavigation.ts@@ -1,6 +1,15 @@export interface UpgradeDestination {href: string;external: boolean;+ hardNavigation?: boolean;+ newTab?: boolean;+ preserveOpener?: boolean;+}++export interface UpgradeDestinationOptions {+ hardNavigation?: boolean;+ newTab?: boolean;+ preserveOpener?: boolean;}function normalizeUpgradeHref(href: string | null | undefined): string {@@ -14,27 +23,47 @@ export function isExternalUpgradeHref(href: string | null | undefined): booleanexport function resolveUpgradeDestination(href: string | null | undefined,+ options: UpgradeDestinationOptions = {},): UpgradeDestination {const normalized = normalizeUpgradeHref(href);+ const external = isExternalUpgradeHref(normalized);return {href: normalized,- external: isExternalUpgradeHref(normalized),+ external,+ hardNavigation: options.hardNavigation ?? external,+ newTab: options.newTab ?? external,+ preserveOpener: options.preserveOpener ?? false,};}-export function openExternalUpgradeDestination(href: string): void {+export function openExternalUpgradeDestination(href: string, preserveOpener = false): void {if (typeof window === 'undefined') return;+ if (preserveOpener) {+ window.open(href, '_blank');+ return;+ }window.open(href, '_blank', 'noopener,noreferrer');}export function navigateToUpgradeDestination(destination: UpgradeDestination,navigate: (href: string) => void,- openExternal: (href: string) => void = openExternalUpgradeDestination,+ openExternal: (href: string, preserveOpener?: boolean) => void = openExternalUpgradeDestination,+ hardNavigate: (href: string) => void = (href) => {+ if (typeof window !== 'undefined') {+ window.location.assign(href);+ }+ },): void {if (!destination.href) return;- if (destination.external) {- openExternal(destination.href);+ const newTab = destination.newTab ?? destination.external;+ const hardNavigation = destination.hardNavigation ?? destination.external;+ if (newTab) {+ openExternal(destination.href, destination.preserveOpener ?? false);+ return;+ }+ if (hardNavigation) {+ hardNavigate(destination.href);return;}navigate(destination.href);diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex a51799454e..360d921d4c 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -4824,6 +4824,7 @@ func TestContract_DemoModeCommercialSurfacePolicy(t *testing.T) {}{{method: http.MethodGet, path: "/api/license/status"},{method: http.MethodGet, path: "/api/license/features"},+ {method: http.MethodGet, path: "/api/license/commercial-posture"},{method: http.MethodGet, path: "/api/license/entitlements"},{method: http.MethodPost, path: "/api/license/activate"},{method: http.MethodPost, path: "/api/license/clear"},@@ -4833,6 +4834,7 @@ func TestContract_DemoModeCommercialSurfacePolicy(t *testing.T) {{method: http.MethodPut, path: "/api/admin/orgs/t-tenant/billing-state"},{method: http.MethodGet, path: "/api/upgrade-metrics/stats"},{method: http.MethodPost, path: "/api/upgrade-metrics/events"},+ {method: http.MethodGet, path: licensePurchaseStartPath},{method: http.MethodGet, path: "/auth/trial-activate"},}diff --git a/internal/api/demo_middleware_test.go b/internal/api/demo_middleware_test.goindex 2511d2b555..c2f770b678 100644--- a/internal/api/demo_middleware_test.go+++ b/internal/api/demo_middleware_test.go@@ -55,8 +55,11 @@ func TestDemoModeMiddleware(t *testing.T) {// Demo mode enabled - commercial surfaces are hidden centrally{"demo on hidden license status", true, http.MethodGet, "/api/license/status", "", false, http.StatusNotFound, true},+ {"demo on hidden commercial posture", true, http.MethodGet, "/api/license/commercial-posture", "", false, http.StatusNotFound, true},{"demo on hidden license entitlements", true, http.MethodGet, "/api/license/entitlements", "", false, http.StatusNotFound, true},+ {"demo on hidden checkout start", true, http.MethodGet, "/auth/license-purchase-start", "", false, http.StatusNotFound, true},{"demo on hidden license activate", true, http.MethodPost, "/api/license/activate", "", false, http.StatusNotFound, true},+ {"demo on hidden purchase start", true, http.MethodGet, licensePurchaseStartPath, "", false, http.StatusNotFound, true},{"demo on hidden trial activation", true, http.MethodGet, "/auth/trial-activate", "", false, http.StatusNotFound, true},{"demo on runtime capabilities", true, http.MethodGet, "/api/license/runtime-capabilities", "", true, http.StatusOK, true},diff --git a/internal/api/demo_mode_commercial.go b/internal/api/demo_mode_commercial.goindex 81c4ab3c33..76ceac334f 100644--- a/internal/api/demo_mode_commercial.go+++ b/internal/api/demo_mode_commercial.go@@ -28,6 +28,16 @@ var publicDemoCommercialPolicies = []publicDemoCommercialRoutePolicy{exposure: publicDemoCommercialExposureHidden,matches: exactDemoCommercialPath("/api/license/features"),},+ {+ route: "GET /api/license/commercial-posture",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/license/commercial-posture"),+ },+ {+ route: "GET /auth/license-purchase-start",+ exposure: publicDemoCommercialExposureHidden,+ matches: exactDemoCommercialMethodPath(http.MethodGet, "/auth/license-purchase-start"),+ },{route: "/api/license/activate",exposure: publicDemoCommercialExposureHidden,diff --git a/internal/api/demo_mode_commercial_test.go b/internal/api/demo_mode_commercial_test.goindex 797fc5020a..4bf24c8b1e 100644--- a/internal/api/demo_mode_commercial_test.go+++ b/internal/api/demo_mode_commercial_test.go@@ -65,6 +65,10 @@ func routeBelongsToPublicDemoCommercialBoundary(route string) bool {switch {case route == "/auth/trial-activate":return true+ case route == licensePurchaseStartPath:+ return true+ case route == "GET "+licensePurchaseStartPath:+ return truecase route == "GET /api/license/runtime-capabilities":return falsecase strings.HasPrefix(route, "/api/license/"):diff --git a/internal/api/entitlement_handlers_test.go b/internal/api/entitlement_handlers_test.goindex 35fb7a9f60..a87e6cfea1 100644--- a/internal/api/entitlement_handlers_test.go+++ b/internal/api/entitlement_handlers_test.go@@ -6,6 +6,7 @@ import ("net/http""net/http/httptest""reflect"+ "strings""testing""time"@@ -168,6 +169,88 @@ func TestBuildEntitlementPayload_NilCapabilities(t *testing.T) {}}+func TestBuildCommercialPosturePayloadWithUsage_CurrentValues(t *testing.T) {+ status := &license.LicenseStatus{+ Valid: true,+ Tier: license.TierFree,+ Features: append([]string(nil), license.TierFeatures[license.TierFree]...),+ MaxMonitoredSystems: 5,+ }++ payload := buildCommercialPosturePayloadWithUsage(status, "", entitlementUsageSnapshot{+ MonitoredSystems: 7,+ LegacyConnections: pkglicensing.LegacyConnectionCounts{+ ProxmoxNodes: 2,+ DockerHosts: 1,+ },+ }, nil)++ if payload.Tier != string(license.TierFree) {+ t.Fatalf("expected tier=%q, got %q", license.TierFree, payload.Tier)+ }+ if payload.SubscriptionState != string(license.SubStateActive) {+ t.Fatalf("expected subscription_state=%q, got %q", license.SubStateActive, payload.SubscriptionState)+ }+ if len(payload.UpgradeReasons) == 0 {+ t.Fatal("expected upgrade reasons for free-tier commercial posture")+ }+ if payload.LegacyConnections.ProxmoxNodes != 2 || payload.LegacyConnections.DockerHosts != 1 {+ t.Fatalf("expected legacy counts to be preserved, got %+v", payload.LegacyConnections)+ }+ if payload.HasMigrationGap {+ t.Fatal("expected has_migration_gap=false under canonical monitored-system counting")+ }+}++func TestHandleCommercialPosture_ActiveLicense(t *testing.T) {+ t.Setenv("PULSE_LICENSE_DEV_MODE", "true")+ handler := createTestHandler(t)+ licenseKey, err := pkglicensing.GenerateLicenseForTesting(+ "[email protected]",+ pkglicensing.TierPro,+ 24*time.Hour,+ )+ if err != nil {+ t.Fatalf("GenerateLicenseForTesting: %v", err)+ }+ if _, err := handler.Service(context.Background()).Activate(licenseKey); err != nil {+ t.Fatalf("Activate() error = %v", err)+ }++ req := httptest.NewRequest(http.MethodGet, "/api/license/commercial-posture", nil)+ rec := httptest.NewRecorder()++ handler.HandleCommercialPosture(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())+ }++ body := rec.Body.String()+ for _, forbidden := range []string{+ `"capabilities"`,+ `"limits"`,+ `"licensed_email"`,+ `"plan_version"`,+ `"max_history_days"`,+ } {+ if strings.Contains(body, forbidden) {+ t.Fatalf("commercial posture leaked field %s in %s", forbidden, body)+ }+ }++ var payload CommercialPosturePayload+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("failed to decode commercial posture payload: %v", err)+ }+ if payload.SubscriptionState != string(license.SubStateActive) {+ t.Fatalf("expected subscription_state %q, got %q", license.SubStateActive, payload.SubscriptionState)+ }+ if payload.Tier != string(license.TierPro) {+ t.Fatalf("expected tier %q, got %q", license.TierPro, payload.Tier)+ }+}+func TestLimitState(t *testing.T) {tests := []struct {name stringdiff --git a/internal/api/license_handlers_test.go b/internal/api/license_handlers_test.goindex 4dbcb96336..c948de3f71 100644--- a/internal/api/license_handlers_test.go+++ b/internal/api/license_handlers_test.go@@ -7,6 +7,7 @@ import ("fmt""net/http""net/http/httptest"+ "net/url""strings""testing""time"@@ -28,6 +29,25 @@ func createTestHandler(t *testing.T) *LicenseHandlers {return NewLicenseHandlers(mtp, false)}+func issuePurchaseReturnToken(t *testing.T, handler *LicenseHandlers, orgID, feature string) string {+ t.Helper()+ handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})+ signingKey, err := handler.purchaseReturnSigningKey()+ if err != nil {+ t.Fatalf("purchaseReturnSigningKey: %v", err)+ }+ token, err := signPurchaseReturnTokenFromLicensing(signingKey, purchaseReturnClaimsModel{+ OrgID: orgID,+ Feature: feature,+ InstanceHost: "pulse.example.com",+ ReturnURL: "https://pulse.example.com/auth/license-purchase-activate",+ })+ if err != nil {+ t.Fatalf("signPurchaseReturnTokenFromLicensing: %v", err)+ }+ return token+}+type licenseFeaturesResponseDTO struct {LicenseStatus string `json:"license_status"`Features map[string]bool `json:"features"`@@ -673,7 +693,66 @@ func TestHandleActivateLicense_ValidKey(t *testing.T) {}}-func TestHandleCheckoutActivation_RedeemsCompletedCheckoutAndRedirectsToBilling(t *testing.T) {+func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *testing.T) {+ handler := createTestHandler(t)+ handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})++ req := httptest.NewRequest(+ http.MethodGet,+ "https://pulse.example.com/auth/license-purchase-start?feature=relay&utm_content=legacy-bookmark",+ nil,+ )+ rec := httptest.NewRecorder()++ handler.HandleCheckoutStart(rec, req)++ if rec.Code != http.StatusSeeOther {+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusSeeOther, rec.Body.String())+ }+ location := rec.Header().Get("Location")+ if location == "" {+ t.Fatal("expected redirect location")+ }+ redirectURL, err := url.Parse(location)+ if err != nil {+ t.Fatalf("parse redirect location: %v", err)+ }+ if redirectURL.Scheme != "https" || redirectURL.Host != "cloud.pulserelay.pro" || redirectURL.Path != "/portal" {+ t.Fatalf("redirect location = %q, want Pulse Account portal", location)+ }+ if got := redirectURL.Query().Get("feature"); got != "relay" {+ t.Fatalf("feature = %q, want relay", got)+ }+ if got := redirectURL.Query().Get("service"); got != "upgrade" {+ t.Fatalf("service = %q, want upgrade", got)+ }+ if got := redirectURL.Query().Get("return_url"); got != "https://pulse.example.com/auth/license-purchase-activate" {+ t.Fatalf("return_url = %q, want canonical purchase callback", got)+ }+ if got := redirectURL.Query().Get("utm_content"); got != "legacy-bookmark" {+ t.Fatalf("utm_content = %q, want preserved query value", got)+ }+ returnToken := redirectURL.Query().Get("purchase_return_token")+ if strings.TrimSpace(returnToken) == "" {+ t.Fatal("expected signed purchase_return_token in redirect")+ }+ signingKey, err := handler.purchaseReturnSigningKey()+ if err != nil {+ t.Fatalf("purchaseReturnSigningKey: %v", err)+ }+ claims, err := verifyPurchaseReturnTokenFromLicensing(returnToken, signingKey, "pulse.example.com", time.Now().UTC())+ if err != nil {+ t.Fatalf("verifyPurchaseReturnTokenFromLicensing: %v", err)+ }+ if claims.OrgID != "default" {+ t.Fatalf("claims.OrgID = %q, want default", claims.OrgID)+ }+ if claims.Feature != "relay" {+ t.Fatalf("claims.Feature = %q, want relay", claims.Feature)+ }+}++func TestHandleCheckoutActivation_RedeemsCompletedCheckoutAndWritesSuccessBridge(t *testing.T) {t.Setenv("PULSE_LICENSE_DEV_MODE", "false")grantJWT, grantPublicKey, err := pkglicensing.GenerateGrantJWTForTesting(pkglicensing.GrantClaims{@@ -735,27 +814,62 @@ func TestHandleCheckoutActivation_RedeemsCompletedCheckoutAndRedirectsToBilling(t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)handler := createTestHandler(t)+ returnToken := issuePurchaseReturnToken(t, handler, "default", "max_monitored_systems")req := httptest.NewRequest(http.MethodPost,- licensePurchaseActivationPath,- strings.NewReader("session_id=cs_success&feature=max_monitored_systems"),+ "https://pulse.example.com"+licensePurchaseActivationPath,+ strings.NewReader("session_id=cs_success&feature=max_monitored_systems&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.StatusSeeOther {- t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusSeeOther, rec.Body.String())+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusOK, rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), "Pulse Pro activated") {+ t.Fatalf("body = %q, want success bridge title", rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), "window.opener.location.assign") {+ t.Fatalf("body = %q, want opener refresh bridge", rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), "window.location.replace(redirectPath)") {+ t.Fatalf("body = %q, want same-tab billing fallback", rec.Body.String())}- if got := rec.Header().Get("Location"); got != "/settings/system/billing/plan?intent=max_monitored_systems" {- t.Fatalf("location = %q, want monitored-system billing plan route", got)+ if !strings.Contains(rec.Body.String(), "window.close()") {+ t.Fatalf("body = %q, want popup close bridge", rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), "/settings/system/billing/plan?intent=max_monitored_systems") {+ t.Fatalf("body = %q, want monitored-system billing route", rec.Body.String())}if !handler.Service(context.Background()).IsActivated() {t.Fatal("expected completed checkout to activate the local license")}}+func TestHandleCheckoutActivation_RejectsMissingPurchaseReturnToken(t *testing.T) {+ handler := createTestHandler(t)+ handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})++ req := httptest.NewRequest(+ http.MethodPost,+ "https://pulse.example.com"+licensePurchaseActivationPath,+ strings.NewReader("session_id=cs_success&feature=max_monitored_systems"),+ )+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ rec := httptest.NewRecorder()++ handler.HandleCheckoutActivation(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusBadRequest, rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), "missing required state") {+ t.Fatalf("body = %q, want missing state message", rec.Body.String())+ }+}+func TestHandleCheckoutActivation_RendersFailurePageWhenCheckoutIsNotFulfilled(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/v1/checkout/session" {@@ -768,10 +882,11 @@ func TestHandleCheckoutActivation_RendersFailurePageWhenCheckoutIsNotFulfilled(tt.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)handler := createTestHandler(t)+ returnToken := issuePurchaseReturnToken(t, handler, "default", "max_monitored_systems")req := httptest.NewRequest(http.MethodPost,- licensePurchaseActivationPath,- strings.NewReader("session_id=cs_pending"),+ "https://pulse.example.com"+licensePurchaseActivationPath,+ strings.NewReader("session_id=cs_pending&feature=max_monitored_systems&purchase_return_token="+url.QueryEscape(returnToken)),)req.Header.Set("Content-Type", "application/x-www-form-urlencoded")rec := httptest.NewRecorder()diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.goindex 2438939732..552552a7a1 100644--- a/internal/api/licensing_bridge.go+++ b/internal/api/licensing_bridge.go@@ -40,6 +40,7 @@ type billingStoreModel = pkglicensing.BillingStoretype billingState = pkglicensing.BillingStatetype subscriptionState = pkglicensing.SubscriptionStatetype entitlementPayloadModel = pkglicensing.EntitlementPayload+type commercialPosturePayloadModel = pkglicensing.CommercialPosturePayloadtype runtimeCapabilitiesPayloadModel = pkglicensing.RuntimeCapabilitiesPayloadtype limitStatusModel = pkglicensing.LimitStatustype upgradeReasonModel = pkglicensing.UpgradeReason@@ -54,6 +55,7 @@ type conversionEvent = pkglicensing.ConversionEventtype conversionHealthStatus = pkglicensing.HealthStatustype conversionCollectionConfigSnapshot = pkglicensing.CollectionConfigSnapshottype trialActivationClaimsModel = pkglicensing.TrialActivationClaims+type purchaseReturnClaimsModel = pkglicensing.PurchaseReturnClaimstype entitlementLeaseClaimsModel = pkglicensing.EntitlementLeaseClaimstype licenseTier = pkglicensing.Tier@@ -100,6 +102,10 @@ func proTrialSignupURLFromLicensing(override string) string {return pkglicensing.ResolveProTrialSignupURL(override)}+func pulseAccountPortalURLFromLicensing(override string) string {+ return pkglicensing.ResolvePulseAccountPortalURL(override)+}+func defaultBillingStateFromLicensing() *billingState {return pkglicensing.DefaultBillingState()}@@ -221,6 +227,13 @@ func buildRuntimeCapabilitiesPayloadFromLicensing(return pkglicensing.BuildRuntimeCapabilitiesPayload(status, subscriptionState)}+func buildCommercialPosturePayloadFromLicensing(+ status *licenseStatus,+ subscriptionState string,+) commercialPosturePayloadModel {+ return pkglicensing.BuildCommercialPosturePayload(status, subscriptionState)+}+func buildFeatureMapFromLicensing(service *licenseService) map[string]bool {return pkglicensing.BuildFeatureMap(service, nil)}@@ -242,6 +255,26 @@ func buildRuntimeCapabilitiesPayloadWithUsageFromLicensing(return pkglicensing.BuildRuntimeCapabilitiesPayloadWithUsage(status, subscriptionState, usage)}+func buildCommercialPosturePayloadWithUsageFromLicensing(+ status *licenseStatus,+ subscriptionState string,+ usage entitlementUsageSnapshotModel,+ trialEndsAtUnix *int64,+) commercialPosturePayloadModel {+ return pkglicensing.BuildCommercialPosturePayloadWithUsage(+ status,+ subscriptionState,+ usage,+ trialEndsAtUnix,+ )+}++func commercialPosturePayloadFromEntitlementPayloadFromLicensing(+ payload entitlementPayloadModel,+) commercialPosturePayloadModel {+ return pkglicensing.CommercialPosturePayloadFromEntitlementPayload(payload)+}+func limitStateFromLicensing(current, limit int64) string {return pkglicensing.LimitState(current, limit)}@@ -274,6 +307,14 @@ func verifyTrialActivationTokenFromLicensing(token string, key ed25519.PublicKeyreturn pkglicensing.VerifyTrialActivationToken(token, key, expectedInstanceHost, now)}+func signPurchaseReturnTokenFromLicensing(signingKey []byte, claims purchaseReturnClaimsModel) (string, error) {+ return pkglicensing.SignPurchaseReturnToken(signingKey, claims)+}++func verifyPurchaseReturnTokenFromLicensing(token string, signingKey []byte, expectedInstanceHost string, now time.Time) (*purchaseReturnClaimsModel, error) {+ return pkglicensing.VerifyPurchaseReturnToken(token, signingKey, expectedInstanceHost, now)+}+func verifyEntitlementLeaseTokenFromLicensing(token string, key ed25519.PublicKey, expectedInstanceHost string, now time.Time) (*entitlementLeaseClaimsModel, error) {return pkglicensing.VerifyEntitlementLeaseToken(token, key, expectedInstanceHost, now)}diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.goindex 5077ccb79c..3da1738bb2 100644--- a/internal/api/licensing_handlers.go+++ b/internal/api/licensing_handlers.go@@ -17,14 +17,23 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/crypto""github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rs/zerolog/log")const (- trialStartRateLimitBurst = 6- trialStartRateLimitWindow = 15 * time.Minute- licensePurchaseActivationPath = "/auth/license-purchase-activate"+ trialStartRateLimitBurst = 6+ trialStartRateLimitWindow = 15 * time.Minute+ licensePurchaseStartPath = "/auth/license-purchase-start"+ licensePurchaseActivationPath = "/auth/license-purchase-activate"+ licensePurchaseReturnTokenField = "purchase_return_token"+ pulseAccountUpgradeService = "upgrade"+ pulseAccountPortalFeatureQueryParam = "feature"+ pulseAccountPortalServiceQueryParam = "service"+ pulseAccountPortalReturnURLQueryParam = "return_url"+ pulseAccountPortalReturnTokenQueryParam = "purchase_return_token"+ purchaseReturnKeyPurpose = "pulse-license-purchase-return")// revocationFeedToken returns the relay feed token for revocation polling.@@ -152,7 +161,7 @@ func (h *LicenseHandlers) StopAllBackgroundLoops() {})}-func trialCallbackURLForRequest(r *http.Request, cfg *config.Config) string {+func publicBaseURLForRequest(r *http.Request, cfg *config.Config) string {baseURL := ""if cfg != nil {baseURL = strings.TrimSpace(cfg.PublicURL)@@ -175,12 +184,32 @@ func trialCallbackURLForRequest(r *http.Request, cfg *config.Config) string {baseURL = scheme + "://" + host}baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")+ return baseURL+}++func trialCallbackURLForRequest(r *http.Request, cfg *config.Config) string {+ baseURL := publicBaseURLForRequest(r, cfg)if baseURL == "" {return ""}return baseURL + "/auth/trial-activate"}+func licensePurchaseCallbackURLForRequest(r *http.Request, cfg *config.Config) string {+ baseURL := publicBaseURLForRequest(r, cfg)+ if baseURL == "" {+ return ""+ }+ return baseURL + licensePurchaseActivationPath+}++func purchaseReturnExpectedHost(r *http.Request, cfg *config.Config) string {+ if cfg != nil && strings.TrimSpace(cfg.PublicURL) != "" {+ return normalizeHostForTrial(cfg.PublicURL)+ }+ return normalizeHostForTrial(publicBaseURLForRequest(r, nil))+}+func trialSignupActionURLForRequest(cfg *config.Config, orgID, returnURL, instanceToken string) (string, error) {signupBaseURL := ""if cfg != nil {@@ -205,6 +234,77 @@ func trialSignupActionURLForRequest(cfg *config.Config, orgID, returnURL, instanreturn parsed.String(), nil}+func (h *LicenseHandlers) purchaseReturnDataDir() string {+ if h == nil {+ return ""+ }+ if h.mtPersistence != nil {+ return h.mtPersistence.BaseDataDir()+ }+ if h.cfg != nil {+ return strings.TrimSpace(h.cfg.DataPath)+ }+ return ""+}++func (h *LicenseHandlers) purchaseReturnSigningKey() ([]byte, error) {+ dataDir := h.purchaseReturnDataDir()+ if strings.TrimSpace(dataDir) == "" {+ return nil, fmt.Errorf("purchase return data path is unavailable")+ }+ cryptoManager, err := crypto.NewCryptoManagerAt(dataDir)+ if err != nil {+ return nil, fmt.Errorf("load purchase return crypto manager: %w", err)+ }+ signingKey, err := cryptoManager.DeriveKey(purchaseReturnKeyPurpose, 32)+ if err != nil {+ return nil, fmt.Errorf("derive purchase return signing key: %w", err)+ }+ return signingKey, nil+}++func pulseAccountUpgradeURLForRequest(feature, returnURL, returnToken string, query url.Values) (string, error) {+ portalURL := strings.TrimSpace(pulseAccountPortalURLFromLicensing(""))+ if portalURL == "" {+ return "", fmt.Errorf("pulse account portal url is unavailable")+ }++ parsed, err := url.Parse(portalURL)+ if err != nil {+ return "", fmt.Errorf("parse pulse account portal url: %w", err)+ }++ params := parsed.Query()+ for key, values := range query {+ switch key {+ case pulseAccountPortalFeatureQueryParam,+ pulseAccountPortalServiceQueryParam,+ pulseAccountPortalReturnURLQueryParam,+ pulseAccountPortalReturnTokenQueryParam,+ "checkout",+ "session_id":+ continue+ }+ for _, value := range values {+ normalizedValue := strings.TrimSpace(value)+ if normalizedValue == "" {+ continue+ }+ params.Set(key, normalizedValue)+ }+ }++ normalizedFeature := strings.TrimSpace(feature)+ if normalizedFeature != "" {+ params.Set(pulseAccountPortalFeatureQueryParam, normalizedFeature)+ }+ params.Set(pulseAccountPortalServiceQueryParam, pulseAccountUpgradeService)+ params.Set(pulseAccountPortalReturnURLQueryParam, strings.TrimSpace(returnURL))+ params.Set(pulseAccountPortalReturnTokenQueryParam, strings.TrimSpace(returnToken))+ parsed.RawQuery = params.Encode()+ return parsed.String(), nil+}+func licensePurchaseActivationRedirectPath(feature string) string {normalizedFeature := strings.TrimSpace(feature)switch normalizedFeature {@@ -235,6 +335,19 @@ func writeLicensePurchaseActivationFailurePage(w http.ResponseWriter, statusCode)}+func writeLicensePurchaseActivationSuccessPage(w http.ResponseWriter, feature string) {+ redirectPath := licensePurchaseActivationRedirectPath(feature)+ escapedLink := html.EscapeString(redirectPath)+ w.Header().Set("Content-Type", "text/html; charset=utf-8")+ w.WriteHeader(http.StatusOK)+ _, _ = 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 Pro activated</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 Pro activated</h1><p id=\"purchase-return-status\" style=\"margin-bottom:1rem\">Pulse is refreshing billing in the original tab.</p><p><a href=\"%s\">Return to Pulse Pro billing</a></p></main><script>(function(){var redirectPath=%q;var statusEl=document.getElementById('purchase-return-status');var redirectedOriginalTab=false;try{if(window.opener&&!window.opener.closed){redirectedOriginalTab=true;window.opener.postMessage({type:'pulse-license-purchase-activated',redirectPath:redirectPath},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 is ready. You can close this tab if it stays open.';}},75);return;}if(statusEl){statusEl.textContent='Pulse Pro is ready. Returning to billing.';}setTimeout(function(){window.location.replace(redirectPath);},75);}());</script></body></html>",+ escapedLink,+ redirectPath,+ )+}+func normalizeHostForTrial(raw string) string {raw = strings.TrimSpace(raw)if raw == "" {@@ -1148,6 +1261,56 @@ func (h *LicenseHandlers) HandleActivateLicense(w http.ResponseWriter, r *http.Rjson.NewEncoder(w).Encode(response)}+// HandleCheckoutStart handles GET /auth/license-purchase-start.+// It mints a short-lived signed return token and redirects the operator into+// Pulse Account so checkout can safely return to the local instance.+func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ expectedHost := purchaseReturnExpectedHost(r, h.cfg)+ returnURL := licensePurchaseCallbackURLForRequest(r, h.cfg)+ if expectedHost == "" || returnURL == "" {+ http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)+ 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)+ return+ }++ orgID := strings.TrimSpace(GetOrgID(r.Context()))+ if orgID == "" {+ orgID = "default"+ }+ feature := strings.TrimSpace(r.URL.Query().Get(pulseAccountPortalFeatureQueryParam))+ 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")+ http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)+ return+ }++ destination, err := pulseAccountUpgradeURLForRequest(feature, returnURL, returnToken, 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)+ return+ }++ http.Redirect(w, r, destination, http.StatusSeeOther)+}+// HandleCheckoutActivation handles POST /auth/license-purchase-activate.// It redeems a completed commercial checkout session into a local activation// and returns the operator to the canonical billing route.@@ -1163,19 +1326,101 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httsessionID := strings.TrimSpace(r.FormValue("session_id"))feature := strings.TrimSpace(r.FormValue("feature"))+ returnToken := strings.TrimSpace(r.FormValue(licensePurchaseReturnTokenField))+ if returnToken == "" {+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, "Purchase activation link expired or is missing required state. Reopen the upgrade flow from Pulse Pro billing.")+ return+ }++ expectedHost := purchaseReturnExpectedHost(r, h.cfg)+ if expectedHost == "" {+ writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, "Pulse could not verify the commercial return target for this instance.")+ return+ }+ signingKey, err := h.purchaseReturnSigningKey()+ if err != nil {+ log.Error().Err(err).Msg("Purchase return signing key unavailable during activation")+ writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, "Pulse could not verify the commercial return state for this instance.")+ return+ }+ claims, err := verifyPurchaseReturnTokenFromLicensing(returnToken, signingKey, expectedHost, time.Now().UTC())+ if err != nil {+ log.Warn().Err(err).Msg("Purchase return token verification failed")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, "Purchase activation link expired or is invalid. Reopen the upgrade flow from Pulse Pro billing.")+ return+ }+ if claims != nil && strings.TrimSpace(claims.Feature) != "" {+ if feature != "" && feature != strings.TrimSpace(claims.Feature) {+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, strings.TrimSpace(claims.Feature), "Purchase activation state did not match the completed upgrade flow.")+ return+ }+ feature = strings.TrimSpace(claims.Feature)+ }if sessionID == "" {writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, "Purchase activation requires a completed checkout session.")return}+ replayStore := h.trialReplay+ if replayStore == nil {+ dataDir := h.purchaseReturnDataDir()+ if strings.TrimSpace(dataDir) != "" {+ replayStore = &jtiReplayStore{configDir: dataDir}+ }+ }+ replaySubject := ""+ if claims != nil {+ replaySubject = strings.TrimSpace(claims.Subject)+ if replaySubject == "" {+ replaySubject = strings.TrimSpace(claims.ID)+ }+ }+ if replayStore == nil || replaySubject == "" {+ writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, "Pulse could not verify the purchase activation state for this checkout.")+ return+ }++ replayID := "purchase_activate:" + replaySubject+ expiresAt := time.Now().UTC().Add(2 * time.Hour)+ if claims != nil && claims.ExpiresAt != nil {+ expiresAt = claims.ExpiresAt.Time+ }+ stored, err := replayStore.checkAndStore(replayID, expiresAt)+ if err != nil {+ log.Error().Err(err).Msg("Purchase activation replay-store failure")+ writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, "Pulse could not verify the purchase activation state for this checkout.")+ return+ }+ if !stored {+ log.Warn().Str("replay_id_prefix", replayID[:24]).Msg("Purchase activation replay blocked")+ writeLicensePurchaseActivationFailurePage(w, http.StatusConflict, feature, "This completed purchase was already returned to Pulse Pro. Reopen billing if you need to confirm the current entitlement.")+ return+ }+ clearReplay := func(reason string, replayErr error) {+ if deleteErr := replayStore.delete(replayID); deleteErr != nil {+ log.Warn().Err(deleteErr).Str("replay_id_prefix", replayID[:24]).Str("reason", reason).Msg("Purchase activation replay-store cleanup failed")+ return+ }+ if replayErr != nil {+ log.Warn().Err(replayErr).Str("replay_id_prefix", replayID[:24]).Str("reason", reason).Msg("Cleared purchase activation replay marker after activation failure")+ }+ }+lsClient := newLicenseServerClientFromLicensing("")if lsClient == nil {+ clearReplay("license_server_unavailable", nil)writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, "Pulse could not contact the commercial activation service.")return}- checkoutResult, err := lsClient.GetCheckoutSessionResult(r.Context(), sessionID)+ ctx := r.Context()+ if claims != nil && strings.TrimSpace(claims.OrgID) != "" {+ ctx = context.WithValue(ctx, OrgIDContextKey, strings.TrimSpace(claims.OrgID))+ }++ checkoutResult, err := lsClient.GetCheckoutSessionResult(ctx, sessionID)if err != nil {+ clearReplay("checkout_lookup_failed", err)log.Warn().Err(err).Str("checkout_session_id", sessionID).Msg("Failed to resolve checkout session during purchase activation")writeLicensePurchaseActivationFailurePage(w, http.StatusBadGateway, feature, "Pulse could not confirm the completed checkout yet. Please try again in a moment.")return@@ -1186,23 +1431,26 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httif checkoutResult != nil && strings.TrimSpace(checkoutResult.Message) != "" {message = strings.TrimSpace(checkoutResult.Message)}+ clearReplay("checkout_not_fulfilled", nil)writeLicensePurchaseActivationFailurePage(w, http.StatusConflict, feature, message)return}activationKey := strings.TrimSpace(checkoutResult.ActivationKey)if activationKey == "" {+ clearReplay("activation_key_missing", nil)writeLicensePurchaseActivationFailurePage(w, http.StatusBadGateway, feature, "The completed checkout did not return an activation key.")return}- if _, err := h.activateLicenseKey(r.Context(), activationKey); err != nil {+ if _, err := h.activateLicenseKey(ctx, activationKey); err != nil {+ clearReplay("license_activation_failed", err)log.Warn().Err(err).Str("checkout_session_id", sessionID).Msg("Failed to activate completed checkout locally")writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, userFriendlyActivationError(err))return}- http.Redirect(w, r, licensePurchaseActivationRedirectPath(feature), http.StatusSeeOther)+ writeLicensePurchaseActivationSuccessPage(w, feature)}// HandleClearLicense handles POST /api/license/cleardiff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex f6c57283c5..fdb5933558 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -445,6 +445,7 @@ var allRouteAllowlist = []string{"/api/license/activate","/api/license/clear","GET /api/license/runtime-capabilities",+ "GET /api/license/commercial-posture","GET /api/license/entitlements","POST /api/license/trial/start","GET /api/license/monitored-system-ledger",@@ -454,6 +455,7 @@ var allRouteAllowlist = []string{"GET /api/upgrade-metrics/config","PUT /api/upgrade-metrics/config","GET /api/admin/upgrade-metrics-funnel",+ "GET /auth/license-purchase-start","GET /api/orgs","POST /api/orgs","GET /api/orgs/{id}",diff --git a/internal/api/router_routes_cloud.go b/internal/api/router_routes_cloud.goindex 904aa28253..b8ca7445f2 100644--- a/internal/api/router_routes_cloud.go+++ b/internal/api/router_routes_cloud.go@@ -72,6 +72,8 @@ func (r *Router) registerHostedRoutes(hostedSignupHandlers *HostedSignupHandlers// Handler self-guards via handoff key file check — returns 404 if not a cloud tenant.r.mux.HandleFunc("/auth/cloud-handoff", HandleCloudHandoff(routerConfig.DataPath))if r.licenseHandlers != nil {+ // Self-hosted commercial checkout handoff: mint a signed return token and redirect into Pulse Account.+ r.mux.HandleFunc("GET /auth/license-purchase-start", RequireAuth(routerConfig, r.licenseHandlers.HandleCheckoutStart))// Hosted trial signup callback: signed token activation flow for self-hosted Pulse Pro trials.r.mux.HandleFunc("/auth/trial-activate", r.licenseHandlers.HandleTrialActivation)// Self-hosted commercial checkout return: complete purchase activation without manual key entry.diff --git a/internal/api/router_routes_licensing.go b/internal/api/router_routes_licensing.goindex 1f341cda98..d0bbb97288 100644--- a/internal/api/router_routes_licensing.go+++ b/internal/api/router_routes_licensing.go@@ -38,6 +38,7 @@ func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHanr.mux.HandleFunc("/api/license/activate", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.licenseHandlers.HandleActivateLicense)))r.mux.HandleFunc("/api/license/clear", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.licenseHandlers.HandleClearLicense)))r.mux.HandleFunc("GET /api/license/runtime-capabilities", RequireAuth(r.config, r.licenseHandlers.HandleRuntimeCapabilities))+ r.mux.HandleFunc("GET /api/license/commercial-posture", RequireAuth(r.config, r.licenseHandlers.HandleCommercialPosture))r.mux.HandleFunc("GET /api/license/entitlements", RequireAuth(r.config, r.licenseHandlers.HandleEntitlements))r.mux.HandleFunc("GET /api/license/monitored-system-ledger", RequireAuth(r.config, r.handleMonitoredSystemLedger))r.mux.HandleFunc("POST /api/license/trial/start", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.licenseHandlers.HandleStartTrial)))diff --git a/internal/api/subscription_entitlements.go b/internal/api/subscription_entitlements.goindex 7b87869801..b2007a575c 100644--- a/internal/api/subscription_entitlements.go+++ b/internal/api/subscription_entitlements.go@@ -18,33 +18,30 @@ type EntitlementPayload = entitlementPayloadModel// response for feature gating and operational limit checks.type RuntimeCapabilitiesPayload = runtimeCapabilitiesPayloadModel+// CommercialPosturePayload is the canonical non-billing commercial response+// for upgrade/trial posture and monitored-system migration guidance.+type CommercialPosturePayload = commercialPosturePayloadModel+// LimitStatus represents a quantitative limit with current usage state.type LimitStatus = limitStatusModel// UpgradeReason provides context for why a user should upgrade.type UpgradeReason = upgradeReasonModel-// HandleEntitlements returns the normalized entitlement payload for the current tenant.-// This is the commercial entitlement endpoint for billing, trial, and upgrade presentation.-func (h *LicenseHandlers) HandleEntitlements(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)- return- }-- svc, _, err := h.getTenantComponents(r.Context())+func (h *LicenseHandlers) buildCommercialEntitlementPayload(+ ctx context.Context,+) (EntitlementPayload, error) {+ svc, _, err := h.getTenantComponents(ctx)if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "internal_error", "Internal server error", nil)- return+ return EntitlementPayload{}, err}- // Build payload from current license status (which is evaluator-aware when no JWT is present).status := svc.Status()- usage := h.entitlementUsageSnapshot(r.Context())+ usage := h.entitlementUsageSnapshot(ctx)trialEndsAtUnix := trialEndsAtUnixFromService(svc)// Onboarding overflow: +1 agent for 14 days on free tier.- overflowGrantedAt := h.ensureOnboardingOverflow(r.Context(), status.Tier)+ overflowGrantedAt := h.ensureOnboardingOverflow(ctx, status.Tier)now := time.Now()if bonus := overflowBonusFromLicensing(status.Tier, overflowGrantedAt, now); bonus > 0 {status.MaxMonitoredSystems += bonus@@ -62,17 +59,52 @@ func (h *LicenseHandlers) HandleEntitlements(w http.ResponseWriter, r *http.Requpayload.PlanVersion = pv}}- existing := h.billingStateForContext(r.Context())+ existing := h.billingStateForContext(ctx)if existing != nil {payload.CommercialMigration = cloneCommercialMigrationStatusFromLicensing(existing.CommercialMigration)}- payload.TrialEligible, payload.TrialEligibilityReason = h.trialStartEligibility(r.Context(), svc, existing)+ payload.TrialEligible, payload.TrialEligibilityReason = h.trialStartEligibility(ctx, svc, existing)payload.HostedMode = h != nil && h.hostedMode+ return payload, nil+}++// HandleEntitlements returns the normalized entitlement payload for the current tenant.+// This is the commercial entitlement endpoint for billing, trial, and upgrade presentation.+func (h *LicenseHandlers) HandleEntitlements(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)+ return+ }++ payload, err := h.buildCommercialEntitlementPayload(r.Context())+ if err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "internal_error", "Internal server error", nil)+ return+ }w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(payload)}+// HandleCommercialPosture returns the canonical non-billing commercial posture payload.+func (h *LicenseHandlers) HandleCommercialPosture(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)+ return+ }++ payload, err := h.buildCommercialEntitlementPayload(r.Context())+ if err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "internal_error", "Internal server error", nil)+ return+ }++ posture := commercialPosturePayloadFromEntitlementPayload(payload)++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(posture)+}+// HandleRuntimeCapabilities returns the canonical non-commercial runtime capability payload.func (h *LicenseHandlers) HandleRuntimeCapabilities(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {@@ -171,6 +203,13 @@ func buildRuntimeCapabilitiesPayload(return buildRuntimeCapabilitiesPayloadFromLicensing(status, subscriptionState)}+func buildCommercialPosturePayload(+ status *licenseStatus,+ subscriptionState string,+) CommercialPosturePayload {+ return buildCommercialPosturePayloadFromLicensing(status, subscriptionState)+}+// buildEntitlementPayloadWithUsage constructs the normalized payload from LicenseStatus and observed usage.func buildEntitlementPayloadWithUsage(status *licenseStatus,@@ -189,6 +228,26 @@ func buildRuntimeCapabilitiesPayloadWithUsage(return buildRuntimeCapabilitiesPayloadWithUsageFromLicensing(status, subscriptionState, usage)}+func buildCommercialPosturePayloadWithUsage(+ status *licenseStatus,+ subscriptionState string,+ usage entitlementUsageSnapshot,+ trialEndsAtUnix *int64,+) CommercialPosturePayload {+ return buildCommercialPosturePayloadWithUsageFromLicensing(+ status,+ subscriptionState,+ usage,+ trialEndsAtUnix,+ )+}++func commercialPosturePayloadFromEntitlementPayload(+ payload EntitlementPayload,+) CommercialPosturePayload {+ return commercialPosturePayloadFromEntitlementPayloadFromLicensing(payload)+}+// limitState returns the over-limit UX state string.// Exported for testing.func limitState(current, limit int64) string {diff --git a/internal/cloudcp/portal/frontend/src/app.test.ts b/internal/cloudcp/portal/frontend/src/app.test.tsindex 0f70c8fb73..f3b5f3911c 100644--- a/internal/cloudcp/portal/frontend/src/app.test.ts+++ b/internal/cloudcp/portal/frontend/src/app.test.ts@@ -152,6 +152,7 @@ describe('portal app', function() {openBillingPanelID: 'retrieve-billing-panel',upgradeFeatureKey: '',upgradeReturnURL: '',+ upgradePurchaseReturnToken: '',upgradeCheckoutSessionID: '',upgradeCheckoutStatus: '',}diff --git a/internal/cloudcp/portal/frontend/src/billing.ts b/internal/cloudcp/portal/frontend/src/billing.tsindex b440b0d678..14e40df831 100644--- a/internal/cloudcp/portal/frontend/src/billing.ts+++ b/internal/cloudcp/portal/frontend/src/billing.ts@@ -89,6 +89,7 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {billingState.openBillingPanelID = nextState.openBillingPanelID;billingState.upgradeFeatureKey = nextState.upgradeFeatureKey;billingState.upgradeReturnURL = nextState.upgradeReturnURL;+ billingState.upgradePurchaseReturnToken = nextState.upgradePurchaseReturnToken;billingState.upgradeCheckoutSessionID = nextState.upgradeCheckoutSessionID;billingState.upgradeCheckoutStatus = nextState.upgradeCheckoutStatus;billingState.upgradePricing = nextState.upgradePricing;@@ -191,6 +192,9 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {if (billingState.upgradeReturnURL) {url.searchParams.set('return_url', billingState.upgradeReturnURL);}+ if (billingState.upgradePurchaseReturnToken) {+ url.searchParams.set('purchase_return_token', billingState.upgradePurchaseReturnToken);+ }url.searchParams.set('service', 'upgrade');url.searchParams.set('checkout', status);if (status === 'success') {diff --git a/internal/cloudcp/portal/frontend/src/billing_view.test.ts b/internal/cloudcp/portal/frontend/src/billing_view.test.tsindex 18e804c676..269c774373 100644--- a/internal/cloudcp/portal/frontend/src/billing_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/billing_view.test.ts@@ -229,6 +229,7 @@ describe('services view', function() {var billingState = createPortalBillingState();billingState.upgradeFeatureKey = 'max_monitored_systems';billingState.upgradeReturnURL = 'https://pulse.example.com/auth/license-purchase-activate';+ billingState.upgradePurchaseReturnToken = 'prt_signed';billingState.upgradeCheckoutSessionID = 'cs_success';billingState.upgradePricing.status = 'ready';billingState.upgradePricing.data = {@@ -270,6 +271,9 @@ describe('services view', function() {expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain('Buy Annual');expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain('Activate in Pulse Pro');expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain('session_id');+ expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain(+ 'purchase_return_token',+ );expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain('ppk_live_preview');});@@ -291,7 +295,7 @@ describe('services view', function() {renderUpgradePanel(billingState, createBootstrap());expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain(- 'Return to Pulse Pro billing to refresh the upgraded entitlement.',+ 'Return to Pulse Pro billing and reopen the upgrade flow',);});});diff --git a/internal/cloudcp/portal/frontend/src/billing_view.ts b/internal/cloudcp/portal/frontend/src/billing_view.tsindex 8dd31fe6d1..ef4711b427 100644--- a/internal/cloudcp/portal/frontend/src/billing_view.ts+++ b/internal/cloudcp/portal/frontend/src/billing_view.ts@@ -145,6 +145,7 @@ export function renderUpgradePanel(billingState: PortalBillingState, bootstrap:var checkoutResultState = billingState.upgradeCheckoutResult;var result = checkoutResultState.data;var returnURL = String(billingState.upgradeReturnURL || '').trim();+ var returnToken = String(billingState.upgradePurchaseReturnToken || '').trim();var sessionID = String(billingState.upgradeCheckoutSessionID || '').trim();var explainer = pricingState.data && pricingState.data.explainer ? pricingState.data.explainer : '';var summaryItems = [] as string[];@@ -176,17 +177,18 @@ export function renderUpgradePanel(billingState: PortalBillingState, bootstrap:} else if (checkoutResultState.status === 'error') {summaryItems.push('<div class="billing-status visible error">' + escapeText(checkoutResultState.error || 'Could not confirm the completed checkout.') + '</div>');} else if (result && result.status === 'fulfilled') {- var activationForm = returnURL && sessionID+ var activationForm = returnURL && sessionID && returnToken? ('<form method="POST" action="' + escapeAttribute(returnURL) + '">' +'<input type="hidden" name="session_id" value="' + escapeAttribute(sessionID) + '">' +'<input type="hidden" name="feature" value="' + escapeAttribute(featureKey) + '">' ++ '<input type="hidden" name="purchase_return_token" value="' + escapeAttribute(returnToken) + '">' +'<div class="form-actions">' +'<button class="btn-primary" type="submit">Activate in Pulse Pro</button>' +'</div>' +'</form>')- : '<div class="helper-text">Return to Pulse Pro billing to refresh the upgraded entitlement. If automatic activation is unavailable, Pulse Account can still retrieve the latest active license.</div>';+ : '<div class="helper-text">Return to Pulse Pro billing and reopen the upgrade flow so Pulse can securely finalize this completed checkout. If automatic return is unavailable, Pulse Account can still retrieve the latest active license.</div>';summaryItems.push('<div class="billing-result">' +'<h4>Checkout complete</h4>' +diff --git a/internal/cloudcp/portal/frontend/src/runtime.test.ts b/internal/cloudcp/portal/frontend/src/runtime.test.tsindex 5b79e6a9ad..cf5343bc53 100644--- a/internal/cloudcp/portal/frontend/src/runtime.test.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.test.ts@@ -63,12 +63,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&feature=max_monitored_systems&return_url=https%3A%2F%2Fpulse.example.com%2Fauth%2Flicense-purchase-activate&checkout=success&session_id=cs_success');+ var handoff = readPortalRuntimeHandoff('https://cloud.pulserelay.pro/portal?email=buyer%40example.com&service=upgrade&feature=max_monitored_systems&return_url=https%3A%2F%2Fpulse.example.com%2Fauth%2Flicense-purchase-activate&purchase_return_token=prt_signed&checkout=success&session_id=cs_success');expect(handoff.email).toBe('[email protected]');expect(handoff.openBillingPanelID).toBe('upgrade-billing-panel');expect(handoff.upgradeFeatureKey).toBe('max_monitored_systems');expect(handoff.upgradeReturnURL).toBe('https://pulse.example.com/auth/license-purchase-activate');+ expect(handoff.upgradePurchaseReturnToken).toBe('prt_signed');expect(handoff.upgradeCheckoutStatus).toBe('success');expect(handoff.upgradeCheckoutSessionID).toBe('cs_success');});@@ -86,6 +87,7 @@ describe('portal runtime', function() {openBillingPanelID: 'refund-billing-panel',upgradeFeatureKey: '',upgradeReturnURL: '',+ upgradePurchaseReturnToken: '',upgradeCheckoutSessionID: '',upgradeCheckoutStatus: '',}@@ -110,6 +112,7 @@ describe('portal runtime', function() {openBillingPanelID: 'upgrade-billing-panel',upgradeFeatureKey: 'max_monitored_systems',upgradeReturnURL: 'https://pulse.example.com/auth/license-purchase-activate',+ upgradePurchaseReturnToken: 'prt_signed',upgradeCheckoutSessionID: 'cs_success',upgradeCheckoutStatus: 'success',}@@ -121,6 +124,7 @@ describe('portal runtime', function() {expect(runtime.store.getBillingState().upgradeReturnURL).toBe('https://pulse.example.com/auth/license-purchase-activate',);+ expect(runtime.store.getBillingState().upgradePurchaseReturnToken).toBe('prt_signed');expect(runtime.store.getBillingState().upgradeCheckoutSessionID).toBe('cs_success');expect(runtime.store.getBillingState().upgradeCheckoutStatus).toBe('success');});diff --git a/internal/cloudcp/portal/frontend/src/runtime.ts b/internal/cloudcp/portal/frontend/src/runtime.tsindex 442fc0fcc6..c60d3554f7 100644--- a/internal/cloudcp/portal/frontend/src/runtime.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.ts@@ -7,6 +7,7 @@ export interface PortalRuntimeHandoff {openBillingPanelID: string;upgradeFeatureKey: string;upgradeReturnURL: string;+ upgradePurchaseReturnToken: string;upgradeCheckoutSessionID: string;upgradeCheckoutStatus: '' | 'success' | 'cancelled';}@@ -59,6 +60,10 @@ function normalizeUpgradeReturnURL(value: string | null): string {return String(value || '').trim();}+function normalizeUpgradePurchaseReturnToken(value: string | null): string {+ return String(value || '').trim();+}+function normalizeUpgradeCheckoutSessionID(value: string | null): string {return String(value || '').trim();}@@ -82,6 +87,7 @@ export function readPortalRuntimeHandoff(locationHref: string | undefined = windopenBillingPanelID: normalizeHandoffBillingPanel(params.get('service')),upgradeFeatureKey: normalizeUpgradeFeatureKey(params.get('feature')),upgradeReturnURL: normalizeUpgradeReturnURL(params.get('return_url')),+ upgradePurchaseReturnToken: normalizeUpgradePurchaseReturnToken(params.get('purchase_return_token')),upgradeCheckoutSessionID: normalizeUpgradeCheckoutSessionID(params.get('session_id')),upgradeCheckoutStatus: normalizeUpgradeCheckoutStatus(params.get('checkout')),};@@ -91,6 +97,7 @@ export function readPortalRuntimeHandoff(locationHref: string | undefined = windopenBillingPanelID: '',upgradeFeatureKey: '',upgradeReturnURL: '',+ upgradePurchaseReturnToken: '',upgradeCheckoutSessionID: '',upgradeCheckoutStatus: '',};@@ -142,6 +149,7 @@ export function createPortalRuntime(billingState.openBillingPanelID = handoff.openBillingPanelID;billingState.upgradeFeatureKey = handoff.upgradeFeatureKey;billingState.upgradeReturnURL = handoff.upgradeReturnURL;+ billingState.upgradePurchaseReturnToken = handoff.upgradePurchaseReturnToken;billingState.upgradeCheckoutSessionID = handoff.upgradeCheckoutSessionID;billingState.upgradeCheckoutStatus = handoff.upgradeCheckoutStatus;}, { notify: false });@@ -150,6 +158,7 @@ export function createPortalRuntime(store.updateBillingState(function(billingState) {billingState.upgradeFeatureKey = handoff.upgradeFeatureKey;billingState.upgradeReturnURL = handoff.upgradeReturnURL;+ billingState.upgradePurchaseReturnToken = handoff.upgradePurchaseReturnToken;billingState.upgradeCheckoutSessionID = handoff.upgradeCheckoutSessionID;billingState.upgradeCheckoutStatus = handoff.upgradeCheckoutStatus;}, { notify: false });diff --git a/internal/cloudcp/portal/frontend/src/state.test.ts b/internal/cloudcp/portal/frontend/src/state.test.tsindex 0f873cb00f..bc15bc4e13 100644--- a/internal/cloudcp/portal/frontend/src/state.test.ts+++ b/internal/cloudcp/portal/frontend/src/state.test.ts@@ -36,6 +36,7 @@ describe('portal state', function() {expect(billingState.refund.submit.pending).toBe(false);expect(billingState.upgradeFeatureKey).toBe('');expect(billingState.upgradeReturnURL).toBe('');+ expect(billingState.upgradePurchaseReturnToken).toBe('');expect(billingState.upgradeCheckoutSessionID).toBe('');expect(billingState.upgradeCheckoutStatus).toBe('');expect(billingState.upgradePricing.status).toBe('idle');diff --git a/internal/cloudcp/portal/frontend/src/state.ts b/internal/cloudcp/portal/frontend/src/state.tsindex 3b0d208898..81242534e8 100644--- a/internal/cloudcp/portal/frontend/src/state.ts+++ b/internal/cloudcp/portal/frontend/src/state.ts@@ -119,6 +119,7 @@ export function createPortalBillingState(): PortalBillingState {openBillingPanelID: '',upgradeFeatureKey: '',upgradeReturnURL: '',+ upgradePurchaseReturnToken: '',upgradeCheckoutSessionID: '',upgradeCheckoutStatus: '',upgradePricing: createQueryState(null),diff --git a/internal/cloudcp/portal/frontend/src/types.ts b/internal/cloudcp/portal/frontend/src/types.tsindex fb0d3d8703..703bbd6884 100644--- a/internal/cloudcp/portal/frontend/src/types.ts+++ b/internal/cloudcp/portal/frontend/src/types.ts@@ -174,6 +174,7 @@ export interface PortalBillingState {openBillingPanelID: string;upgradeFeatureKey: string;upgradeReturnURL: string;+ upgradePurchaseReturnToken: string;upgradeCheckoutSessionID: string;upgradeCheckoutStatus: PortalUpgradeCheckoutStatus;upgradePricing: PortalQueryState<PortalUpgradePricingModel | null>;diff --git a/pkg/licensing/entitlement_payload.go b/pkg/licensing/entitlement_payload.goindex 2ac2af358b..e35de3bab2 100644--- a/pkg/licensing/entitlement_payload.go+++ b/pkg/licensing/entitlement_payload.go@@ -84,6 +84,49 @@ type EntitlementPayload struct {CommercialMigration *CommercialMigrationStatus `json:"commercial_migration,omitempty"`}+// CommercialPosturePayload is the canonical non-billing commercial contract+// for upgrade messaging, trial posture, and monitored-system migration copy.+// It intentionally excludes billing identity, grandfathered plan terms, and+// other full-entitlement details that belong only to billing surfaces.+type CommercialPosturePayload struct {+ // SubscriptionState is the current subscription lifecycle state.+ SubscriptionState string `json:"subscription_state"`++ // UpgradeReasons provides user-actionable upgrade prompts.+ UpgradeReasons []UpgradeReason `json:"upgrade_reasons"`++ // Tier is the marketing tier name (for display only, never gate on this).+ Tier string `json:"tier"`++ // TrialExpiresAt is the trial expiration Unix timestamp when in trial state.+ TrialExpiresAt *int64 `json:"trial_expires_at,omitempty"`++ // TrialDaysRemaining is the number of whole or partial days remaining in trial.+ TrialDaysRemaining *int `json:"trial_days_remaining,omitempty"`++ // TrialEligible indicates whether this org can start a self-serve trial right now.+ TrialEligible bool `json:"trial_eligible"`++ // TrialEligibilityReason is set when trial start is denied.+ TrialEligibilityReason string `json:"trial_eligibility_reason,omitempty"`++ // OverflowDaysRemaining is set when the onboarding overflow (+1 host) is active.+ OverflowDaysRemaining *int `json:"overflow_days_remaining,omitempty"`++ // LegacyConnections is retained for response compatibility. Monitored-system+ // enforcement now counts API-backed and agent-backed top-level systems+ // together, so this field is informational only.+ LegacyConnections LegacyConnectionCounts `json:"legacy_connections"`++ // HasMigrationGap is retained for response compatibility. API-backed systems+ // now count toward the same monitored-system cap as agent-backed systems.+ HasMigrationGap bool `json:"has_migration_gap"`++ // CommercialMigration reports unresolved paid-license migration work entering+ // from v5-era commercial state.+ CommercialMigration *CommercialMigrationStatus `json:"commercial_migration,omitempty"`+}+// RuntimeCapabilitiesPayload is the canonical non-commercial license contract// for feature gating and runtime retention/limit decisions.type RuntimeCapabilitiesPayload struct {@@ -157,6 +200,20 @@ func BuildEntitlementPayload(status *LicenseStatus, subscriptionState string) Enreturn BuildEntitlementPayloadWithUsage(status, subscriptionState, EntitlementUsageSnapshot{}, nil)}+// BuildCommercialPosturePayload constructs the canonical non-billing+// commercial posture payload from LicenseStatus.+func BuildCommercialPosturePayload(+ status *LicenseStatus,+ subscriptionState string,+) CommercialPosturePayload {+ return BuildCommercialPosturePayloadWithUsage(+ status,+ subscriptionState,+ EntitlementUsageSnapshot{},+ nil,+ )+}+// BuildRuntimeCapabilitiesPayload constructs the canonical non-commercial// runtime capability payload from LicenseStatus.func BuildRuntimeCapabilitiesPayload(@@ -186,6 +243,45 @@ func BuildRuntimeCapabilitiesPayloadWithUsage(}}+// BuildCommercialPosturePayloadWithUsage constructs the canonical non-billing+// commercial posture payload from LicenseStatus and observed usage.+func BuildCommercialPosturePayloadWithUsage(+ status *LicenseStatus,+ subscriptionState string,+ usage EntitlementUsageSnapshot,+ trialEndsAtUnix *int64,+) CommercialPosturePayload {+ return CommercialPosturePayloadFromEntitlementPayload(+ BuildEntitlementPayloadWithUsage(status, subscriptionState, usage, trialEndsAtUnix),+ )+}++// CommercialPosturePayloadFromEntitlementPayload projects the non-billing+// commercial posture fields out of the full entitlement payload.+func CommercialPosturePayloadFromEntitlementPayload(+ payload EntitlementPayload,+) CommercialPosturePayload {+ sanitized := CommercialPosturePayload{+ SubscriptionState: payload.SubscriptionState,+ UpgradeReasons: append([]UpgradeReason(nil), payload.UpgradeReasons...),+ Tier: payload.Tier,+ TrialExpiresAt: payload.TrialExpiresAt,+ TrialDaysRemaining: payload.TrialDaysRemaining,+ TrialEligible: payload.TrialEligible,+ TrialEligibilityReason: payload.TrialEligibilityReason,+ OverflowDaysRemaining: payload.OverflowDaysRemaining,+ LegacyConnections: payload.LegacyConnections,+ HasMigrationGap: payload.HasMigrationGap,+ }+ if payload.CommercialMigration != nil {+ sanitized.CommercialMigration = CloneCommercialMigrationStatus(payload.CommercialMigration)+ }+ if sanitized.UpgradeReasons == nil {+ sanitized.UpgradeReasons = []UpgradeReason{}+ }+ return sanitized+}+// BuildEntitlementPayloadWithUsage constructs the normalized payload from LicenseStatus and observed usage.func BuildEntitlementPayloadWithUsage(status *LicenseStatus,diff --git a/pkg/licensing/entitlement_payload_test.go b/pkg/licensing/entitlement_payload_test.goindex 70b9511f0e..e405119e91 100644--- a/pkg/licensing/entitlement_payload_test.go+++ b/pkg/licensing/entitlement_payload_test.go@@ -1,7 +1,9 @@package licensingimport (+ "encoding/json""reflect"+ "strings""testing""time")@@ -240,6 +242,90 @@ func TestBuildEntitlementPayload_NilStatus_MaxHistoryDays(t *testing.T) {}}+func TestBuildCommercialPosturePayloadWithUsage_CurrentValues(t *testing.T) {+ status := &LicenseStatus{+ Valid: true,+ Tier: TierFree,+ Features: append([]string(nil), TierFeatures[TierFree]...),+ MaxMonitoredSystems: 5,+ }++ payload := BuildCommercialPosturePayloadWithUsage(status, "", EntitlementUsageSnapshot{+ MonitoredSystems: 7,+ LegacyConnections: LegacyConnectionCounts{+ ProxmoxNodes: 2,+ DockerHosts: 1,+ },+ }, nil)++ if payload.Tier != string(TierFree) {+ t.Fatalf("expected tier=%q, got %q", TierFree, payload.Tier)+ }+ if payload.SubscriptionState != string(SubStateActive) {+ t.Fatalf("expected subscription_state=%q, got %q", SubStateActive, payload.SubscriptionState)+ }+ if len(payload.UpgradeReasons) == 0 {+ t.Fatal("expected commercial posture to preserve upgrade reasons")+ }+ if payload.LegacyConnections.ProxmoxNodes != 2 || payload.LegacyConnections.DockerHosts != 1 {+ t.Fatalf("expected legacy connection counts to be preserved, got %+v", payload.LegacyConnections)+ }+ if payload.HasMigrationGap {+ t.Fatal("expected has_migration_gap=false under canonical monitored-system counting")+ }+}++func TestCommercialPosturePayloadFromEntitlementPayload_StripsBillingIdentityFields(t *testing.T) {+ expiresAt := time.Now().Add(48 * time.Hour).UTC().Format(time.RFC3339)+ payload := BuildEntitlementPayloadWithUsage(&LicenseStatus{+ Valid: true,+ Tier: TierPro,+ PlanVersion: "v5_lifetime_grandfathered",+ Email: "[email protected]",+ ExpiresAt: &expiresAt,+ IsLifetime: false,+ DaysRemaining: 2,+ Features: append([]string(nil), TierFeatures[TierPro]...),+ MaxMonitoredSystems: 50,+ }, string(SubStateActive), EntitlementUsageSnapshot{+ MonitoredSystems: 12,+ LegacyConnections: LegacyConnectionCounts{+ ProxmoxNodes: 1,+ },+ }, nil)++ posture := CommercialPosturePayloadFromEntitlementPayload(payload)++ if posture.Tier != string(TierPro) {+ t.Fatalf("expected tier=%q, got %q", TierPro, posture.Tier)+ }+ if posture.SubscriptionState != string(SubStateActive) {+ t.Fatalf("expected subscription_state=%q, got %q", SubStateActive, posture.SubscriptionState)+ }+ if posture.LegacyConnections.ProxmoxNodes != 1 {+ t.Fatalf("expected proxmox_nodes=1, got %+v", posture.LegacyConnections)+ }++ body, err := json.Marshal(posture)+ if err != nil {+ t.Fatalf("marshal commercial posture: %v", err)+ }+ jsonBody := string(body)+ for _, forbidden := range []string{+ `"capabilities"`,+ `"limits"`,+ `"licensed_email"`,+ `"plan_version"`,+ `"hosted_mode"`,+ `"valid"`,+ `"max_history_days"`,+ } {+ if strings.Contains(jsonBody, forbidden) {+ t.Fatalf("commercial posture leaked billing/runtime field %s in %s", forbidden, jsonBody)+ }+ }+}+func TestBuildRuntimeCapabilitiesPayloadWithUsage_CurrentValues(t *testing.T) {status := &LicenseStatus{Valid: true,diff --git a/pkg/licensing/purchase_return.go b/pkg/licensing/purchase_return.gonew file mode 100644index 0000000000..007901651f--- /dev/null+++ b/pkg/licensing/purchase_return.go@@ -0,0 +1,196 @@+package licensing++import (+ "errors"+ "fmt"+ "net/url"+ "strings"+ "time"++ "github.com/golang-jwt/jwt/v5"+)++const (+ // PurchaseReturnTokenIssuer is the JWT issuer for self-hosted commercial return tokens.+ PurchaseReturnTokenIssuer = "pulse-self-hosted-purchase"++ // PurchaseReturnTokenAudience is the JWT audience for self-hosted commercial return tokens.+ PurchaseReturnTokenAudience = "pulse-self-hosted-purchase-return"++ // PurchaseReturnPath is the canonical Pulse callback path for completing a self-hosted upgrade.+ PurchaseReturnPath = "/auth/license-purchase-activate"+)++var (+ ErrPurchaseReturnSigningKeyInvalid = errors.New("purchase return signing key is invalid")+ ErrPurchaseReturnOrgIDMissing = errors.New("purchase return org_id is required")+ ErrPurchaseReturnInstanceMissing = errors.New("purchase return instance host is required")+ ErrPurchaseReturnReturnURLMissing = errors.New("purchase return return_url is required")+ ErrPurchaseReturnReturnURLInvalid = errors.New("purchase return return_url is invalid")+ ErrPurchaseReturnHostMismatch = errors.New("purchase return token host mismatch")+)++// PurchaseReturnClaims are minted by the local Pulse instance before handing an+// operator into Pulse Account checkout. Pulse verifies them when the completed+// checkout returns to the local instance for activation.+type PurchaseReturnClaims struct {+ OrgID string `json:"org_id"`+ Feature string `json:"feature,omitempty"`+ InstanceHost string `json:"instance_host"`+ ReturnURL string `json:"return_url"`+ jwt.RegisteredClaims+}++// SignPurchaseReturnToken signs a self-hosted Pulse Account return JWT using a+// local instance-owned HMAC key.+func SignPurchaseReturnToken(signingKey []byte, claims PurchaseReturnClaims) (string, error) {+ if len(signingKey) < 32 {+ return "", ErrPurchaseReturnSigningKeyInvalid+ }+ claims.OrgID = strings.TrimSpace(claims.OrgID)+ if claims.OrgID == "" {+ return "", ErrPurchaseReturnOrgIDMissing+ }+ claims.Feature = strings.TrimSpace(claims.Feature)+ claims.InstanceHost = normalizeHost(claims.InstanceHost)+ if claims.InstanceHost == "" {+ return "", ErrPurchaseReturnInstanceMissing+ }+ claims.ReturnURL = strings.TrimSpace(claims.ReturnURL)+ returnHost, err := ValidatePurchaseReturnURL(claims.ReturnURL, claims.InstanceHost)+ if err != nil {+ return "", err+ }+ claims.InstanceHost = returnHost++ now := time.Now().UTC()+ if claims.IssuedAt == nil {+ claims.IssuedAt = jwt.NewNumericDate(now)+ }+ if claims.ExpiresAt == nil {+ claims.ExpiresAt = jwt.NewNumericDate(now.Add(2 * time.Hour))+ }+ if strings.TrimSpace(claims.ID) == "" {+ jti, err := randomJTI()+ if err != nil {+ return "", fmt.Errorf("generate purchase return jti: %w", err)+ }+ claims.ID = jti+ }+ if strings.TrimSpace(claims.Subject) == "" {+ claims.Subject = claims.OrgID+ }+ if strings.TrimSpace(claims.Issuer) == "" {+ claims.Issuer = PurchaseReturnTokenIssuer+ }+ if len(claims.Audience) == 0 {+ claims.Audience = jwt.ClaimStrings{PurchaseReturnTokenAudience}+ }++ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)+ signed, err := token.SignedString(signingKey)+ if err != nil {+ return "", fmt.Errorf("sign purchase return token: %w", err)+ }+ return signed, nil+}++// VerifyPurchaseReturnToken verifies a self-hosted purchase-return JWT.+func VerifyPurchaseReturnToken(token string, signingKey []byte, expectedInstanceHost string, now time.Time) (*PurchaseReturnClaims, error) {+ if len(signingKey) < 32 {+ return nil, ErrPurchaseReturnSigningKeyInvalid+ }+ token = strings.TrimSpace(token)+ if token == "" {+ return nil, errors.New("purchase return token is required")+ }+ if now.IsZero() {+ now = time.Now().UTC()+ }++ claims := &PurchaseReturnClaims{}+ parsed, err := jwt.ParseWithClaims(+ token,+ claims,+ func(t *jwt.Token) (any, error) {+ if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {+ return nil, fmt.Errorf("unexpected signing method: %s", t.Method.Alg())+ }+ return signingKey, nil+ },+ jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),+ jwt.WithIssuer(PurchaseReturnTokenIssuer),+ jwt.WithAudience(PurchaseReturnTokenAudience),+ jwt.WithTimeFunc(func() time.Time { return now }),+ )+ if err != nil {+ return nil, err+ }+ if !parsed.Valid {+ return nil, errors.New("purchase return token is invalid")+ }++ claims.OrgID = strings.TrimSpace(claims.OrgID)+ if claims.OrgID == "" {+ return nil, ErrPurchaseReturnOrgIDMissing+ }+ claims.Feature = strings.TrimSpace(claims.Feature)+ claims.InstanceHost = normalizeHost(claims.InstanceHost)+ claims.ReturnURL = strings.TrimSpace(claims.ReturnURL)+ if claims.InstanceHost == "" {+ return nil, ErrPurchaseReturnInstanceMissing+ }+ returnHost, err := ValidatePurchaseReturnURL(claims.ReturnURL, claims.InstanceHost)+ if err != nil {+ return nil, err+ }+ claims.InstanceHost = returnHost++ expected := normalizeHost(expectedInstanceHost)+ if expected != "" && !strings.EqualFold(claims.InstanceHost, expected) {+ return nil, ErrPurchaseReturnHostMismatch+ }+ return claims, nil+}++// ValidatePurchaseReturnURL validates the Pulse Account checkout callback target+// and returns its normalized hostname.+func ValidatePurchaseReturnURL(raw, expectedInstanceHost string) (string, error) {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return "", ErrPurchaseReturnReturnURLMissing+ }+ parsed, err := url.Parse(raw)+ if err != nil || parsed == nil {+ return "", ErrPurchaseReturnReturnURLInvalid+ }+ if !parsed.IsAbs() || strings.TrimSpace(parsed.Host) == "" {+ return "", ErrPurchaseReturnReturnURLInvalid+ }+ if parsed.EscapedPath() != PurchaseReturnPath {+ return "", ErrPurchaseReturnReturnURLInvalid+ }+ if strings.TrimSpace(parsed.RawQuery) != "" || strings.TrimSpace(parsed.Fragment) != "" {+ return "", ErrPurchaseReturnReturnURLInvalid+ }++ host := normalizeHost(parsed.Hostname())+ if host == "" {+ return "", ErrPurchaseReturnReturnURLInvalid+ }+ switch strings.ToLower(strings.TrimSpace(parsed.Scheme)) {+ case "https":+ case "http":+ if !isAllowedInsecureTrialActivationReturnHost(host) {+ return "", ErrPurchaseReturnReturnURLInvalid+ }+ default:+ return "", ErrPurchaseReturnReturnURLInvalid+ }++ expected := normalizeHost(expectedInstanceHost)+ if expected != "" && !strings.EqualFold(host, expected) {+ return "", ErrPurchaseReturnHostMismatch+ }+ return host, nil+}diff --git a/pkg/licensing/purchase_return_test.go b/pkg/licensing/purchase_return_test.gonew file mode 100644index 0000000000..40c6525c84--- /dev/null+++ b/pkg/licensing/purchase_return_test.go@@ -0,0 +1,130 @@+package licensing++import (+ "bytes"+ "errors"+ "testing"+ "time"++ "github.com/golang-jwt/jwt/v5"+)++func testPurchaseReturnSigningKey() []byte {+ return bytes.Repeat([]byte{0x42}, 32)+}++func TestSignAndVerifyPurchaseReturnToken(t *testing.T) {+ token, err := SignPurchaseReturnToken(testPurchaseReturnSigningKey(), PurchaseReturnClaims{+ OrgID: "default",+ Feature: "max_monitored_systems",+ InstanceHost: "pulse.example.com",+ ReturnURL: "https://pulse.example.com/auth/license-purchase-activate",+ RegisteredClaims: jwt.RegisteredClaims{+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)),+ },+ })+ if err != nil {+ t.Fatalf("SignPurchaseReturnToken: %v", err)+ }++ claims, err := VerifyPurchaseReturnToken(token, testPurchaseReturnSigningKey(), "pulse.example.com", time.Now())+ if err != nil {+ t.Fatalf("VerifyPurchaseReturnToken: %v", err)+ }+ if claims.OrgID != "default" {+ t.Fatalf("claims.OrgID=%q, want %q", claims.OrgID, "default")+ }+ if claims.Feature != "max_monitored_systems" {+ t.Fatalf("claims.Feature=%q, want %q", claims.Feature, "max_monitored_systems")+ }+ if claims.InstanceHost != "pulse.example.com" {+ t.Fatalf("claims.InstanceHost=%q, want %q", claims.InstanceHost, "pulse.example.com")+ }+}++func TestVerifyPurchaseReturnToken_HostMismatch(t *testing.T) {+ token, err := SignPurchaseReturnToken(testPurchaseReturnSigningKey(), PurchaseReturnClaims{+ OrgID: "default",+ InstanceHost: "pulse-a.example.com",+ ReturnURL: "https://pulse-a.example.com/auth/license-purchase-activate",+ RegisteredClaims: jwt.RegisteredClaims{+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)),+ },+ })+ if err != nil {+ t.Fatalf("SignPurchaseReturnToken: %v", err)+ }++ _, err = VerifyPurchaseReturnToken(token, testPurchaseReturnSigningKey(), "pulse-b.example.com", time.Now())+ if !errors.Is(err, ErrPurchaseReturnHostMismatch) {+ t.Fatalf("VerifyPurchaseReturnToken() error=%v, want %v", err, ErrPurchaseReturnHostMismatch)+ }+}++func TestValidatePurchaseReturnURL(t *testing.T) {+ tests := []struct {+ name string+ raw string+ expectedHost string+ wantHost string+ wantErr error+ }{+ {+ name: "https public host",+ raw: "https://pulse.example.com/auth/license-purchase-activate",+ expectedHost: "pulse.example.com",+ wantHost: "pulse.example.com",+ },+ {+ name: "http localhost allowed",+ raw: "http://localhost:7655/auth/license-purchase-activate",+ wantHost: "localhost",+ },+ {+ name: "missing return url",+ raw: "",+ wantErr: ErrPurchaseReturnReturnURLMissing,+ },+ {+ name: "http public host rejected",+ raw: "http://pulse.example.com/auth/license-purchase-activate",+ wantErr: ErrPurchaseReturnReturnURLInvalid,+ },+ {+ name: "query string rejected",+ raw: "https://pulse.example.com/auth/license-purchase-activate?token=x",+ wantErr: ErrPurchaseReturnReturnURLInvalid,+ },+ {+ name: "host mismatch rejected",+ raw: "https://pulse.example.com/auth/license-purchase-activate",+ expectedHost: "other.example.com",+ wantErr: ErrPurchaseReturnHostMismatch,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ gotHost, err := ValidatePurchaseReturnURL(tt.raw, tt.expectedHost)+ if !errors.Is(err, tt.wantErr) {+ t.Fatalf("ValidatePurchaseReturnURL() error=%v, want %v", err, tt.wantErr)+ }+ if gotHost != tt.wantHost {+ t.Fatalf("ValidatePurchaseReturnURL() host=%q, want %q", gotHost, tt.wantHost)+ }+ })+ }+}++func TestSignPurchaseReturnToken_RequiresReturnURL(t *testing.T) {+ _, err := SignPurchaseReturnToken(testPurchaseReturnSigningKey(), PurchaseReturnClaims{+ OrgID: "default",+ InstanceHost: "pulse.example.com",+ RegisteredClaims: jwt.RegisteredClaims{+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)),+ },+ })+ if !errors.Is(err, ErrPurchaseReturnReturnURLMissing) {+ t.Fatalf("SignPurchaseReturnToken() error=%v, want %v", err, ErrPurchaseReturnReturnURLMissing)+ }+}diff --git a/pkg/licensing/upgrade.go b/pkg/licensing/upgrade.goindex 3dd357667a..2309ca4855 100644--- a/pkg/licensing/upgrade.go+++ b/pkg/licensing/upgrade.go@@ -11,24 +11,39 @@ const DefaultUpgradeURL = "https://pulserelay.pro/pricing?utm_source=pulse&utm_m// DefaultProTrialSignupURL is the hosted signup/checkout entrypoint for Pulse Pro trials.const DefaultProTrialSignupURL = "https://cloud.pulserelay.pro/start-pro-trial?utm_source=pulse&utm_medium=app&utm_campaign=trial_signup"+// DefaultPulseAccountPortalURL is the authenticated Pulse Account portal entrypoint.+const DefaultPulseAccountPortalURL = "https://cloud.pulserelay.pro/portal"+// ProTrialSignupURLEnvVar overrides the hosted signup URL for Pulse Pro trials.const ProTrialSignupURLEnvVar = "PULSE_PRO_TRIAL_SIGNUP_URL"+// PulseAccountPortalURLEnvVar overrides the Pulse Account portal URL.+const PulseAccountPortalURLEnvVar = "PULSE_ACCOUNT_PORTAL_URL"+// ResolveProTrialSignupURL returns the canonical hosted signup URL for Pulse Pro trials.// Invalid overrides are ignored and the default URL is returned.func ResolveProTrialSignupURL(override string) string {- if normalized, ok := validateProTrialSignupURLOverride(override); ok {+ if normalized, ok := validateExternalUpgradeURLOverride(override); ok {return normalized}return DefaultProTrialSignupURL}+// ResolvePulseAccountPortalURL returns the canonical Pulse Account portal URL.+// Invalid overrides are ignored and the default URL is returned.+func ResolvePulseAccountPortalURL(override string) string {+ if normalized, ok := validateExternalUpgradeURLOverride(override); ok {+ return normalized+ }+ return DefaultPulseAccountPortalURL+}+// ProTrialSignupURL returns the default hosted signup URL for Pulse Pro trials.func ProTrialSignupURL() string {return DefaultProTrialSignupURL}-func validateProTrialSignupURLOverride(raw string) (string, bool) {+func validateExternalUpgradeURLOverride(raw string) (string, bool) {raw = strings.TrimSpace(raw)if raw == "" {return "", falsediff --git a/pkg/licensing/upgrade_test.go b/pkg/licensing/upgrade_test.goindex bb41dfa66a..61aca601c5 100644--- a/pkg/licensing/upgrade_test.go+++ b/pkg/licensing/upgrade_test.go@@ -32,3 +32,34 @@ func TestResolveProTrialSignupURL_RejectsInvalidOverrides(t *testing.T) {})}}++func TestResolvePulseAccountPortalURL_DefaultWhenUnset(t *testing.T) {+ if got := ResolvePulseAccountPortalURL(""); got != DefaultPulseAccountPortalURL {+ t.Fatalf("ResolvePulseAccountPortalURL(\"\") = %q, want %q", got, DefaultPulseAccountPortalURL)+ }+}++func TestResolvePulseAccountPortalURL_UsesValidOverride(t *testing.T) {+ const override = "https://example.com/portal?src=test"++ if got := ResolvePulseAccountPortalURL(override); got != override {+ t.Fatalf("ResolvePulseAccountPortalURL() = %q, want %q", got, override)+ }+}++func TestResolvePulseAccountPortalURL_RejectsInvalidOverrides(t *testing.T) {+ testCases := []string{+ "relative/path",+ "javascript:alert(1)",+ "https://",+ "ftp://example.com/portal",+ }++ for _, tc := range testCases {+ t.Run(tc, func(t *testing.T) {+ if got := ResolvePulseAccountPortalURL(tc); got != DefaultPulseAccountPortalURL {+ t.Fatalf("ResolvePulseAccountPortalURL() = %q, want default %q", got, DefaultPulseAccountPortalURL)+ }+ })+ }+}diff --git a/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts b/tests/integration/tests/53-demo-mode-commercial-boundary.spec.tsindex 392d1a339a..12201257a4 100644--- a/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts+++ b/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts@@ -102,10 +102,12 @@ base.describe('Demo mode commercial boundary', () => {page,}, testInfo) => {let runtimeCapabilitiesRequests = 0;+ let commercialPostureRequests = 0;let entitlementsRequests = 0;let licenseStatusRequests = 0;let monitoredSystemLedgerRequests = 0;let billingStateRequests = 0;+ let checkoutStartRequests = 0;await page.addInitScript(() => {localStorage.setItem('pulse_whats_new_v2_shown', 'true');@@ -128,6 +130,15 @@ base.describe('Demo mode commercial boundary', () => {});});+ await page.route('**/api/license/commercial-posture', async (route) => {+ commercialPostureRequests += 1;+ await route.fulfill({+ status: 404,+ contentType: 'application/json',+ body: JSON.stringify({ error: 'not found' }),+ });+ });+await page.route('**/api/license/entitlements', async (route) => {entitlementsRequests += 1;await route.fulfill({@@ -164,6 +175,15 @@ base.describe('Demo mode commercial boundary', () => {});});+ await page.route('**/auth/license-purchase-start**', async (route) => {+ checkoutStartRequests += 1;+ await route.fulfill({+ status: 404,+ contentType: 'application/json',+ body: JSON.stringify({ error: 'not found' }),+ });+ });+await page.goto('/settings/system/billing', { waitUntil: 'domcontentloaded' });await page.waitForURL('**/settings/infrastructure/install', { timeout: 15_000 });@@ -172,6 +192,7 @@ base.describe('Demo mode commercial boundary', () => {message: 'expected demo shell to load runtime capabilities',}).toBeGreaterThan(0);+ expect(commercialPostureRequests, 'demo settings route should not read commercial posture').toBe(0);expect(entitlementsRequests, 'demo settings route should not read commercial entitlements').toBe(0);await expect(@@ -198,6 +219,7 @@ base.describe('Demo mode commercial boundary', () => {'demo settings route should not read the monitored-system ledger',).toBe(0);expect(billingStateRequests, 'demo settings route should not read hosted billing state').toBe(0);+ expect(checkoutStartRequests, 'demo settings route should not trigger hosted checkout start').toBe(0);const screenshotPath = path.resolve(__dirname,@@ -242,6 +264,7 @@ base.describe('Demo mode commercial boundary', () => {await hiddenNotFound('**/api/license/status');await hiddenNotFound('**/api/license/features');+ await hiddenNotFound('**/api/license/commercial-posture');await hiddenNotFound('**/api/license/entitlements');await hiddenNotFound('**/api/license/activate');await hiddenNotFound('**/api/license/clear');@@ -249,6 +272,7 @@ base.describe('Demo mode commercial boundary', () => {await hiddenNotFound('**/api/license/monitored-system-ledger');await hiddenNotFound('**/api/admin/orgs/**/billing-state');await hiddenNotFound('**/api/upgrade-metrics/**');+ await hiddenNotFound('**/auth/license-purchase-start**');await hiddenNotFound('**/auth/trial-activate');await page.goto('/settings/infrastructure/install', { waitUntil: 'domcontentloaded' });@@ -272,6 +296,7 @@ base.describe('Demo mode commercial boundary', () => {runtimeCapabilities: await probe('/api/license/runtime-capabilities'),status: await probe('/api/license/status'),features: await probe('/api/license/features'),+ commercialPosture: await probe('/api/license/commercial-posture'),entitlements: await probe('/api/license/entitlements'),activate: await probe('/api/license/activate', {method: 'POST',@@ -287,6 +312,7 @@ base.describe('Demo mode commercial boundary', () => {ledger: await probe('/api/license/monitored-system-ledger'),billingState: await probe('/api/admin/orgs/default/billing-state'),upgradeMetrics: await probe('/api/upgrade-metrics/stats'),+ checkoutStart: await probe('/auth/license-purchase-start'),trialActivate: await probe('/auth/trial-activate'),};});@@ -305,6 +331,7 @@ base.describe('Demo mode commercial boundary', () => {{ key: 'max_monitored_systems', limit: 0, current: 0, state: 'ok' },]);+ expect(responses.commercialPosture.status).toBe(404);expect(responses.entitlements.status).toBe(404);expect(responses.status.status).toBe(404);expect(responses.features.status).toBe(404);@@ -314,6 +341,7 @@ base.describe('Demo mode commercial boundary', () => {expect(responses.ledger.status).toBe(404);expect(responses.billingState.status).toBe(404);expect(responses.upgradeMetrics.status).toBe(404);+ expect(responses.checkoutStart.status).toBe(404);expect(responses.trialActivate.status).toBe(404);},);diff --git a/tests/integration/tests/54-monitored-system-billing-focus.spec.ts b/tests/integration/tests/54-monitored-system-billing-focus.spec.tsindex eb51b8ca8f..b8cc894e2d 100644--- a/tests/integration/tests/54-monitored-system-billing-focus.spec.ts+++ b/tests/integration/tests/54-monitored-system-billing-focus.spec.ts@@ -19,6 +19,27 @@ const MONITORED_SYSTEM_ENTITLEMENTS = {overflow_days_remaining: 14,};+const MONITORED_SYSTEM_RUNTIME_CAPABILITIES = {+ capabilities: [],+ limits: [{ key: 'max_monitored_systems', limit: 5, current: 16, state: 'enforced' }],+ hosted_mode: false,+ max_history_days: 90,+};++const MONITORED_SYSTEM_COMMERCIAL_POSTURE = {+ subscription_state: 'expired',+ upgrade_reasons: [],+ tier: 'free',+ trial_eligible: false,+ legacy_connections: {+ proxmox_nodes: 0,+ docker_hosts: 0,+ kubernetes_clusters: 0,+ },+ has_migration_gap: false,+ overflow_days_remaining: 14,+};+const MONITORED_SYSTEM_LEDGER = {systems: [{@@ -86,6 +107,19 @@ async function configureMonitoredSystemBillingFixtures(page: Page) {});});+ await page.route('**/api/license/runtime-capabilities', async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ capabilities: [],+ limits: [{ key: 'max_monitored_systems', limit: 5, current: 16, state: 'enforced' }],+ hosted_mode: false,+ max_history_days: 90,+ }),+ });+ });+await page.route('**/api/license/entitlements', async (route) => {await route.fulfill({status: 200,@@ -94,6 +128,22 @@ async function configureMonitoredSystemBillingFixtures(page: Page) {});});+ await page.route('**/api/license/runtime-capabilities', async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(MONITORED_SYSTEM_RUNTIME_CAPABILITIES),+ });+ });++ await page.route('**/api/license/commercial-posture', async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(MONITORED_SYSTEM_COMMERCIAL_POSTURE),+ });+ });+await page.route('**/api/license/monitored-system-ledger', async (route) => {await route.fulfill({status: 200,@@ -142,7 +192,7 @@ test.describe('Monitored-system billing focus', () => {await expect(page.getByText('Need a higher monitored-system cap?')).toBeVisible();await expect(page.getByRole('link', { name: 'Compare plans' })).toHaveAttribute('href',- 'https://cloud.pulserelay.pro/portal?feature=max_monitored_systems&service=upgrade&return_url=http%3A%2F%2F127.0.0.1%3A5173%2Fauth%2Flicense-purchase-activate',+ '/auth/license-purchase-start?feature=max_monitored_systems',);});});diff --git a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts b/tests/integration/tests/55-self-hosted-upgrade-return.spec.tsindex 7e48450ff5..946dc7fa27 100644--- a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts+++ b/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts@@ -1,9 +1,12 @@import { test, expect, type BrowserContext, type Page, type Route } from '@playwright/test';const DEV_SERVER_URL = 'http://127.0.0.1:5173';+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 ACTIVATED_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems`;+const PURCHASE_RETURN_TOKEN = 'prt_signed_checkout_return';const MONITORED_SYSTEM_ENTITLEMENTS = {capabilities: [],@@ -22,6 +25,27 @@ const MONITORED_SYSTEM_ENTITLEMENTS = {overflow_days_remaining: 14,};+const MONITORED_SYSTEM_RUNTIME_CAPABILITIES = {+ capabilities: [],+ limits: [{ key: 'max_monitored_systems', limit: 5, current: 16, state: 'enforced' }],+ hosted_mode: false,+ max_history_days: 90,+};++const MONITORED_SYSTEM_COMMERCIAL_POSTURE = {+ subscription_state: 'expired',+ upgrade_reasons: [],+ tier: 'free',+ trial_eligible: false,+ legacy_connections: {+ proxmox_nodes: 0,+ docker_hosts: 0,+ kubernetes_clusters: 0,+ },+ has_migration_gap: false,+ overflow_days_remaining: 14,+};+const MONITORED_SYSTEM_LEDGER = {systems: [{@@ -94,12 +118,11 @@ async function configureBillingFixtures(context: BrowserContext, page: Page) {});await context.route('**/api/license/runtime-capabilities', async (route) => {- await fulfillJSON(route, {- capabilities: [],- limits: [{ key: 'max_monitored_systems', limit: 5, current: 16, state: 'enforced' }],- hosted_mode: false,- max_history_days: 90,- });+ await fulfillJSON(route, MONITORED_SYSTEM_RUNTIME_CAPABILITIES);+ });++ await context.route('**/api/license/commercial-posture', async (route) => {+ await fulfillJSON(route, MONITORED_SYSTEM_COMMERCIAL_POSTURE);});await context.route('**/api/license/entitlements', async (route) => {@@ -135,12 +158,30 @@ test.describe('Self-hosted upgrade return flow', () => {const context = page.context();await configureBillingFixtures(context, page);+ let purchaseStartURL = '';++ await context.route(`${PURCHASE_START_URL}**`, async (route) => {+ const requestUrl = new URL(route.request().url());+ purchaseStartURL = requestUrl.toString();+ expect(requestUrl.searchParams.get('feature')).toBe('max_monitored_systems');+ await route.fulfill({+ status: 303,+ headers: {+ location:+ `${PULSE_ACCOUNT_PORTAL_URL}?feature=max_monitored_systems&service=upgrade` ++ `&return_url=${encodeURIComponent(PURCHASE_RETURN_URL)}` ++ `&purchase_return_token=${encodeURIComponent(PURCHASE_RETURN_TOKEN)}`,+ },+ body: '',+ });+ });await context.route(`${PULSE_ACCOUNT_PORTAL_URL}**`, async (route) => {const requestUrl = new URL(route.request().url());expect(requestUrl.searchParams.get('feature')).toBe('max_monitored_systems');expect(requestUrl.searchParams.get('service')).toBe('upgrade');expect(requestUrl.searchParams.get('return_url')).toBe(PURCHASE_RETURN_URL);+ expect(requestUrl.searchParams.get('purchase_return_token')).toBe(PURCHASE_RETURN_TOKEN);await route.fulfill({status: 200,@@ -152,6 +193,7 @@ test.describe('Self-hosted upgrade return flow', () => {`<form method="POST" action="${escapeAttribute(PURCHASE_RETURN_URL)}">` +'<input type="hidden" name="session_id" value="cs_upgrade_return">' +'<input type="hidden" name="feature" value="max_monitored_systems">' ++ `<input type="hidden" name="purchase_return_token" value="${escapeAttribute(PURCHASE_RETURN_TOKEN)}">` +'<button type="submit">Activate in Pulse Pro</button>' +'</form>' +'</body></html>',@@ -163,12 +205,15 @@ test.describe('Self-hosted upgrade return flow', () => {const formData = new URLSearchParams(route.request().postData() || '');expect(formData.get('session_id')).toBe('cs_upgrade_return');expect(formData.get('feature')).toBe('max_monitored_systems');+ expect(formData.get('purchase_return_token')).toBe(PURCHASE_RETURN_TOKEN);await route.fulfill({- status: 303,- headers: {- location: ACTIVATED_BILLING_URL,- },- body: '',+ status: 200,+ contentType: 'text/html',+ body:+ '<!doctype html><html><body>' ++ '<h1>Pulse Pro activated</h1>' ++ `<script>(function(){var redirectPath=${JSON.stringify(ACTIVATED_BILLING_URL)};if(window.opener&&!window.opener.closed){window.opener.location.assign(redirectPath);window.close();return;}window.location.replace(redirectPath);}());</script>` ++ '</body></html>',});});@@ -177,24 +222,32 @@ test.describe('Self-hosted upgrade return flow', () => {const comparePlansLink = page.getByRole('link', { name: 'Compare plans' });await expect(comparePlansLink).toHaveAttribute('href',- `${PULSE_ACCOUNT_PORTAL_URL}?feature=max_monitored_systems&service=upgrade&return_url=${encodeURIComponent(PURCHASE_RETURN_URL)}`,+ `${PURCHASE_START_PATH}?feature=max_monitored_systems`,);- const [popup] = await Promise.all([- page.waitForEvent('popup'),- comparePlansLink.click(),- ]);-- await popup.waitForLoadState('domcontentloaded');- await expect(popup.getByRole('heading', { name: 'Pulse Account' })).toBeVisible();- await expect(popup.getByRole('button', { name: 'Activate in Pulse Pro' })).toBeVisible();+ await expect(comparePlansLink).toHaveAttribute('target', '_blank');+ await comparePlansLink.click();+ await expect.poll(() => purchaseStartURL).toBe(+ `${PURCHASE_START_URL}?feature=max_monitored_systems`,+ );- await popup.getByRole('button', { name: 'Activate in Pulse Pro' }).click();- await popup.waitForURL('**/settings/system/billing/plan?intent=max_monitored_systems');- await expect(popup.getByRole('heading', { name: 'Pulse Pro' }).first()).toBeVisible();- await expect(popup.getByRole('tab', { name: 'Plan' })).toHaveAttribute('aria-selected', 'true');+ await page.goto(+ `${PULSE_ACCOUNT_PORTAL_URL}?feature=max_monitored_systems&service=upgrade` ++ `&return_url=${encodeURIComponent(PURCHASE_RETURN_URL)}` ++ `&purchase_return_token=${encodeURIComponent(PURCHASE_RETURN_TOKEN)}`,+ {+ waitUntil: 'domcontentloaded',+ },+ );+ await expect(page).toHaveURL(+ new RegExp(+ `${PULSE_ACCOUNT_PORTAL_URL.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}.*purchase_return_token=${PURCHASE_RETURN_TOKEN}`,+ ),+ );+ await expect(page.getByRole('heading', { name: 'Pulse Account' })).toBeVisible();+ await expect(page.getByRole('button', { name: 'Activate in Pulse Pro' })).toBeVisible();+ await page.getByRole('button', { name: 'Activate in Pulse Pro' }).click();await expect(page).toHaveURL(/\/settings\/system\/billing\/plan\?intent=max_monitored_systems$/);- await popup.close();});});