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
Retire self-hosted trial activation callback
rcourtmancc26f59f019e
diff --git a/docs/UPGRADE_v6.md b/docs/UPGRADE_v6.mdindex d664222ef5..aa64b65b98 100644--- a/docs/UPGRADE_v6.md+++ b/docs/UPGRADE_v6.md@@ -128,12 +128,11 @@ monitoring stays available across Community, Relay, and Pro, while Relay andPro sell convenience, history, AI operations, and advanced administration.Relay raises history to 14 days, while Pro raises it to 90 days.-Self-hosted v6 does not expose a general in-app trial or hosted AI quickstart-path. If support deliberately issues a trial or hosted handoff for a specific-case, Pulse only reflects that lifecycle after the hosted control plane returns-a signed activation token to `/auth/trial-activate`; ordinary upgraded-self-hosted installs should use activation, recovery, or BYOK/local AI setup-instead.+Self-hosted v6 does not expose a general in-app trial, trial-return callback,+or hosted AI quickstart path. Ordinary upgraded self-hosted installs should use+activation, recovery, or BYOK/local AI setup instead; any exceptional+support-issued entitlement is reflected through hosted entitlement state rather+than a local in-app trial acquisition flow.#### v5 License Migrationdiff --git a/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md b/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.mdindex cdb7ecdaad..d6b489a065 100644--- a/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md+++ b/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md@@ -49,8 +49,9 @@ Companion drill:The self-hosted proof must keep the retired trial-start transport contract:`POST /api/license/trial/start` returns `404` on an ordinary self-hosted v6runtime and does not mutate entitlements. Ordinary self-hosted runtime- surfaces must still suppress trial prompts; signed support handoffs may return- through `/auth/trial-activate` only.+ surfaces must still suppress trial prompts, and the retired+ `/auth/trial-activate` callback must remain absent from the ordinary router+ and settings UI.The same proof slice must keep retired hosted-AI quickstart out of normal GAruntime paths: `/api/settings/ai` and `/api/ai/patrol/status` must not exposequickstart credit/status fields, missing AI config in hosted mode must notdiff --git a/docs/release-control/v6/internal/SOURCE_OF_TRUTH.md b/docs/release-control/v6/internal/SOURCE_OF_TRUTH.mdindex 14d4c94178..1c9a591adb 100644--- a/docs/release-control/v6/internal/SOURCE_OF_TRUTH.md+++ b/docs/release-control/v6/internal/SOURCE_OF_TRUTH.md@@ -421,9 +421,11 @@ Assertion design rules:3. Trial acquisition is retired from ordinary self-hosted v6 GA.`POST /api/license/trial/start` must not be registered as an in-app routeand must return `404` when probed on a normal self-hosted runtime. The local- runtime may redeem signed trial activations through `/auth/trial-activate`,- but it must not mint local trial state directly or prompt users into paid- trial entry from default self-hosted surfaces.+ runtime must also keep the retired `/auth/trial-activate` callback out of+ the ordinary router and settings UI. Hosted/cloud entitlement leases may+ refresh already-approved hosted state, but local self-hosted Pulse must not+ mint trial state directly or prompt users into paid trial entry from default+ self-hosted surfaces.4. Hosted AI quickstart is retired from ordinary v6 GA runtime paths.Self-hosted and hosted app settings must stay BYOK/local-provider first unlessan operator explicitly configures a provider. The runtime must not auto-grantdiff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex 219beef127..a4ef5e1ad3 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -4857,7 +4857,7 @@},{"id": "trial-authority-saas-controlled",- "summary": "Trial authority for v6 is SaaS-controlled; hosted signup initiates trial start and local runtime may only redeem signed trial activations.",+ "summary": "Trial acquisition for ordinary self-hosted v6 is retired: SaaS/cloud may own hosted trial/signup state, but the local runtime must not expose local trial start or the retired trial activation return path.","kind": "contract","decided_at": "2026-03-06","subsystem_ids": [diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 7424dfd2b3..a779a7c161 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -492,7 +492,7 @@ the manifest's support-floor row.1. New install or update continuity behavior hidden only inside broad monitoring ownership.2. Agent profile or fleet-control behavior implemented outside the canonical agent settings/profile surfaces.3. Installer or update flows that depend on branch-tip, dev-only, or non-release asset behavior for supported RC/stable paths.-4. Lifecycle setup, install, or fleet surfaces that invoke retired self-hosted trial acquisition; `POST /api/license/trial/start` must stay closed on the ordinary self-hosted router, and approved support/hosted activation belongs to signed `/auth/trial-activate` rather than lifecycle-local CTAs.+4. Lifecycle setup, install, or fleet surfaces that invoke retired self-hosted trial acquisition; `POST /api/license/trial/start` and the retired `/auth/trial-activate` callback must stay closed on the ordinary self-hosted router rather than reappearing as lifecycle-local CTAs or retry paths.## Completion Obligations@@ -1627,9 +1627,9 @@ That same shared `internal/api/` dependency also assumes ordinary self-hostedcommercial-trial acquisition is retired: lifecycle-adjacent setup, install, andfleet surfaces must not expose direct trial CTAs or depend on`POST /api/license/trial/start`, and the normal router must fail that path as-`404` without mutating entitlements. Approved support or hosted handoff remains-owned by signed `/auth/trial-activate` redemption, not by lifecycle-local retry-or backoff behavior.+`404` without mutating entitlements. The retired `/auth/trial-activate`+self-hosted callback must also stay absent from lifecycle retry and backoff+behavior.That same shared `internal/api/` dependency also assumes session-carried OIDCrefresh tokens stay fail-closed at rest: `session_store.go` may only persistor recover those tokens through encrypted-at-rest session payloads, and anydiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 0b01fd3892..320a131eab 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -672,12 +672,11 @@ the canonical monitored-system blocked payload.28. Keep local trial-start transport retired from self-hosted v6 GA runtimepaths. `POST /api/license/trial/start` must not be registered as an ordinaryin-app acquisition endpoint; browser API clients, route inventory, demo- mode, and feature gates must all treat it as absent. Signed hosted/support- handoffs may still return through `/auth/trial-activate`, but trial- acquisition must not start from the self-hosted app. Hosted self-serve- verification failures may render owned HTML, but they must preserve- originating Pulse context instead of collapsing into generic control-plane- failures.+ mode, and feature gates must all treat it as absent. The retired+ `/auth/trial-activate` self-hosted return path must also stay absent from+ the ordinary router and settings UI; signed hosted entitlement leases may+ refresh cached hosted/cloud entitlement state, but they must not create a+ local Pro trial acquisition callback.29. Keep `/api/security/dev/reset-first-run` transport-backed and genuinelyunauthenticated: when the dev reset route clears first-run auth it mustalso clear any env-backed auth state that feeds `/api/security/status`, sodiff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 1e18cce04c..477fdb3526 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -985,10 +985,12 @@ The self-hosted trial-start boundary is now retired for ordinary v6 GAruntimes. Local `POST /api/license/trial/start` must not be registered as anin-app acquisition route, and it must not return the oldhosted-signup or trial-rate-limit payloads from a normal self-hosted instance.-Signed activation handoffs may still return through-`/auth/trial-activate`, but the user must not be prompted into a paid trial-from the self-hosted app. Browser and shell coverage now guard that retired-boundary: `tests/integration/tests/07-trial-signup-return.spec.ts` and+The retired `/auth/trial-activate` return path must also stay out of the+ordinary self-hosted router and Pro settings UI. Hosted/cloud entitlement lease+refresh may still validate signed leases for already-approved hosted state, but+ordinary self-hosted Pulse must not create a local trial acquisition callback.+Browser and shell coverage now guard that retired boundary:+`tests/integration/tests/07-trial-signup-return.spec.ts` and`tests/integration/scripts/trial-signup-contract.sh` must expect `404` from theretired route and prove entitlements remain unchanged. The paid-prompt browserproof in `tests/integration/tests/58-self-hosted-trial-rate-limit-ui.spec.ts`@@ -1026,14 +1028,10 @@ than falling back to a form with missing Pulse initiation context.Hosted service/configuration failures during verification, hosted checkoutpreparation, or checkout-session creation must also render as owned"temporarily unavailable" outcome UX rather than inline form errors.-The self-hosted activation return notice on `/settings/system-pro` is part of-that same boundary: the `trial` query result is a one-shot handoff outcome and-must be consumed into owned UI state, then removed from the URL rather than-becoming sticky page state across refresh and sharing.-That same shared notice owner must also keep activation-result framing-customer-facing: replayed handoffs should confirm the current entitlement state-rather than reading like a fresh failure, while invalid and unavailable states-should direct the operator back to the secure trial handoff on this instance.+The old self-hosted trial activation return notice on `/settings/system-pro` is+retired with that callback: the `trial` query result must not produce owned+activation UI, a success banner, or retry copy in v6 GA. Purchase activation+continues through the Pulse Account return contract instead.That same hosted owner also applies after Stripe returns to`/trial-signup/complete`: customer-facing completion failures must stay insideowned trial UX rather than dropping raw control-plane error strings, and they@@ -1748,7 +1746,7 @@ verified that the 13 canonical Cloud/MSP v6 `price_*` IDs are present in thegoverned `pulse-pro` operational docs and license-server env template, and thateach ID resolves to an active live recurring Stripe price object.Activation service runtime, license-server transport, encrypted activation-persistence, and hosted trial activation now follow the same ratchet. Changes+persistence, and hosted entitlement lease signing now follow the same ratchet. Changesto `pkg/licensing/service.go`, `pkg/licensing/grant_refresh.go`,`pkg/licensing/revocation_poll.go`, `pkg/licensing/license_server_client.go`,`pkg/licensing/persistence.go`, `pkg/licensing/activation_store.go`, anddiff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex caf64def15..2a8a5a9229 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -288,6 +288,12 @@ non-shell installer/update scripts explicit inside the current self-hostedrelease-confidence lane instead of leaving them as implied behavior around thecore runtime.+The canonical v6 upgrade guide now follows the free-first self-hosted GA+posture for install and support guidance: it describes activation, recovery,+and BYOK/local AI setup, while explicitly keeping general in-app trials,+trial-return callbacks, and hosted AI quickstart acquisition out of the+ordinary upgrade path.+That same release-confidence lane now also owns the shipped Helm chart path,so release automation, packaged chart metadata, and chart-runtime smoke nolonger depend on unowned `deploy/helm/pulse/` files while the governeddiff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 5d78e057e2..f99ccf1d0e 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -164,6 +164,10 @@ regression protection.process version once, but they must not add per-request release lookups,filesystem walks, or other heavy work just to compute whether an attachedagent is current.+ Retiring self-hosted trial acquisition follows that same rule: removing+ `/auth/trial-activate` and `POST /api/license/trial/start` from public-path+ and CSRF inventories must stay as constant-time route-table absence rather+ than replacing the old callback with persistence-backed router probes.5. Extend dashboard hot-path filter, sort, grouping, and stats math through `frontend-modern/src/components/Dashboard/workloadSelectors.ts`, and extend workload identity, discovery routing, and node-topology helpers through `frontend-modern/src/components/Dashboard/workloadTopology.ts`, rather than duplicating selector or topology logic in `frontend-modern/src/components/Dashboard/Dashboard.tsx`Dashboard landing-page estate orientation is part of that same hot-pathdiscipline. First-viewport system count, health, source coverage, anddiff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 7398ae2ace..97c523718a 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -2280,7 +2280,7 @@},{"id": "hosted-trial-activation",- "label": "hosted trial activation proof",+ "label": "hosted entitlement lease signing proof","match_prefixes": [],"match_files": ["pkg/licensing/trial_activation.go",diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 5f264b0122..04a891428a 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -499,7 +499,7 @@ querying, and the operator-facing storage health presentation layer.17. Letting recovery-event focus leak as hidden state on the protected inventory surface; switching back to protected items must clear event-only `rollupId` and `day` context, and protected-item drill-ins must open recovery events without preserving an invisible day filter that can make valid history look empty.18. Letting the recovery details panel lead with transport-shaped payloads; operator-facing details must summarize outcome, artifact, target, restore readiness, and readable metadata labels first, while raw JSON and provider-specific keys stay behind an explicitly technical disclosure.19. Letting recovery posture summaries become passive counters only; summary-card actions may focus events, stale inventory, or attention inventory, but those actions must route through the canonical recovery workspace and route-state owner instead of mutating local-only filter state.-20. Letting storage or recovery surfaces invoke retired self-hosted trial acquisition; `POST /api/license/trial/start` must stay closed on the ordinary self-hosted router, and storage/recovery-adjacent billing or support handoffs must not treat trial activation as recovery identity, restore proof, or backup transport state.+20. Letting storage or recovery surfaces invoke retired self-hosted trial acquisition; `POST /api/license/trial/start` and `/auth/trial-activate` must stay closed on the ordinary self-hosted router, and storage/recovery-adjacent billing or support handoffs must not treat trial activation as recovery identity, restore proof, or backup transport state.## Completion Obligations@@ -1885,8 +1885,8 @@ That same shared `internal/api/` dependency also assumes customer-visiblecommercial acquisition stays out of storage and recovery surfaces by default:storage- or recovery-adjacent flows must not invoke or advertise the retired`POST /api/license/trial/start` route, and the normal self-hosted router must-return `404` for that path without mutating entitlements. Approved support or-hosted handoff remains owned by signed `/auth/trial-activate` redemption, not by+return `404` for that path without mutating entitlements. The retired+`/auth/trial-activate` self-hosted callback must also stay absent fromstorage/recovery-local retry or backoff behavior.That same shared `internal/api/` dependency now also assumes adjacentcommercial helper surfaces speak in monitored-system terms: recovery- ordiff --git a/frontend-modern/src/components/Settings/ProLicensePanel.tsx b/frontend-modern/src/components/Settings/ProLicensePanel.tsxindex 2a20100d20..a887ab2128 100644--- a/frontend-modern/src/components/Settings/ProLicensePanel.tsx+++ b/frontend-modern/src/components/Settings/ProLicensePanel.tsx@@ -114,7 +114,6 @@ const ProLicensePanelContent: Component = () => {purchaseActivationAction={state.purchaseActivationAction()}onPurchaseActivationActionClick={state.handlePurchaseActivationActionClick}purchaseActivationNotice={state.purchaseActivationNotice()}- trialActivationNotice={state.trialActivationNotice()}trialEnded={state.trialEnded()}/>diff --git a/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx b/frontend-modern/src/components/Settings/ProLicensePlanSection.tsxindex ca3e7c5b7a..4ecf311fca 100644--- a/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx+++ b/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx@@ -88,7 +88,6 @@ interface ProLicensePlanSectionProps {destination: UpgradeDestination;} | null;onPurchaseActivationActionClick: () => void;- trialActivationNotice: Notice | null;trialEnded: boolean;}@@ -261,14 +260,6 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (pro</Show></div></Show>- <Show when={props.trialActivationNotice}>- {(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.commercialMigrationNotice}>{(notice) => (<div class={`mb-4 rounded-md border p-3 text-sm ${notice().tone}`}>diff --git a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsxindex 05d5b5de6c..33cf2fb59c 100644--- a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx@@ -762,33 +762,6 @@ describe('ProLicensePanel', () => {).toBeInTheDocument();});- it('shows the hosted activation success banner on the Pro settings route', async () => {- mockEntitlements = {- capabilities: ['ai_patrol', 'ai_autofix', 'ai_alerts'],- limits: [],- subscription_state: 'trial',- upgrade_reasons: [],- tier: 'pro',- trial_eligible: false,- };- useLocationMock.mockReturnValue({- search: '?trial=activated',- pathname: '/settings/system/billing/plan',- hash: '',- });-- renderPanel();-- expect(screen.getByText('Pulse Pro trial is now active')).toBeInTheDocument();- expect(screen.getByText(/this instance now has Pulse Pro trial access/i)).toBeInTheDocument();- expect(screen.getByText('Available during this trial')).toBeInTheDocument();- expect(screen.getAllByText('Safe Remediation Workflows').length).toBeGreaterThan(0);- expect(navigateMock).toHaveBeenCalledWith(SELF_HOSTED_PRO_BILLING_PLAN_HREF, {- replace: true,- scroll: false,- });- });-it.each([{purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,diff --git a/frontend-modern/src/components/Settings/useProLicensePanelState.ts b/frontend-modern/src/components/Settings/useProLicensePanelState.tsindex 62489c6d42..eb133ca304 100644--- a/frontend-modern/src/components/Settings/useProLicensePanelState.ts+++ b/frontend-modern/src/components/Settings/useProLicensePanelState.ts@@ -23,7 +23,6 @@ import {getSelfHostedCurrentPlanStatusPresentation,getLicenseSubscriptionStatusPresentation,getLicenseTierLabel,- getTrialActivationNotice,getDisplayableMonitoredSystemContinuity,hasActiveUncappedSelfHostedContinuity,isDisplayableLicenseFeature,@@ -91,12 +90,11 @@ export function useProLicensePanelState() {);const [activating, setActivating] = createSignal(false);const [clearing, setClearing] = createSignal(false);- const [trialActivationResult, setTrialActivationResult] = createSignal('');const [purchaseActivationResult, setPurchaseActivationResult] = createSignal('');const [purchaseActivationIntent, setPurchaseActivationIntent] =createSignal<SelfHostedBillingPlanIntent | null>(null);const [activationSuccessSource, setActivationSuccessSource] = createSignal<- 'manual' | 'purchase' | 'trial' | null+ 'manual' | 'purchase' | null>(null);const entitlements = createMemo(() => licenseEntitlements());@@ -116,15 +114,7 @@ export function useProLicensePanelState() {onMount(() => {const params = new URLSearchParams(location.search);- const trialResult = params.get('trial')?.trim().toLowerCase() ?? '';const purchaseResult = getSelfHostedBillingPurchaseArrival(location.search) ?? '';- if (trialResult) {- setTrialActivationResult(trialResult);- if (trialResult === 'activated') {- setActivationSuccessSource('trial');- }- params.delete('trial');- }if (purchaseResult) {setPurchaseActivationResult(purchaseResult);setPurchaseActivationIntent(getSelfHostedBillingPlanIntent(location.search));@@ -145,7 +135,7 @@ export function useProLicensePanelState() {);}}- if (trialResult || purchaseResult) {+ if (purchaseResult) {const nextSearch = params.toString();const nextPath = `${location.pathname}${nextSearch ? `?${nextSearch}` : ''}${location.hash ?? ''}`;navigate(nextPath, { replace: true, scroll: false });@@ -443,12 +433,6 @@ export function useProLicensePanelState() {entitlements()?.trial_eligibility_reason === 'already_used',);- const trialActivationNotice = createMemo(() => {- if (trialActivationResult().trim().toLowerCase() === 'activated') {- return null;- }- return getTrialActivationNotice(trialActivationResult());- });const purchaseActivationNotice = createMemo(() => {if (purchaseActivationResult().trim().toLowerCase() === 'activated') {return null;@@ -684,7 +668,6 @@ export function useProLicensePanelState() {showCountingRulesByDefault,showRecoveryByDefault,statusPresentation,- trialActivationNotice,trialEnded,};}diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.tsindex a4de64b610..b5359d45fa 100644--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts@@ -2501,7 +2501,7 @@ describe('frontend resource type boundaries', () => {expect(proLicensePanelSource).toContain('./ProLicensePlanSection');expect(proLicensePanelStateSource).toContain('getLicenseSubscriptionStatusPresentation');expect(proLicensePanelStateSource).toContain('formatLicensePlanVersion');- expect(proLicensePanelStateSource).toContain('getTrialActivationNotice');+ expect(proLicensePanelStateSource).not.toContain('getTrialActivationNotice');expect(proLicensePanelStateSource).toContain('getCommercialMigrationNotice');expect(proLicensePlanSectionSource).toContain('getLicenseStatusLoadingState');expect(proLicensePlanSectionSource).toContain('getNoActiveProLicenseState');@@ -2533,7 +2533,7 @@ describe('frontend resource type boundaries', () => {expect(licensePresentationSource).toContain('export const formatLicensePlanVersion');expect(licensePresentationSource).toContain('titleCaseDelimitedLabel');expect(licensePresentationSource).toContain('export const getCommercialMigrationNotice');- expect(licensePresentationSource).toContain('export const getTrialActivationNotice');+ expect(licensePresentationSource).not.toContain('export const getTrialActivationNotice');expect(securityPostureSummarySource).toContain('getSecurityScorePresentation');expect(securityPostureSummarySource).toContain('getSecurityScoreIconComponent');expect(securityPostureSummarySource).toContain('getSecurityFeatureCardPresentation');diff --git a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts b/frontend-modern/src/utils/__tests__/licensePresentation.test.tsindex 59fe73082f..3c076543d2 100644--- a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts+++ b/frontend-modern/src/utils/__tests__/licensePresentation.test.ts@@ -24,7 +24,6 @@ import {getInactiveProUpsellNotice,getPurchaseActivationNotice,getTrialEndedProLicenseNotice,- getTrialActivationNotice,isDisplayableLicenseFeature,isGrandfatheredRecurringV5PlanVersion,isUncappedGrandfatheredPlanVersion,@@ -434,7 +433,7 @@ describe('licensePresentation', () => {).toEqual({ cards: [] });});- it('builds activation-success summaries for purchase, pasted-key, and trial activation paths', () => {+ it('builds activation-success summaries for purchase and pasted-key paths', () => {expect(getSelfHostedActivationSuccessPresentation({entitlements: {@@ -503,19 +502,9 @@ describe('licensePresentation', () => {upgrade_reasons: [],},displayableCapabilities: ['Pulse Patrol', 'Safe Remediation Workflows'],- source: 'trial',+ source: 'purchase',}),- ).toEqual({- 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 trial is now active',- body: 'The trial handoff completed and this instance now has Pulse Pro trial access.',- highlightsLabel: 'Available during this trial',- highlights: [- 'Alert Root-Cause Analysis',- 'Safe Remediation Workflows',- '90-day metric history',- ],- });+ ).toBeNull();expect(getSelfHostedActivationSuccessPresentation({@@ -655,30 +644,6 @@ describe('licensePresentation', () => {});});- it('returns canonical trial activation notices', () => {- expect(getTrialActivationNotice('activated')).toMatchObject({- title: 'Trial activated',- tone: expect.stringContaining('green'),- });- expect(getTrialActivationNotice('replayed')).toMatchObject({- title: 'Trial already activated',- tone: expect.stringContaining('sky'),- });- expect(getTrialActivationNotice('invalid')).toMatchObject({- title: 'Activation link invalid',- body: expect.stringContaining('Return to Plans'),- });- expect(getTrialActivationNotice('unavailable')).toMatchObject({- title: 'Activation unavailable',- body: expect.stringContaining('Refresh the billing state below'),- });- expect(getTrialActivationNotice('ineligible')).toMatchObject({- title: 'Trial not available',- tone: expect.stringContaining('red'),- });- expect(getTrialActivationNotice('')).toBeNull();- });-it('returns canonical purchase activation notices', () => {expect(getPurchaseActivationNotice('activated')).toMatchObject({title: 'Plan activated',diff --git a/frontend-modern/src/utils/licensePresentation.ts b/frontend-modern/src/utils/licensePresentation.tsindex b68cd7a00f..de25fdc4d4 100644--- a/frontend-modern/src/utils/licensePresentation.ts+++ b/frontend-modern/src/utils/licensePresentation.ts@@ -111,7 +111,7 @@ export interface SelfHostedActivationSuccessPresentation extends LicenseInlineNohighlights: string[];}-export type SelfHostedActivationSuccessSource = 'manual' | 'purchase' | 'trial';+export type SelfHostedActivationSuccessSource = 'manual' | 'purchase';export interface SelfHostedPlanComparisonCardPresentation {title: string;@@ -519,7 +519,7 @@ export const getSelfHostedCurrentPlanPresentation = ({body:unlockedFeatures.length > 0? `${planLabel} trial capabilities are active on this instance right now.`- : `${planLabel} trial activation is in progress on this instance.`,+ : `${planLabel} trial entitlement is being confirmed for this instance.`,unlockedFeaturesLabel,unlockedFeatures,includedExtrasLabel: includedExtras.length > 0 ? 'Included extras' : undefined,@@ -589,11 +589,7 @@ export const getSelfHostedActivationSuccessPresentation = ({return null;}- if (source === 'trial') {- if (normalizedState !== 'trial') {- return null;- }- } else if (normalizedState !== 'active' && normalizedState !== 'grace') {+ if (normalizedState !== 'active' && normalizedState !== 'grace') {return null;}@@ -603,16 +599,6 @@ export const getSelfHostedActivationSuccessPresentation = ({displayableCapabilities,});- if (source === 'trial') {- return {- tone: 'border-green-200 dark:border-green-900 bg-green-50 dark:bg-green-900 text-green-900 dark:text-green-100',- title: `${planLabel} trial is now active`,- body: `The trial handoff completed and this instance now has ${planLabel} trial access.`,- highlightsLabel: 'Available during this trial',- highlights,- };- }-return {tone: 'border-green-200 dark:border-green-900 bg-green-50 dark:bg-green-900 text-green-900 dark:text-green-100',title: `${planLabel} is now active`,@@ -698,43 +684,6 @@ export const getCommercialMigrationNotice = (};};-export const getTrialActivationNotice = (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: 'Trial activated',- body: 'Pulse activated the Pro trial for this instance. The entitlement state below is live.',- };- case 'invalid':- 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 link invalid',- body: 'That activation handoff is invalid or expired. Return to Plans on this instance and start a fresh secure trial handoff.',- };- case 'replayed':- return {- tone: 'border-sky-200 dark:border-sky-900 bg-sky-50 dark:bg-sky-900 text-sky-900 dark:text-sky-100',- title: 'Trial already activated',- body: 'This activation handoff was already redeemed for this instance. Use the current entitlement state below as the source of truth.',- };- case 'unavailable':- return {- tone: 'border-amber-200 dark:border-amber-900 bg-amber-50 dark:bg-amber-900 text-amber-900 dark:text-amber-100',- title: 'Activation unavailable',- body: 'Pulse could not finish activation right now. Refresh the billing state below, then retry the return link or start the secure trial handoff again from this instance if needed.',- };- case 'ineligible':- return {- tone: 'border-red-200 dark:border-red-900 bg-red-50 dark:bg-red-900 text-red-900 dark:text-red-100',- title: 'Trial not available',- body: 'This organization is not eligible for another Pro trial. Review the current license state below or upgrade instead.',- };- default:- return null;- }-};-export const getPurchaseActivationNotice = (result?: string | null): LicenseInlineNotice | null => {switch ((result || '').trim().toLowerCase()) {case 'activated':diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 5c6774b38c..a28dd119c5 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -6399,7 +6399,6 @@ func TestContract_DemoModeCommercialSurfacePolicy(t *testing.T) {{method: http.MethodGet, path: "/api/logs/level"},{method: http.MethodPost, path: "/api/logs/level"},{method: http.MethodGet, path: licensePurchaseStartPath},- {method: http.MethodGet, path: "/auth/trial-activate"},}for _, tc := range testCases {diff --git a/internal/api/demo_middleware_test.go b/internal/api/demo_middleware_test.goindex 05391c5204..12281a4be4 100644--- a/internal/api/demo_middleware_test.go+++ b/internal/api/demo_middleware_test.go@@ -73,7 +73,6 @@ func TestDemoModeMiddleware(t *testing.T) {{"demo on hidden checkout start", true, http.MethodGet, "/auth/license-purchase-start", "", false, http.StatusNotFound, true},{"demo on hidden license activate", true, http.MethodPost, "/api/license/activate", "", false, http.StatusNotFound, true},{"demo on hidden purchase start", true, http.MethodGet, licensePurchaseStartPath, "", false, http.StatusNotFound, true},- {"demo on hidden trial activation", true, http.MethodGet, "/auth/trial-activate", "", false, http.StatusNotFound, true},{"demo on runtime capabilities", true, http.MethodGet, "/api/license/runtime-capabilities", "", true, http.StatusOK, true},// Demo mode enabled - modification requests blockeddiff --git a/internal/api/demo_mode_commercial.go b/internal/api/demo_mode_commercial.goindex 3d985dcd00..136f635232 100644--- a/internal/api/demo_mode_commercial.go+++ b/internal/api/demo_mode_commercial.go@@ -128,11 +128,6 @@ var publicDemoCommercialPolicies = []publicDemoCommercialRoutePolicy{exposure: publicDemoCommercialExposureHidden,matches: exactDemoCommercialOrgBillingStatePath(http.MethodPut),},- {- route: "/auth/trial-activate",- exposure: publicDemoCommercialExposureHidden,- matches: exactDemoCommercialPath("/auth/trial-activate"),- },}func publicDemoCommercialPolicyForRequest(diff --git a/internal/api/demo_mode_commercial_test.go b/internal/api/demo_mode_commercial_test.goindex 7823d953f9..6dffe58ba0 100644--- a/internal/api/demo_mode_commercial_test.go+++ b/internal/api/demo_mode_commercial_test.go@@ -137,8 +137,6 @@ func TestPublicDemoCommercialPolicyForRequestHidesUsagePreviewRoutes(t *testing.func routeBelongsToPublicDemoCommercialBoundary(route string) bool {switch {- case route == "/auth/trial-activate":- return truecase route == licensePurchaseStartPath:return truecase route == "GET "+licensePurchaseStartPath:diff --git a/internal/api/hosted_lifecycle_integration_test.go b/internal/api/hosted_lifecycle_integration_test.goindex 289c12c394..7dfc7e0ffd 100644--- a/internal/api/hosted_lifecycle_integration_test.go+++ b/internal/api/hosted_lifecycle_integration_test.go@@ -2,12 +2,9 @@ package apiimport ("context"- "crypto/ed25519"- "encoding/base64""encoding/json""net/http""net/http/httptest"- "net/url""os""path/filepath""reflect"@@ -15,27 +12,13 @@ import ("testing""time"- "github.com/golang-jwt/jwt/v5""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/hosted""github.com/rcourtman/pulse-go-rewrite/internal/license""github.com/rcourtman/pulse-go-rewrite/internal/license/entitlements""github.com/rcourtman/pulse-go-rewrite/internal/models"- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing")-func issueHostedLifecycleTrialInitiationToken(t *testing.T, h *LicenseHandlers, orgID, returnURL string) string {- t.Helper()- if h == nil || h.trialInitiations == nil {- t.Fatal("trial initiation store is not configured")- }- token, err := h.trialInitiations.issue(orgID, returnURL, time.Now().UTC().Add(trialSignupInitiationTTL))- if err != nil {- t.Fatalf("issue trial initiation token: %v", err)- }- return token-}-func TestHostedLifecycle(t *testing.T) {t.Run("Signup_SeedsTrialBillingState_ForBillingAdmin", func(t *testing.T) {router, persistence, _, _, baseDir := newHostedSignupTestRouter(t, true)@@ -181,254 +164,6 @@ func TestHostedLifecycle(t *testing.T) {}})- t.Run("Trial_Start_Countdown_Expiry", func(t *testing.T) {- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- handlers := NewLicenseHandlers(mtp, false, &config.Config{PublicURL: "https://pulse.example.com"})-- ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")-- pub, priv, err := ed25519.GenerateKey(nil)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- handlers.trialRedeemer = func(token string) (*hostedTrialRedemptionResponse, error) {- claims, err := pkglicensing.VerifyTrialActivationToken(token, pub, "", time.Now().UTC())- if err != nil {- return nil, err- }- return issueTrialRedemptionResponse(t, priv, claims.OrgID, claims.InstanceHost, claims.Email, time.Now().UTC()), nil- }- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))- handlers.trialRedeemer = func(string) (*hostedTrialRedemptionResponse, error) {- return issueTrialRedemptionResponse(t, priv, "default", "pulse.example.com", "[email protected]", time.Now()), nil- }- returnURL := "https://pulse.example.com/auth/trial-activate"- instanceToken := issueHostedLifecycleTrialInitiationToken(t, handlers, "default", returnURL)-- token, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken: %v", err)- }-- startReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token), nil).WithContext(ctx)- startReq.Host = "pulse.example.com"- startRec := httptest.NewRecorder()- handlers.HandleTrialActivation(startRec, startReq)- if startRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("trial activation status=%d, want %d: %s", startRec.Code, http.StatusTemporaryRedirect, startRec.Body.String())- }- if got := startRec.Header().Get("Location"); got != "/settings/system-pro?trial=activated" {- t.Fatalf("trial activation redirect=%q, want %q", got, "/settings/system-pro?trial=activated")- }-- billingStore := config.NewFileBillingStore(baseDir)- state, err := billingStore.GetBillingState("default")- if err != nil || state == nil {- t.Fatalf("GetBillingState(default) failed: %v state=%v", err, state)- }- if state.SubscriptionState != entitlements.SubStateTrial {- t.Fatalf("trial activation subscription_state=%q, want %q", state.SubscriptionState, entitlements.SubStateTrial)- }- rawData, err := os.ReadFile(filepath.Join(baseDir, "billing.json"))- if err != nil {- t.Fatalf("ReadFile(billing.json): %v", err)- }- var rawState entitlements.BillingState- if err := json.Unmarshal(rawData, &rawState); err != nil {- t.Fatalf("Unmarshal(raw billing.json): %v", err)- }- if rawState.SubscriptionState != "" {- t.Fatalf("raw subscription_state=%q, want empty", rawState.SubscriptionState)- }- if rawState.PlanVersion != "" {- t.Fatalf("raw plan_version=%q, want empty", rawState.PlanVersion)- }- if len(rawState.Capabilities) != 0 {- t.Fatalf("raw capabilities=%v, want empty", rawState.Capabilities)- }- if rawState.TrialEndsAt != nil {- t.Fatalf("raw trial_ends_at=%v, want nil", rawState.TrialEndsAt)- }- if rawState.TrialStartedAt == nil {- t.Fatal("expected raw trial_started_at to be preserved")- }- if rawState.EntitlementJWT == "" {- t.Fatal("expected entitlement_jwt ciphertext to be stored")- }- if rawState.EntitlementJWT == state.EntitlementJWT {- t.Fatal("expected entitlement_jwt to be encrypted at rest")- }- if rawState.EntitlementRefreshToken == "" {- t.Fatal("expected entitlement_refresh_token ciphertext to be stored")- }- if rawState.EntitlementRefreshToken == "etr_test_default" {- t.Fatal("expected entitlement_refresh_token to be encrypted at rest")- }-- entReq1 := httptest.NewRequest(http.MethodGet, "/api/license/entitlements", nil).WithContext(ctx)- entRec1 := httptest.NewRecorder()- handlers.HandleEntitlements(entRec1, entReq1)- if entRec1.Code != http.StatusOK {- t.Fatalf("entitlements status=%d, want %d: %s", entRec1.Code, http.StatusOK, entRec1.Body.String())- }-- var payload1 EntitlementPayload- if err := json.NewDecoder(entRec1.Body).Decode(&payload1); err != nil {- t.Fatalf("decode entitlements payload: %v", err)- }- if payload1.SubscriptionState != string(license.SubStateTrial) {- t.Fatalf("subscription_state=%q, want %q", payload1.SubscriptionState, license.SubStateTrial)- }- if payload1.TrialDaysRemaining == nil || *payload1.TrialDaysRemaining <= 0 {- t.Fatalf("expected trial_days_remaining to be populated and > 0, got %v", payload1.TrialDaysRemaining)- }-- // Manually expire the trial by replacing the entitlement lease with an already-expired one.- loaded, err := billingStore.GetBillingState("default")- if err != nil || loaded == nil {- t.Fatalf("GetBillingState(default) failed: %v state=%v", err, loaded)- }- loaded.EntitlementJWT = issueTrialEntitlementLease(t, priv, "default", "pulse.example.com", "[email protected]", time.Now().Add(-15*24*time.Hour))- if err := billingStore.SaveBillingState("default", loaded); err != nil {- t.Fatalf("SaveBillingState(default) failed: %v", err)- }-- entReq2 := httptest.NewRequest(http.MethodGet, "/api/license/entitlements", nil).WithContext(ctx)- entRec2 := httptest.NewRecorder()- handlers.HandleEntitlements(entRec2, entReq2)- if entRec2.Code != http.StatusOK {- t.Fatalf("entitlements (post-expiry) status=%d, want %d: %s", entRec2.Code, http.StatusOK, entRec2.Body.String())- }-- var payload2 EntitlementPayload- if err := json.NewDecoder(entRec2.Body).Decode(&payload2); err != nil {- t.Fatalf("decode entitlements payload (post-expiry): %v", err)- }- if payload2.SubscriptionState != string(license.SubStateExpired) {- t.Fatalf("subscription_state=%q, want %q", payload2.SubscriptionState, license.SubStateExpired)- }- if sliceContainsString(payload2.Capabilities, license.FeatureAIAutoFix) {- t.Fatalf("expected pro-only capability %q to be removed on expiry; got %v", license.FeatureAIAutoFix, payload2.Capabilities)- }- for _, freeFeature := range license.TierFeatures[license.TierFree] {- if !sliceContainsString(payload2.Capabilities, freeFeature) {- t.Fatalf("expected free-tier feature %q to remain after expiry; got %v", freeFeature, payload2.Capabilities)- }- }- })-- t.Run("One_Trial_Per_Org_Enforcement", func(t *testing.T) {- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- handlers := NewLicenseHandlers(mtp, false, &config.Config{PublicURL: "https://pulse.example.com"})-- pub, priv, err := ed25519.GenerateKey(nil)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- handlers.trialRedeemer = func(token string) (*hostedTrialRedemptionResponse, error) {- claims, err := pkglicensing.VerifyTrialActivationToken(token, pub, "", time.Now().UTC())- if err != nil {- return nil, err- }- return issueTrialRedemptionResponse(t, priv, claims.OrgID, claims.InstanceHost, claims.Email, time.Now().UTC()), nil- }- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))- handlers.trialRedeemer = func(token string) (*hostedTrialRedemptionResponse, error) {- claims, err := pkglicensing.VerifyTrialActivationToken(token, pub, "pulse.example.com", time.Now())- if err != nil {- t.Fatalf("VerifyTrialActivationToken(redeemer): %v", err)- }- return issueTrialRedemptionResponse(t, priv, claims.OrgID, claims.InstanceHost, claims.Email, time.Now()), nil- }-- org1 := "trial-org-1"- ctx1 := context.WithValue(context.Background(), OrgIDContextKey, org1)- returnURL := "https://pulse.example.com/auth/trial-activate"- instanceToken1 := issueHostedLifecycleTrialInitiationToken(t, handlers, org1, returnURL)-- token1, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: org1,- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken1,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken(org1): %v", err)- }-- req1 := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token1), nil).WithContext(ctx1)- req1.Host = "pulse.example.com"- rec1 := httptest.NewRecorder()- handlers.HandleTrialActivation(rec1, req1)- if rec1.Code != http.StatusTemporaryRedirect {- t.Fatalf("org1 first activation status=%d, want %d: %s", rec1.Code, http.StatusTemporaryRedirect, rec1.Body.String())- }-- token2, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: org1,- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken1,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken(org1 second): %v", err)- }-- req2 := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token2), nil).WithContext(ctx1)- req2.Host = "pulse.example.com"- rec2 := httptest.NewRecorder()- handlers.HandleTrialActivation(rec2, req2)- if rec2.Code != http.StatusTemporaryRedirect {- t.Fatalf("org1 second activation status=%d, want %d: %s", rec2.Code, http.StatusTemporaryRedirect, rec2.Body.String())- }- if got := rec2.Header().Get("Location"); got != "/settings/system-pro?trial=invalid" {- t.Fatalf("org1 second activation redirect=%q, want %q", got, "/settings/system-pro?trial=invalid")- }-- org2 := "trial-org-2"- ctx2 := context.WithValue(context.Background(), OrgIDContextKey, org2)- instanceToken2 := issueHostedLifecycleTrialInitiationToken(t, handlers, org2, returnURL)- token3, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: org2,- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken2,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken(org2): %v", err)- }- req3 := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token3), nil).WithContext(ctx2)- req3.Host = "pulse.example.com"- rec3 := httptest.NewRecorder()- handlers.HandleTrialActivation(rec3, req3)- if rec3.Code != http.StatusTemporaryRedirect {- t.Fatalf("org2 activation status=%d, want %d: %s", rec3.Code, http.StatusTemporaryRedirect, rec3.Body.String())- }- })-t.Run("Reaper_Cleanup_Cascade", func(t *testing.T) {baseDir := t.TempDir()mtp := config.NewMultiTenantPersistence(baseDir)diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.goindex 2747a2b6f9..541ef4f1d4 100644--- a/internal/api/licensing_bridge.go+++ b/internal/api/licensing_bridge.go@@ -66,7 +66,6 @@ type conversionInfrastructureOnboardingDayBreakdown = pkglicensing.Infrastructurtype conversionInfrastructureOnboardingPathBreakdown = pkglicensing.InfrastructureOnboardingPathBreakdowntype conversionInfrastructureOnboardingPlatformBreakdown = pkglicensing.InfrastructureOnboardingPlatformBreakdowntype conversionInfrastructureOnboardingReport = pkglicensing.InfrastructureOnboardingReport-type trialActivationClaimsModel = pkglicensing.TrialActivationClaimstype purchaseReturnClaimsModel = pkglicensing.PurchaseReturnClaimstype entitlementLeaseClaimsModel = pkglicensing.EntitlementLeaseClaimstype licenseTier = pkglicensing.Tier@@ -318,10 +317,6 @@ func trialActivationPublicKeyFromLicensing() (ed25519.PublicKey, error) {return pkglicensing.TrialActivationPublicKey()}-func verifyTrialActivationTokenFromLicensing(token string, key ed25519.PublicKey, expectedInstanceHost string, now time.Time) (*trialActivationClaimsModel, error) {- return pkglicensing.VerifyTrialActivationToken(token, key, expectedInstanceHost, now)-}-func signPurchaseReturnTokenFromLicensing(signingKey []byte, claims purchaseReturnClaimsModel) (string, error) {return pkglicensing.SignPurchaseReturnToken(signingKey, claims)}diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.goindex 8989af5118..0094b4f58f 100644--- a/internal/api/licensing_handlers.go+++ b/internal/api/licensing_handlers.go@@ -1,7 +1,6 @@package apiimport (- "bytes""context""encoding/json""errors"@@ -59,10 +58,7 @@ type LicenseHandlers struct {hostedMode boolcfg *config.Configservices sync.Map // map[string]*licenseService- trialReplay *jtiReplayStorepurchaseReturnRedemptions *purchaseReturnRedemptionStore- trialInitiations *trialSignupInitiationStore- trialRedeemer func(token string) (*hostedTrialRedemptionResponse, error)monitor *monitoring.MonitormtMonitor *monitoring.MultiTenantMonitorconversionRecorder *conversionRecorder@@ -80,22 +76,16 @@ func NewLicenseHandlers(mtp *config.MultiTenantPersistence, hostedMode bool, cfgcfg = cfgs[0]}- var trialReplay *jtiReplayStorevar purchaseReturnRedemptions *purchaseReturnRedemptionStore- var trialInitiations *trialSignupInitiationStoreif mtp != nil {- trialReplay = &jtiReplayStore{configDir: mtp.BaseDataDir()}purchaseReturnRedemptions = &purchaseReturnRedemptionStore{configDir: mtp.BaseDataDir()}- trialInitiations = &trialSignupInitiationStore{configDir: mtp.BaseDataDir()}}return &LicenseHandlers{mtPersistence: mtp,hostedMode: hostedMode,cfg: cfg,- trialReplay: trialReplay,purchaseReturnRedemptions: purchaseReturnRedemptions,- trialInitiations: trialInitiations,}}@@ -859,274 +849,6 @@ func (h *LicenseHandlers) FeatureService(ctx context.Context) licenseFeatureChecreturn h.Service(ctx)}-// HandleTrialActivation handles GET /auth/trial-activate.-// It verifies a hosted signup trial activation token, blocks replay, persists a-// signed hosted entitlement lease, then redirects to Settings.-func (h *LicenseHandlers) HandleTrialActivation(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- if h == nil || h.mtPersistence == nil {- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }-- token := strings.TrimSpace(r.URL.Query().Get("token"))- if token == "" {- http.Redirect(w, r, trialActivationResultURL("invalid"), http.StatusTemporaryRedirect)- return- }-- publicKey, err := trialActivationPublicKeyFromLicensing()- if err != nil {- log.Error().Err(err).Msg("Trial activation public key not configured")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }-- // Prefer configured PublicURL for host binding validation.- // Fall back to request Host only if no PublicURL is configured, to avoid- // an attacker-controlled Host header weakening instance binding.- // If PublicURL is set but normalizes to empty (malformed), fail closed.- expectedHost := ""- if h.cfg != nil && strings.TrimSpace(h.cfg.PublicURL) != "" {- expectedHost = normalizeHostForTrial(h.cfg.PublicURL)- if expectedHost == "" {- log.Error().Msg("PublicURL configured but could not extract host for trial activation binding")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- } else {- expectedHost = normalizeHostForTrial(r.Host)- }- if expectedHost == "" {- log.Error().Msg("Could not determine host for trial activation binding")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- claims, err := verifyTrialActivationTokenFromLicensing(token, publicKey, expectedHost, time.Now().UTC())- if err != nil {- log.Warn().Err(err).Msg("Trial activation token verification failed")- http.Redirect(w, r, trialActivationResultURL("invalid"), http.StatusTemporaryRedirect)- return- }-- replayStore := h.trialReplay- if replayStore == nil {- replayStore = &jtiReplayStore{configDir: h.mtPersistence.BaseDataDir()}- }- replaySubject := strings.TrimSpace(claims.Subject)- if replaySubject == "" {- replaySubject = strings.TrimSpace(claims.ID)- }- if replaySubject == "" {- log.Warn().Msg("Trial activation token missing subject and jti")- http.Redirect(w, r, trialActivationResultURL("invalid"), http.StatusTemporaryRedirect)- return- }- replayID := "trial_activate:" + replaySubject- expiresAt := time.Now().UTC().Add(15 * time.Minute)- if claims.ExpiresAt != nil {- expiresAt = claims.ExpiresAt.Time- }- stored, err := replayStore.checkAndStore(replayID, expiresAt)- if err != nil {- log.Error().Err(err).Msg("Trial activation replay-store failure")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- if !stored {- log.Warn().Str("replay_id_prefix", replayID[:24]).Msg("Trial activation token replay blocked")- http.Redirect(w, r, trialActivationResultURL("replayed"), http.StatusTemporaryRedirect)- return- }- clearReplay := func(reason string, err error) {- if replayStore == nil {- return- }- if deleteErr := replayStore.delete(replayID); deleteErr != nil {- log.Warn().Err(deleteErr).Str("replay_id_prefix", replayID[:24]).Str("reason", reason).Msg("Trial activation replay-store cleanup failed")- return- }- if err != nil {- log.Warn().Err(err).Str("replay_id_prefix", replayID[:24]).Str("reason", reason).Msg("Cleared trial activation replay marker after transient failure")- }- }-- orgID := strings.TrimSpace(claims.OrgID)- if orgID == "" {- orgID = "default"- }- if h.trialInitiations == nil {- clearReplay("initiation_store_unavailable", nil)- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- returnURL := strings.TrimSpace(claims.ReturnURL)- ok, err := h.trialInitiations.validate(orgID, returnURL, claims.InstanceToken, time.Now().UTC())- if err != nil {- clearReplay("initiation_validation_failed", err)- log.Error().Err(err).Str("org_id", orgID).Msg("Trial activation initiation token validation failed")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- if !ok {- log.Warn().Str("org_id", orgID).Msg("Trial activation missing or invalid initiation token")- http.Redirect(w, r, trialActivationResultURL("invalid"), http.StatusTemporaryRedirect)- return- }-- ctx := context.WithValue(r.Context(), OrgIDContextKey, orgID)- svc, _, err := h.getTenantComponents(ctx)- if err != nil {- clearReplay("tenant_resolution_failed", err)- log.Error().Err(err).Str("org_id", orgID).Msg("Trial activation tenant resolution failed")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }-- billingStore := config.NewFileBillingStore(h.mtPersistence.BaseDataDir())- existing, err := billingStore.GetBillingState(orgID)- if err != nil {- clearReplay("billing_state_load_failed", err)- log.Error().Err(err).Str("org_id", orgID).Msg("Trial activation billing state load failed")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- decision := evaluateTrialStartEligibilityFromLicensing(svc.Current() != nil && svc.IsValid(), existing)- if !decision.Allowed {- log.Info().- Str("org_id", orgID).- Str("reason", string(decision.Reason)).- Msg("Trial activation denied due to ineligible state")- http.Redirect(w, r, trialActivationResultURL("ineligible"), http.StatusTemporaryRedirect)- return- }-- redeemer := h.trialRedeemer- if redeemer == nil {- redeemer = h.acknowledgeHostedTrialRedemption- }- var redemption *hostedTrialRedemptionResponse- if redeemer != nil {- redemption, err = redeemer(token)- if err != nil {- clearReplay("redemption_ack_failed", err)- log.Warn().Err(err).Str("org_id", orgID).Msg("Hosted trial redemption acknowledgement failed")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- }- entitlementJWT := ""- entitlementRefreshToken := ""- if redemption != nil {- entitlementJWT = strings.TrimSpace(redemption.EntitlementJWT)- entitlementRefreshToken = strings.TrimSpace(redemption.EntitlementRefreshToken)- }- if strings.TrimSpace(entitlementJWT) == "" {- clearReplay("entitlement_lease_missing", nil)- log.Warn().Str("org_id", orgID).Msg("Hosted trial redemption returned no entitlement lease")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- if entitlementRefreshToken == "" {- clearReplay("entitlement_refresh_token_missing", nil)- log.Warn().Str("org_id", orgID).Msg("Hosted trial redemption returned no entitlement refresh token")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- leaseClaims, err := verifyEntitlementLeaseTokenFromLicensing(entitlementJWT, publicKey, expectedHost, time.Now().UTC())- if err != nil {- clearReplay("entitlement_lease_invalid", err)- log.Warn().Err(err).Str("org_id", orgID).Msg("Hosted trial entitlement lease verification failed")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- if strings.TrimSpace(leaseClaims.OrgID) != orgID {- clearReplay("entitlement_lease_org_mismatch", nil)- log.Warn().- Str("org_id", orgID).- Str("lease_org_id", strings.TrimSpace(leaseClaims.OrgID)).- Msg("Hosted trial entitlement lease org mismatch")- http.Redirect(w, r, trialActivationResultURL("invalid"), http.StatusTemporaryRedirect)- return- }-- state := &billingState{}- if existing != nil {- state = normalizeBillingStateFromLicensing(existing)- }- // Keep only the signed hosted lease plus trial-used bookkeeping locally.- // Effective Pro capabilities and limits must resolve from the lease on read.- state.EntitlementJWT = entitlementJWT- state.EntitlementRefreshToken = entitlementRefreshToken- state.Capabilities = []string{}- state.Limits = map[string]int64{}- state.MetersEnabled = []string{}- state.PlanVersion = ""- state.SubscriptionState = ""- state.TrialStartedAt = leaseClaims.TrialStartedAt- state.TrialEndsAt = nil- state.TrialExtendedAt = nil- if err := billingStore.SaveBillingState(orgID, state); err != nil {- clearReplay("billing_state_save_failed", err)- log.Error().Err(err).Str("org_id", orgID).Msg("Trial activation billing state save failed")- http.Redirect(w, r, trialActivationResultURL("unavailable"), http.StatusTemporaryRedirect)- return- }- if svc.Current() == nil {- eval := newLicenseEvaluatorForBillingStoreFromLicensing(billingStore, orgID, 0, expectedHost)- svc.SetEvaluator(eval)- }- h.ensureHostedEntitlementRefreshForOrg(orgID, svc)-- isSecure, sameSite := getCookieSettings(r)- http.SetCookie(w, &http.Cookie{- Name: CookieNameOrgID,- Value: orgID,- Path: "/",- Secure: isSecure,- SameSite: sameSite,- MaxAge: int((24 * time.Hour).Seconds()),- })-- h.emitConversionEvent(orgID, conversionEvent{- Type: conversionEventTrialStarted,- Surface: "hosted_signup",- })-- if consumed, consumeErr := h.trialInitiations.consume(orgID, returnURL, claims.InstanceToken, time.Now().UTC()); consumeErr != nil {- log.Warn().Err(consumeErr).Str("org_id", orgID).Msg("Trial initiation token consume failed after activation")- } else if !consumed {- log.Warn().Str("org_id", orgID).Msg("Trial initiation token was not consumed after activation")- }-- log.Info().- Str("org_id", orgID).- Str("email", strings.TrimSpace(claims.Email)).- Msg("Trial activation succeeded")-- http.Redirect(w, r, trialActivationResultURL("activated"), http.StatusTemporaryRedirect)-}--func trialActivationResultURL(result string) string {- return "/settings/system-pro?trial=" + url.QueryEscape(strings.TrimSpace(result))-}--func normalizeTrialOrgID(raw string) string {- orgID := strings.TrimSpace(raw)- if orgID == "" {- return "default"- }- return orgID-}--type hostedTrialRedemptionResponse struct {- EntitlementJWT string `json:"entitlement_jwt"`- EntitlementRefreshToken string `json:"entitlement_refresh_token"`-}-type hostedTrialLeaseRefreshRequest struct {OrgID string `json:"org_id"`InstanceHost string `json:"instance_host"`@@ -1137,66 +859,6 @@ type hostedTrialLeaseRefreshResponse struct {EntitlementJWT string `json:"entitlement_jwt"`}-func (h *LicenseHandlers) acknowledgeHostedTrialRedemption(token string) (*hostedTrialRedemptionResponse, error) {- if h == nil {- return nil, nil- }- redemptionURL := trialSignupRedemptionURLFromConfig(h.cfg)- if redemptionURL == "" {- return nil, nil- }- payload, err := json.Marshal(map[string]string{"token": strings.TrimSpace(token)})- if err != nil {- return nil, fmt.Errorf("marshal trial redemption payload: %w", err)- }- req, err := http.NewRequest(http.MethodPost, redemptionURL, bytes.NewReader(payload))- if err != nil {- return nil, fmt.Errorf("build trial redemption request: %w", err)- }- req.Header.Set("Content-Type", "application/json")- client := securityutil.NewRestrictedOutboundHTTPClient(5*time.Second, securityutil.RestrictedOutboundHTTPOptions{- AllowedSchemes: []string{"http", "https"},- AllowLoopback: true,- })- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("post trial redemption acknowledgement: %w", err)- }- defer resp.Body.Close()- if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return nil, fmt.Errorf("trial redemption acknowledgement returned status %d", resp.StatusCode)- }- var response hostedTrialRedemptionResponse- if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {- return nil, fmt.Errorf("decode trial redemption acknowledgement: %w", err)- }- if strings.TrimSpace(response.EntitlementJWT) == "" {- return nil, fmt.Errorf("trial redemption acknowledgement missing entitlement_jwt")- }- if strings.TrimSpace(response.EntitlementRefreshToken) == "" {- return nil, fmt.Errorf("trial redemption acknowledgement missing entitlement_refresh_token")- }- return &response, nil-}--func trialSignupRedemptionURLFromConfig(cfg *config.Config) string {- signupBaseURL := ""- if cfg != nil {- signupBaseURL = strings.TrimSpace(cfg.ProTrialSignupURL)- }- signupURL := strings.TrimSpace(proTrialSignupURLFromLicensing(signupBaseURL))- if signupURL == "" {- return ""- }- parsed, err := parseHostedCommercialURL(signupURL)- if err != nil || parsed == nil {- return ""- }- parsed.Path = "/api/trial-signup/redeem"- parsed.RawQuery = ""- return parsed.String()-}-func hostedEntitlementRefreshURLFromConfig(cfg *config.Config) string {signupBaseURL := ""if cfg != nil {diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex 9dce9a3e10..62791c15ec 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -282,7 +282,6 @@ var publicRouteAllowlist = []string{"/api/auto-register","/api/auto-unregister","/auth/cloud-handoff",- "/auth/trial-activate",licensePurchaseActivationPath,"/install.sh","/install.ps1",@@ -346,7 +345,6 @@ var bareRouteAllowlist = []string{"/api/cloud/handoff/exchange","/api/clusters/","/auth/cloud-handoff",- "/auth/trial-activate",licensePurchaseActivationPath,"/ws","/api/saml/",@@ -512,7 +510,6 @@ var allRouteAllowlist = []string{"/api/public/magic-link/verify","/api/cloud/handoff/exchange","/auth/cloud-handoff",- "/auth/trial-activate",licensePurchaseActivationPath,"/api/saml/","/api/admin/roles",diff --git a/internal/api/router.go b/internal/api/router.goindex a1235121f4..31298d8697 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -3484,7 +3484,6 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {"/api/server/info", // Server info for installer script"/api/ai/oauth/callback", // OAuth callback from Anthropic for Claude subscription auth"/auth/cloud-handoff", // Cloud control plane handoff (token-authenticated)- "/auth/trial-activate", // Hosted trial signup callback (token-authenticated)"/auth/license-purchase-activate", // Self-hosted checkout return (session-authenticated via commercial backend)}@@ -3644,10 +3643,6 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {if req.URL.Path == "/auth/cloud-handoff" {skipCSRF = true}- // Skip CSRF for hosted trial activation callback (GET with signed token).- if req.URL.Path == "/auth/trial-activate" {- skipCSRF = true- }// Skip CSRF for self-hosted checkout activation return (POST from Pulse Account, no prior session required).if req.URL.Path == "/auth/license-purchase-activate" {skipCSRF = truediff --git a/internal/api/router_csrf_skip_inventory_test.go b/internal/api/router_csrf_skip_inventory_test.goindex e74581cb06..e93d5ed6dc 100644--- a/internal/api/router_csrf_skip_inventory_test.go+++ b/internal/api/router_csrf_skip_inventory_test.go@@ -77,6 +77,5 @@ var csrfSkipAllowlist = []string{"/api/security/validate-bootstrap-token","/api/setup-script-url","/auth/cloud-handoff",- "/auth/trial-activate",licensePurchaseActivationPath,}diff --git a/internal/api/router_public_paths_inventory_test.go b/internal/api/router_public_paths_inventory_test.goindex 3496cd0a82..61a5f249f3 100644--- a/internal/api/router_public_paths_inventory_test.go+++ b/internal/api/router_public_paths_inventory_test.go@@ -125,6 +125,5 @@ var publicPathsAllowlist = []string{"/api/server/info","/api/ai/oauth/callback","/auth/cloud-handoff",- "/auth/trial-activate",licensePurchaseActivationPath,}diff --git a/internal/api/router_routes_cloud.go b/internal/api/router_routes_cloud.goindex b8ca7445f2..8107565d51 100644--- a/internal/api/router_routes_cloud.go+++ b/internal/api/router_routes_cloud.go@@ -74,8 +74,6 @@ func (r *Router) registerHostedRoutes(hostedSignupHandlers *HostedSignupHandlersif r.licenseHandlers != nil {// Self-hosted commercial checkout handoff: mint a signed return token and redirect into Pulse Account.r.mux.HandleFunc("GET /auth/license-purchase-start", RequireAuth(routerConfig, r.licenseHandlers.HandleCheckoutStart))- // Hosted trial signup callback: signed token activation flow for self-hosted Pulse Pro trials.- r.mux.HandleFunc("/auth/trial-activate", r.licenseHandlers.HandleTrialActivation)// Self-hosted commercial checkout return: complete purchase activation without manual key entry.r.mux.HandleFunc("/auth/license-purchase-activate", r.licenseHandlers.HandleCheckoutActivation)}diff --git a/internal/api/trial_handlers_test.go b/internal/api/trial_handlers_test.goindex fcbd2ade0a..b0242d6967 100644--- a/internal/api/trial_handlers_test.go+++ b/internal/api/trial_handlers_test.go@@ -5,10 +5,8 @@ import ("crypto/ed25519""encoding/base64""encoding/json"- "errors""net/http""net/http/httptest"- "net/url""os""path/filepath""strings"@@ -22,18 +20,6 @@ import (pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing")-func issueTrialSignupInitiationToken(t *testing.T, h *LicenseHandlers, orgID, returnURL string) string {- t.Helper()- if h == nil || h.trialInitiations == nil {- t.Fatal("trial initiation store is not configured")- }- token, err := h.trialInitiations.issue(orgID, returnURL, time.Now().UTC().Add(trialSignupInitiationTTL))- if err != nil {- t.Fatalf("issue trial initiation token: %v", err)- }- return token-}-func issueTrialEntitlementLease(t *testing.T, priv ed25519.PrivateKey, orgID, instanceHost, email string, now time.Time) string {t.Helper()trialState := pkglicensing.BuildTrialBillingState(now.UTC(), license.TierFeatures[license.TierPro])@@ -60,21 +46,6 @@ func issueTrialEntitlementLease(t *testing.T, priv ed25519.PrivateKey, orgID, inreturn token}-func hostedTrialRedemptionWithLease(lease string) *hostedTrialRedemptionResponse {- return &hostedTrialRedemptionResponse{- EntitlementJWT: lease,- EntitlementRefreshToken: "refresh_test_token",- }-}--func issueTrialRedemptionResponse(t *testing.T, priv ed25519.PrivateKey, orgID, instanceHost, email string, now time.Time) *hostedTrialRedemptionResponse {- t.Helper()- return &hostedTrialRedemptionResponse{- EntitlementJWT: issueTrialEntitlementLease(t, priv, orgID, instanceHost, email, now),- EntitlementRefreshToken: "etr_test_" + orgID,- }-}-func TestTrialStartRoute_RetiredFromSelfHostedRouter(t *testing.T) {rawToken := "trial-start-retired-token-123.12345678"record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsWrite}, nil)@@ -139,401 +110,6 @@ func TestTrialEntitlements_TrialDaysRemainingFromBillingState(t *testing.T) {}}-func TestTrialActivation_SignedTokenStartsTrial(t *testing.T) {- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- h := NewLicenseHandlers(mtp, false)- pub, priv, err := ed25519.GenerateKey(nil)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))- h.trialRedeemer = func(string) (*hostedTrialRedemptionResponse, error) {- return issueTrialRedemptionResponse(t, priv, "default", "pulse.example.com", "[email protected]", time.Now()), nil- }- returnURL := "https://pulse.example.com/auth/trial-activate"- instanceToken := issueTrialSignupInitiationToken(t, h, "default", returnURL)-- token, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken: %v", err)- }-- req := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token), nil)- req.Host = "pulse.example.com"- rec := httptest.NewRecorder()- h.HandleTrialActivation(rec, req)-- if rec.Code != http.StatusTemporaryRedirect {- t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusTemporaryRedirect, rec.Body.String())- }- if got := rec.Header().Get("Location"); got != "/settings/system-pro?trial=activated" {- t.Fatalf("redirect=%q, want %q", got, "/settings/system-pro?trial=activated")- }-- store := config.NewFileBillingStore(baseDir)- state, err := store.GetBillingState("default")- if err != nil {- t.Fatalf("GetBillingState: %v", err)- }- if state == nil || state.SubscriptionState != entitlements.SubStateTrial {- t.Fatalf("subscription_state=%q, want %q", state.SubscriptionState, entitlements.SubStateTrial)- }- if strings.TrimSpace(state.EntitlementJWT) == "" {- t.Fatal("expected entitlement_jwt to be stored")- }-- rawData, err := os.ReadFile(filepath.Join(baseDir, "billing.json"))- if err != nil {- t.Fatalf("ReadFile(billing.json): %v", err)- }- var rawState entitlements.BillingState- if err := json.Unmarshal(rawData, &rawState); err != nil {- t.Fatalf("Unmarshal(raw billing.json): %v", err)- }- if strings.TrimSpace(rawState.EntitlementJWT) == "" {- t.Fatal("expected entitlement_jwt ciphertext to be persisted")- }- if rawState.EntitlementJWT == state.EntitlementJWT {- t.Fatal("expected entitlement_jwt to be encrypted at rest")- }- if strings.TrimSpace(rawState.EntitlementRefreshToken) == "" {- t.Fatal("expected entitlement_refresh_token ciphertext to be persisted")- }- if rawState.EntitlementRefreshToken == "etr_test_default" {- t.Fatal("expected entitlement_refresh_token to be encrypted at rest")- }- if rawState.SubscriptionState != "" {- t.Fatalf("raw subscription_state=%q, want empty", rawState.SubscriptionState)- }- if rawState.PlanVersion != "" {- t.Fatalf("raw plan_version=%q, want empty", rawState.PlanVersion)- }- if len(rawState.Capabilities) != 0 {- t.Fatalf("raw capabilities=%v, want empty", rawState.Capabilities)- }- if len(rawState.Limits) != 0 {- t.Fatalf("raw limits=%v, want empty", rawState.Limits)- }- if rawState.TrialStartedAt == nil {- t.Fatal("expected raw trial_started_at to be preserved")- }- if rawState.TrialEndsAt != nil {- t.Fatalf("raw trial_ends_at=%v, want nil", rawState.TrialEndsAt)- }-}--func TestTrialActivation_ReplayTokenRejected(t *testing.T) {- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- h := NewLicenseHandlers(mtp, false)- pub, priv, err := ed25519.GenerateKey(nil)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))- h.trialRedeemer = func(string) (*hostedTrialRedemptionResponse, error) {- return issueTrialRedemptionResponse(t, priv, "default", "pulse.example.com", "[email protected]", time.Now()), nil- }- returnURL := "https://pulse.example.com/auth/trial-activate"- instanceToken := issueTrialSignupInitiationToken(t, h, "default", returnURL)-- token, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken: %v", err)- }-- firstReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token), nil)- firstReq.Host = "pulse.example.com"- firstRec := httptest.NewRecorder()- h.HandleTrialActivation(firstRec, firstReq)- if firstRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("first status=%d, want %d", firstRec.Code, http.StatusTemporaryRedirect)- }-- replayReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token), nil)- replayReq.Host = "pulse.example.com"- replayRec := httptest.NewRecorder()- h.HandleTrialActivation(replayRec, replayReq)-- if replayRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("replay status=%d, want %d", replayRec.Code, http.StatusTemporaryRedirect)- }- if got := replayRec.Header().Get("Location"); got != "/settings/system-pro?trial=replayed" {- t.Fatalf("replay redirect=%q, want %q", got, "/settings/system-pro?trial=replayed")- }-}--func TestTrialActivation_ReissuedTokenForSameSessionRejected(t *testing.T) {- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- h := NewLicenseHandlers(mtp, false)- pub, priv, err := ed25519.GenerateKey(nil)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))- h.trialRedeemer = func(string) (*hostedTrialRedemptionResponse, error) {- return issueTrialRedemptionResponse(t, priv, "default", "pulse.example.com", "[email protected]", time.Now()), nil- }- returnURL := "https://pulse.example.com/auth/trial-activate"- instanceToken := issueTrialSignupInitiationToken(t, h, "default", returnURL)-- expiresAt := jwt.NewNumericDate(time.Now().Add(10 * time.Minute))- firstToken, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- Subject: "cs_same_session",- ExpiresAt: expiresAt,- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken(first): %v", err)- }- secondToken, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- Subject: "cs_same_session",- ExpiresAt: expiresAt,- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken(second): %v", err)- }- if firstToken == secondToken {- t.Fatalf("expected distinct signed tokens for same session subject")- }-- firstReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(firstToken), nil)- firstReq.Host = "pulse.example.com"- firstRec := httptest.NewRecorder()- h.HandleTrialActivation(firstRec, firstReq)- if firstRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("first status=%d, want %d", firstRec.Code, http.StatusTemporaryRedirect)- }-- secondReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(secondToken), nil)- secondReq.Host = "pulse.example.com"- secondRec := httptest.NewRecorder()- h.HandleTrialActivation(secondRec, secondReq)-- if secondRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("second status=%d, want %d", secondRec.Code, http.StatusTemporaryRedirect)- }- if got := secondRec.Header().Get("Location"); got != "/settings/system-pro?trial=replayed" {- t.Fatalf("second redirect=%q, want %q", got, "/settings/system-pro?trial=replayed")- }-}--func TestTrialActivation_RequiresPendingInitiationToken(t *testing.T) {- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- h := NewLicenseHandlers(mtp, false)-- pub, priv, err := ed25519.GenerateKey(nil)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))-- token, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: "tsi_missing",- ReturnURL: "https://pulse.example.com/auth/trial-activate",- RegisteredClaims: jwt.RegisteredClaims{- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken: %v", err)- }-- req := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token), nil)- req.Host = "pulse.example.com"- rec := httptest.NewRecorder()- h.HandleTrialActivation(rec, req)-- if rec.Code != http.StatusTemporaryRedirect {- t.Fatalf("status=%d, want %d", rec.Code, http.StatusTemporaryRedirect)- }- if got := rec.Header().Get("Location"); got != "/settings/system-pro?trial=invalid" {- t.Fatalf("redirect=%q, want %q", got, "/settings/system-pro?trial=invalid")- }-}--func TestTrialActivation_ConsumedInitiationTokenCannotBeReused(t *testing.T) {- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- h := NewLicenseHandlers(mtp, false)- pub, priv, err := ed25519.GenerateKey(nil)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))- h.trialRedeemer = func(string) (*hostedTrialRedemptionResponse, error) {- return issueTrialRedemptionResponse(t, priv, "default", "pulse.example.com", "[email protected]", time.Now()), nil- }-- returnURL := "https://pulse.example.com/auth/trial-activate"- instanceToken := issueTrialSignupInitiationToken(t, h, "default", returnURL)-- firstToken, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- Subject: "cs_first",- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken(first): %v", err)- }-- firstReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(firstToken), nil)- firstReq.Host = "pulse.example.com"- firstRec := httptest.NewRecorder()- h.HandleTrialActivation(firstRec, firstReq)- if firstRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("first status=%d, want %d", firstRec.Code, http.StatusTemporaryRedirect)- }- if got := firstRec.Header().Get("Location"); got != "/settings/system-pro?trial=activated" {- t.Fatalf("first redirect=%q, want %q", got, "/settings/system-pro?trial=activated")- }-- billingStore := config.NewFileBillingStore(baseDir)- if err := billingStore.SaveBillingState("default", &entitlements.BillingState{}); err != nil {- t.Fatalf("SaveBillingState(reset): %v", err)- }-- secondToken, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- Subject: "cs_second",- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken(second): %v", err)- }-- secondReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(secondToken), nil)- secondReq.Host = "pulse.example.com"- secondRec := httptest.NewRecorder()- h.HandleTrialActivation(secondRec, secondReq)-- if secondRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("second status=%d, want %d", secondRec.Code, http.StatusTemporaryRedirect)- }- if got := secondRec.Header().Get("Location"); got != "/settings/system-pro?trial=invalid" {- t.Fatalf("second redirect=%q, want %q", got, "/settings/system-pro?trial=invalid")- }-}--func TestTrialActivation_RedeemerFailureReturnsUnavailableAndAllowsRetry(t *testing.T) {- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- h := NewLicenseHandlers(mtp, false)-- pub, priv, err := ed25519.GenerateKey(nil)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))-- returnURL := "https://pulse.example.com/auth/trial-activate"- instanceToken := issueTrialSignupInitiationToken(t, h, "default", returnURL)- token, err := pkglicensing.SignTrialActivationToken(priv, pkglicensing.TrialActivationClaims{- OrgID: "default",- Email: "[email protected]",- InstanceHost: "pulse.example.com",- InstanceToken: instanceToken,- ReturnURL: returnURL,- RegisteredClaims: jwt.RegisteredClaims{- Subject: "cs_retryable_redeem",- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),- },- })- if err != nil {- t.Fatalf("SignTrialActivationToken: %v", err)- }-- h.trialRedeemer = func(string) (*hostedTrialRedemptionResponse, error) {- return nil, errors.New("control plane unavailable")- }-- firstReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token), nil)- firstReq.Host = "pulse.example.com"- firstRec := httptest.NewRecorder()- h.HandleTrialActivation(firstRec, firstReq)-- if firstRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("first status=%d, want %d", firstRec.Code, http.StatusTemporaryRedirect)- }- if got := firstRec.Header().Get("Location"); got != "/settings/system-pro?trial=unavailable" {- t.Fatalf("first redirect=%q, want %q", got, "/settings/system-pro?trial=unavailable")- }-- store := config.NewFileBillingStore(baseDir)- state, err := store.GetBillingState("default")- if err != nil {- t.Fatalf("GetBillingState: %v", err)- }- if state != nil && state.SubscriptionState == entitlements.SubStateTrial {- t.Fatalf("trial state should not be written when redemption fails")- }-- h.trialRedeemer = func(string) (*hostedTrialRedemptionResponse, error) {- return issueTrialRedemptionResponse(t, priv, "default", "pulse.example.com", "[email protected]", time.Now()), nil- }-- secondReq := httptest.NewRequest(http.MethodGet, "/auth/trial-activate?token="+url.QueryEscape(token), nil)- secondReq.Host = "pulse.example.com"- secondRec := httptest.NewRecorder()- h.HandleTrialActivation(secondRec, secondReq)-- if secondRec.Code != http.StatusTemporaryRedirect {- t.Fatalf("second status=%d, want %d", secondRec.Code, http.StatusTemporaryRedirect)- }- if got := secondRec.Header().Get("Location"); got != "/settings/system-pro?trial=activated" {- t.Fatalf("second redirect=%q, want %q", got, "/settings/system-pro?trial=activated")- }-}-func TestRefreshHostedEntitlementLeaseOnce_RenewsLeaseAndKeepsLeaseOnlyState(t *testing.T) {baseDir := t.TempDir()mtp := config.NewMultiTenantPersistence(baseDir)diff --git a/internal/api/trial_signup_initiation_store.go b/internal/api/trial_signup_initiation_store.godeleted file mode 100644index 9aec9e0abc..0000000000--- a/internal/api/trial_signup_initiation_store.go+++ /dev/null@@ -1,278 +0,0 @@-package api--import (- "crypto/rand"- "crypto/sha256"- "database/sql"- "encoding/base64"- "encoding/hex"- "fmt"- "net/url"- "os"- "path/filepath"- "strings"- "sync"- "time"-- _ "modernc.org/sqlite"-)--const trialSignupInitiationTTL = 2 * time.Hour--type trialSignupInitiationStore struct {- once sync.Once- db *sql.DB- mu sync.Mutex-- configDir string- initErr error-}--func (s *trialSignupInitiationStore) init() {- s.once.Do(func() {- dir := filepath.Clean(s.configDir)- if strings.TrimSpace(dir) == "" {- s.initErr = fmt.Errorf("configDir is required")- return- }- secretsDir := filepath.Join(dir, "secrets")- if err := os.MkdirAll(secretsDir, handoffPrivateDirPerm); err != nil {- s.initErr = fmt.Errorf("create trial signup secrets dir: %w", err)- return- }- if err := os.Chmod(secretsDir, handoffPrivateDirPerm); err != nil {- s.initErr = fmt.Errorf("chmod trial signup secrets dir: %w", err)- return- }-- dbPath := filepath.Join(secretsDir, "trial_signup_state.db")- dsn := dbPath + "?" + url.Values{- "_pragma": []string{- "busy_timeout(30000)",- "journal_mode(WAL)",- "synchronous(NORMAL)",- },- }.Encode()-- db, err := sql.Open("sqlite", dsn)- if err != nil {- s.initErr = fmt.Errorf("open trial signup initiation db: %w", err)- return- }- db.SetMaxOpenConns(1)- db.SetMaxIdleConns(1)- db.SetConnMaxLifetime(0)-- schema := `- CREATE TABLE IF NOT EXISTS trial_signup_initiations (- token_hash TEXT PRIMARY KEY,- org_id TEXT NOT NULL,- return_url TEXT NOT NULL,- expires_at INTEGER NOT NULL- );- CREATE INDEX IF NOT EXISTS idx_trial_signup_initiations_expires_at ON trial_signup_initiations(expires_at);- `- if _, err := db.Exec(schema); err != nil {- _ = db.Close()- s.initErr = fmt.Errorf("init trial signup initiation schema: %w", err)- return- }- hasReturnURL, err := trialSignupInitiationTableHasColumn(db, "trial_signup_initiations", "return_url")- if err != nil {- _ = db.Close()- s.initErr = fmt.Errorf("check trial signup initiation schema for return_url: %w", err)- return- }- if !hasReturnURL {- if _, err := db.Exec(`ALTER TABLE trial_signup_initiations ADD COLUMN return_url TEXT NOT NULL DEFAULT ''`); err != nil {- _ = db.Close()- s.initErr = fmt.Errorf("migrate trial signup initiation schema: add return_url: %w", err)- return- }- }- for _, path := range []string{dbPath, dbPath + "-wal", dbPath + "-shm"} {- if err := hardenPrivateFile(path, handoffPrivateFilePerm); err != nil {- _ = db.Close()- s.initErr = fmt.Errorf("harden trial signup initiation file permissions: %w", err)- return- }- }- s.db = db- })-}--func (s *trialSignupInitiationStore) issue(orgID, returnURL string, expiresAt time.Time) (string, error) {- s.init()- if s.initErr != nil {- return "", s.initErr- }- if s.db == nil {- return "", fmt.Errorf("trial signup initiation store not initialized")- }- orgID = normalizeTrialSignupInitiationOrgID(orgID)- returnURL = strings.TrimSpace(returnURL)- if returnURL == "" {- return "", fmt.Errorf("return_url is required")- }- expiresAt = expiresAt.UTC()- if expiresAt.IsZero() {- expiresAt = time.Now().UTC().Add(trialSignupInitiationTTL)- }-- rawToken, err := randomTrialSignupInitiationToken()- if err != nil {- return "", err- }- tokenHash := hashTrialSignupInitiationToken(rawToken)-- s.mu.Lock()- defer s.mu.Unlock()-- if err := s.cleanupExpiredLocked(time.Now().UTC()); err != nil {- return "", err- }- if _, err := s.db.Exec(- `INSERT INTO trial_signup_initiations (token_hash, org_id, return_url, expires_at) VALUES (?, ?, ?, ?)`,- tokenHash,- orgID,- returnURL,- expiresAt.Unix(),- ); err != nil {- return "", fmt.Errorf("insert trial signup initiation: %w", err)- }- return rawToken, nil-}--func (s *trialSignupInitiationStore) validate(orgID, returnURL, rawToken string, now time.Time) (bool, error) {- s.init()- if s.initErr != nil {- return false, s.initErr- }- if s.db == nil {- return false, fmt.Errorf("trial signup initiation store not initialized")- }- orgID = normalizeTrialSignupInitiationOrgID(orgID)- returnURL = strings.TrimSpace(returnURL)- tokenHash := hashTrialSignupInitiationToken(rawToken)- if tokenHash == "" {- return false, nil- }- now = now.UTC()-- s.mu.Lock()- defer s.mu.Unlock()-- if err := s.cleanupExpiredLocked(now); err != nil {- return false, err- }- var expiresAt int64- err := s.db.QueryRow(- `SELECT expires_at FROM trial_signup_initiations WHERE token_hash = ? AND org_id = ? AND return_url = ?`,- tokenHash,- orgID,- returnURL,- ).Scan(&expiresAt)- if err == nil {- return expiresAt > now.Unix(), nil- }- if err == sql.ErrNoRows {- return false, nil- }- return false, fmt.Errorf("lookup trial signup initiation: %w", err)-}--func (s *trialSignupInitiationStore) consume(orgID, returnURL, rawToken string, now time.Time) (bool, error) {- s.init()- if s.initErr != nil {- return false, s.initErr- }- if s.db == nil {- return false, fmt.Errorf("trial signup initiation store not initialized")- }- orgID = normalizeTrialSignupInitiationOrgID(orgID)- returnURL = strings.TrimSpace(returnURL)- tokenHash := hashTrialSignupInitiationToken(rawToken)- if tokenHash == "" {- return false, nil- }- now = now.UTC()-- s.mu.Lock()- defer s.mu.Unlock()-- if err := s.cleanupExpiredLocked(now); err != nil {- return false, err- }- res, err := s.db.Exec(- `DELETE FROM trial_signup_initiations WHERE token_hash = ? AND org_id = ? AND return_url = ? AND expires_at > ?`,- tokenHash,- orgID,- returnURL,- now.Unix(),- )- if err != nil {- return false, fmt.Errorf("consume trial signup initiation: %w", err)- }- affected, err := res.RowsAffected()- if err != nil {- return false, fmt.Errorf("trial signup initiation rows affected: %w", err)- }- return affected > 0, nil-}--func (s *trialSignupInitiationStore) cleanupExpiredLocked(now time.Time) error {- if _, err := s.db.Exec(`DELETE FROM trial_signup_initiations WHERE expires_at <= ?`, now.UTC().Unix()); err != nil {- return fmt.Errorf("cleanup trial signup initiations: %w", err)- }- return nil-}--func normalizeTrialSignupInitiationOrgID(orgID string) string {- orgID = strings.TrimSpace(orgID)- if orgID == "" {- return "default"- }- return orgID-}--func hashTrialSignupInitiationToken(raw string) string {- raw = strings.TrimSpace(raw)- if raw == "" {- return ""- }- sum := sha256.Sum256([]byte(raw))- return hex.EncodeToString(sum[:])-}--func randomTrialSignupInitiationToken() (string, error) {- buf := make([]byte, 32)- if _, err := rand.Read(buf); err != nil {- return "", fmt.Errorf("generate trial signup initiation token: %w", err)- }- return "tsi1_" + base64.RawURLEncoding.EncodeToString(buf), nil-}--func trialSignupInitiationTableHasColumn(db *sql.DB, tableName, columnName string) (bool, error) {- rows, err := db.Query(`PRAGMA table_info(` + tableName + `)`)- if err != nil {- return false, err- }- defer rows.Close()-- var cid int- var name, dataType string- var notNull, pk int- var defaultValue any- for rows.Next() {- if err := rows.Scan(&cid, &name, &dataType, ¬Null, &defaultValue, &pk); err != nil {- return false, err- }- if strings.EqualFold(strings.TrimSpace(name), strings.TrimSpace(columnName)) {- return true, nil- }- }- if err := rows.Err(); err != nil {- return false, err- }- return false, nil-}diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.pyindex fa57a081ef..ec9d8a7924 100644--- a/scripts/release_control/canonical_completion_guard_test.py+++ b/scripts/release_control/canonical_completion_guard_test.py@@ -3792,7 +3792,7 @@ index 1111111..2222222 100644[{"id": "hosted-trial-activation",- "label": "hosted trial activation proof",+ "label": "hosted entitlement lease signing proof","touched_runtime_files": ["pkg/licensing/trial_activation.go"],"allow_same_subsystem_tests": False,"test_prefixes": [],diff --git a/scripts/release_control/release_promotion_policy_test.py b/scripts/release_control/release_promotion_policy_test.pyindex 01381d927e..9cf1f46dad 100644--- a/scripts/release_control/release_promotion_policy_test.py+++ b/scripts/release_control/release_promotion_policy_test.py@@ -163,8 +163,9 @@ class ReleasePromotionPolicyTest(unittest.TestCase):self.assertIn("manual reinstall or other explicit trust migration", normalize_ws(upgrade_guide))self.assertIn("### License and Entitlements", upgrade_guide)self.assertNotIn("### License, Trial, and Entitlements", upgrade_guide)- self.assertIn("does not expose a general in-app trial or hosted AI quickstart", normalize_ws(upgrade_guide))+ self.assertIn("does not expose a general in-app trial, trial-return callback, or hosted AI quickstart", normalize_ws(upgrade_guide))self.assertNotIn("`POST /api/license/trial/start`", upgrade_guide)+ self.assertNotIn("signed activation token to `/auth/trial-activate`", upgrade_guide)self.assertNotIn("25 hosted Patrol", upgrade_guide)if current_version == "6.0.0":self.assertIn("docs/releases/RELEASE_NOTES_v6.md", upgrade_guide)diff --git a/tests/integration/scripts/trial-signup-contract.sh b/tests/integration/scripts/trial-signup-contract.shindex 9fb6121bb3..7c4bb18593 100755--- a/tests/integration/scripts/trial-signup-contract.sh+++ b/tests/integration/scripts/trial-signup-contract.sh@@ -1,9 +1,9 @@#!/usr/bin/env bashset -euo pipefail-# Retired trial-start contract probe for self-hosted Pulse.+# Retired trial-acquisition contract probe for self-hosted Pulse.# This verifies ordinary self-hosted v6 runtimes do not expose in-app trial-# acquisition. Signed activation handoffs still use /auth/trial-activate.+# acquisition or the retired trial-return callback.PULSE_BASE_URL="${PULSE_BASE_URL:-http://127.0.0.1:7655}"PULSE_E2E_USERNAME="${PULSE_E2E_USERNAME:-admin}"@@ -27,6 +27,7 @@ login_body="${tmp_dir}/login.json"entitlements_before_body="${tmp_dir}/entitlements_before.json"entitlements_after_body="${tmp_dir}/entitlements_after.json"trial_start_body="${tmp_dir}/trial_start.json"+trial_activate_body="${tmp_dir}/trial_activate.txt"wait_for_http() {local url="$1"@@ -53,10 +54,10 @@ assert_code() {fi}-echo "[1/5] Waiting for Pulse API readiness at ${PULSE_BASE_URL}"+echo "[1/6] Waiting for Pulse API readiness at ${PULSE_BASE_URL}"wait_for_http "${PULSE_BASE_URL}/api/login"-echo "[2/5] Login with configured test credentials"+echo "[2/6] Login with configured test credentials"login_code="$(curl -sS -o "${login_body}" -w '%{http_code}' \-c "${cookies_file}" \@@ -72,7 +73,7 @@ if [ -z "${csrf_token}" ]; thenexit 1fi-echo "[3/5] Capture entitlements before retired route probe"+echo "[3/6] Capture entitlements before retired route probe"entitlements_before_code="$(curl -sS -o "${entitlements_before_body}" -w '%{http_code}' \-b "${cookies_file}" \@@ -80,7 +81,7 @@ entitlements_before_code="$()"assert_code "200" "${entitlements_before_code}" "GET /api/license/entitlements"-echo "[4/5] Verify ordinary self-hosted trial start route is not exposed"+echo "[4/6] Verify ordinary self-hosted trial start route is not exposed"trial_start_code="$(curl -sS -o "${trial_start_body}" -w '%{http_code}' \-X POST \@@ -95,7 +96,15 @@ if jq -e '.code == "trial_signup_required" or .code == "trial_rate_limited"' "${exit 1fi-echo "[5/5] Verify entitlements remain unchanged"+echo "[5/6] Verify retired self-hosted trial activation callback is not exposed"+trial_activate_code="$(+ curl -sS -o "${trial_activate_body}" -w '%{http_code}' \+ -b "${cookies_file}" \+ "${PULSE_BASE_URL}/auth/trial-activate?token=retired_probe"+)"+assert_code "404" "${trial_activate_code}" "GET /auth/trial-activate"++echo "[6/6] Verify entitlements remain unchanged"entitlements_after_code="$(curl -sS -o "${entitlements_after_body}" -w '%{http_code}' \-b "${cookies_file}" \@@ -112,8 +121,9 @@ if [ "${before_summary}" != "${after_summary}" ]; thenexit 1fi-echo "PASS: self-hosted trial-start route is retired"+echo "PASS: self-hosted trial acquisition routes are retired"echo " login_code=${login_code}"echo " entitlements_before_code=${entitlements_before_code}"echo " trial_start_code=${trial_start_code}"+echo " trial_activate_code=${trial_activate_code}"echo " entitlements_after_code=${entitlements_after_code}"diff --git a/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts b/tests/integration/tests/53-demo-mode-commercial-boundary.spec.tsindex b1612ac0a0..940fbd0a8a 100644--- a/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts+++ b/tests/integration/tests/53-demo-mode-commercial-boundary.spec.ts@@ -145,7 +145,6 @@ async function probeDemoCommercialBoundaryFromBrowser(vmwareDraftPreview: await probe('/api/vmware/connections/preview', postEmptyJSON),vmwareSavedPreview: await probe('/api/vmware/connections/conn-1/preview', postEmptyJSON),checkoutStart: await probe('/auth/license-purchase-start'),- trialActivate: await probe('/auth/trial-activate'),};});}@@ -405,7 +404,6 @@ base.describe('Demo mode commercial boundary', () => {await hiddenNotFound('**/api/vmware/connections/preview');await hiddenNotFound('**/api/vmware/connections/*/preview');await hiddenNotFound('**/auth/license-purchase-start**');- await hiddenNotFound('**/auth/trial-activate');await page.goto('/settings/infrastructure/install', { waitUntil: 'domcontentloaded' });@@ -433,7 +431,7 @@ base.describe('Managed demo runtime commercial boundary', () => {const hiddenCommercialRequests = trackBrowserRequests(page,- /\/api\/license\/(?!runtime-capabilities)|\/api\/admin\/orgs\/[^/]+\/billing-state|\/api\/upgrade-metrics\/|\/auth\/license-purchase-start|\/auth\/trial-activate/,+ /\/api\/license\/(?!runtime-capabilities)|\/api\/admin\/orgs\/[^/]+\/billing-state|\/api\/upgrade-metrics\/|\/auth\/license-purchase-start/,);try {await page.goto('/settings/system/billing/usage?details=counting-rules', {