#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
fix(usage): make fleet statistics available across tiers without unauthorized UI requests (#7959)
ConnorYoh3ae2fbefa730
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/FleetUsageController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/FleetUsageController.javaindex 8f95920e5a..af298e03e6 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/FleetUsageController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/FleetUsageController.java@@ -18,32 +18,30 @@ import stirling.software.proprietary.audit.AuditLevel;import stirling.software.proprietary.config.AuditConfigurationProperties;import stirling.software.proprietary.model.api.usage.FleetUsageStats;import stirling.software.proprietary.repository.PersistentAuditEventRepository;-import stirling.software.proprietary.security.config.EnterpriseEndpoint;import stirling.software.proprietary.security.database.repository.UserRepository;/**- * Admin endpoint exposing free-editor fleet usage for the portal Usage card. Audit-derived figures- * (active editors, PDFs processed) are null (rendered as "N/A") rather than a misleading 0 whenever- * the data can't exist: the events they count (PDF_PROCESS, FILE_OPERATION, HTTP_REQUEST) are all- * STANDARD level, so a gate on {@code isEnabled()} alone would still return 0 at level=OFF/BASIC —- * we gate on {@code isLevelEnabled(STANDARD)} instead.+ * Instance-wide free-editor usage for admins on every license tier. Activity counts use the+ * document-processing events recorded without Enterprise at BASIC or above, over the last 30 days+ * of retained history. Disabled recording returns null rather than a misleading zero.** <p>Known limitation: on a login-disabled self-hosted instance every request is anonymous, so its* audit origin is SYSTEM (not WEB) and it is excluded from these WEB-only counts — active/PDFs then* read 0 despite real usage. Historical audit rows written before the {@code source} column existed- * carry {@code source=null}, so the cumulative "PDFs edited" figure effectively starts at deploy.+ * carry {@code source=null} and are excluded from these counts.*/@Slf4j@RestController@RequestMapping("/api/v1/usage")@PreAuthorize("hasRole('ADMIN')")@RequiredArgsConstructor-@EnterpriseEndpoint// Self-hosted only: counts are server-wide. On SaaS this endpoint is owned by the team-scoped// SaasFleetUsageController (@Profile("saas")) so one backend can't leak another tenant's usage.@Profile("!saas")public class FleetUsageController {+ private static final List<String> PDF_TYPES = List.of("PDF_PROCESS", "FILE_OPERATION");+private final PersistentAuditEventRepository auditRepository;private final UserRepository userRepository;private final AuditConfigurationProperties auditConfig;@@ -53,19 +51,17 @@ public class FleetUsageController {// Exclude the reserved INTERNAL_API_USER row that InitialSecuritySetup creates on every// install, so a fresh single-admin instance reads 1 editor, not 2.Long deployed = userRepository.countByUsernameNot(Role.INTERNAL_API_USER.getRoleId());- // STANDARD is the level at which the counted events are recorded; below it the data- // can't exist, so report N/A instead of a 0 that would misrepresent an empty table.- boolean auditOn = auditConfig.isLevelEnabled(AuditLevel.STANDARD);+ boolean auditOn = auditConfig.isLevelEnabled(AuditLevel.BASIC);Instant since = Instant.now().minus(30, ChronoUnit.DAYS);Long active =auditOn- ? auditRepository.countDistinctPrincipalsBySourceExcludingTypeAfter(- "WEB", "UI_DATA", since)+ ? auditRepository.countDistinctPrincipalsBySourceAndTypeInAfter(+ "WEB", PDF_TYPES, since): null;Long pdfs =auditOn? auditRepository.countByTypeInAndSourceAndTimestampAfter(- List.of("PDF_PROCESS", "FILE_OPERATION"), "WEB", Instant.EPOCH)+ PDF_TYPES, "WEB", since): null;if (active != null && deployed != null && active > deployed) {active = deployed; // active editors are a subset of those deployeddiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/PersistentAuditEventRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/PersistentAuditEventRepository.javaindex e140b8f5c8..b96b947631 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/repository/PersistentAuditEventRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/PersistentAuditEventRepository.java@@ -285,10 +285,10 @@ public interface PersistentAuditEventRepository extends JpaRepository<Persistent@Query("SELECT COUNT(DISTINCT e.principal) FROM PersistentAuditEvent e "- + "WHERE e.source = :source AND e.type <> :excludeType AND e.timestamp > :since")- long countDistinctPrincipalsBySourceExcludingTypeAfter(+ + "WHERE e.source = :source AND e.type IN :types AND e.timestamp > :since")+ long countDistinctPrincipalsBySourceAndTypeInAfter(@Param("source") String source,- @Param("excludeType") String excludeType,+ @Param("types") List<String> types,@Param("since") Instant since);// Team-scoped (SaaS) variants: same free-UI counts, constrained to a team's member principals.@@ -304,11 +304,11 @@ public interface PersistentAuditEventRepository extends JpaRepository<Persistent@Query("SELECT COUNT(DISTINCT e.principal) FROM PersistentAuditEvent e "- + "WHERE e.source = :source AND e.type <> :excludeType "+ + "WHERE e.source = :source AND e.type IN :types "+ "AND e.principal IN :principals AND e.timestamp > :since")- long countDistinctPrincipalsBySourceExcludingTypeAndPrincipalInAfter(+ long countDistinctPrincipalsBySourceAndTypeInAndPrincipalInAfter(@Param("source") String source,- @Param("excludeType") String excludeType,+ @Param("types") List<String> types,@Param("principals") List<String> principals,@Param("since") Instant since);}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/FleetUsageControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/FleetUsageControllerTest.javaindex 11e168b8d1..861be53ca3 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/FleetUsageControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/FleetUsageControllerTest.java@@ -10,11 +10,14 @@ import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import java.time.Instant;+import java.time.temporal.ChronoUnit;+import java.util.List;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;@@ -43,7 +46,7 @@ class FleetUsageControllerTest {@DisplayName("deployed reflects the user count, excluding the internal API user")void deployedFromUserCount() {when(userRepository.countByUsernameNot(anyString())).thenReturn(7L);- when(auditConfig.isLevelEnabled(AuditLevel.STANDARD)).thenReturn(false);+ when(auditConfig.isLevelEnabled(AuditLevel.BASIC)).thenReturn(false);FleetUsageStats stats = controller.fleetStats();@@ -52,20 +55,19 @@ class FleetUsageControllerTest {}@Test- @DisplayName("audit-derived figures are null when auditing is below STANDARD")+ @DisplayName("audit-derived figures are null when auditing is disabled or below BASIC")void auditOffYieldsNulls() {when(userRepository.countByUsernameNot(anyString())).thenReturn(3L);- // Covers both disabled and the enabled-but-level=OFF/BASIC misconfig: isLevelEnabled+ // Disabled recording must not be presented as zero activity. isLevelEnabled// is false, so no events can exist and we must report N/A, not a 0 from an empty table.- when(auditConfig.isLevelEnabled(AuditLevel.STANDARD)).thenReturn(false);+ when(auditConfig.isLevelEnabled(AuditLevel.BASIC)).thenReturn(false);FleetUsageStats stats = controller.fleetStats();assertThat(stats.activeThisMonth()).isNull();assertThat(stats.pdfsProcessed()).isNull();verify(auditRepository, never())- .countDistinctPrincipalsBySourceExcludingTypeAfter(- any(), any(), any(Instant.class));+ .countDistinctPrincipalsBySourceAndTypeInAfter(any(), any(), any(Instant.class));verify(auditRepository, never()).countByTypeInAndSourceAndTimestampAfter(anyList(), any(), any(Instant.class));}@@ -74,28 +76,41 @@ class FleetUsageControllerTest {@DisplayName("audit-derived figures come from the repository when auditing is enabled")void auditOnReadsRepository() {when(userRepository.countByUsernameNot(anyString())).thenReturn(10L);- when(auditConfig.isLevelEnabled(AuditLevel.STANDARD)).thenReturn(true);- when(auditRepository.countDistinctPrincipalsBySourceExcludingTypeAfter(- eq("WEB"), eq("UI_DATA"), any(Instant.class)))+ when(auditConfig.isLevelEnabled(AuditLevel.BASIC)).thenReturn(true);+ when(auditRepository.countDistinctPrincipalsBySourceAndTypeInAfter(+ eq("WEB"),+ eq(List.of("PDF_PROCESS", "FILE_OPERATION")),+ any(Instant.class))).thenReturn(4L);when(auditRepository.countByTypeInAndSourceAndTimestampAfter(anyList(), eq("WEB"), any(Instant.class))).thenReturn(1234L);+ Instant earliest = Instant.now().minus(30, ChronoUnit.DAYS);FleetUsageStats stats = controller.fleetStats();assertThat(stats.editorsDeployed()).isEqualTo(10L);assertThat(stats.activeThisMonth()).isEqualTo(4L);assertThat(stats.pdfsProcessed()).isEqualTo(1234L);+ ArgumentCaptor<Instant> since = ArgumentCaptor.forClass(Instant.class);+ verify(auditRepository)+ .countByTypeInAndSourceAndTimestampAfter(+ eq(List.of("PDF_PROCESS", "FILE_OPERATION")), eq("WEB"), since.capture());+ assertThat(since.getValue()).isBetween(earliest, Instant.now().minus(30, ChronoUnit.DAYS));+ verify(auditRepository)+ .countDistinctPrincipalsBySourceAndTypeInAfter(+ "WEB", List.of("PDF_PROCESS", "FILE_OPERATION"), since.getValue());}@Test@DisplayName("active editors are clamped to deployed (active is a subset)")void activeClampedToDeployed() {when(userRepository.countByUsernameNot(anyString())).thenReturn(2L);- when(auditConfig.isLevelEnabled(AuditLevel.STANDARD)).thenReturn(true);- when(auditRepository.countDistinctPrincipalsBySourceExcludingTypeAfter(- eq("WEB"), eq("UI_DATA"), any(Instant.class)))+ when(auditConfig.isLevelEnabled(AuditLevel.BASIC)).thenReturn(true);+ when(auditRepository.countDistinctPrincipalsBySourceAndTypeInAfter(+ eq("WEB"),+ eq(List.of("PDF_PROCESS", "FILE_OPERATION")),+ any(Instant.class))).thenReturn(9L);when(auditRepository.countByTypeInAndSourceAndTimestampAfter(anyList(), eq("WEB"), any(Instant.class)))diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/FleetUsageSecurityTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/FleetUsageSecurityTest.javanew file mode 100644index 0000000000..067eb99e26--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/FleetUsageSecurityTest.java@@ -0,0 +1,92 @@+package stirling.software.proprietary.controller.api;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.context.annotation.AnnotationConfigApplicationContext;+import org.springframework.context.annotation.Configuration;+import org.springframework.context.annotation.EnableAspectJAutoProxy;+import org.springframework.security.access.AccessDeniedException;+import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;+import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;+import org.springframework.security.core.authority.AuthorityUtils;+import org.springframework.security.core.context.SecurityContextHolder;++import stirling.software.common.model.enumeration.Role;+import stirling.software.proprietary.config.AuditConfigurationProperties;+import stirling.software.proprietary.repository.PersistentAuditEventRepository;+import stirling.software.proprietary.security.config.EnterpriseEndpointAspect;+import stirling.software.proprietary.security.database.repository.UserRepository;++class FleetUsageSecurityTest {++ private AnnotationConfigApplicationContext context;+ private UserRepository users;+ private PersistentAuditEventRepository events;+ private FleetUsageController controller;++ @BeforeEach+ void setUp() {+ users = mock(UserRepository.class);+ events = mock(PersistentAuditEventRepository.class);+ context = new AnnotationConfigApplicationContext();+ context.register(SecurityConfig.class);+ context.registerBean(UserRepository.class, () -> users);+ context.registerBean(PersistentAuditEventRepository.class, () -> events);+ context.registerBean(+ AuditConfigurationProperties.class, () -> mock(AuditConfigurationProperties.class));+ context.registerBean(+ EnterpriseEndpointAspect.class, () -> new EnterpriseEndpointAspect(false));+ context.registerBean(FleetUsageController.class);+ context.refresh();+ controller = context.getBean(FleetUsageController.class);+ }++ @AfterEach+ void tearDown() {+ SecurityContextHolder.clearContext();+ context.close();+ }++ @Test+ void adminCanReadWithoutEnterpriseLicense() {+ authenticate("ROLE_ADMIN");+ when(users.countByUsernameNot(Role.INTERNAL_API_USER.getRoleId())).thenReturn(3L);++ assertThat(controller.fleetStats().editorsDeployed()).isEqualTo(3L);+ }++ @Test+ void nonAdminCannotReadInstanceStatistics() {+ authenticate("ROLE_USER");++ assertThatThrownBy(() -> controller.fleetStats()).isInstanceOf(AccessDeniedException.class);+ verifyNoInteractions(users, events);+ }++ @Test+ void signedOutCannotReadInstanceStatistics() {+ assertThatThrownBy(() -> controller.fleetStats())+ .isInstanceOf(AuthenticationCredentialsNotFoundException.class);+ verifyNoInteractions(users, events);+ }++ private void authenticate(String role) {+ SecurityContextHolder.getContext()+ .setAuthentication(+ new UsernamePasswordAuthenticationToken(+ "user", null, AuthorityUtils.createAuthorityList(role)));+ }++ @Configuration+ @EnableAspectJAutoProxy+ @EnableMethodSecurity+ static class SecurityConfig {}+}diff --git a/app/saas/src/main/java/stirling/software/saas/usage/SaasFleetUsageController.java b/app/saas/src/main/java/stirling/software/saas/usage/SaasFleetUsageController.javaindex 2c427fc7c6..d94fe25eb2 100644--- a/app/saas/src/main/java/stirling/software/saas/usage/SaasFleetUsageController.java+++ b/app/saas/src/main/java/stirling/software/saas/usage/SaasFleetUsageController.java@@ -35,13 +35,14 @@ import stirling.software.saas.util.AuthenticationUtils;** <ul>* <li>editorsDeployed — number of team members ({@code team_memberships}), not seat limits;- * <li>activeThisMonth — distinct members with a free-UI ("WEB", non-{@code UI_DATA}) audit event- * in the last 30 days, clamped to a subset of deployed;- * <li>pdfsProcessed — the team's cumulative free-UI PDF/file operations.+ * <li>activeThisMonth — distinct members with a free-UI document operation in the last 30 days,+ * clamped to a subset of deployed;+ * <li>pdfsProcessed — the team's free-UI PDF/file operations in the last 30 days of retained+ * history.* </ul>** <p>Team resolution + membership mirror {@code PaygWalletController}. Audit-derived figures are- * null (rendered "N/A") when EE auditing is below STANDARD. Cost is always $0 (client literal).+ * null (rendered "N/A") when document recording is disabled or below BASIC.*/@Slf4j@RestController@@ -84,18 +85,18 @@ public class SaasFleetUsageController {Long deployed = (long) members.size();// Guard the empty IN-list (invalid JPQL) as well as the audit-level gate.- boolean auditOn = !members.isEmpty() && auditConfig.isLevelEnabled(AuditLevel.STANDARD);+ boolean auditOn = !members.isEmpty() && auditConfig.isLevelEnabled(AuditLevel.BASIC);Instant since = Instant.now().minus(30, ChronoUnit.DAYS);Long active =auditOn? auditRepository- .countDistinctPrincipalsBySourceExcludingTypeAndPrincipalInAfter(- "WEB", "UI_DATA", members, since)+ .countDistinctPrincipalsBySourceAndTypeInAndPrincipalInAfter(+ "WEB", PDF_TYPES, members, since): null;Long pdfs =auditOn? auditRepository.countByTypeInAndSourceAndPrincipalInAndTimestampAfter(- PDF_TYPES, "WEB", members, Instant.EPOCH)+ PDF_TYPES, "WEB", members, since): null;if (active != null && active > deployed) {active = deployed; // active editors are a subset of those deployeddiff --git a/app/saas/src/test/java/stirling/software/saas/usage/SaasFleetUsageControllerTest.java b/app/saas/src/test/java/stirling/software/saas/usage/SaasFleetUsageControllerTest.javaindex 8d49267821..291818ab95 100644--- a/app/saas/src/test/java/stirling/software/saas/usage/SaasFleetUsageControllerTest.java+++ b/app/saas/src/test/java/stirling/software/saas/usage/SaasFleetUsageControllerTest.java@@ -11,12 +11,14 @@ import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import java.time.Instant;+import java.time.temporal.ChronoUnit;import java.util.List;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.springframework.http.HttpStatus;@@ -93,14 +95,18 @@ class SaasFleetUsageControllerTest {TeamMembership leader = memberOf(42L, "[email protected]");TeamMembership bob = memberOf(42L, "[email protected]");when(memberRepo.findByTeamId(42L)).thenReturn(List.of(leader, bob));- when(auditConfig.isLevelEnabled(AuditLevel.STANDARD)).thenReturn(true);- when(auditRepository.countDistinctPrincipalsBySourceExcludingTypeAndPrincipalInAfter(- eq("WEB"), eq("UI_DATA"), anyList(), any(Instant.class)))+ when(auditConfig.isLevelEnabled(AuditLevel.BASIC)).thenReturn(true);+ when(auditRepository.countDistinctPrincipalsBySourceAndTypeInAndPrincipalInAfter(+ eq("WEB"),+ eq(List.of("PDF_PROCESS", "FILE_OPERATION")),+ anyList(),+ any(Instant.class))).thenReturn(1L);when(auditRepository.countByTypeInAndSourceAndPrincipalInAndTimestampAfter(anyList(), eq("WEB"), anyList(), any(Instant.class))).thenReturn(88L);+ Instant earliest = Instant.now().minus(30, ChronoUnit.DAYS);ResponseEntity<FleetUsageStats> res = controller.fleetStats(auth);FleetUsageStats stats = res.getBody();@@ -108,21 +114,29 @@ class SaasFleetUsageControllerTest {assertThat(stats.editorsDeployed()).isEqualTo(2L);assertThat(stats.activeThisMonth()).isEqualTo(1L);assertThat(stats.pdfsProcessed()).isEqualTo(88L);+ ArgumentCaptor<Instant> since = ArgumentCaptor.forClass(Instant.class);verify(auditRepository).countByTypeInAndSourceAndPrincipalInAndTimestampAfter(eq(List.of("PDF_PROCESS", "FILE_OPERATION")),eq("WEB"),eq(List.of("[email protected]", "[email protected]")),- any(Instant.class));+ since.capture());+ assertThat(since.getValue()).isBetween(earliest, Instant.now().minus(30, ChronoUnit.DAYS));+ verify(auditRepository)+ .countDistinctPrincipalsBySourceAndTypeInAndPrincipalInAfter(+ "WEB",+ List.of("PDF_PROCESS", "FILE_OPERATION"),+ List.of("[email protected]", "[email protected]"),+ since.getValue());}@Test- @DisplayName("audit-derived figures are null when auditing is below STANDARD")+ @DisplayName("audit-derived figures are null when auditing is disabled or below BASIC")void auditOffYieldsNulls() {Authentication auth = authFor(1L, 42L);TeamMembership leader = memberOf(42L, "[email protected]");when(memberRepo.findByTeamId(42L)).thenReturn(List.of(leader));- when(auditConfig.isLevelEnabled(AuditLevel.STANDARD)).thenReturn(false);+ when(auditConfig.isLevelEnabled(AuditLevel.BASIC)).thenReturn(false);FleetUsageStats stats = controller.fleetStats(auth).getBody();@@ -141,9 +155,12 @@ class SaasFleetUsageControllerTest {Authentication auth = authFor(1L, 42L);TeamMembership leader = memberOf(42L, "[email protected]");when(memberRepo.findByTeamId(42L)).thenReturn(List.of(leader));- when(auditConfig.isLevelEnabled(AuditLevel.STANDARD)).thenReturn(true);- when(auditRepository.countDistinctPrincipalsBySourceExcludingTypeAndPrincipalInAfter(- eq("WEB"), eq("UI_DATA"), anyList(), any(Instant.class)))+ when(auditConfig.isLevelEnabled(AuditLevel.BASIC)).thenReturn(true);+ when(auditRepository.countDistinctPrincipalsBySourceAndTypeInAndPrincipalInAfter(+ eq("WEB"),+ eq(List.of("PDF_PROCESS", "FILE_OPERATION")),+ anyList(),+ any(Instant.class))).thenReturn(5L);when(auditRepository.countByTypeInAndSourceAndPrincipalInAndTimestampAfter(anyList(), eq("WEB"), anyList(), any(Instant.class)))diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 569409012d..e540137a7c 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -7373,11 +7373,11 @@ eyebrow = "Volume discount · 1M+ PDFs"title = "Stirling Enterprise"[portal.billing.freeEditors]-activeThisMonth = "Active this month"+activeThisMonth = "Active editors (30 days)"cost = "Cost"editorsDeployed = "Editors deployed"inviteTeammates = "Invite teammates"-pdfsEdited = "PDFs edited"+pdfsEdited = "Edit operations (30 days)"subtitle = "Deploy anywhere, for your whole team."title = "Free PDF Editors"@@ -8321,7 +8321,7 @@ tagline = "Native app for Microsoft Windows"title = "Windows"[portal.home.editor]-activeOfDeployed = "{{active}} of {{total}} active this month"+activeOfDeployed = "{{active}} of {{total}} active in the last 30 days"name = "PDF Editor"open = "Open in browser"updated = "updated {{time}}"diff --git a/frontend/editor/src/portal-saas/api/fleetStats.ts b/frontend/editor/src/portal-saas/api/fleetStats.tsindex 9ba701f4c6..369fbd69ed 100644--- a/frontend/editor/src/portal-saas/api/fleetStats.ts+++ b/frontend/editor/src/portal-saas/api/fleetStats.ts@@ -5,11 +5,16 @@ export type { FleetStats };/*** SaaS build: fleet usage is team-scoped and served by the SaaS backend, so it is- * read via {@code apiClient.saas} — the admin's Supabase JWT, which the SaaS backend+ * read via {@code apiClient.saas} — the member's Supabase JWT, which the SaaS backend* uses to resolve the caller's team. Shadows the self-hosted* src/portal/api/fleetStats.ts (which reads the local backend server-wide).*/-export function fetchFleetStats(signal?: AbortSignal): Promise<FleetStats> {+/** Prefer useFleetStats; direct callers must pass the resolved access gate before any request. */+export async function fetchFleetStats(+ enabled: boolean,+ signal?: AbortSignal,+): Promise<FleetStats | null> {+ if (!enabled) return null;return apiClient.saas.json<FleetStats>("/api/v1/usage/fleet-stats", {signal,});diff --git a/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.test.ts b/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.test.tsnew file mode 100644index 0000000000..de69ed041a--- /dev/null+++ b/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.test.ts@@ -0,0 +1,39 @@+import { renderHook } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import { useFleetStatsAccess } from "@portal/hooks/useFleetStatsAccess";++const state = vi.hoisted(() => ({+ auth: {+ loading: false,+ error: null as Error | null,+ session: {} as object | null,+ user: { id: "member" } as { id: string } | null,+ isAnonymous: false,+ },+}));+vi.mock("@app/auth/UseSession", () => ({ useAuth: () => state.auth }));++beforeEach(() => {+ state.auth = {+ loading: false,+ error: null,+ session: {},+ user: { id: "member" },+ isAnonymous: false,+ };+});++it("allows a signed-in SaaS member without requiring an admin role", () => {+ expect(renderHook(() => useFleetStatsAccess()).result.current).toBe("member");+});++it.each([+ { loading: true },+ { session: null },+ { user: null },+ { isAnonymous: true },+ { error: new Error("Session unavailable") },+])("denies an unresolved or anonymous SaaS session: %j", (override) => {+ Object.assign(state.auth, override);+ expect(renderHook(() => useFleetStatsAccess()).result.current).toBeNull();+});diff --git a/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.ts b/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.tsnew file mode 100644index 0000000000..1b74fa2eb7--- /dev/null+++ b/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.ts@@ -0,0 +1,10 @@+import { useAuth } from "@app/auth/UseSession";++/** SaaS returns team-scoped statistics to signed-in members as well as leaders. */+export function useFleetStatsAccess(): string | null {+ const auth = useAuth();+ if (auth.loading || auth.error || !auth.session || auth.isAnonymous) {+ return null;+ }+ return auth.user?.id ?? null;+}diff --git a/frontend/editor/src/portal/api/fleetStats.ts b/frontend/editor/src/portal/api/fleetStats.tsindex 48bc247d84..1ac3f822c0 100644--- a/frontend/editor/src/portal/api/fleetStats.ts+++ b/frontend/editor/src/portal/api/fleetStats.ts@@ -8,8 +8,8 @@ import { apiClient } from "@portal/api/http";* shadows this module (src/portal-saas/api/fleetStats.ts) to read the team-scoped* SaaS backend instead.*- * Any field may be null when the backend can't compute it (e.g. EE auditing is- * disabled); the card renders null as "N/A" rather than a misleading 0.+ * Activity counts cover document operations in the last 30 days of retained+ * history. Disabled recording returns null; the card renders it as "N/A".*/export interface FleetStats {editorsDeployed: number | null;@@ -17,7 +17,12 @@ export interface FleetStats {pdfsProcessed: number | null;}-export function fetchFleetStats(signal?: AbortSignal): Promise<FleetStats> {+/** Prefer useFleetStats; direct callers must pass the resolved access gate before any request. */+export async function fetchFleetStats(+ enabled: boolean,+ signal?: AbortSignal,+): Promise<FleetStats | null> {+ if (!enabled) return null;return apiClient.local.json<FleetStats>("/api/v1/usage/fleet-stats", {signal,});diff --git a/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.tsx b/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.tsxindex 25ef05ec9e..a0729d2bf1 100644--- a/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.tsx+++ b/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.tsx@@ -9,8 +9,8 @@ import { useFleetStats } from "@portal/queries/infrastructure";* "Free PDF Editors" team-fleet card. Editors-deployed / active-this-month /* PDFs-edited come from the instance's usage endpoint* ({@code GET /api/v1/usage/fleet-stats}), derived from the audit trail filtered- * to free UI tool runs. A figure the backend can't compute (e.g. EE auditing is- * off) arrives as null and renders "N/A". Cost is always $0.+ * to free UI tool runs. A figure the backend can't compute (e.g. document recording is+ * off) arrives as null and renders "N/A". Activity covers the last 30 days of retained history.*/function fmtMetric(value: number | null | undefined, loading: boolean): string {if (loading) return "—";@@ -52,12 +52,15 @@ export function FreePdfEditorsCard() {<MetricCardlabel={t("portal.billing.freeEditors.activeThisMonth",- "Active this month",+ "Active editors (30 days)",)}value={fmtMetric(data?.activeThisMonth, loading)}/><MetricCard- label={t("portal.billing.freeEditors.pdfsEdited", "PDFs edited")}+ label={t(+ "portal.billing.freeEditors.pdfsEdited",+ "Edit operations (30 days)",+ )}value={fmtMetric(data?.pdfsProcessed, loading)}/><MetricCarddiff --git a/frontend/editor/src/portal/hooks/useFleetStatsAccess.ts b/frontend/editor/src/portal/hooks/useFleetStatsAccess.tsnew file mode 100644index 0000000000..a4642f49b9--- /dev/null+++ b/frontend/editor/src/portal/hooks/useFleetStatsAccess.ts@@ -0,0 +1,16 @@+import { useAuth } from "@app/auth/UseSession";++/** Cache scope for a confirmed local admin; null prevents requests, including login-off sessions. */+export function useFleetStatsAccess(): string | null {+ const auth = useAuth();+ if (+ auth.loading ||+ auth.error ||+ !auth.session ||+ auth.isAnonymous ||+ !auth.isAdmin+ ) {+ return null;+ }+ return auth.user?.id ?? null;+}diff --git a/frontend/editor/src/portal/queries/fleetStats.test.tsx b/frontend/editor/src/portal/queries/fleetStats.test.tsxnew file mode 100644index 0000000000..682a5c0f22--- /dev/null+++ b/frontend/editor/src/portal/queries/fleetStats.test.tsx@@ -0,0 +1,134 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useFleetStats } from "@portal/queries/infrastructure";+import { fetchFleetStats } from "@portal/api/fleetStats";++const state = vi.hoisted(() => ({+ auth: {+ loading: false,+ error: null as Error | null,+ session: {} as object | null,+ user: { id: "admin" } as { id: string } | null,+ isAdmin: true,+ isAnonymous: false,+ },+ json: vi.fn(),+}));++vi.mock("@app/auth/UseSession", () => ({ useAuth: () => state.auth }));+vi.mock("@portal/api/http", () => ({+ apiClient: { local: { json: state.json }, saas: { json: state.json } },+}));++function setup() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ return { client, ...renderHook(() => useFleetStats(), { wrapper }) };+}++beforeEach(() => {+ state.auth = {+ loading: false,+ error: null,+ session: {},+ user: { id: "admin" },+ isAdmin: true,+ isAnonymous: false,+ };+ state.json.mockReset().mockResolvedValue({+ editorsDeployed: 4,+ activeThisMonth: 2,+ pdfsProcessed: 12,+ });+});++describe("fleet statistics access", () => {+ it.each([+ { loading: true },+ { isAdmin: false },+ { isAdmin: undefined },+ { session: null },+ { user: null },+ { isAnonymous: true },+ { error: new Error("Session unavailable") },+ ])(+ "does not request statistics for an unconfirmed admin: %j",+ async (override) => {+ Object.assign(state.auth, override);+ const { result, client } = setup();+ await act(async () => {+ await client.invalidateQueries();+ });+ expect(state.json).not.toHaveBeenCalled();+ expect(result.current).toEqual({+ data: null,+ loading: false,+ error: null,+ });+ },+ );++ it("starts only after admin authentication resolves", async () => {+ state.auth.loading = true;+ const { result, rerender } = setup();+ expect(state.json).not.toHaveBeenCalled();+ state.auth.loading = false;+ rerender();+ await waitFor(() => expect(result.current.data?.editorsDeployed).toBe(4));+ expect(state.json).toHaveBeenCalledTimes(1);+ });++ it("hides cached statistics and stops refetching after access is revoked", async () => {+ const { result, rerender, client } = setup();+ await waitFor(() => expect(result.current.data?.editorsDeployed).toBe(4));+ state.auth.isAdmin = false;+ rerender();+ await act(async () => {+ await client.invalidateQueries();+ });+ expect(result.current.data).toBeNull();+ expect(state.json).toHaveBeenCalledTimes(1);+ });++ it("does not reuse another account's cached statistics", async () => {+ const { result, rerender } = setup();+ await waitFor(() => expect(result.current.data?.editorsDeployed).toBe(4));+ state.json.mockResolvedValue({+ editorsDeployed: 1,+ activeThisMonth: 0,+ pdfsProcessed: 0,+ });+ state.auth.user = { id: "another-admin" };+ rerender();+ expect(result.current.data).toBeNull();+ await waitFor(() => expect(result.current.data?.editorsDeployed).toBe(1));+ });++ it.each([401, 403, 404, 500])(+ "keeps optional statistics quiet on HTTP %i",+ async (status) => {+ state.json.mockRejectedValue(+ Object.assign(new Error("Unavailable"), { status }),+ );+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current).toEqual({+ data: null,+ loading: false,+ error: null,+ });+ expect(state.json).toHaveBeenCalledTimes(1);+ },+ );++ it("requires direct API callers to opt into the request", async () => {+ expect(await fetchFleetStats(false)).toBeNull();+ expect(state.json).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/portal/queries/infrastructure.ts b/frontend/editor/src/portal/queries/infrastructure.tsindex c70763598b..2f032001a1 100644--- a/frontend/editor/src/portal/queries/infrastructure.ts+++ b/frontend/editor/src/portal/queries/infrastructure.ts@@ -12,15 +12,23 @@ import {type EditorDeploymentResponse,} from "@portal/api/editorDeploy";import type { Tier } from "@portal/contexts/TierContext";+import { useFleetStatsAccess } from "@portal/hooks/useFleetStatsAccess";-/** Base query: fleet processing stats (GET /api/v1/usage/fleet-stats). */+/** Optional fleet metrics: unauthorized sessions never fetch, and failures leave figures unavailable. */export function useFleetStats(): AsyncState<FleetStats> {- return toAsyncState(- useQuery({- queryKey: qk.fleetStats(),- queryFn: ({ signal }) => fetchFleetStats(signal),- }),- );+ const scope = useFleetStatsAccess();+ const enabled = scope !== null;+ const query = useQuery({+ queryKey: [...qk.fleetStats(), scope],+ queryFn: ({ signal }) => fetchFleetStats(enabled, signal),+ enabled,+ retry: false,+ });+ return {+ data: enabled ? (query.data ?? null) : null,+ loading: enabled && query.isPending,+ error: null,+ };}/** Base query: recent audit-log activity (tier-scoped). */