Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Stabilize commercial activation continuity ownership

rcourtman5567fd1b8042
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 29b6ce495e..1d2c0d5bf6 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -218,6 +218,10 @@ management, and fleet control surfaces.
continuity, use those billing reads to restart pending continuity
reconciliation, or reinterpret continuity-verification payloads as a real
`0 / limit` monitored-system state.
+ When the commercial reconciler captures the floor, lifecycle-adjacent
+ code must treat the resulting activation-state callback as commercial
+ ownership cleanup only, not as install inventory proof or fleet enrollment
+ state.
## Forbidden Paths
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index c705059db7..470c7801cb 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1306,6 +1306,15 @@ also stay side-effect free with respect to the reconciler lifecycle itself:
they may observe pending continuity state, but only activation-state
transitions such as activate, restore, grant refresh, and clear/revocation may
bootstrap or tear down the pending-floor reconcile loop.
+Continuity capture is itself an activation-state mutation: after the reconciler
+persists the one-time floor, the service callback must publish the updated
+activation state so ownership can cancel the pending loop without making
+ordinary billing reads restart or stop it.
+When save-time monitored-system admission fails with a commercial denial, the
+structured API error must preserve the canonical `monitored_system_preview`
+object through `frontend-modern/src/utils/apiClient.ts` and
+`frontend-modern/src/api/responseUtils.ts` so platform settings can render the
+same current/projected verdict instead of falling back to generic license copy.
That same configured-path contract now also has an explicit shared owner for
manual auth env files: `internal/api/auth_env_path.go` must remain the only
place that derives `.env` from configured runtime paths, and neighboring
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index d24089d46f..98e3b2c78a 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -853,6 +853,14 @@ settled. The reconcile loop itself is activation-state-owned as well:
activation, restore, grant refresh, and revocation/clear transitions may
start or stop continuity reconciliation, but ordinary billing reads must stay
observer-only and must not bootstrap that background work on demand.
+The continuity capture path must notify through that same activation-state
+ownership boundary after it persists the grandfather floor, so the reconciler
+can stop because state changed rather than because a later status or
+entitlements read happened to observe the captured floor.
+Save-time monitored-system commercial denials must carry the canonical
+`monitored_system_preview` object through the shared frontend API error path,
+so TrueNAS and VMware settings render the same helper-owned projected-usage
+explanation after a rejected save that they render after an explicit preview.
That continuity rule cannot depend on webhook metadata being perfect. The
canonical Stripe price-to-plan lookup in `pkg/licensing/features.go` and
`pkg/licensing/stripe_subscription.go` must recognize the still-renewing
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 28a288ca0f..e6b9861a96 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -181,6 +181,10 @@ querying, and the operator-facing storage health presentation layer.
pending grandfather floor, use those reads to restart continuity
reconciliation, or collapse continuity-verification payloads into a real
`0 / limit` monitored-system reading.
+ When the commercial reconciler captures the floor, storage and recovery
+ must treat the resulting activation-state callback as commercial ownership
+ cleanup only, not as protected-inventory proof or recovery entitlement
+ state.
## Forbidden Paths
diff --git a/frontend-modern/src/api/__tests__/responseUtils.test.ts b/frontend-modern/src/api/__tests__/responseUtils.test.ts
index 76bc239034..29b6176216 100644
--- a/frontend-modern/src/api/__tests__/responseUtils.test.ts
+++ b/frontend-modern/src/api/__tests__/responseUtils.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
-import { apiErrorCode, apiErrorDetailField } from '@/api/responseUtils';
+import {
+ apiErrorCode,
+ apiErrorDetailField,
+ apiErrorMonitoredSystemPreview,
+} from '@/api/responseUtils';
describe('responseUtils structured API errors', () => {
it('reads canonical code and detail fields from shared API errors', () => {
@@ -17,4 +21,40 @@ describe('responseUtils structured API errors', () => {
'VMware vCenter 6.7 is below the supported VI JSON release floor',
);
});
+
+ it('normalizes monitored-system preview payloads from shared API errors', () => {
+ const error = {
+ monitored_system_preview: {
+ current_count: 5,
+ projected_count: 6,
+ additional_count: 1,
+ limit: 5,
+ would_exceed_limit: true,
+ effect: 'creates_new',
+ current_systems: [],
+ projected_systems: [
+ {
+ name: 'backup',
+ type: 'truenas-system',
+ status: 'online',
+ source: 'truenas',
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ },
+ };
+
+ expect(apiErrorMonitoredSystemPreview(error)).toMatchObject({
+ current_count: 5,
+ projected_count: 6,
+ would_exceed_limit: true,
+ projected_systems: [
+ expect.objectContaining({
+ name: 'backup',
+ source: 'truenas',
+ }),
+ ],
+ });
+ });
});
diff --git a/frontend-modern/src/api/responseUtils.ts b/frontend-modern/src/api/responseUtils.ts
index 2e3e7b8d14..fa3f0b96ed 100644
--- a/frontend-modern/src/api/responseUtils.ts
+++ b/frontend-modern/src/api/responseUtils.ts
@@ -1,3 +1,9 @@
+import {
+ normalizeMonitoredSystemLedgerPreviewResponse,
+ type MonitoredSystemLedgerPreviewResponse,
+ type MonitoredSystemLedgerRawPreviewResponse,
+} from './monitoredSystemLedger';
+
type APIErrorPayload = {
error?: unknown;
message?: unknown;
@@ -8,6 +14,7 @@ type APIErrorLike = {
code?: unknown;
detail?: unknown;
details?: unknown;
+ monitored_system_preview?: unknown;
};
type APIResponseLike = {
@@ -243,6 +250,23 @@ export function apiErrorDetailField(error: unknown, field: string): string | nul
return details[field] ?? null;
}
+export function apiErrorMonitoredSystemPreview(
+ error: unknown,
+): MonitoredSystemLedgerPreviewResponse | null {
+ if (!error || typeof error !== 'object') {
+ return null;
+ }
+
+ const rawPreview = (error as APIErrorLike).monitored_system_preview;
+ if (!rawPreview || typeof rawPreview !== 'object') {
+ return null;
+ }
+
+ return normalizeMonitoredSystemLedgerPreviewResponse(
+ rawPreview as MonitoredSystemLedgerRawPreviewResponse,
+ );
+}
+
export function isAPIErrorStatus(error: unknown, expectedStatus: number): boolean {
return apiErrorStatus(error) === expectedStatus;
}
@@ -384,12 +408,11 @@ export function normalizeStructuredAPIError(
};
}
-export function promoteLegacyAlertIdentifier<
- T extends { alertIdentifier?: string } & object,
->(record: T & { alert_identifier?: string }): T {
+export function promoteLegacyAlertIdentifier<T extends { alertIdentifier?: string } & object>(
+ record: T & { alert_identifier?: string },
+): T {
const alertIdentifier =
- optionalTrimmedString(record.alertIdentifier) ??
- optionalTrimmedString(record.alert_identifier);
+ optionalTrimmedString(record.alertIdentifier) ?? optionalTrimmedString(record.alert_identifier);
const { alert_identifier: _alertIdentifier, ...rest } = record;
return alertIdentifier ? ({ ...rest, alertIdentifier } as T) : (rest as T);
}
diff --git a/frontend-modern/src/utils/__tests__/apiClient.error.test.ts b/frontend-modern/src/utils/__tests__/apiClient.error.test.ts
index 4389b4dff7..b062a7aad8 100644
--- a/frontend-modern/src/utils/__tests__/apiClient.error.test.ts
+++ b/frontend-modern/src/utils/__tests__/apiClient.error.test.ts
@@ -51,4 +51,51 @@ describe('apiClient structured error extraction', () => {
},
});
});
+
+ it('preserves monitored-system preview payloads from canonical 402 errors', async () => {
+ const error = await apiErrorFromResponse(
+ new Response(
+ JSON.stringify({
+ error: 'license_required',
+ message: 'Monitored-system limit reached (6/5)',
+ feature: 'max_monitored_systems',
+ monitored_system_preview: {
+ current_count: 5,
+ projected_count: 6,
+ additional_count: 1,
+ limit: 5,
+ would_exceed_limit: true,
+ effect: 'creates_new',
+ current_systems: [],
+ projected_systems: [
+ {
+ name: 'backup',
+ type: 'truenas-system',
+ status: 'online',
+ source: 'truenas',
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ },
+ }),
+ {
+ status: 402,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
+ 'Fallback message',
+ );
+
+ expect(error).toMatchObject({
+ message: 'Monitored-system limit reached (6/5)',
+ status: 402,
+ feature: 'max_monitored_systems',
+ monitored_system_preview: {
+ current_count: 5,
+ projected_count: 6,
+ would_exceed_limit: true,
+ },
+ });
+ });
});
diff --git a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
index d1dccc4f58..8faafc2f5a 100644
--- a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
+++ b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
@@ -67,6 +67,59 @@ describe('apiClient org context', () => {
expect(headers['X-Pulse-Org-ID']).toBe('tenant-ledger');
});
+ it('preserves hosted org context and preview payloads on monitored-system denials', async () => {
+ mockFetch.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ error: 'license_required',
+ message: 'Monitored-system limit reached (6/5)',
+ feature: 'max_monitored_systems',
+ monitored_system_preview: {
+ current_count: 5,
+ projected_count: 6,
+ additional_count: 1,
+ limit: 5,
+ would_exceed_limit: true,
+ effect: 'creates_new',
+ current_systems: [],
+ projected_systems: [
+ {
+ name: 'backup',
+ type: 'truenas-system',
+ status: 'online',
+ source: 'truenas',
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ },
+ }),
+ {
+ status: 402,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
+ );
+
+ setOrgID('tenant-ledger');
+ await expect(
+ apiFetchJSON('/api/truenas/connections', { method: 'POST', body: '{}' }),
+ ).rejects.toMatchObject({
+ message: 'Monitored-system limit reached (6/5)',
+ status: 402,
+ feature: 'max_monitored_systems',
+ monitored_system_preview: {
+ current_count: 5,
+ projected_count: 6,
+ would_exceed_limit: true,
+ },
+ });
+
+ const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
+ const headers = options.headers as Record<string, string>;
+ expect(headers['X-Pulse-Org-ID']).toBe('tenant-ledger');
+ });
+
it('uses default org context when skipOrgContext is enabled', async () => {
mockFetch.mockResolvedValue(new Response('[]', { status: 200 }));
diff --git a/frontend-modern/src/utils/apiClient.ts b/frontend-modern/src/utils/apiClient.ts
index d345c42547..086ba0b413 100644
--- a/frontend-modern/src/utils/apiClient.ts
+++ b/frontend-modern/src/utils/apiClient.ts
@@ -83,6 +83,7 @@ type APIErrorShape = Error & {
detail?: string;
details?: APIErrorDetails;
feature?: string;
+ monitored_system_preview?: unknown;
requiredScope?: string;
upgrade_url?: string;
status?: number;
@@ -117,6 +118,7 @@ async function createAPIErrorFromResponse(
let errorDetail: string | undefined;
let errorDetails: APIErrorDetails | undefined;
let errorFeature: string | undefined;
+ let errorMonitoredSystemPreview: unknown;
let errorRequiredScope: string | undefined;
let errorUpgradeUrl: string | undefined;
try {
@@ -131,6 +133,12 @@ async function createAPIErrorFromResponse(
}
errorCode = sanitizeBoundedText(jsonError.code, MAX_API_ERROR_CODE_LENGTH) ?? undefined;
errorDetails = sanitizeAPIErrorDetails(jsonError.details);
+ if (
+ jsonError.monitored_system_preview &&
+ typeof jsonError.monitored_system_preview === 'object'
+ ) {
+ errorMonitoredSystemPreview = jsonError.monitored_system_preview;
+ }
errorRequiredScope = sanitizeBoundedText(jsonError.requiredScope, 128) ?? undefined;
errorFeature = sanitizeBoundedText(jsonError.feature, 128) ?? undefined;
errorUpgradeUrl = sanitizeBoundedText(jsonError.upgrade_url, 2048) ?? undefined;
@@ -147,7 +155,9 @@ async function createAPIErrorFromResponse(
}
}
- const err = new Error(errorMessage || `Request failed with status ${response.status}`) as APIErrorShape;
+ const err = new Error(
+ errorMessage || `Request failed with status ${response.status}`,
+ ) as APIErrorShape;
err.status = response.status;
if (errorCode) {
err.code = errorCode;
@@ -164,6 +174,9 @@ async function createAPIErrorFromResponse(
if (errorFeature) {
err.feature = errorFeature;
}
+ if (errorMonitoredSystemPreview) {
+ err.monitored_system_preview = errorMonitoredSystemPreview;
+ }
if (errorUpgradeUrl) {
err.upgrade_url = errorUpgradeUrl;
}
diff --git a/internal/api/legacy_grandfather_reconcile.go b/internal/api/legacy_grandfather_reconcile.go
index 35412343f3..be5983b4a5 100644
--- a/internal/api/legacy_grandfather_reconcile.go
+++ b/internal/api/legacy_grandfather_reconcile.go
@@ -43,13 +43,38 @@ func (h *LicenseHandlers) legacyGrandfatherReconcileLoop(orgID string) *legacyGr
return loop
}
+func (h *LicenseHandlers) bindLegacyGrandfatherReconcileOwnership(orgID string, service *licenseService) {
+ if h == nil || service == nil {
+ return
+ }
+
+ orgID = normalizeHostedEntitlementOrgID(orgID)
+ service.SetActivationStateChangeCallback(func(*activationStateModel) {
+ h.syncLegacyGrandfatherReconcileOwnership(orgID, service)
+ })
+}
+
+func (h *LicenseHandlers) syncLegacyGrandfatherReconcileOwnership(orgID string, service *licenseService) {
+ if h == nil {
+ return
+ }
+
+ orgID = normalizeHostedEntitlementOrgID(orgID)
+ if service == nil || !service.NeedsLegacyMonitoredSystemCapture() {
+ h.requestLegacyGrandfatherReconcileLoopStop(orgID)
+ return
+ }
+
+ h.ensureLegacyGrandfatherReconcileLoop(orgID, service)
+}
+
func (h *LicenseHandlers) ensureLegacyGrandfatherReconcileLoop(orgID string, service *licenseService) {
if h == nil || service == nil {
return
}
orgID = normalizeHostedEntitlementOrgID(orgID)
if !service.NeedsLegacyMonitoredSystemCapture() {
- h.stopLegacyGrandfatherReconcileLoop(orgID)
+ h.requestLegacyGrandfatherReconcileLoopStop(orgID)
return
}
@@ -115,6 +140,35 @@ func (h *LicenseHandlers) stopLegacyGrandfatherReconcileLoop(orgID string) {
h.legacyGrandfatherReconcile.Delete(orgID)
}
+func (h *LicenseHandlers) requestLegacyGrandfatherReconcileLoopStop(orgID string) {
+ if h == nil {
+ return
+ }
+ orgID = normalizeHostedEntitlementOrgID(orgID)
+ value, ok := h.legacyGrandfatherReconcile.Load(orgID)
+ if !ok {
+ return
+ }
+ loop, ok := value.(*legacyGrandfatherReconcileLoop)
+ if !ok || loop == nil {
+ h.legacyGrandfatherReconcile.Delete(orgID)
+ return
+ }
+
+ loop.mu.Lock()
+ if !loop.running {
+ loop.mu.Unlock()
+ h.legacyGrandfatherReconcile.Delete(orgID)
+ return
+ }
+ cancel := loop.cancel
+ loop.mu.Unlock()
+
+ if cancel != nil {
+ cancel()
+ }
+}
+
func (h *LicenseHandlers) runLegacyGrandfatherReconcileLoop(
ctx context.Context,
orgID string,
diff --git a/internal/api/licensing_handlers_auto_migrate_test.go b/internal/api/licensing_handlers_auto_migrate_test.go
index caa6fde926..84baf28485 100644
--- a/internal/api/licensing_handlers_auto_migrate_test.go
+++ b/internal/api/licensing_handlers_auto_migrate_test.go
@@ -480,12 +480,22 @@ func TestGetTenantComponents_BackfillsGrandfatherFloorAfterRestoreWhenMonitorArr
}
handlers.SetMonitors(buildGrandfatherFloorMonitor(23), nil)
- svc = handlers.Service(ctx)
- if svc == nil {
- t.Fatal("expected cached service")
- }
- if got := svc.Status().MaxMonitoredSystems; got != 23 {
- t.Fatalf("status.MaxMonitoredSystems=%d, want 23 after late monitor capture", got)
+
+ deadline := time.Now().Add(8 * time.Second)
+ for {
+ loaded, err := persistence.LoadActivationState()
+ if err != nil {
+ t.Fatalf("load activation state: %v", err)
+ }
+ if loaded != nil &&
+ loaded.Continuity.GrandfatheredMaxMonitoredSystems == 23 &&
+ loaded.Continuity.GrandfatheredMonitoredSystemsCapturedAt != 0 {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("expected async grandfather capture after late monitor restore, last activation state=%+v", loaded)
+ }
+ time.Sleep(100 * time.Millisecond)
}
loaded, err := persistence.LoadActivationState()
@@ -501,10 +511,111 @@ func TestGetTenantComponents_BackfillsGrandfatherFloorAfterRestoreWhenMonitorArr
if loaded.Continuity.GrandfatheredMonitoredSystemsCapturedAt == 0 {
t.Fatal("expected captured timestamp after late monitor restore")
}
+ if got := svc.Status().MaxMonitoredSystems; got != 23 {
+ t.Fatalf("status.MaxMonitoredSystems=%d, want 23 after late monitor capture", got)
+ }
handlers.StopAllBackgroundLoops()
}
+func TestBillingReads_DoNotRestartLegacyGrandfatherReconcileLoop(t *testing.T) {
+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
+
+ grantJWT, grantPublicKey, err := pkglicensing.GenerateGrantJWTForTesting(pkglicensing.GrantClaims{
+ LicenseID: "lic_floor_read_only",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ Features: []string{"relay"},
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ Email: "[email protected]",
+ })
+ if err != nil {
+ t.Fatalf("generate grant jwt: %v", err)
+ }
+ pkglicensing.SetPublicKey(grantPublicKey)
+ t.Cleanup(func() { pkglicensing.SetPublicKey(nil) })
+
+ baseDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(baseDir)
+ cp, err := mtp.GetPersistence("default")
+ if err != nil {
+ t.Fatalf("init default persistence: %v", err)
+ }
+ persistence, err := pkglicensing.NewPersistence(cp.GetConfigDir())
+ if err != nil {
+ t.Fatalf("new persistence: %v", err)
+ }
+ if err := persistence.SaveActivationState(&pkglicensing.ActivationState{
+ InstallationID: "inst_floor_read_only",
+ InstallationToken: "pit_live_floor_read_only",
+ LicenseID: "lic_floor_read_only",
+ GrantJWT: grantJWT,
+ GrantJTI: "grant_floor_read_only",
+ GrantExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ InstanceFingerprint: "fp-floor-read-only",
+ LicenseServerURL: "https://license.pulserelay.pro",
+ ActivatedAt: time.Now().Add(-time.Hour).Unix(),
+ LastRefreshedAt: time.Now().Add(-time.Hour).Unix(),
+ Continuity: pkglicensing.ActivationContinuity{
+ LegacyMigration: true,
+ },
+ }); err != nil {
+ t.Fatalf("save activation state: %v", err)
+ }
+
+ handlers := NewLicenseHandlers(mtp, false)
+ t.Cleanup(handlers.StopAllBackgroundLoops)
+
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")
+ svc := handlers.Service(ctx)
+ if svc == nil {
+ t.Fatal("expected non-nil service")
+ }
+
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ if value, ok := handlers.legacyGrandfatherReconcile.Load("default"); ok {
+ if loop, ok := value.(*legacyGrandfatherReconcileLoop); ok && loop.isRunning() {
+ break
+ }
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("expected restore-owned grandfather reconcile loop to start")
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+
+ handlers.stopLegacyGrandfatherReconcileLoop("default")
+ if _, ok := handlers.legacyGrandfatherReconcile.Load("default"); ok {
+ t.Fatal("expected grandfather reconcile loop to stop before read-only check")
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/api/license/status", nil).WithContext(ctx)
+ rec := httptest.NewRecorder()
+ handlers.HandleLicenseStatus(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("license status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ time.Sleep(100 * time.Millisecond)
+ if _, ok := handlers.legacyGrandfatherReconcile.Load("default"); ok {
+ t.Fatal("license status read restarted grandfather reconcile loop")
+ }
+
+ req = httptest.NewRequest(http.MethodGet, "/api/license/entitlements", nil).WithContext(ctx)
+ rec = httptest.NewRecorder()
+ handlers.HandleEntitlements(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("license entitlements=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ time.Sleep(100 * time.Millisecond)
+ if _, ok := handlers.legacyGrandfatherReconcile.Load("default"); ok {
+ t.Fatal("license entitlements read restarted grandfather reconcile loop")
+ }
+}
+
func TestActivateLicenseKey_GrandfathersObservedMonitoredSystemsForLegacyMigration(t *testing.T) {
t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
diff --git a/internal/api/purchase_return_redemptions.go b/internal/api/purchase_return_redemptions.go
index 036837e655..7b0ec3adee 100644
--- a/internal/api/purchase_return_redemptions.go
+++ b/internal/api/purchase_return_redemptions.go
@@ -186,17 +186,17 @@ func (s *purchaseReturnRedemptionStore) begin(attempt purchaseReturnRedemptionAt
}
switch existing.Status {
case purchaseReturnRedemptionStateActivated:
- committed = true
if err := tx.Commit(); err != nil {
return "", nil, fmt.Errorf("commit activated purchase redemption lookup: %w", err)
}
+ committed = true
return purchaseReturnRedemptionDecisionAlreadyActivated, existing, nil
case purchaseReturnRedemptionStateStarted:
if now.Sub(existing.UpdatedAt) < purchaseReturnRedemptionStaleAfter {
- committed = true
if err := tx.Commit(); err != nil {
return "", nil, fmt.Errorf("commit in-progress purchase redemption lookup: %w", err)
}
+ committed = true
return purchaseReturnRedemptionDecisionInProgress, existing, nil
}
case purchaseReturnRedemptionStateFailed:
@@ -225,10 +225,10 @@ func (s *purchaseReturnRedemptionStore) begin(attempt purchaseReturnRedemptionAt
return "", nil, err
}
if byPortalHandoffID != nil {
- committed = true
if err := tx.Commit(); err != nil {
return "", nil, fmt.Errorf("commit portal handoff conflict lookup: %w", err)
}
+ committed = true
return purchaseReturnRedemptionDecisionConflict, byPortalHandoffID, nil
}
@@ -237,10 +237,10 @@ func (s *purchaseReturnRedemptionStore) begin(attempt purchaseReturnRedemptionAt
return "", nil, err
}
if bySessionID != nil {
- committed = true
if err := tx.Commit(); err != nil {
return "", nil, fmt.Errorf("commit checkout session conflict lookup: %w", err)
}
+ committed = true
return purchaseReturnRedemptionDecisionConflict, bySessionID, nil
}
diff --git a/pkg/licensing/grant_refresh.go b/pkg/licensing/grant_refresh.go
index a362f952fc..43f002fbb9 100644
--- a/pkg/licensing/grant_refresh.go
+++ b/pkg/licensing/grant_refresh.go
@@ -240,7 +240,8 @@ func (s *Service) refreshGrantOnce(ctx context.Context) error {
cb := s.onLicenseChange
snapshot := cloneLicense(s.license)
- stateCopy := s.activationState
+ activationCB := s.onActivationStateChange
+ stateCopy := cloneActivationState(s.activationState)
s.mu.Unlock()
// Apply updated refresh hints from the server (policy may change between refreshes).
@@ -256,6 +257,9 @@ func (s *Service) refreshGrantOnce(ctx context.Context) error {
if cb != nil {
cb(snapshot)
}
+ if activationCB != nil {
+ activationCB(stateCopy)
+ }
log.Info().
Str("grant_jti", resp.Grant.JTI).
@@ -274,6 +278,7 @@ func (s *Service) clearActivationState() {
s.license = nil
s.evaluator = nil
cb := s.onLicenseChange
+ activationCB := s.onActivationStateChange
s.mu.Unlock()
if persistence != nil {
@@ -285,6 +290,9 @@ func (s *Service) clearActivationState() {
if cb != nil {
cb(nil)
}
+ if activationCB != nil {
+ activationCB(nil)
+ }
}
// nextRefreshInterval calculates the next refresh delay with jitter and backoff.
diff --git a/pkg/licensing/grant_refresh_test.go b/pkg/licensing/grant_refresh_test.go
index a3717cfe49..4dad873a66 100644
--- a/pkg/licensing/grant_refresh_test.go
+++ b/pkg/licensing/grant_refresh_test.go
@@ -141,6 +141,10 @@ func TestGrantRefreshLoop_401ClearsActivation(t *testing.T) {
svc := NewService()
svc.SetLicenseServerClient(NewLicenseServerClient(server.URL))
svc.SetPersistence(p)
+ var callbackState *ActivationState
+ svc.SetActivationStateChangeCallback(func(state *ActivationState) {
+ callbackState = state
+ })
state := &ActivationState{
InstallationID: "inst_revoked",
@@ -198,6 +202,9 @@ func TestGrantRefreshLoop_401ClearsActivation(t *testing.T) {
if svc.IsActivated() {
t.Error("expected activation cleared after 401 revocation")
}
+ if callbackState != nil {
+ t.Fatalf("expected nil activation-state callback after 401 revocation, got %+v", callbackState)
+ }
// Verify the persisted state was also cleared.
if p.ActivationStateExists() {
@@ -666,6 +673,71 @@ func TestRefreshGrantOnce_CallsLicenseChangeCallback(t *testing.T) {
}
}
+func TestRefreshGrantOnce_CallsActivationStateChangeCallback(t *testing.T) {
+ setupTestPublicKey(t)
+
+ newGrantJWT := makeTestGrantJWT(t, &GrantClaims{
+ LicenseID: "lic_activation_callback",
+ Tier: "relay",
+ State: "active",
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(RefreshGrantResponse{
+ Grant: GrantEnvelope{
+ JWT: newGrantJWT,
+ JTI: "grant_activation_callback",
+ ExpiresAt: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),
+ },
+ })
+ }))
+ defer server.Close()
+
+ initialJWT := makeTestGrantJWT(t, &GrantClaims{
+ LicenseID: "lic_initial_activation_callback",
+ Tier: "pro",
+ State: "active",
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ })
+
+ var callbackState *ActivationState
+ svc := NewService()
+ svc.SetActivationStateChangeCallback(func(state *ActivationState) {
+ callbackState = state
+ })
+ svc.SetLicenseServerClient(NewLicenseServerClient(server.URL))
+
+ state := &ActivationState{
+ InstallationID: "inst_activation_callback",
+ InstallationToken: "pit_live_activation_callback",
+ LicenseID: "lic_initial_activation_callback",
+ GrantJWT: initialJWT,
+ GrantJTI: "grant_old_activation_callback",
+ InstanceFingerprint: "fp-activation-callback",
+ }
+ svc.mu.Lock()
+ svc.activationState = state
+ svc.mu.Unlock()
+ if err := svc.RestoreActivation(state); err != nil {
+ t.Fatalf("RestoreActivation: %v", err)
+ }
+
+ callbackState = nil
+ if err := svc.refreshGrantOnce(context.Background()); err != nil {
+ t.Fatalf("refreshGrantOnce: %v", err)
+ }
+
+ if callbackState == nil {
+ t.Fatal("activation-state callback was not invoked")
+ }
+ if callbackState.GrantJTI != "grant_activation_callback" {
+ t.Fatalf("GrantJTI = %q, want grant_activation_callback", callbackState.GrantJTI)
+ }
+}
+
func TestGenerateFingerprint(t *testing.T) {
fp1, err := generateFingerprint()
if err != nil {
diff --git a/pkg/licensing/service.go b/pkg/licensing/service.go
index 9510dcdc57..1efb62e6ce 100644
--- a/pkg/licensing/service.go
+++ b/pkg/licensing/service.go
@@ -74,6 +74,9 @@ type Service struct {
// Callback when license changes
onLicenseChange func(*License)
+ // Callback when activation state changes.
+ onActivationStateChange func(*ActivationState)
+
// Optional canonical evaluator for B2 entitlement checks.
// When set and no JWT license is active, HasFeature/Status/SubscriptionState
// delegate to evaluator primitives (capabilities/limits/subscription state).
@@ -121,6 +124,13 @@ func (s *Service) SetLicenseChangeCallback(cb func(*License)) {
s.onLicenseChange = cb
}
+// SetActivationStateChangeCallback sets a callback for activation-state changes.
+func (s *Service) SetActivationStateChangeCallback(cb func(*ActivationState)) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.onActivationStateChange = cb
+}
+
// SetEvaluator overrides the entitlement evaluator.
// In normal operation, Activate and Clear manage the evaluator automatically.
// This method exists for testing; production code should not call it directly.
@@ -176,6 +186,7 @@ func (s *Service) Activate(licenseKey string) (*License, error) {
// Clear any activation state — this is now a legacy JWT license.
s.activationState = nil
cb := s.onLicenseChange
+ activationCB := s.onActivationStateChange
snapshot := cloneLicense(s.license)
persistence := s.persistence
s.mu.Unlock()
@@ -188,6 +199,9 @@ func (s *Service) Activate(licenseKey string) (*License, error) {
if cb != nil {
cb(snapshot)
}
+ if activationCB != nil {
+ activationCB(nil)
+ }
// Keep legacy mutability in explicit dev-mode to avoid breaking existing
// test fixtures that patch claims after activation. In production mode,
@@ -321,7 +335,9 @@ func (s *Service) applyActivationResponse(
s.evaluator = NewEvaluator(source)
s.activationState = state
cb := s.onLicenseChange
+ activationCB := s.onActivationStateChange
snapshot := cloneLicense(s.license)
+ stateSnapshot := cloneActivationState(state)
s.mu.Unlock()
// Apply refresh hints from the server.
@@ -339,6 +355,9 @@ func (s *Service) applyActivationResponse(
if cb != nil {
cb(snapshot)
}
+ if activationCB != nil {
+ activationCB(stateSnapshot)
+ }
return snapshot, nil
}
@@ -354,11 +373,7 @@ func (s *Service) IsActivated() bool {
func (s *Service) GetActivationState() *ActivationState {
s.mu.RLock()
defer s.mu.RUnlock()
- if s.activationState == nil {
- return nil
- }
- stateCopy := *s.activationState
- return &stateCopy
+ return cloneActivationState(s.activationState)
}
// SetLicenseServerClient sets the HTTP client for license server communication.
@@ -399,12 +414,17 @@ func (s *Service) RestoreActivation(state *ActivationState) error {
s.evaluator = NewEvaluator(source)
s.activationState = &stateCopy
cb := s.onLicenseChange
+ activationCB := s.onActivationStateChange
snapshot := cloneLicense(s.license)
+ stateSnapshot := cloneActivationState(&stateCopy)
s.mu.Unlock()
if cb != nil {
cb(snapshot)
}
+ if activationCB != nil {
+ activationCB(stateSnapshot)
+ }
return nil
}
@@ -453,7 +473,9 @@ func (s *Service) CaptureLegacyMonitoredSystemGrandfatherFloor(count int) error
stateCopy := *s.activationState
persistence := s.persistence
cb := s.onLicenseChange
+ activationCB := s.onActivationStateChange
snapshot := cloneLicense(s.license)
+ stateSnapshot := cloneActivationState(s.activationState)
s.mu.Unlock()
if persistence != nil {
@@ -465,6 +487,9 @@ func (s *Service) CaptureLegacyMonitoredSystemGrandfatherFloor(count int) error
if shouldNotify && cb != nil {
cb(snapshot)
}
+ if activationCB != nil {
+ activationCB(stateSnapshot)
+ }
return nil
}
@@ -536,6 +561,7 @@ func (s *Service) Clear() {
hadActivation := s.activationState != nil
s.activationState = nil
cb := s.onLicenseChange
+ activationCB := s.onActivationStateChange
s.mu.Unlock()
// Clear persisted activation state if it existed.
@@ -548,6 +574,9 @@ func (s *Service) Clear() {
if cb != nil {
cb(nil)
}
+ if activationCB != nil {
+ activationCB(nil)
+ }
}
// Current returns the current license, or nil if none.
@@ -948,6 +977,16 @@ func cloneLicense(in *License) *License {
return &out
}
+func cloneActivationState(in *ActivationState) *ActivationState {
+ if in == nil {
+ return nil
+ }
+
+ out := *in
+ out.Continuity = normalizeActivationContinuity(in.Continuity)
+ return &out
+}
+
func cloneClaims(in Claims) Claims {
out := in
if in.Features != nil {
diff --git a/pkg/licensing/service_activate_test.go b/pkg/licensing/service_activate_test.go
index 40dcc590a8..dad2184881 100644
--- a/pkg/licensing/service_activate_test.go
+++ b/pkg/licensing/service_activate_test.go
@@ -193,6 +193,120 @@ func TestServiceActivate_ExchangedLegacyJWTMarksLegacyMigrationContinuity(t *tes
}
}
+func TestServiceActivate_CallsActivationStateChangeCallback(t *testing.T) {
+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
+ setupTestPublicKey(t)
+
+ svc := NewService()
+ licenseKey, err := GenerateLicenseForTesting("[email protected]", TierPro, 24*time.Hour)
+ if err != nil {
+ t.Fatalf("GenerateLicenseForTesting: %v", err)
+ }
+
+ grantJWT := makeTestGrantJWT(t, &GrantClaims{
+ LicenseID: "lic_activation_callback",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/licenses/exchange" {
+ t.Fatalf("Path = %q, want /v1/licenses/exchange", r.URL.Path)
+ }
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(ActivateInstallationResponse{
+ License: ActivateResponseLicense{
+ LicenseID: "lic_activation_callback",
+ State: "active",
+ Tier: "pro",
+ MaxMonitoredSystems: 10,
+ },
+ Installation: ActivateResponseInstallation{
+ InstallationID: "inst_activation_callback",
+ InstallationToken: "pit_live_activation_callback",
+ Status: "active",
+ },
+ Grant: GrantEnvelope{
+ JWT: grantJWT,
+ JTI: "grant_activation_callback",
+ ExpiresAt: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),
+ },
+ })
+ }))
+ defer server.Close()
+
+ var callbackState *ActivationState
+ svc.SetActivationStateChangeCallback(func(state *ActivationState) {
+ callbackState = state
+ })
+ svc.SetLicenseServerClient(NewLicenseServerClient(server.URL))
+
+ if _, err := svc.Activate(licenseKey); err != nil {
+ t.Fatalf("Activate: %v", err)
+ }
+
+ if callbackState == nil {
+ t.Fatal("activation-state callback was not invoked")
+ }
+ if callbackState.InstallationID != "inst_activation_callback" {
+ t.Fatalf("InstallationID = %q, want inst_activation_callback", callbackState.InstallationID)
+ }
+ if !callbackState.Continuity.LegacyMigration {
+ t.Fatal("expected legacy activation callback to preserve migration continuity")
+ }
+}
+
+func TestServiceRestoreActivation_CallsActivationStateChangeCallback(t *testing.T) {
+ setupTestPublicKey(t)
+
+ grantJWT := makeTestGrantJWT(t, &GrantClaims{
+ LicenseID: "lic_restore_callback",
+ Tier: "pro",
+ PlanKey: "v5_pro_monthly_grandfathered",
+ State: "active",
+ MaxMonitoredSystems: 10,
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ })
+
+ svc := NewService()
+ var callbackState *ActivationState
+ svc.SetActivationStateChangeCallback(func(state *ActivationState) {
+ callbackState = state
+ })
+
+ state := &ActivationState{
+ InstallationID: "inst_restore_callback",
+ InstallationToken: "pit_live_restore_callback",
+ LicenseID: "lic_restore_callback",
+ GrantJWT: grantJWT,
+ GrantJTI: "grant_restore_callback",
+ GrantExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ InstanceFingerprint: "fp-restore-callback",
+ Continuity: ActivationContinuity{
+ LegacyMigration: true,
+ },
+ }
+
+ if err := svc.RestoreActivation(state); err != nil {
+ t.Fatalf("RestoreActivation: %v", err)
+ }
+
+ if callbackState == nil {
+ t.Fatal("activation-state callback was not invoked")
+ }
+ if callbackState.InstallationID != "inst_restore_callback" {
+ t.Fatalf("InstallationID = %q, want inst_restore_callback", callbackState.InstallationID)
+ }
+ if !callbackState.Continuity.LegacyMigration {
+ t.Fatal("expected restore callback to preserve migration continuity")
+ }
+}
+
func TestServiceCaptureLegacyMonitoredSystemGrandfatherFloorPersistsAndUpdatesStatus(t *testing.T) {
setupTestPublicKey(t)
@@ -219,6 +333,10 @@ func TestServiceCaptureLegacyMonitoredSystemGrandfatherFloorPersistsAndUpdatesSt
svc := NewService()
svc.SetPersistence(p)
+ var callbackState *ActivationState
+ svc.SetActivationStateChangeCallback(func(state *ActivationState) {
+ callbackState = state
+ })
state := &ActivationState{
InstallationID: "inst_floor",
InstallationToken: "pit_live_floor",
@@ -234,9 +352,19 @@ func TestServiceCaptureLegacyMonitoredSystemGrandfatherFloorPersistsAndUpdatesSt
t.Fatalf("RestoreActivation: %v", err)
}
+ callbackState = nil
if err := svc.CaptureLegacyMonitoredSystemGrandfatherFloor(23); err != nil {
t.Fatalf("CaptureLegacyMonitoredSystemGrandfatherFloor: %v", err)
}
+ if callbackState == nil {
+ t.Fatal("expected activation-state callback after monitored-system capture")
+ }
+ if callbackState.Continuity.GrandfatheredMaxMonitoredSystems != 23 {
+ t.Fatalf("callback GrandfatheredMaxMonitoredSystems=%d, want 23", callbackState.Continuity.GrandfatheredMaxMonitoredSystems)
+ }
+ if callbackState.Continuity.GrandfatheredMonitoredSystemsCapturedAt == 0 {
+ t.Fatal("expected callback capture timestamp")
+ }
status := svc.Status()
if status.MaxMonitoredSystems != 23 {