Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Use opaque checkout intents for self-hosted upgrade returns
rcourtman8c004f9a4cee
diff --git a/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md b/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.mdindex b21d5f3df3..58179fdab8 100644--- a/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md+++ b/docs/release-control/v6/internal/PULSE_ACCOUNT_PORTAL_SPEC.md@@ -429,8 +429,9 @@ Transition rule:3. in-product self-hosted upgrade CTAs should hand off into `Pulse Account`billing first, with `Pulse Account` owning self-hosted plan comparison andcheckout before returning through Pulse's activation callback- via a signed instance-bound handoff token rather than loose return query- parameters+ via a signed instance-bound return token plus an opaque commercial-owned+ `checkout_intent_id` rather than loose return query parameters or a+ browser-visible Pulse handoff URL4. utility pages should shrink toward redirects or lightweight recoveryhandoffs once equivalent Pulse Account areas exist@@ -472,9 +473,11 @@ Accepted as sufficient for RC and GA:billing route automatically5. `Pulse Account` must not render a second manual `Activate in Pulse Pro`step after hosted checkout success; the portal must resolve a verified- Pulse return template from a Pulse-owned purchase handoff record first and- let checkout success flow straight into Pulse's activation bridge-6. commercial surfaces are functional but still fragmented outside the owned+ commercial-owned `checkout_intent_id` first and let checkout success flow+ straight into Pulse's activation bridge+6. owned billing must surface explicit self-hosted purchase arrival states+ (`activated`, `cancelled`, `expired`, `failed`) after checkout return+7. commercial surfaces are functional but still fragmented outside the ownedcheckout-return path### Candidate lane targetdiff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 5fe50ee386..afa62395b4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -197,9 +197,9 @@ management, and fleet control surfaces.`/auth/license-purchase-start`, `/auth/license-purchase-handoff`, or`/auth/license-purchase-activate`, lifecycle-adjacent setup and fleetsurfaces may rely on that public-route wiring but must not reinterpret the- commercial-owned `purchase_handoff_id` record, the resolved- `activation_url_template`, purchase-return tokens, activation-bridge form- state, or demo-hidden commercial route policy as installer credentials,+ commercial-owned `checkout_intent_id`, purchase-return tokens,+ activation-bridge form state, owned billing purchase-arrival states, or+ demo-hidden commercial route policy as installer credentials,registration state, or fleet enrollment authority.## Forbidden Paths@@ -351,8 +351,8 @@ commercial reads.That same shared boundary now also owns the one-time checkout-return lookup:lifecycle-adjacent surfaces may initiate billing or account handoff throughshared public routes, but they must never persist, derive, or replay the-server-owned `purchase_handoff_id` or resolved activation template as lifecycle-state.+server-owned `checkout_intent_id` or owned billing purchase-arrival state as+lifecycle state.Lifecycle-adjacent storage and fleet surfaces now also depend on one governedphysical-disk history transport. When agent-backed disk telemetry is renderedthrough shared drawers or lifecycle-adjacent resource context, those readsdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 3cea74d674..7a719c19e1 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -527,29 +527,31 @@ hosted-only accounts do not render self-hosted license, refund, privacy, orself-hosted escalation paths by default, and self-hosted-only accounts do notfront-load an empty hosted-billing block before the real self-hosted jobs.That same runtime handoff contract now also covers product-originated-self-hosted upgrade arrivals: `/portal?service=upgrade&purchase_handoff_url=...`+self-hosted upgrade arrivals: `/portal?service=upgrade&checkout_intent_id=...`may open a portal-owned upgrade job inside `Billing`, but it must notfabricate broader self-hosted commercial history or revealretrieve/refund/privacy panels for a hosted-only account that only arrivedthrough an upgrade CTA.That same commercial contract now also includes the self-hosted purchasereturn path. Product-originated upgrade handoffs must include a canonical-server-owned `purchase_handoff_url` that points at a Pulse-owned handoff-record. Pulse still binds checkout completion to a signed-`purchase_return_token`, but that token must stay inside the Pulse-owned-handoff record and verified activation template rather than leaking into the-portal arrival URL. The portal runtime must resolve a verified-`activation_url_template` through Pulse-owned `GET /auth/license-purchase-handoff`-and use that verified template as the checkout success target instead of-trusting browser referrer state or loose `feature` / `return_url` query-parameters. Pulse's public `GET /auth/license-purchase-activate`+commercial-owned `checkout_intent_id`. Pulse still binds checkout completion+to a signed `purchase_return_token`, but that token must stay inside the+Pulse-owned activation callback path rather than leaking into the portal+arrival URL. The portal runtime must resolve the verified checkout intent+through the shared commercial API and use only that opaque intent when it+starts checkout instead of trusting browser referrer state or loose `feature`+/ `return_url` parameters. Pulse's public `GET /auth/license-purchase-activate`callback then serves an auto-submitting bridge into the owned POST activationpath, which redeems the completed checkout through the sharedlicense/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.+route. Stripe cancel must return directly to owned billing with+`purchase=cancelled`; activation success, expiry, and failure must return to+owned billing with explicit arrival states so the billing runtime can surface+those results in-product. When the upgrade flow was opened in a secondary tab,+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 keepsdiff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 9b8af08502..56824ad953 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -449,21 +449,23 @@ checkout-session creation, and the purchase return handoff back into Pulse viapublic pricing surface inside the runtime, and the authenticated portal shellmust not collapse back into a public-site-only waystation for new-purchasedepth. That handoff now starts through Pulse-owned `GET /auth/license-purchase-start`,-which mints a signed `purchase_return_token` for the local instance, wraps it-inside a short-lived Pulse-owned purchase handoff record, and sends-`Pulse Account` an absolute `purchase_handoff_url` before the browser leaves-for the portal. `Pulse Account` must resolve that server-owned handoff record-through Pulse-owned `GET /auth/license-purchase-handoff` before it starts-checkout, so the portal never trusts browser referrer state or loose-`feature` / `return_url` query parameters for self-hosted purchase completion.-Stripe success now lands-on Pulse's public `GET /auth/license-purchase-activate` bridge, which-auto-submits into the owned POST activation path; the portal must not render a-second manual `Activate in Pulse Pro` step after checkout. 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.+which mints a signed `purchase_return_token`, creates a commercial-owned+`checkout_intent_id` that already contains the resolved Pulse success/cancel+targets, and sends only that opaque `checkout_intent_id` to `Pulse Account`+before the browser leaves for the portal. `Pulse Account` must resolve that+checkout intent through the shared commercial API before it starts checkout,+so the portal never trusts browser referrer state, loose `feature` /+`return_url` query parameters, or a Pulse-local handoff URL for self-hosted+purchase completion. Stripe success now lands on Pulse's public+`GET /auth/license-purchase-activate` bridge, which auto-submits into the+owned POST activation path; the portal must not render a second manual+`Activate in Pulse Pro` step after checkout. Stripe cancel must return+directly to the owned Pulse billing plan route rather than back into the+portal. The owned activation callback must accept the signed state, redeem the+completed checkout, and return the operator to the canonical billing plan+route with an explicit owned purchase arrival state (`purchase=activated`,+`purchase=expired`, or `purchase=failed`) whether checkout completed in a+secondary tab or in the current-tab fallback path.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/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex db34fd8808..8bf46a0542 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -166,8 +166,8 @@ querying, and the operator-facing storage health presentation layer.`/auth/license-purchase-start`, `/auth/license-purchase-handoff`, or`/auth/license-purchase-activate`, storage and recovery may coexist withthose shared public-route helpers but must not reuse the commercial-owned- `purchase_handoff_id` record, the resolved `activation_url_template`,- purchase-return tokens, activation-bridge callbacks, or demo-hidden+ `checkout_intent_id`, purchase-return tokens, activation-bridge+ callbacks, owned billing purchase-arrival states, or demo-hiddencommercial route policy as recovery identity, restore proof, previewframing, or backup/recovery-local transport.@@ -350,8 +350,9 @@ applied.That same adjacent commercial boundary also owns one-time checkout-returnlookup. Storage and recovery may coexist with the shared purchase return routesin the app shell, but they must not cache, derive, or replay the-server-resolved `purchase_handoff_id` or activation template as recovery route-state, restore evidence, or storage-local navigation context.+server-resolved `checkout_intent_id` or owned billing purchase-arrival state+as recovery route state, restore evidence, or storage-local navigation+context.Storage- or recovery-adjacent commercial helpers must therefore wait for theshared presentation policy to resolve before attempting any read that couldotherwise hit a hidden commercial route during bootstrap.diff --git a/frontend-modern/src/components/Settings/ProLicensePanel.tsx b/frontend-modern/src/components/Settings/ProLicensePanel.tsxindex 979d3968c7..66ecb90211 100644--- a/frontend-modern/src/components/Settings/ProLicensePanel.tsx+++ b/frontend-modern/src/components/Settings/ProLicensePanel.tsx@@ -68,6 +68,7 @@ export const ProLicensePanel: Component = () => {hasPaidFeatures={state.hasPaidFeatures()}loading={state.loading()}onReload={() => void state.loadPanelData()}+ purchaseActivationNotice={state.purchaseActivationNotice()}showMonitoredSystemUpgradeArrival={state.showMonitoredSystemUpgradeArrival()}showTrialStart={state.showTrialStart()}startingTrial={state.startingTrial()}diff --git a/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx b/frontend-modern/src/components/Settings/ProLicensePlanSection.tsxindex edd060d9dd..9a889958e3 100644--- a/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx+++ b/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx@@ -36,6 +36,7 @@ interface ProLicensePlanSectionProps {loading: boolean;onReload: () => void;onStartTrial: () => void;+ purchaseActivationNotice: Notice | null;statusPresentation: {badgeClass: string;label: string;@@ -63,6 +64,14 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (proreturn (<>+ <Show when={props.purchaseActivationNotice}>+ {(notice) => (+ <div class={`mb-4 rounded-md border p-3 text-sm ${notice().tone}`}>+ <p class="font-medium">{notice().title}</p>+ <p class="mt-1 text-xs opacity-90">{notice().body}</p>+ </div>+ )}+ </Show><Show when={props.showMonitoredSystemUpgradeArrival}><div class="mb-4 rounded-md border border-primary/30 bg-primary/5 p-3 text-sm text-base-content"><p class="font-medium">diff --git a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsxindex 15c4b458b7..6249f25a60 100644--- a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx@@ -12,6 +12,10 @@ import {getPublicPricingUrl,getSelfHostedPurchaseStartUrl,SELF_HOSTED_PRO_BILLING_PLAN_HREF,+ SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,+ SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED,+ SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED,+ SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED,SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID,SELF_HOSTED_PRO_BILLING_USAGE_HREF,SELF_HOSTED_PRO_BILLING_USAGE_SECTION_ID,@@ -79,11 +83,12 @@ vi.mock('@/stores/notifications', () => ({}));describe('ProLicensePanel', () => {- const renderPanel = () => render(() => (- <Router>- <Route path="/" component={() => <ProLicensePanel />} />- </Router>- ));+ const renderPanel = () =>+ render(() => (+ <Router>+ <Route path="/" component={() => <ProLicensePanel />} />+ </Router>+ ));beforeEach(() => {mockEntitlements = {@@ -119,7 +124,9 @@ describe('ProLicensePanel', () => {href: getPublicPricingUrl(feature),external: true,}));- getUpgradeActionUrlOrFallbackMock.mockImplementation((feature?: string) => getPublicPricingUrl(feature));+ getUpgradeActionUrlOrFallbackMock.mockImplementation((feature?: string) =>+ getPublicPricingUrl(feature),+ );useLocationMock.mockReturnValue({search: '',pathname: '/settings/system/billing/plan',@@ -363,6 +370,39 @@ describe('ProLicensePanel', () => {});});+ it.each([+ {+ purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,+ title: 'Pulse Pro activated',+ },+ {+ purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED,+ title: 'Checkout cancelled',+ },+ {+ purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED,+ title: 'Upgrade return expired',+ },+ {+ purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED,+ title: 'Activation needs attention',+ },+ ])('shows the purchase arrival notice for $purchase', async ({ purchase, title }) => {+ useLocationMock.mockReturnValue({+ search: `?purchase=${purchase}`,+ pathname: '/settings/system/billing/plan',+ hash: '',+ });++ renderPanel();++ expect(screen.getByText(title)).toBeInTheDocument();+ expect(navigateMock).toHaveBeenCalledWith(SELF_HOSTED_PRO_BILLING_PLAN_HREF, {+ replace: true,+ scroll: false,+ });+ });+it('focuses the usage billing section when the usage route requests counting rules', async () => {useLocationMock.mockReturnValue({search: '?details=counting-rules',@@ -373,7 +413,9 @@ describe('ProLicensePanel', () => {renderPanel();expect(screen.getByRole('tab', { name: 'Usage' })).toHaveAttribute('aria-selected', 'true');- expect(document.getElementById(SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID)).not.toBeInTheDocument();+ expect(+ document.getElementById(SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID),+ ).not.toBeInTheDocument();expect(document.getElementById(SELF_HOSTED_PRO_BILLING_USAGE_SECTION_ID)).toBeInTheDocument();expect(screen.getByText('Monitored Systems')).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Hide counting rules' })).toBeInTheDocument();@@ -553,7 +595,7 @@ describe('ProLicensePanel', () => {expect(proLicensePanelSource).toContain('./ProLicensePlanSection');expect(proLicensePanelSource).toContain('SelfHostedCommercialRecoverySection');expect(proLicensePanelSource).toContain('SELF_HOSTED_PRO_BILLING_PRESENTATION');- expect(proLicensePanelSource).toContain("value={state.activeSection()}");+ expect(proLicensePanelSource).toContain('value={state.activeSection()}');expect(proLicensePanelSource).toContain('<Subtabs');expect(proLicensePanelSource).not.toContain('createSignal(');expect(proLicensePanelSource).not.toContain('useLocation()');@@ -561,7 +603,7 @@ describe('ProLicensePanel', () => {expect(proLicensePanelStateSource).toContain('resolveSelfHostedBillingSection');expect(proLicensePanelStateSource).toContain('getSelfHostedBillingPlanIntent');expect(proLicensePanelStateSource).toContain('getSelfHostedBillingUsageDetail');- expect(proLicensePanelStateSource).toContain('const setActiveSection = (section: SelfHostedBillingSection) => {');+ expect(proLicensePanelStateSource).toContain('const setActiveSection = (section: string) => {');expect(proLicensePanelStateSource).toContain('loadLicenseEntitlements(true)');expect(proLicensePanelStateSource).toContain('loadCommercialPosture(true)');expect(proLicensePanelStateSource).toContain('loadRuntimeCapabilities(true)');@@ -587,14 +629,14 @@ describe('ProLicensePanel', () => {expect(proLicensePlanSectionSource).toContain('!props.hasPaidFeatures && !props.trialEnded ? getInactiveProUpsellNotice() : null;',);- expect(proLicensePlanSectionSource).toContain(- 'monitoredSystemUpgradeArrivalTitle',- );+ expect(proLicensePlanSectionSource).toContain('monitoredSystemUpgradeArrivalTitle');expect(proLicensePlanSectionSource).toContain("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.');+ expect(proLicensePlanSectionSource).not.toContain(+ 'Unlock Pulse Patrol, alert analysis, auto-fix, and more.',+ );expect(selfHostedCommercialRecoverySectionSource).toContain('SELF_HOSTED_RECOVERY_PRESENTATION',);@@ -605,9 +647,7 @@ describe('ProLicensePanel', () => {'https://github.com/rcourtman/Pulse/blob/main/TERMS.md',);expect(selfHostedCommercialRecoverySectionSource).not.toContain('Start 14-day Pro Trial');- expect(selfHostedCommercialRecoverySectionSource).not.toContain(- 'Legacy v5 license detected',- );+ expect(selfHostedCommercialRecoverySectionSource).not.toContain('Legacy v5 license detected');expect(proLicensePanelSource).toContain('id={SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID}');expect(proLicensePanelSource).toContain('id={SELF_HOSTED_PRO_BILLING_USAGE_SECTION_ID}');});diff --git a/frontend-modern/src/components/Settings/useProLicensePanelState.ts b/frontend-modern/src/components/Settings/useProLicensePanelState.tsindex ba51f11be4..b631d94cfc 100644--- a/frontend-modern/src/components/Settings/useProLicensePanelState.ts+++ b/frontend-modern/src/components/Settings/useProLicensePanelState.ts@@ -1,9 +1,7 @@import { createMemo, createSignal, onMount } from 'solid-js';import { useLocation, useNavigate } from '@solidjs/router';import { notificationStore } from '@/stores/notifications';-import {- loadCommercialPosture,-} from '@/stores/licenseCommercial';+import { loadCommercialPosture } from '@/stores/licenseCommercial';import { isMultiTenantEnabled } from '@/stores/license';import { loadRuntimeCapabilities } from '@/stores/license';import {@@ -17,6 +15,7 @@ import {getCommercialMigrationNotice,getGrandfatheredPriceContinuityNotice,getLicenseFeatureLabel,+ getPurchaseActivationNotice,getLicenseSubscriptionStatusPresentation,getLicenseTierLabel,getTrialActivationNotice,@@ -24,11 +23,13 @@ import {} from '@/utils/licensePresentation';import {getSelfHostedBillingPlanIntent,+ getSelfHostedBillingPurchaseArrival,getSelfHostedBillingUsageDetail,resolveSelfHostedBillingSection,SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL,SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT,SELF_HOSTED_PRO_BILLING_PLAN_ROUTE,+ SELF_HOSTED_PRO_BILLING_PURCHASE_QUERY_PARAM,SELF_HOSTED_PRO_BILLING_USAGE_ROUTE,type SelfHostedBillingSection,} from '@/utils/pricingHandoff';@@ -58,6 +59,7 @@ export function useProLicensePanelState() {const [clearing, setClearing] = createSignal(false);const [startingTrial, setStartingTrial] = createSignal(false);const [trialActivationResult, setTrialActivationResult] = createSignal('');+ const [purchaseActivationResult, setPurchaseActivationResult] = createSignal('');const entitlements = createMemo(() => licenseEntitlements());const subscriptionState = createMemo(() => entitlements()?.subscription_state);@@ -72,10 +74,17 @@ export function useProLicensePanelState() {onMount(() => {const params = new URLSearchParams(location.search);- const result = params.get('trial')?.trim().toLowerCase() ?? '';- if (result) {- setTrialActivationResult(result);+ const trialResult = params.get('trial')?.trim().toLowerCase() ?? '';+ const purchaseResult = getSelfHostedBillingPurchaseArrival(location.search) ?? '';+ if (trialResult) {+ setTrialActivationResult(trialResult);params.delete('trial');+ }+ if (purchaseResult) {+ setPurchaseActivationResult(purchaseResult);+ params.delete(SELF_HOSTED_PRO_BILLING_PURCHASE_QUERY_PARAM);+ }+ if (trialResult || purchaseResult) {const nextSearch = params.toString();const nextPath = `${location.pathname}${nextSearch ? `?${nextSearch}` : ''}${location.hash ?? ''}`;navigate(nextPath, { replace: true, scroll: false });@@ -87,7 +96,10 @@ export function useProLicensePanelState() {return resolveSelfHostedBillingSection(location.pathname, location.search, location.hash);});- const setActiveSection = (section: SelfHostedBillingSection) => {+ const setActiveSection = (section: string) => {+ if (section !== 'plan' && section !== 'usage') {+ return;+ }const nextPath =section === 'usage'? SELF_HOSTED_PRO_BILLING_USAGE_ROUTE@@ -142,9 +154,9 @@ export function useProLicensePanelState() {if (!current) return false;return Boolean(current.licensed_email ||- current.expires_at ||- current.trial_expires_at ||- current.tier !== 'free',+ current.expires_at ||+ current.trial_expires_at ||+ current.tier !== 'free',);});@@ -154,7 +166,9 @@ export function useProLicensePanelState() {return getLicenseTierLabel(current.tier);});- const formattedPlanTerms = createMemo(() => formatLicensePlanVersion(entitlements()?.plan_version));+ const formattedPlanTerms = createMemo(() =>+ formatLicensePlanVersion(entitlements()?.plan_version),+ );const formattedFeatures = createMemo(() => {const current = entitlements();@@ -215,6 +229,9 @@ export function useProLicensePanelState() {const trialActivationNotice = createMemo(() => {return getTrialActivationNotice(trialActivationResult());});+ const purchaseActivationNotice = createMemo(() => {+ return getPurchaseActivationNotice(purchaseActivationResult());+ });const commercialMigrationNotice = createMemo(() =>getCommercialMigrationNotice(entitlements()?.commercial_migration),@@ -276,7 +293,9 @@ export function useProLicensePanelState() {loadRuntimeCapabilities(true),]);} catch (error) {- notificationStore.error(error instanceof Error ? error.message : 'Failed to activate license');+ notificationStore.error(+ error instanceof Error ? error.message : 'Failed to activate license',+ );} finally {setActivating(false);}@@ -320,6 +339,7 @@ export function useProLicensePanelState() {loadPanelData,loading,looksLikeLegacyLicenseKey,+ purchaseActivationNotice,setActiveSection,setLicenseKey,showCountingRulesByDefault,diff --git a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts b/frontend-modern/src/utils/__tests__/licensePresentation.test.tsindex 7bb7819608..9b453e2794 100644--- a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts+++ b/frontend-modern/src/utils/__tests__/licensePresentation.test.ts@@ -15,6 +15,7 @@ import {getNoActiveProLicenseState,getOrganizationBillingLicenseStatusLabel,getInactiveProUpsellNotice,+ getPurchaseActivationNotice,getTrialEndedProLicenseNotice,getTrialActivationNotice,isDisplayableLicenseFeature,@@ -186,6 +187,26 @@ describe('licensePresentation', () => {expect(getTrialActivationNotice('')).toBeNull();});+ it('returns canonical purchase activation notices', () => {+ expect(getPurchaseActivationNotice('activated')).toMatchObject({+ title: 'Pulse Pro activated',+ tone: expect.stringContaining('green'),+ });+ expect(getPurchaseActivationNotice('cancelled')).toMatchObject({+ title: 'Checkout cancelled',+ tone: expect.stringContaining('amber'),+ });+ expect(getPurchaseActivationNotice('expired')).toMatchObject({+ title: 'Upgrade return expired',+ body: expect.stringContaining('Start the upgrade again'),+ });+ expect(getPurchaseActivationNotice('failed')).toMatchObject({+ title: 'Activation needs attention',+ tone: expect.stringContaining('red'),+ });+ expect(getPurchaseActivationNotice('')).toBeNull();+ });+it('returns canonical organization and billing-admin billing vocabulary', () => {expect(getOrganizationBillingLicenseStatusLabel({ valid: false, in_grace_period: false })).toBe('No License',diff --git a/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts b/frontend-modern/src/utils/__tests__/pricingHandoff.test.tsindex fadd44f388..d0892a1baf 100644--- a/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts+++ b/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts@@ -4,6 +4,7 @@ import {getSelfHostedPurchaseReturnUrl,getSelfHostedBillingHref,getSelfHostedBillingPlanIntent,+ getSelfHostedBillingPurchaseArrival,getSelfHostedBillingUsageDetail,getPulseAccountPortalUpgradeUrl,getPricingRouteDestination,@@ -18,6 +19,7 @@ import {SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL,SELF_HOSTED_PRO_BILLING_PLAN_HREF,SELF_HOSTED_PRO_BILLING_PLAN_MONITORED_SYSTEM_UPGRADE_HREF,+ SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,SELF_HOSTED_PRO_BILLING_ROUTE,SELF_HOSTED_PRO_BILLING_USAGE_COUNTING_RULES_HREF,SELF_HOSTED_PRO_BILLING_USAGE_HREF,@@ -38,15 +40,13 @@ describe('pricingHandoff', () => {});it('routes self-hosted upgrades to Pulse Account first', () => {- expect(getUpgradeFallbackDestination('relay')).toBe(- getSelfHostedPurchaseStartUrl('relay'),- );+ expect(getUpgradeFallbackDestination('relay')).toBe(getSelfHostedPurchaseStartUrl('relay'));});it('derives the canonical self-hosted purchase return URL from the app origin', () => {- expect(getSelfHostedPurchaseReturnUrl('https://pulse.example.com/settings/system/billing/plan')).toBe(- `https://pulse.example.com${SELF_HOSTED_PURCHASE_RETURN_PATH}`,- );+ expect(+ getSelfHostedPurchaseReturnUrl('https://pulse.example.com/settings/system/billing/plan'),+ ).toBe(`https://pulse.example.com${SELF_HOSTED_PURCHASE_RETURN_PATH}`);});it('returns the canonical public pricing URL when no feature is provided', () => {@@ -79,17 +79,16 @@ describe('pricingHandoff', () => {expect(getSelfHostedBillingHref('plan', {intent: SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT,+ purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,}),- ).toBe(SELF_HOSTED_PRO_BILLING_PLAN_MONITORED_SYSTEM_UPGRADE_HREF);+ ).toBe(+ `${SELF_HOSTED_PRO_BILLING_PLAN_MONITORED_SYSTEM_UPGRADE_HREF}&purchase=${SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED}`,+ );});it('canonicalizes legacy self-hosted billing aliases to route-owned states', () => {expect(- resolveCanonicalSelfHostedBillingHref(- SELF_HOSTED_PRO_BILLING_ROUTE,- '',- '#pulse-pro-usage',- ),+ resolveCanonicalSelfHostedBillingHref(SELF_HOSTED_PRO_BILLING_ROUTE, '', '#pulse-pro-usage'),).toBe(SELF_HOSTED_PRO_BILLING_USAGE_HREF);expect(resolveCanonicalSelfHostedBillingHref(SELF_HOSTED_PRO_BILLING_ROUTE)).toBe(SELF_HOSTED_PRO_BILLING_PLAN_HREF,@@ -100,15 +99,16 @@ describe('pricingHandoff', () => {expect(resolveSelfHostedBillingSection(SELF_HOSTED_PRO_BILLING_USAGE_HREF)).toBe('usage');expect(resolveSelfHostedBillingSection(SELF_HOSTED_PRO_BILLING_PLAN_HREF)).toBe('plan');expect(- getSelfHostedBillingUsageDetail(- '?details=' + SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL,- ),+ getSelfHostedBillingUsageDetail('?details=' + SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL),).toBe(SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL);expect(- getSelfHostedBillingPlanIntent(- '?intent=' + SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT,- ),+ getSelfHostedBillingPlanIntent('?intent=' + SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT),).toBe(SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT);+ expect(+ getSelfHostedBillingPurchaseArrival(+ '?purchase=' + SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,+ ),+ ).toBe(SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED);});it('scopes in-product billing destinations to canonical routes and leaves external ones alone', () => {@@ -154,9 +154,7 @@ describe('pricingHandoff', () => {});it('detects the internal self-hosted purchase start destination', () => {- expect(isSelfHostedPurchaseStartDestination(getSelfHostedPurchaseStartUrl('relay'))).toBe(- true,- );+ expect(isSelfHostedPurchaseStartDestination(getSelfHostedPurchaseStartUrl('relay'))).toBe(true);expect(isSelfHostedPurchaseStartDestination(SELF_HOSTED_PURCHASE_START_PATH)).toBe(true);expect(isSelfHostedPurchaseStartDestination(getPulseAccountPortalUpgradeUrl('relay'))).toBe(false,@@ -172,7 +170,8 @@ describe('pricingHandoff', () => {expect(withOrigin).toContain('feature=relay');expect(withOrigin).toContain('service=upgrade');expect(withOrigin).toContain(- 'return_url=' + encodeURIComponent(`https://pulse.example.com${SELF_HOSTED_PURCHASE_RETURN_PATH}`),+ 'return_url=' ++ encodeURIComponent(`https://pulse.example.com${SELF_HOSTED_PURCHASE_RETURN_PATH}`),);});});diff --git a/frontend-modern/src/utils/licensePresentation.ts b/frontend-modern/src/utils/licensePresentation.tsindex 0373d58fbc..491ada3e4c 100644--- a/frontend-modern/src/utils/licensePresentation.ts+++ b/frontend-modern/src/utils/licensePresentation.ts@@ -44,11 +44,7 @@ const FEATURE_MIN_TIER_LABELS: Record<string, string> = {multi_tenant: 'MSP',};-const NON_DISPLAYABLE_FEATURES = new Set([- 'multi_user',- 'white_label',- 'unlimited',-]);+const NON_DISPLAYABLE_FEATURES = new Set(['multi_user', 'white_label', 'unlimited']);export interface LicenseSubscriptionStatusPresentation {label: string;@@ -268,6 +264,37 @@ export const getTrialActivationNotice = (result?: string | null): LicenseInlineN}};+export const getPurchaseActivationNotice = (result?: string | null): LicenseInlineNotice | null => {+ switch ((result || '').trim().toLowerCase()) {+ case 'activated':+ return {+ tone: 'border-green-200 dark:border-green-900 bg-green-50 dark:bg-green-900 text-green-900 dark:text-green-100',+ title: 'Pulse Pro activated',+ body: 'Pulse finished checkout and activated this instance automatically. The plan state below is live.',+ };+ case 'cancelled':+ return {+ tone: 'border-amber-200 dark:border-amber-900 bg-amber-50 dark:bg-amber-900 text-amber-900 dark:text-amber-100',+ title: 'Checkout cancelled',+ body: 'Checkout was cancelled before completion. The current plan state below is unchanged.',+ };+ case 'expired':+ return {+ tone: 'border-amber-200 dark:border-amber-900 bg-amber-50 dark:bg-amber-900 text-amber-900 dark:text-amber-100',+ title: 'Upgrade return expired',+ body: 'That secure checkout return link expired or was already used. Start the upgrade again from this instance if you still need it.',+ };+ case 'failed':+ return {+ tone: 'border-red-200 dark:border-red-900 bg-red-50 dark:bg-red-900 text-red-900 dark:text-red-100',+ title: 'Activation needs attention',+ body: 'Checkout completed, but Pulse could not finish local activation automatically. Review the plan state below, then retry the upgrade or use recovery if needed.',+ };+ default:+ return null;+ }+};+export const getLicenseSubscriptionStatusPresentation = (state?: string | null,): LicenseSubscriptionStatusPresentation => {diff --git a/frontend-modern/src/utils/pricingHandoff.ts b/frontend-modern/src/utils/pricingHandoff.tsindex 5009d84974..9dfd4b1ea4 100644--- a/frontend-modern/src/utils/pricingHandoff.ts+++ b/frontend-modern/src/utils/pricingHandoff.ts@@ -20,21 +20,27 @@ export const SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID = 'pulse-pro-plan';export const SELF_HOSTED_PRO_BILLING_USAGE_SECTION_ID = 'pulse-pro-usage';export const SELF_HOSTED_PRO_BILLING_USAGE_DETAILS_QUERY_PARAM = 'details';export const SELF_HOSTED_PRO_BILLING_PLAN_INTENT_QUERY_PARAM = 'intent';+export const SELF_HOSTED_PRO_BILLING_PURCHASE_QUERY_PARAM = 'purchase';export const SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL = 'counting-rules';export const SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT = 'max_monitored_systems';+export const SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED = 'activated';+export const SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED = 'cancelled';+export const SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED = 'expired';+export const SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED = 'failed';export type SelfHostedBillingSection = 'plan' | 'usage';-export type SelfHostedBillingUsageDetail =- typeof SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL;-export type SelfHostedBillingPlanIntent =- typeof SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT;+export type SelfHostedBillingUsageDetail = typeof SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL;+export type SelfHostedBillingPlanIntent = typeof SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT;+export type SelfHostedBillingPurchaseArrival =+ | typeof SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED+ | typeof SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED+ | typeof SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED+ | typeof SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED;export const SELF_HOSTED_PRO_BILLING_PLAN_HREF = SELF_HOSTED_PRO_BILLING_PLAN_ROUTE;export const SELF_HOSTED_PRO_BILLING_USAGE_HREF = SELF_HOSTED_PRO_BILLING_USAGE_ROUTE;-export const SELF_HOSTED_PRO_BILLING_USAGE_COUNTING_RULES_HREF =- `${SELF_HOSTED_PRO_BILLING_USAGE_ROUTE}?${SELF_HOSTED_PRO_BILLING_USAGE_DETAILS_QUERY_PARAM}=${SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL}`;-export const SELF_HOSTED_PRO_BILLING_PLAN_MONITORED_SYSTEM_UPGRADE_HREF =- `${SELF_HOSTED_PRO_BILLING_PLAN_ROUTE}?${SELF_HOSTED_PRO_BILLING_PLAN_INTENT_QUERY_PARAM}=${SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT}`;+export const SELF_HOSTED_PRO_BILLING_USAGE_COUNTING_RULES_HREF = `${SELF_HOSTED_PRO_BILLING_USAGE_ROUTE}?${SELF_HOSTED_PRO_BILLING_USAGE_DETAILS_QUERY_PARAM}=${SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL}`;+export const SELF_HOSTED_PRO_BILLING_PLAN_MONITORED_SYSTEM_UPGRADE_HREF = `${SELF_HOSTED_PRO_BILLING_PLAN_ROUTE}?${SELF_HOSTED_PRO_BILLING_PLAN_INTENT_QUERY_PARAM}=${SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT}`;const IN_PRODUCT_PRICING_DESTINATIONS: Record<string, string> = {max_monitored_systems: SELF_HOSTED_PRO_BILLING_PLAN_MONITORED_SYSTEM_UPGRADE_HREF,@@ -155,14 +161,16 @@ export function getPublicPricingUrl(feature?: string | null): string {return url.toString();}-export function getPulseAccountPortalUrl(options: {- email?: string | null;- feature?: string | null;- locationHref?: string;- returnUrl?: string | null;- service?: string | null;- searchParams?: URLSearchParams;-} = {}): string {+export function getPulseAccountPortalUrl(+ options: {+ email?: string | null;+ feature?: string | null;+ locationHref?: string;+ returnUrl?: string | null;+ service?: string | null;+ searchParams?: URLSearchParams;+ } = {},+): string {const url = new URL(DEFAULT_PULSE_ACCOUNT_PORTAL_URL);if (options.searchParams) {for (const [key, value] of options.searchParams.entries()) {@@ -188,7 +196,8 @@ export function getPulseAccountPortalUrl(options: {url.searchParams.set('service', normalizedService);}- const normalizedReturnUrl = options.returnUrl?.trim() || getSelfHostedPurchaseReturnUrl(options.locationHref);+ const normalizedReturnUrl =+ options.returnUrl?.trim() || getSelfHostedPurchaseReturnUrl(options.locationHref);if (normalizedReturnUrl) {url.searchParams.set(PULSE_ACCOUNT_PORTAL_RETURN_URL_QUERY_PARAM, normalizedReturnUrl);}@@ -222,26 +231,36 @@ export function getSelfHostedBillingUsageDetail(return detail === SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL ? detail : null;}-export function getSelfHostedBillingPlanIntent(- search: string,-): SelfHostedBillingPlanIntent | null {- const intent = billingSearch(search)- .get(SELF_HOSTED_PRO_BILLING_PLAN_INTENT_QUERY_PARAM)- ?.trim();+export function getSelfHostedBillingPlanIntent(search: string): SelfHostedBillingPlanIntent | null {+ const intent = billingSearch(search).get(SELF_HOSTED_PRO_BILLING_PLAN_INTENT_QUERY_PARAM)?.trim();return intent === SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT ? intent : null;}+export function getSelfHostedBillingPurchaseArrival(+ search: string,+): SelfHostedBillingPurchaseArrival | null {+ const purchase = billingSearch(search).get(SELF_HOSTED_PRO_BILLING_PURCHASE_QUERY_PARAM)?.trim();+ switch (purchase) {+ case SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED:+ case SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED:+ case SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED:+ case SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED:+ return purchase;+ default:+ return null;+ }+}+export function getSelfHostedBillingHref(section: SelfHostedBillingSection,options: {detail?: SelfHostedBillingUsageDetail | null;intent?: SelfHostedBillingPlanIntent | null;+ purchase?: SelfHostedBillingPurchaseArrival | null;} = {},): string {const baseRoute =- section === 'usage'- ? SELF_HOSTED_PRO_BILLING_USAGE_ROUTE- : SELF_HOSTED_PRO_BILLING_PLAN_ROUTE;+ section === 'usage' ? SELF_HOSTED_PRO_BILLING_USAGE_ROUTE : SELF_HOSTED_PRO_BILLING_PLAN_ROUTE;const params = new URLSearchParams();if (section === 'usage' && options.detail === SELF_HOSTED_PRO_BILLING_COUNTING_RULES_DETAIL) {@@ -251,16 +270,17 @@ export function getSelfHostedBillingHref();}- if (- section === 'plan' &&- options.intent === SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT- ) {+ if (section === 'plan' && options.intent === SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT) {params.set(SELF_HOSTED_PRO_BILLING_PLAN_INTENT_QUERY_PARAM,SELF_HOSTED_PRO_BILLING_MONITORED_SYSTEM_INTENT,);}+ if (options.purchase) {+ params.set(SELF_HOSTED_PRO_BILLING_PURCHASE_QUERY_PARAM, options.purchase);+ }+const search = params.toString();return `${baseRoute}${search ? `?${search}` : ''}`;}@@ -307,9 +327,7 @@ export function resolveCanonicalSelfHostedBillingHref(const section = resolveSelfHostedBillingSection(normalizedPath, search, hash);const canonicalPath =- section === 'usage'- ? SELF_HOSTED_PRO_BILLING_USAGE_ROUTE- : SELF_HOSTED_PRO_BILLING_PLAN_ROUTE;+ section === 'usage' ? SELF_HOSTED_PRO_BILLING_USAGE_ROUTE : SELF_HOSTED_PRO_BILLING_PLAN_ROUTE;const normalizedSearch = normalizeSearch(search);return `${canonicalPath}${normalizedSearch ? `?${normalizedSearch}` : ''}`;@@ -321,6 +339,7 @@ export function scopeSelfHostedBillingDestination(options: {detail?: SelfHostedBillingUsageDetail | null;intent?: SelfHostedBillingPlanIntent | null;+ purchase?: SelfHostedBillingPurchaseArrival | null;} = {},): UpgradeDestination {if (destination.external) {diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 61724813ea..474ce49b8d 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -4754,7 +4754,7 @@ func TestContract_EntitlementPayloadMonitoredSystemUsageJSONSnapshot(t *testing.const want = `{"capabilities":["update_alerts","sso","ai_patrol","relay","mobile_app","push_notifications","long_term_metrics","ai_alerts","ai_autofix","kubernetes_ai","agent_profiles","advanced_sso","rbac","audit_logging","advanced_reporting"],- "limits":[{"key":"max_monitored_systems","limit":15,"current":7,"state":"ok"}],+ "limits":[{"key":"max_monitored_systems","limit":15,"current":7,"current_available":true,"state":"ok"}],"subscription_state":"active","upgrade_reasons":[],"tier":"pro",@@ -4887,6 +4887,27 @@ func TestContract_DemoModeCommercialSurfacePolicy(t *testing.T) {func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {handler := createTestHandler(t)handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})+ var capturedReq struct {+ Feature string `json:"feature"`+ SuccessURL string `json:"success_url"`+ CancelURL string `json:"cancel_url"`+ }++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/v1/checkout/intent" {+ t.Fatalf("unexpected path %q", r.URL.Path)+ }+ if err := json.NewDecoder(r.Body).Decode(&capturedReq); err != nil {+ t.Fatalf("decode checkout intent request: %v", err)+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "checkout_intent_id": "cki_placeholder",+ "feature": capturedReq.Feature,+ })+ }))+ defer server.Close()+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)req := httptest.NewRequest(http.MethodGet,@@ -4919,47 +4940,20 @@ func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {if got := redirectURL.Query().Get("purchase_return_token"); got != "" {t.Fatalf("purchase_return_token=%q, want omitted portal query", got)}-- handoffURL := strings.TrimSpace(redirectURL.Query().Get("purchase_handoff_url"))- if handoffURL == "" {- t.Fatal("expected purchase_handoff_url in Pulse Account redirect")+ if got := redirectURL.Query().Get("purchase_handoff_url"); got != "" {+ t.Fatalf("purchase_handoff_url=%q, want omitted portal query", got)}-- handoffReq := httptest.NewRequest(http.MethodGet, handoffURL, nil)- handoffRec := httptest.NewRecorder()- handler.HandleCheckoutHandoff(handoffRec, handoffReq)-- if handoffRec.Code != http.StatusOK {- t.Fatalf("handoff status=%d, want %d: %s", handoffRec.Code, http.StatusOK, handoffRec.Body.String())+ if got := redirectURL.Query().Get("checkout_intent_id"); got != "cki_placeholder" {+ t.Fatalf("checkout_intent_id=%q, want cki_placeholder", got)}- var handoffPayload struct {- Feature string `json:"feature"`- ActivationURLTemplate string `json:"activation_url_template"`- }- if err := json.NewDecoder(handoffRec.Body).Decode(&handoffPayload); err != nil {- t.Fatalf("decode handoff payload: %v", err)- }-- handoffURLParsed, err := url.Parse(handoffURL)+ activationURL, err := url.Parse(capturedReq.SuccessURL)if err != nil {- t.Fatalf("parse purchase_handoff_url: %v", err)- }- handoffID := strings.TrimSpace(handoffURLParsed.Query().Get(licensePurchaseHandoffIDField))- if handoffID == "" {- t.Fatal("expected purchase_handoff_id in purchase_handoff_url")- }- handoffQuery := handoffURLParsed.Query()- handoffQuery.Set(licensePurchaseHandoffIDField, "placeholder")- handoffURLParsed.RawQuery = handoffQuery.Encode()-- activationURL, err := url.Parse(handoffPayload.ActivationURLTemplate)- if err != nil {- t.Fatalf("parse activation_url_template: %v", err)+ t.Fatalf("parse success_url: %v", err)}returnToken := strings.TrimSpace(activationURL.Query().Get(licensePurchaseReturnTokenField))if returnToken == "" {- t.Fatal("expected signed purchase_return_token in activation_url_template")+ t.Fatal("expected signed purchase_return_token in success_url")}signingKey, err := handler.purchaseReturnSigningKey()if err != nil {@@ -4980,17 +4974,19 @@ func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {activationURL.RawQuery = activationQuery.Encode()got, err := json.Marshal(struct {- PortalService string `json:"portal_service"`- PortalUtmContent string `json:"portal_utm_content"`- PortalHandoffURL string `json:"portal_handoff_url"`- HandoffFeature string `json:"handoff_feature"`- ActivationURLTemplate string `json:"activation_url_template"`+ PortalService string `json:"portal_service"`+ PortalUtmContent string `json:"portal_utm_content"`+ CheckoutIntentID string `json:"checkout_intent_id"`+ IntentFeature string `json:"intent_feature"`+ SuccessURLTemplate string `json:"success_url_template"`+ CancelURL string `json:"cancel_url"`}{- PortalService: redirectURL.Query().Get("service"),- PortalUtmContent: redirectURL.Query().Get("utm_content"),- PortalHandoffURL: handoffURLParsed.String(),- HandoffFeature: handoffPayload.Feature,- ActivationURLTemplate: activationURL.String(),+ PortalService: redirectURL.Query().Get("service"),+ PortalUtmContent: redirectURL.Query().Get("utm_content"),+ CheckoutIntentID: redirectURL.Query().Get("checkout_intent_id"),+ IntentFeature: capturedReq.Feature,+ SuccessURLTemplate: activationURL.String(),+ CancelURL: capturedReq.CancelURL,})if err != nil {t.Fatalf("marshal normalized handoff snapshot: %v", err)@@ -4999,9 +4995,10 @@ func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {const want = `{"portal_service":"upgrade","portal_utm_content":"legacy-bookmark",- "portal_handoff_url":"https://pulse.example.com/auth/license-purchase-handoff?purchase_handoff_id=placeholder",- "handoff_feature":"max_monitored_systems",- "activation_url_template":"https://pulse.example.com/auth/license-purchase-activate?purchase_return_token=placeholder\u0026session_id=%7BCHECKOUT_SESSION_ID%7D"+ "checkout_intent_id":"cki_placeholder",+ "intent_feature":"max_monitored_systems",+ "success_url_template":"https://pulse.example.com/auth/license-purchase-activate?purchase_return_token=placeholder\u0026session_id=%7BCHECKOUT_SESSION_ID%7D",+ "cancel_url":"https://pulse.example.com/settings/system/billing/plan?intent=max_monitored_systems\u0026purchase=cancelled"}`assertJSONSnapshot(t, got, want)diff --git a/internal/api/license_handlers_test.go b/internal/api/license_handlers_test.goindex d90800e554..7fd109b974 100644--- a/internal/api/license_handlers_test.go+++ b/internal/api/license_handlers_test.go@@ -696,6 +696,30 @@ func TestHandleActivateLicense_ValidKey(t *testing.T) {func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *testing.T) {handler := createTestHandler(t)handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})+ var capturedReq struct {+ Feature string `json:"feature"`+ SuccessURL string `json:"success_url"`+ CancelURL string `json:"cancel_url"`+ }++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/v1/checkout/intent" {+ t.Fatalf("unexpected path %q", r.URL.Path)+ }+ if r.Method != http.MethodPost {+ t.Fatalf("method = %s, want POST", r.Method)+ }+ if err := json.NewDecoder(r.Body).Decode(&capturedReq); err != nil {+ t.Fatalf("decode checkout intent request: %v", err)+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "checkout_intent_id": "cki_test_upgrade",+ "feature": capturedReq.Feature,+ })+ }))+ defer server.Close()+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)req := httptest.NewRequest(http.MethodGet,@@ -729,9 +753,11 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *tesif got := redirectURL.Query().Get("return_url"); got != "" {t.Fatalf("return_url = %q, want omitted portal query", got)}- handoffURL := redirectURL.Query().Get("purchase_handoff_url")- if strings.TrimSpace(handoffURL) == "" {- t.Fatal("expected purchase_handoff_url in redirect")+ if got := redirectURL.Query().Get("checkout_intent_id"); got != "cki_test_upgrade" {+ t.Fatalf("checkout_intent_id = %q, want cki_test_upgrade", got)+ }+ if got := redirectURL.Query().Get("purchase_handoff_url"); got != "" {+ t.Fatalf("purchase_handoff_url = %q, want omitted portal query", got)}if got := redirectURL.Query().Get("utm_content"); got != "legacy-bookmark" {t.Fatalf("utm_content = %q, want preserved query value", got)@@ -740,42 +766,20 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *test.Fatalf("purchase_return_token = %q, want omitted portal query", got)}- handoffURLParsed, err := url.Parse(handoffURL)- if err != nil {- t.Fatalf("parse purchase_handoff_url: %v", err)- }- if handoffURLParsed.Scheme != "https" || handoffURLParsed.Host != "pulse.example.com" || handoffURLParsed.Path != licensePurchaseHandoffPath {- t.Fatalf("purchase_handoff_url = %q, want Pulse handoff endpoint", handoffURL)- }- handoffID := handoffURLParsed.Query().Get(licensePurchaseHandoffIDField)- if strings.TrimSpace(handoffID) == "" {- t.Fatal("expected purchase_handoff_id in purchase_handoff_url")+ if capturedReq.Feature != "relay" {+ t.Fatalf("checkout intent feature = %q, want relay", capturedReq.Feature)}- handoffReq := httptest.NewRequest(http.MethodGet, handoffURL, nil)- handoffRec := httptest.NewRecorder()- handler.HandleCheckoutHandoff(handoffRec, handoffReq)- if handoffRec.Code != http.StatusOK {- t.Fatalf("handoff status = %d, want %d (body=%q)", handoffRec.Code, http.StatusOK, handoffRec.Body.String())- }- var handoffResp struct {- Feature string `json:"feature"`- ActivationURLTemplate string `json:"activation_url_template"`- }- if err := json.Unmarshal(handoffRec.Body.Bytes(), &handoffResp); err != nil {- t.Fatalf("unmarshal handoff response: %v", err)- }- if handoffResp.Feature != "relay" {- t.Fatalf("handoff feature = %q, want relay", handoffResp.Feature)- }-- activationURL, err := url.Parse(handoffResp.ActivationURLTemplate)+ activationURL, err := url.Parse(capturedReq.SuccessURL)if err != nil {- t.Fatalf("parse activation_url_template: %v", err)+ t.Fatalf("parse success_url: %v", err)+ }+ if activationURL.String() != capturedReq.SuccessURL {+ t.Fatalf("success_url normalized unexpectedly: %q", capturedReq.SuccessURL)}returnToken := activationURL.Query().Get(licensePurchaseReturnTokenField)if strings.TrimSpace(returnToken) == "" {- t.Fatal("expected signed purchase_return_token in activation template")+ t.Fatal("expected signed purchase_return_token in success_url")}signingKey, err := handler.purchaseReturnSigningKey()if err != nil {@@ -791,6 +795,9 @@ func TestHandleCheckoutStart_RedirectsToPulseAccountWithSignedReturnState(t *tesif claims.Feature != "relay" {t.Fatalf("claims.Feature = %q, want relay", claims.Feature)}+ if capturedReq.CancelURL != "https://pulse.example.com/settings/system/billing/plan?purchase=cancelled" {+ t.Fatalf("cancel_url = %q", capturedReq.CancelURL)+ }}func TestHandleCheckoutHandoff_ResolvesServerOwnedPurchaseRecord(t *testing.T) {@@ -1005,7 +1012,7 @@ func TestHandleCheckoutActivation_RedeemsCompletedCheckoutAndWritesSuccessBridgeif !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") {+ if !strings.Contains(rec.Body.String(), "/settings/system/billing/plan?intent=max_monitored_systems&purchase=activated") {t.Fatalf("body = %q, want monitored-system billing route", rec.Body.String())}if !handler.Service(context.Background()).IsActivated() {@@ -1064,6 +1071,9 @@ func TestHandleCheckoutActivation_RendersFailurePageWhenCheckoutIsNotFulfilled(tif !strings.Contains(rec.Body.String(), "Checkout is not complete yet.") {t.Fatalf("body = %q, want pending checkout message", rec.Body.String())}+ if !strings.Contains(rec.Body.String(), "purchase=failed") {+ t.Fatalf("body = %q, want failed purchase billing redirect", rec.Body.String())+ }}// ========================================diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.goindex 552552a7a1..4f0172badc 100644--- a/internal/api/licensing_bridge.go+++ b/internal/api/licensing_bridge.go@@ -58,6 +58,8 @@ type trialActivationClaimsModel = pkglicensing.TrialActivationClaimstype purchaseReturnClaimsModel = pkglicensing.PurchaseReturnClaimstype entitlementLeaseClaimsModel = pkglicensing.EntitlementLeaseClaimstype licenseTier = pkglicensing.Tier+type checkoutIntentRequestModel = pkglicensing.CheckoutIntentRequest+type checkoutIntentResponseModel = pkglicensing.CheckoutIntentResponseconst (featureMultiTenantKey = pkglicensing.FeatureMultiTenantdiff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.goindex 1d8ff44fe4..93989570d1 100644--- a/internal/api/licensing_handlers.go+++ b/internal/api/licensing_handlers.go@@ -32,10 +32,16 @@ const (licensePurchaseSessionIDField = "session_id"licensePurchaseReturnTokenField = "purchase_return_token"pulseAccountUpgradeService = "upgrade"+ pulseAccountPortalCheckoutIntentField = "checkout_intent_id"pulseAccountPortalFeatureQueryParam = "feature"pulseAccountPortalHandoffURLQueryParam = "purchase_handoff_url"pulseAccountPortalServiceQueryParam = "service"pulseAccountPortalReturnTokenQueryParam = "purchase_return_token"+ selfHostedBillingPurchaseQueryParam = "purchase"+ selfHostedBillingPurchaseActivated = "activated"+ selfHostedBillingPurchaseCancelled = "cancelled"+ selfHostedBillingPurchaseExpired = "expired"+ selfHostedBillingPurchaseFailed = "failed"purchaseReturnKeyPurpose = "pulse-license-purchase-return")@@ -285,7 +291,7 @@ func (h *LicenseHandlers) purchaseCheckoutHandoffStore() *purchaseCheckoutHandofreturn h.purchaseHandoffs}-func pulseAccountUpgradeURLForRequest(handoffURL string, query url.Values) (string, error) {+func pulseAccountUpgradeURLForRequest(checkoutIntentID string, query url.Values) (string, error) {portalURL := strings.TrimSpace(pulseAccountPortalURLFromLicensing(""))if portalURL == "" {return "", fmt.Errorf("pulse account portal url is unavailable")@@ -300,9 +306,11 @@ func pulseAccountUpgradeURLForRequest(handoffURL string, query url.Values) (strifor key, values := range query {switch key {case pulseAccountPortalFeatureQueryParam,+ pulseAccountPortalCheckoutIntentField,pulseAccountPortalHandoffURLQueryParam,pulseAccountPortalServiceQueryParam,pulseAccountPortalReturnTokenQueryParam,+ "return_url","checkout","session_id":continue@@ -317,11 +325,27 @@ func pulseAccountUpgradeURLForRequest(handoffURL string, query url.Values) (stri}params.Set(pulseAccountPortalServiceQueryParam, pulseAccountUpgradeService)- params.Set(pulseAccountPortalHandoffURLQueryParam, strings.TrimSpace(handoffURL))+ params.Set(pulseAccountPortalCheckoutIntentField, strings.TrimSpace(checkoutIntentID))parsed.RawQuery = params.Encode()return parsed.String(), nil}+func publicAbsoluteURLForPath(r *http.Request, cfg *config.Config, path string) (string, error) {+ baseURL := publicBaseURLForRequest(r, cfg)+ if baseURL == "" {+ return "", fmt.Errorf("public base url is unavailable")+ }+ base, err := url.Parse(baseURL)+ if err != nil || base == nil {+ return "", fmt.Errorf("parse public base url: %w", err)+ }+ relative, err := url.Parse(strings.TrimSpace(path))+ if err != nil || relative == nil {+ return "", fmt.Errorf("parse relative public path: %w", err)+ }+ return base.ResolveReference(relative).String(), nil+}+func licensePurchaseHandoffURLForRequest(r *http.Request,cfg *config.Config,@@ -353,21 +377,38 @@ func licensePurchaseActivationTemplateURL(returnURL, returnToken string) (stringreturn parsed.String(), nil}-func licensePurchaseActivationRedirectPath(feature string) string {+func licensePurchaseActivationRedirectPath(feature, purchaseResult string) string {normalizedFeature := strings.TrimSpace(feature)+ query := url.Values{}switch normalizedFeature {case "max_monitored_systems":- return "/settings/system/billing/plan?intent=max_monitored_systems"- default:+ query.Set("intent", "max_monitored_systems")+ }+ switch strings.TrimSpace(purchaseResult) {+ case selfHostedBillingPurchaseActivated,+ selfHostedBillingPurchaseCancelled,+ selfHostedBillingPurchaseExpired,+ selfHostedBillingPurchaseFailed:+ query.Set(selfHostedBillingPurchaseQueryParam, strings.TrimSpace(purchaseResult))+ }+ encoded := query.Encode()+ if encoded == "" {return "/settings/system/billing/plan"}+ return "/settings/system/billing/plan?" + encoded}-func writeLicensePurchaseActivationFailurePage(w http.ResponseWriter, statusCode int, feature, message string) {+func writeLicensePurchaseActivationFailurePage(+ w http.ResponseWriter,+ statusCode int,+ feature string,+ purchaseResult string,+ message string,+) {if statusCode < http.StatusBadRequest {statusCode = http.StatusBadRequest}- redirectPath := licensePurchaseActivationRedirectPath(feature)+ redirectPath := licensePurchaseActivationRedirectPath(feature, purchaseResult)escapedMessage := html.EscapeString(strings.TrimSpace(message))if escapedMessage == "" {escapedMessage = "Purchase activation could not be completed."@@ -377,14 +418,16 @@ func writeLicensePurchaseActivationFailurePage(w http.ResponseWriter, statusCodew.WriteHeader(statusCode)_, _ = fmt.Fprintf(w,- "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Pulse Pro activation</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 activation failed</h1><p style=\"margin-bottom:1rem\">%s</p><p><a href=\"%s\">Open Pulse Pro billing</a></p></main></body></html>",+ "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Pulse Pro activation</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 activation needs attention</h1><p id=\"purchase-return-status\" style=\"margin-bottom:1rem\">%s</p><p><a href=\"%s\">Open 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-return',redirectPath:redirectPath,result:%q},window.location.origin);window.opener.location.assign(redirectPath);}}catch(_){redirectedOriginalTab=false;}if(redirectedOriginalTab){setTimeout(function(){try{window.close();}catch(_){ }if(statusEl){statusEl.textContent='Pulse Pro billing has been reopened in the original tab. You can close this window if it stays open.';}},75);return;}if(statusEl){statusEl.textContent='Returning to Pulse Pro billing.';}setTimeout(function(){window.location.replace(redirectPath);},150);}());</script></body></html>",escapedMessage,escapedLink,+ redirectPath,+ strings.TrimSpace(purchaseResult),)}func writeLicensePurchaseActivationSuccessPage(w http.ResponseWriter, feature string) {- redirectPath := licensePurchaseActivationRedirectPath(feature)+ redirectPath := licensePurchaseActivationRedirectPath(feature, selfHostedBillingPurchaseActivated)escapedLink := html.EscapeString(redirectPath)w.Header().Set("Content-Type", "text/html; charset=utf-8")w.WriteHeader(http.StatusOK)@@ -1405,30 +1448,41 @@ func (h *LicenseHandlers) HandleCheckoutStart(w http.ResponseWriter, r *http.Reqreturn}- handoffStore := h.purchaseCheckoutHandoffStore()- if handoffStore == nil {+ cancelURL, err := publicAbsoluteURLForPath(+ r,+ h.cfg,+ licensePurchaseActivationRedirectPath(feature, selfHostedBillingPurchaseCancelled),+ )+ if err != nil {+ log.Error().Err(err).Str("feature", feature).Msg("Failed to build Pulse Account cancellation return url")http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)return}- handoffID, err := handoffStore.issue(- feature,- activationURLTemplate,- time.Now().UTC().Add(purchaseCheckoutHandoffTTL),- )- if err != nil {- log.Error().Err(err).Str("feature", feature).Msg("Failed to issue Pulse Account handoff record")++ lsClient := newLicenseServerClientFromLicensing("")+ if lsClient == nil {http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)return}- handoffURL, err := licensePurchaseHandoffURLForRequest(r, h.cfg, handoffID)+ checkoutIntent, err := lsClient.CreateCheckoutIntent(r.Context(), checkoutIntentRequestModel{+ Feature: feature,+ SuccessURL: activationURLTemplate,+ CancelURL: cancelURL,+ })if err != nil {- log.Error().Err(err).Str("feature", feature).Msg("Failed to build Pulse Account handoff url")+ log.Error().Err(err).Str("feature", feature).Msg("Failed to create Pulse Account checkout intent")+ http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)+ return+ }+ checkoutIntentID := strings.TrimSpace(checkoutIntent.CheckoutIntentID)+ if checkoutIntentID == "" {+ log.Error().Str("feature", feature).Msg("Pulse Account checkout intent response omitted id")http.Error(w, "Pulse Account handoff unavailable", http.StatusServiceUnavailable)return}- destination, err := pulseAccountUpgradeURLForRequest(handoffURL, r.URL.Query())+ destination, err := pulseAccountUpgradeURLForRequest(checkoutIntentID, 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)@@ -1512,13 +1566,13 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httfeature := strings.TrimSpace(r.URL.Query().Get("feature"))returnToken := strings.TrimSpace(r.URL.Query().Get(licensePurchaseReturnTokenField))if returnToken == "" || sessionID == "" {- writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, "Purchase activation link expired or is missing required state. Reopen the upgrade flow from Pulse Pro billing.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, selfHostedBillingPurchaseExpired, "Purchase activation link expired or is missing required state. Reopen the upgrade flow from Pulse Pro billing.")return}claims, err := h.verifiedPurchaseReturnClaims(r, returnToken)if err != nil {log.Warn().Err(err).Msg("Purchase return token verification failed during GET bridge")- writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, "Purchase activation link expired or is invalid. Reopen the upgrade flow from Pulse Pro billing.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, selfHostedBillingPurchaseExpired, "Purchase activation link expired or is invalid. Reopen the upgrade flow from Pulse Pro billing.")return}if claims != nil && strings.TrimSpace(claims.Feature) != "" {@@ -1532,7 +1586,7 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httreturn}if err := r.ParseForm(); err != nil {- writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, "", "Purchase activation request was invalid.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, "", selfHostedBillingPurchaseFailed, "Purchase activation request was invalid.")return}@@ -1540,25 +1594,25 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httfeature := 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.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, selfHostedBillingPurchaseExpired, "Purchase activation link expired or is missing required state. Reopen the upgrade flow from Pulse Pro billing.")return}claims, err := h.verifiedPurchaseReturnClaims(r, returnToken)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.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, selfHostedBillingPurchaseExpired, "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.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, strings.TrimSpace(claims.Feature), selfHostedBillingPurchaseExpired, "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.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, selfHostedBillingPurchaseFailed, "Purchase activation requires a completed checkout session.")return}@@ -1577,7 +1631,7 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *htt}}if replayStore == nil || replaySubject == "" {- writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, "Pulse could not verify the purchase activation state for this checkout.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, selfHostedBillingPurchaseFailed, "Pulse could not verify the purchase activation state for this checkout.")return}@@ -1589,12 +1643,12 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httstored, 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.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, selfHostedBillingPurchaseFailed, "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.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusConflict, feature, selfHostedBillingPurchaseActivated, "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) {@@ -1610,7 +1664,7 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httlsClient := newLicenseServerClientFromLicensing("")if lsClient == nil {clearReplay("license_server_unavailable", nil)- writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, "Pulse could not contact the commercial activation service.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusServiceUnavailable, feature, selfHostedBillingPurchaseFailed, "Pulse could not contact the commercial activation service.")return}@@ -1623,7 +1677,7 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httif 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.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadGateway, feature, selfHostedBillingPurchaseFailed, "Pulse could not confirm the completed checkout yet. Please try again in a moment.")return}@@ -1633,21 +1687,21 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *httmessage = strings.TrimSpace(checkoutResult.Message)}clearReplay("checkout_not_fulfilled", nil)- writeLicensePurchaseActivationFailurePage(w, http.StatusConflict, feature, message)+ writeLicensePurchaseActivationFailurePage(w, http.StatusConflict, feature, selfHostedBillingPurchaseFailed, 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.")+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadGateway, feature, selfHostedBillingPurchaseFailed, "The completed checkout did not return an activation key.")return}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))+ writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, feature, selfHostedBillingPurchaseFailed, userFriendlyActivationError(err))return}diff --git a/internal/cloudcp/portal/commercial_proxy.go b/internal/cloudcp/portal/commercial_proxy.goindex f084e961bc..010ab2abbe 100644--- a/internal/cloudcp/portal/commercial_proxy.go+++ b/internal/cloudcp/portal/commercial_proxy.go@@ -20,6 +20,10 @@ var allowedCommercialProxyEndpoints = map[string]map[string]struct{}{http.MethodGet: {},http.MethodPost: {},},+ "/v1/checkout/intent": {+ http.MethodGet: {},+ http.MethodPost: {},+ },"/v1/manage/request": {http.MethodPost: {},},diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.jsonindex 513793d4e0..afb654a4ea 100644--- a/internal/cloudcp/portal/dist/build_manifest.json+++ b/internal/cloudcp/portal/dist/build_manifest.json@@ -1,5 +1,5 @@{- "source_hash": "a9eb5e65c406a16d4470b9296fbd6f2ca7bd54d9bbf37606ed6a6d4b7f6fc1c4",+ "source_hash": "23046feb48a7193d9ac229bba75f08a8c899b1092d0e4b86bab9e327f4e58abf","build_inputs": ["package.json","tsconfig.json",diff --git a/internal/cloudcp/portal/dist/portal_app.js b/internal/cloudcp/portal/dist/portal_app.jsindex 5c3374ee36..6ba669ff30 100644--- a/internal/cloudcp/portal/dist/portal_app.js+++ b/internal/cloudcp/portal/dist/portal_app.js@@ -831,11 +831,8 @@return {openBillingPanelID: "",upgradeFeatureKey: "",- upgradeInstanceOrigin: "",- upgradePurchaseReturnToken: "",- upgradeActivationURLTemplate: "",- upgradeHandoff: createQueryState(null),- upgradeCheckoutStatus: "",+ upgradeCheckoutIntentID: "",+ upgradeCheckoutIntent: createQueryState(null),upgradePricing: createQueryState(null),upgradeCheckout: createMutationState(),flows: {@@ -1413,7 +1410,7 @@if (plans.length === 0) {return "";}- var checkoutDisabled = billingState.upgradeCheckout.pending || billingState.upgradeHandoff.status === "loading" || !String(billingState.upgradeActivationURLTemplate || "").trim();+ var checkoutDisabled = billingState.upgradeCheckout.pending || billingState.upgradeCheckoutIntent.status === "loading" || !String(billingState.upgradeCheckoutIntentID || "").trim() || billingState.upgradeCheckoutIntent.status !== "ready";return '<div class="billing-upgrade-plan-grid">' + plans.map(function(plan) {var buttons = Array.isArray(plan.buttons) ? plan.buttons : [];var checkoutButtons = buttons.filter(function(button) {@@ -1431,29 +1428,25 @@if (!root) return;var featureKey = String(billingState.upgradeFeatureKey || "").trim();var pricingState = billingState.upgradePricing;- var handoffState = billingState.upgradeHandoff;- var activationURLTemplate = String(billingState.upgradeActivationURLTemplate || "").trim();- var returnToken = String(billingState.upgradePurchaseReturnToken || "").trim();+ var checkoutIntentState = billingState.upgradeCheckoutIntent;+ var checkoutIntentID = String(billingState.upgradeCheckoutIntentID || "").trim();var explainer = pricingState.data && pricingState.data.explainer ? pricingState.data.explainer : "";var summaryItems = [];- if (billingState.upgradeCheckoutStatus === "cancelled") {- summaryItems.push('<div class="billing-status visible">Checkout was cancelled before completion.</div>');- }if (billingState.upgradeCheckout.pending) {summaryItems.push('<div class="billing-status visible">Redirecting to secure checkout...</div>');}if (billingState.upgradeCheckout.error) {summaryItems.push('<div class="billing-status visible error">' + escapeText(billingState.upgradeCheckout.error) + "</div>");}- if (!returnToken) {+ if (!checkoutIntentID) {summaryItems.push(- '<div class="billing-status visible error">Open this upgrade from Pulse Pro billing so Pulse Account can verify the return path before checkout.</div>'+ '<div class="billing-status visible error">Open this upgrade from Pulse Pro billing so Pulse Account can verify the secure checkout intent before checkout.</div>');- } else if (handoffState.status === "loading" && !activationURLTemplate) {- summaryItems.push('<div class="billing-status visible">Verifying the secure Pulse Pro return path...</div>');- } else if (handoffState.status === "error") {- summaryItems.push('<div class="billing-status visible error">' + escapeText(handoffState.error || "Failed to verify the secure Pulse Pro return path.") + "</div>");- } else if (handoffState.status === "ready" && activationURLTemplate) {+ } else if (checkoutIntentState.status === "loading") {+ summaryItems.push('<div class="billing-status visible">Verifying the secure Pulse Pro checkout intent...</div>');+ } else if (checkoutIntentState.status === "error") {+ summaryItems.push('<div class="billing-status visible error">' + escapeText(checkoutIntentState.error || "Failed to verify the secure Pulse Pro checkout intent.") + "</div>");+ } else if (checkoutIntentState.status === "ready") {summaryItems.push('<div class="billing-status visible success">Pulse Account will return completed checkout directly to Pulse Pro billing.</div>');}if (pricingState.status === "loading" && !pricingState.data) {@@ -1686,11 +1679,8 @@var nextState = createPortalBillingState();billingState.openBillingPanelID = nextState.openBillingPanelID;billingState.upgradeFeatureKey = nextState.upgradeFeatureKey;- billingState.upgradeInstanceOrigin = nextState.upgradeInstanceOrigin;- billingState.upgradePurchaseReturnToken = nextState.upgradePurchaseReturnToken;- billingState.upgradeActivationURLTemplate = nextState.upgradeActivationURLTemplate;- billingState.upgradeHandoff = nextState.upgradeHandoff;- billingState.upgradeCheckoutStatus = nextState.upgradeCheckoutStatus;+ billingState.upgradeCheckoutIntentID = nextState.upgradeCheckoutIntentID;+ billingState.upgradeCheckoutIntent = nextState.upgradeCheckoutIntent;billingState.upgradePricing = nextState.upgradePricing;billingState.upgradeCheckout = nextState.upgradeCheckout;billingState.flows = nextState.flows;@@ -1757,29 +1747,6 @@setValue(flow.codeInputID, "");}}- function currentPortalBaseURL() {- try {- var locationURL = new URL(window.location.href);- var portalPath = String(store.getBootstrap().portal_path || "/portal").trim() || "/portal";- var portalURL = new URL(portalPath, locationURL.origin);- return portalURL.toString();- } catch {- return String(store.getBootstrap().portal_path || "/portal");- }- }- function buildUpgradeCheckoutCancelURL() {- var url = new URL(currentPortalBaseURL());- var billingState = getBillingState();- if (billingState.flows.manage.emailValue) {- url.searchParams.set("email", billingState.flows.manage.emailValue);- }- if (billingState.upgradePurchaseReturnToken) {- url.searchParams.set("purchase_return_token", billingState.upgradePurchaseReturnToken);- }- url.searchParams.set("service", "upgrade");- url.searchParams.set("checkout", "cancelled");- return url.toString();- }async function loadUpgradePricing(force) {var billingState = getBillingState();if (!force && (billingState.upgradePricing.status === "loading" || billingState.upgradePricing.status === "ready")) {@@ -1803,87 +1770,61 @@});}}- async function resolveUpgradeHandoff(force) {+ async function resolveUpgradeCheckoutIntent(force) {var billingState = getBillingState();- var returnToken = billingState.upgradePurchaseReturnToken;- if (!returnToken) return;- if (!force && (billingState.upgradeHandoff.status === "loading" || billingState.upgradeHandoff.status === "ready")) {- return;- }- if (!billingState.upgradeInstanceOrigin) {- updateBillingState(function(nextBillingState) {- failQueryState(- nextBillingState.upgradeHandoff,- null,- "Reopen this upgrade from Pulse Pro billing so Pulse Account can verify the return path."- );- nextBillingState.upgradeActivationURLTemplate = "";- });+ var checkoutIntentID = String(billingState.upgradeCheckoutIntentID || "").trim();+ if (!checkoutIntentID) return;+ if (!force && (billingState.upgradeCheckoutIntent.status === "loading" || billingState.upgradeCheckoutIntent.status === "ready")) {return;}updateBillingState(function(nextBillingState) {- beginQueryState(nextBillingState.upgradeHandoff, null);+ beginQueryState(nextBillingState.upgradeCheckoutIntent, null);});try {- var handoffURL = new URL("/auth/license-purchase-handoff", billingState.upgradeInstanceOrigin);- handoffURL.searchParams.set("purchase_return_token", returnToken);- var response = await fetch(handoffURL.toString(), {- headers: { Accept: "application/json" }- });- if (!response.ok) {- var errorText = "";- try {- errorText = (await response.text()).trim();- } catch {- errorText = "";- }- throw new Error(errorText || "Failed to verify the Pulse Pro upgrade return path.");+ var result = await api.getCommercialJSON(+ "/v1/checkout/intent?checkout_intent_id=" + encodeURIComponent(checkoutIntentID)+ );+ var resolvedCheckoutIntentID = String(result.checkout_intent_id || "").trim();+ if (!resolvedCheckoutIntentID) {+ throw new Error("Pulse Account could not verify the secure Pulse Pro checkout intent.");}- var result = await response.json();var resolvedFeature = String(result.feature || "").trim();- var activationURLTemplate = String(result.activation_url_template || "").trim();- if (!activationURLTemplate) {- throw new Error("Pulse Account could not verify the Pulse Pro checkout return path.");- }updateBillingState(function(nextBillingState) {- resolveQueryState(nextBillingState.upgradeHandoff, result);+ resolveQueryState(nextBillingState.upgradeCheckoutIntent, result);+ nextBillingState.upgradeCheckoutIntentID = resolvedCheckoutIntentID;nextBillingState.upgradeFeatureKey = resolvedFeature;- nextBillingState.upgradeActivationURLTemplate = activationURLTemplate;});} catch (err) {updateBillingState(function(nextBillingState) {failQueryState(- nextBillingState.upgradeHandoff,+ nextBillingState.upgradeCheckoutIntent,null,- err instanceof Error ? err.message : "Failed to verify the Pulse Pro upgrade return path."+ err instanceof Error ? err.message : "Failed to verify the secure Pulse Pro checkout intent.");- nextBillingState.upgradeActivationURLTemplate = "";});}}async function startUpgradeCheckout(planKey, tier, billingCycle) {if (!planKey || !tier || !billingCycle) return;- var activationURLTemplate = String(getBillingState().upgradeActivationURLTemplate || "").trim();- if (!activationURLTemplate) {+ var checkoutIntentID = String(getBillingState().upgradeCheckoutIntentID || "").trim();+ if (!checkoutIntentID) {updateBillingState(function(nextBillingState) {failMutationState(nextBillingState.upgradeCheckout,- "Pulse Account could not verify the secure return path. Reopen the upgrade flow from Pulse Pro billing."+ "Pulse Account could not verify the secure checkout intent. Reopen the upgrade flow from Pulse Pro billing.");});return;}updateBillingState(function(nextBillingState) {beginMutationState(nextBillingState.upgradeCheckout);- nextBillingState.upgradeCheckoutStatus = "";});try {var data = await api.postCommercialJSON("/v1/checkout/session", {plan_key: planKey,tier,billing_cycle: billingCycle,- success_url: activationURLTemplate,- cancel_url: buildUpgradeCheckoutCancelURL()+ checkout_intent_id: checkoutIntentID});if (!data || !data.url) {throw new Error("Checkout URL was not returned.");@@ -2181,9 +2122,9 @@}function renderBillingRuntime() {var billingState = getBillingState();- if (billingState.openBillingPanelID === "upgrade-billing-panel" || !!billingState.upgradeFeatureKey || !!billingState.upgradePurchaseReturnToken) {+ if (billingState.openBillingPanelID === "upgrade-billing-panel" || !!billingState.upgradeFeatureKey || !!billingState.upgradeCheckoutIntentID) {void loadUpgradePricing(false);- void resolveUpgradeHandoff(false);+ void resolveUpgradeCheckoutIntent(false);}renderOpenBillingPanels(getBillingState().openBillingPanelID);renderAllFlows();@@ -2667,7 +2608,7 @@var accounts = Array.isArray(context.bootstrap.accounts) ? context.bootstrap.accounts : [];var hosted = hasHostedAccounts(accounts);var showSelfHostedCommercial = hasSelfHostedCommercial(context.bootstrap);- var showSelfHostedUpgradeHandoff = !!normalizeUpgradeFeatureKey(context.billingState.upgradeFeatureKey);+ var showSelfHostedUpgradeHandoff = context.billingState.openBillingPanelID === "upgrade-billing-panel" || !!normalizeUpgradeFeatureKey(context.billingState.upgradeFeatureKey) || !!String(context.billingState.upgradeCheckoutIntentID || "").trim();var showSelfHostedBillingShell = showSelfHostedCommercial || showSelfHostedUpgradeHandoff;var shellSections = visibleShellSections(context.bootstrap);var preferredSection = context.activeSection || preferredPortalShellSection(context.bootstrap);@@ -2962,14 +2903,10 @@function normalizeHandoffEmail(value) {return String(value || "").trim();}- function normalizeHandoffInstanceOrigin(value) {+ function normalizeUpgradeCheckoutIntentID(value) {var trimmed = String(value || "").trim();if (!trimmed) return "";- try {- return new URL(trimmed).origin;- } catch {- return "";- }+ return /^[A-Za-z0-9_-]+$/.test(trimmed) ? trimmed : "";}function normalizeHandoffBillingPanel(value) {switch (String(value || "").trim()) {@@ -2990,38 +2927,21 @@function normalizeUpgradeFeatureKey2(value) {return String(value || "").trim();}- function normalizeUpgradePurchaseReturnToken(value) {- return String(value || "").trim();- }- function normalizeUpgradeCheckoutStatus(value) {- switch (String(value || "").trim()) {- case "success":- return "success";- case "cancelled":- return "cancelled";- default:- return "";- }- }- function readPortalRuntimeHandoff(locationHref = window.location.href, referrerHref = typeof document !== "undefined" ? document.referrer : "") {+ function readPortalRuntimeHandoff(locationHref = window.location.href) {try {var params = new URL(locationHref).searchParams;return {email: normalizeHandoffEmail(params.get("email")),openBillingPanelID: normalizeHandoffBillingPanel(params.get("service")),- upgradeInstanceOrigin: normalizeHandoffInstanceOrigin(referrerHref),- upgradeFeatureKey: normalizeUpgradeFeatureKey2(params.get("purchase_return_token") ? "" : params.get("feature")),- upgradePurchaseReturnToken: normalizeUpgradePurchaseReturnToken(params.get("purchase_return_token")),- upgradeCheckoutStatus: normalizeUpgradeCheckoutStatus(params.get("checkout"))+ upgradeCheckoutIntentID: normalizeUpgradeCheckoutIntentID(params.get("checkout_intent_id")),+ upgradeFeatureKey: normalizeUpgradeFeatureKey2(params.get("feature"))};} catch {return {email: "",openBillingPanelID: "",- upgradeInstanceOrigin: "",- upgradeFeatureKey: "",- upgradePurchaseReturnToken: "",- upgradeCheckoutStatus: ""+ upgradeCheckoutIntentID: "",+ upgradeFeatureKey: ""};}}@@ -3060,20 +2980,14 @@store.setActiveShellSection("billing");store.updateBillingState(function(billingState) {billingState.openBillingPanelID = handoff.openBillingPanelID;- billingState.upgradeInstanceOrigin = handoff.upgradeInstanceOrigin;+ billingState.upgradeCheckoutIntentID = handoff.upgradeCheckoutIntentID;billingState.upgradeFeatureKey = handoff.upgradeFeatureKey;- billingState.upgradePurchaseReturnToken = handoff.upgradePurchaseReturnToken;- billingState.upgradeActivationURLTemplate = "";- billingState.upgradeCheckoutStatus = handoff.upgradeCheckoutStatus;}, { notify: false });- } else if (handoff.upgradeFeatureKey || handoff.upgradePurchaseReturnToken) {+ } else if (handoff.upgradeFeatureKey || handoff.upgradeCheckoutIntentID) {store.setActiveShellSection("billing");store.updateBillingState(function(billingState) {- billingState.upgradeInstanceOrigin = handoff.upgradeInstanceOrigin;+ billingState.upgradeCheckoutIntentID = handoff.upgradeCheckoutIntentID;billingState.upgradeFeatureKey = handoff.upgradeFeatureKey;- billingState.upgradePurchaseReturnToken = handoff.upgradePurchaseReturnToken;- billingState.upgradeActivationURLTemplate = "";- billingState.upgradeCheckoutStatus = handoff.upgradeCheckoutStatus;}, { notify: false });}return {diff --git a/internal/cloudcp/portal/frontend/src/app.test.ts b/internal/cloudcp/portal/frontend/src/app.test.tsindex 60d8594a2c..69ef20306f 100644--- a/internal/cloudcp/portal/frontend/src/app.test.ts+++ b/internal/cloudcp/portal/frontend/src/app.test.ts@@ -150,9 +150,8 @@ describe('portal app', function() {{email: '[email protected]',openBillingPanelID: 'retrieve-billing-panel',- upgradeHandoffURL: '',+ upgradeCheckoutIntentID: '',upgradeFeatureKey: '',- upgradeCheckoutStatus: '',});diff --git a/internal/cloudcp/portal/frontend/src/billing.ts b/internal/cloudcp/portal/frontend/src/billing.tsindex 641895d0ba..228c063e8c 100644--- a/internal/cloudcp/portal/frontend/src/billing.ts+++ b/internal/cloudcp/portal/frontend/src/billing.ts@@ -41,7 +41,7 @@ import type {PortalBillingFlowID,PortalBillingState,PortalCheckoutSessionCreateResponse,- PortalUpgradeHandoffModel,+ PortalUpgradeCheckoutIntentModel,PortalUpgradePricingModel,VerificationFlowState,} from './types';@@ -88,10 +88,8 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {var nextState = createPortalBillingState();billingState.openBillingPanelID = nextState.openBillingPanelID;billingState.upgradeFeatureKey = nextState.upgradeFeatureKey;- billingState.upgradeHandoffURL = nextState.upgradeHandoffURL;- billingState.upgradeActivationURLTemplate = nextState.upgradeActivationURLTemplate;- billingState.upgradeHandoff = nextState.upgradeHandoff;- billingState.upgradeCheckoutStatus = nextState.upgradeCheckoutStatus;+ billingState.upgradeCheckoutIntentID = nextState.upgradeCheckoutIntentID;+ billingState.upgradeCheckoutIntent = nextState.upgradeCheckoutIntent;billingState.upgradePricing = nextState.upgradePricing;billingState.upgradeCheckout = nextState.upgradeCheckout;billingState.flows = nextState.flows;@@ -168,31 +166,6 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {}}- function currentPortalBaseURL(): string {- try {- var locationURL = new URL(window.location.href);- var portalPath = String(store.getBootstrap().portal_path || '/portal').trim() || '/portal';- var portalURL = new URL(portalPath, locationURL.origin);- return portalURL.toString();- } catch {- return String(store.getBootstrap().portal_path || '/portal');- }- }-- function buildUpgradeCheckoutCancelURL(): string {- var url = new URL(currentPortalBaseURL());- var billingState = getBillingState();- if (billingState.flows.manage.emailValue) {- url.searchParams.set('email', billingState.flows.manage.emailValue);- }- if (billingState.upgradeHandoffURL) {- url.searchParams.set('purchase_handoff_url', billingState.upgradeHandoffURL);- }- url.searchParams.set('service', 'upgrade');- url.searchParams.set('checkout', 'cancelled');- return url.toString();- }-async function loadUpgradePricing(force: boolean) {var billingState = getBillingState();if (!force && (billingState.upgradePricing.status === 'loading' || billingState.upgradePricing.status === 'ready')) {@@ -217,75 +190,62 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {}}- async function resolveUpgradeHandoff(force: boolean) {+ async function resolveUpgradeCheckoutIntent(force: boolean) {var billingState = getBillingState();- var handoffURL = String(billingState.upgradeHandoffURL || '').trim();- if (!handoffURL) return;- if (!force && (billingState.upgradeHandoff.status === 'loading' || billingState.upgradeHandoff.status === 'ready')) {+ var checkoutIntentID = String(billingState.upgradeCheckoutIntentID || '').trim();+ if (!checkoutIntentID) return;+ if (!force && (billingState.upgradeCheckoutIntent.status === 'loading' || billingState.upgradeCheckoutIntent.status === 'ready')) {return;}updateBillingState(function(nextBillingState) {- beginQueryState(nextBillingState.upgradeHandoff, null);+ beginQueryState(nextBillingState.upgradeCheckoutIntent, null);});try {- var response = await fetch(handoffURL, {- headers: { Accept: 'application/json' },- });- if (!response.ok) {- var errorText = '';- try {- errorText = (await response.text()).trim();- } catch {- errorText = '';- }- throw new Error(errorText || 'Failed to verify the Pulse Pro upgrade return path.');+ var result = await api.getCommercialJSON<PortalUpgradeCheckoutIntentModel>(+ '/v1/checkout/intent?checkout_intent_id=' + encodeURIComponent(checkoutIntentID),+ );+ var resolvedCheckoutIntentID = String(result.checkout_intent_id || '').trim();+ if (!resolvedCheckoutIntentID) {+ throw new Error('Pulse Account could not verify the secure Pulse Pro checkout intent.');}- var result = await response.json() as PortalUpgradeHandoffModel;var resolvedFeature = String(result.feature || '').trim();- var activationURLTemplate = String(result.activation_url_template || '').trim();- if (!activationURLTemplate) {- throw new Error('Pulse Account could not verify the Pulse Pro checkout return path.');- }updateBillingState(function(nextBillingState) {- resolveQueryState(nextBillingState.upgradeHandoff, result);+ resolveQueryState(nextBillingState.upgradeCheckoutIntent, result);+ nextBillingState.upgradeCheckoutIntentID = resolvedCheckoutIntentID;nextBillingState.upgradeFeatureKey = resolvedFeature;- nextBillingState.upgradeActivationURLTemplate = activationURLTemplate;});} catch (err) {updateBillingState(function(nextBillingState) {failQueryState(- nextBillingState.upgradeHandoff,+ nextBillingState.upgradeCheckoutIntent,null,- err instanceof Error ? err.message : 'Failed to verify the Pulse Pro upgrade return path.',+ err instanceof Error ? err.message : 'Failed to verify the secure Pulse Pro checkout intent.',);- nextBillingState.upgradeActivationURLTemplate = '';});}}async function startUpgradeCheckout(planKey: string, tier: string, billingCycle: string) {if (!planKey || !tier || !billingCycle) return;- var activationURLTemplate = String(getBillingState().upgradeActivationURLTemplate || '').trim();- if (!activationURLTemplate) {+ var checkoutIntentID = String(getBillingState().upgradeCheckoutIntentID || '').trim();+ if (!checkoutIntentID) {updateBillingState(function(nextBillingState) {failMutationState(nextBillingState.upgradeCheckout,- 'Pulse Account could not verify the secure return path. Reopen the upgrade flow from Pulse Pro billing.',+ 'Pulse Account could not verify the secure checkout intent. Reopen the upgrade flow from Pulse Pro billing.',);});return;}updateBillingState(function(nextBillingState) {beginMutationState(nextBillingState.upgradeCheckout);- nextBillingState.upgradeCheckoutStatus = '';});try {var data = await api.postCommercialJSON<PortalCheckoutSessionCreateResponse>('/v1/checkout/session', {plan_key: planKey,tier: tier,billing_cycle: billingCycle,- success_url: activationURLTemplate,- cancel_url: buildUpgradeCheckoutCancelURL(),+ checkout_intent_id: checkoutIntentID,});if (!data || !data.url) {throw new Error('Checkout URL was not returned.');@@ -592,10 +552,10 @@ export function installBillingRuntime(deps: BillingRuntimeDeps): void {if (billingState.openBillingPanelID === 'upgrade-billing-panel' ||!!billingState.upgradeFeatureKey ||- !!billingState.upgradeHandoffURL+ !!billingState.upgradeCheckoutIntentID) {void loadUpgradePricing(false);- void resolveUpgradeHandoff(false);+ void resolveUpgradeCheckoutIntent(false);}renderOpenBillingPanels(getBillingState().openBillingPanelID);renderAllFlows();diff --git a/internal/cloudcp/portal/frontend/src/billing_view.test.ts b/internal/cloudcp/portal/frontend/src/billing_view.test.tsindex 0c6d504bca..2ef45ca156 100644--- a/internal/cloudcp/portal/frontend/src/billing_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/billing_view.test.ts@@ -228,13 +228,11 @@ describe('services view', function() {var billingState = createPortalBillingState();billingState.upgradeFeatureKey = 'max_monitored_systems';- billingState.upgradeHandoffURL =- 'https://pulse.example.com/auth/license-purchase-handoff?purchase_handoff_id=pch1_signed';- billingState.upgradeActivationURLTemplate = 'https://pulse.example.com/auth/license-purchase-activate?purchase_return_token=prt_signed&session_id={CHECKOUT_SESSION_ID}';- billingState.upgradeHandoff.status = 'ready';- billingState.upgradeHandoff.data = {+ billingState.upgradeCheckoutIntentID = 'cki_signed';+ billingState.upgradeCheckoutIntent.status = 'ready';+ billingState.upgradeCheckoutIntent.data = {+ checkout_intent_id: 'cki_signed',feature: 'max_monitored_systems',- activation_url_template: billingState.upgradeActivationURLTemplate,};billingState.upgradePricing.status = 'ready';billingState.upgradePricing.data = {@@ -280,10 +278,9 @@ describe('services view', function() {document.body.innerHTML = '<div id="upgrade-billing-root"></div>';var billingState = createPortalBillingState();- billingState.upgradeHandoffURL =- 'https://pulse.example.com/auth/license-purchase-handoff?purchase_handoff_id=pch1_signed';- billingState.upgradeHandoff.status = 'error';- billingState.upgradeHandoff.error = 'Pulse Account could not verify the secure return path.';+ billingState.upgradeCheckoutIntentID = 'cki_signed';+ billingState.upgradeCheckoutIntent.status = 'error';+ billingState.upgradeCheckoutIntent.error = 'Pulse Account could not verify the secure checkout intent.';billingState.upgradePricing.status = 'ready';billingState.upgradePricing.data = {title: 'Pricing',@@ -313,7 +310,7 @@ describe('services view', function() {renderUpgradePanel(billingState, createBootstrap());expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain(- 'Pulse Account could not verify the secure return path.',+ 'Pulse Account could not verify the secure checkout intent.',);expect((document.querySelector('[data-account-billing-action="upgrade-start-checkout"]') as HTMLButtonElement).disabled,diff --git a/internal/cloudcp/portal/frontend/src/billing_view.ts b/internal/cloudcp/portal/frontend/src/billing_view.tsindex 0fc8b4b619..64dd621060 100644--- a/internal/cloudcp/portal/frontend/src/billing_view.ts+++ b/internal/cloudcp/portal/frontend/src/billing_view.ts@@ -89,8 +89,9 @@ function renderUpgradePlansHTML(billingState: PortalBillingState): string {}var checkoutDisabled = billingState.upgradeCheckout.pending ||- billingState.upgradeHandoff.status === 'loading' ||- !String(billingState.upgradeActivationURLTemplate || '').trim();+ billingState.upgradeCheckoutIntent.status === 'loading' ||+ !String(billingState.upgradeCheckoutIntentID || '').trim() ||+ billingState.upgradeCheckoutIntent.status !== 'ready';return '<div class="billing-upgrade-plan-grid">' + plans.map(function(plan) {var buttons = Array.isArray(plan.buttons) ? plan.buttons : [];@@ -139,30 +140,26 @@ export function renderUpgradePanel(billingState: PortalBillingState, _bootstrap:var featureKey = String(billingState.upgradeFeatureKey || '').trim();var pricingState = billingState.upgradePricing;- var handoffState = billingState.upgradeHandoff;- var activationURLTemplate = String(billingState.upgradeActivationURLTemplate || '').trim();- var handoffURL = String(billingState.upgradeHandoffURL || '').trim();+ var checkoutIntentState = billingState.upgradeCheckoutIntent;+ var checkoutIntentID = String(billingState.upgradeCheckoutIntentID || '').trim();var explainer = pricingState.data && pricingState.data.explainer ? pricingState.data.explainer : '';var summaryItems = [] as string[];- if (billingState.upgradeCheckoutStatus === 'cancelled') {- summaryItems.push('<div class="billing-status visible">Checkout was cancelled before completion.</div>');- }if (billingState.upgradeCheckout.pending) {summaryItems.push('<div class="billing-status visible">Redirecting to secure checkout...</div>');}if (billingState.upgradeCheckout.error) {summaryItems.push('<div class="billing-status visible error">' + escapeText(billingState.upgradeCheckout.error) + '</div>');}- if (!handoffURL) {+ if (!checkoutIntentID) {summaryItems.push(- '<div class="billing-status visible error">Open this upgrade from Pulse Pro billing so Pulse Account can verify the return path before checkout.</div>',+ '<div class="billing-status visible error">Open this upgrade from Pulse Pro billing so Pulse Account can verify the secure checkout intent before checkout.</div>',);- } else if (handoffState.status === 'loading' && !activationURLTemplate) {- summaryItems.push('<div class="billing-status visible">Verifying the secure Pulse Pro return path...</div>');- } else if (handoffState.status === 'error') {- summaryItems.push('<div class="billing-status visible error">' + escapeText(handoffState.error || 'Failed to verify the secure Pulse Pro return path.') + '</div>');- } else if (handoffState.status === 'ready' && activationURLTemplate) {+ } else if (checkoutIntentState.status === 'loading') {+ summaryItems.push('<div class="billing-status visible">Verifying the secure Pulse Pro checkout intent...</div>');+ } else if (checkoutIntentState.status === 'error') {+ summaryItems.push('<div class="billing-status visible error">' + escapeText(checkoutIntentState.error || 'Failed to verify the secure Pulse Pro checkout intent.') + '</div>');+ } else if (checkoutIntentState.status === 'ready') {summaryItems.push('<div class="billing-status visible success">Pulse Account will return completed checkout directly to Pulse Pro billing.</div>');}if (pricingState.status === 'loading' && !pricingState.data) {diff --git a/internal/cloudcp/portal/frontend/src/runtime.test.ts b/internal/cloudcp/portal/frontend/src/runtime.test.tsindex f2b2d005cc..4c83d43841 100644--- a/internal/cloudcp/portal/frontend/src/runtime.test.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.test.ts@@ -64,18 +64,13 @@ describe('portal runtime', function() {it('derives canonical email and billing handoff from the portal URL', function() {var handoff = readPortalRuntimeHandoff(- 'https://cloud.pulserelay.pro/portal?email=buyer%40example.com&service=upgrade&purchase_handoff_url=' +- encodeURIComponent('https://pulse.example.com/auth/license-purchase-handoff?purchase_handoff_id=pch1_signed') +- '&checkout=cancelled',+ 'https://cloud.pulserelay.pro/portal?email=buyer%40example.com&service=upgrade&checkout_intent_id=cki_signed',);expect(handoff.email).toBe('[email protected]');expect(handoff.openBillingPanelID).toBe('upgrade-billing-panel');- expect(handoff.upgradeHandoffURL).toBe(- 'https://pulse.example.com/auth/license-purchase-handoff?purchase_handoff_id=pch1_signed',- );+ expect(handoff.upgradeCheckoutIntentID).toBe('cki_signed');expect(handoff.upgradeFeatureKey).toBe('');- expect(handoff.upgradeCheckoutStatus).toBe('cancelled');});it('applies email and billing handoff to the initial portal store', function() {@@ -89,9 +84,8 @@ describe('portal runtime', function() {{email: '[email protected]',openBillingPanelID: 'refund-billing-panel',- upgradeHandoffURL: '',+ upgradeCheckoutIntentID: '',upgradeFeatureKey: '',- upgradeCheckoutStatus: '',});@@ -112,19 +106,14 @@ describe('portal runtime', function() {{email: '',openBillingPanelID: 'upgrade-billing-panel',- upgradeHandoffURL:- 'https://pulse.example.com/auth/license-purchase-handoff?purchase_handoff_id=pch1_signed',+ upgradeCheckoutIntentID: 'cki_signed',upgradeFeatureKey: '',- upgradeCheckoutStatus: 'cancelled',});expect(runtime.store.getShellState().activeSection).toBe('billing');expect(runtime.store.getBillingState().openBillingPanelID).toBe('upgrade-billing-panel');- expect(runtime.store.getBillingState().upgradeHandoffURL).toBe(- 'https://pulse.example.com/auth/license-purchase-handoff?purchase_handoff_id=pch1_signed',- );+ expect(runtime.store.getBillingState().upgradeCheckoutIntentID).toBe('cki_signed');expect(runtime.store.getBillingState().upgradeFeatureKey).toBe('');- expect(runtime.store.getBillingState().upgradeCheckoutStatus).toBe('cancelled');});});diff --git a/internal/cloudcp/portal/frontend/src/runtime.ts b/internal/cloudcp/portal/frontend/src/runtime.tsindex 4241550c62..95e9089850 100644--- a/internal/cloudcp/portal/frontend/src/runtime.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.ts@@ -5,9 +5,8 @@ import type { PortalBootstrapData } from './types';export interface PortalRuntimeHandoff {email: string;openBillingPanelID: string;- upgradeHandoffURL: string;+ upgradeCheckoutIntentID: string;upgradeFeatureKey: string;- upgradeCheckoutStatus: '' | 'success' | 'cancelled';}export interface PortalRuntime {@@ -33,20 +32,12 @@ function normalizeHandoffEmail(value: string | null): string {return String(value || '').trim();}-function normalizeUpgradeHandoffURL(+function normalizeUpgradeCheckoutIntentID(value: string | null | undefined,): string {var trimmed = String(value || '').trim();if (!trimmed) return '';- try {- var parsed = new URL(trimmed);- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {- return '';- }- return parsed.toString();- } catch {- return '';- }+ return /^[A-Za-z0-9_-]+$/.test(trimmed) ? trimmed : '';}function normalizeHandoffBillingPanel(value: string | null): string {@@ -70,17 +61,6 @@ function normalizeUpgradeFeatureKey(value: string | null): string {return String(value || '').trim();}-function normalizeUpgradeCheckoutStatus(value: string | null): '' | 'success' | 'cancelled' {- switch (String(value || '').trim()) {- case 'success':- return 'success';- case 'cancelled':- return 'cancelled';- default:- return '';- }-}-export function readPortalRuntimeHandoff(locationHref: string | undefined = window.location.href,): PortalRuntimeHandoff {@@ -89,17 +69,15 @@ export function readPortalRuntimeHandoff(return {email: normalizeHandoffEmail(params.get('email')),openBillingPanelID: normalizeHandoffBillingPanel(params.get('service')),- upgradeHandoffURL: normalizeUpgradeHandoffURL(params.get('purchase_handoff_url')),+ upgradeCheckoutIntentID: normalizeUpgradeCheckoutIntentID(params.get('checkout_intent_id')),upgradeFeatureKey: normalizeUpgradeFeatureKey(params.get('feature')),- upgradeCheckoutStatus: normalizeUpgradeCheckoutStatus(params.get('checkout')),};} catch {return {email: '',openBillingPanelID: '',- upgradeHandoffURL: '',+ upgradeCheckoutIntentID: '',upgradeFeatureKey: '',- upgradeCheckoutStatus: '',};}}@@ -147,18 +125,14 @@ export function createPortalRuntime(store.setActiveShellSection('billing');store.updateBillingState(function(billingState) {billingState.openBillingPanelID = handoff.openBillingPanelID;- billingState.upgradeHandoffURL = handoff.upgradeHandoffURL;+ billingState.upgradeCheckoutIntentID = handoff.upgradeCheckoutIntentID;billingState.upgradeFeatureKey = handoff.upgradeFeatureKey;- billingState.upgradeActivationURLTemplate = '';- billingState.upgradeCheckoutStatus = handoff.upgradeCheckoutStatus;}, { notify: false });- } else if (handoff.upgradeFeatureKey || handoff.upgradeHandoffURL) {+ } else if (handoff.upgradeFeatureKey || handoff.upgradeCheckoutIntentID) {store.setActiveShellSection('billing');store.updateBillingState(function(billingState) {- billingState.upgradeHandoffURL = handoff.upgradeHandoffURL;+ billingState.upgradeCheckoutIntentID = handoff.upgradeCheckoutIntentID;billingState.upgradeFeatureKey = handoff.upgradeFeatureKey;- billingState.upgradeActivationURLTemplate = '';- billingState.upgradeCheckoutStatus = handoff.upgradeCheckoutStatus;}, { notify: false });}return {diff --git a/internal/cloudcp/portal/frontend/src/shell_view.ts b/internal/cloudcp/portal/frontend/src/shell_view.tsindex 71c4f0eb1c..a78bfacf5b 100644--- a/internal/cloudcp/portal/frontend/src/shell_view.ts+++ b/internal/cloudcp/portal/frontend/src/shell_view.ts@@ -1236,7 +1236,7 @@ export function renderAuthenticatedPortalHTML(context: ShellViewContext): stringvar showSelfHostedUpgradeHandoff =context.billingState.openBillingPanelID === 'upgrade-billing-panel' ||!!normalizeUpgradeFeatureKey(context.billingState.upgradeFeatureKey) ||- !!String(context.billingState.upgradeHandoffURL || '').trim();+ !!String(context.billingState.upgradeCheckoutIntentID || '').trim();var showSelfHostedBillingShell = showSelfHostedCommercial || showSelfHostedUpgradeHandoff;var shellSections = visibleShellSections(context.bootstrap);var preferredSection = context.activeSection || preferredPortalShellSection(context.bootstrap);diff --git a/internal/cloudcp/portal/frontend/src/state.test.ts b/internal/cloudcp/portal/frontend/src/state.test.tsindex a76e531260..330a9be706 100644--- a/internal/cloudcp/portal/frontend/src/state.test.ts+++ b/internal/cloudcp/portal/frontend/src/state.test.ts@@ -35,10 +35,8 @@ describe('portal state', function() {expect(billingState.flows.manage.confirm.pending).toBe(false);expect(billingState.refund.submit.pending).toBe(false);expect(billingState.upgradeFeatureKey).toBe('');- expect(billingState.upgradeHandoffURL).toBe('');- expect(billingState.upgradeActivationURLTemplate).toBe('');- expect(billingState.upgradeHandoff.status).toBe('idle');- expect(billingState.upgradeCheckoutStatus).toBe('');+ expect(billingState.upgradeCheckoutIntentID).toBe('');+ expect(billingState.upgradeCheckoutIntent.status).toBe('idle');expect(billingState.upgradePricing.status).toBe('idle');billingState.flows.manage.emailValue = '[email protected]';diff --git a/internal/cloudcp/portal/frontend/src/state.ts b/internal/cloudcp/portal/frontend/src/state.tsindex 6d0e41ea83..2294f21613 100644--- a/internal/cloudcp/portal/frontend/src/state.ts+++ b/internal/cloudcp/portal/frontend/src/state.ts@@ -118,10 +118,8 @@ export function createPortalBillingState(): PortalBillingState {return {openBillingPanelID: '',upgradeFeatureKey: '',- upgradeHandoffURL: '',- upgradeActivationURLTemplate: '',- upgradeHandoff: createQueryState(null),- upgradeCheckoutStatus: '',+ upgradeCheckoutIntentID: '',+ upgradeCheckoutIntent: createQueryState(null),upgradePricing: createQueryState(null),upgradeCheckout: createMutationState(),flows: {diff --git a/internal/cloudcp/portal/frontend/src/types.ts b/internal/cloudcp/portal/frontend/src/types.tsindex fcf17e909b..eeb088aadf 100644--- a/internal/cloudcp/portal/frontend/src/types.ts+++ b/internal/cloudcp/portal/frontend/src/types.ts@@ -79,13 +79,11 @@ export interface PortalUpgradePricingModel {plans: PortalUpgradePricingPlan[];}-export interface PortalUpgradeHandoffModel {+export interface PortalUpgradeCheckoutIntentModel {+ checkout_intent_id: string;feature?: string;- activation_url_template?: string;}-export type PortalUpgradeCheckoutStatus = '' | 'success' | 'cancelled';-export interface PortalCheckoutSessionCreateResponse {url?: string;plan_key?: string;@@ -165,10 +163,8 @@ export interface RefundState {export interface PortalBillingState {openBillingPanelID: string;upgradeFeatureKey: string;- upgradeHandoffURL: string;- upgradeActivationURLTemplate: string;- upgradeHandoff: PortalQueryState<PortalUpgradeHandoffModel | null>;- upgradeCheckoutStatus: PortalUpgradeCheckoutStatus;+ upgradeCheckoutIntentID: string;+ upgradeCheckoutIntent: PortalQueryState<PortalUpgradeCheckoutIntentModel | null>;upgradePricing: PortalQueryState<PortalUpgradePricingModel | null>;upgradeCheckout: PortalMutationState;flows: Record<PortalBillingFlowID, VerificationFlowState>;diff --git a/pkg/licensing/license_server_client.go b/pkg/licensing/license_server_client.goindex 8b62bef5a4..29aa8e71be 100644--- a/pkg/licensing/license_server_client.go+++ b/pkg/licensing/license_server_client.go@@ -36,6 +36,22 @@ type CheckoutSessionResult struct {PlanKey string `json:"plan_key,omitempty"`}+// CheckoutIntentRequest is the canonical server-owned request for a hosted+// self-hosted checkout handoff.+type CheckoutIntentRequest struct {+ Feature string `json:"feature,omitempty"`+ SuccessURL string `json:"success_url"`+ CancelURL string `json:"cancel_url"`+}++// CheckoutIntentResponse is the canonical opaque checkout handoff returned by+// the license server.+type CheckoutIntentResponse struct {+ CheckoutIntentID string `json:"checkout_intent_id"`+ Feature string `json:"feature,omitempty"`+ ExpiresAt int64 `json:"expires_at,omitempty"`+}+// NewLicenseServerClient creates a client for the license server.// The base URL defaults to DefaultLicenseServerURL. The PULSE_LICENSE_SERVER_URL// env var override is only allowed in non-release builds.@@ -192,6 +208,38 @@ func (c *LicenseServerClient) GetCheckoutSessionResult(ctx context.Context, sessreturn &result, nil}+// CreateCheckoutIntent stores a server-owned self-hosted checkout handoff and+// returns an opaque checkout_intent_id for Pulse Account browser flows.+func (c *LicenseServerClient) CreateCheckoutIntent(ctx context.Context, req CheckoutIntentRequest) (*CheckoutIntentResponse, error) {+ body, err := json.Marshal(req)+ if err != nil {+ return nil, fmt.Errorf("marshal checkout intent request: %w", err)+ }++ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/v1/checkout/intent", bytes.NewReader(body))+ if err != nil {+ return nil, fmt.Errorf("create checkout intent request: %w", err)+ }+ httpReq.Header.Set("Content-Type", "application/json")+ httpReq.Header.Set("Accept", "application/json")++ resp, err := c.httpClient.Do(httpReq)+ if err != nil {+ return nil, fmt.Errorf("checkout intent request failed: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {+ return nil, c.parseError(resp)+ }++ var result CheckoutIntentResponse+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil {+ return nil, fmt.Errorf("decode checkout intent response: %w", err)+ }+ return &result, nil+}+// BootstrapQuickstart exchanges a runtime identity for a short-lived// quickstart token and the current authoritative quickstart inventory.// Callers must pass a server-verified quickstart authority token asdiff --git a/pkg/licensing/license_server_client_test.go b/pkg/licensing/license_server_client_test.goindex 38e5e7c273..35a2d55592 100644--- a/pkg/licensing/license_server_client_test.go+++ b/pkg/licensing/license_server_client_test.go@@ -322,6 +322,61 @@ func TestClientGetCheckoutSessionResult(t *testing.T) {})}+func TestClientCreateCheckoutIntent(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Errorf("Method = %q, want POST", r.Method)+ }+ if r.URL.Path != "/v1/checkout/intent" {+ t.Errorf("Path = %q, want /v1/checkout/intent", r.URL.Path)+ }+ if r.Header.Get("Content-Type") != "application/json" {+ t.Errorf("Content-Type = %q, want application/json", r.Header.Get("Content-Type"))+ }+ if r.Header.Get("Accept") != "application/json" {+ t.Errorf("Accept = %q, want application/json", r.Header.Get("Accept"))+ }++ var req CheckoutIntentRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ t.Fatalf("decode request: %v", err)+ }+ if req.Feature != "max_monitored_systems" {+ t.Fatalf("Feature = %q, want max_monitored_systems", req.Feature)+ }+ if req.SuccessURL != "https://pulse.example.com/auth/license-purchase-activate?purchase_return_token=prt_signed&session_id={CHECKOUT_SESSION_ID}" {+ t.Fatalf("SuccessURL = %q", req.SuccessURL)+ }+ if req.CancelURL != "https://pulse.example.com/settings/system/billing/plan?intent=max_monitored_systems&purchase=cancelled" {+ t.Fatalf("CancelURL = %q", req.CancelURL)+ }++ w.WriteHeader(http.StatusOK)+ _ = json.NewEncoder(w).Encode(CheckoutIntentResponse{+ CheckoutIntentID: "cki_test_123",+ Feature: "max_monitored_systems",+ ExpiresAt: 1_775_000_000,+ })+ }))+ defer server.Close()++ client := NewLicenseServerClient(server.URL)+ result, err := client.CreateCheckoutIntent(context.Background(), CheckoutIntentRequest{+ Feature: "max_monitored_systems",+ SuccessURL: "https://pulse.example.com/auth/license-purchase-activate?purchase_return_token=prt_signed&session_id={CHECKOUT_SESSION_ID}",+ CancelURL: "https://pulse.example.com/settings/system/billing/plan?intent=max_monitored_systems&purchase=cancelled",+ })+ if err != nil {+ t.Fatalf("CreateCheckoutIntent failed: %v", err)+ }+ if result.CheckoutIntentID != "cki_test_123" {+ t.Fatalf("CheckoutIntentID = %q, want cki_test_123", result.CheckoutIntentID)+ }+ if result.Feature != "max_monitored_systems" {+ t.Fatalf("Feature = %q, want max_monitored_systems", result.Feature)+ }+}+func TestClientRefreshGrant(t *testing.T) {t.Run("successful refresh", func(t *testing.T) {newGrantJWT := makeTestGrantJWT(t, &GrantClaims{diff --git a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts b/tests/integration/tests/55-self-hosted-upgrade-return.spec.tsindex 0dc1ad8adb..28f44a72c2 100644--- a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts+++ b/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts@@ -1,21 +1,29 @@-import { test, expect, type BrowserContext, type Page, type Route } from '@playwright/test';+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 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 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 PURCHASE_HANDOFF_URL =- `${DEV_SERVER_URL}/auth/license-purchase-handoff?purchase_handoff_id=pch1_checkout_return`;+const CHECKOUT_INTENT_ID = "cki_checkout_return";+const ACTIVATED_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems&purchase=activated`;+const FINAL_BILLING_URL = `${DEV_SERVER_URL}/settings/system/billing/plan?intent=max_monitored_systems`;+const PURCHASE_RETURN_TOKEN = "prt_signed_checkout_return";const MONITORED_SYSTEM_ENTITLEMENTS = {capabilities: [],- limits: [{ key: 'max_monitored_systems', limit: 5, current: 16, state: 'enforced' }],- subscription_state: 'expired',+ limits: [+ { key: "max_monitored_systems", limit: 5, current: 16, state: "enforced" },+ ],+ subscription_state: "expired",upgrade_reasons: [],- tier: 'free',+ tier: "free",trial_eligible: false,hosted_mode: false,legacy_connections: {@@ -29,15 +37,17 @@ const MONITORED_SYSTEM_ENTITLEMENTS = {const MONITORED_SYSTEM_RUNTIME_CAPABILITIES = {capabilities: [],- limits: [{ key: 'max_monitored_systems', limit: 5, current: 16, state: 'enforced' }],+ 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',+ subscription_state: "expired",upgrade_reasons: [],- tier: 'free',+ tier: "free",trial_eligible: false,legacy_connections: {proxmox_nodes: 0,@@ -51,26 +61,28 @@ const MONITORED_SYSTEM_COMMERCIAL_POSTURE = {const MONITORED_SYSTEM_LEDGER = {systems: [{- name: 'edge-cluster',- type: 'cluster',- status: 'warning',+ name: "edge-cluster",+ type: "cluster",+ status: "warning",status_explanation: {summary:- 'At least one included source has a warning state, so Pulse keeps this monitored system under review.',+ "At least one included source has a warning state, so Pulse keeps this monitored system under review.",reasons: [],},latest_included_signal: {- name: 'edge-cluster',- type: 'cluster',- source: 'kubernetes',- at: '2026-04-07T09:00:00Z',+ name: "edge-cluster",+ type: "cluster",+ source: "kubernetes",+ at: "2026-04-07T09:00:00Z",},- source: 'kubernetes',+ source: "kubernetes",explanation: {summary:- 'Counts as one monitored system because Pulse merged multiple top-level views into one canonical cluster.',+ "Counts as one monitored system because Pulse merged multiple top-level views into one canonical cluster.",reasons: [],- surfaces: [{ name: 'edge-cluster', type: 'cluster', source: 'kubernetes' }],+ surfaces: [+ { name: "edge-cluster", type: "cluster", source: "kubernetes" },+ ],},},],@@ -81,25 +93,25 @@ const MONITORED_SYSTEM_LEDGER = {function fulfillJSON(route: Route, payload: unknown, status = 200) {return route.fulfill({status,- contentType: 'application/json',+ contentType: "application/json",body: JSON.stringify(payload),});}function escapeAttribute(value: string): string {return value- .replaceAll('&', '&')- .replaceAll('"', '"')- .replaceAll('<', '<')- .replaceAll('>', '>');+ .replaceAll("&", "&")+ .replaceAll('"', """)+ .replaceAll("<", "<")+ .replaceAll(">", ">");}async function configureBillingFixtures(context: BrowserContext, page: Page) {await page.addInitScript(() => {- localStorage.setItem('pulse_whats_new_v2_shown', 'true');+ localStorage.setItem("pulse_whats_new_v2_shown", "true");});- await context.route('**/api/security/status', async (route) => {+ await context.route("**/api/security/status", async (route) => {await fulfillJSON(route, {hasAuthentication: true,hideLocalLogin: false,@@ -108,156 +120,183 @@ async function configureBillingFixtures(context: BrowserContext, page: Page) {});});- await context.route('**/api/state', async (route) => {+ await context.route("**/api/state", async (route) => {await fulfillJSON(route, { ok: true });});- await context.route('**/api/system/settings', async (route) => {+ await context.route("**/api/system/settings", async (route) => {await fulfillJSON(route, {- theme: 'system',+ theme: "system",fullWidthMode: false,});});- await context.route('**/api/license/runtime-capabilities', async (route) => {+ await context.route("**/api/license/runtime-capabilities", async (route) => {await fulfillJSON(route, MONITORED_SYSTEM_RUNTIME_CAPABILITIES);});- await context.route('**/api/license/commercial-posture', async (route) => {+ await context.route("**/api/license/commercial-posture", async (route) => {await fulfillJSON(route, MONITORED_SYSTEM_COMMERCIAL_POSTURE);});- await context.route('**/api/license/entitlements', async (route) => {+ await context.route("**/api/license/entitlements", async (route) => {await fulfillJSON(route, MONITORED_SYSTEM_ENTITLEMENTS);});- await context.route('**/api/license/monitored-system-ledger', async (route) => {- await fulfillJSON(route, MONITORED_SYSTEM_LEDGER);- });+ await context.route(+ "**/api/license/monitored-system-ledger",+ async (route) => {+ await fulfillJSON(route, MONITORED_SYSTEM_LEDGER);+ },+ );}async function openMonitoredSystemUpgradeArrival(page: Page) {await page.goto(`${DEV_SERVER_URL}/settings/system-general`, {- waitUntil: 'domcontentloaded',+ waitUntil: "domcontentloaded",});await expect(- page.getByRole('status').filter({ hasText: 'Monitored systems: 16/5' }),+ page.getByRole("status").filter({ hasText: "Monitored systems: 16/5" }),).toBeVisible();await page- .getByRole('status')- .filter({ hasText: 'Monitored systems: 16/5' })- .getByRole('link', { name: 'Upgrade to add more' })+ .getByRole("status")+ .filter({ hasText: "Monitored systems: 16/5" })+ .getByRole("link", { name: "Upgrade to add more" }).click();- await page.waitForURL('**/settings/system/billing/plan?intent=max_monitored_systems');- await expect(page.getByRole('tab', { name: 'Plan' })).toHaveAttribute('aria-selected', 'true');+ await page.waitForURL(+ "**/settings/system/billing/plan?intent=max_monitored_systems",+ );+ await expect(page.getByRole("tab", { name: "Plan" })).toHaveAttribute(+ "aria-selected",+ "true",+ );}-test.describe('Self-hosted upgrade return flow', () => {- test('returns from Pulse Account checkout into the owned billing plan route', async ({+test.describe("Self-hosted upgrade return flow", () => {+ test("returns from Pulse Account checkout into the owned billing plan route", async ({page,}, testInfo) => {- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only billing continuity');+ test.skip(+ testInfo.project.name.startsWith("mobile-"),+ "Desktop-only billing continuity",+ );const context = page.context();await configureBillingFixtures(context, page);- let purchaseStartURL = '';+ 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');+ expect(requestUrl.searchParams.get("feature")).toBe(+ "max_monitored_systems",+ );await route.fulfill({status: 303,headers: {- location:- `${PULSE_ACCOUNT_PORTAL_URL}?service=upgrade` +- `&purchase_handoff_url=${encodeURIComponent(PURCHASE_HANDOFF_URL)}`,+ location: `${PULSE_ACCOUNT_PORTAL_URL}?service=upgrade&checkout_intent_id=${CHECKOUT_INTENT_ID}`,},- body: '',+ body: "",});});await context.route(`${PULSE_ACCOUNT_PORTAL_URL}**`, async (route) => {const requestUrl = new URL(route.request().url());- expect(requestUrl.searchParams.get('service')).toBe('upgrade');- expect(requestUrl.searchParams.get('feature')).toBeNull();- expect(requestUrl.searchParams.get('return_url')).toBeNull();- expect(requestUrl.searchParams.get('purchase_handoff_url')).toBe(PURCHASE_HANDOFF_URL);+ expect(requestUrl.searchParams.get("service")).toBe("upgrade");+ expect(requestUrl.searchParams.get("feature")).toBeNull();+ expect(requestUrl.searchParams.get("return_url")).toBeNull();+ expect(requestUrl.searchParams.get("purchase_handoff_url")).toBeNull();+ expect(requestUrl.searchParams.get("checkout_intent_id")).toBe(+ CHECKOUT_INTENT_ID,+ );await route.fulfill({status: 200,- contentType: 'text/html',+ contentType: "text/html",body:- '<!doctype html><html><body>' +- '<h1>Pulse Account</h1>' +- '<p>Checkout complete. Returning to Pulse Pro.</p>' ++ "<!doctype html><html><body>" ++ "<h1>Pulse Account</h1>" ++ "<p>Checkout complete. Returning to Pulse Pro.</p>" +`<script>setTimeout(function(){window.location.replace(${JSON.stringify(`${PURCHASE_RETURN_URL}?session_id=cs_upgrade_return&purchase_return_token=${encodeURIComponent(PURCHASE_RETURN_TOKEN)}`,)});},150);</script>` +- '</body></html>',+ "</body></html>",});});await context.route(`${PURCHASE_RETURN_URL}**`, async (route) => {const request = route.request();- if (request.method() === 'GET') {+ if (request.method() === "GET") {const requestUrl = new URL(request.url());- expect(requestUrl.searchParams.get('session_id')).toBe('cs_upgrade_return');- expect(requestUrl.searchParams.get('purchase_return_token')).toBe(PURCHASE_RETURN_TOKEN);+ expect(requestUrl.searchParams.get("session_id")).toBe(+ "cs_upgrade_return",+ );+ expect(requestUrl.searchParams.get("purchase_return_token")).toBe(+ PURCHASE_RETURN_TOKEN,+ );await route.fulfill({status: 200,- contentType: 'text/html',+ contentType: "text/html",body:- '<!doctype html><html><body>' +- '<h1>Finalizing Pulse Pro upgrade</h1>' ++ "<!doctype html><html><body>" ++ "<h1>Finalizing Pulse Pro upgrade</h1>" +`<form id="purchase-activation-continue-form" method="POST" action="${escapeAttribute(PURCHASE_RETURN_URL)}">` +'<input type="hidden" name="session_id" value="cs_upgrade_return">' +`<input type="hidden" name="purchase_return_token" value="${escapeAttribute(PURCHASE_RETURN_TOKEN)}">` +- '</form>' ++ "</form>" +'<script>setTimeout(function(){document.getElementById("purchase-activation-continue-form")?.submit();},50);</script>' +- '</body></html>',+ "</body></html>",});return;}- expect(request.method()).toBe('POST');- const formData = new URLSearchParams(request.postData() || '');- expect(formData.get('session_id')).toBe('cs_upgrade_return');- expect(formData.get('purchase_return_token')).toBe(PURCHASE_RETURN_TOKEN);+ expect(request.method()).toBe("POST");+ const formData = new URLSearchParams(request.postData() || "");+ expect(formData.get("session_id")).toBe("cs_upgrade_return");+ expect(formData.get("purchase_return_token")).toBe(PURCHASE_RETURN_TOKEN);await route.fulfill({status: 200,- contentType: 'text/html',+ contentType: "text/html",body:- '<!doctype html><html><body>' +- '<h1>Pulse Pro activated</h1>' ++ "<!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>',+ "</body></html>",});});await openMonitoredSystemUpgradeArrival(page);- const comparePlansLink = page.getByRole('link', { name: 'Compare plans' });+ const comparePlansLink = page.getByRole("link", { name: "Compare plans" });await expect(comparePlansLink).toHaveAttribute(- 'href',+ "href",`${PURCHASE_START_PATH}?feature=max_monitored_systems`,);- await expect(comparePlansLink).toHaveAttribute('target', '_blank');+ await expect(comparePlansLink).toHaveAttribute("target", "_blank");await comparePlansLink.click();- await expect.poll(() => purchaseStartURL).toBe(- `${PURCHASE_START_URL}?feature=max_monitored_systems`,- );+ await expect+ .poll(() => purchaseStartURL)+ .toBe(`${PURCHASE_START_URL}?feature=max_monitored_systems`);await page.goto(- `${PULSE_ACCOUNT_PORTAL_URL}?service=upgrade&purchase_handoff_url=${encodeURIComponent(PURCHASE_HANDOFF_URL)}`,+ `${PULSE_ACCOUNT_PORTAL_URL}?service=upgrade&checkout_intent_id=${CHECKOUT_INTENT_ID}`,{- waitUntil: 'domcontentloaded',+ waitUntil: "domcontentloaded",},);- await expect(page.getByRole('heading', { name: 'Pulse Account' })).toBeVisible();- await expect(page.getByText('Checkout complete. Returning to Pulse Pro.')).toBeVisible();- await expect(page.getByRole('button', { name: 'Activate in Pulse Pro' })).toHaveCount(0);- await expect(page).toHaveURL(/\/settings\/system\/billing\/plan\?intent=max_monitored_systems$/);+ await expect(+ page.getByRole("heading", { name: "Pulse Account" }),+ ).toBeVisible();+ await expect(+ page.getByText("Checkout complete. Returning to Pulse Pro."),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Activate in Pulse Pro" }),+ ).toHaveCount(0);+ await expect(page).toHaveURL(FINAL_BILLING_URL);+ await expect(+ page.getByText("Pulse Pro activated", { exact: true }),+ ).toBeVisible();});});